diff --git a/.github/agents/专家.agent.md b/.github/agents/专家.agent.md index f45c97d..561bed9 100644 --- a/.github/agents/专家.agent.md +++ b/.github/agents/专家.agent.md @@ -3,7 +3,7 @@ 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: Claude Opus 4.6 +model: DeepSeek V4 Pro (deepseek) --- # WMS 专家兜底代理(`wms-expert-agent`) diff --git a/.github/agents/发布.agent.md b/.github/agents/发布.agent.md index 9baa21f..4a6b690 100644 --- a/.github/agents/发布.agent.md +++ b/.github/agents/发布.agent.md @@ -3,7 +3,7 @@ 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: GPT-5 mini (copilot) +model: DeepSeek V4 Pro (deepseek) --- diff --git a/.github/agents/开发.agent.md b/.github/agents/开发.agent.md index b88dd9d..37edf55 100644 --- a/.github/agents/开发.agent.md +++ b/.github/agents/开发.agent.md @@ -3,7 +3,7 @@ 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) +model: DeepSeek V4 Pro (deepseek) --- # WMS 开发代理(`wms-dev-agent`) diff --git a/.github/agents/数据库.agent.md b/.github/agents/数据库.agent.md index 03a045e..8b451ef 100644 --- a/.github/agents/数据库.agent.md +++ b/.github/agents/数据库.agent.md @@ -3,7 +3,7 @@ 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 : GPT-5 mini (copilot) +model : DeepSeek V4 Pro (deepseek) --- # WMS 数据库代理(`wms-db-agent`) diff --git a/.github/agents/文档.agent.md b/.github/agents/文档.agent.md index d8fdb78..cf6a18f 100644 --- a/.github/agents/文档.agent.md +++ b/.github/agents/文档.agent.md @@ -3,7 +3,7 @@ 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: GPT-5 mini (copilot) +model: DeepSeek V4 Pro (deepseek) --- # WMS 文档代理(`wms-doc-agent`) diff --git a/.github/agents/测试.agent.md b/.github/agents/测试.agent.md index c5f6b59..c238c3e 100644 --- a/.github/agents/测试.agent.md +++ b/.github/agents/测试.agent.md @@ -3,7 +3,7 @@ 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: Gemini 2.5 Pro (copilot) +model: DeepSeek V4 Pro (deepseek) --- # WMS 测试代理(`wms-test-agent`) diff --git a/.github/agents/缓存.agent.md b/.github/agents/缓存.agent.md index bae0b20..ec91c87 100644 --- a/.github/agents/缓存.agent.md +++ b/.github/agents/缓存.agent.md @@ -3,7 +3,7 @@ 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: GPT-5 mini (copilot) +model: DeepSeek V4 Pro (deepseek) --- # WMS Redis 代理(`wms-redis-agent`) diff --git a/.github/agents/评审.agent.md b/.github/agents/评审.agent.md index 2c5a91f..4c84cbf 100644 --- a/.github/agents/评审.agent.md +++ b/.github/agents/评审.agent.md @@ -3,7 +3,7 @@ name: wms-review-agent description: "Use when the user asks for 代码评审、审查、review、缺陷、风险、回归、兼容性、可维护性、代码质量检查、变更影响分析。专用于 WMS 只读代码评审与风险识别。" argument-hint: "描述要评审的代码、分支或变更范围,例如:评审某个 PR、审查某个接口改动、检查回归风险、分析兼容性问题。" tools: ['read', 'search'] -model: Claude Opus 4.6 +model: DeepSeek V4 Pro (deepseek) --- # WMS 评审代理(`wms-review-agent`) diff --git a/.github/agents/调度.agent.md b/.github/agents/调度.agent.md index 82a1f3c..71f750c 100644 --- a/.github/agents/调度.agent.md +++ b/.github/agents/调度.agent.md @@ -2,12 +2,22 @@ name: wms-dispatcher-agent description: "Use when the user asks about 任务委派、任务分派、调度、router、triage、多领域排障、不确定该找哪个 agent,或需要把问题分给 数据库/Redis/发布/开发/测试/文档 等模块。专用于 WMS 任务分诊与委派。" argument-hint: "描述你的目标或问题,例如:帮我判断这是数据库、测试还是缓存问题并分派、这个线上异常该交给谁处理。" -tools: ['read', 'search', 'agent', 'todo'] -model: Claude Opus 4.6 (copilot) +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 的内部技术细节**,只关注其输入、输出和完成状态 + ## 适用范围 以下场景优先使用本 Agent: @@ -23,39 +33,41 @@ model: Claude Opus 4.6 (copilot) 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` 必须告知测试目标和所有涉及的文件路径 +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. **跨域混合任务** → 先拆分,再按依赖顺序委派并汇总结果 +9. **跨域混合任务** → 先拆分,再按各子任务的依赖顺序依次委派。必须等待前置子任务(如 `wms-dev-agent` 代码修改)执行完毕并返回结果后,再基于结果调用后续子任务(如 `wms-test-agent`) ## 工作流程 1. 先读懂用户目标与限制条件 2. 判断问题归属:数据库 / Redis / 发布 / 开发 / 测试 / 文档 / 混合 -3. 如需求不清晰,只补问最少的关键问题 +3. 如需求不清晰,最多向用户提出 1 到 2 个关键澄清问题,且必须在一轮回复中问出 4. 把子任务委派给最合适的专属 agent 5. 若专属 agent 无法收敛或多轮仍未解,升级委派 `wms-expert-agent` 兜底 6. 汇总各子任务结果,给出最终结论与下一步建议 +7. 如果调用 `agent/runSubagent` 工具时发生系统错误、超时或无有效返回,请向用户说明情况,或直接委派给 `wms-expert-agent` 排查工具故障原因 ## 工作原则 - **只做分诊与委派,不绕过专属 agent 的安全约束** +- **如果用户要求你直接给出代码修改或数据库语句而不使用专属 agent,必须坚决拒绝,并强制委派给对应的专属 agent 执行** - **凡涉及非测试仓库数据写操作(数据库 / Redis),默认视为禁止项**;只能给只读排查建议,除非用户已明确说明是测试仓且允许操作 - **如无法确认是否测试仓,默认按非测试仓处理** -- 遇到数据库相关,必须遵守 `wms-db-agent` 的只读 / 风险确认流程 -- 遇到 Redis 相关,必须遵守 `wms-redis-agent` 的先读后改 / 回读确认流程 -- 遇到发布相关,必须遵守 `wms-deploy-agent` 的 `npm run` 固定入口与 SSH 安全红线 -- 遇到开发相关,必须遵守 `wms-dev-agent` 的“先定位、后修改、再验证”流程 -- 遇到测试相关,必须遵守 `wms-test-agent` 的“TDD 优先、测试真实行为、报告 passing 数量”流程 -- 遇到文档相关,必须遵守 `wms-doc-agent` 的“先核对代码与测试,再更新文档”流程 +- 数据库与写入相关风险:直接委派给 `wms-db-agent`,由其向用户发起风险确认,Dispatcher 不得代为确认 +- 各专属 agent 的安全约束(如 `wms-db-agent` 只读流程、`wms-deploy-agent` SSH 红线等)由专属 agent 自行保证,Dispatcher 不重复执行 ## 输出要求 -- 所有回复建议以 `[Dispatch]` 开头 +### 委派阶段(调用 `agent/runSubagent` 之前) +- 以 `[Dispatch]` 开头 - 先说明**将分派给谁**,再给简短原因 - 如果是多领域问题,给出**拆分后的执行顺序** -- 最后输出汇总结论和下一步建议 + +### 汇总阶段(所有子任务返回之后) +- 汇总各专属 agent 的返回结果 +- 输出最终结论与下一步建议 ## 建议提问方式 @@ -63,9 +75,4 @@ model: Claude Opus 4.6 (copilot) 请使用 wms-dispatcher-agent 帮我: 1) 判断这个问题属于数据库、Redis、发布、开发、测试还是文档问题 2) 分派给正确的 agent -3) 汇总处理结果与下一步建议 -``` - -## 结论 - -`wms-dispatcher-agent` 用于 WMS 场景下的任务分诊与委派;当用户不确定该找哪个 agent,或问题跨多个领域时,应优先交给本 Agent。 \ No newline at end of file +3) 汇总处理结果与下一步建议 \ No newline at end of file diff --git a/app/controller/docs.js b/app/controller/docs.js index aed64dd..9996374 100644 --- a/app/controller/docs.js +++ b/app/controller/docs.js @@ -434,7 +434,7 @@ function normalizeGroups(docData) { if (docData && Array.isArray(docData.endpoints)) { return [{ - groupName: 'Endpoints', + groupName: docData.groupName || 'Endpoints', module: docData.module || '', list: docData.endpoints, }]; @@ -645,12 +645,13 @@ function renderHtmlPage({ docs, entryPath, }) { + const isOpenapi = docData.module === 'openapi'; 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 = docs.map(name => { + const navHtml = isOpenapi ? '' : docs.filter(name => name !== 'openapi').map(name => { const activeClass = name === docName ? 'active' : ''; return `${escapeHtml(name)}`; }).join(''); @@ -1005,6 +1006,49 @@ function renderHtmlPage({ } th { background: #f6f9ff; } .muted { color: var(--muted); } + .openapi-guide { + margin-top: 14px; + border: 1px solid #d7e4f7; + background: #fcfdff; + border-radius: 10px; + padding: 16px; + } + .openapi-guide h3 { + margin: 12px 0 8px; + font-size: 15px; + color: #1a4c8f; + } + .openapi-guide h3:first-child { + margin-top: 0; + } + .guide-code { + background: #0d1d33; + color: #d8e7ff; + border-radius: 8px; + padding: 12px; + font-size: 13px; + font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace; + overflow-x: auto; + white-space: pre-wrap; + word-break: break-all; + line-height: 1.6; + margin: 4px 0 0; + } + .guide-notes { + list-style: disc; + padding-left: 20px; + margin: 4px 0 0; + color: var(--muted); + font-size: 13px; + line-height: 1.8; + } + .guide-notes code { + background: #e8f1fc; + padding: 1px 6px; + border-radius: 4px; + font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace; + font-size: 12px; + } @media (max-width: 768px) { .container { padding: 14px; } .method-card { padding: 12px; } @@ -1032,7 +1076,7 @@ function renderHtmlPage({ 查看变更记录 查看 JSON -
+ ${isOpenapi ? '' : `

全局 Authorization

@@ -1042,8 +1086,8 @@ function renderHtmlPage({

全局业务 Header

${globalHeadersControls}

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

-
-
+
`} + ${isOpenapi ? '' : `

文档资源

${renderWindowElement('打开变更记录', changesUrl, 'doc-resource-link')} @@ -1052,7 +1096,53 @@ function renderHtmlPage({
点击上方按钮后,可直接预览当前文档的变更记录或原文 JSON。
-
+
`} + ${isOpenapi ? `
+

请求方式

+
POST /openapi?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) = ...
+ +

注意事项

+ +

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

+
` : ''}
@@ -1234,6 +1324,7 @@ function renderHtmlPage({ function md51(str) { var state = [ 1732584193, -271733879, -1732584194, 271733878 ]; + var originalLength = str.length; var i; for (i = 64; i <= str.length; i += 64) { md5cycle(state, md5blk(str.substring(i - 64, i))); @@ -1248,7 +1339,7 @@ function renderHtmlPage({ md5cycle(state, tail); tail = new Array(16).fill(0); } - tail[14] = str.length * 8; + tail[14] = originalLength * 8; md5cycle(state, tail); return state; } @@ -1941,6 +2032,14 @@ class DocsController extends Controller { await this.list(); } + /** + * 渲染 OpenAPI 文档独立页面。 + * @return {Promise} 无返回值。 + */ + async openapi() { + await this.renderDoc('openapi'); + } + async detail() { const { ctx } = this; const docName = ctx.params.docName; diff --git a/app/controller/openapiCallback.js b/app/controller/openapiCallback.js new file mode 100644 index 0000000..e10ad8c --- /dev/null +++ b/app/controller/openapiCallback.js @@ -0,0 +1,277 @@ +'use strict'; +const { Controller } = require('egg'); +const { CALLBACK_EVENTS } = require('../service/openapi/callbackRegistry'); + +/** + * OpenAPI 回调测试控制器。 + * 提供独立的回调调试页面,用于模拟回调推送并查看响应结果。 + */ +class OpenapiCallbackController extends Controller { + /** + * 渲染回调测试页面。 + * 页面支持选择已注册的回调事件、填入测试 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 回调测试

+

选择已注册的回调事件,填入测试 URL,模拟真实回调推送。

+

+ ← 返回 API 文档 +

+
+ +
+ + +

+ +
+
+ + +
+
+ + +
+
+ + + + + + + + + +
点击发送后显示响应
+
+
+ + + +`; + } +} + +module.exports = OpenapiCallbackController; diff --git a/app/dict/businessDict.js b/app/dict/businessDict.js index 4fb637f..43fa09c 100644 --- a/app/dict/businessDict.js +++ b/app/dict/businessDict.js @@ -135,6 +135,7 @@ module.exports = { STORE_CREATE: '创建货主', STORE_CREATE_WAREHOUSE: '创建仓库', STORE_SIGN: '签约货主', + STORE_OPEN_ACCOUNT: '仓库代开户', STORE_RENAME: '修改签约备注', STORE_UNBIND: '解绑签约', STORE_SAVE_POLICY_CONFIG: '保存签约策略配置', diff --git a/app/lib/express_print_payload_builder.js b/app/lib/express_print_payload_builder.js index 9b12989..e630ac8 100644 --- a/app/lib/express_print_payload_builder.js +++ b/app/lib/express_print_payload_builder.js @@ -97,6 +97,7 @@ class ExpressPrintPayloadBuilder { buildPayload(options = {}) { const requestOptions = isPlainObject(options) ? options : {}; const platform = String(requestOptions.platform || '').trim(); + const normalizedPlatform = this.normalizePlatform(platform); if (!platform) { throw new Error('快递打印缺少平台标识'); } @@ -117,19 +118,58 @@ class ExpressPrintPayloadBuilder { } const payload = this.loadTemplate(platform); - if (!isPlainObject(payload.task)) { - payload.task = {}; - } const requestId = idGenerator.nextRequestId(); this.applyRequestId(payload, requestId); - payload.task.taskID = idGenerator.nextTaskId(); - payload.task.printer = printerName; - payload.task.documents = this.buildDocumentsFromOrders(orders, idGenerator); + payload.printer = printerName; + + if (Array.isArray(payload.taskList)) { + payload.taskList.forEach(item => { + if (isPlainObject(item)) { + item.printer = printerName; + } + }); + } + + if (normalizedPlatform === 'sph') { + this.applySphTaskDynamicFields(payload, orders); + } 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 映射为 documents。 * @param {Array} orders 订单数组。 @@ -148,6 +188,91 @@ class ExpressPrintPayloadBuilder { }); } + /** + * 将 SPH 订单中的动态业务字段回填到模板 taskList[0]。 + * + * 仅覆盖动态字段,避免改写模板固定结构。 + * + * @param {Object} payload 打印请求 payload。 + * @param {Array} orders 外部传入的订单打印数据数组。 + */ + applySphTaskDynamicFields(payload, orders) { + if (!Array.isArray(payload.taskList) || !isPlainObject(payload.taskList[0])) { + return; + } + + const sourceTask = this.resolveSphTaskFromOrders(orders); + if (!isPlainObject(sourceTask)) { + return; + } + + const targetTask = payload.taskList[0]; + const dynamicFields = [ + 'printInfo', + 'printNum', + 'splitControl', + 'showDeliveryLogo', + 'customInfo', + 'extendData', + 'taskID', + ]; + + dynamicFields.forEach(field => { + if (Object.prototype.hasOwnProperty.call(sourceTask, field)) { + targetTask[field] = deepClone(sourceTask[field]); + } + }); + } + + /** + * 从首个订单提取 SPH 动态任务数据。 + * + * 优先读取标准 taskList[0];若上游直接传 task 结构(printInfo/printNum 等)也兼容。 + * + * @param {Array} orders 外部传入的订单打印数据数组。 + * @return {Object|null} SPH 动态任务对象。 + */ + resolveSphTaskFromOrders(orders) { + if (!Array.isArray(orders) || orders.length === 0) { + return null; + } + + const firstOrder = isPlainObject(orders[0]) ? orders[0] : {}; + const candidates = []; + if (isPlainObject(firstOrder.print_data)) { + candidates.push(firstOrder.print_data); + } + if (isPlainObject(firstOrder)) { + candidates.push(firstOrder); + } + + const sphDynamicFields = [ + 'printInfo', + 'printNum', + 'splitControl', + 'showDeliveryLogo', + 'customInfo', + 'extendData', + 'taskID', + ]; + + for (const candidate of candidates) { + if (Array.isArray(candidate.taskList) && isPlainObject(candidate.taskList[0])) { + return candidate.taskList[0]; + } + + if (isPlainObject(candidate.taskList)) { + return candidate.taskList; + } + + if (sphDynamicFields.some(field => Object.prototype.hasOwnProperty.call(candidate, field))) { + return candidate; + } + } + + return null; + } + /** * 解析单个订单对应的 document。 * @param {Object} order 订单对象。 diff --git a/app/lib/printer_data_builder.js b/app/lib/printer_data_builder.js index c91c5ff..f6a373e 100644 --- a/app/lib/printer_data_builder.js +++ b/app/lib/printer_data_builder.js @@ -92,6 +92,11 @@ const LINE_BREAK_MAP = Object.freeze({ * @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', @@ -969,6 +974,30 @@ function resolveCainiaoMainTemplateURL(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。 * @@ -1348,6 +1377,7 @@ function applyPddExpressFieldMapping(platform, skeleton, orderExpress, orderDeli 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( @@ -1426,6 +1456,13 @@ function applyPddExpressFieldMapping(platform, skeleton, orderExpress, orderDeli 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; @@ -1465,6 +1502,152 @@ function applyPddExpressFieldMapping(platform, skeleton, orderExpress, orderDeli } } +/** + * 获取抖音 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 策略配置对象。 + */ +function applyDouyinExpressFieldMapping(platform, skeleton, orderExpress, orderDelivery, policyConfig) { + 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), + expressInterfaceName: toTrimmedString( + safeOrderExpress.logistics_interface_name + || safeOrderExpress.logistics_name + || safeOrderDelivery.logistics_interface_name + || safeOrderDelivery.logistics_name + ), + fallbackTotalQty: Number(safeOrderDelivery.items_count || safeOrderDelivery.items_total || 0), + } + ); + const customProductInfo = mergeWaybillCustomLines(customProductInfoLines, { lineBreak: '\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)) { + customContent.templateURL = 'http://www.ye4s.com/mb/douyin1.xml'; + } + customContent.data = isPlainObject(customContent.data) ? customContent.data : {}; + customContent.data.productInfo = customProductInfo || '无拣货信息'; + } +} + /** * 菜鸟平台主面单与自定义区字段回填。 * @@ -1612,6 +1795,403 @@ function applyCainiaoExpressFieldMapping( } } +/** + * 解析小红书主面单 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 风险提示列表。 + */ +function applyXhsExpressFieldMapping( + platform, + skeleton, + orderExpress, + orderDelivery, + policyConfig, + warnings +) { + 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), + expressInterfaceName: toTrimmedString( + safeOrderExpress.logistics_interface_name + || safeOrderExpress.logistics_name + || safeOrderDelivery.logistics_interface_name + || safeOrderDelivery.logistics_name + ), + fallbackTotalQty: Number(safeOrderDelivery.items_count || safeOrderDelivery.items_total || 0), + } + ); + const customProductInfo = mergeWaybillCustomLines(customProductInfoLines, { + lineBreak: 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].extendData.sender 使用 policy_config 发件人信息 + * - taskList[0].taskID 优先沿用 buildPlatformRequestSkeleton 现有 taskId + * + * @param {string} platform 归一化平台编码。 + * @param {Object} skeleton 打印请求骨架。 + * @param {Object} orderExpress 快递单对象。 + * @param {Object} orderDelivery 订单对象。 + * @param {Object} policyConfig 策略配置对象。 + */ +function applySphExpressFieldMapping( + platform, + skeleton, + orderExpress, + orderDelivery, + policyConfig +) { + 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 : {}; + const currentCurNum = toNumber(task.printNum.curNum, 0); + task.printNum.curNum = currentCurNum > 0 ? currentCurNum : 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), + expressInterfaceName: toTrimmedString( + safeOrderExpress.logistics_interface_name + || safeOrderExpress.logistics_name + || safeOrderDelivery.logistics_interface_name + || safeOrderDelivery.logistics_name + ), + fallbackTotalQty: Number(safeOrderDelivery.items_count || safeOrderDelivery.items_total || 0), + } + ); + const customProductInfo = mergeWaybillCustomLines(customProductInfoLines, { + lineBreak: LINE_BREAK_MAP.LF, + }).replace(/\n/g, '
'); + + 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 风险提示列表。 + */ +function applyJdExpressFieldMapping( + platform, + skeleton, + orderExpress, + orderDelivery, + policyConfig, + templateSample, + warnings +) { + 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), + expressInterfaceName: toTrimmedString( + safeOrderExpress.logistics_interface_name + || safeOrderExpress.logistics_name + || safeOrderDelivery.logistics_interface_name + || safeOrderDelivery.logistics_name + ), + fallbackTotalQty: Number(safeOrderDelivery.items_count || safeOrderDelivery.items_total || 0), + } + ); + const customProductInfo = mergeWaybillCustomLines(customProductInfoLines, { + lineBreak: LINE_BREAK_MAP.LF, + trailingLineBreak: true, + }); + + content.customData = isPlainObject(content.customData) ? content.customData : {}; + content.customData.GoodsInfo = customProductInfo; +} + /** * 构建平台请求骨架。 * @param {Object} input 输入对象。 @@ -1737,6 +2317,41 @@ function buildPlatformRequestSkeleton(input = {}) { policyConfig ); + applyDouyinExpressFieldMapping( + normalized.platform, + skeleton, + orderExpressForCompose, + orderDeliveryForCompose, + policyConfig + ); + + applyJdExpressFieldMapping( + normalized.platform, + skeleton, + orderExpressForCompose, + orderDeliveryForCompose, + policyConfig, + templateSample, + warnings + ); + + applyXhsExpressFieldMapping( + normalized.platform, + skeleton, + orderExpressForCompose, + orderDeliveryForCompose, + policyConfig, + warnings + ); + + applySphExpressFieldMapping( + normalized.platform, + skeleton, + orderExpressForCompose, + orderDeliveryForCompose, + policyConfig + ); + return { platform: normalized.platform, platform_meta: normalized.meta, diff --git a/app/model/express_interface.js b/app/model/express_interface.js index 85a4ed7..f9dd3fe 100644 --- a/app/model/express_interface.js +++ b/app/model/express_interface.js @@ -51,6 +51,31 @@ module.exports = app => { allowNull: true, comment: '平台店铺ID', }, + template_id: { + type: BIGINT(20).UNSIGNED, + 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, diff --git a/app/model/order_delivery.js b/app/model/order_delivery.js index 88ed64d..539d653 100644 --- a/app/model/order_delivery.js +++ b/app/model/order_delivery.js @@ -2,7 +2,7 @@ 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, JSON } = Sequelize; // 状态机枚举定义 const StatusEnum = { @@ -66,6 +66,11 @@ module.exports = app => { allowNull: true, comment: '订单标记', }, + extend_props: { + type: JSON, + allowNull: true, + comment: '订单扩展属性', + }, source_platform_code: { type: STRING(50), allowNull: true, diff --git a/app/model/order_items_factory.js b/app/model/order_items_factory.js index 372f340..a370b87 100644 --- a/app/model/order_items_factory.js +++ b/app/model/order_items_factory.js @@ -185,7 +185,7 @@ module.exports = app => { try { const DynamicModel = this.buildDynamicModel(warehouseId, type, tableName); - // await this.ensureManagedTableSchema(tableName, type, warehouseId, DynamicModel); + await this.ensureManagedTableSchema(tableName, type, warehouseId, DynamicModel); // 复制关联关系 this.copyAssociations(this.app.model.OrderItems, DynamicModel); @@ -267,9 +267,8 @@ module.exports = app => { const mainModel = this.app.model.OrderItems; const attributes = cloneAttributes(mainModel && mainModel.rawAttributes); - if (attributes.id) { - delete attributes.id.autoIncrement; - } + // 保留 id 字段的 autoIncrement,与 order_delivery_factory 行为一致, + // 确保分表 wms_order_items_{warehouseId} 的 bulkCreate 能正常自增生成 id if (type === 'history' && !attributes.archive_time) { attributes.archive_time = { diff --git a/app/router.js b/app/router.js index c4f6a81..a557b37 100644 --- a/app/router.js +++ b/app/router.js @@ -17,15 +17,29 @@ module.exports = app => { // 系统接口 PDA/WEB 统一入口 router.post('/system', controller.home.system); - // 独立 docs 目录挂载 - router.get('/docs', controller.docs.docsIndex); - router.get('/docs/:relPath(.*)', controller.docs.docsFile); - // api文档相关 - router.get('/api/docs', controller.docs.list); - router.get('/api/docs/:docName/raw', controller.docs.raw); - router.get('/api/docs/:docName/changes', controller.docs.changes); - router.get('/api/docs/:docName', controller.docs.detail); + // 仅开发环境可访问的内部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); + + // OpenAPI 回调测试 — 所有环境均可访问的独立调试页面 + router.get('/docs/api/openapi/callback-test', controller.openapiCallback.testPage); + + // 仅开发环境可访问的 docs 通配路由(静态文件),必须在 /docs/api/openapi 之后注册 + if (app.config.env === 'local') { + router.get('/docs/:relPath(.*)', controller.docs.docsFile); + } // OpenAPI 入口 router.post('/openapi', controller.openapi.index); diff --git a/app/service/openapi.js b/app/service/openapi.js index 74fe38e..09cbf7f 100644 --- a/app/service/openapi.js +++ b/app/service/openapi.js @@ -180,6 +180,19 @@ class OpenapiService extends Service { }; } + // 时间戳时效校验(±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; diff --git a/app/service/openapi/callback.js b/app/service/openapi/callback.js new file mode 100644 index 0000000..e9b2995 --- /dev/null +++ b/app/service/openapi/callback.js @@ -0,0 +1,225 @@ +'use strict'; + +const Service = require('egg').Service; +const { signRequest } = require('../../lib/api_sign'); + +/** @type {number} 最大重试次数 */ +const MAX_RETRY = 3; + +/** @type {number[]} 递增重试延迟(毫秒) */ +const RETRY_DELAY_MS = [2000, 5000, 15000]; + +/** + * OpenAPI 统一回调通知服务。 + * 将订单状态变更等事件通过签名鉴权回调到外部 callback_url, + * 支持自动重试与日志记录。 + */ +class OpenapiCallbackService extends Service { + + /** + * 计算回调签名(与 OpenAPI 入口签名算法完全一致)。 + * @param {Object} options 签名参数。 + * @param {string} options.event 事件名,如 order_completed。 + * @param {string} options.appKey 应用 app_key。 + * @param {string} options.selfAppSecret 应用密钥。 + * @param {Object} options.body 回调请求体数据。 + * @param {string} options.timestamp 毫秒时间戳。 + * @return {{ canonicalQuery: string, bodySign: string, sign: string }} 签名计算结果。 + */ + signCallback({ event, appKey, selfAppSecret, body, timestamp }) { + const query = { + method: event, + v: '1.0', + timestamp, + app_key: appKey, + }; + + return signRequest({ query, body, selfAppSecret }); + } + + /** + * 发送回调请求(带自动重试)。 + * 非 2xx 响应或网络错误触发重试,最多重试 MAX_RETRY 次, + * 每次重试间隔递增(2s → 5s → 15s)。 + * @param {Object} options 回调选项。 + * @param {string} options.callbackUrl 回调目标 URL。 + * @param {string} options.appKey 应用 app_key。 + * @param {string} options.selfAppSecret 应用密钥。 + * @param {string} options.event 事件名,如 order_completed。 + * @param {Object} options.data 回调数据。 + * @param {Object} [options.metadata] 额外元数据。 + * @return {Promise} 回调结果 { success, retryCount, response, error }。 + */ + async sendWithRetry({ callbackUrl, appKey, selfAppSecret, event, data, metadata }) { + const { ctx } = this; + const timestamp = String(Date.now()); + const body = { event, data, metadata: metadata || {} }; + const { sign } = this.signCallback({ event, appKey, selfAppSecret, body, timestamp }); + + 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) { + 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}`); + + await this.logCallback({ + appKey, + event, + callbackUrl, + success: false, + retryCount: attempt, + response: result.data, + error: lastError.message, + }); + } catch (error) { + lastError = error; + + await this.logCallback({ + appKey, + event, + callbackUrl, + success: false, + retryCount: attempt, + response: null, + 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 与密钥,发送回调通知。 + * @param {Object} options 回调选项。 + * @param {string} options.appKey 应用 app_key。 + * @param {string} options.event 事件名,如 order_completed。 + * @param {Object} options.data 回调数据。 + * @param {Object} [options.metadata] 额外元数据。 + * @return {Promise} 回调结果 { success, retryCount, response, error }。 + */ + async sendByAppKey({ appKey, event, data, metadata }) { + 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, + data, + metadata, + }); + } + + /** + * 记录回调日志。 + * 格式:[OpenapiCallback] event=xxx appKey=xxx url=xxx retry=N success=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 logMessage = `[OpenapiCallback] event=${event} appKey=${appKey} url=${callbackUrl} retry=${retryCount} success=${success}`; + + 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..35a95e8 --- /dev/null +++ b/app/service/openapi/callbackRegistry.js @@ -0,0 +1,31 @@ +'use strict'; + +/** + * OpenAPI 回调事件注册表。 + * 每个事件包含 name(事件名)、label(展示名)、description(说明)、 + * sampleData(示例数据,与真实回调数据格式一致)。 + */ +const CALLBACK_EVENTS = [ + { + name: 'order_completed', + label: '订单发货完成', + description: '订单同步(出库)完成后触发', + sampleData: { + orderIds: [ 1001, 1002 ], + status: 'completed', + successCount: 2, + failedCount: 0, + }, + }, + { + name: 'order_cancelled', + label: '订单已取消', + description: '订单取消成功后触发', + sampleData: { + orderCode: 'TEST-ORDER-001', + status: 'cancelled', + }, + }, +]; + +module.exports = { CALLBACK_EVENTS }; diff --git a/app/service/openapiMethods/callback.js b/app/service/openapiMethods/callback.js new file mode 100644 index 0000000..1daa9a7 --- /dev/null +++ b/app/service/openapiMethods/callback.js @@ -0,0 +1,78 @@ +'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 与 data。 + * @param {Object} [payload.query={}] 请求 query 数据,需包含 app_key。 + * @return {Promise} 回调测试结果。 + */ + async test(payload = {}) { + const { body = {}, query = {} } = payload; + const { event = 'order_completed', data = {} } = body; + + try { + const info = await this.resolveAppInfo(query.app_key); + const result = await this.ctx.service.openapi.callback.sendByAppKey({ + appKey: info.appKey, + event, + data, + metadata: { test: true }, + }); + + 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..6d47240 --- /dev/null +++ b/app/service/openapiMethods/deliveryorder.js @@ -0,0 +1,159 @@ +'use strict'; + +const MainService = require('../main'); + +class OpenapiDeliveryorderService extends MainService { + /** + * 通过 app_key 解析仓库与货主信息。 + * 查询 ApiApp 并关联 StoreWarehouse 以获取 storeId、warehouseId。 + * @param {string} appKey 开放接口 app_key。 + * @return {Promise} 包含 storeId、warehouseId、appKey、customerId、warehouseCode 的信息对象。 + */ + async resolveAppInfo(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', + [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: false, + }, + ], + raw: true, + }); + + if (!appConfig || !appConfig.warehouse_id) { + throw new Error(`无法解析仓库信息,请检查 app_key: ${normalizedAppKey}`); + } + + return { + storeId: appConfig.store_id || null, + warehouseId: appConfig.warehouse_id, + appKey: normalizedAppKey, + customerId: null, + warehouseCode: '', + }; + } + + /** + * 查询发货单。 + * @param {Object} payload 调用参数。 + * @param {Object} payload.body 请求体数据,需包含 deliveryOrderCode。 + * @param {Object} payload.query 请求 query 数据,需包含 app_key。 + * @return {Promise} 查询结果,成功时返回订单详情,失败时返回错误信息。 + */ + async query(payload = {}) { + const { body = {}, query = {} } = payload; + const { deliveryOrderCode } = body; + + if (!deliveryOrderCode) { + return this.fail('deliveryOrderCode 参数缺失'); + } + + try { + const info = await this.resolveAppInfo(query.app_key); + const DeliveryModel = await this.ctx.model.OrderDeliveryFactory.getCurrentModel(info.warehouseId); + const order = await DeliveryModel.findOne({ + where: { delivery_order_code: deliveryOrderCode }, + }); + + 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}`); + } + } + + /** + * 创建发货单。 + * @param {Object} payload 调用参数。 + * @param {Object} payload.body 请求体数据,需包含 deliveryOrder 与 orderLines。 + * @param {Object} payload.query 请求 query 数据,需包含 app_key。 + * @return {Promise} 创建结果,成功时返回订单ID等,失败时返回错误信息。 + */ + async create(payload = {}) { + const { body = {}, query = {} } = payload; + const { deliveryOrder, orderLines } = body; + + if (!deliveryOrder || !deliveryOrder.deliveryOrderCode) { + return this.fail('deliveryOrder 参数缺失或不完整'); + } + if (!orderLines) { + return this.fail('orderLines 参数缺失'); + } + + try { + const info = await this.resolveAppInfo(query.app_key); + this.setInfo( + info.storeId, + info.warehouseId, + info.appKey, + info.customerId, + info.warehouseCode + ); + + const data = { + request: { + deliveryOrder, + orderLines, + }, + }; + + 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: info.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/inventory.js b/app/service/openapiMethods/inventory.js new file mode 100644 index 0000000..6b9a65b --- /dev/null +++ b/app/service/openapiMethods/inventory.js @@ -0,0 +1,106 @@ +'use strict'; + +const MainService = require('../main'); + +/** + * OpenAPI 库存服务。 + * 提供库存查询能力,映射到 StockStore 底层模型。 + */ +class OpenapiInventoryService extends MainService { + + /** + * 通过 app_key 解析仓库与货主信息。 + * 查询 ApiApp 并关联 StoreWarehouse 以获取 storeId、warehouseId。 + * warehouseCode 优先使用 qimen_warehouse_code,为空时回退使用 warehouseId; + * ownerCode 优先使用 store_id,为空时回退使用空字符串。 + * @param {string} appKey 开放接口 app_key。 + * @return {Promise} 包含 storeId、warehouseId、appKey、customerId、warehouseCode、ownerCode 的信息对象。 + */ + async resolveAppInfo(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: false, + }, + ], + raw: true, + }); + + if (!appConfig || !appConfig.warehouse_id) { + throw new Error(`无法解析仓库信息,请检查 app_key: ${normalizedAppKey}`); + } + + const warehouseId = appConfig.warehouse_id; + const storeId = appConfig.store_id || null; + + return { + storeId, + warehouseId, + appKey: normalizedAppKey, + customerId: null, + warehouseCode: appConfig.qimen_warehouse_code || String(warehouseId), + ownerCode: storeId ? String(storeId) : '', + }; + } + + /** + * 库存查询。 + * 根据商品 ID 列表查询对应的库存信息,包括总库存、锁定量和可用量。 + * @param {Object} payload 调用参数。 + * @param {Object} payload.body 请求体数据,需包含 itemIds(商品 ID 数组)。 + * @param {Object} payload.query 请求 query 数据,需包含 app_key。 + * @return {Promise} 查询结果,成功时返回 items 数组。 + */ + async query(payload = {}) { + const { body = {}, query = {} } = payload; + const { itemIds } = body; + + if (!Array.isArray(itemIds) || itemIds.length === 0) { + return this.fail('itemIds 参数缺失或为空'); + } + + await this.resolveAppInfo(query.app_key); + const items = []; + + for (const itemId of itemIds) { + const result = await this.ctx.service.systems.stockStore.getItemStorages(itemId); + if (result.success && result.data) { + 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..514d71d --- /dev/null +++ b/app/service/openapiMethods/order.js @@ -0,0 +1,163 @@ +'use strict'; + +const MainService = require('../main'); + +class OpenapiOrderService extends MainService { + /** + * 通过 app_key 解析仓库与货主信息。 + * 查询 ApiApp 并关联 StoreWarehouse 以获取 storeId、warehouseId。 + * @param {string} appKey 开放接口 app_key。 + * @return {Promise} 包含 storeId、warehouseId、appKey、customerId、warehouseCode 的信息对象。 + */ + async resolveAppInfo(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', + [ 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: false, + }, + ], + raw: true, + }); + + if (!appConfig || !appConfig.warehouse_id) { + throw new Error(`无法解析仓库信息,请检查 app_key: ${normalizedAppKey}`); + } + + return { + storeId: appConfig.store_id || null, + warehouseId: appConfig.warehouse_id, + appKey: normalizedAppKey, + customerId: null, + warehouseCode: '', + }; + } + + /** + * 取消发货单。 + * 当前仅支持出库单类型(JYCK/HHCK/BFCK → ORDER),非出库单类型返回不支持。 + * @param {Object} payload 调用参数。 + * @param {Object} payload.body 请求体数据,包含 orderCode、orderType。 + * @param {Object} payload.query 请求 query 数据,包含 app_key。 + * @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 + const ORDER_TYPES = [ 'JYCK', 'HHCK', 'BFCK' ]; + if (!ORDER_TYPES.includes(orderType)) { + return this.fail('暂不支持该订单类型的取消操作'); + } + + const normalizedOrderCode = String(orderCode || '').trim(); + if (!normalizedOrderCode) { + return this.fail('orderCode 参数缺失'); + } + + try { + const info = await this.resolveAppInfo(query.app_key); + + const DeliveryModel = await ctx.model.OrderDeliveryFactory.getCurrentModel(info.warehouseId); + const transaction = await ctx.model.transaction(); + try { + const existingOrder = await DeliveryModel.findOne({ + where: { + delivery_order_code: normalizedOrderCode, + warehouse_id: info.warehouseId, + store_id: info.storeId, + }, + transaction, + lock: transaction.LOCK.UPDATE, + }); + + if (!existingOrder) { + await transaction.rollback(); + return this.fail('未找到对应的订单'); + } + + const pickStatus = String(existingOrder.pick_status || 'none').trim(); + const printStatus = String(existingOrder.print_status || 'none').trim(); + + if (pickStatus !== 'none' || printStatus !== 'none') { + await existingOrder.update({ + intercept_status: 'intercepting', + updated_at: new Date(), + }, { + transaction, + }); + + await transaction.commit(); + return this.fail('取消失败,已通知拦截执行'); + } + + await existingOrder.update({ + status: 'cancel', + outbound_status: 'fin', + step: 4, + updated_at: new Date(), + }, { + transaction, + }); + + await transaction.commit(); + + // 取消成功后触发 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 || '').trim(); + if (appKey) { + callbackService.sendByAppKey({ + appKey, + event: 'order_cancelled', + data: { + orderCode, + status: 'cancelled', + }, + }).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}`); + } + } +} + +module.exports = OpenapiOrderService; diff --git a/app/service/openapiMethods/singleitem.js b/app/service/openapiMethods/singleitem.js new file mode 100644 index 0000000..5aad33b --- /dev/null +++ b/app/service/openapiMethods/singleitem.js @@ -0,0 +1,137 @@ +'use strict'; + +const MainService = require('../main'); + +/** + * OpenAPI 单品服务。 + * 提供商品(单品)的同步与查询能力,映射到 StockStore 底层模型。 + */ +class OpenapiSingleitemService extends MainService { + + /** + * 通过 app_key 解析仓库与货主信息。 + * 查询 ApiApp 并关联 StoreWarehouse 以获取 storeId、warehouseId。 + * warehouseCode 优先使用 qimen_warehouse_code,为空时回退使用 warehouseId; + * ownerCode 优先使用 store_id,为空时回退使用空字符串。 + * @param {string} appKey 开放接口 app_key。 + * @return {Promise} 包含 storeId、warehouseId、appKey、customerId、warehouseCode、ownerCode 的信息对象。 + */ + async resolveAppInfo(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: false, + }, + ], + raw: true, + }); + + if (!appConfig || !appConfig.warehouse_id) { + throw new Error(`无法解析仓库信息,请检查 app_key: ${normalizedAppKey}`); + } + + const warehouseId = appConfig.warehouse_id; + const storeId = appConfig.store_id || null; + + return { + storeId, + warehouseId, + appKey: normalizedAppKey, + customerId: null, + warehouseCode: appConfig.qimen_warehouse_code || String(warehouseId), + ownerCode: storeId ? String(storeId) : '', + }; + } + + /** + * 同步(新增或更新)单品信息。 + * 将外部系统的商品数据写入 StockStore,并自动同步到库存表。 + * @param {Object} payload 调用参数。 + * @param {Object} payload.body 请求体数据,仅需包含 item;warehouseCode 和 ownerCode 由 app_key 自动解析,调用方不得传入。 + * @param {Object} payload.query 请求 query 数据,需包含 app_key。 + * @return {Promise} 同步结果,成功时返回 itemId。 + */ + async synchronize(payload = {}) { + const { body = {}, query = {} } = payload; + const { item } = body; + + if (!item || !item.itemCode) { + return this.fail('item 参数缺失或不完整(缺少 itemCode)'); + } + + try { + const { storeId, warehouseId, appKey, warehouseCode, ownerCode } = await this.resolveAppInfo(query.app_key); + + 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}`); + } + } + + /** + * 查询单品详情。 + * 根据 itemId 查询 StockStore 记录并转换为 OpenAPI 统一格式。 + * @param {Object} payload 调用参数。 + * @param {Object} payload.body 请求体数据,需包含 itemId。 + * @param {Object} payload.query 请求 query 数据,需包含 app_key。 + * @return {Promise} 查询结果,成功时返回商品详情。 + */ + async query(payload = {}) { + const { body = {}, query = {} } = payload; + const { itemId } = body; + + if (!itemId) { + return this.fail('itemId 参数缺失'); + } + + try { + // 验证 app_key 有效性 + await this.resolveAppInfo(query.app_key); + + const row = await this.ctx.model.StockStore.findByPk(itemId); + 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/systemMethods/index.js b/app/service/systemMethods/index.js index ec720d6..92e46bc 100644 --- a/app/service/systemMethods/index.js +++ b/app/service/systemMethods/index.js @@ -173,6 +173,113 @@ function normalizeFirstWrappedArray(values, nestedKeys = []) { 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), + }; +} + /** * 规范化菜鸟标准模板子项列表。 * @@ -270,9 +377,10 @@ function appendExpressMappingKey(targetMap, rawKey, mappingItem) { * 构建抖音电子面单快递映射表。 * * @param {Array} expressList 系统快递列表 + * @param platformCode * @return {Object} 支持 DY 平台编码与系统快递编码双键的映射表 */ -function buildExpressNameMap(expressList,platformCode = 'DY') { +function buildExpressNameMap(expressList, platformCode = 'DY') { return normalizeArray(expressList).reduce((result, expressItem) => { const currentExpressItem = expressItem && typeof expressItem === 'object' ? expressItem : {}; const mappingItem = { @@ -332,46 +440,107 @@ function formatPddWaybillSearchResponse(responseData, expressNameMap = {}) { const list = subscriptions.map(subscription => { const subscriptionItem = subscription && typeof subscription === 'object' ? subscription : {}; - const accounts = normalizeArray(subscriptionItem.branch_account_cols).map(account => { + 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 customerCodes = normalizeWrappedArray(accountItem.customer_code_list, [ 'string' ]) + 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); - const shipAddresses = normalizeArray(accountItem.shipp_address_cols).map(address => { - const addressItem = address && typeof address === 'object' ? address : {}; + 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: normalizeText(addressItem.province), - city: normalizeText(addressItem.city), - district: normalizeText(addressItem.district), - detail: normalizeText(addressItem.detail), - full_address: normalizeText(addressItem.full_address), + province, + city, + district, + town, + detail, + full_address: fullAddress || `${province}${city}${district}${town}${detail}`, }; }); - const services = normalizeArray(accountItem.service_info_cols).map(service => { + 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 = normalizeArray(serviceItem.service_attributes).map(attribute => { + 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), - attribute_name: normalizeText(attributeItem.attribute_name), - attribute_type: normalizeText(attributeItem.attribute_type), - type_desc: normalizeText(attributeItem.type_desc), + 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), - service_name: normalizeText(serviceItem.service_name), - service_desc: normalizeText(serviceItem.service_desc), + 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, }; }); - return { + const result = { branch_code: normalizeText(accountItem.branch_code), branch_name: normalizeText(accountItem.branch_name), quantity: accountItem.quantity === null || accountItem.quantity === undefined ? 0 : accountItem.quantity, @@ -382,6 +551,20 @@ function formatPddWaybillSearchResponse(responseData, expressNameMap = {}) { 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); @@ -394,6 +577,7 @@ function formatPddWaybillSearchResponse(responseData, expressNameMap = {}) { wp_name: normalizeText(expressMapping.name) || '', sys_express_code: normalizeText(expressMapping.sys_express_code) || '', wp_type: normalizeText(subscriptionItem.wp_type), + providerid, accounts, }; }); @@ -449,12 +633,14 @@ function formatDyWaybillSearchResponse(responseData, expressNameMap = {}) { ); 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, @@ -464,7 +650,7 @@ function formatDyWaybillSearchResponse(responseData, expressNameMap = {}) { wpCode, ]); - const accounts = normalizeFirstWrappedArray([ + const accountSources = normalizeFirstWrappedArray([ subscriptionItem.branch_account_cols, subscriptionItem.branchAccounts, subscriptionItem.branch_accounts, @@ -473,8 +659,27 @@ function formatDyWaybillSearchResponse(responseData, expressNameMap = {}) { subscriptionItem.results, subscriptionItem.result, subscriptionItem.list, - ], [ 'waybill_branch_account', 'branch_account', 'account', 'results', 'result', 'list' ]).map(account => { + ], [ '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 @@ -482,23 +687,38 @@ function formatDyWaybillSearchResponse(responseData, expressNameMap = {}) { || 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', 'address' ]).map(address => { - const addressItem = address && typeof address === 'object' ? address : {}; + ], [ '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: normalizeText(addressItem.province), - city: normalizeText(addressItem.city || addressItem.town), - district: normalizeText(addressItem.district || addressItem.area), - detail: normalizeText(addressItem.detail || addressItem.address_detail || addressItem.address), - full_address: normalizeText(addressItem.full_address || addressItem.fullAddress || ''), + province, + city, + district, + town, + detail, + full_address: fullAddress || `${province}${city}${district}${town}${detail}`, }; }); const services = normalizeFirstWrappedArray([ @@ -531,22 +751,25 @@ function formatDyWaybillSearchResponse(responseData, expressNameMap = {}) { attributes, }; }); - console.log("accountItem",subscriptionItem.logisticsaccount,"\n\n") const result = { - branch_code: accountItem.sitecode, - branch_name: accountItem.sitename, + 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, }; - if(subscriptionItem.logisticsaccount){ - result.customer_code_list = [subscriptionItem.logisticsaccount]; - } - if(subscriptionItem.shopid){ - result.platform_shop_id = subscriptionItem.shopid; + const platformShopId = normalizeText( + accountItem.shopid + || subscriptionItem.shopid + || accountItem.providerid + || subscriptionItem.providerid + ); + if (platformShopId) { + result.platform_shop_id = platformShopId; } return result; }); @@ -555,9 +778,20 @@ function formatDyWaybillSearchResponse(responseData, expressNameMap = {}) { groupedByWpCode.set(wpCode, { wp_code: wpCode, wp_name: normalizeText(expressMapping.name) - || normalizeText(subscriptionItem.wp_name || subscriptionItem.cp_name || subscriptionItem.cpname), + || 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.waybill_type || subscriptionItem.type), + wp_type: normalizeText( + subscriptionItem.wp_type + || subscriptionItem.providertype + || subscriptionItem.waybill_type + || subscriptionItem.type + ), + providerid, accounts: [], shipAddressKeys: new Set(), }); @@ -567,13 +801,26 @@ function formatDyWaybillSearchResponse(responseData, expressNameMap = {}) { if (!groupedItem.wp_name) { groupedItem.wp_name = normalizeText(expressMapping.name) - || normalizeText(subscriptionItem.wp_name || subscriptionItem.cp_name || subscriptionItem.cpname); + || 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.waybill_type || subscriptionItem.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 => { @@ -611,6 +858,7 @@ function formatDyWaybillSearchResponse(responseData, expressNameMap = {}) { wp_name: item.wp_name, sys_express_code: item.sys_express_code, wp_type: item.wp_type, + providerid: item.providerid, accounts: item.accounts, })); @@ -1626,6 +1874,61 @@ class indexService extends MainService { 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; + } + /** * 实时请求淘宝菜鸟电子面单网点列表。 * @@ -1747,22 +2050,33 @@ class indexService extends MainService { * * @param {string} appSecret 菠萝派访问令牌 * @param {string|number} platid 菠萝派平台标识 + * @param isJD * @return {Promise>} 归一化后的模板数组 * @throws {Error} 当配置缺失或接口返回失败时抛出异常 */ - async requestPolyStdTemplates(appSecret,platid) { + async requestPolyStdTemplates(appSecret, platid, isJD = false) { + console.log('请求菠萝派标准模板接口入参', { appSecret: String(appSecret || '').trim() ? '***' : '', platid }); const { service } = this; - if(!appSecret || !platid){ + if (!appSecret || !platid) { throw new Error('菠萝派接口配置缺失'); } - const responseData = await service.systems.poloApi.request('Differ.JH.Logistics.GetTemplates', { - templatestype:"ALL" - }, { - interface_url: 'https://api.polyapi.com/OpenAPI/do', + 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: platid, + token: appSecret, + platid, version: '1.0', }); console.log('请求菠萝派标准模板接口响应', JSON.stringify(responseData)); @@ -1800,7 +2114,7 @@ class indexService extends MainService { : Array.isArray(nestedData) ? nestedData : []; - const cpCode = itemCpCode ?? itemCpcode ?? itemCpCodeCamel; + const cpCode = itemCpCode ?? itemCpcode ?? itemCpCodeCamel; return { ...restItem, @@ -1932,7 +2246,7 @@ class indexService extends MainService { case 'DY': { const accessToken = String(shopPlain.access_token || '').trim(); const expressList = await this.service.systems.express.getExpressList(true); - const expressNameMap = buildExpressNameMap(expressList,"DY"); + const expressNameMap = buildExpressNameMap(expressList, 'DY'); const responseData = await service.systems.poloApi.request('Differ.JH.Logistics.GetWayBillCondition', { }, { interface_url: 'https://api.polyapi.com/OpenAPI/do', @@ -1950,7 +2264,7 @@ class indexService extends MainService { case 'KS':{ const accessToken = String(shopPlain.access_token || '').trim(); const expressList = await this.service.systems.express.getExpressList(true); - const expressNameMap = buildExpressNameMap(expressList, "KS"); + const expressNameMap = buildExpressNameMap(expressList, 'KS'); const responseData = await service.systems.poloApi.request('Differ.JH.Logistics.GetWayBillCondition', { }, { interface_url: 'https://api.polyapi.com/OpenAPI/do', @@ -1968,7 +2282,7 @@ class indexService extends MainService { case 'SPH':{ const accessToken = String(shopPlain.access_token || '').trim(); const expressList = await this.service.systems.express.getExpressList(true); - const expressNameMap = buildExpressNameMap(expressList, "SPH"); + const expressNameMap = buildExpressNameMap(expressList, 'SPH'); const responseData = await service.systems.poloApi.request('Differ.JH.Logistics.GetWayBillCondition', { }, { interface_url: 'https://api.polyapi.com/OpenAPI/do', @@ -1986,8 +2300,9 @@ class indexService extends MainService { case 'XHS':{ const accessToken = String(shopPlain.access_token || '').trim(); const expressList = await this.service.systems.express.getExpressList(true); - const expressNameMap = buildExpressNameMap(expressList, "XHS"); + 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, @@ -2001,7 +2316,150 @@ class indexService extends MainService { 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; @@ -2105,22 +2563,36 @@ class indexService extends MainService { */ 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: { - [fieldName]: expressCode, + [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 code = String(plainRow[fieldName] || '').trim().toUpperCase(); + const candidateCodes = [ + plainRow.code, + plainRow[fieldName], + ].map(item => String(item || '').trim().toUpperCase()).filter(Boolean); - if (code) { + for (const code of candidateCodes) { allowedCodeSet.add(code); } } @@ -2138,18 +2610,40 @@ class indexService extends MainService { */ async filterPrintPlatformTemplateResponseData(responseData, platformCode, expressCode) { console.log('入参', platformCode, expressCode); - // 获取对应的wp_code - const allowedCodeSet = await this.getTemplateAllowedExpressCodeSet(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', normalizedResponseData); + // console.log('normalizedResponseData', JSON.stringify(normalizedResponseData)); // normalizedResponseData数组中的cp_code字段与allowedCodeSet匹配的第一个对象 - return normalizedResponseData.find(item => { - const itemCpCode = String(item.cp_code || '').trim().toUpperCase(); + 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; } /** @@ -2163,6 +2657,10 @@ class indexService extends MainService { return 'index:cainiao:stfTemplates:responseData'; } + if (platformCode === 'PDD') { + return 'index:printPlatform:PDD:templates:v2:responseData'; + } + return `index:printPlatform:${platformCode}:templates:responseData`; } @@ -2172,12 +2670,21 @@ class indexService extends MainService { * 当前已实现 CAINIAO 平台,其它平台返回空对象,便于后续扩展。 * * @param {string} platformCode 平台编码 + * @param s + * @param platid + * @param expressCode * @return {Promise} 平台模板响应 */ - async requestPrintPlatformTemplateList(platformCode,s = null,platid = null) { + 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]; @@ -2188,6 +2695,197 @@ class indexService extends MainService { 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; + } + /** * 获取打印平台模板列表。 * @@ -2199,7 +2897,7 @@ class indexService extends MainService { * @param {string} data.express_code 快递编码(下划线) * @param {string} [data.expressCode] 快递编码(驼峰) * @param {string} [data.shopId] 店铺ID(驼峰) - * + * * @return {Promise} 返回模板列表结果 */ async getPrintPlatformTemplateList(data = {}) { @@ -2229,14 +2927,10 @@ class indexService extends MainService { include: this.buildShopPrintPlatformInclude(true), }); } - if (!expressCode) { + if (platformCode === 'PDD' && !expressCode) { return this.fail('express_code 不能为空', { code: 400 }); } - const shouldBypassCache = Number.isFinite(shopId) && shopId > 0; - const cacheKey = this.getPrintPlatformTemplateCacheKey(platformCode); - const cached = shouldBypassCache ? null : await this.app.getCacheAsync(cacheKey); - let accessToken = ''; let platid = null; if (shop) { @@ -2249,19 +2943,26 @@ class indexService extends MainService { 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) - : await this.requestPrintPlatformTemplateList(platformCode); - // console.log('打印平台模板查询原始响应:', JSON.stringify(responseDataFromSource)); + ? await this.requestPrintPlatformTemplateList(platformCode, accessToken, platid, expressCode) + : await this.requestPrintPlatformTemplateList(platformCode, null, null, expressCode); + console.log('打印平台模板查询原始响应:', JSON.stringify(responseDataFromSource)); - if (cached === null || cached === undefined) { - // await this.app.setCacheAsync(cacheKey, responseDataFromSource, 3600); + 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, diff --git a/app/service/systemMethods/order/base.js b/app/service/systemMethods/order/base.js index d4e60b7..7f3c7f5 100644 --- a/app/service/systemMethods/order/base.js +++ b/app/service/systemMethods/order/base.js @@ -43,7 +43,7 @@ const ORDER_LIST_BASE_ATTRIBUTES = Object.freeze([ 'wave_scan_result', 'post_status', 'storage_status', 'pick_status', 'pack_status', 'inspection_status', 'print_status', 'claim_status', - 'outbound_status', 'lock_status', 'intercept_status', 'basket_number', + 'outbound_status', 'lock_status', 'intercept_status', 'basket_number', 'recheck_status', ]); const ORDER_WEIGHT_TYPE_LABELS = Object.freeze({ diff --git a/app/service/systemMethods/order/pendingOrder.js b/app/service/systemMethods/order/pendingOrder.js index 779c59b..8073a08 100644 --- a/app/service/systemMethods/order/pendingOrder.js +++ b/app/service/systemMethods/order/pendingOrder.js @@ -28,9 +28,9 @@ class PendingOrderService extends OrderBaseService { constructor(ctx) { super(ctx); const _noNeedLogin = ''; - const _noNeedRight = 'list,pendingOrder,reverseReviewOrder,markPendingOutboundOrder,cancelOrder,allocateExpressCode,allocateStorage,allocateStorageProgress,cancelAllocateStorage,syncOrderIds,updateOrderPlatform,updateOrderExpress,cloneOrder,createOrder,downloadCreateTemplate,importOrdersFromExcel'; - const _noNeedLog = 'list,markPendingOutboundOrder,cancelOrder,allocateExpressCode,allocateStorage,allocateStorageProgress,cancelAllocateStorage,syncOrderIds'; - const _noNeedAuth = 'list,pendingOrder,reverseReviewOrder,markPendingOutboundOrder,cancelOrder,allocateExpressCode,allocateStorage,allocateStorageProgress,cancelAllocateStorage,syncOrderIds,updateOrderPlatform,updateOrderExpress,cloneOrder,createOrder,downloadCreateTemplate,importOrdersFromExcel'; + const _noNeedRight = 'list,pendingOrder,reverseReviewOrder,markPendingOutboundOrder,cancelOrder,allocateExpressCode,allocateStorage,allocateStorageProgress,cancelAllocateStorage,syncOrderIds,updateOrderPlatform,updateOrderExpress,cloneOrder,createOrder,parseAddress'; + const _noNeedLog = 'list,markPendingOutboundOrder,cancelOrder,allocateExpressCode,allocateStorage,allocateStorageProgress,cancelAllocateStorage,syncOrderIds,parseAddress'; + const _noNeedAuth = 'list,pendingOrder,reverseReviewOrder,markPendingOutboundOrder,cancelOrder,allocateExpressCode,allocateStorage,allocateStorageProgress,cancelAllocateStorage,syncOrderIds,updateOrderPlatform,updateOrderExpress,cloneOrder,createOrder,parseAddress'; this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); } @@ -103,7 +103,248 @@ class PendingOrderService extends OrderBaseService { * @return {Promise} 更新后的订单信息。 */ async reverseReviewOrder(data = {}) { - return await this.updateOrderInspectionState(data, 'none'); + 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, 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; + } + } + + /** + * 校验订单是否已分配运单号。 + * + * 若任一订单存在非空运单号,直接抛出业务异常,阻止反审。 + * + * @param {Array} orderIds 订单ID集合。 + * @param {Object} transaction Sequelize 事务对象。 + * @return {Promise} 无返回值。 + */ + async assertOrdersWithoutWaybill(orderIds = [], 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 expressRows = await orderExpressModel.findAll({ + attributes: [ 'order_id', 'waybill_code' ], + where: { + order_id: normalizedOrderIds, + }, + 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, + }); + } } /** @@ -1464,6 +1705,7 @@ class PendingOrderService extends OrderBaseService { step: 0, status: 'created', inspection_status: 'none', + recheck_status: 'none', storage_status: 'none', post_status: 'none', pick_status: 'none', @@ -1573,6 +1815,100 @@ class PendingOrderService extends OrderBaseService { }); } + /** + * 智能地址解析:使用 DeepSeek 将用户输入的地址字符串解析为结构化地址。 + * @param {Object} data 请求数据。 + * @param {string} data.address 原始地址字符串(必填)。 + * @return {Promise} 解析结果,成功返回 province/city/area/town/detailAddress/name/mobile 等,失败返回错误。 + */ + async parseAddress(data = {}) { + const address = String(data.address || '').trim(); + if (!address) { + return this.fail('地址字符串不能为空'); + } + + const apiKey = this.config.deepseek.apiKey; + const baseUrl = this.config.deepseek.baseUrl || 'https://api.deepseek.com'; + if (!apiKey) { + return this.fail('DeepSeek API Key 未配置'); + } + + try { + const prompt = `你是一个专业的中文地址解析助手,拥有丰富的中国地理知识。请解析以下地址字符串。 + +规则: +1. 提取字段:province(省)、city(市)、area(区/县)、town(乡镇/街道)、detailAddress(详细地址)、name(收件人)、mobile(手机号) +2. **利用你的中国地理知识**:如果地址包含村/镇/街道/社区名称,请检索你的知识库推测它所属的省市区。例如: + - "和丰一社" + 常见于广东地区村组命名 → 推测为广东省 东莞市/广州市等 + - 根据地址中的方言特征、命名习惯推测所在区域 +3. 如果实在无法确定,province填"暂未识别",city和area同理填"暂未识别" +4. detailAddress去除省市区部分,只保留街道/村/门牌号 +5. 只返回纯JSON,不含解释或markdown + +地址字符串: "${address}" + +请返回JSON:`; + + const result = await this.ctx.curl(`${baseUrl}/v1/chat/completions`, { + method: 'POST', + contentType: 'json', + dataType: 'json', + headers: { + Authorization: `Bearer ${apiKey}`, + }, + data: { + model: 'deepseek-chat', + messages: [ + { role: 'system', content: '你是一个专业的地址解析助手,只返回JSON格式结果。' }, + { role: 'user', content: prompt }, + ], + temperature: 0, + max_tokens: 500, + }, + timeout: 15000, + }); + + if (result.status !== 200 || !result.data) { + return this.fail('地址解析服务请求失败'); + } + + const content = result.data.choices?.[0]?.message?.content || ''; + + // 清理可能的 markdown 代码块标记 + let jsonStr = content.trim(); + jsonStr = jsonStr.replace(/^```json\s*/i, '').replace(/\s*```$/i, ''); + jsonStr = jsonStr.replace(/^```\s*/i, '').replace(/\s*```$/i, ''); + + try { + const parsed = JSON.parse(jsonStr); + const province = String(parsed.province || '').trim(); + const city = String(parsed.city || '').trim(); + const area = String(parsed.area || '').trim(); + const town = String(parsed.town || '').trim(); + + if (!province || province === '暂未识别' || province === '其他') { + return this.fail('地址解析失败:省市区无法识别,请补充更多地址信息后重试'); + } + + return this.success('地址解析成功', { + province, + city, + area, + town, + detailAddress: String(parsed.detailAddress || '').trim(), + name: String(parsed.name || '').trim(), + mobile: String(parsed.mobile || '').trim(), + }); + } catch (parseError) { + this.ctx.logger.warn('[parseAddress] JSON解析失败,原始返回: %s', content); + return this.fail('地址解析结果格式异常,请重试'); + } + } catch (error) { + this.ctx.logger.error('[parseAddress] DeepSeek请求异常: %s', error.message); + return this.fail(`地址解析失败: ${error.message}`); + } + } + /** * 手动创建待处理订单。 * @@ -1591,7 +1927,7 @@ class PendingOrderService extends OrderBaseService { * @param {string} [data.area] 区/县。 * @param {string} [data.town] 镇/街道。 * @param {string} [data.zip_code] 邮编。 - * @param {Array} data.items 订单明细(必填,每项含 item_code 与 plan_qty)。 + * @param {Array} data.items 订单明细(必填,每项含 item_id 与 plan_qty)。 * @param {string} [data.delivery_order_code] 订单号,不传则自动生成。 * @param {string} [data.logistics_code] 快递编码,不传则读货主默认快递策略。 * @param {string} [data.logistics_name] 快递名称。 @@ -1629,37 +1965,68 @@ class PendingOrderService extends OrderBaseService { 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 所需的驼峰格式) + // 2. 批量查询商品信息(利用 getItemInfoWithCache 的 Redis 缓存) + const itemIds = rawItems + .map(item => Number(item && item.item_id)) + .filter(id => Number.isInteger(id) && id > 0); + const itemInfoMap = new Map(); + for (const itemId of itemIds) { + const info = await this.service.systems.stockStore.getItemInfoWithCache(itemId); + if (info && !info.__isNull) { + itemInfoMap.set(itemId, info); + } + } + + // 3. 适配明细格式并校验(转为 addOrder 所需的驼峰格式) const orderLineItems = rawItems.map((item, idx) => { if (!item || typeof item !== 'object') { throw new Error(`第${idx + 1}行明细格式无效`); } - const itemCode = String(item.item_code || '').trim(); - if (!itemCode) { - throw new Error(`第${idx + 1}行商品编码 item_code 不能为空`); + 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, - itemName: String(item.item_name || '').trim(), + itemCode: String(item.item_code || '').trim() + || String(itemInfoMap.get(itemId)?.item_code || '').trim(), + itemId, + itemName: String(item.item_name || '').trim() + || String(itemInfoMap.get(itemId)?.item_name || '').trim() + || '商品', planQty, orderLineNo: String(item.order_line_no || String(idx + 1)).trim(), actualPrice: Number(item.actual_price) || 0, }; }); - // 3. 自动生成订单号(如未传) + // 4. 自动生成订单号(如未传) const deliveryOrderCode = String(requestData.delivery_order_code || '').trim() || `SYS${Date.now()}${Math.floor(Math.random() * 9000) + 1000}`; - // 4. 适配为 addOrder 所需的奇门嵌套格式 + // 5. 适配为 addOrder 所需的奇门嵌套格式 const adaptedData = { request: { deliveryOrder: { @@ -1676,9 +2043,9 @@ class PendingOrderService extends OrderBaseService { name, mobile, tel, - province: String(requestData.province || '').trim(), - city: String(requestData.city || '').trim(), - area: String(requestData.area || '').trim(), + province, + city, + area, town: String(requestData.town || '').trim(), detailAddress, zipCode: String(requestData.zip_code || '').trim(), @@ -1696,7 +2063,7 @@ class PendingOrderService extends OrderBaseService { appKey: (this.ctx.user && this.ctx.user.app_key) || '', }; - // 5. 委托 addOrder 执行完整逻辑(库存预占、平台快递解析、入队列、操作日志) + // 6. 委托 addOrder 执行完整逻辑(库存预占、平台快递解析、入队列、操作日志) const result = await this.service.systems.deliveryOrder.addOrder(adaptedData, info); if (!result.success) { @@ -1722,331 +2089,6 @@ class PendingOrderService extends OrderBaseService { }); } - /** - * 下载创建订单的 Excel 导入模板。 - * - * 返回 base64 编码的 Excel 文件内容,前端解码后作为 .xlsx 文件下载。 - * 表头中标注 * 的列为必填项。 - * 多行相同订单号的行组成一个完整订单,每行代表一个商品明细。 - * - * @return {Promise} 统一 success 包装,含 base64 字符串与文件名。 - */ - async downloadCreateTemplate() { - const ExcelJS = require('exceljs'); - const workbook = new ExcelJS.Workbook(); - const sheet = workbook.addWorksheet('创建订单导入模板'); - - // 列定义:header 中带 * 表示必填 - const columns = [ - { header: '*订单号', key: 'delivery_order_code', width: 24 }, - { header: '*货主ID', key: 'store_id', width: 12 }, - { header: '*收件人姓名', key: 'name', width: 16 }, - { header: '*手机号(mobile/tel至少填一项)', key: 'mobile', width: 28 }, - { header: '电话', key: 'tel', width: 16 }, - { header: '*详细地址', key: 'detail_address', width: 36 }, - { 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_code', width: 20 }, - { header: '商品名称', key: 'item_name', width: 24 }, - { header: '*计划数量', key: 'plan_qty', width: 12 }, - { 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, - }); - - // 同订单第二个商品(示例) - 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, - }); - - // 添加说明工作表 - 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. 快递编码、系统平台编码不填时,系统会读取货主默认策略自动填充。', - '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', - }); - } - - /** - * 通过 Excel 文件批量创建订单。 - * - * 接受 base64 编码的 Excel 文件,按订单号分组,每组调用 createOrder 逻辑创建一个订单。 - * 每行代表一条商品明细;同一订单号的行组成一个完整订单,订单头信息取每组第一行。 - * - * @param {Object} data 请求体。 - * @param {string} data.file_base64 base64 编码的 .xlsx 文件内容(必填)。 - * @return {Promise} 统一 success 包装,含成功/失败明细。 - */ - async importOrdersFromExcel(data = {}) { - const requestData = this.isPlainObject(data) ? data : {}; - const fileBase64 = String(requestData.file_base64 || '').trim(); - if (!fileBase64) { - throw new Error('file_base64 不能为空'); - } - - const ExcelJS = require('exceljs'); - const workbook = new ExcelJS.Workbook(); - const buffer = Buffer.from(fileBase64, 'base64'); - await workbook.xlsx.load(buffer); - - const sheet = workbook.getWorksheet(1); - if (!sheet) { - throw new Error('Excel 文件中未找到工作表'); - } - - // 读取表头(第1行),建立列名->列序号映射 - const headerMap = {}; - const headerRow = sheet.getRow(1); - headerRow.eachCell((cell, colNumber) => { - const rawHeader = String(cell.value || '').trim().replace(/^\*/, ''); - // 归一化 key - const keyMap = { - 订单号: 'delivery_order_code', - 货主ID: 'store_id', - 收件人姓名: 'name', - '手机号(mobile/tel至少填一项)': 'mobile', - 手机号: 'mobile', - 电话: 'tel', - 详细地址: 'detail_address', - 省份: 'province', - 城市: 'city', - '区/县': 'area', - '镇/街道': 'town', - 邮编: 'zip_code', - 快递编码: 'logistics_code', - 快递名称: 'logistics_name', - 系统平台编码: 'sys_platform_code', - 来源平台编码: 'source_platform_code', - 来源订单号: 'source_order_codes', - 订单类型: 'order_type', - '是否紧急(Y/N)': 'is_urgency', - '是否需要发票(Y/N)': 'invoice_flag', - 商品编码: 'item_code', - 商品名称: 'item_name', - 计划数量: 'plan_qty', - 行号: 'order_line_no', - 实际价格: 'actual_price', - }; - const key = keyMap[rawHeader]; - if (key) { - headerMap[key] = colNumber; - } - }); - - // 辅助:从行中取值 - const getCellValue = (row, key) => { - const colNum = headerMap[key]; - if (!colNum) return undefined; - const cell = row.getCell(colNum); - const val = cell && cell.value; - if (val === null || val === undefined) return ''; - return String(val).trim(); - }; - - // 读取所有数据行(从第2行开始),跳过空行 - const orderMap = new Map(); // delivery_order_code -> { headerData, items[] } - const orderSequence = []; // 保持顺序 - - sheet.eachRow((row, rowNumber) => { - if (rowNumber === 1) return; // 跳过表头 - const deliveryOrderCode = getCellValue(row, 'delivery_order_code'); - if (!deliveryOrderCode) return; // 跳过空行 - - if (!orderMap.has(deliveryOrderCode)) { - // 首次出现,记录订单头信息 - orderMap.set(deliveryOrderCode, { - headerData: { - delivery_order_code: deliveryOrderCode, - store_id: getCellValue(row, 'store_id'), - name: getCellValue(row, 'name'), - mobile: getCellValue(row, 'mobile'), - tel: getCellValue(row, 'tel'), - detail_address: getCellValue(row, 'detail_address'), - province: getCellValue(row, 'province'), - city: getCellValue(row, 'city'), - area: getCellValue(row, 'area'), - town: getCellValue(row, 'town'), - zip_code: getCellValue(row, 'zip_code'), - logistics_code: getCellValue(row, 'logistics_code'), - logistics_name: getCellValue(row, 'logistics_name'), - sys_platform_code: getCellValue(row, 'sys_platform_code'), - source_platform_code: getCellValue(row, 'source_platform_code'), - source_order_codes: getCellValue(row, 'source_order_codes'), - order_type: getCellValue(row, 'order_type'), - is_urgency: getCellValue(row, 'is_urgency'), - invoice_flag: getCellValue(row, 'invoice_flag'), - }, - items: [], - }); - orderSequence.push(deliveryOrderCode); - } - - const itemCode = getCellValue(row, 'item_code'); - if (itemCode) { - orderMap.get(deliveryOrderCode).items.push({ - item_code: itemCode, - item_name: getCellValue(row, 'item_name'), - plan_qty: getCellValue(row, 'plan_qty'), - order_line_no: getCellValue(row, 'order_line_no'), - actual_price: getCellValue(row, 'actual_price'), - }); - } - }); - - if (orderSequence.length === 0) { - throw new Error('Excel 中未找到有效数据行'); - } - - // 逐个创建订单 - const results = { - total: orderSequence.length, - success_count: 0, - fail_count: 0, - success_orders: [], - fail_orders: [], - }; - - for (const deliveryOrderCode of orderSequence) { - const { headerData, items } = orderMap.get(deliveryOrderCode); - try { - const createData = { - ...headerData, - store_id: Number(headerData.store_id) || 0, - items: items.map((item, idx) => ({ - item_code: item.item_code, - item_name: item.item_name || '', - plan_qty: Number(item.plan_qty) || 0, - order_line_no: item.order_line_no || String(idx + 1), - actual_price: Number(item.actual_price) || 0, - })), - }; - const result = await this.createOrder(createData); - results.success_count++; - results.success_orders.push({ - delivery_order_code: deliveryOrderCode, - order_id: result && result.data && result.data.order_id, - step: result && result.data && result.data.step, - step_label: result && result.data && result.data.step_label, - }); - } catch (err) { - results.fail_count++; - results.fail_orders.push({ - delivery_order_code: deliveryOrderCode, - error: err.message, - }); - } - } - - return this.success('ok', results); - } } module.exports = PendingOrderService; diff --git a/app/service/systemMethods/order/wave.js b/app/service/systemMethods/order/wave.js index 65a8006..fdde4e0 100644 --- a/app/service/systemMethods/order/wave.js +++ b/app/service/systemMethods/order/wave.js @@ -2,6 +2,7 @@ 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; @@ -24,6 +25,8 @@ const WAVE_STRATEGY_QUICK_SCAN_TASK_CACHE_KEY_PREFIX = 'wave:quick-scan:task:'; const WAVE_STRATEGY_QUICK_SCAN_TASK_CACHE_TTL_SECONDS = 60 * 60 * 24; 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 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(); @@ -45,6 +48,41 @@ const WAVE_STRATEGY_FALLBACK_WHERE_FIELD_MAP = Object.freeze({ province: 'province', sys_platform_name: 'sys_platform_name', }); +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, + }), +}); class WaveService extends OrderBaseService { /** @@ -55,9 +93,9 @@ class WaveService extends OrderBaseService { constructor(ctx) { super(ctx); const _noNeedLogin = ''; - const _noNeedRight = 'wavePickTaskList,groupOrderFetchList,singleOrderFetchList,waveStrategyList,waveStrategyFallbackOrderList,groupFetch,singleFetch,fetch,fetchTaskProgress,batchList,batchCancel,batchCancelTaskProgress,batchRemoveExceptionOrders,batchRemoveExceptionOrdersTaskProgress,batchAllocateExpress,batchAllocateExpressTaskProgress,batchAllocateStorage,batchAllocateStorageTaskProgress,batchAutoGrouping,batchFinishAutoGrouping,batchRemoveOrders,singleFetchByIds,waveStrategyQuickScan,waveStrategyQuickScanTaskProgress'; - const _noNeedLog = 'wavePickTaskList,groupOrderFetchList,singleOrderFetchList,waveStrategyList,waveStrategyFallbackOrderList,groupFetch,singleFetch,fetch,fetchTaskProgress,batchList,batchCancel,batchCancelTaskProgress,batchRemoveExceptionOrders,batchRemoveExceptionOrdersTaskProgress,batchAllocateExpress,batchAllocateExpressTaskProgress,batchAllocateStorage,batchAllocateStorageTaskProgress,batchAutoGrouping,batchFinishAutoGrouping,batchRemoveOrders,singleFetchByIds,waveStrategyQuickScan,waveStrategyQuickScanTaskProgress'; - const _noNeedAuth = 'wavePickTaskList,groupOrderFetchList,singleOrderFetchList,waveStrategyList,waveStrategyFallbackOrderList,groupFetch,singleFetch,fetch,fetchTaskProgress,batchList,batchCancel,batchCancelTaskProgress,batchRemoveExceptionOrders,batchRemoveExceptionOrdersTaskProgress,batchAllocateExpress,batchAllocateExpressTaskProgress,batchAllocateStorage,batchAllocateStorageTaskProgress,batchAutoGrouping,batchFinishAutoGrouping,batchRemoveOrders,singleFetchByIds,waveStrategyQuickScan,waveStrategyQuickScanTaskProgress'; + const _noNeedRight = 'wavePickTaskCancelSelf,groupOrderFetchList,singleOrderFetchList,waveStrategyList,waveStrategyFallbackOrderList,waveStrategyFetchPda,waveStrategyFetchAdmin,groupFetch,singleFetch,fetch,fetchTaskProgress,batchList,wavePickTaskList,batchCancel,batchCancelTaskProgress,batchRemoveExceptionOrders,batchRemoveExceptionOrdersTaskProgress,batchAllocateExpress,batchAllocateExpressTaskProgress,batchAllocateStorage,batchAllocateStorageTaskProgress,batchAutoGrouping,batchFinishAutoGrouping,batchRemoveOrders,singleFetchByIds,waveStrategyQuickScan,waveStrategyQuickScanTaskProgress'; + const _noNeedLog = 'groupOrderFetchList,singleOrderFetchList,waveStrategyList,waveStrategyFallbackOrderList,waveStrategyFetchPda,waveStrategyFetchAdmin,groupFetch,singleFetch,fetch,fetchTaskProgress,batchList,wavePickTaskList,batchCancel,batchCancelTaskProgress,batchRemoveExceptionOrders,batchRemoveExceptionOrdersTaskProgress,batchAllocateExpress,batchAllocateExpressTaskProgress,batchAllocateStorage,batchAllocateStorageTaskProgress,batchAutoGrouping,batchFinishAutoGrouping,batchRemoveOrders,singleFetchByIds,waveStrategyQuickScan,waveStrategyQuickScanTaskProgress'; + const _noNeedAuth = 'groupOrderFetchList,singleOrderFetchList,waveStrategyList,waveStrategyFallbackOrderList,waveStrategyFetchPda,waveStrategyFetchAdmin,groupFetch,singleFetch,fetch,fetchTaskProgress,batchList,wavePickTaskList,batchCancel,batchCancelTaskProgress,batchRemoveExceptionOrders,batchRemoveExceptionOrdersTaskProgress,batchAllocateExpress,batchAllocateExpressTaskProgress,batchAllocateStorage,batchAllocateStorageTaskProgress,batchAutoGrouping,batchFinishAutoGrouping,batchRemoveOrders,singleFetchByIds,waveStrategyQuickScan,waveStrategyQuickScanTaskProgress'; this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); } @@ -658,8 +696,9 @@ class WaveService extends OrderBaseService { * @param {string} params.logisticsName 快递名称。 * @param {string} params.itemSnapshotKey 机器明细快照。 * @param {string} [params.wavePrefix] 波次编号前缀。 - * @param {string} [params.waveNo] 波次编号(传入则直接使用)。 + * @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}>} 创建结果。 */ @@ -675,6 +714,7 @@ class WaveService extends OrderBaseService { wavePrefix, waveNo, waveType, + source, transaction, } = {}) { const normalizedWarehouseId = Number(warehouseId || 0); @@ -688,6 +728,8 @@ class WaveService extends OrderBaseService { 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; let normalizedWaveNo = normalizedWaveNoInput; if (!normalizedWaveNo) { const datePart = this.getCurrentDatePart(); @@ -712,6 +754,7 @@ class WaveService extends OrderBaseService { item_snapshot_key, warehouse_id, creator, + source, create_time, update_time ) @@ -730,6 +773,7 @@ class WaveService extends OrderBaseService { :itemSnapshotKey, :warehouseId, :creator, + :source, NOW(), NOW() ) @@ -748,6 +792,7 @@ class WaveService extends OrderBaseService { itemSnapshotKey: normalizedItemSnapshotKey, warehouseId: Number.isInteger(normalizedWarehouseId) ? normalizedWarehouseId : 0, creator, + source: normalizedSource, }, transaction, }); @@ -770,245 +815,6 @@ class WaveService extends OrderBaseService { }; } - /** - * 按订单ID清理波次索引记录。 - * - * @param {Object} params 清理参数。 - * @param {number|string} params.warehouseId 仓库ID。 - * @param {Array|number|string} params.orderIds 订单ID集合。 - * @param {Object} params.transaction Sequelize 事务。 - * @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, - }); - } - - /** - * 按波次ID清理波次索引记录(用于兜底)。 - * - * @param {Object} params 清理参数。 - * @param {number|string} params.warehouseId 仓库ID。 - * @param {Array|number|string} params.waveIds 波次ID集合。 - * @param {Object} params.transaction Sequelize 事务。 - * @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|number|string} params.orderIds 订单ID集合。 - * @param {Object} [params.orderModel] 订单模型(可复用外层已获取模型)。 - * @param {Object} params.transaction Sequelize 事务。 - * @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, - }); - } - - /** - * 按波次整批覆盖订单索引并返回各波次当前订单数。 - * - * 处理流程: - * 1. 查询目标波次下当前订单(按 wave_id ASC, id ASC)。 - * 2. 先按波次批量删除 wms_order_wave_index。 - * 3. 按每个波次内订单顺序重建 wave_index;platforms_index 按平台内顺序重建(同平台按 id ASC,从 1 开始)。 - * - * @param {Object} params 覆盖参数。 - * @param {number|string} params.warehouseId 仓库ID。 - * @param {Array|number|string} params.waveIds 波次ID集合。 - * @param {Object} [params.orderModel] 订单模型(可复用外层已获取模型)。 - * @param {Object} params.transaction Sequelize 事务。 - * @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' ], - 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 || ''), - }); - } - - await this.deleteOrderWaveIndexByWaveIds({ - warehouseId: normalizedWarehouseId, - waveIds: normalizedWaveIds, - transaction, - }); - - const valueSqlList = []; - const replacements = { - warehouseId: normalizedWarehouseId, - }; - - let rowIndex = 0; - for (const waveId of normalizedWaveIds) { - const orderRowsByWave = waveOrderRowsMap.get(waveId) || []; - 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; - } - /** * 构建抓取候选订单筛选条件。 * @@ -1048,6 +854,7 @@ class WaveService extends OrderBaseService { * @param {number} [minGroupOrderFetchQuantity=13] 最小团购抓取数量。 * @param {Object} [options={}] 额外抓取选项。 * @param {number} [options.maxFetchQuantity=0] 本结构最大抓取订单数上限,0 表示不限制。 + * @param {number|string} [options.source=0] 波次来源:0-普通波次 1-管理后台策略任务 2-PDA策略任务。 * @return {Promise} 单结构抓取结果。 */ async fetchSingleStructure( @@ -1066,6 +873,8 @@ class WaveService extends OrderBaseService { && Number(normalizedOptions.maxFetchQuantity) > 0 ? Number(normalizedOptions.maxFetchQuantity) : 0; + const normalizedSourceInput = Number(normalizedOptions.source); + const normalizedSource = [ 0, 1, 2 ].includes(normalizedSourceInput) ? normalizedSourceInput : 0; const normalizedMinGroupOrderFetchQuantity = Number.isInteger(Number(minGroupOrderFetchQuantity)) && Number(minGroupOrderFetchQuantity) > 0 ? Number(minGroupOrderFetchQuantity) @@ -1124,6 +933,7 @@ class WaveService extends OrderBaseService { logisticsName: structure.logistics_name, itemSnapshotKey: structure.item_snapshot_key, wavePrefix, + source: normalizedSource, transaction, }); const orderFlagExpression = this.app.Sequelize.literal(`CASE @@ -1190,14 +1000,6 @@ class WaveService extends OrderBaseService { }); } - await this.rebuildOrderWaveIndex({ - warehouseId, - waveId, - orderIds: grabbedOrderIds, - orderModel: model, - transaction, - }); - allWaveIds.push(waveId); allOrderIds.push(...grabbedOrderIds); fetchedOrderLogItems.push(...grabbedOrderIds.map(orderId => ({ @@ -1222,6 +1024,10 @@ class WaveService extends OrderBaseService { }); 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 = '可抓取订单不足'; @@ -1406,63 +1212,64 @@ class WaveService extends OrderBaseService { * @return {string} 规范化后的筛选值,未传时返回空字符串。 */ normalizeBatchListStorageAssignmentStatusFilter(value) { - if (value === undefined || value === null || value === '') { - return ''; - } - - const normalizedValue = String(value).trim(); - if (!normalizedValue) { - return ''; - } - - const allowedValues = [ '未分配', '部分分配', '已分配' ]; - if (!allowedValues.includes(normalizedValue)) { - throw new Error(`storage_assignment_status 参数不合法,仅支持: ${allowedValues.join('、')}`); - } - - return normalizedValue; + return this.normalizeBatchListAssignmentStatusFilterByType(value, 'storage'); } /** - * 规范化波次列表快递分配状态筛选值。 + * 规范化波次列表快递分配状态筛选值(英文枚举)。 * * @param {string} value 入参筛选值。 * @return {string} 规范化后的筛选值,未传时返回空字符串。 */ normalizeBatchListExpressAssignmentStatusFilter(value) { - if (value === undefined || value === null || value === '') { - return ''; - } - - const normalizedValue = String(value).trim(); - if (!normalizedValue) { - return ''; - } - - const allowedValueMap = { - unassigned: '未分配', - partially_assigned: '部分分配', - assigned: '已分配', - }; - if (allowedValueMap[normalizedValue]) { - return allowedValueMap[normalizedValue]; - } - - const allowedValues = [ '未分配', '部分分配', '已分配' ]; - if (!allowedValues.includes(normalizedValue)) { - throw new Error('express_assignment_status 参数不合法,仅支持: unassigned、partially_assigned、assigned'); - } - - return normalizedValue; + return this.normalizeBatchListAssignmentStatusFilterByType(value, 'express'); } /** - * 规范化波次列表打印状态筛选值。 + * 规范化波次列表打印状态筛选值(英文枚举)。 * * @param {string} value 入参筛选值。 * @return {string} 规范化后的筛选值,未传时返回空字符串。 */ normalizeBatchListPrintAssignmentStatusFilter(value) { + return this.normalizeBatchListAssignmentStatusFilterByType(value, 'print'); + } + + /** + * 根据类型获取波次分配状态筛选配置。 + * + * @param {'storage'|'express'|'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'} 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 ''; } @@ -1472,21 +1279,23 @@ class WaveService extends OrderBaseService { return ''; } - const allowedValueMap = { - unprinted: '未打印', - partially_printed: '部分打印', - printed: '已打印', - }; - if (allowedValueMap[normalizedValue]) { - return allowedValueMap[normalizedValue]; + 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('、')}`); } - const allowedValues = [ '未打印', '部分打印', '已打印' ]; - if (!allowedValues.includes(normalizedValue)) { - throw new Error('print_assignment_status 参数不合法,仅支持: unprinted、partially_printed、printed'); - } - - return normalizedValue; + return matchedValue; } /** @@ -1530,109 +1339,50 @@ class WaveService extends OrderBaseService { * @return {{ sql: string, replacements: Object }} SQL 条件片段与参数。 */ buildBatchListStorageAssignmentFilterClause(statusFilter = '') { - const normalizedStatusFilter = this.normalizeBatchListStorageAssignmentStatusFilter(statusFilter); - if (!normalizedStatusFilter) { - return { - sql: '', - replacements: {}, - }; - } - - const totalExpr = 'COALESCE(wave_order_stats.order_total, 0)'; - const storageNoneExpr = 'COALESCE(wave_order_stats.storage_none_count, 0)'; - const storageFinExpr = 'COALESCE(wave_order_stats.storage_fin_count, 0)'; - const storageErrorExpr = 'COALESCE(wave_order_stats.storage_error_count, 0)'; - let whereClause = ''; - - if (normalizedStatusFilter === '已分配') { - whereClause = ` - ${storageFinExpr} = ${totalExpr} - AND ${totalExpr} > 0 - `; - } else if (normalizedStatusFilter === '部分分配') { - whereClause = ` - ${storageErrorExpr} = 0 - AND ${storageNoneExpr} <> ${totalExpr} - AND ${storageFinExpr} <> ${totalExpr} - `; - } else if (normalizedStatusFilter === '未分配') { - return { - sql: ` - AND ( - ${totalExpr} = 0 - OR ${storageErrorExpr} > 0 - OR ${storageNoneExpr} = ${totalExpr} - )`, - replacements: {}, - }; - } - - return { - sql: ` - AND ${whereClause}`, - replacements: {}, - }; + return this.buildBatchListAssignmentStatusFilterClauseByType(statusFilter, 'storage'); } /** * 构建波次列表快递分配状态筛选 SQL 条件。 * - * @param {string} statusFilter 快递分配状态筛选值。 + * @param {string} statusFilter 快递分配状态筛选值(none/partial/finished)。 * @return {{ sql: string, replacements: Object }} SQL 条件片段与参数。 */ buildBatchListExpressAssignmentFilterClause(statusFilter = '') { - const normalizedStatusFilter = this.normalizeBatchListExpressAssignmentStatusFilter(statusFilter); - if (!normalizedStatusFilter) { - return { - sql: '', - replacements: {}, - }; - } - - const totalExpr = 'COALESCE(wave_order_stats.order_total, 0)'; - const expressNoneExpr = 'COALESCE(wave_order_stats.post_none_count, 0)'; - const expressFinExpr = 'COALESCE(wave_order_stats.post_fin_count, 0)'; - const expressErrorExpr = 'COALESCE(wave_order_stats.post_error_count, 0)'; - let whereClause = ''; - - if (normalizedStatusFilter === '已分配') { - whereClause = ` - ${expressFinExpr} = ${totalExpr} - AND ${totalExpr} > 0 - `; - } else if (normalizedStatusFilter === '部分分配') { - whereClause = ` - ${expressErrorExpr} = 0 - AND ${expressNoneExpr} <> ${totalExpr} - AND ${expressFinExpr} <> ${totalExpr} - `; - } else if (normalizedStatusFilter === '未分配') { - return { - sql: ` - AND ( - ${totalExpr} = 0 - OR ${expressErrorExpr} > 0 - OR ${expressNoneExpr} = ${totalExpr} - )`, - replacements: {}, - }; - } - - return { - sql: ` - AND ${whereClause}`, - replacements: {}, - }; + return this.buildBatchListAssignmentStatusFilterClauseByType(statusFilter, 'express'); } /** * 构建波次列表打印状态筛选 SQL 条件。 * - * @param {string} statusFilter 打印状态筛选值。 + * @param {string} statusFilter 打印状态筛选值(none/partial/finished)。 * @return {{ sql: string, replacements: Object }} SQL 条件片段与参数。 */ buildBatchListPrintAssignmentFilterClause(statusFilter = '') { - const normalizedStatusFilter = this.normalizeBatchListPrintAssignmentStatusFilter(statusFilter); + return this.buildBatchListAssignmentStatusFilterClauseByType(statusFilter, 'print'); + } + + /** + * 按类型构建波次列表分配状态筛选 SQL 条件。 + * + * @param {string} statusFilter 分配状态筛选值(none/partial/finished)。 + * @param {'storage'|'express'|'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: '', @@ -1640,44 +1390,54 @@ class WaveService extends OrderBaseService { }; } - const totalExpr = 'COALESCE(wave_order_stats.order_total, 0)'; - const printNoneExpr = 'COALESCE(wave_order_stats.print_none_count, 0)'; - const printFinExpr = 'COALESCE(wave_order_stats.print_fin_count, 0)'; - let whereClause = ''; + const statsPrefix = String(schema && schema.statsColumnPrefix || '').trim(); + if (!statsPrefix) { + throw new Error('分配状态筛选配置不完整,缺少统计字段前缀'); + } - if (normalizedStatusFilter === '已打印') { - whereClause = ` - ${printFinExpr} = ${totalExpr} - AND ${totalExpr} > 0 - `; - } else if (normalizedStatusFilter === '部分打印') { - whereClause = ` - ${printNoneExpr} <> ${totalExpr} - AND ${printFinExpr} <> ${totalExpr} - `; - } else if (normalizedStatusFilter === '未打印') { + 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 - OR ${printNoneExpr} = ${totalExpr} + ${withErrorStatus ? `OR ${errorExpr} > 0\n ` : ''}OR ${noneExpr} = ${totalExpr} )`, replacements: {}, }; } - return { - sql: ` - AND ${whereClause}`, - replacements: {}, - }; + throw new Error(`不支持的分配状态筛选值: ${normalizedStatusFilter}`); } /** * 构建波次列表 where 条件(白名单字段)。 * - * @param {Object} whereData 查询 where 入参。 - * @return {{ sql: string, replacements: Object, storageAssignmentStatus: string, expressAssignmentStatus: string, printAssignmentStatus: string }} SQL 条件片段、参数与分配状态筛选值。 + * @param {Object} whereData 查询 where 入参。 + * @return {{ sql: string, replacements: Object, storageAssignmentStatus: string, expressAssignmentStatus: string, printAssignmentStatus: string }} SQL 条件片段、参数与分配状态筛选值。 */ buildBatchListWhereClause(whereData = {}) { const normalizedWhere = this.isPlainObject(whereData) ? whereData : {}; @@ -1692,7 +1452,6 @@ class WaveService extends OrderBaseService { 'wave_no', 'wave_type', 'wave_status', - 'source', 'creator', 'logistics_name', 'item_part_type', @@ -1700,6 +1459,7 @@ class WaveService extends OrderBaseService { 'item_snapshot_key', 'item_detail_machine', 'distinguish_express', + 'source', 'total_orders_min', 'total_orders_max', 'processed_orders_min', @@ -1782,16 +1542,7 @@ class WaveService extends OrderBaseService { appendLikeCondition('wave_no', 'wave_no', 'whereWaveNo'); appendIntegerEqualCondition('wave_type', 'wave_type', 'whereWaveType'); appendIntegerEqualCondition('wave_status', 'wave_status', 'whereWaveStatus'); - const source = normalizedWhere.source; - if (source !== undefined && source !== null && source !== '') { - const normalizedSource = Number(source); - if (!Number.isInteger(normalizedSource) || ![ 0, 1, 2 ].includes(normalizedSource)) { - throw new Error('source 参数不合法'); - } - - conditions.push('source = :whereSource'); - replacements.whereSource = normalizedSource; - } + appendIntegerEqualCondition('source', 'source', 'whereSource', true); appendLikeCondition('creator', 'creator', 'whereCreator'); appendLikeCondition('logistics_name', 'logistics_name', 'whereLogisticsName'); appendLikeCondition('item_part', 'item_part', 'whereItemPart'); @@ -1859,218 +1610,6 @@ class WaveService extends OrderBaseService { }; } - /** - * 解析分配状态。 - * - * @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, - }; - } - /** - * 拣货任务列表查询。 - * - * 基于 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} 列表与分页结果。 - */ - 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.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, - t.batch_no, - 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 - 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); - - 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(), - batch_no: String(item && item.batch_no || '').trim(), - 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, - })); - - 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); - } - } - /** * 解析拣货任务列表分页参数。 * @@ -2094,87 +1633,6 @@ class WaveService extends OrderBaseService { }); } - - mergeOrderItemDetails(itemRows = []) { - const merged = new Map(); - - for (const row of itemRows) { - const normalized = this.normalizeOrderItemRow(row); - if (!normalized.item_code || 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('|'); - } - - /** * 归一化拣货任务列表请求参数。 * @@ -2364,6 +1822,171 @@ class WaveService extends OrderBaseService { }; } + /** + * 解析分配状态。 + * + * @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); + if (!normalized.item_code || 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 ''; @@ -2919,6 +2542,18 @@ class WaveService extends OrderBaseService { */ async waveStrategyList(data = {}) { const requestData = this.isPlainObject(data) ? data : {}; + const rawType = requestData.strategy_type ?? requestData?.where?.strategy_type; + let normalizedStrategyType; + if (rawType !== undefined && rawType !== null && `${rawType}` !== '') { + normalizedStrategyType = Number(rawType); + if (![ 1, 2 ].includes(normalizedStrategyType)) { + throw new Error('strategy_type 仅支持 1(散单) 或 2(团购)'); + } + } + 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) { @@ -2931,10 +2566,15 @@ class WaveService extends OrderBaseService { } const offset = (page - 1) * pageSize; + const where = { + warehouse_id: contextWarehouseId, + }; + if (normalizedStrategyType !== undefined) { + where.strategy_type = normalizedStrategyType; + } + const queryResult = await strategyModel.findAndCountAll({ - where: { - warehouse_id: contextWarehouseId, - }, + where, order: [ [ 'status', 'DESC' ], [ 'id', 'DESC' ], @@ -2945,11 +2585,40 @@ class WaveService extends OrderBaseService { }); const list = Array.isArray(queryResult && queryResult.rows) ? queryResult.rows : []; + const strategyIds = [ ...new Set(list + .map(item => Number(item && item.id || 0)) + .filter(item => Number.isInteger(item) && item > 0)) ]; + const matchedOrderCountMap = await this.getWaveStrategyMatchedOrderCountFilteredMap( + contextWarehouseId, + strategyIds + ); + const nextFetchOrderCountMap = calculateNextFetchOrderCount + ? await this.getWaveStrategyNextFetchOrderCountMap(contextWarehouseId, list) + : new Map(); + const debugFetchOrderListMap = debugEnabled + ? await this.getWaveStrategyDebugFetchOrderListMap(contextWarehouseId, list) + : new Map(); + 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; return this.success('ok', { - list, + list: mergedList, pagination: { page, pageSize, @@ -2961,6 +2630,366 @@ class WaveService extends OrderBaseService { }); } + /** + * 批量预演当前页策略“下一个抓取订单数”。 + * + * 仅执行候选查询与规则计算,不写库、不建波次、不占锁。 + * + * @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 + 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.status != 'cancel' + AND o.outbound_status != 'padding' + 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 ].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), + }); + 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; + } + + /** + * 按策略统计过滤后命中订单数。 + * + * 过滤口径: + * 1) 仅统计未在波次订单(wave_id = 0); + * 2) 仅统计 step != 0 的订单; + * 3) 仅统计状态有效订单(status != cancel 且 outbound_status != padding); + * 4) 同结构数量需落在策略 min_same_structure/max_same_structure 区间内。 + * + * 同结构定义沿用快速扫描口径:优先 items_hash,空时回退 items。 + * + * @param {number|string} warehouseId 仓库ID。 + * @param {Array} strategyIds 当前页策略ID列表。 + * @return {Promise>} strategy_id 到过滤后命中订单数的映射。 + */ + async getWaveStrategyMatchedOrderCountFilteredMap(warehouseId, strategyIds = []) { + const normalizedWarehouseId = Number(warehouseId || 0); + if (!Number.isInteger(normalizedWarehouseId) || normalizedWarehouseId <= 0) { + throw new Error('未识别到当前仓库上下文'); + } + + const normalizedStrategyIds = [ ...new Set((Array.isArray(strategyIds) ? strategyIds : []) + .map(item => Number(item)) + .filter(item => Number.isInteger(item) && item > 0)) ]; + if (normalizedStrategyIds.length === 0) { + return new Map(); + } + + const orderModel = await this.getOrderModel('pendingOrder', normalizedWarehouseId); + const orderTableName = this.getModelTableSqlName(orderModel); + const 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 + 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.status != 'cancel' + AND o.outbound_status != 'padding' + INNER JOIN ( + SELECT + COALESCE(NULLIF(TRIM(COALESCE(src.items_hash, '')), ''), TRIM(COALESCE(src.items, ''))) AS structure_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.status != 'cancel' + AND src.outbound_status != 'padding' + GROUP BY COALESCE(NULLIF(TRIM(COALESCE(src.items_hash, '')), ''), TRIM(COALESCE(src.items, ''))) + ) same_structure + ON same_structure.structure_key = COALESCE(NULLIF(TRIM(COALESCE(o.items_hash, '')), ''), TRIM(COALESCE(o.items, ''))) + 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(s.min_same_structure, 0) + AND (s.max_same_structure IS NULL 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: normalizedStrategyIds, + }, + type: this.ctx.model.QueryTypes.SELECT, + }); + + const matchedMap = new Map(); + (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); + }); + + return matchedMap; + } + /** * 新增波次策略。 * @@ -3181,6 +3210,30 @@ class WaveService extends OrderBaseService { 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') { @@ -3239,8 +3292,18 @@ class WaveService extends OrderBaseService { 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'); - payload.batch_mode = this.normalizeRequiredPositiveInteger(requestData.batch_mode, 'batch_mode'); + 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(); @@ -3249,11 +3312,17 @@ class WaveService extends OrderBaseService { } 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 (Object.prototype.hasOwnProperty.call(requestData, 'batch_mode')) { - payload.batch_mode = this.normalizeRequiredPositiveInteger(requestData.batch_mode, 'batch_mode'); + payload.batch_mode = this.normalizePositiveInteger(requestData.batch_mode, 'batch_mode'); + } else if (payload.strategy_type === 2) { + payload.batch_mode = 0; } } @@ -3271,9 +3340,58 @@ class WaveService extends OrderBaseService { this.patchWaveStrategyIntegerField(payload, requestData, 'order_max_qty'); this.patchWaveStrategyIntegerField(payload, requestData, 'min_same_structure'); this.patchWaveStrategyIntegerField(payload, requestData, 'max_same_structure'); - this.patchWaveStrategyIntegerField(payload, requestData, 'batch_max_orders'); - this.patchWaveStrategyIntegerField(payload, requestData, 'batch_max_skus'); - this.patchWaveStrategyIntegerField(payload, requestData, 'group_batch_max_orders'); + 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; + } + 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); @@ -3285,22 +3403,36 @@ class WaveService extends OrderBaseService { payload.description = String(requestData.description || '').trim(); } if (Object.prototype.hasOwnProperty.call(requestData, 'allowed_provinces')) { - payload.allowed_provinces = this.normalizeWaveStrategyQuickScanStringList(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')) { - payload.allowed_platforms = this.normalizeWaveStrategyQuickScanStringList(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 allowedOwners = this.normalizeWaveStrategyQuickScanStringList(requestData.allowed_owners); - await this.validateWaveStrategyAllowedOwners(allowedOwners, warehouseId); - payload.allowed_owners = allowedOwners; + 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 allowedExpresses = this.normalizeWaveStrategyQuickScanStringList(requestData.allowed_expresses); - await this.validateWaveStrategyAllowedExpresses(allowedExpresses); - payload.allowed_expresses = allowedExpresses; + 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); @@ -3312,6 +3444,71 @@ class WaveService extends OrderBaseService { 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-团购)。 + * @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', + }; + } + /** * 按字段补丁方式归一化波次策略正整数参数。 * @@ -3364,14 +3561,15 @@ class WaveService extends OrderBaseService { */ async validateWaveStrategyAllowedExpresses(expressList = []) { const normalizedExpresses = Array.isArray(expressList) - ? expressList.map(item => String(item || '').trim().toLowerCase()).filter(Boolean) + ? expressList.map(item => String(item || '').trim()).filter(Boolean) : []; if (normalizedExpresses.length === 0) { return; } const availableExpressSet = await this.getWaveStrategyAvailableExpressSet(); - const illegalExpresses = normalizedExpresses.filter(item => !availableExpressSet.has(item)); + 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(', ')}`); @@ -3822,6 +4020,7 @@ class WaveService extends OrderBaseService { total_orders, processed_orders, distinguish_express, + source, logistics_name, item_snapshot_key, warehouse_id, @@ -3837,7 +4036,12 @@ class WaveService extends OrderBaseService { 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.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 FROM ( SELECT wave_id FROM wms_wave_batch @@ -3847,7 +4051,6 @@ class WaveService extends OrderBaseService { GROUP BY candidate_wave.wave_id ) wave_order_stats ON wave_order_stats.wave_id = wb.wave_id WHERE 1 = 1 - AND COALESCE(wave_order_stats.order_total, 0) > 0 ${storageAssignmentFilterClause.sql} ${expressAssignmentFilterClause.sql} ${printAssignmentFilterClause.sql} @@ -3862,12 +4065,22 @@ class WaveService extends OrderBaseService { wb.total_orders, wb.processed_orders, wb.distinguish_express, + wb.source, wb.logistics_name, wb.item_snapshot_key, wb.warehouse_id, wb.creator, wb.create_time, - wb.update_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 ${batchListFromSql} ORDER BY wb.total_orders DESC, wb.wave_id DESC LIMIT :limit OFFSET :offset @@ -3922,82 +4135,17 @@ class WaveService extends OrderBaseService { }); } - const waveIds = rawList - .map(item => Number(item && item.wave_id || 0)) - .filter(id => Number.isInteger(id) && id > 0); - - const orderRows = waveIds.length > 0 - ? await orderModel.findAll({ - where: { - wave_id: { [Op.in]: waveIds }, - }, - attributes: [ 'wave_id', 'storage_status', 'post_status', 'print_status' ], - raw: true, - }) - : []; - - const waveOrderStatsMap = new Map(); - for (const row of orderRows) { - const waveId = Number(row && row.wave_id || 0); - if (!Number.isInteger(waveId) || waveId <= 0) { - continue; - } - - if (!waveOrderStatsMap.has(waveId)) { - waveOrderStatsMap.set(waveId, { - orderCount: 0, - storageNoneCount: 0, - storageFinCount: 0, - storageErrorCount: 0, - expressNoneCount: 0, - expressFinCount: 0, - expressErrorCount: 0, - printNoneCount: 0, - printFinCount: 0, - }); - } - - const stats = waveOrderStatsMap.get(waveId); - const storageStatus = String(row && row.storage_status || '').trim(); - const expressStatus = String(row && row.post_status || '').trim(); - const printStatus = String(row && row.print_status || '').trim(); - - stats.orderCount += 1; - if (storageStatus === 'none') { - stats.storageNoneCount += 1; - } else if (storageStatus === 'fin') { - stats.storageFinCount += 1; - } else if (storageStatus === 'error') { - stats.storageErrorCount += 1; - } - - if (expressStatus === 'none') { - stats.expressNoneCount += 1; - } else if (expressStatus === 'fin') { - stats.expressFinCount += 1; - } else if (expressStatus === 'error') { - stats.expressErrorCount += 1; - } - - if (printStatus === 'none') { - stats.printNoneCount += 1; - } else if (printStatus === 'fin') { - stats.printFinCount += 1; - } - } - const list = rawList.map(batch => { const waveId = Number(batch && batch.wave_id || 0); - const stats = waveOrderStatsMap.get(waveId) || {}; - const orderCount = Number(stats.orderCount || 0); - const storageNoneCount = Number(stats.storageNoneCount || 0); - const storageFinCount = Number(stats.storageFinCount || 0); - const storageErrorCount = Number(stats.storageErrorCount || 0); - const expressNoneCount = Number(stats.expressNoneCount || 0); - const expressFinCount = Number(stats.expressFinCount || 0); - const expressErrorCount = Number(stats.expressErrorCount || 0); - const printNoneCount = Number(stats.printNoneCount || 0); - const printFinCount = Number(stats.printFinCount || 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); return { wave_id: waveId, @@ -4010,6 +4158,7 @@ class WaveService extends OrderBaseService { 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_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), @@ -4040,6 +4189,133 @@ class WaveService extends OrderBaseService { }); } + /** + * 拣货任务列表查询。 + * + * 基于 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} 列表与分页结果。 + */ + 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.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, + t.batch_no, + 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 + 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); + + 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(), + batch_no: String(item && item.batch_no || '').trim(), + 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, + })); + + 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); + } + } + /** * 批量解除波次任务提交接口。 * @@ -4075,6 +4351,22 @@ class WaveService extends OrderBaseService { 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 requestedTaskId = this.normalizeBatchCancelTaskId(data); const taskId = requestedTaskId || this.generateBatchCancelTaskId(warehouseId); const existingTask = await this.getBatchCancelTaskProgress(taskId); @@ -4085,7 +4377,7 @@ class WaveService extends OrderBaseService { task_id: taskId, warehouse_id: Number(existingTask.warehouse_id || warehouseId), state: String(existingTask.state || 'submitted').trim() || 'submitted', - message: 'Batch cancel task already exists. Check progress with order.wave.batchCancelTaskProgress', + message: '批量解除波次任务已存在,请勿重复提交。', accepted_at: existingTask.accepted_at || existingTask.submitted_at || new Date().toISOString(), }); } @@ -4131,7 +4423,7 @@ class WaveService extends OrderBaseService { status: 'success', task_id: taskId, warehouse_id: warehouseId, - message: 'Batch cancel submitted. Check progress with order.wave.batchCancelTaskProgress', + message: '批量解除波次任务已提交。', accepted_at: acceptedAt, }); } @@ -4282,7 +4574,7 @@ class WaveService extends OrderBaseService { task_id: taskId, warehouse_id: Number(existingTask.warehouse_id || warehouseId), state: String(existingTask.state || 'submitted').trim() || 'submitted', - message: 'Batch allocate express task already exists. Check progress with order.wave.batchAllocateExpressTaskProgress', + message: '批量分配快递任务已存在,请勿重复提交。', accepted_at: existingTask.accepted_at || existingTask.submitted_at || new Date().toISOString(), }); } @@ -4336,7 +4628,7 @@ class WaveService extends OrderBaseService { status: 'success', task_id: taskId, warehouse_id: warehouseId, - message: 'Batch allocate express submitted. Check progress with order.wave.batchAllocateExpressTaskProgress', + message: '批量分配快递任务已提交。', accepted_at: acceptedAt, }); } catch (error) { @@ -4462,7 +4754,7 @@ class WaveService extends OrderBaseService { task_id: taskId, warehouse_id: Number(existingTask.warehouse_id || warehouseId), state: String(existingTask.state || 'submitted').trim() || 'submitted', - message: 'Batch allocate storage task already exists. Check progress with order.wave.batchAllocateStorageTaskProgress', + message: '批量分配储位任务已存在,请勿重复提交。', accepted_at: existingTask.accepted_at || existingTask.submitted_at || new Date().toISOString(), }); } @@ -4513,7 +4805,7 @@ class WaveService extends OrderBaseService { status: 'success', task_id: taskId, warehouse_id: warehouseId, - message: 'Batch allocate storage submitted. Check progress with order.wave.batchAllocateStorageTaskProgress', + message: '批量分配储位任务已提交。', accepted_at: acceptedAt, }); } @@ -4622,6 +4914,110 @@ class WaveService extends OrderBaseService { 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 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, + }); + + await this.setWaveStrategyQuickScanWarehouseLock(normalizedWarehouseId, taskId, { + state: 'submitted', + accepted_at: acceptedAt, + }); + + if (wait) { + await this.runWaveStrategyQuickScanTask({ + taskId, + warehouseId: normalizedWarehouseId, + ...(orderIds.length > 0 ? { orderIds } : {}), + }); + + 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 } : {}), + }).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, + }; + } + /** * 提交波次策略快速扫描异步任务。 * @@ -4635,72 +5031,11 @@ class WaveService extends OrderBaseService { throw new Error('未识别到当前仓库上下文'); } - const warehouseId = contextWarehouseId; - const runningTask = await this.getWaveStrategyQuickScanWarehouseLock(warehouseId); - 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 this.success('ok', { - status: 'success', - task_id: existingTaskId, - warehouse_id: warehouseId, - state: existingState, - message: 'Quick scan task is already running. Check progress with order.wave.waveStrategyQuickScanTaskProgress', - accepted_at: runningTask.accepted_at || existingProgress && existingProgress.accepted_at || new Date().toISOString(), - }); - } - - await this.clearWaveStrategyQuickScanWarehouseLock(warehouseId, existingTaskId); - } - - const taskId = this.generateWaveStrategyQuickScanTaskId(warehouseId); - const acceptedAt = new Date().toISOString(); - - await this.setWaveStrategyQuickScanTaskProgress(taskId, 'submitted', { - warehouse_id: warehouseId, - 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, - error: '', - error_code: '', - result: null, - }); - - await this.setWaveStrategyQuickScanWarehouseLock(warehouseId, taskId, { - state: 'submitted', - accepted_at: acceptedAt, - }); - - setImmediate(() => { - this.runWaveStrategyQuickScanTask({ - taskId, - warehouseId, - }).catch(error => { - this.ctx.logger.error('[wave.waveStrategyQuickScan] 后台任务异常', { - taskId, - warehouseId, - error: error && error.message ? error.message : error, - stack: error && error.stack ? error.stack : '', - }); - }); - }); + const submitPayload = await this.submitWaveStrategyQuickScanForWarehouse(contextWarehouseId); return this.success('ok', { status: 'success', - task_id: taskId, - warehouse_id: warehouseId, - state: 'submitted', - message: 'Quick scan task submitted. Check progress with order.wave.waveStrategyQuickScanTaskProgress', - accepted_at: acceptedAt, + ...submitPayload, }); } @@ -4744,6 +5079,426 @@ class WaveService extends OrderBaseService { }); } + /** + * 构建快速扫描订单查询条件。 + * + * @param {number} warehouseId 仓库ID。 + * @param {number} strategyVersion 当前策略版本号。 + * @param {Array} [orderIds=[]] 限定扫描订单ID数组。 + * @return {Object} 订单查询 where 条件。 + */ + buildWaveStrategyQuickScanOrderWhere(warehouseId, strategyVersion, orderIds = []) { + const normalizedOrderIds = this.normalizeIdsInput(orderIds); + const where = { + warehouse_id: warehouseId, + step: { [Op.ne]: 0 }, + wave_id: 0, + [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(normalizedWarehouseId) && normalizedWarehouseId > 0) { + setImmediate(() => { + this.submitWaveStrategyQuickScanForWarehouse(normalizedWarehouseId).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 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', + ], + where: this.buildWaveStrategyQuickScanOrderWhere(warehouseId, strategyVersion, orderIds), + 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, + }; + } + /** * 执行波次策略快速扫描后台任务。 * @@ -4752,6 +5507,9 @@ class WaveService extends OrderBaseService { * @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 = {}) { @@ -4795,61 +5553,27 @@ class WaveService extends OrderBaseService { }); 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 subjectConfig = await this.getWarehouseSubjectConfig(warehouseId); const strategyVersion = this.normalizeWaveStrategyQuickScanVersion( this.getWarehouseSubjectConfigValue(subjectConfig, 'wave_strategy_version') ); - 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 strategyRows = await strategyModel.findAll({ - where: { - warehouse_id: warehouseId, - status: 1, - }, - order: [[ 'id', 'ASC' ]], - raw: true, - }); - 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', - ], - where: { - warehouse_id: warehouseId, - step: { [Op.ne]: 0 }, - wave_id: 0, - [Op.or]: [ - { wave_strategy_version: { [Op.ne]: strategyVersion } }, - { wave_strategy_version: { [Op.is]: null } }, - ], - }, - raw: true, + const scanResult = await this.executeWaveStrategyQuickScan({ + warehouseId, + strategyVersion, + orderIds, + taskId: normalizedTaskId, }); - const normalizedOrders = Array.isArray(orderRows) ? orderRows : []; - const totalOrderCount = normalizedOrders.length; - if (totalOrderCount === 0) { + if (scanResult.totalOrderCount === 0) { const durationMs = Date.now() - startTime; await this.setWaveStrategyQuickScanTaskProgress(normalizedTaskId, 'success', { warehouse_id: warehouseId, @@ -4869,77 +5593,24 @@ class WaveService extends OrderBaseService { return; } - const structureStoreSetMap = new Map(); - - for (const order of normalizedOrders) { - const structureKey = this.getWaveStrategyQuickScanStructureKey(order); - if (!structureKey) { - continue; - } - - const storeId = String(order && order.store_id || '').trim(); - if (!structureStoreSetMap.has(structureKey)) { - structureStoreSetMap.set(structureKey, new Set()); - } - if (storeId) { - structureStoreSetMap.get(structureKey).add(storeId); - } - } - - const matchedOrderIds = []; - const unmatchedOrderIds = []; - let processedOrderCount = 0; - - for (const order of normalizedOrders) { - const matched = this.isWaveStrategyQuickScanOrderMatched(order, strategyList, { - structureStoreSetMap, - }); - - const orderId = Number(order && order.id || 0); - if (Number.isInteger(orderId) && orderId > 0) { - if (matched) { - matchedOrderIds.push(orderId); - } else { - unmatchedOrderIds.push(orderId); - } - } - - processedOrderCount += 1; - if (processedOrderCount % 200 === 0 || processedOrderCount === totalOrderCount) { - await this.setWaveStrategyQuickScanTaskProgress(normalizedTaskId, 'running', { - warehouse_id: warehouseId, - total_order_count: totalOrderCount, - processed_order_count: processedOrderCount, - matched_order_count: matchedOrderIds.length, - unmatched_order_count: unmatchedOrderIds.length, - progress_percent: Math.min(99, Math.round((processedOrderCount / totalOrderCount) * 100)), - }); - } - } - - 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, - }); - const durationMs = Date.now() - startTime; await this.setWaveStrategyQuickScanTaskProgress(normalizedTaskId, 'success', { warehouse_id: warehouseId, - total_order_count: totalOrderCount, - processed_order_count: totalOrderCount, - matched_order_count: matchedOrderIds.length, - unmatched_order_count: unmatchedOrderIds.length, + 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, - matched_order_count: matchedOrderIds.length, - unmatched_order_count: unmatchedOrderIds.length, + 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: '波次策略快速扫描完成', }, @@ -5215,7 +5886,9 @@ class WaveService extends OrderBaseService { 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, 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), @@ -5223,9 +5896,9 @@ class WaveService extends OrderBaseService { 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), + allowed_expresses: this.normalizeWaveStrategyQuickScanStringList(normalizedRow.allowed_expresses, false), allowed_provinces: this.normalizeWaveStrategyQuickScanStringList(normalizedRow.allowed_provinces), - allowed_platforms: this.normalizeWaveStrategyQuickScanStringList(normalizedRow.allowed_platforms), + 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), }; @@ -5284,9 +5957,10 @@ class WaveService extends OrderBaseService { * 支持数组、JSON 字符串、逗号分隔字符串。 * * @param {*} value 原始值。 - * @return {Array} 归一化字符串数组(小写去重)。 + * @param {boolean} [toLowerCase=true] 是否转为小写,默认 true 保持向后兼容。 + * @return {Array} 归一化字符串数组(去重)。 */ - normalizeWaveStrategyQuickScanStringList(value) { + normalizeWaveStrategyQuickScanStringList(value, toLowerCase = true) { let rawList = []; if (Array.isArray(value)) { @@ -5310,7 +5984,7 @@ class WaveService extends OrderBaseService { } return [ ...new Set(rawList - .map(item => String(item || '').trim().toLowerCase()) + .map(item => { const s = String(item || '').trim(); return toLowerCase ? s.toLowerCase() : s; }) .filter(Boolean)) ]; } @@ -5330,23 +6004,54 @@ class WaveService extends OrderBaseService { } /** - * 计算订单快递 key。 + * 计算订单快递 key(同快递判定仅使用 sys_logistics_code)。 * * @param {Object} order 订单记录。 - * @return {string} 快递 key。 + * @return {string} 快递 key(sys_logistics_code 去首尾空格后结果,空值返回空字符串)。 */ getWaveStrategyQuickScanExpressKey(order = {}) { - const sysLogisticsCode = String(order && order.sys_logistics_code || '').trim(); - if (sysLogisticsCode) { - return sysLogisticsCode; + return String(order && order.sys_logistics_code || '').trim(); + } + + /** + * 当 require_same_express=1 时,按快递分组候选订单,仅保留最大快递组的订单。 + * + * 分组 key 使用 getWaveStrategyQuickScanExpressKey(sys_logistics_code), + * 空 key 的订单不参与筛选(直接丢弃)。 + * + * @param {Array} candidateRows 候选订单数组。 + * @return {Array} 按快递筛选后的候选订单数组(仅含最大快递组)。 + */ + filterCandidateOrdersByRequireSameExpress(candidateRows = []) { + const rows = Array.isArray(candidateRows) ? candidateRows : []; + if (rows.length === 0) { + return []; } - const logisticsCode = String(order && order.logistics_code || '').trim(); - if (logisticsCode) { - return logisticsCode; + 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); } - return String(order && order.logistics_name || '').trim(); + if (expressGroups.size === 0) { + return []; + } + + let maxGroup = []; + for (const groupOrders of expressGroups.values()) { + if (groupOrders.length > maxGroup.length) { + maxGroup = groupOrders; + } + } + + return maxGroup; } /** @@ -5358,18 +6063,39 @@ class WaveService extends OrderBaseService { * @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 false; + return []; } + const matchedStrategyIds = []; for (const strategy of list) { - if (this.isWaveStrategyQuickScanOrderMatchedSingleStrategy(order, strategy, context)) { - return true; + 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 false; + return [ ...new Set(matchedStrategyIds) ]; } /** @@ -5384,15 +6110,42 @@ class WaveService extends OrderBaseService { const normalizedOrder = this.isPlainObject(order) ? order : {}; const normalizedStrategy = this.isPlainObject(strategy) ? strategy : {}; const structureStoreSetMap = context && context.structureStoreSetMap instanceof Map ? context.structureStoreSetMap : new Map(); + const structurePrimaryExpressMap = context && context.structurePrimaryExpressMap instanceof Map + ? context.structurePrimaryExpressMap + : null; + const structurePrimaryOwnerMap = context && context.structurePrimaryOwnerMap instanceof Map + ? context.structurePrimaryOwnerMap + : null; const structureKey = this.getWaveStrategyQuickScanStructureKey(normalizedOrder); if (!structureKey) { return false; } + const storeId = String(normalizedOrder.store_id || '').trim().toLowerCase(); + if (normalizedStrategy.allow_cross_owner === false) { - const ownerSet = structureStoreSetMap.get(structureKey); - if (ownerSet instanceof Set && ownerSet.size > 1) { + 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; + } + } + } + + if (normalizedStrategy.require_same_express === true && structurePrimaryExpressMap instanceof Map) { + const primaryExpressKey = String(structurePrimaryExpressMap.get(structureKey) || '').trim().toLowerCase(); + if (!primaryExpressKey) { + return false; + } + + const currentExpressKey = String(this.getWaveStrategyQuickScanExpressKey(normalizedOrder) || '').trim().toLowerCase(); + if (currentExpressKey !== primaryExpressKey) { return false; } } @@ -5407,7 +6160,6 @@ class WaveService extends OrderBaseService { return false; } - const storeId = String(normalizedOrder.store_id || '').trim().toLowerCase(); if (normalizedStrategy.allowed_owners.length > 0 && !normalizedStrategy.allowed_owners.includes(storeId)) { return false; } @@ -5418,7 +6170,8 @@ class WaveService extends OrderBaseService { String(normalizedOrder.logistics_name || '').trim().toLowerCase(), ].filter(Boolean); if (normalizedStrategy.allowed_expresses.length > 0) { - const hitExpress = expressCandidates.some(code => normalizedStrategy.allowed_expresses.includes(code)); + const allowedLower = (normalizedStrategy.allowed_expresses || []).map(s => String(s).toLowerCase()); + const hitExpress = expressCandidates.some(code => allowedLower.includes(code)); if (!hitExpress) { return false; } @@ -5434,7 +6187,8 @@ class WaveService extends OrderBaseService { String(normalizedOrder.source_platform_code || '').trim().toLowerCase(), ].filter(Boolean); if (normalizedStrategy.allowed_platforms.length > 0) { - const hitPlatform = platformCandidates.some(code => normalizedStrategy.allowed_platforms.includes(code)); + const allowedPlatformsLower = normalizedStrategy.allowed_platforms.map(s => String(s).toLowerCase()); + const hitPlatform = platformCandidates.some(code => allowedPlatformsLower.includes(code)); if (!hitPlatform) { return false; } @@ -5606,6 +6360,7 @@ class WaveService extends OrderBaseService { } const orderModel = await this.getOrderModel('pendingOrder', warehouseId); + const transaction = await this.ctx.model.transaction(); try { @@ -5677,7 +6432,7 @@ class WaveService extends OrderBaseService { waveType: 2, distinguishExpress: false, logisticsName: '', - itemSnapshotKey: '混合订单', + itemSnapshotKey: 'manual_single_ids', wavePrefix: singleFetchByIdsWavePrefix, transaction, }); @@ -5751,14 +6506,6 @@ class WaveService extends OrderBaseService { }); } - await this.rebuildOrderWaveIndex({ - warehouseId, - waveId, - orderIds: grabbedOrderIds, - orderModel, - transaction, - }); - await transaction.commit(); await this.batchCreateOrderOperationLogs(grabbedOrderIds.map(orderId => ({ @@ -5769,6 +6516,10 @@ class WaveService extends OrderBaseService { warehouseId, scene: 'singleFetchByIds', }); + this.enqueueWaveStrategyQuickScanPostOrderChange(warehouseId, grabbedOrderIds, { + triggerScan: false, + source: 'singleFetchByIds', + }); return this.success('ok', { ids: normalizedIds, @@ -5822,6 +6573,37 @@ class WaveService extends OrderBaseService { } 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 { @@ -5884,13 +6666,39 @@ class WaveService extends OrderBaseService { const updatedOrderCount = Number(Array.isArray(orderUpdateResult) ? orderUpdateResult[0] : orderUpdateResult || 0); - const remainingCountMap = await this.replaceOrderWaveIndexByWaveIds({ + await this.deleteOrderWaveIndexByOrderIds({ warehouseId, - waveIds: affectedWaveIds, - orderModel, + orderIds: removedOrderIds, transaction, }); + const remainingRows = await orderModel.findAll({ + attributes: [ + 'wave_id', + [ this.ctx.model.fn('COUNT', this.ctx.model.col('id')), 'remaining_count' ], + ], + where: { + wave_id: { + [Op.in]: affectedWaveIds, + [Op.gt]: 0, + }, + }, + group: [ 'wave_id' ], + raw: true, + transaction, + }); + + const remainingCountMap = new Map(); + for (const row of (Array.isArray(remainingRows) ? remainingRows : [])) { + const waveId = Number(row && row.wave_id || 0); + const remainingCount = Number(row && row.remaining_count || 0); + if (!Number.isInteger(waveId) || waveId <= 0) { + continue; + } + + remainingCountMap.set(waveId, Number.isInteger(remainingCount) && remainingCount > 0 ? remainingCount : 0); + } + const updatedWaveIds = []; const emptiedWaveIds = []; @@ -5949,6 +6757,10 @@ class WaveService extends OrderBaseService { warehouseId, scene: 'batchRemoveOrders', }); + this.enqueueWaveStrategyQuickScanPostOrderChange(warehouseId, removedOrderIds, { + triggerScan: true, + source: 'batchRemoveOrders', + }); return this.success('ok', { ids: normalizedIds, @@ -6011,7 +6823,7 @@ class WaveService extends OrderBaseService { task_id: taskId, warehouse_id: Number(existingTask.warehouse_id || warehouseId), state: String(existingTask.state || 'submitted').trim() || 'submitted', - message: 'Batch remove exception orders task already exists. Check progress with order.wave.batchRemoveExceptionOrdersTaskProgress', + message: '批量移除异常订单任务已存在,请勿重复提交。', accepted_at: existingTask.accepted_at || existingTask.submitted_at || new Date().toISOString(), }); } @@ -6060,7 +6872,7 @@ class WaveService extends OrderBaseService { status: 'success', task_id: taskId, warehouse_id: warehouseId, - message: 'Batch remove exception orders submitted. Check progress with order.wave.batchRemoveExceptionOrdersTaskProgress', + message: '批量移除异常订单任务已提交。', accepted_at: acceptedAt, }); } @@ -6700,6 +7512,7 @@ class WaveService extends OrderBaseService { let affectedOrderCount = 0; let canceledWaveCount = 0; const affectedWaveIds = []; + const removedOrderIdSet = new Set(); for (const wave of targetWaves) { const waveId = Number(wave.wave_id || 0); @@ -6730,9 +7543,6 @@ class WaveService extends OrderBaseService { }; }) .filter(Boolean); - const affectedOrderIds = [ ...new Set((Array.isArray(affectedOrderRows) ? affectedOrderRows : []) - .map(row => Number(row && row.id || 0)) - .filter(orderId => Number.isInteger(orderId) && orderId > 0)) ]; const orderUpdateResult = await orderModel.update({ wave_id: 0, @@ -6743,21 +7553,6 @@ class WaveService extends OrderBaseService { }, transaction, }); - - if (affectedOrderIds.length > 0) { - await this.deleteOrderWaveIndexByOrderIds({ - warehouseId, - orderIds: affectedOrderIds, - transaction, - }); - } else { - await this.deleteOrderWaveIndexByWaveIds({ - warehouseId, - waveIds: [ waveId ], - transaction, - }); - } - const currentAffectedOrderCount = Number( Array.isArray(orderUpdateResult) ? orderUpdateResult[0] : orderUpdateResult || 0 ); @@ -6782,6 +7577,12 @@ class WaveService extends OrderBaseService { || 0 ); + await this.deleteOrderWaveIndexByWaveIds({ + warehouseId, + waveIds: [ waveId ], + transaction, + }); + await transaction.commit(); await this.batchCreateOrderOperationLogs(cancelOrderLogItems, { @@ -6789,6 +7590,13 @@ class WaveService extends OrderBaseService { 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 @@ -6832,6 +7640,12 @@ class WaveService extends OrderBaseService { } } + 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, @@ -7362,11 +8176,6 @@ class WaveService extends OrderBaseService { } const startTime = Date.now(); - let matchedOrderIds = []; - let matchedOrderCount = 0; - let orderModel = null; - let useBusinessKeyColumn = true; - let normalizedOrders = []; await this.setBatchAllocateExpressTaskProgress(normalizedTaskId, 'running', { warehouse_id: warehouseId, wave_ids: waveIds.join(','), @@ -7386,7 +8195,7 @@ class WaveService extends OrderBaseService { }); try { - orderModel = await this.getOrderModel('pendingOrder', warehouseId); + const orderModel = await this.getOrderModel('pendingOrder', warehouseId); const baseOrderWhere = { warehouse_id: warehouseId, wave_id: { @@ -7397,6 +8206,7 @@ class WaveService extends OrderBaseService { }, }; let orderRows = []; + let useBusinessKeyColumn = true; try { orderRows = await orderModel.findAll({ @@ -7431,22 +8241,20 @@ class WaveService extends OrderBaseService { matchedOrderCount: Array.isArray(orderRows) ? orderRows.length : 0, }); - normalizedOrders = (Array.isArray(orderRows) ? orderRows : []) + const normalizedOrders = (Array.isArray(orderRows) ? orderRows : []) .map(row => { const orderId = Number(row && row.id || 0); if (!Number.isInteger(orderId) || orderId <= 0) { return null; } - const businessKey = Number(useBusinessKeyColumn ? row && row.business_key : 0); + const businessKey = Number(useBusinessKeyColumn ? row && row.business_key : 1); return { order_id: orderId, - business_key: Number.isInteger(businessKey) && businessKey > 0 ? businessKey : 0, + business_key: Number.isInteger(businessKey) && businessKey > 0 ? businessKey : 1, }; }) .filter(Boolean); - matchedOrderIds = normalizedOrders.map(item => Number(item && item.order_id || 0)).filter(orderId => Number.isInteger(orderId) && orderId > 0); - matchedOrderCount = matchedOrderIds.length; if (normalizedOrders.length === 0) { this.ctx.logger.info('[wave.batchAllocateExpress] 未筛选到可分配快递号订单', { @@ -7524,57 +8332,6 @@ class WaveService extends OrderBaseService { trace_id: traceId, }); } catch (error) { - const durationMs = Date.now() - startTime; - const canIdentifyBusinessKey = useBusinessKeyColumn; - const rollbackOrderIds = canIdentifyBusinessKey - ? normalizedOrders - .filter(item => Number(item && item.business_key) === 1) - .map(item => Number(item && item.order_id || 0)) - .filter(orderId => Number.isInteger(orderId) && orderId > 0) - : []; - if (!canIdentifyBusinessKey) { - this.ctx.logger.warn('[wave.batchAllocateExpress] business_key 列不可用,按强约束跳过 post_status 失败回写', { - traceId, - taskId: normalizedTaskId, - warehouseId, - waveIds, - matchedOrderCount, - }); - } else if (rollbackOrderIds.length === 0) { - this.ctx.logger.info('[wave.batchAllocateExpress] 未命中 business_id=1 订单,跳过 post_status 失败回写', { - traceId, - taskId: normalizedTaskId, - warehouseId, - waveIds, - matchedOrderCount, - }); - } - - if (rollbackOrderIds.length > 0 && orderModel && typeof orderModel.update === 'function') { - try { - await this.service.systems.express.markWaybillAsyncOrdersAsError( - orderModel, - rollbackOrderIds, - error && error.message ? `${error.message}` : `${error}`, - { - warehouse_id: warehouseId, - wave_id: { - [Op.in]: waveIds, - }, - } - ); - } catch (updateError) { - this.ctx.logger.warn('[wave.batchAllocateExpress] 通过统一 helper 回写订单失败状态失败', { - traceId, - taskId: normalizedTaskId, - warehouseId, - waveIds, - matchedOrderCount: rollbackOrderIds.length, - error: updateError && updateError.message ? updateError.message : `${updateError}`, - }); - } - } - this.ctx.logger.error('[wave.batchAllocateExpress] 后台任务执行失败', { traceId, taskId: normalizedTaskId, @@ -7585,14 +8342,9 @@ class WaveService extends OrderBaseService { }); await this.setBatchAllocateExpressTaskProgress(normalizedTaskId, 'failed', { warehouse_id: warehouseId, - total_wave_count: waveIds.length, - total_order_count: matchedOrderCount, - processed_order_count: matchedOrderCount, - success_order_count: 0, - failed_order_count: matchedOrderCount, - progress_percent: 100, + progress_percent: 0, end_time: Date.now(), - duration_ms: durationMs, + duration_ms: Date.now() - startTime, error: error && error.message ? error.message : `${error}`, error_code: 'WAVE_BATCH_ALLOCATE_EXPRESS_FAILED', trace_id: traceId, @@ -7962,14 +8714,6 @@ class WaveService extends OrderBaseService { transaction, }); - const orderModel = await this.getOrderModel('pendingOrder', warehouseId); - await this.replaceOrderWaveIndexByWaveIds({ - warehouseId, - waveIds: updatableWaveIds, - orderModel, - transaction, - }); - const updateMeta = Array.isArray(updateResult) ? updateResult[1] : null; const updatedWaveCount = Number( updateMeta && (updateMeta.affectedRows || updateMeta.affectedCount || updateMeta.rowCount) @@ -8079,14 +8823,6 @@ class WaveService extends OrderBaseService { transaction, }); - const orderModel = await this.getOrderModel('pendingOrder', warehouseId); - await this.replaceOrderWaveIndexByWaveIds({ - warehouseId, - waveIds: updatedWaveIds, - orderModel, - transaction, - }); - const updateMeta = Array.isArray(updateResult) ? updateResult[1] : null; const updatedWaveCount = Number( updateMeta && (updateMeta.affectedRows || updateMeta.affectedCount || updateMeta.rowCount) @@ -8516,6 +9252,2996 @@ class WaveService extends OrderBaseService { 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 explicitPickMode = Number(requestData.pick_mode ?? requestData.pickMode); + if (Number.isInteger(explicitPickMode) && explicitPickMode >= 1 && explicitPickMode <= 5) { + return explicitPickMode; + } + + const strategyType = Number(strategyRow.strategy_type || 0); + 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: null, + 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}` : ''})`); + } + } + + /** + * 查询策略自动分流候选订单(命中策略且未分配波次)。 + * + * 过滤口径:step != 0、wave_id = 0、status != cancel、outbound_status != padding, + * 并按同结构数量命中 min_same_structure/max_same_structure。 + * + * @param {Object} params 查询参数。 + * @param {number|string} params.warehouseId 仓库ID。 + * @param {number|string} params.strategyId 策略ID。 + * @param {number|string|null} [params.minSameStructure=0] 最小同结构数量。 + * @param {number|string|null} [params.maxSameStructure=null] 最大同结构数量。 + * @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 orderModel = await this.getOrderModel('pendingOrder', warehouseId); + const orderTableName = this.getModelTableSqlName(orderModel); + const structureExpr = alias => `COALESCE(NULLIF(TRIM(COALESCE(${alias}.items_hash, '')), ''), TRIM(COALESCE(${alias}.items, '')))`; + 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')}` : ''; + 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 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.status != 'cancel' + AND o.outbound_status != 'padding' + 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.status != 'cancel' + AND src.outbound_status != 'padding' + GROUP BY ${structureExpr('src')}${groupKeyExtra} + ) same_structure + ON same_structure.structure_key = ${structureExpr('o')}${joinKeyExtra} + WHERE m.warehouse_id = :warehouseId + AND m.strategy_id = :strategyId + AND same_structure.same_structure_count >= :minSameStructure + AND (:maxSameStructure IS NULL OR same_structure.same_structure_count <= :maxSameStructure) + ORDER BY o.id ASC + `, { + replacements: { + warehouseId, + strategyId, + minSameStructure, + maxSameStructure, + }, + 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), + })) + .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 {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 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' }, + }, + 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, + }); + + const orderFlagExpression = this.app.Sequelize.literal(`CASE + WHEN order_flag IS NULL OR order_flag = '' THEN '${WAVE_MANUAL_FETCH_FLAG}' + WHEN order_flag LIKE '%${WAVE_MANUAL_FETCH_FLAG}%' THEN order_flag + ELSE CONCAT(order_flag, ',${WAVE_MANUAL_FETCH_FLAG}') + END`); + + await orderModel.update({ + wave_id: waveId, + wave_no: waveNo, + order_flag: orderFlagExpression, + }, { + 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, + }); + } + + await this.rebuildOrderWaveIndex({ + warehouseId, + waveId, + orderIds: grabbedOrderIds, + orderModel, + transaction, + }); + + return { + waveId, + waveNo, + selectedOrderIds: grabbedOrderIds, + }; + } + + /** + * 自动补齐按策略抓取的 selected_wave_ids / selected_order_ids。 + * + * 仅用于 PDA 按策略抓取场景,内部按 strategy_type + pick_mode 执行分流。 + * + * @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); + + await this.ensureNoActiveWavePickTaskForOperator({ + warehouseId, + operatorId, + transaction, + }); + + const candidateRows = await this.getWaveStrategyFetchCandidateOrders({ + warehouseId, + strategyId, + minSameStructure: strategyRow.min_same_structure, + maxSameStructure: strategyRow.max_same_structure, + requireSameExpress: Number(strategyRow.require_same_express || 0), + }); + 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, + grouped_count: groupedRows.length, + 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 groupLimitRaw = Number(strategyRow.group_batch_max_orders || plan.box_limit || 0); + const groupLimit = Number.isInteger(groupLimitRaw) && groupLimitRaw > 0 ? groupLimitRaw : 1; + const selectedGroups = groupedRows + .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, + 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) { + 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('散单策略无可用候选订单'); + } + + 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(`散单策略不支持的 pick_mode: ${pickMode}`); + } + + if (selectedOrderIds.length <= 0) { + throw new Error('散单策略筛选后无可用订单(候选可能已被剔除)'); + } + + const limitedOrderIds = orderLimit > 0 + ? selectedOrderIds.slice(0, orderLimit) + : selectedOrderIds; + if (limitedOrderIds.length <= 0) { + throw new Error('散单策略筛选后无可用订单(batch_max_orders 限制导致为空)'); + } + + const createdWave = await this.createWaveBatchByOrderIdsInTransaction({ + warehouseId, + orderIds: limitedOrderIds, + waveType: 2, + wavePrefix: wavePrefixResolution.wavePrefix, + source: waveBatchSource, + 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('散单策略创建波次失败:无有效波次生成'); + } + } 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, + 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):合并全部候选订单后创建一个散单波次。 + * + * @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 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), + }); + 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) { + for (const group of groupedRows) { + const created = await this.createWaveBatchByOrderIdsInTransaction({ + warehouseId, + orderIds: group.order_ids, + waveType: 1, + wavePrefix: wavePrefixResolution.wavePrefix, + source: waveBatchSource, + transaction, + }); + createdWaveIds.push(created.waveId); + createdWaveNos.push(created.waveNo); + createdOrderIds.push(...created.selectedOrderIds); + } + } else if (strategyType === 1) { + 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('散单策略无可用候选订单'); + } + + const createdWave = await this.createWaveBatchByOrderIdsInTransaction({ + warehouseId, + orderIds: mergedOrderIds, + waveType: 2, + wavePrefix: wavePrefixResolution.wavePrefix, + source: waveBatchSource, + 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(); + + 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 + let resolvedBatchNo = null; + if ([ 2, 3, 4 ].includes(pickMode) && selectedWaveIds.length > 0) { + const batchRows = await this.ctx.model.query( + 'SELECT wave_no FROM wms_wave_batch WHERE wave_id = :waveId AND warehouse_id = :warehouseId LIMIT 1', + { + replacements: { waveId: selectedWaveIds[0], warehouseId }, + type: this.ctx.model.QueryTypes.SELECT, + transaction, + } + ); + resolvedBatchNo = (batchRows.length > 0 && batchRows[0].wave_no) ? String(batchRows[0].wave_no).trim() : null; + } + + const taskPayload = this.buildTaskCreatePayload({ + plan: effectivePlan, + data: effectiveRequestData, + selectedWaveIds, + selectedOrderIds, + cartId: normalizedCartId, + }); + if (resolvedBatchNo !== null) { + taskPayload.batch_no = resolvedBatchNo; + } + + 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, + }); + const taskOrderRows = this.buildTaskOrderRows({ + taskId, + plan: effectivePlan, + selectedWaveIds, + selectedOrderIds, + cartId: normalizedCartId, + }); + 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(); + + 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: 0, + batch_no: 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。 + * @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 + : []; + + return selectedWaveIds.map((waveId, index) => ({ + task_id: taskId, + wave_id: waveId, + wave_no: null, + box_no: index + 1, + status: 0, + bind_time: null, + pick_time: null, + warehouse_id: warehouseId, + })); + } + + /** + * 构建任务订单明细写入行。 + * + * @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。 + * @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); + + if (![ 2, 3, 4 ].includes(pickMode)) { + return []; + } + + const defaultWaveId = selectedWaveIds.length > 0 ? selectedWaveIds[0] : null; + return selectedOrderIds.map((orderId, index) => ({ + task_id: taskId, + wave_id: defaultWaveId, + order_id: orderId, + order_no: null, + box_no: 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, current_task_id + 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}`); + } + + const activeTaskId = Number(cartRow.current_task_id || 0); + if (activeTaskId > 0 && activeTaskId !== 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_pick_cart + SET + current_task_id = :taskId, + bind_user_id = :operatorId, + last_bind_time = NOW(), + last_seen_time = NOW() + WHERE id = :cartId + AND warehouse_id = :warehouseId + `, { + replacements: { + taskId, + operatorId, + cartId, + warehouseId, + }, + 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, + }; + + 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, + 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, + :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/2 的任务。取消后会回收拣货车绑定、 + * 删除任务关联波次并将订单 wave_id 清空,使订单可重新参与后续策略抓取。 + * + * @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 = []; + + 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 + 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); + if (![ 0, 1, 2 ].includes(taskStatus)) { + const error = new Error('当前任务状态不允许取消'); + error.statusCode = 400; + error.data = { + task_id: taskId, + task_no: String(taskRow.task_no || '').trim(), + warehouse_id: warehouseId, + status: taskStatus, + }; + throw error; + } + + 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)) ]; + + let releasedWaveRows = []; + if (waveIds.length > 0) { + 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: '', + }, { + 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.ctx.model.query(` + DELETE FROM wms_wave_pick_task_wave + WHERE task_id = :taskId + AND warehouse_id = :warehouseId + `, { + replacements: { + taskId, + warehouseId, + }, + transaction, + }); + } + + await this.ctx.model.query(` + UPDATE wms_wave_pick_task + SET + status = 9, + current_cart_id = NULL, + current_cart_code_snapshot = NULL, + ${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.ctx.model.query(` + UPDATE wms_pick_cart + SET + current_task_id = NULL, + bind_user_id = NULL, + last_seen_time = NOW(), + update_time = NOW() + WHERE warehouse_id = :warehouseId + AND current_task_id = :taskId + `, { + replacements: { + taskId, + warehouseId, + }, + 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) || null + : null, + 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, + released_wave_ids: waveIds, + released_order_count: 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: `任务取消并释放波次: ${taskNo || taskId}`, + operator_id: Number.isInteger(operatorId) ? operatorId : 0, + operator_name: operatorName, + snapshot: JSON.stringify({ + task_no: taskNo, + released_wave_ids: waveIds, + released_order_count: taskOrderIds.length, + released_wave_nos: (Array.isArray(releasedWaveRows) ? releasedWaveRows : []) + .map(row => String(row && row.wave_no || '').trim()) + .filter(Boolean), + }), + }], transaction); + + cancelledTaskNos.push(taskNo); + } + + await transaction.commit(); + + return { + cancelled_count: normalizedTaskIds.length, + task_ids: normalizedTaskIds, + task_nos: cancelledTaskNos, + }; + } catch (error) { + await transaction.rollback(); + throw error; + } + } + + /** + * 取消拣货任务并释放关联波次。 + * + * 仅允许取消状态为 0/1/2 的任务。取消后会回收拣货车绑定、 + * 删除任务关联波次并将订单 wave_id 清空,使订单可重新参与后续策略抓取。 + * + * @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: 1, + }); + + 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' ], + 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 || ''), + }); + } + + 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 orderRowsByWave = waveOrderRowsMap.get(waveId) || []; + 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。 * diff --git a/app/service/systemMethods/pick.js b/app/service/systemMethods/pick.js index 45dd25e..b140cc8 100644 --- a/app/service/systemMethods/pick.js +++ b/app/service/systemMethods/pick.js @@ -11,9 +11,9 @@ class PickService extends MainService { constructor(ctx) { super(ctx); const _noNeedLogin = ''; - const _noNeedRight = 'query,wavePickTaskDetail,wavePickTaskCurrent'; + const _noNeedRight = 'query,wavePickTaskDetail,wavePickTaskCurrent,wavePickTaskSubmit,wavePickTaskComplete'; const _noNeedLog = 'query'; - const _noNeedAuth = 'query,wavePickTaskDetail,wavePickTaskCurrent'; + const _noNeedAuth = 'query,wavePickTaskDetail,wavePickTaskCurrent,wavePickTaskSubmit,wavePickTaskComplete'; this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); } @@ -67,6 +67,250 @@ class PickService extends MainService { 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=''] 备注。 + * @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 remark = String(params && params.remark || '').trim(); + 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' ], + raw: true, + }); + 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, + 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, + :pickMode, + 0, + 2, + 1, + :orderCount, + 0, + :operatorId, + :operatorName, + :remark, + NOW(), + NOW() + ) + `, + { + replacements: { + taskNo, + warehouseId, + waveId, + pickMode, + orderCount: normalizedOrderIds.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 (normalizedOrderIds.length > 0) { + const orderValuesSql = []; + const orderReplacements = {}; + normalizedOrderIds.forEach((orderId, index) => { + const orderIdKey = `orderId${index}`; + const orderNoKey = `orderNo${index}`; + orderValuesSql.push(`( + :taskId, + :waveId, + :${orderIdKey}, + :${orderNoKey}, + :warehouseId, + 0, + 0, + NOW(), + NOW() + )`); + orderReplacements[orderIdKey] = orderId; + orderReplacements[orderNoKey] = orderNoMap.get(orderId) || ''; + }); + + await ctx.model.query( + ` + INSERT INTO wms_wave_pick_task_order ( + task_id, + wave_id, + order_id, + order_no, + warehouse_id, + pick_status, + review_status, + create_time, + update_time + ) VALUES ${orderValuesSql.join(',\n')} + `, + { + replacements: { + taskId, + waveId, + warehouseId, + ...orderReplacements, + }, + transaction, + } + ); + } + + await transaction.commit(); + return { + task_id: taskId, + task_no: taskNo, + }; + } catch (error) { + await transaction.rollback(); + throw error; + } + } + /** * 按关键字获取或创建波次拣货任务。 * @@ -74,6 +318,12 @@ class PickService extends MainService { * - 命中运单号:先定位订单并强校验订单已入波次。 * - 命中波次号:直接按波次定位。 * + * 去重策略(按优先级): + * 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。 * - 若波次存在活动任务但创建人非当前用户:返回冲突失败信息。 @@ -242,11 +492,18 @@ class PickService extends MainService { 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_wave tw - INNER JOIN wms_wave_pick_task t ON t.id = tw.task_id - WHERE tw.wave_id = :waveId - AND t.warehouse_id = :warehouseId - AND t.status IN (0, 1, 2) + 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 `, @@ -285,11 +542,64 @@ class PickService extends MainService { ); } + // 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; const pickMode = isGroupWave ? 1 : 2; - if (!isGroupWave && selectedOrderIds.length === 0) { + if (selectedOrderIds.length === 0) { let orderModel = null; try { orderModel = await this.getOrderModelByWarehouse(normalizedWarehouseId); @@ -324,36 +634,20 @@ class PickService extends MainService { } if (selectedOrderIds.length <= 0) { - return this.fail('散单波次下无可用订单,无法创建任务', {}, 400); + return this.fail('波次下无可用订单,无法创建任务', {}, 400); } } try { - const plan = { - strategy_id: 0, - warehouse_id: normalizedWarehouseId, - source: 'pda', - operator: { - operator_id: operatorId, - operator_name: operatorName, - }, - pick_mode: pickMode, - wave_limit: 1, - order_limit: selectedOrderIds.length, - sku_limit: 0, - box_limit: 0, - dynamic_append: false, - selected_wave_ids: [ targetWaveId ], - }; - const createData = { - keyword: normalizedKeyword, - selected_order_ids: pickMode === 2 ? selectedOrderIds : [], - }; - - const createdTask = await service.systemMethods.order.wave.createWavePickTaskFromPlan({ - plan, - data: createData, - waveBatchSource: 2, + const createdTask = await this.createWavePickTask({ + warehouseId: normalizedWarehouseId, + waveId: targetWaveId, + waveNo: targetWaveNo, + pickMode, + operatorId, + operatorName, + orderIds: selectedOrderIds, + remark: `pick.query keyword=${normalizedKeyword}`, }); return this.success('ok', { @@ -416,7 +710,8 @@ class PickService extends MainService { } catch (error) { const code = Number(error && error.code); if (Number.isInteger(code) && code >= 400 && code < 600) { - return this.fail(error.message || '查询失败', {}, code); + 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); @@ -450,6 +745,104 @@ class PickService extends MainService { 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); + } + } + + /** + * 完全提交拣货任务。 + * + * 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); + } + } + } module.exports = PickService; diff --git a/app/service/systemMethods/pickCart.js b/app/service/systemMethods/pickCart.js new file mode 100644 index 0000000..3f9ac10 --- /dev/null +++ b/app/service/systemMethods/pickCart.js @@ -0,0 +1,316 @@ +'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,detail,list,codeDuplicateCheck'; + const _noNeedLog = ''; + const _noNeedAuth = 'scan,bindTaskCart,create,update,delete,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 请求参数。 + * @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, + }); + 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 5fb7b10..3c4c95b 100644 --- a/app/service/systemMethods/print.js +++ b/app/service/systemMethods/print.js @@ -255,6 +255,182 @@ class PrintService extends MainService { return Array.from(orderIdSet); } + /** + * 规范化快递打印平台编码,兼容常见别名。 + * @param {Object} payload 入参。 + * @param {string} payload.platformCode 原始平台编码。 + * @param {Object} [payload.payloadBuilder] 快递 payload 组装器。 + * @return {string} 规范化平台编码。 + */ + normalizeExpressPlatformCode(payload = {}) { + const normalizedPayload = payload && typeof payload === 'object' ? payload : {}; + const platformCode = String(normalizedPayload.platformCode || '').trim(); + const payloadBuilder = normalizedPayload.payloadBuilder; + if (payloadBuilder && typeof payloadBuilder.normalizePlatform === 'function') { + try { + const normalizedPlatformCode = String(payloadBuilder.normalizePlatform(platformCode) || '').trim().toLowerCase(); + if (normalizedPlatformCode) { + return normalizedPlatformCode; + } + } catch (error) { + this.ctx.logger.warn('[print.send] 平台编码归一化失败,回退本地策略', { + platformCode, + reason: error && error.message ? error.message : `${error}`, + }); + } + } + + const lowerPlatformCode = platformCode.toLowerCase(); + if ([ 'shipinhao', 'wechatvideo' ].includes(lowerPlatformCode)) { + return 'sph'; + } + if (lowerPlatformCode === 'ks') { + return 'kuaishou'; + } + return lowerPlatformCode; + } + + /** + * 按订单ID批量加载波次序号上下文,用于 SPH 发送阶段覆写 printNum。 + * 数据来源:wms_order_wave_index。 + * 查询失败时优雅降级为空映射,不阻断发送流程。 + * @param {Object} payload 入参。 + * @param {number|string} payload.warehouseId 仓库ID。 + * @param {Array} payload.orderIds 订单ID列表。 + * @return {Promise<{orderWaveIndexMap:Map,waveTotalOrdersMap:Map}>} 波次索引上下文。 + */ + async queryWavePrintNumContextForOrderIds(payload = {}) { + const normalizedPayload = payload && typeof payload === 'object' ? payload : {}; + const warehouseId = Number(normalizedPayload.warehouseId || 0); + const orderIds = this.normalizeOrderIds(normalizedPayload.orderIds); + const emptyResult = { + orderWaveIndexMap: new Map(), + waveTotalOrdersMap: new Map(), + }; + if (!Number.isInteger(warehouseId) || warehouseId <= 0 || orderIds.length === 0) { + return emptyResult; + } + + const orderPrintService = this.service && this.service.systems && this.service.systems.orderPrint; + if (!orderPrintService + || typeof orderPrintService.queryWaveOrderIndexMapByOrderIds !== 'function' + || typeof orderPrintService.queryWaveTotalOrderCountMap !== 'function') { + this.ctx.logger.warn('[print.send] SPH printNum 覆写依赖服务不可用,跳过波次索引查询', { + warehouseId, + orderIdsCount: orderIds.length, + }); + return emptyResult; + } + + try { + const orderWaveIndexMapResult = await orderPrintService.queryWaveOrderIndexMapByOrderIds(orderIds, warehouseId); + const orderWaveIndexMap = orderWaveIndexMapResult instanceof Map + ? orderWaveIndexMapResult + : new Map(); + const waveIds = Array.from(new Set(Array.from(orderWaveIndexMap.values()) + .map(item => Number(item && item.wave_id || 0)) + .filter(waveId => Number.isInteger(waveId) && waveId > 0))); + const waveTotalOrdersMapResult = await orderPrintService.queryWaveTotalOrderCountMap(waveIds, warehouseId); + const waveTotalOrdersMap = waveTotalOrdersMapResult instanceof Map + ? waveTotalOrdersMapResult + : new Map(); + return { + orderWaveIndexMap, + waveTotalOrdersMap, + }; + } catch (error) { + this.ctx.logger.warn('[print.send] SPH printNum 覆写波次索引查询失败,回退模板默认值', { + warehouseId, + orderIdsCount: orderIds.length, + reason: error && error.message ? error.message : `${error}`, + }); + return emptyResult; + } + } + + /** + * 将 SPH 发送任务中的 printNum 覆写为波次内序号与波次总单数。 + * @param {Object} payload 入参。 + * @param {Object} payload.requestPayload 待发送 payload。 + * @param {number|string} payload.orderId 当前订单ID。 + * @param {Map} payload.orderWaveIndexMap 订单波次索引映射。 + * @param {Map} payload.waveTotalOrdersMap 波次总单数映射。 + * @return {{applied:boolean,orderId:number,waveId:number,curNum:number,sumNum:number,reason:string}} 覆写结果。 + */ + applySphPrintNumByWaveIndex(payload = {}) { + const normalizedPayload = payload && typeof payload === 'object' ? payload : {}; + const requestPayload = normalizedPayload.requestPayload && typeof normalizedPayload.requestPayload === 'object' + ? normalizedPayload.requestPayload + : null; + const orderId = Number(normalizedPayload.orderId || 0); + const fallbackResult = { + applied: false, + orderId, + waveId: 0, + curNum: 0, + sumNum: 0, + reason: '', + }; + if (!requestPayload) { + return { + ...fallbackResult, + reason: 'requestPayload 非对象', + }; + } + + const taskList = Array.isArray(requestPayload.taskList) ? requestPayload.taskList : []; + const firstTask = taskList[0] && typeof taskList[0] === 'object' ? taskList[0] : null; + if (!firstTask) { + return { + ...fallbackResult, + reason: 'taskList[0] 不存在', + }; + } + if (!Number.isInteger(orderId) || orderId <= 0) { + return { + ...fallbackResult, + reason: 'orderId 非法', + }; + } + + const orderWaveIndexMap = normalizedPayload.orderWaveIndexMap instanceof Map + ? normalizedPayload.orderWaveIndexMap + : new Map(); + const waveTotalOrdersMap = normalizedPayload.waveTotalOrdersMap instanceof Map + ? normalizedPayload.waveTotalOrdersMap + : new Map(); + const waveOrderIndexInfo = orderWaveIndexMap.get(orderId); + const waveId = Number(waveOrderIndexInfo && waveOrderIndexInfo.wave_id || 0); + const curNum = Number(waveOrderIndexInfo && waveOrderIndexInfo.wave_index || 0); + const sumNum = Number(waveTotalOrdersMap.get(waveId) || 0); + if (!Number.isInteger(waveId) || waveId <= 0 || !Number.isInteger(curNum) || curNum <= 0 || !Number.isInteger(sumNum) || sumNum <= 0) { + return { + ...fallbackResult, + waveId, + curNum, + sumNum, + reason: '波次索引信息缺失', + }; + } + + const currentPrintNum = firstTask.printNum && typeof firstTask.printNum === 'object' && !Array.isArray(firstTask.printNum) + ? firstTask.printNum + : {}; + firstTask.printNum = { + ...currentPrintNum, + curNum, + sumNum, + }; + return { + applied: true, + orderId, + waveId, + curNum, + sumNum, + reason: '', + }; + } + /** * 从打印记录 data 中提取订单ID列表。 * 兼容 data 为对象或 JSON 字符串,无法识别时返回空数组。 @@ -2009,10 +2185,18 @@ class PrintService extends MainService { }; } - const normalizedPlatformCode = String(platformGroup && platformGroup.platform ? platformGroup.platform : '').trim().toLowerCase(); - const isKuaishouPlatform = normalizedPlatformCode === 'kuaishou' || normalizedPlatformCode === 'ks'; + const normalizedPlatformCode = this.normalizeExpressPlatformCode({ + platformCode: platformGroup && platformGroup.platform ? platformGroup.platform : '', + payloadBuilder: normalizedPayload.payloadBuilder, + }); + const isKuaishouPlatform = normalizedPlatformCode === 'kuaishou'; + const isSphPlatform = normalizedPlatformCode === 'sph'; const orderBatches = []; - if (isKuaishouPlatform) { + if (isSphPlatform) { + for (const order of orders) { + orderBatches.push([ order ]); + } + } else if (isKuaishouPlatform) { for (let index = 0; index < orders.length; index += 10) { orderBatches.push(orders.slice(index, index + 10)); } @@ -2020,6 +2204,23 @@ class PrintService extends MainService { orderBatches.push(orders); } const totalDocumentCount = orders.length; + let sphOrderWaveIndexMap = new Map(); + let sphWaveTotalOrdersMap = new Map(); + if (isSphPlatform) { + const platformOrderIds = this.collectOrderIdsFromPlatformGroup(platformGroup, orders); + const wavePrintNumContext = await this.queryWavePrintNumContextForOrderIds({ + warehouseId: normalizedPayload.warehouseId, + orderIds: platformOrderIds, + }); + sphOrderWaveIndexMap = wavePrintNumContext.orderWaveIndexMap; + sphWaveTotalOrdersMap = wavePrintNumContext.waveTotalOrdersMap; + this.ctx.logger.info('[print.send] SPH 波次索引上下文加载完成', { + ...groupSummary, + orderIdsCount: platformOrderIds.length, + orderWaveIndexCount: sphOrderWaveIndexMap.size, + waveCount: sphWaveTotalOrdersMap.size, + }); + } for (let batchIndex = 0; batchIndex < orderBatches.length; batchIndex++) { const batchOrders = orderBatches[batchIndex]; @@ -2045,12 +2246,44 @@ class PrintService extends MainService { requestPayload.task.totalDocumentCount = totalDocumentCount; } currentTaskCode = await this.reserveUniquePrintTaskCode(); - if (requestPayload.task && typeof requestPayload.task === 'object' && !Array.isArray(requestPayload.task)) { + if (isSphPlatform + && Array.isArray(requestPayload.taskList) + && requestPayload.taskList[0] + && typeof requestPayload.taskList[0] === 'object' + && !Array.isArray(requestPayload.taskList[0])) { + requestPayload.taskList[0].taskID = currentTaskCode; + } else if (requestPayload.task && typeof requestPayload.task === 'object' && !Array.isArray(requestPayload.task)) { requestPayload.task.taskID = currentTaskCode; } if (currentTaskCode && !generatedTaskCodes.includes(currentTaskCode)) { generatedTaskCodes.push(currentTaskCode); } + + if (isSphPlatform) { + const currentOrderId = Number(batchOrderIds[0] || 0); + const sphOverrideResult = this.applySphPrintNumByWaveIndex({ + requestPayload, + orderId: currentOrderId, + orderWaveIndexMap: sphOrderWaveIndexMap, + waveTotalOrdersMap: sphWaveTotalOrdersMap, + }); + if (sphOverrideResult.applied) { + this.ctx.logger.info('[print.send] SPH printNum 覆写成功', { + ...batchSummary, + orderId: sphOverrideResult.orderId, + waveId: sphOverrideResult.waveId, + curNum: sphOverrideResult.curNum, + sumNum: sphOverrideResult.sumNum, + }); + } else { + this.ctx.logger.info('[print.send] SPH printNum 覆写跳过,保持模板默认值', { + ...batchSummary, + orderId: sphOverrideResult.orderId, + reason: sphOverrideResult.reason, + }); + } + } + const payloadSummary = this.summarizeExpressPayload(requestPayload); this.ctx.logger.info('[print.send] 组装 payload 成功', { ...batchSummary, diff --git a/app/service/systemMethods/setting/expressInterface.js b/app/service/systemMethods/setting/expressInterface.js index 2f19a4f..914e658 100644 --- a/app/service/systemMethods/setting/expressInterface.js +++ b/app/service/systemMethods/setting/expressInterface.js @@ -157,6 +157,16 @@ class expressInterfaceService extends MainService { templateUrl: camelTemplateUrl, ext_data: extData, extData: camelExtData, + template_id: templateId, + templateId: camelTemplateId, + paymode, + payMode, + brandno, + brandNo, + providertype, + providerType, + providerid, + providerId, ...rest } = data || {}; @@ -197,6 +207,21 @@ class expressInterfaceService extends MainService { 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, '创建快递接口失败'); } @@ -234,6 +259,16 @@ class expressInterfaceService extends MainService { extData: camelExtData, platform_shop_id: platformShopId, platformShopId: camelPlatformShopId, + template_id: templateId, + templateId: camelTemplateId, + paymode, + payMode, + brandno, + brandNo, + providertype, + providerType, + providerid, + providerId, ...rest } = data || {}; @@ -278,6 +313,21 @@ class expressInterfaceService extends MainService { 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; + } return await this.callSystemExpressInterface('update', payload, '更新快递接口失败'); } diff --git a/app/service/systemMethods/storeWarehouse/store.js b/app/service/systemMethods/storeWarehouse/store.js index f908d90..3ce0b58 100644 --- a/app/service/systemMethods/storeWarehouse/store.js +++ b/app/service/systemMethods/storeWarehouse/store.js @@ -26,9 +26,9 @@ class StoreWarehouseStoreService extends MainService { constructor(ctx) { super(ctx); const _noNeedLogin = ''; - const _noNeedRight = 'list,sign,unbind,rename,getPolicyConfig,getPolicyConfigFields,savePolicyConfig,listApiConfig,saveApiConfig,deleteQimenConfig'; + const _noNeedRight = 'list,sign,unbind,rename,openAccount,getPolicyConfig,getPolicyConfigFields,savePolicyConfig,listApiConfig,saveApiConfig,deleteQimenConfig'; const _noNeedLog = '*'; - const _noNeedAuth = 'list,sign,unbind,rename,getPolicyConfig,getPolicyConfigFields,savePolicyConfig,listApiConfig,saveApiConfig,deleteQimenConfig'; + const _noNeedAuth = 'list,sign,unbind,rename,openAccount,getPolicyConfig,getPolicyConfigFields,savePolicyConfig,listApiConfig,saveApiConfig,deleteQimenConfig'; this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); } @@ -367,6 +367,32 @@ class StoreWarehouseStoreService extends MainService { }); } } + + /** + * 仓库代货主一键开户。 + * + * @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, + }); + } + } } module.exports = StoreWarehouseStoreService; diff --git a/app/service/systems/auth/user.js b/app/service/systems/auth/user.js index 27a3efa..f6476ce 100644 --- a/app/service/systems/auth/user.js +++ b/app/service/systems/auth/user.js @@ -2365,9 +2365,10 @@ class UserService extends Service { /** * 用户注册(重构版) - * @param {Object} userInfo 用户信息 + * @param {Object} userInfo 用户信息 + * @param {Object|null} transaction 可选事务对象,传入时 Account.create 将在事务内执行 */ - async register(userInfo) { + async register(userInfo, transaction = null) { const { ctx } = this; // 检查用户名是否已存在 @@ -2390,7 +2391,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/delivery_order.js b/app/service/systems/delivery_order.js index 1409d99..0c94204 100644 --- a/app/service/systems/delivery_order.js +++ b/app/service/systems/delivery_order.js @@ -663,6 +663,9 @@ class DeliveryOrderService extends Service { { prepend: true } ); + // 将建单渠道注入 info,供 addOrderLines 区分 MANUAL 降级逻辑 + info.createChannel = normalizedCreateChannel; + let itemsInfo = null; // 添加订单明细 if (orderLines && (orderLines.orderLine)) { @@ -1072,7 +1075,7 @@ class DeliveryOrderService extends Service { */ async addOrderLines(orderLines, orderId, info, transaction) { const { ctx, app } = this; - const { warehouseId, appKey, storeId } = info; + const { warehouseId, appKey, storeId, createChannel } = info; let order_items = []; if (orderLines && typeof orderLines === 'object') { @@ -1129,16 +1132,33 @@ class DeliveryOrderService extends Service { } else { wms_stock = await app.model.StockStore.findByPk(line.itemId, { transaction }); } - // 如果没有itemId,直接记录错误 - if (!wms_stock) { + + // MANUAL 渠道降级:信任调用方提供的 itemId,跳过 StockStore 校验 + const isManualFallback = createChannel === 'MANUAL' && line.itemId && !wms_stock; + + if (!wms_stock && !isManualFallback) { errors.push(`商品《${line.itemName}》编码《${line.itemCode}》\n未同步推送到仓库`); continue; } + if (isManualFallback) { + // 手工建单降级模式:使用调用方传入的 itemId,stockId 置 0,跳过库存锁定 + wms_stock = { + id: line.itemId, + stock_id: 0, + item_name: line.itemName || '', + item_code: line.itemCode || '', + gross_weight: 0, + }; + } + const itemId = parseInt(wms_stock.id); const stockId = Number(wms_stock.stock_id) || 0; // ========== 核心库存检查逻辑 ========== - if (!stockId) { + // MANUAL 降级时 stockId 为 0,跳过库存记录检查与锁定 + const isManualNoStock = isManualFallback && !stockId; + + if (!stockId && !isManualNoStock) { errors.push(`第${i + 1}行: 商品《${wms_stock.item_name}》库存记录不存在`); continue; } @@ -1149,24 +1169,28 @@ class DeliveryOrderService extends Service { } processedItemIds.add(itemId); - // 锁定库存 - const lockResult = await ctx.service.systems.stockStore.lockItemStorages( - stockId, - planQty, - transaction - ); + // 锁定库存(MANUAL 降级时跳过) + if (!isManualNoStock) { + const lockResult = await ctx.service.systems.stockStore.lockItemStorages( + stockId, + planQty, + transaction + ); - if (!lockResult.success) { - errors.push(`SKU${wms_stock.id}商品《${wms_stock.item_name}》编码《${wms_stock.item_code}》\n锁定失败: ${lockResult.error}`); - continue; + if (!lockResult.success) { + errors.push(`SKU${wms_stock.id}商品《${wms_stock.item_name}》编码《${wms_stock.item_code}》\n锁定失败: ${lockResult.error}`); + continue; + } + + const totalQtyForStock = (stockQuantityMap.get(stockId) || 0) + planQty; + stockQuantityMap.set(stockId, totalQtyForStock); } - const totalQtyForStock = (stockQuantityMap.get(stockId) || 0) + planQty; - stockQuantityMap.set(stockId, totalQtyForStock); - - // 优先使用商品主数据重量,缺失时降级为0。 - const weight = parseFloat(wms_stock.gross_weight) || 0; - stockWeightMap.set(stockId, weight); + // 优先使用商品主数据重量,缺失时降级为0;MANUAL 降级时重量为 0 + const weight = isManualNoStock ? 0 : (parseFloat(wms_stock.gross_weight) || 0); + if (!isManualNoStock) { + stockWeightMap.set(stockId, weight); + } // ========== 库存检查逻辑结束 ========== // 所有检查通过,准备订单行数据 diff --git a/app/service/systems/express.js b/app/service/systems/express.js index 9e68ed8..faec8a3 100644 --- a/app/service/systems/express.js +++ b/app/service/systems/express.js @@ -56,6 +56,8 @@ const WAYBILL_ORDER_DELIVERY_MIN_ATTRIBUTES = Object.freeze([ 'oaid', 'source_order_codes', 'logistics_code', + 'extend_props', + 'buyer_nick', ]); class ExpressService extends Service { @@ -1510,7 +1512,10 @@ class ExpressService extends Service { continue; } - platformCodeByPrintPlatformIdMap.set(printPlatformId, platformCode); + if (!platformCodeByPrintPlatformIdMap.has(printPlatformId)) { + platformCodeByPrintPlatformIdMap.set(printPlatformId, []); + } + platformCodeByPrintPlatformIdMap.get(printPlatformId).push(platformCode); } if (!printPlatformModel || typeof printPlatformModel.findAll !== 'function' || platformCodeByPrintPlatformIdMap.size <= 0) { @@ -1535,12 +1540,14 @@ class ExpressService extends Service { continue; } - const systemPlatformCode = platformCodeByPrintPlatformIdMap.get(printPlatformId); - if (!systemPlatformCode) { + const systemPlatformCodes = platformCodeByPrintPlatformIdMap.get(printPlatformId); + if (!Array.isArray(systemPlatformCodes) || systemPlatformCodes.length === 0) { continue; } - printPlatformCodeMap.set(systemPlatformCode, platformCode); + for (const systemPlatformCode of systemPlatformCodes) { + printPlatformCodeMap.set(systemPlatformCode, platformCode); + } } return printPlatformCodeMap; @@ -1569,7 +1576,10 @@ class ExpressService extends Service { continue; } - platformCodeByPrintPlatformIdMap.set(printPlatformId, platformCode); + if (!platformCodeByPrintPlatformIdMap.has(printPlatformId)) { + platformCodeByPrintPlatformIdMap.set(printPlatformId, []); + } + platformCodeByPrintPlatformIdMap.get(printPlatformId).push(platformCode); } if (!printPlatformModel || typeof printPlatformModel.findAll !== 'function' || platformCodeByPrintPlatformIdMap.size <= 0) { @@ -1594,12 +1604,14 @@ class ExpressService extends Service { continue; } - const systemPlatformCode = platformCodeByPrintPlatformIdMap.get(printPlatformId); - if (!systemPlatformCode) { + const systemPlatformCodes = platformCodeByPrintPlatformIdMap.get(printPlatformId); + if (!Array.isArray(systemPlatformCodes) || systemPlatformCodes.length === 0) { continue; } - requestPlatformCodeMap.set(systemPlatformCode, requestPlatformCode); + for (const systemPlatformCode of systemPlatformCodes) { + requestPlatformCodeMap.set(systemPlatformCode, requestPlatformCode); + } } return requestPlatformCodeMap; @@ -1640,6 +1652,15 @@ class ExpressService extends Service { ? 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; } @@ -1665,6 +1686,13 @@ class ExpressService extends Service { 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; } diff --git a/app/service/systems/express_platform.js b/app/service/systems/express_platform.js index f89a55e..e94e7e4 100644 --- a/app/service/systems/express_platform.js +++ b/app/service/systems/express_platform.js @@ -430,21 +430,26 @@ class ExpressPlatformService extends MainService { api: 'Differ.JH.LogisticsPlatFeatures', response: Dictionary_result, }); - console.log("listByWarehousePlatformCode",listByWarehousePlatformCode) + console.log('listByWarehousePlatformCode', listByWarehousePlatformCode); const order_bizcontent = { orders: orders.map(order_tmp => { const order = order_tmp.order_delivery; - return { + const expressListItem = ExpressList.find(item => item.code === listByWarehousePlatformCode.sys_express_code) || {}; + let playload = { + object_Id: `${order.warehouse_id}_${order.id}_${order_tmp.business_key}`, // 菠萝派平台要求订单唯一标识必须为字符串 orderno: `${order.warehouse_id}_${order.id}_${order_tmp.business_key}`, // 菠萝派平台要求订单号必须为字符串 plattradeno: order.source_order_codes || order.delivery_order_code || '', ismultiplepieces: order.package_count > 1 ? 1 : 0, logisticno: allocatedWaybillMap.get(`${Number(order.id) || 0}:${Number(order_tmp.business_key) || 0}`) || '', logistictype: order.logistics_code || '', + providercode: expressListItem[listByWarehousePlatformCode.platform_code] || order.logistics_code || '', numpackage: order.package_count || 1, - businesstype: 'JH_Normal', + businessType: listByWarehousePlatformCode.product_type, businessplat: order.sys_platform_code === 'KS' ? order.sys_platform_code : 'OTHERS', paymode: listByWarehousePlatformCode.paymode ?? 1, ordertype: listByWarehousePlatformCode.ordertype ?? 'JH_Normal', + ProviderID: listByWarehousePlatformCode.providerid ?? '', + procode: order.procode || '普通商品', codpaymoney: order.ar_amount ?? null, packagemoney: order.item_amount ?? null, weight: Number(order.items_weight) || 0, @@ -454,13 +459,15 @@ class ExpressPlatformService extends MainService { height: Number(order.height) || 0, volume: Number(order.volume) || 0, ispickup: listByWarehousePlatformCode.ispickup ?? 0, - producttype: listByWarehousePlatformCode.product_type || '', + ProductType: listByWarehousePlatformCode.product_type || '', Sipshopid: listByWarehousePlatformCode.platform_shop_id || '', + oaid: order.oaid || '', sys_express_code: listByWarehousePlatformCode.sys_express_code || '', platform_code: listByWarehousePlatformCode.platform_code || '', - cpcode: ExpressList.find(item => item.code === listByWarehousePlatformCode.sys_express_code)[listByWarehousePlatformCode.platform_code] || '', + cpcode: expressListItem[listByWarehousePlatformCode.platform_code] || '', logisticsproductname: 'JH_02', dmssorting: 0, + brandno: listByWarehousePlatformCode.brandno || null, needencrypt: 1, ordersource: matchedPlatform.ordersource || '', inputsite: listByWarehousePlatformCode.site_code || '', @@ -470,7 +477,6 @@ class ExpressPlatformService extends MainService { company: listByWarehousePlatformCode.shop_name || '', name: listByWarehousePlatformCode.sender_name || '', phone: listByWarehousePlatformCode.sender_tel || '', - mobile: listByWarehousePlatformCode.sender_tel || '', country: 'CN', city: listByWarehousePlatformCode.city_name || '', province: listByWarehousePlatformCode.province_name || '', @@ -499,14 +505,130 @@ class ExpressPlatformService extends MainService { count: item.plan_qty || 0, }))) || [], Mallmaskid: '', - - template_url: matchedPlatform.template_url || '', + + template_url: listByWarehousePlatformCode.template_id || '', labelformat: listByWarehousePlatformCode.labelformat || '', extraInfo: ExpressList.find(item => item.code === listByWarehousePlatformCode.sys_express_code)?.polyapi_extra_info || '', }; + if (Number(matchedPlatform.platid) === 673) { + playload.BizVersion = '2'; + playload.brandno = listByWarehousePlatformCode.brandno || ''; + } + if (Number(matchedPlatform.platid) === 544) { + const { + orderno, + plattradeno, + logistictype, + ProductType, + providercode, + numpackage, + businessplat, + paymode, + ordertype, + businessType, + codpaymoney, + ProviderID, + cpcode, + logisticsproductname, + needencrypt, + ordersource, + shipperno, + sitecode, + goods, + sender = {}, + receiver = {}, + } = playload; + const { + name: senderNameRaw, + company: senderCompanyRaw, + phone: senderPhoneRaw, + mobile: senderMobileRaw, + country, + city: senderCity, + province: senderProvince, + address: senderAddress, + } = sender; + const { + name, + phone, + mobile, + 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, + expresstype: ProductType, + logistictype, + providercode: providercode || cpcode || logistictype || '', + numpackage, + businessplat, + mainsubpaymode: '1', + ordertype, + businessType: businessType || ordertype || 'JH_Normal', + codpaymoney, + ProviderID, + cpcode, + logisticsproductname, + needencrypt, + ordersource, + shipperno, + sitecode, + customername, + goods, + 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 = order.source_order_codes.split(",")[0]; + if(!order.extend_props.ewaybill_order_code){ + throw new Error('订单数据错误,参数不全缺失extend_props.ewaybill_order_code,请复制次信息给ERP方反馈'); + } + playload.oaid = order.extend_props.ewaybill_order_code; + 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, @@ -519,7 +641,7 @@ class ExpressPlatformService extends MainService { this.ctx.logger.info('[expressPlatform.polyapi] PolyAPI 分配快递号接口调用后', { traceId, api: 'Differ.JH.Logistics.PostOrder', - response: result, + response: JSON.stringify(result), }); if (result && result.code !== '10000') { this.ctx.logger.error('[expressPlatform.polyapi] PolyAPI 返回业务失败', { @@ -555,7 +677,7 @@ class ExpressPlatformService extends MainService { logistics_interface_name: listByWarehousePlatformCode.name || '', platform_code: listByWarehousePlatformCode.platform_code || '', status: 1, - + retry_count: 0, }, orderDeliveryValues: { @@ -596,9 +718,218 @@ class ExpressPlatformService extends MainService { }; }); break; - case 'JD': - case 'XHS': - case 'SPH': + case 'JD':{ + const batchPrintSipshopid = String(listByWarehousePlatformCode.platform_shop_id || '0'); + const batchPrintOrders = (result.results || []).map(item => ({ + orderno: String(item.orderno || ''), + logisticno: String(item.logisticno || item.waybill_code || ''), + 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: '', + remark: '', + carrier: batchPrintSipshopid, + selleruserid: '', + printno: '', + iscloudprint: 'false', + needprintdetail: 'false', + extenddata: '', + providercode: String(item.procode || item.realcpcode || item.logisticcompanycode || ''), + packageno: '', + fontsize: '', + platorderno: String(item.plattradeno || item.platorderno || item.orderno || ''), + sipshopid: batchPrintSipshopid, + })); + 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, order_id, business_key ] = objectId.split('_'); + 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(), + logistics_code: listByWarehousePlatformCode.logistics_code || '', + logistics_interface_id: listByWarehousePlatformCode.id || null, + logistics_name: listByWarehousePlatformCode.logistics_name || '', + 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, order_id, business_key ] = String(item.orderno || '').split('_'); + 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(), + logistics_code: listByWarehousePlatformCode.logistics_code || '', + logistics_interface_id: listByWarehousePlatformCode.id || null, + logistics_name: listByWarehousePlatformCode.logistics_name || '', + 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, order_id, business_key ] = objectIdParts; + 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(), + logistics_code: listByWarehousePlatformCode.logistics_code || '', + logistics_interface_id: listByWarehousePlatformCode.id || null, + logistics_name: listByWarehousePlatformCode.logistics_name || '', + 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, order_id, business_key ] = String(item.orderno || '').split('_'); @@ -875,8 +1206,8 @@ class ExpressPlatformService extends MainService { 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(matchedPlatform.template_url) - ? String(matchedPlatform.template_url).trim() + const normalizedTemplateUrl = isValidCainiaoTemplateUrl(listByWarehousePlatformCode.template_url) + ? String(listByWarehousePlatformCode.template_url).trim() : DEFAULT_CAINIAO_TEMPLATE_URL; if (!appKey || !appSecret) { throw new Error('淘宝接口配置缺失'); @@ -914,7 +1245,7 @@ class ExpressPlatformService extends MainService { }, package_info: { items: (orderDelivery && orderDelivery.orderItems || []).map(item => ({ - name: item.item_name, + name: item.item_name || '商品', count: item.plan_qty, })) || [], goods_description: '物品', @@ -934,6 +1265,7 @@ class ExpressPlatformService extends MainService { oaid: orderDelivery && orderDelivery.oaid || '', tid: sourceOrderCodes[0] || '', }, + oaid: orderDelivery && orderDelivery.oaid || '', user_id: listByWarehousePlatformCode.shop && listByWarehousePlatformCode.shop.owner_id || 0, notify_extend_info: normalizedExtData, }; @@ -1426,7 +1758,7 @@ class ExpressPlatformService extends MainService { }, package_info: { items: (order_tmp.order_delivery && order_tmp.order_delivery.orderItems || []).map(item => ({ - name: item.item_name, + name: item.item_name || '商品', count: item.plan_qty, })) || [], }, @@ -1443,7 +1775,7 @@ class ExpressPlatformService extends MainService { 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: matchedPlatform.template_url || '', + template_url: listByWarehousePlatformCode.template_url || '', user_id: listByWarehousePlatformCode.shop.owner_id || 0, }; } diff --git a/app/service/systems/order_async.js b/app/service/systems/order_async.js index 11a8b14..3c562cb 100644 --- a/app/service/systems/order_async.js +++ b/app/service/systems/order_async.js @@ -765,6 +765,39 @@ async function finalizeLocalChannelOrdersInternal(service, createChannel, groupe const failedCount = syncResults.filter(item => item.status === 'failed').length; const overallSuccess = failedCount === 0 && successCount === syncResults.length; + // 同步成功后触发 OpenAPI 回调通知(fire-and-forget,不阻塞主流程) + if (createChannel === CREATE_CHANNEL_API && successCount > 0) { + try { + const callbackService = service.ctx.service.openapi && service.ctx.service.openapi.callback; + + if (callbackService && typeof callbackService.sendByAppKey === 'function') { + const appKey = String(context.appKey || '').trim(); + + if (appKey) { + callbackService.sendByAppKey({ + appKey, + event: 'order_completed', + data: { + orderIds, + status: 'completed', + successCount, + failedCount, + }, + metadata: { + warehouseId, + createChannel, + syncTarget, + }, + }).catch(err => { + service.ctx.logger.warn(`[OrderAsyncService] OpenAPI 回调忽略失败: ${err.message}`); + }); + } + } + } catch (err) { + service.ctx.logger.warn(`[OrderAsyncService] 触发回调异常,不影响主流程: ${err.message}`); + } + } + return { create_channel: createChannel, order_ids: orderIds, diff --git a/app/service/systems/order_export.js b/app/service/systems/order_export.js index 0ab5d2e..600332f 100644 --- a/app/service/systems/order_export.js +++ b/app/service/systems/order_export.js @@ -47,6 +47,7 @@ const ORDER_EXPORT_COLUMNS = Object.freeze([ { 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: 'post_status', width: 14 }, { header: '打包状态', key: 'pack_status', width: 14 }, { header: '归档时间', key: 'archive_time', width: 20 }, @@ -257,6 +258,7 @@ class OrderExportService extends OrderBaseService { delivery_time: this.normalizeExportCellValue(safeOrderRow.delivery_time), outbound_status: this.normalizeExportCellValue(safeOrderRow.outbound_status), inspection_status: this.normalizeExportCellValue(safeOrderRow.inspection_status), + recheck_status: this.normalizeExportCellValue(safeOrderRow.recheck_status), post_status: this.normalizeExportCellValue(safeOrderRow.post_status), pack_status: this.normalizeExportCellValue(safeOrderRow.pack_status), archive_time: this.normalizeExportCellValue(safeOrderRow.archive_time), diff --git a/app/service/systems/order_print.js b/app/service/systems/order_print.js index 4422a58..ecbdee7 100644 --- a/app/service/systems/order_print.js +++ b/app/service/systems/order_print.js @@ -526,11 +526,21 @@ class OrderPrintSystemService extends OrderBaseService { .filter(orderId => Number.isInteger(orderId) && orderId > 0); const orderExpressRows = await this.queryOrderExpressByOrderIds(orderIds); this.assertBusinessWaybillCompleteness(orderIds, orderExpressRows); - const enrichedOrderExpressRows = await this.enrichCainiaoOrderExpressRows( + 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 => { @@ -1103,6 +1113,15 @@ class OrderPrintSystemService extends OrderBaseService { * @param {Array} orderIds 订单ID数组。 * @return {Promise>} 快递单信息列表。 */ + /** + * 根据订单 ID 列表批量查询运单记录。 + * 返回 business_key=1 的主运单,按 order_id、business_key、id 升序排列。 + * + * @param {number[]} orderIds 订单 ID 列表。 + * @returns {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 = []) { if (!Array.isArray(orderIds) || orderIds.length === 0) { return []; @@ -1123,6 +1142,7 @@ class OrderPrintSystemService extends OrderBaseService { 'waybill_code', 'logistics_code', 'logistics_name', + 'logistics_interface_id', 'logistics_interface_name', 'platform_code', 'warehouse_id', @@ -1352,6 +1372,36 @@ ${waveFilterSql} 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'; + } + /** * 收集菜鸟编码映射可能命中的快递编码候选项。 * @@ -1443,6 +1493,87 @@ ${waveFilterSql} 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 : []; + } + /** * 按订单物流编码匹配菜鸟主面单接口配置。 * @@ -1499,6 +1630,186 @@ ${waveFilterSql} 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; + } + /** * 为菜鸟打印订单补齐主面单专用来源字段。 * @@ -1580,6 +1891,234 @@ ${waveFilterSql} }); } + /** + * 为京东打印订单补齐主面单模板来源字段。 + * + * 仅对打印平台归一化为京东的订单生效;补齐失败时保留原始运单数据,避免影响其他平台打印。 + * + * @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); + 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 matchedInterface = this.pickDouyinExpressInterface(douyinInterfaceList, orderRow, row); + const matchedTemplateUrl = String(matchedInterface && matchedInterface.template_url || '').trim(); + this.ctx.logger.info('[enrichPddDyOrderExpressRows] douyin 单笔匹配结果', { + orderId, + hasMatchedInterface: !!matchedInterface, + matchedTemplateUrl, + sysLogisticsCode: orderRow.sys_logistics_code, + logisticsCode: row.logistics_code, + }); + if (!matchedTemplateUrl) { + return row; + } + + // 获取菠萝派 API 请求参数 + let dyParams = ''; + try { + if (matchedInterface) { + const cacheKey = `douyin:params:${orderRow.sys_logistics_code || orderRow.logistics_code || ''}:${row.logistics_interface_id || ''}`; + + // 菠萝派配置:appkey/app_secret 来自项目 config.poloApi,token 来自快递接口 + const poloConfig = this.config.poloApi || {}; + + // 先查 Redis 缓存 + if (this.app && typeof this.app.getCacheAsync === 'function') { + const cached = await this.app.getCacheAsync(cacheKey); + if (cached && typeof cached === 'string') { + dyParams = cached; + } + } + // 缓存未命中,调菠萝派 + if (!dyParams) { + 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: matchedInterface.token || '', + }, + token: matchedInterface.token || '', + }); + + this.ctx.logger.info('[DouyinParams] 菠萝派 GetPlatApiRequestInfo 响应:', JSON.stringify(result)); + dyParams = result.requestinfo || JSON.stringify(result); + + if (this.app && typeof this.app.setCacheAsync === 'function') { + await this.app.setCacheAsync(cacheKey, dyParams, 270); + } + } + } + } catch (err) { + this.ctx.logger.warn('[enrichPddDyOrderExpressRows] 获取 Douyin params 失败: %s', err.message); + } + + return { + ...row, + dy_template_url: matchedTemplateUrl, + dy_params: dyParams, + }; + } + + return row; + })); + } + /** * 获取波次订单对应货主的签约策略映射。 * @@ -1725,7 +2264,6 @@ ${waveFilterSql} }, }); const printData = this.extractSinglePlatformPrintData(printPayload); - return { wave_id: waveId, wave_no: String(orderRow.wave_no || '').trim(), @@ -1776,6 +2314,10 @@ ${waveFilterSql} return taskListEntry.documents[0]; } + if (Array.isArray(requestSkeleton.taskList) && this.isPlainObject(requestSkeleton.taskList[0])) { + return requestSkeleton.taskList[0]; + } + return {}; } diff --git a/app/service/systems/order_storage_allocation.js b/app/service/systems/order_storage_allocation.js index 17f688c..555f0bb 100644 --- a/app/service/systems/order_storage_allocation.js +++ b/app/service/systems/order_storage_allocation.js @@ -1393,6 +1393,7 @@ class OrderStorageAllocationService extends MainService { const { ctx } = this; const unallocatedPostStatus = 'none'; const fastFailReason = '快递状态未分配,禁止同步'; + const snBatchForbiddenReason = 'SN订单不支持批量回传,请改用单订单回传'; const requestData = data && typeof data === 'object' ? data : {}; const normalizeNumber = (value, defaultValue = 0) => { const numericValue = Number(value); @@ -1533,6 +1534,79 @@ class OrderStorageAllocationService extends MainService { orderMap.set(Number(plainOrder.id), plainOrder); } + // SN 管理订单不允许走批量回传:通过订单明细 stock_id 反查 stock_warehouse.is_sn_mgmt。 + const snOrderIdSet = 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; + + 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: [ 'order_id', 'stock_id' ], + 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)); + + 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) { + snOrderIdSet.add(orderId); + } + } + } + } + } catch (snDetectError) { + ctx.logger.error('[OrderStorageAllocationService.syncOrderIds] SN订单检测失败', { + warehouseId, + orderIds: existingOrderIds, + message: snDetectError && snDetectError.message, + }); + throw snDetectError; + } + } + + if (snOrderIdSet.size > 0) { + const forbiddenOrderIds = Array.from(snOrderIdSet).sort((a, b) => a - b); + await transaction.rollback(); + return { + code: 400, + message: snBatchForbiddenReason, + data: { + warehouse_id: warehouseId, + requested_order_ids: orderIds, + forbidden_order_ids: forbiddenOrderIds, + }, + }; + } + const skippedOrders = []; const fastFailedOrders = []; const syncableOrders = []; @@ -1575,7 +1649,8 @@ class OrderStorageAllocationService extends MainService { syncableOrders.push(orderRow); } - const fastFailedOrderIds = fastFailedOrders + const expressFastFailedOrderIds = fastFailedOrders + .filter(order => String(order && order.failed_reason || '').trim() === 'express_unallocated') .map(order => normalizeNumber(order.order_id, 0)) .filter(orderId => orderId > 0); @@ -1600,7 +1675,7 @@ class OrderStorageAllocationService extends MainService { }); } - if (fastFailedOrderIds.length > 0) { + if (expressFastFailedOrderIds.length > 0) { await orderModel.update({ sync_status: 'error', sync_message: fastFailReason, @@ -1611,7 +1686,7 @@ class OrderStorageAllocationService extends MainService { }, { where: { id: { - [ctx.app.Sequelize.Op.in]: fastFailedOrderIds, + [ctx.app.Sequelize.Op.in]: expressFastFailedOrderIds, }, warehouse_id: warehouseId, }, @@ -1620,7 +1695,7 @@ class OrderStorageAllocationService extends MainService { ctx.logger.warn('[OrderStorageAllocationService.syncOrderIds] 命中快递状态未分配快速失败,已阻断同步派发', { warehouseId, - orderIds: fastFailedOrderIds, + orderIds: expressFastFailedOrderIds, reason: fastFailReason, }); } @@ -1690,7 +1765,7 @@ class OrderStorageAllocationService extends MainService { code: 200, message: syncableOrderIds.length > 0 ? '同步已受理,已生成按来源分组的同步计划' - : (fastFailedOrders.length > 0 ? '同步失败:存在快递状态未分配订单' : '没有需要同步的订单'), + : (fastFailedOrders.length > 0 ? '同步失败:存在不允许批量回传的订单' : '没有需要同步的订单'), data: responseData, }; } catch (error) { diff --git a/app/service/systems/pick.js b/app/service/systems/pick.js index 80c48af..794fba6 100644 --- a/app/service/systems/pick.js +++ b/app/service/systems/pick.js @@ -59,9 +59,12 @@ class PickSystemService extends Service { * @param {number} [code=400] 错误码。 * @return {Error} 错误对象。 */ - createBusinessError(message, code = 400) { + 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; } @@ -832,7 +835,7 @@ class PickSystemService extends Service { FROM wms_wave_pick_task t WHERE t.warehouse_id = :warehouseId AND t.pick_user_id = :pickUserId - AND t.status IN (0, 1, 2) + AND t.status IN (0, 1) ORDER BY t.id DESC LIMIT 1 `, { @@ -903,6 +906,32 @@ class PickSystemService extends Service { 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); const taskOrderColumnSet = await this.getTableColumnSet('wms_wave_pick_task_order'); @@ -929,7 +958,8 @@ class PickSystemService extends Service { ctx.model.query(` SELECT pto.order_id, - pto.box_no + pto.box_no, + pto.pick_status FROM wms_wave_pick_task_order pto WHERE pto.task_id = :taskId ${taskOrderWarehouseFilterSql} @@ -955,6 +985,13 @@ class PickSystemService extends Service { ]); 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)) ]; @@ -1004,6 +1041,39 @@ class PickSystemService extends Service { } } + 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: { @@ -1017,6 +1087,29 @@ class PickSystemService extends Service { }) : []; + 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)}` ); @@ -1091,7 +1184,7 @@ class PickSystemService extends Service { boxMapByNo, }); - return { + const result = { task: { task_id: Number(taskRow.task_id || 0), task_no: String(taskRow.task_no || '').trim(), @@ -1100,7 +1193,14 @@ class PickSystemService extends Service { 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), @@ -1111,10 +1211,1245 @@ class PickSystemService extends Service { required_qty: Number(row && row.required_qty || 0), picked_qty: Number(row && row.picked_qty || 0), })), - picking_details: pickingDetails, picking_summary: pickingSummary, picking_view: pickingView, }; + + // 团购小波次不需要返回拣货明细,减少带宽浪费 + if (pickMode !== 1) { + 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 + 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); + } + + 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, 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); + } + + 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); + } + } + + 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, + }); + + const progress = await this.getTaskPickProgress(taskId, warehouseId, transaction); + if (mode === 1 || progress.isCompleted) { + 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, + }, + 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(); + return { + task_id: taskId, + mode, + confirmed_order_ids: targetOrderIds, + is_completed: progress.isCompleted, + progress: { + total_orders: progress.totalOrders, + picked_orders: progress.pickedOrders, + pending_orders: progress.pendingOrders, + }, + }; + } catch (error) { + await transaction.rollback(); + throw error; + } + } + + /** + * 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 previousCartId = Number(taskRow && taskRow.current_cart_id || 0); + const bindType = previousCartId > 0 && previousCartId !== targetCartId ? 2 : 1; + + const transaction = await ctx.model.transaction(); + try { + const cartActiveBindingRows = await ctx.model.query(` + SELECT + b.id, + b.task_id, + t.task_no, + t.status AS task_status + 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 activeBinding = Array.isArray(cartActiveBindingRows) && cartActiveBindingRows.length > 0 + ? cartActiveBindingRows[0] + : null; + const bindingTaskId = Number(activeBinding && activeBinding.task_id || 0); + const bindingTaskStatus = Number(activeBinding && activeBinding.task_status || 0); + if (bindingTaskId > 0 && bindingTaskId !== taskId && [ 0, 1, 2 ].includes(bindingTaskStatus)) { + throw this.createBusinessError('该拣货车已绑定其他活动任务,无法重复绑定', 409, { + task_id: bindingTaskId, + task_no: String(activeBinding && activeBinding.task_no || '').trim() || null, + cart_id: targetCartId, + cart_code: targetCartCode, + }); + } + + if (previousCartId > 0 && previousCartId !== targetCartId) { + await ctx.model.query(` + UPDATE wms_pick_cart + SET current_task_id = NULL, + bind_user_id = NULL, + update_time = NOW() + WHERE id = :previousCartId + AND warehouse_id = :warehouseId + AND current_task_id = :taskId + `, { + replacements: { + previousCartId, + warehouseId, + taskId, + }, + transaction, + }); + } + + await ctx.model.query(` + UPDATE wms_pick_task_cart_binding + SET is_active = 0, + unbind_user_id = :operatorId, + unbind_time = NOW(), + update_time = NOW() + WHERE warehouse_id = :warehouseId + AND is_active = 1 + AND (task_id = :taskId OR cart_id = :cartId) + `, { + replacements: { + operatorId, + warehouseId, + taskId, + cartId: targetCartId, + }, + transaction, + }); + + 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, + :bindType, + 1, + NOW(), + NOW(), + NOW() + ) + `, { + replacements: { + taskId, + cartId: targetCartId, + cartCode: targetCartCode, + warehouseId, + operatorId, + bindType, + }, + 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 ctx.model.query(` + UPDATE wms_pick_cart + SET current_task_id = :taskId, + bind_user_id = :operatorId, + last_bind_time = NOW(), + last_seen_time = NOW(), + update_time = NOW() + WHERE id = :cartId + AND warehouse_id = :warehouseId + `, { + replacements: { + taskId, + operatorId, + cartId: targetCartId, + warehouseId, + }, + 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); + } + + await this.assertPickCartCodeUnique(cartCode, warehouseId); + + const insertResult = 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, + }, + }); + + const insertHead = Array.isArray(insertResult) ? insertResult[0] : null; + const insertMeta = Array.isArray(insertResult) ? insertResult[1] : null; + const cartId = Number( + (insertMeta && (insertMeta.insertId || insertMeta.lastID || insertMeta.id)) + || (insertHead && (insertHead.insertId || insertHead.lastID || insertHead.id)) + || 0 + ); + if (!Number.isInteger(cartId) || cartId <= 0) { + throw this.createBusinessError('拣货车创建失败', 500); + } + + 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 && Number(cartRow.current_task_id || 0) > 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 {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, + }, + }; } } diff --git a/app/service/systems/pickCart.js b/app/service/systems/pickCart.js new file mode 100644 index 0000000..cb449e0 --- /dev/null +++ b/app/service/systems/pickCart.js @@ -0,0 +1,88 @@ +'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 查询参数。 + * @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/setting/expressInterface.js b/app/service/systems/setting/expressInterface.js index 291d54b..7cbefae 100644 --- a/app/service/systems/setting/expressInterface.js +++ b/app/service/systems/setting/expressInterface.js @@ -274,6 +274,12 @@ class SettingExpressInterfaceService extends Service { shop_id: { field: 'shop_id', }, + template_id: { + field: 'template_id', + }, + brandno: { + field: 'brandno', + }, sender_name: { field: 'sender_name', }, @@ -724,6 +730,11 @@ class SettingExpressInterfaceService extends Service { 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: row.template_id === undefined || row.template_id === null ? null : Number(row.template_id), + 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), @@ -1048,6 +1059,7 @@ class SettingExpressInterfaceService extends Service { { district_name: { [Op.like]: `%${keyword}%` } }, { site_code: { [Op.like]: `%${keyword}%` } }, { product_type: { [Op.like]: `%${keyword}%` } }, + { brandno: { [Op.like]: `%${keyword}%` } }, { shop_name: { [Op.like]: `%${keyword}%` } }, ], }); @@ -1059,7 +1071,7 @@ class SettingExpressInterfaceService extends Service { }, include: this.getInterfaceInclude(), attributes: [ - 'id', 'name', 'express_code', 'warehouse_id', 'shop_id', 'platform_shop_id', 'platform_code', + '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', @@ -1203,6 +1215,32 @@ class SettingExpressInterfaceService extends Service { allowEmpty: true, min: 1, }), + template_id: this.normalizeInteger(data.template_id !== undefined ? data.template_id : data.templateId, 'template_id', { + allowEmpty: true, + min: 1, + }), + 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', { @@ -1275,6 +1313,16 @@ class SettingExpressInterfaceService extends Service { || 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'); @@ -1304,8 +1352,8 @@ class SettingExpressInterfaceService extends Service { if (!hasName && !hasExpressCode && !hasPlatformCode && !hasSysExpressCode && !hasSenderName && !hasSenderTel && !hasWeight && !hasWeightType - && !hasShopId && !hasPlatformShopId - && !hasViewer && !hasClientId && !hasIsPickup + && !hasShopId && !hasPlatformShopId && !hasTemplateId && !hasPaymode && !hasBrandNo + && !hasProviderType && !hasProviderId && !hasViewer && !hasClientId && !hasIsPickup && !hasShipperNo && !hasTemplateUrl && !hasProvinceName && !hasCityName && !hasDistrictName && !hasAddress && !hasTownName && !hasSiteCode && !hasProductType && !hasShopName && !hasExtData) { @@ -1394,6 +1442,55 @@ class SettingExpressInterfaceService extends Service { ); } + if (hasTemplateId) { + updates.template_id = this.normalizeInteger( + data.template_id !== undefined ? data.template_id : data.templateId, + 'template_id', + { + allowEmpty: true, + min: 1, + } + ); + } + + 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); } diff --git a/app/service/systems/shops.js b/app/service/systems/shops.js index 46fd91c..3aaf497 100644 --- a/app/service/systems/shops.js +++ b/app/service/systems/shops.js @@ -11,6 +11,45 @@ const { * 店铺业务服务。 */ 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); + } + /** * 创建业务错误。 * @@ -362,12 +401,9 @@ class ShopsService extends Service { required: true, maxLength: 100, }); - const shopName = `PENDING_${this.generateAuthorizeRandomCode()}`; - - await this.ensureShopNameUnique({ + const shopName = await this.generatePendingShopName({ warehouseId, platformCode, - shopName, }); const created = await ctx.model.Shop.create({ diff --git a/app/service/systems/stock_store.js b/app/service/systems/stock_store.js index 4275edf..cb809f5 100644 --- a/app/service/systems/stock_store.js +++ b/app/service/systems/stock_store.js @@ -202,7 +202,7 @@ class stockStoreService extends Service { // ⭐ 关键修复:使用 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 对象 }); diff --git a/app/service/systems/store.js b/app/service/systems/store.js index 4e4cc47..dff7cff 100644 --- a/app/service/systems/store.js +++ b/app/service/systems/store.js @@ -650,7 +650,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, }, }); diff --git a/app/service/systems/store_warehouse.js b/app/service/systems/store_warehouse.js index a2b794e..6a02cf0 100644 --- a/app/service/systems/store_warehouse.js +++ b/app/service/systems/store_warehouse.js @@ -2197,6 +2197,7 @@ class SettingStoreWarehouseService extends Service { contact_person: contactPerson || null, contact_phone: contactPhone || null, email, + callback_url: this.normalizeText(data.callback_url || data.callbackUrl, 'callback_url', 500) || null, is_enabled: isEnabled, }; @@ -2511,6 +2512,202 @@ class SettingStoreWarehouseService extends Service { 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.logo_url] 可选,Logo链接。 + * @param {string} [data.domain] 可选,绑定域名。 + * @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字符)。 + * @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, + logo_url: data.logo_url || null, + domain: data.domain || null, + 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, + use_status: 1, + }; + + if (storeRemask !== null) { + relationData.store_remask = storeRemask; + } + 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; + } + } } module.exports = SettingStoreWarehouseService; diff --git a/app_service_systemMethods_index_head.js b/app_service_systemMethods_index_head.js new file mode 100644 index 0000000..d2654f9 Binary files /dev/null and b/app_service_systemMethods_index_head.js differ diff --git a/config/config.default.js b/config/config.default.js index f24da08..7c18215 100644 --- a/config/config.default.js +++ b/config/config.default.js @@ -48,6 +48,10 @@ module.exports = appInfo => { appKey: 23535631, security: 'd0cbd3935e3afa2b42b5dc600c08a795', }; + config.deepseek = { + apiKey: process.env.DEEPSEEK_API_KEY || '', + baseUrl: 'https://api.deepseek.com', + }; config.tencentCloud = { ...tencentCloudConfig, }; diff --git a/database/migrations/20260528100000-drop-platid-from-wms-platform.js b/database/migrations/20260528100000-drop-platid-from-wms-platform.js index 3282184..bdb38f5 100644 --- a/database/migrations/20260528100000-drop-platid-from-wms-platform.js +++ b/database/migrations/20260528100000-drop-platid-from-wms-platform.js @@ -65,4 +65,4 @@ module.exports = { await queryInterface.addColumn(TABLE_NAME, COLUMN_NAME, buildPlatidColumn(Sequelize)); }, -}; \ No newline at end of file +}; 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/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/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/db_query.js b/db_query.js index 73e6c5a..ce2fe7d 100644 --- a/db_query.js +++ b/db_query.js @@ -6,7 +6,7 @@ const config = { database: 'wms', username: 'wms', password: 'dspxmRwRdRbWtbm7', - logging: false + logging: false, }; const sequelize = new Sequelize(config.database, config.username, config.password, config); @@ -15,25 +15,25 @@ async function run() { try { const results = {}; - const [dyxdCountResult] = await sequelize.query("SELECT COUNT(*) as count FROM wms_platform WHERE code='DYXD'"); + const [ dyxdCountResult ] = await sequelize.query("SELECT COUNT(*) as count FROM wms_platform WHERE code='DYXD'"); results.dyxdCount = dyxdCountResult[0].count; - const [dyCountResult] = await sequelize.query("SELECT COUNT(*) as count FROM wms_platform WHERE code='DY'"); + const [ dyCountResult ] = await sequelize.query("SELECT COUNT(*) as count FROM wms_platform WHERE code='DY'"); results.dyCount = dyCountResult[0].count; - const [dyRowResult] = await sequelize.query("SELECT * FROM wms_platform WHERE code='DY' LIMIT 1"); + const [ dyRowResult ] = await sequelize.query("SELECT * FROM wms_platform WHERE code='DY' LIMIT 1"); results.dyRow = dyRowResult[0] || null; // The user asked for "metaExists (SequelizeMeta 是否存在该 migration 记录)" // Based on previous terminal logs, the migration file name or pattern seems to be related to "platform_code" or "wms_platform" - const [metaResult] = await sequelize.query("SELECT * FROM SequelizeMeta"); + const [ metaResult ] = await sequelize.query('SELECT * FROM SequelizeMeta'); const migrationName = '20250303080004-platform_code.js'; // This is an assumption based on common naming. // Let's search for any record that contains 'platform' in the name. const exists = metaResult.some(m => m.name.includes('platform')); results.metaExists = exists; try { - const [expressTotalResult] = await sequelize.query("SELECT COUNT(*) as count FROM wms_express"); + const [ expressTotalResult ] = await sequelize.query('SELECT COUNT(*) as count FROM wms_express'); results.expressTotal = expressTotalResult[0].count; } catch (e) {} diff --git a/methods/changes/openapi.json b/methods/changes/openapi.json index fa168c3..e772399 100644 --- a/methods/changes/openapi.json +++ b/methods/changes/openapi.json @@ -1,63 +1,271 @@ [ - { - "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-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" + } ] diff --git a/methods/changes/system.json b/methods/changes/system.json index ec9436d..75edba2 100644 --- a/methods/changes/system.json +++ b/methods/changes/system.json @@ -2496,5 +2496,354 @@ ], "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" } ] diff --git a/methods/openapi.json b/methods/openapi.json index b424c12..c944d3e 100644 --- a/methods/openapi.json +++ b/methods/openapi.json @@ -1,160 +1,1463 @@ { "module": "openapi", "description": "开放 API 统一入口,独立链路,HTTP POST /openapi,记录入口校验/鉴权规则与返回格式。", - "version": "2026.04.26-openapi-04", - "updatedAt": "2026-04-26", + "version": "2026.06.05-openapi-15", + "updatedAt": "2026-06-05", "http": { "path": "/openapi", "method": "POST" }, "headers": [], - "endpoints": [ - { - "method": "openapi.index", - "description": "开放 API 统一入口,接收 POST /openapi;完成 JSON body 解析、app_key 校验与签名校验,返回统一响应(与系统 style 的 code/message/data 保持一致)。", - "isNeedAuth": false, - "isNeedLogin": false, - "headers": [], - "params": [ - { - "name": "method", - "type": "string", - "required": true, - "source": "query", - "description": "目标系统方法名,必填(例如 order.list)" - }, - { - "name": "v", - "type": "string", - "required": true, - "source": "query", - "description": "API 版本号" - }, - { - "name": "timestamp", - "type": "number", - "required": true, - "source": "query", - "description": "时间戳(数字)" - }, - { - "name": "app_key", - "type": "string", - "required": true, - "source": "query", - "description": "开放平台分配的 app_key;兼容别名 appkey 与 self_app_key(任一存在即可)" - }, - { - "name": "sign", - "type": "string", - "required": true, - "source": "query", - "description": "签名字段,兼容别名 signature(MD5 小写 hex)" - } - ], - "requestBody": [ - { - "name": "body", - "type": "object", - "required": true, - "source": "body", - "description": "请求体必须为 JSON;入口优先读取 rawBody,空体或非 JSON 返回 400,错误文案为 'json数据为空' 或 'json数据解析错误'。" - } - ], - "response": [ - { - "name": "code", - "type": "number", - "required": true, - "description": "业务码:成功通常为 1" - }, - { - "name": "message", - "type": "string", - "required": true, - "description": "提示消息" - }, - { - "name": "data", - "type": "object", - "required": false, - "description": "接口返回数据" - }, - { - "name": "timestamp", - "type": "number", - "required": true, - "description": "响应时间戳" - } - ], - "errors": [ - { - "code": 400, - "message": "参数缺失或错误: method/v/timestamp 或 app_key" - }, - { - "code": 400, - "message": "json数据为空" - }, - { - "code": 400, - "message": "json数据解析错误" - }, - { - "code": 401, - "message": "app_key 无效或不可用" - }, - { - "code": 401, - "message": "签名校验失败" - }, - { - "code": 500, - "message": "接口错误: " - } - ], - "notes": [ - "独立链路:/openapi 为独立入口,不依附于 system/qimen,不复用系统的请求头强校验或鉴权链。", - "不校验 platform/project 等请求头:openapi 不对 platform/project 请求头做强制校验或拒绝,headers 字段为空。", - "body 使用 JSON 解析:content-type 应包含 application/json;优先读取 ctx.request.rawBody,若未提供则回退到 ctx.request.body 或原始请求流;空体或解析失败返回 400(错误消息为 'json数据为空' 或 'json数据解析错误')。", - "app_key 校验:通过数据库表 wms_api_app(或对应模型)按 self_app_key/app_key 查询,要求 is_enabled=1 且 interface_type_id=2(OPEN_API 类型)才视为有效,否则返回 401(消息 'app_key 无效或不可用')。", - "签名规则:构建 canonicalQuery(取 query 参数,支持别名 app_key/appkey/self_app_key,签名字段支持 sign/signature;排除签名字段本身),按 key 的字母序排序并用 & 连接 key=value;计算 bodySign 为 md5(稳定序列化(body));将 canonicalQuery + self_app_secret + bodySign 连接成字符串并对该字符串计算 md5(小写 hex),结果与请求中 sign/signature 比对,匹配即通过。", - "method 分发:openapi 的 method 分发走 openapiMethods 专用目录(代码内实现独立路由/分发);已存在方法示例:index.ping(模块=基础模块)。", - "返回风格:成功与失败返回使用与系统一致的 code/message/data 格式(无需额外 flag 字段),以保证与系统端点兼容。" - ] - }, - { - "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" - ] - } - ] + "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 模块 取消发货单接口,支持直接取消未拣货/未打印的订单;已拣货或已打印的订单改为拦截状态", + "isNeedAuth": false, + "isNeedLogin": false, + "headers": [], + "params": [ + { + "name": "orderCode", + "type": "string", + "required": true, + "source": "body", + "description": "发货单编码(必填),要取消的订单号" + }, + { + "name": "orderType", + "type": "string", + "required": false, + "source": "body", + "description": "订单类型,默认 JYCK(一般交易出库单);当前支持 JYCK(一般交易出库)、HHCK(换货出库)、BFCK(补发出库)" + } + ], + "requestBody": [ + { + "name": "orderCode", + "type": "string", + "required": true, + "source": "body", + "description": "发货单编码(必填),要取消的订单号" + }, + { + "name": "orderType", + "type": "string", + "required": false, + "source": "body", + "description": "订单类型,默认 JYCK(一般交易出库单);当前支持 JYCK(一般交易出库)、HHCK(换货出库)、BFCK(补发出库)" + } + ], + "response": [ + { + "name": "code", + "type": "number", + "required": true, + "description": "业务码:1=成功,0=失败" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "提示消息" + }, + { + "name": "data", + "type": "object", + "required": false, + "description": "取消成功时可能包含订单状态信息" + } + ], + "errors": [ + { + "code": 400, + "message": "订单号不能为空" + }, + { + "code": 400, + "message": "暂不支持该订单类型的取消操作" + }, + { + "code": 404, + "message": "未找到对应的订单" + }, + { + "code": 409, + "message": "取消失败,已通知拦截执行(订单已拣货或已打印,改为拦截状态)" + } + ], + "notes": [ + "模块:order 模块", + "方法部署位置:openapiMethods/order.cancel", + "取消逻辑:未拣货且未打印的订单直接取消(status=cancel, outbound_status=fin, step=4);已拣货或已打印的订单标记为拦截状态(intercept_status=intercepting),不直接取消", + "订单类型映射:JYCK/HHCK/BFCK → 出库单取消;其他类型暂不支持", + "使用事务 + 行锁保证并发安全", + "取消操作为不可逆操作,请谨慎调用", + "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": "毛重(kg)" + }, + { + "name": "item.netWeight", + "type": "number", + "required": false, + "source": "body", + "description": "净重(kg)" + }, + { + "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" + ] + } + ] + } + ] + } } diff --git a/methods/system.json b/methods/system.json index 37a0995..5170308 100644 --- a/methods/system.json +++ b/methods/system.json @@ -1,8 +1,8 @@ { "module": "system", "description": "系统接口标准入口,method 对应系统内置方法,全部使用 POST 请求,参数统一放在 body 内", - "version": "0.0.5", - "updatedAt": "2026-05-30", + "version": "0.4.0", + "updatedAt": "2026-06-05", "headers": [ { "name": "platform", @@ -1568,16 +1568,22 @@ "type": "object", "required": true, "description": "分页信息(page、pageSize、total、totalPages、hasPrevious、hasNext)" + }, + { + "name": "recheck_status", + "type": "string", + "required": false, + "description": "复核状态:none=未复核,fin=已复核" } ], "errors": [ { "code": "400", - "description": "缺少仓库上下文或 where 参数格式错误" + "message": "缺少仓库上下文或 where 参数格式错误" }, { "code": "500", - "description": "查询失败" + "message": "查询失败" } ] }, @@ -2364,16 +2370,22 @@ "type": "object", "required": true, "description": "分页信息" + }, + { + "name": "recheck_status", + "type": "string", + "required": false, + "description": "复核状态:none=未复核,fin=已复核" } ], "errors": [ { "code": "400", - "description": "参数格式错误或缺少仓库上下文" + "message": "参数格式错误或缺少仓库上下文" }, { "code": "500", - "description": "查询失败" + "message": "查询失败" } ] }, @@ -2522,7 +2534,7 @@ ] }, { - "groupName": "待处理订单模块", + "groupName": "订单待处理模块", "module": "order.pendingOrder", "list": [ { @@ -2573,16 +2585,22 @@ "type": "object", "required": true, "description": "分页信息" + }, + { + "name": "recheck_status", + "type": "string", + "required": false, + "description": "复核状态:none=未复核,fin=已复核" } ], "errors": [ { "code": "400", - "description": "参数格式错误或缺少仓库上下文" + "message": "参数格式错误或缺少仓库上下文" }, { "code": "500", - "description": "查询失败" + "message": "查询失败" } ] }, @@ -3084,7 +3102,7 @@ }, { "method": "order.pendingOrder.syncOrderIds", - "description": "同步待处理订单入口,仅接收 order_ids 并转发到服务层,当前不做业务处理。", + "description": "同步待处理订单入口,支持批量传入 order_ids。服务端会按 create_channel 分组派发同步任务;若命中 SN 管理订单(is_sn_mgmt=Y),该订单会被拦截并标记失败,不允许走批量回传,需改用单订单回传。", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -3101,7 +3119,7 @@ "type": "array|string|number", "required": true, "source": "body", - "description": "订单 ID 列表,支持数组、逗号分隔字符串或单个 ID。当前仅透传到服务层,不做额外处理。" + "description": "订单 ID 列表,支持数组、逗号分隔字符串或单个 ID。服务端会校验订单状态并执行批量同步拦截规则(含 SN 订单限制)。" } ], "response": [ @@ -3135,6 +3153,10 @@ "code": 400, "message": "order_ids 不能为空或格式错误" }, + { + "code": 400, + "message": "SN订单不支持批量回传,请改用单订单回传" + }, { "code": 500, "message": "内部错误:服务层同步失败" @@ -3509,23 +3531,23 @@ { "name": "province", "type": "string", - "required": false, + "required": true, "source": "body", - "description": "省份" + "description": "省份(必填,空值返回 400)" }, { "name": "city", "type": "string", - "required": false, + "required": true, "source": "body", - "description": "城市" + "description": "城市(必填,空值返回 400)" }, { "name": "area", "type": "string", - "required": false, + "required": true, "source": "body", - "description": "区/县" + "description": "区/县(必填,空值返回 400)" }, { "name": "town", @@ -3546,7 +3568,7 @@ "type": "array", "required": true, "source": "body", - "description": "订单明细数组,每项含 item_code(商品编码)和 plan_qty(计划数量,正整数);item_name、order_line_no、actual_price 为可选" + "description": "订单明细数组,每项含 item_id(商品主键,必填,正整数)和 plan_qty(计划数量,正整数);item_name(优先外部传入,其次从 StockStore 缓存获取,最后兜底'商品')、order_line_no、actual_price 为可选" }, { "name": "delivery_order_code", @@ -3652,18 +3674,23 @@ ], "errors": [ { - "code": "400", - "description": "必填字段缺失、items 格式错误或 delivery_order_code 重复" + "code": 400, + "message": "必填字段缺失(含 province/city/area)、items 格式错误(item_id 须为正整数)或 delivery_order_code 重复" }, { - "code": "404", - "description": "货主与仓库无有效合约关系(getContractConfig 返回 null 时降级为需审核)" + "code": 404, + "message": "货主与仓库无有效合约关系(getContractConfig 返回 null 时降级为需审核)" } + ], + "notes": [ + "使用 item_id 直接匹配商品主键,不依赖外部系统商品同步;item_id 可通过 singleitem.synchronize 返回的 itemId 获取", + "province/city/area 为必填项,空值返回 400" ] }, { "method": "order.pendingOrder.downloadCreateTemplate", - "description": "下载创建订单的 Excel 导入模板。返回 base64 编码的 xlsx 文件,前端解码后作为附件下载。表头中标注 * 的列为必填项,多行相同订单号的行组成一个完整订单。", + "description": "下载创建订单的 Excel 导入模板。返回 base64 编码的 xlsx 文件,前端解码后作为附件下载。表头中标注 * 的列为必填项,多行相同订单号的行组成一个完整订单。(已作废)", + "status": "deprecated", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -3699,7 +3726,8 @@ }, { "method": "order.pendingOrder.importOrdersFromExcel", - "description": "通过 Excel 文件批量创建订单。接受 base64 编码的 xlsx 内容,按订单号分组,每组创建一个订单(step 由货主策略决定)。每行代表一条商品明细;同一订单号的多行组成一个完整订单,头信息取每组第一行。", + "description": "通过 Excel 文件批量创建订单。接受 base64 编码的 xlsx 内容,按订单号分组,每组创建一个订单(step 由货主策略决定)。每行代表一条商品明细;同一订单号的多行组成一个完整订单,头信息取每组第一行。(已作废)", + "status": "deprecated", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -3754,9 +3782,104 @@ "errors": [ { "code": "400", - "description": "file_base64 为空、Excel 格式无效或无有效数据行" + "message": "file_base64 为空、Excel 格式无效或无有效数据行" } ] + }, + { + "method": "order.pendingOrder.parseAddress", + "description": "智能地址解析:使用 AI 将非结构化地址字符串解析为省/市/区/详细地址/收件人/手机号", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [], + "params": [ + { + "name": "address", + "type": "string", + "required": true, + "source": "body", + "description": "原始地址字符串(必填),如\"张三 13800138000 广东省广州市天河区体育西路100号\"" + } + ], + "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" + } + ], + "errors": [ + { + "code": 400, + "message": "地址字符串不能为空" + }, + { + "code": 500, + "message": "地址解析失败(AI服务异常或密钥未配置)" + } + ], + "notes": [ + "方法部署位置:systemMethods/order/pendingOrder/parseAddress", + "使用 DeepSeek AI 模型进行智能解析", + "解析结果可直接回填到 createOrder 的收件人信息字段", + "未识别到的字段返回空字符串" + ] } ] }, @@ -4013,6 +4136,13 @@ "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": [ @@ -4156,6 +4286,80 @@ "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": "储位分配状态" + } + ] + } + ] } ] }, @@ -4334,6 +4538,13 @@ "required": false, "source": "body", "description": "允许的快递编码列表(可选,支持数组/JSON/逗号分隔);系统会校验所传编码是否在可用快递列表内,非法值将导致 400 错误。" + }, + { + "name": "wave_prefix", + "type": "string", + "required": false, + "source": "body", + "description": "波次编号前缀(可选),最多 5 个字符,如 D、B、A;不传则保持原值" } ], "response": [ @@ -4353,11 +4564,11 @@ "errors": [ { "code": "400", - "description": "缺少必填参数或参数校验失败(包括 allowed_owners/allowed_expresses 非法)" + "message": "缺少必填参数或参数校验失败(包括 allowed_owners/allowed_expresses 非法)" }, { "code": "500", - "description": "创建失败或内部错误" + "message": "创建失败或内部错误" } ] }, @@ -4521,6 +4732,13 @@ "required": false, "source": "body", "description": "允许的快递编码列表(可选,支持数组/JSON/逗号分隔);系统会校验所传编码是否在可用快递列表内,非法值将导致 400 错误。" + }, + { + "name": "wave_prefix", + "type": "string", + "required": false, + "source": "body", + "description": "波次编号前缀(可选),最多 5 个字符,如 D、B、A;不传则保持原值" } ], "response": [ @@ -4540,15 +4758,15 @@ "errors": [ { "code": "400", - "description": "缺少 id 或无可更新字段或参数校验失败" + "message": "缺少 id 或无可更新字段或参数校验失败" }, { "code": "404", - "description": "波次策略不存在" + "message": "波次策略不存在" }, { "code": "500", - "description": "更新失败或内部错误" + "message": "更新失败或内部错误" } ] }, @@ -7128,16 +7346,22 @@ "type": "object", "required": true, "description": "分页信息" + }, + { + "name": "recheck_status", + "type": "string", + "required": false, + "description": "复核状态:none=未复核,fin=已复核" } ], "errors": [ { "code": "400", - "description": "参数格式错误或缺少仓库上下文" + "message": "参数格式错误或缺少仓库上下文" }, { "code": "500", - "description": "查询失败" + "message": "查询失败" } ] }, @@ -7370,16 +7594,22 @@ "type": "object", "required": true, "description": "分页信息" + }, + { + "name": "recheck_status", + "type": "string", + "required": false, + "description": "复核状态:none=未复核,fin=已复核" } ], "errors": [ { "code": "400", - "description": "参数格式错误或缺少仓库上下文" + "message": "参数格式错误或缺少仓库上下文" }, { "code": "500", - "description": "查询失败" + "message": "查询失败" } ] }, @@ -7555,16 +7785,22 @@ "type": "object", "required": true, "description": "分页信息" + }, + { + "name": "recheck_status", + "type": "string", + "required": false, + "description": "复核状态:none=未复核,fin=已复核" } ], "errors": [ { "code": "400", - "description": "参数格式错误或缺少仓库上下文" + "message": "参数格式错误或缺少仓库上下文" }, { "code": "500", - "description": "查询失败" + "message": "查询失败" } ] }, @@ -7693,16 +7929,22 @@ "type": "object", "required": true, "description": "分页信息" + }, + { + "name": "recheck_status", + "type": "string", + "required": false, + "description": "复核状态:none=未复核,fin=已复核" } ], "errors": [ { "code": "400", - "description": "参数格式错误或缺少仓库上下文" + "message": "参数格式错误或缺少仓库上下文" }, { "code": "500", - "description": "查询失败" + "message": "查询失败" } ] }, @@ -7831,16 +8073,22 @@ "type": "object", "required": true, "description": "分页信息" + }, + { + "name": "recheck_status", + "type": "string", + "required": false, + "description": "复核状态:none=未复核,fin=已复核" } ], "errors": [ { "code": "400", - "description": "参数格式错误或缺少仓库上下文" + "message": "参数格式错误或缺少仓库上下文" }, { "code": "500", - "description": "查询失败" + "message": "查询失败" } ] }, @@ -7969,16 +8217,22 @@ "type": "object", "required": true, "description": "分页信息" + }, + { + "name": "recheck_status", + "type": "string", + "required": false, + "description": "复核状态:none=未复核,fin=已复核" } ], "errors": [ { "code": "400", - "description": "参数格式错误或缺少仓库上下文" + "message": "参数格式错误或缺少仓库上下文" }, { "code": "500", - "description": "查询失败" + "message": "查询失败" } ] }, @@ -10298,12 +10552,115 @@ "list": [ { "method": "index.getPlatformList", - "description": "合并后的平台列表", + "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, - "params": [], - "response": [], - "errors": [] + "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", @@ -11082,6 +11439,13 @@ "required": false, "source": "body", "description": "店铺 ID(支持 shopId),正整数,可空;未传或空值按 null 处理" + }, + { + "name": "address", + "type": "string", + "required": false, + "source": "body", + "description": "发件人详细地址(可选),使用 index.getShopExpressList 返回的 detail 字段值,非 full_address" } ], "response": [ @@ -11121,6 +11485,13 @@ "required": false, "source": "body", "description": "shop_id" + }, + { + "name": "address", + "type": "string", + "required": false, + "source": "body", + "description": "发件人详细地址(可选),使用 index.getShopExpressList 返回的 detail 字段值,非 full_address" } ], "response": [ @@ -13205,7 +13576,7 @@ "list": [ { "method": "pick.query", - "description": "按订单查询波次拣货信息,支持 full/full_display/is_full 控制是否完整显示;接口按当前登录用户仓库上下文过滤,防止跨仓越界。", + "description": "按 keyword(运单号或波次号)获取或创建当前用户的拣货任务:命中同用户活动任务返回 existing;无活动任务则创建并返回 created;若活动任务归属他人则返回冲突提示。", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -13218,102 +13589,59 @@ ], "params": [ { - "name": "waybill_code", + "name": "keyword", "type": "string", "required": true, "source": "body", - "description": "快递号/运单号,必填。" - }, - { - "name": "full_display", - "type": "boolean", - "required": false, - "source": "body", - "description": "是否完整显示拣货明细;默认 false。true 返回全部拣货明细,false 仅返回未完成的(inspection_status != 'fin')。" + "description": "关键字,支持运单号或波次号。" } ], "response": [ { - "name": "order_id", - "type": "string|number", - "description": "订单 ID" - }, - { - "name": "wave_id", + "name": "task_id", "type": "number", - "description": "波次 ID(若订单未关联波次则为空)" + "required": true, + "description": "拣货任务ID。" }, { - "name": "wave_no", + "name": "status", "type": "string", - "description": "波次编号(若订单未关联波次则为空)" + "required": true, + "description": "任务状态:existing(命中当前用户已有活动任务)或 created(新建成功)。" }, { - "name": "full_display", - "type": "boolean", - "description": "是否以完整明细展示(等同于请求中的 full/full_display/is_full)" - }, - { - "name": "summary", - "type": "object", - "description": "汇总信息", - "children": [ - { - "name": "total_count", - "type": "number", - "description": "明细总行数" - }, - { - "name": "pending_review_count", - "type": "number", - "description": "待复核行数" - }, - { - "name": "reviewed_count", - "type": "number", - "description": "已复核行数" - }, - { - "name": "quantity_total", - "type": "number", - "description": "明细总件数" - }, - { - "name": "display_count", - "type": "number", - "description": "展示行数(受 full 参数影响)" - }, - { - "name": "display_quantity_total", - "type": "number", - "description": "展示的总件数(受 full 参数影响)" - } - ] - }, - { - "name": "list", - "type": "array", - "description": "拣货明细列表(根据 full 参数返回全量或仅未复核明细),每项为明细对象,字段视实现而定。" + "name": "tip", + "type": "string", + "required": true, + "description": "提示文案。" } ], "errors": [ { - "code": "400", - "description": "order_id 为空或订单无波次号" + "code": 400, + "message": "参数错误或目标波次不满足建任务条件(如 keyword 为空、缺少仓库上下文、目标波次信息不完整、散单波次无可用订单)。" }, { - "code": "404", - "description": "订单不存在" + "code": 401, + "message": "未获取到操作人上下文。" }, { - "code": "500", - "description": "内部错误" + "code": 404, + "message": "关键字未命中有效运单/波次,或命中的订单/波次不属于当前仓库。" + }, + { + "code": 409, + "message": "目标波次已存在他人创建的活动任务(失败 data 含 task_id、task_owner_id、task_owner_name)。" + }, + { + "code": 500, + "message": "内部错误(如分表模型不可用或任务创建异常)。" } ] }, { "method": "pick.wavePickTaskDetail", - "description": "按任务ID获取拣货任务详情,返回精简的 task、boxes、picking_details 与 picking_summary;仅允许任务的 pick_user_id 与当前登录用户(operator_id/employees_id)一致时返回数据,否则返回 403。", + "description": "按任务ID获取拣货任务详情。查询前会校验任务内订单是否全部完成快递号与储位分配:若存在未分配快递号或未分配储位订单,将返回 400 并在 data 中返回 action 与 order_ids 供前端触发一键分配;详情响应新增中间态进度语义(task.is_completed、task.progress 与顶层 is_completed),用于前端判断是否已完成与展示阶段进度;仅允许任务的 pick_user_id 与当前登录用户一致时返回详情。当 pick_mode=1(团购小波次)时,picking_details 字段不返回以减少带宽。", "isNeedAuth": false, "isNeedLogin": true, "isNeedRight": false, @@ -13343,39 +13671,85 @@ { "name": "task_id", "type": "number", - "description": "任务ID" + "description": "任务ID", + "required": false }, { "name": "task_no", "type": "string", - "description": "任务编号" + "description": "任务编号", + "required": false }, { "name": "status", "type": "number", - "description": "任务状态" + "description": "任务状态", + "required": false }, { "name": "pick_mode", "type": "number", - "description": "拣货模式" + "description": "拣货模式", + "required": false }, { "name": "start_at", "type": "string", - "description": "开始时间(ISO 字符串或 null)" + "description": "开始时间(ISO 字符串或 null)", + "required": false }, { "name": "finish_at", "type": "string", - "description": "完成时间(ISO 字符串或 null)" + "description": "完成时间(ISO 字符串或 null)", + "required": false }, { "name": "batch_no", "type": "string", - "description": "批次号" + "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", @@ -13385,79 +13759,94 @@ { "name": "task_id", "type": "number", - "description": "任务ID" + "description": "任务ID", + "required": false }, { "name": "box_id", "type": "number", - "description": "箱ID" + "description": "箱ID", + "required": false }, { "name": "box_no", "type": "string", - "description": "箱编码" + "description": "箱编码", + "required": false }, { "name": "box_type", "type": "number", - "description": "箱类型" + "description": "箱类型", + "required": false }, { "name": "status", "type": "number", - "description": "箱状态" + "description": "箱状态", + "required": false }, { "name": "ref_label", "type": "string", - "description": "箱参考标签或关联业务标识(用于前端定位/关联)" + "description": "箱参考标签或关联业务标识(用于前端定位/关联)", + "required": false }, { "name": "required_qty", "type": "number", - "description": "箱内需要拣货的总数量" + "description": "箱内需要拣货的总数量", + "required": false }, { "name": "picked_qty", "type": "number", - "description": "当前已完成拣货的数量" + "description": "当前已完成拣货的数量", + "required": false } - ] + ], + "required": false }, { "name": "picking_details", "type": "array", - "description": "拣货明细列表(按库位/商品/数量拆分),用于从明细视角展示拣货要求", + "description": "拣货明细列表(按库位/商品/数量拆分),用于从明细视角展示拣货要求。注意:当 pick_mode=1(团购小波次)时该字段不返回,减少带宽浪费;其他 pick_mode(2/3/4/5)正常返回。", "children": [ { "name": "order_id", "type": "number", - "description": "订单ID" + "description": "订单ID", + "required": false }, { "name": "order_item_id", "type": "number", - "description": "订单行ID" + "description": "订单行ID", + "required": false }, { "name": "quantity", "type": "number", - "description": "本行需拣货数量" + "description": "本行需拣货数量", + "required": false }, { "name": "storage_id", "type": "number", - "description": "仓库ID" + "description": "仓库ID", + "required": false }, { "name": "space_id", "type": "number", - "description": "库位ID" + "description": "库位ID", + "required": false }, { "name": "space_name", "type": "string", - "description": "库位名称" + "description": "库位名称", + "required": false }, { "name": "location_space", @@ -13467,56 +13856,68 @@ { "name": "space_code", "type": "string", - "description": "库位编码" + "description": "库位编码", + "required": false }, { "name": "custom_name", "type": "string", - "description": "库位自定义名称" + "description": "库位自定义名称", + "required": false }, { "name": "custom_barcode", "type": "string", - "description": "库位自定义条码" + "description": "库位自定义条码", + "required": false }, { "name": "pick_sequence", "type": "number", - "description": "拣货序列,用于路线/优先级排序" + "description": "拣货序列,用于路线/优先级排序", + "required": false }, { "name": "pick_priority", "type": "number", - "description": "拣货优先级(数值越小优先级越高)" + "description": "拣货优先级(数值越小优先级越高)", + "required": false } - ] + ], + "required": false }, { "name": "item_code", "type": "string", - "description": "商品编码" + "description": "商品编码", + "required": false }, { "name": "item_name", "type": "string", - "description": "商品名称" + "description": "商品名称", + "required": false }, { "name": "stock_id", "type": "number", - "description": "库存记录ID(stock 主键)" + "description": "库存记录ID(stock 主键)", + "required": false }, { "name": "plan_qty", "type": "number", - "description": "计划拣货数量(用于与实际拣货对比)" + "description": "计划拣货数量(用于与实际拣货对比)", + "required": false }, { "name": "item_snapshot", "type": "object", - "description": "商品快照(下单时的商品信息,可能包含规格/属性等)" + "description": "商品快照(下单时的商品信息,可能包含规格/属性等)", + "required": false } - ] + ], + "required": false }, { "name": "picking_summary", @@ -13526,24 +13927,29 @@ { "name": "total_lines", "type": "number", - "description": "明细行数(picking_details.length)" + "description": "明细行数(picking_details.length)", + "required": false }, { "name": "total_qty", "type": "number", - "description": "明细总数量(quantity 汇总)" + "description": "明细总数量(quantity 汇总)", + "required": false }, { "name": "distinct_spaces", "type": "number", - "description": "涉及的不同库位数量" + "description": "涉及的不同库位数量", + "required": false }, { "name": "distinct_items", "type": "number", - "description": "涉及的不同商品数量" + "description": "涉及的不同商品数量", + "required": false } - ] + ], + "required": false }, { "name": "picking_view", @@ -13553,27 +13959,32 @@ { "name": "mode_code", "type": "number", - "description": "拣货视图模式编码,与 task.pick_mode 对应" + "description": "拣货视图模式编码,与 task.pick_mode 对应", + "required": false }, { "name": "mode_name", "type": "string", - "description": "拣货视图模式名称" + "description": "拣货视图模式名称", + "required": false }, { "name": "require_box_allocations", "type": "boolean", - "description": "当前模式是否需要箱分配;pick_mode=1/3/4 时为 true,pick_mode=2/5 时为 false" + "description": "当前模式是否需要箱分配;pick_mode=1/3/4 时为 true,pick_mode=2/5 时为 false", + "required": false }, { "name": "group_by", "type": "string", - "description": "分组字段,示例值:\"space+item\"" + "description": "分组字段,示例值:\"space+item\"", + "required": false }, { "name": "sort_by", "type": "array", - "description": "排序字段数组,典型为 [\"pick_sequence\",\"pick_priority\",\"space_id\",\"item_code\"]" + "description": "排序字段数组,典型为 [\"pick_sequence\",\"pick_priority\",\"space_id\",\"item_code\"]", + "required": false }, { "name": "items", @@ -13583,12 +13994,14 @@ { "name": "space_id", "type": "number", - "description": "库位 ID" + "description": "库位 ID", + "required": false }, { "name": "space_name", "type": "string", - "description": "库位名称" + "description": "库位名称", + "required": false }, { "name": "location_space", @@ -13598,49 +14011,59 @@ { "name": "space_code", "type": "string", - "description": "库位编码" + "description": "库位编码", + "required": false }, { "name": "custom_name", "type": "string", - "description": "库位自定义名称" + "description": "库位自定义名称", + "required": false }, { "name": "custom_barcode", "type": "string", - "description": "库位自定义条码" + "description": "库位自定义条码", + "required": false }, { "name": "pick_sequence", "type": "number", - "description": "拣货序列,用于路线/优先级排序" + "description": "拣货序列,用于路线/优先级排序", + "required": false }, { "name": "pick_priority", "type": "number", - "description": "拣货优先级(数值越小优先)" + "description": "拣货优先级(数值越小优先)", + "required": false } - ] + ], + "required": false }, { "name": "item_code", "type": "string", - "description": "商品编码" + "description": "商品编码", + "required": false }, { "name": "item_name", "type": "string", - "description": "商品名称" + "description": "商品名称", + "required": false }, { "name": "stock_id", "type": "number", - "description": "库存记录ID(stock 主键)" + "description": "库存记录ID(stock 主键)", + "required": false }, { "name": "total_qty", "type": "number", - "description": "该库位该商品的总需拣货数量" + "description": "该库位该商品的总需拣货数量", + "required": false }, { "name": "box_allocations", @@ -13650,52 +14073,908 @@ { "name": "box_id", "type": "number", - "description": "箱ID" + "description": "箱ID", + "required": false }, { "name": "box_no", "type": "string", - "description": "箱编码" + "description": "箱编码", + "required": false }, { "name": "box_type", "type": "number", - "description": "箱类型" + "description": "箱类型", + "required": false }, { "name": "required_qty", "type": "number", - "description": "该箱分配需要拣货的数量" + "description": "该箱分配需要拣货的数量", + "required": false }, { "name": "picked_qty", "type": "number", - "description": "该箱已完成拣货的数量" + "description": "该箱已完成拣货的数量", + "required": false }, { "name": "allocated_qty", "type": "number", - "description": "该箱已分配的数量(由后端分配)" + "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", - "description": "task_id 缺失或不合法" + "code": 400, + "message": "参数或业务状态不满足提交条件(如 task_id 不合法、缺少仓库上下文、任务已完成/已取消)。" }, { - "code": "403", - "description": "当前操作人与任务创建人不一致,无权查看" + "code": 401, + "message": "未获取到操作人上下文。" }, { - "code": "404", - "description": "拣货任务不存在" + "code": 403, + "message": "当前操作人与任务创建人不一致,无权操作。" + }, + { + "code": 404, + "message": "拣货任务不存在。" + }, + { + "code": 500, + "message": "提交失败。" + } + ] + }, + { + "method": "pick.wavePickTaskComplete", + "description": "完全提交拣货任务。支持 mode=1 全部确认,mode=2 部分确认(需传 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": "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、任务下无可确认订单等)。" + }, + { + "code": 401, + "message": "未获取到操作人上下文。" + }, + { + "code": 403, + "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.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": "校验失败。" } ] } @@ -17465,11 +18744,14 @@ "type": "string", "required": false, "source": "body", - "description": "API 类型入库单回调地址(VARCHAR(500),仅 OPEN_API 类型使用)" + "description": "API 回调通知 URL(可选),最大 500 字符;配置后订单状态变更时将回调通知推送到此地址;兼容别名 callbackUrl" } ], "response": [], - "errors": [] + "errors": [], + "notes": [ + "callback_url:OpenAPI 类型的接口可配置回调地址,订单同步完成/取消等事件将推送到此 URL" + ] }, { "method": "storeWarehouse.store.deleteQimenConfig", @@ -17502,6 +18784,194 @@ ], "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": "logo_url", + "type": "string", + "required": false, + "source": "body", + "description": "Logo 链接" + }, + { + "name": "domain", + "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 字符" + }, + { + "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": [] } ] }, @@ -18507,7 +19977,7 @@ "list": [ { "method": "order.wave.batchList", - "description": "波次列表查询。仅使用当前登录操作者的仓库ID作为查询约束(禁止传入 warehouse_id / warehouseId)。支持通过白名单字段进行过滤(通过 where 对象传入),接口对 wave_status 固定叠加查询状态 0/1,无需客户端传入。列表按订单数量从大到小排序,并附带波次基础信息与分配状态汇总。", + "description": "波次列表查询。仅使用当前登录操作者仓库上下文(禁止传入 warehouse_id/warehouseId)。支持 where 白名单过滤,固定查询 wave_status=0/1;返回波次基础信息及分配状态汇总。支持 only_todo=1 仅返回仍有未复核订单的波次,并返回复核状态汇总(review_assignment_status)与未复核数量(unreviewed_order_count)。", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -18526,12 +19996,19 @@ "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- 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(等值)\n- total_orders_min / total_orders_max(范围)\n- processed_orders_min / processed_orders_max(范围)\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- 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 中说明错误字段与允许取值。" + "description": "筛选白名单字段(object,可选)。仅支持下列字段过滤,且禁止传入 warehouse_id / warehouseId:\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(等值)\n- total_orders_min / total_orders_max(范围)\n- processed_orders_min / processed_orders_max(范围)\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- 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- sync_assignment_status(等值,string,可选,英文枚举,取值:unsynced、partially_synced、synced;语义:按同步状态聚合判断,synced 表示全部 fin,partially_synced 表示部分已同步且不含 error,unsynced 表示全 padding 或包含 error(异常并入未同步集合))。\n- review_assignment_status(等值,string,可选,英文枚举:unreviewed、partially_reviewed、reviewed;分别表示未复核、部分复核、已复核)。" } ], "response": [ @@ -18539,7 +20016,7 @@ "name": "list", "type": "array", "required": true, - "description": "波次列表,包含波次基础信息与状态汇总(order_count / storage_assignment_status / express_assignment_status / print_assignment_status)。每条记录新增字段 source(number):来源标识,0=普通波次(正常后台操作),1=管理后台策略任务,2=PDA策略任务。" + "description": "波次列表,包含波次基础信息与状态汇总(order_count / storage_assignment_status / express_assignment_status / print_assignment_status / sync_assignment_status / review_assignment_status / unreviewed_order_count)。每条记录新增字段 source(number):来源标识,0=普通波次(正常后台操作),1=管理后台策略任务,2=PDA策略任务。" }, { "name": "pagination", diff --git a/scripts/db-query-runner.js b/scripts/db-query-runner.js index 9e43b1d..f69c37b 100644 --- a/scripts/db-query-runner.js +++ b/scripts/db-query-runner.js @@ -5,7 +5,7 @@ const mysql = require('mysql2/promise'); async function main() { const arg = process.argv[2]; if (!arg) { - console.error(JSON.stringify({success:false, error: 'No queries provided as @file or JSON string'})); + console.error(JSON.stringify({ success: false, error: 'No queries provided as @file or JSON string' })); process.exit(2); } let queries; @@ -15,19 +15,19 @@ async function main() { const raw = fs.readFileSync(fp, 'utf8'); queries = JSON.parse(raw); } catch (err) { - console.error(JSON.stringify({success:false, error: 'Failed to read/parse queries file: ' + err.message})); + console.error(JSON.stringify({ success: false, error: 'Failed to read/parse queries file: ' + err.message })); process.exit(2); } } else { try { queries = JSON.parse(arg); } catch (err) { - console.error(JSON.stringify({success:false, error: 'Failed to parse queries JSON: ' + err.message})); + console.error(JSON.stringify({ success: false, error: 'Failed to parse queries JSON: ' + err.message })); process.exit(2); } } if (!Array.isArray(queries)) { - console.error(JSON.stringify({success:false, error: 'Queries must be an array of SQL strings'})); + console.error(JSON.stringify({ success: false, error: 'Queries must be an array of SQL strings' })); process.exit(2); } @@ -35,7 +35,7 @@ async function main() { try { cfgModule = require(path.join(__dirname, '..', 'database', 'config.js')); } catch (err) { - console.error(JSON.stringify({success:false, error: 'Failed to load database/config.js: ' + err.message})); + console.error(JSON.stringify({ success: false, error: 'Failed to load database/config.js: ' + err.message })); process.exit(1); } const cfg = cfgModule && cfgModule.production ? cfgModule.production : cfgModule; @@ -50,14 +50,14 @@ async function main() { try { conn = await mysql.createConnection({ host, port, user, password, database, multipleStatements: true }); } catch (err) { - console.error(JSON.stringify({success:false, error: 'DB connection failed: ' + err.message})); + console.error(JSON.stringify({ success: false, error: 'DB connection failed: ' + err.message })); process.exit(1); } const results = []; for (const q of queries) { try { - const [rows] = await conn.query(q); + const [ rows ] = await conn.query(q); results.push({ query: q, rows }); } catch (err) { results.push({ query: q, error: err && err.message }); @@ -68,6 +68,6 @@ async function main() { } main().catch(err => { - console.error(JSON.stringify({success:false, error: err.message})); + console.error(JSON.stringify({ success: false, error: err.message })); process.exit(1); }); diff --git a/test/app/service/systemMethods/setting/expressInterface.test.js b/test/app/service/systemMethods/setting/expressInterface.test.js index 4710438..5e7ba13 100644 --- a/test/app/service/systemMethods/setting/expressInterface.test.js +++ b/test/app/service/systemMethods/setting/expressInterface.test.js @@ -174,6 +174,9 @@ describe('test/app/service/systemMethods/setting/expressInterface.test.js', () = name: '顺丰接口', express_code: 'SF', platform_code: 'TB', + templateId: 5566, + brandNo: 'BRAND-CREATE', + providerType: 'KDNIAO', sysExpressCode: 'SF', weightType: 2, address: '上海市浦东新区', @@ -192,7 +195,10 @@ describe('test/app/service/systemMethods/setting/expressInterface.test.js', () = id: 11, name: '顺丰接口-更新', token: 'token-2', + templateId: '7788', platformShopId: '8899', + brandno: 'BRAND-UPDATE', + providerType: 'CAINIAO', sys_express_code: 'SF', weight_type: 3, address: '深圳市南山区', @@ -218,6 +224,9 @@ describe('test/app/service/systemMethods/setting/expressInterface.test.js', () = name: '顺丰接口', express_code: 'SF', platform_code: 'TB', + template_id: 5566, + brandno: 'BRAND-CREATE', + providertype: 'KDNIAO', sys_express_code: 'SF', weight_type: 2, address: '上海市浦东新区', @@ -237,7 +246,10 @@ describe('test/app/service/systemMethods/setting/expressInterface.test.js', () = id: 11, name: '顺丰接口-更新', token: 'token-2', + template_id: '7788', platform_shop_id: '8899', + brandno: 'BRAND-UPDATE', + providertype: 'CAINIAO', sys_express_code: 'SF', weight_type: 3, address: '深圳市南山区', diff --git a/test/app/service/systems/setting/expressInterface.test.js b/test/app/service/systems/setting/expressInterface.test.js index f80ccf7..5799133 100644 --- a/test/app/service/systems/setting/expressInterface.test.js +++ b/test/app/service/systems/setting/expressInterface.test.js @@ -56,6 +56,8 @@ function createHarness(options = {}) { express_code: 'SF', platform_code: 'TB', platform_shop_id: 20001, + template_id: 50001, + brandno: 'BRAND-DEFAULT', express_platform_id: 1, weight_type: 2, express: { @@ -148,6 +150,9 @@ function createHarness(options = {}) { warehouse_id: {}, shop_id: {}, platform_shop_id: {}, + template_id: {}, + brandno: {}, + providertype: {}, sender_name: {}, sender_tel: {}, weight: {}, @@ -436,6 +441,9 @@ describe('test/app/service/systems/setting/expressInterface.test.js', () => { sys_express_code: 'SF', platform_code: 'TB', platform_shop_id: 30001, + template_id: 88001, + brandno: 'BRAND-LIST', + providertype: 'KDNIAO', express_platform_id: 1, express: { code: 'SF', @@ -500,6 +508,9 @@ describe('test/app/service/systems/setting/expressInterface.test.js', () => { assert.equal(result.data.list[0].name, '顺丰接口'); assert.equal(result.data.list[0].platform_code, 'TB'); assert.equal(result.data.list[0].platform_shop_id, 30001); + assert.equal(result.data.list[0].template_id, 88001); + assert.equal(result.data.list[0].brandno, 'BRAND-LIST'); + assert.equal(result.data.list[0].providertype, 'KDNIAO'); assert.equal(result.data.list[0].sys_express_code, 'SF'); assert.equal(result.data.list[0].template_url, 'https://example.com/template/list'); assert.equal(result.data.list[0].is_system_express_code, 1); @@ -555,6 +566,9 @@ describe('test/app/service/systems/setting/expressInterface.test.js', () => { id: 20, warehouse_id: 100000, shop_id: 301, + template_id: 1201, + brandno: 'BRAND-YTO', + providertype: 'KDNIAO', sys_express_code: 'SYS-YTO', name: '圆通接口', express_code: 'YTO', @@ -591,6 +605,9 @@ describe('test/app/service/systems/setting/expressInterface.test.js', () => { id: 11, warehouse_id: 100000, sys_express_code: 'SYS-SF', + template_id: 1202, + brandno: 'BRAND-SF', + providertype: 'CAINIAO', name: '顺丰接口', express_code: 'SF', platform_code: 'TB', @@ -608,6 +625,9 @@ describe('test/app/service/systems/setting/expressInterface.test.js', () => { id: 15, warehouse_id: 100000, sys_express_code: 'SYS-ZTO', + template_id: 1203, + brandno: 'BRAND-ZTO', + providertype: 'KDNIAO', name: '中通接口', express_code: 'ZTO', platform_code: 'TB', @@ -641,8 +661,13 @@ describe('test/app/service/systems/setting/expressInterface.test.js', () => { assert.equal(Array.isArray(result.data), true); assert.equal(result.data.length, 3); assert.equal(result.data[0].express_code, 'SF'); + assert.equal(result.data[0].template_id, 1202); + assert.equal(result.data[0].brandno, 'BRAND-SF'); + assert.equal(result.data[0].providertype, 'CAINIAO'); assert.equal(result.data[1].express_code, 'ZTO'); + assert.equal(result.data[1].brandno, 'BRAND-ZTO'); assert.equal(result.data[2].express_code, 'YTO'); + assert.equal(result.data[2].brandno, 'BRAND-YTO'); assert.equal(result.data[2].shop.id, 301); assert.equal(result.data[2].shop.shop_name, '圆通店铺'); assert.equal(result.data[0].weight, 10); @@ -663,6 +688,8 @@ describe('test/app/service/systems/setting/expressInterface.test.js', () => { id: 12, warehouse_id: 100000, shop_id: 302, + template_id: 33002, + brandno: 'BRAND-CACHE-YTO', sys_express_code: 'SYS-YTO', name: '圆通接口', express_code: 'YTO', @@ -699,6 +726,8 @@ describe('test/app/service/systems/setting/expressInterface.test.js', () => { id: 11, warehouse_id: 100000, sys_express_code: 'SYS-SF', + template_id: 33001, + brandno: 'BRAND-CACHE-SF', name: '顺丰接口', express_code: 'SF', platform_code: 'TB', @@ -726,7 +755,10 @@ describe('test/app/service/systems/setting/expressInterface.test.js', () => { assert.equal(Array.isArray(result.data), true); assert.equal(result.data.length, 2); assert.equal(result.data[0].express_code, 'SF'); + assert.equal(result.data[0].template_id, 33001); + assert.equal(result.data[0].brandno, 'BRAND-CACHE-SF'); assert.equal(result.data[1].express_code, 'YTO'); + assert.equal(result.data[1].brandno, 'BRAND-CACHE-YTO'); assert.equal(result.data[1].shop.id, 302); assert.equal(result.data[1].shop.shop_name, '圆通店铺缓存'); assert.equal(result.data[0].express.polyapi_code, 'SF_API'); @@ -781,6 +813,7 @@ describe('test/app/service/systems/setting/expressInterface.test.js', () => { id: 12, warehouse_id: 100000, shop_id: 302, + template_id: 44002, sys_express_code: 'SYS-YTO', name: '圆通接口', express_code: 'YTO', @@ -837,11 +870,14 @@ describe('test/app/service/systems/setting/expressInterface.test.js', () => { is_share: 1, can_use_count: 5, weight_type: 2, + providerType: 'KDNIAO', + brandNo: 'BRAND-CREATE', address: '朝阳区望京', town_name: '望京街道', ispickup: 1, shipperno: 'SNO-001', template_url: 'https://example.com/template/create', + template_id: 889900, extData: { retry: 2, channel: 'polyapi', @@ -852,6 +888,8 @@ describe('test/app/service/systems/setting/expressInterface.test.js', () => { assert.equal(calls.createPayload.express_code, 'JD'); assert.equal(calls.createPayload.sys_express_code, 'JD'); assert.equal(calls.createPayload.platform_code, 'TB'); + assert.equal(calls.createPayload.brandno, 'BRAND-CREATE'); + assert.equal(calls.createPayload.providertype, 'KDNIAO'); assert.equal(calls.printPlatformFindOneCalls.length, 1); assert.deepEqual(calls.printPlatformFindOneCalls[0].where, { platform_code: 'TB', @@ -859,6 +897,8 @@ describe('test/app/service/systems/setting/expressInterface.test.js', () => { assert.equal(result.data.express_code, 'JD'); assert.equal(result.data.sys_express_code, 'JD'); assert.equal(result.data.platform_code, 'TB'); + assert.equal(result.data.brandno, 'BRAND-CREATE'); + assert.equal(result.data.providertype, 'KDNIAO'); assert.equal(result.data.sender_name, '李四'); assert.equal(result.data.weight_type, 2); assert.equal(result.data.address, '朝阳区望京'); @@ -867,6 +907,8 @@ describe('test/app/service/systems/setting/expressInterface.test.js', () => { assert.equal(result.data.shipperno, 'SNO-001'); assert.equal(calls.createPayload.template_url, 'https://example.com/template/create'); assert.equal(result.data.template_url, 'https://example.com/template/create'); + assert.equal(calls.createPayload.template_id, 889900); + assert.equal(result.data.template_id, 889900); assert.deepEqual(calls.createPayload.ext_data, { retry: 2, channel: 'polyapi', @@ -895,6 +937,7 @@ describe('test/app/service/systems/setting/expressInterface.test.js', () => { assert.equal(result.code, 200); assert.equal(calls.createPayload.express_code, 'SF'); assert.equal(calls.createPayload.platform_code, 'TB'); + assert.equal(calls.createPayload.template_id, null); assert.equal(calls.createPayload.weight_type, 1); assert.equal(calls.findOneCalls.some(item => item.where && item.where.express_code === 'SF' && item.where.warehouse_id === 100000), false); }); @@ -928,6 +971,9 @@ describe('test/app/service/systems/setting/expressInterface.test.js', () => { name: '顺丰接口-更新', express_code: 'sf-pdd', platform_code: 'pdd', + templateId: '998877', + brandNo: 'BRAND-UPDATE', + providerType: 'CAINIAO', weight_type: 3, address: '上海市浦东新区', town_name: '张江镇', @@ -944,6 +990,9 @@ describe('test/app/service/systems/setting/expressInterface.test.js', () => { assert.equal(calls.updatePayload.updates.name, '顺丰接口-更新'); assert.equal(calls.updatePayload.updates.express_code, 'SF-PDD'); assert.equal(calls.updatePayload.updates.platform_code, 'PDD'); + assert.equal(calls.updatePayload.updates.template_id, 998877); + assert.equal(calls.updatePayload.updates.brandno, 'BRAND-UPDATE'); + assert.equal(calls.updatePayload.updates.providertype, 'CAINIAO'); assert.equal(calls.printPlatformFindOneCalls.length, 1); assert.deepEqual(calls.printPlatformFindOneCalls[0].where, { platform_code: 'PDD', @@ -959,6 +1008,9 @@ describe('test/app/service/systems/setting/expressInterface.test.js', () => { print_mode: 'thermal', }); assert.equal(result.data.name, '顺丰接口-更新'); + assert.equal(result.data.template_id, 998877); + assert.equal(result.data.brandno, 'BRAND-UPDATE'); + assert.equal(result.data.providertype, 'CAINIAO'); assert.equal(result.data.template_url, 'https://example.com/template/update'); assert.deepEqual(result.data.ext_data, { print_mode: 'thermal', @@ -1012,6 +1064,32 @@ describe('test/app/service/systems/setting/expressInterface.test.js', () => { assert.equal(result.data.platform_shop_id, 20088); }); + it('should normalize empty template_id to null when updating', async () => { + const { ctx, calls } = createHarness(); + const service = new SettingExpressInterfaceService(ctx); + + const result = await service.update({ + id: 11, + templateId: '', + }); + + assert.equal(calls.updatePayload.updates.template_id, null); + assert.equal(result.data.template_id, null); + }); + + it('should normalize empty brandno to null when updating', async () => { + const { ctx, calls } = createHarness(); + const service = new SettingExpressInterfaceService(ctx); + + const result = await service.update({ + id: 11, + brandNo: '', + }); + + assert.equal(calls.updatePayload.updates.brandno, null); + assert.equal(result.data.brandno, null); + }); + it('should clear token when shop_id is cleared', async () => { const { ctx, calls } = createHarness(); const service = new SettingExpressInterfaceService(ctx); diff --git a/test/app/service/systems/shops.test.js b/test/app/service/systems/shops.test.js index eca4388..e1e6700 100644 --- a/test/app/service/systems/shops.test.js +++ b/test/app/service/systems/shops.test.js @@ -57,6 +57,18 @@ function createHarness(options = {}) { dynamicConditions: [], rawConditionsByField: {}, }, + async curl() { + if (typeof options.curl === 'function') { + return await options.curl(...arguments); + } + + return { + data: { + code: 1, + msg: 'mock failed', + }, + }; + }, model: { Shop: { async findAndCountAll(query) { @@ -186,6 +198,51 @@ describe('test/app/service/systems/shops.test.js', () => { assert.equal(calls.shopCreatePayload.shop_name.startsWith('PENDING_'), true); }); + it('add 未传 shop_name 时,首次占位名冲突应重试并成功', async () => { + let findOneCallCount = 0; + const { service, calls } = createHarness({ + shopFindOne: async () => { + findOneCallCount += 1; + + if (findOneCallCount === 1) { + return createFindOneResult({ id: 101 }); + } + + return null; + }, + }); + const generatedCodes = [ 'RETRY1', 'RETRY2' ]; + service.generateAuthorizeRandomCode = () => generatedCodes.shift() || 'RETRY_FALLBACK'; + + const result = await service.add({ + custom_name: '重试店铺', + platform_code: 'PDD', + }); + + assert.equal(result.id, 9001); + assert.equal(calls.shopCreatePayload.shop_name, 'PENDING_RETRY2'); + }); + + it('add 连续冲突超过重试上限时应返回占位名冲突提示', async () => { + const { service } = createHarness({ + shopFindOne: async () => { + return createFindOneResult({ id: 102 }); + }, + }); + service.generateAuthorizeRandomCode = () => 'ALWAYS_CONFLICT'; + + await assert.rejects(async () => { + await service.add({ + custom_name: '冲突店铺', + platform_code: 'PDD', + }); + }, error => { + assert.equal(error && error.message, '系统生成占位名冲突,请重试'); + assert.equal(error && error.code, 409); + return true; + }); + }); + it('del 遇到快递接口引用时应拒绝删除', async () => { const { service } = createHarness({ shopRows: [ @@ -230,7 +287,7 @@ describe('test/app/service/systems/shops.test.js', () => { assert.equal(result.id, 7); }); - it('getAuthorizeSessionKey 对未实现平台应返回 501 错误', async () => { + it('getAuthorizeSessionKey 请求授权接口失败时应抛出业务错误', async () => { const { service } = createHarness({ shopRows: [ { @@ -251,6 +308,12 @@ describe('test/app/service/systems/shops.test.js', () => { status: 'ACTIVE', }, ], + curl: async () => ({ + data: { + code: 1, + msg: '接口异常', + }, + }), }); await assert.rejects(async () => { @@ -258,6 +321,6 @@ describe('test/app/service/systems/shops.test.js', () => { id: 9, callbackurl: 'https://callback.example.com', }); - }, /暂未实现授权会话换取能力/); + }, /获取授权失败:接口异常/); }); });