1
This commit is contained in:
parent
4beefcd22c
commit
99367e5043
2
.github/agents/专家.agent.md
vendored
2
.github/agents/专家.agent.md
vendored
@ -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`)
|
||||
|
||||
2
.github/agents/发布.agent.md
vendored
2
.github/agents/发布.agent.md
vendored
@ -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)
|
||||
|
||||
---
|
||||
|
||||
|
||||
2
.github/agents/开发.agent.md
vendored
2
.github/agents/开发.agent.md
vendored
@ -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`)
|
||||
|
||||
2
.github/agents/数据库.agent.md
vendored
2
.github/agents/数据库.agent.md
vendored
@ -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`)
|
||||
|
||||
2
.github/agents/文档.agent.md
vendored
2
.github/agents/文档.agent.md
vendored
@ -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`)
|
||||
|
||||
2
.github/agents/测试.agent.md
vendored
2
.github/agents/测试.agent.md
vendored
@ -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`)
|
||||
|
||||
2
.github/agents/缓存.agent.md
vendored
2
.github/agents/缓存.agent.md
vendored
@ -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`)
|
||||
|
||||
2
.github/agents/评审.agent.md
vendored
2
.github/agents/评审.agent.md
vendored
@ -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`)
|
||||
|
||||
45
.github/agents/调度.agent.md
vendored
45
.github/agents/调度.agent.md
vendored
@ -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。
|
||||
3) 汇总处理结果与下一步建议
|
||||
@ -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 `<a class="tab ${activeClass}" href="/api/docs/${encodeURIComponent(name)}">${escapeHtml(name)}</a>`;
|
||||
}).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({
|
||||
<a class="tab" href="${escapeHtml(changesUrl)}">查看变更记录</a>
|
||||
<a class="tab" href="${escapeHtml(rawUrl)}">查看 JSON</a>
|
||||
</div>
|
||||
<div class="global-auth">
|
||||
${isOpenapi ? '' : `<div class="global-auth">
|
||||
<h3>全局 Authorization</h3>
|
||||
<div class="row">
|
||||
<input id="globalAuth" type="text" placeholder="Bearer xxxxx" />
|
||||
@ -1042,8 +1086,8 @@ function renderHtmlPage({
|
||||
<h3>全局业务 Header</h3>
|
||||
${globalHeadersControls}
|
||||
<p class="muted">来自 JSON 的 headers 定义;带 * 的字段为必填,支持下拉 list 选择。</p>
|
||||
</div>
|
||||
<div class="doc-tools">
|
||||
</div>`}
|
||||
${isOpenapi ? '' : `<div class="doc-tools">
|
||||
<h3>文档资源</h3>
|
||||
<div class="doc-tools-actions">
|
||||
${renderWindowElement('打开变更记录', changesUrl, 'doc-resource-link')}
|
||||
@ -1052,7 +1096,53 @@ function renderHtmlPage({
|
||||
<button type="button" id="previewRawBtn">预览原文 JSON</button>
|
||||
</div>
|
||||
<pre id="docResourcePreview" class="req-result muted">点击上方按钮后,可直接预览当前文档的变更记录或原文 JSON。</pre>
|
||||
</div>
|
||||
</div>`}
|
||||
${isOpenapi ? `<div class="openapi-guide">
|
||||
<h3>请求方式</h3>
|
||||
<pre class="guide-code">POST /openapi?method={方法名}&v=1.0×tamp={时间戳}&app_key={app_key}&sign={签名}
|
||||
Content-Type: application/json
|
||||
|
||||
{请求体 JSON}</pre>
|
||||
|
||||
<h3>签名算法(MD5)</h3>
|
||||
<pre class="guide-code">参与签名字符串 = 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) = ...</pre>
|
||||
|
||||
<h3>注意事项</h3>
|
||||
<ul class="guide-notes">
|
||||
<li><strong>method</strong> 格式为 <code>模块.方法</code>,如 <code>index.ping</code></li>
|
||||
<li><strong>app_key</strong> / <strong>self_app_secret</strong> 由仓库申请配置,请联系仓库管理员获取</li>
|
||||
<li>请求体必须为合法 JSON,空 body 传 <code>{}</code></li>
|
||||
<li>时间戳 <strong>timestamp</strong> 为 Unix 秒级时间戳(数字类型)</li>
|
||||
<li>时间戳 <strong>timestamp</strong> 时效校验:与服务器时间差不得超过 ±10 分钟(600 秒),超时返回 400</li>
|
||||
<li>签名结果为 32 位小写十六进制字符串</li>
|
||||
</ul>
|
||||
<p style="margin-top:12px;font-size:13px;">
|
||||
<a href="/docs/api/openapi/callback-test" style="color:#1565c0;">→ 回调测试工具</a>
|
||||
<span class="muted">(模拟接收回调通知,验证回调链路)</span>
|
||||
</p>
|
||||
</div>` : ''}
|
||||
</section>
|
||||
|
||||
<section class="layout">
|
||||
@ -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<void>} 无返回值。
|
||||
*/
|
||||
async openapi() {
|
||||
await this.renderDoc('openapi');
|
||||
}
|
||||
|
||||
async detail() {
|
||||
const { ctx } = this;
|
||||
const docName = ctx.params.docName;
|
||||
|
||||
277
app/controller/openapiCallback.js
Normal file
277
app/controller/openapiCallback.js
Normal file
@ -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 = `<!doctype html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>OpenAPI 回调测试</title>
|
||||
<style>
|
||||
* { box-sizing: border-box; }
|
||||
body { font-family: "Segoe UI","PingFang SC","Microsoft YaHei",sans-serif; background: #f4f6fb; color: #1f2a44; margin: 0; padding: 24px; }
|
||||
.container { max-width: 720px; margin: 0 auto; }
|
||||
h1 { font-size: 22px; margin: 0 0 8px; }
|
||||
.card { background: #fff; border: 1px solid #dbe1ee; border-radius: 12px; padding: 20px; margin-bottom: 16px; box-shadow: 0 4px 16px rgba(18,48,102,0.06); }
|
||||
label { display: block; font-weight: 600; margin: 12px 0 4px; color: #254974; font-size: 13px; }
|
||||
select, input, textarea { width: 100%; border: 1px solid #b5ccec; border-radius: 8px; padding: 8px 10px; font-size: 13px; font-family: inherit; }
|
||||
textarea { font-family: ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace; resize: vertical; }
|
||||
.row { display: grid; grid-template-columns: 1fr 1fr; gap: 12px; }
|
||||
.send-btn { border: 1px solid #0f5cb2; background: #1565c0; color: #fff; border-radius: 8px; padding: 10px 20px; cursor: pointer; font-size: 14px; margin-top: 12px; }
|
||||
.send-btn:disabled { opacity: 0.6; cursor: not-allowed; }
|
||||
pre { background: #0d1d33; color: #d8e7ff; border-radius: 8px; padding: 12px; font-size: 12px; overflow: auto; max-height: 400px; white-space: pre-wrap; word-break: break-all; margin: 12px 0 0; }
|
||||
.muted { color: #62708a; font-size: 12px; }
|
||||
.desc { color: #62708a; font-size: 13px; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="container">
|
||||
<div class="card">
|
||||
<h1>OpenAPI 回调测试</h1>
|
||||
<p class="desc">选择已注册的回调事件,填入测试 URL,模拟真实回调推送。</p>
|
||||
<p style="margin-top:6px;font-size:13px;">
|
||||
<a href="/docs/api/openapi" style="color:#1565c0;">← 返回 API 文档</a>
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div class="card">
|
||||
<label>回调事件</label>
|
||||
<select id="eventSelect">
|
||||
<option value="">请选择事件</option>
|
||||
</select>
|
||||
<p id="eventDesc" class="muted"></p>
|
||||
|
||||
<div class="row">
|
||||
<div>
|
||||
<label>app_key</label>
|
||||
<input id="appKeyInput" type="text" placeholder="APP2024011514301234" />
|
||||
</div>
|
||||
<div>
|
||||
<label>self_app_secret</label>
|
||||
<input id="secretInput" type="password" placeholder="密钥" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<label>测试回调 URL</label>
|
||||
<input id="callbackUrlInput" type="text" placeholder="https://your-system.com/api/callback" />
|
||||
|
||||
<label>回调数据 Body(自动填充模板,可编辑)</label>
|
||||
<textarea id="dataInput" rows="8" placeholder='{}'></textarea>
|
||||
|
||||
<button id="sendBtn" class="send-btn" onclick="sendTest()">发送测试回调</button>
|
||||
|
||||
<pre id="resultBox">点击发送后显示响应</pre>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
var EVENTS = ${eventsJson};
|
||||
|
||||
var eventSelect = document.getElementById('eventSelect');
|
||||
var eventDesc = document.getElementById('eventDesc');
|
||||
var dataInput = document.getElementById('dataInput');
|
||||
var resultBox = document.getElementById('resultBox');
|
||||
|
||||
// 填充下拉列表
|
||||
EVENTS.forEach(function(ev) {
|
||||
var opt = document.createElement('option');
|
||||
opt.value = ev.name;
|
||||
opt.textContent = ev.label + ' (' + ev.name + ')';
|
||||
eventSelect.appendChild(opt);
|
||||
});
|
||||
|
||||
eventSelect.addEventListener('change', function() {
|
||||
var name = eventSelect.value;
|
||||
var found = EVENTS.find(function(e) { return e.name === name; });
|
||||
if (found) {
|
||||
eventDesc.textContent = found.description;
|
||||
dataInput.value = JSON.stringify(found.sampleData, null, 2);
|
||||
} else {
|
||||
eventDesc.textContent = '';
|
||||
dataInput.value = '{}';
|
||||
}
|
||||
});
|
||||
|
||||
function nowTimestamp() { return Math.floor(Date.now() / 1000); }
|
||||
|
||||
function md5(value) {
|
||||
// 使用与 docs.js 一致的 md5 实现(修复后版本)
|
||||
function add32(a,b){return(a+b)&0xFFFFFFFF}
|
||||
function cmn(q,a,b,x,s,t){a=add32(add32(a,q),add32(x,t));return add32((a<<s)|(a>>>32-s),b)}
|
||||
function ff(a,b,c,d,x,s,t){return cmn((b&c)|((~b)&d),a,b,x,s,t)}
|
||||
function gg(a,b,c,d,x,s,t){return cmn((b&d)|(c&(~d)),a,b,x,s,t)}
|
||||
function hh(a,b,c,d,x,s,t){return cmn(b^c^d,a,b,x,s,t)}
|
||||
function ii(a,b,c,d,x,s,t){return cmn(c^(b|(~d)),a,b,x,s,t)}
|
||||
|
||||
var originalLength = value.length;
|
||||
var str = value;
|
||||
var m = [];
|
||||
var i = 0;
|
||||
while (str.length >= 64) {
|
||||
m = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];
|
||||
for (var j = 0; j < 64; j++) m[j>>2] |= str.charCodeAt(j) << ((j%4)*8);
|
||||
var block = m;
|
||||
var a0=1732584193,b0=-271733879,c0=-1732584194,d0=271733878;
|
||||
var a=a0,b=b0,c=c0,d=d0;
|
||||
a=ff(a,b,c,d,block[0],7,-680876936);d=ff(d,a,b,c,block[1],12,-389564586);
|
||||
c=ff(c,d,a,b,block[2],17,606105819);b=ff(b,c,d,a,block[3],22,-1044525330);
|
||||
a=ff(a,b,c,d,block[4],7,-176418897);d=ff(d,a,b,c,block[5],12,1200080426);
|
||||
c=ff(c,d,a,b,block[6],17,-1473231341);b=ff(b,c,d,a,block[7],22,-45705983);
|
||||
a=ff(a,b,c,d,block[8],7,1770035416);d=ff(d,a,b,c,block[9],12,-1958414417);
|
||||
c=ff(c,d,a,b,block[10],17,-42063);b=ff(b,c,d,a,block[11],22,-1990404162);
|
||||
a=ff(a,b,c,d,block[12],7,1804603682);d=ff(d,a,b,c,block[13],12,-40341101);
|
||||
c=ff(c,d,a,b,block[14],17,-1502002290);b=ff(b,c,d,a,block[15],22,1236535329);
|
||||
a=gg(a,b,c,d,block[1],5,-165796510);d=gg(d,a,b,c,block[6],9,-1069501632);
|
||||
c=gg(c,d,a,b,block[11],14,643717713);b=gg(b,c,d,a,block[0],20,-373897302);
|
||||
a=gg(a,b,c,d,block[5],5,-701558691);d=gg(d,a,b,c,block[10],9,38016083);
|
||||
c=gg(c,d,a,b,block[15],14,-660478335);b=gg(b,c,d,a,block[4],20,-405537848);
|
||||
a=gg(a,b,c,d,block[9],5,568446438);d=gg(d,a,b,c,block[14],9,-1019803690);
|
||||
c=gg(c,d,a,b,block[3],14,-187363961);b=gg(b,c,d,a,block[8],20,1163531501);
|
||||
a=gg(a,b,c,d,block[13],5,-1444681467);d=gg(d,a,b,c,block[2],9,-51403784);
|
||||
c=gg(c,d,a,b,block[7],14,1735328473);b=gg(b,c,d,a,block[12],20,-1926607734);
|
||||
a=hh(a,b,c,d,block[5],4,-378558);d=hh(d,a,b,c,block[8],11,-2022574463);
|
||||
c=hh(c,d,a,b,block[11],16,1839030562);b=hh(b,c,d,a,block[14],23,-35309556);
|
||||
a=hh(a,b,c,d,block[1],4,-1530992060);d=hh(d,a,b,c,block[4],11,1272893353);
|
||||
c=hh(c,d,a,b,block[7],16,-155497632);b=hh(b,c,d,a,block[10],23,-1094730640);
|
||||
a=hh(a,b,c,d,block[13],4,681279174);d=hh(d,a,b,c,block[0],11,-358537222);
|
||||
c=hh(c,d,a,b,block[3],16,-722521979);b=hh(b,c,d,a,block[6],23,76029189);
|
||||
a=hh(a,b,c,d,block[9],4,-640364487);d=hh(d,a,b,c,block[12],11,-421815835);
|
||||
c=hh(c,d,a,b,block[15],16,530742520);b=hh(b,c,d,a,block[2],23,-995338651);
|
||||
a=ii(a,b,c,d,block[0],6,-198630844);d=ii(d,a,b,c,block[7],10,1126891415);
|
||||
c=ii(c,d,a,b,block[14],15,-1416354905);b=ii(b,c,d,a,block[5],21,-57434055);
|
||||
a=ii(a,b,c,d,block[12],6,1700485571);d=ii(d,a,b,c,block[3],10,-1894986606);
|
||||
c=ii(c,d,a,b,block[10],15,-1051523);b=ii(b,c,d,a,block[1],21,-2054922799);
|
||||
a=ii(a,b,c,d,block[8],6,1873313359);d=ii(d,a,b,c,block[15],10,-30611744);
|
||||
c=ii(c,d,a,b,block[6],15,-1560198380);b=ii(b,c,d,a,block[13],21,1309151649);
|
||||
a=ii(a,b,c,d,block[4],6,-145523070);d=ii(d,a,b,c,block[11],10,-1120210379);
|
||||
c=ii(c,d,a,b,block[2],15,718787259);b=ii(b,c,d,a,block[9],21,-343485551);
|
||||
a0=add32(a0,a);b0=add32(b0,b);c0=add32(c0,c);d0=add32(d0,d);
|
||||
str = str.substring(64);
|
||||
}
|
||||
|
||||
var tail = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];
|
||||
for (i = 0; i < str.length; i++) tail[i>>2] |= str.charCodeAt(i) << ((i%4)*8);
|
||||
tail[i>>2] |= 0x80 << ((i%4)*8);
|
||||
tail[14] = originalLength * 8; // 修复:使用原始长度
|
||||
|
||||
a0=ff(a0,b0,c0,d0,tail[0],7,-680876936);d0=ff(d0,a0,b0,c0,tail[1],12,-389564586);
|
||||
c0=ff(c0,d0,a0,b0,tail[2],17,606105819);b0=ff(b0,c0,d0,a0,tail[3],22,-1044525330);
|
||||
a0=ff(a0,b0,c0,d0,tail[4],7,-176418897);d0=ff(d0,a0,b0,c0,tail[5],12,1200080426);
|
||||
c0=ff(c0,d0,a0,b0,tail[6],17,-1473231341);b0=ff(b0,c0,d0,a0,tail[7],22,-45705983);
|
||||
a0=ff(a0,b0,c0,d0,tail[8],7,1770035416);d0=ff(d0,a0,b0,c0,tail[9],12,-1958414417);
|
||||
c0=ff(c0,d0,a0,b0,tail[10],17,-42063);b0=ff(b0,c0,d0,a0,tail[11],22,-1990404162);
|
||||
a0=ff(a0,b0,c0,d0,tail[12],7,1804603682);d0=ff(d0,a0,b0,c0,tail[13],12,-40341101);
|
||||
c0=ff(c0,d0,a0,b0,tail[14],17,-1502002290);b0=ff(b0,c0,d0,a0,tail[15],22,1236535329);
|
||||
|
||||
function toHex(num) {
|
||||
var s = ''; for (var k = 0; k < 4; k++) s += ('0' + ((num>>>(k*8))&0xFF).toString(16)).slice(-2);
|
||||
return s;
|
||||
}
|
||||
return (toHex(a0)+toHex(b0)+toHex(c0)+toHex(d0)).toLowerCase();
|
||||
}
|
||||
|
||||
function stableStringify(value) {
|
||||
if (value === undefined) return '';
|
||||
if (value === null || typeof value !== 'object') return JSON.stringify(value);
|
||||
if (Array.isArray(value)) {
|
||||
var items = value.map(function(v) { return stableStringify(v); });
|
||||
return '[' + items.join(',') + ']';
|
||||
}
|
||||
if (Object.prototype.toString.call(value) !== '[object Object]') return JSON.stringify(value);
|
||||
var keys = Object.keys(value).sort();
|
||||
var fields = keys.map(function(k) { return JSON.stringify(k) + ':' + stableStringify(value[k]); });
|
||||
return '{' + fields.join(',') + '}';
|
||||
}
|
||||
|
||||
function computeSign(query, body, secret) {
|
||||
// 排除 sign/signature,按 key 字母序排序
|
||||
var ignoreKeys = ['sign', 'signature'];
|
||||
var sortedKeys = Object.keys(query).filter(function(k) {
|
||||
return ignoreKeys.indexOf(k.toLowerCase()) === -1 && query[k] !== undefined;
|
||||
}).sort();
|
||||
var canonicalQuery = sortedKeys.map(function(k) {
|
||||
return k + '=' + String(query[k] == null ? '' : typeof query[k] === 'object' ? stableStringify(query[k]) : query[k]);
|
||||
}).join('&');
|
||||
|
||||
var bodySign = md5(stableStringify(body));
|
||||
var signText = canonicalQuery + secret + bodySign;
|
||||
return md5(signText);
|
||||
}
|
||||
|
||||
async function sendTest() {
|
||||
var appKey = document.getElementById('appKeyInput').value.trim();
|
||||
var secret = document.getElementById('secretInput').value.trim();
|
||||
var callbackUrl = document.getElementById('callbackUrlInput').value.trim();
|
||||
var eventName = eventSelect.value;
|
||||
var dataText = dataInput.value.trim();
|
||||
var sendBtn = document.getElementById('sendBtn');
|
||||
|
||||
if (!eventName) { resultBox.textContent = '请选择回调事件'; return; }
|
||||
if (!appKey) { resultBox.textContent = '请输入 app_key'; return; }
|
||||
if (!secret) { resultBox.textContent = '请输入 self_app_secret'; return; }
|
||||
if (!callbackUrl) { resultBox.textContent = '请输入测试回调 URL'; return; }
|
||||
|
||||
sendBtn.disabled = true;
|
||||
sendBtn.textContent = '发送中...';
|
||||
resultBox.textContent = '请求中...';
|
||||
|
||||
try {
|
||||
var body = JSON.parse(dataText);
|
||||
var ts = nowTimestamp();
|
||||
var query = { method: eventName, v: '1.0', timestamp: ts, app_key: appKey };
|
||||
var sign = computeSign(query, body, secret);
|
||||
|
||||
var reqUrl = callbackUrl + (callbackUrl.indexOf('?') >= 0 ? '&' : '?') +
|
||||
'method=' + encodeURIComponent(eventName) +
|
||||
'&v=1.0' +
|
||||
'×tamp=' + ts +
|
||||
'&app_key=' + encodeURIComponent(appKey) +
|
||||
'&sign=' + sign;
|
||||
|
||||
resultBox.textContent = \`POST \${reqUrl}\n\n\${JSON.stringify(body, null, 2)}\n\n请求中...\`;
|
||||
|
||||
var resp = await fetch(reqUrl, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
var respText = await resp.text();
|
||||
var respInfo = \`HTTP \${resp.status} \${resp.statusText}\n\n\`;
|
||||
try {
|
||||
var respJson = JSON.parse(respText);
|
||||
respInfo += JSON.stringify(respJson, null, 2);
|
||||
} catch(e) {
|
||||
respInfo += respText;
|
||||
}
|
||||
resultBox.textContent = \`POST \${reqUrl}\n\n\${JSON.stringify(body, null, 2)}\n\n--- 响应 ---\n\${respInfo}\`;
|
||||
} catch(e) {
|
||||
resultBox.textContent = '请求失败: ' + e.message;
|
||||
} finally {
|
||||
sendBtn.disabled = false;
|
||||
sendBtn.textContent = '发送测试回调';
|
||||
}
|
||||
}
|
||||
</script>
|
||||
</body>
|
||||
</html>`;
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = OpenapiCallbackController;
|
||||
@ -135,6 +135,7 @@ module.exports = {
|
||||
STORE_CREATE: '创建货主',
|
||||
STORE_CREATE_WAREHOUSE: '创建仓库',
|
||||
STORE_SIGN: '签约货主',
|
||||
STORE_OPEN_ACCOUNT: '仓库代开户',
|
||||
STORE_RENAME: '修改签约备注',
|
||||
STORE_UNBIND: '解绑签约',
|
||||
STORE_SAVE_POLICY_CONFIG: '保存签约策略配置',
|
||||
|
||||
@ -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<Object>} orders 订单数组。
|
||||
@ -148,6 +188,91 @@ class ExpressPrintPayloadBuilder {
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 将 SPH 订单中的动态业务字段回填到模板 taskList[0]。
|
||||
*
|
||||
* 仅覆盖动态字段,避免改写模板固定结构。
|
||||
*
|
||||
* @param {Object} payload 打印请求 payload。
|
||||
* @param {Array<Object>} 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<Object>} 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 订单对象。
|
||||
|
||||
@ -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 使用现有商品汇总文本并按 <br> 拼接
|
||||
* - 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, '<br>');
|
||||
|
||||
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,
|
||||
|
||||
@ -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,
|
||||
|
||||
@ -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,
|
||||
|
||||
@ -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 = {
|
||||
|
||||
@ -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);
|
||||
|
||||
@ -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;
|
||||
|
||||
225
app/service/openapi/callback.js
Normal file
225
app/service/openapi/callback.js
Normal file
@ -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<Object>} 回调结果 { 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<Object>} 回调结果 { 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;
|
||||
31
app/service/openapi/callbackRegistry.js
Normal file
31
app/service/openapi/callbackRegistry.js
Normal file
@ -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 };
|
||||
78
app/service/openapiMethods/callback.js
Normal file
78
app/service/openapiMethods/callback.js
Normal file
@ -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<Object>} 包含 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<Object>} 回调测试结果。
|
||||
*/
|
||||
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;
|
||||
159
app/service/openapiMethods/deliveryorder.js
Normal file
159
app/service/openapiMethods/deliveryorder.js
Normal file
@ -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<Object>} 包含 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<Object>} 查询结果,成功时返回订单详情,失败时返回错误信息。
|
||||
*/
|
||||
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<Object>} 创建结果,成功时返回订单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;
|
||||
106
app/service/openapiMethods/inventory.js
Normal file
106
app/service/openapiMethods/inventory.js
Normal file
@ -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<Object>} 包含 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<Object>} 查询结果,成功时返回 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;
|
||||
163
app/service/openapiMethods/order.js
Normal file
163
app/service/openapiMethods/order.js
Normal file
@ -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<Object>} 包含 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<Object>} 取消结果,成功时返回成功消息,失败时返回错误信息。
|
||||
*/
|
||||
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;
|
||||
137
app/service/openapiMethods/singleitem.js
Normal file
137
app/service/openapiMethods/singleitem.js
Normal file
@ -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<Object>} 包含 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<Object>} 同步结果,成功时返回 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<Object>} 查询结果,成功时返回商品详情。
|
||||
*/
|
||||
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;
|
||||
File diff suppressed because it is too large
Load Diff
@ -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({
|
||||
|
||||
@ -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<Object>} 更新后的订单信息。
|
||||
*/
|
||||
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<number>} orderIds 订单ID集合。
|
||||
* @param {Object} transaction Sequelize 事务对象。
|
||||
* @return {Promise<void>} 无返回值。
|
||||
*/
|
||||
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<number|string>} params.waveIds 受影响波次ID集合。
|
||||
* @param {Object} params.orderModel 订单模型。
|
||||
* @param {Object} params.transaction Sequelize 事务对象。
|
||||
* @return {Promise<void>} 无返回值。
|
||||
*/
|
||||
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<Object>} 解析结果,成功返回 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<Object>} data.items 订单明细(必填,每项含 item_code 与 plan_qty)。
|
||||
* @param {Array<Object>} 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<Object>} 统一 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<Object>} 统一 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;
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@ -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<number>} 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<Object>} 统一 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>|number|string} [data.order_ids] 部分确认时的订单ID集合。
|
||||
* @return {Promise<Object>} 统一 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;
|
||||
|
||||
316
app/service/systemMethods/pickCart.js
Normal file
316
app/service/systemMethods/pickCart.js
Normal file
@ -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<Object>} 统一 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<Object>} 统一 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<Object>} 统一 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<Object>} 统一 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<Object>} 统一 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<Object>} 统一 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<Object>} 统一 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<Object>} 统一 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;
|
||||
@ -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<number|string>} payload.orderIds 订单ID列表。
|
||||
* @return {Promise<{orderWaveIndexMap:Map<number, {wave_id:number, wave_index:number, platforms_index:number}>,waveTotalOrdersMap:Map<number, number>}>} 波次索引上下文。
|
||||
*/
|
||||
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<number, {wave_id:number, wave_index:number, platforms_index:number}>} payload.orderWaveIndexMap 订单波次索引映射。
|
||||
* @param {Map<number, number>} 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,
|
||||
|
||||
@ -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, '更新快递接口失败');
|
||||
}
|
||||
|
||||
@ -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<Object>} 统一响应结果。
|
||||
*/
|
||||
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;
|
||||
|
||||
@ -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,
|
||||
|
||||
@ -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);
|
||||
}
|
||||
// ========== 库存检查逻辑结束 ==========
|
||||
|
||||
// 所有检查通过,准备订单行数据
|
||||
|
||||
@ -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;
|
||||
}
|
||||
|
||||
|
||||
@ -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,
|
||||
};
|
||||
}
|
||||
|
||||
@ -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,
|
||||
|
||||
@ -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),
|
||||
|
||||
@ -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<number>} orderIds 订单ID数组。
|
||||
* @return {Promise<Array<Object>>} 快递单信息列表。
|
||||
*/
|
||||
/**
|
||||
* 根据订单 ID 列表批量查询运单记录。
|
||||
* 返回 business_key=1 的主运单,按 order_id、business_key、id 升序排列。
|
||||
*
|
||||
* @param {number[]} orderIds 订单 ID 列表。
|
||||
* @returns {Promise<Array<Object>>} 匹配的运单记录数组,字段包含 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<Array<Object>>} 接口配置列表。
|
||||
*/
|
||||
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<Array<Object>>} 接口配置列表。
|
||||
*/
|
||||
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<Array<Object>>} 接口配置列表。
|
||||
*/
|
||||
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<Object>} 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<Object>} 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<Object>} 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<Object>} orderRows 订单列表。
|
||||
* @param {Array<Object>} orderExpressRows 快递单列表。
|
||||
* @param {number} warehouseId 仓库ID。
|
||||
* @return {Promise<Array<Object>>} 补齐后的快递单列表。
|
||||
*/
|
||||
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<Object>} orderRows 订单列表。
|
||||
* @param {Array<Object>} orderExpressRows 快递单列表。
|
||||
* @param {number} warehouseId 仓库ID。
|
||||
* @return {Promise<Array<Object>>} 补齐后的快递单列表。
|
||||
*/
|
||||
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 {};
|
||||
}
|
||||
|
||||
|
||||
@ -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) {
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
88
app/service/systems/pickCart.js
Normal file
88
app/service/systems/pickCart.js
Normal file
@ -0,0 +1,88 @@
|
||||
'use strict';
|
||||
|
||||
const Service = require('egg').Service;
|
||||
|
||||
class PickCartSystemService extends Service {
|
||||
/**
|
||||
* 按拣货车编码扫码查询。
|
||||
*
|
||||
* @param {Object} params 查询参数。
|
||||
* @param {string} params.cartCode 拣货车编码。
|
||||
* @return {Promise<Object>} 拣货车信息。
|
||||
*/
|
||||
async scan(params = {}) {
|
||||
return await this.service.systems.pick.pickCartScan(params);
|
||||
}
|
||||
|
||||
/**
|
||||
* 绑定拣货任务与拣货车。
|
||||
*
|
||||
* @param {Object} params 绑定参数。
|
||||
* @return {Promise<Object>} 绑定结果。
|
||||
*/
|
||||
async bindTaskCart(params = {}) {
|
||||
return await this.service.systems.pick.wavePickTaskBindCart(params);
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建拣货车。
|
||||
*
|
||||
* @param {Object} params 创建参数。
|
||||
* @return {Promise<Object>} 创建结果。
|
||||
*/
|
||||
async create(params = {}) {
|
||||
return await this.service.systems.pick.pickCartCreate(params);
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新拣货车。
|
||||
*
|
||||
* @param {Object} params 更新参数。
|
||||
* @return {Promise<Object>} 更新结果。
|
||||
*/
|
||||
async update(params = {}) {
|
||||
return await this.service.systems.pick.pickCartUpdate(params);
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除拣货车。
|
||||
*
|
||||
* @param {Object} params 删除参数。
|
||||
* @return {Promise<Object>} 删除结果。
|
||||
*/
|
||||
async delete(params = {}) {
|
||||
return await this.service.systems.pick.pickCartDelete(params);
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询拣货车详情。
|
||||
*
|
||||
* @param {Object} params 查询参数。
|
||||
* @return {Promise<Object>} 详情结果。
|
||||
*/
|
||||
async detail(params = {}) {
|
||||
return await this.service.systems.pick.pickCartDetail(params);
|
||||
}
|
||||
|
||||
/**
|
||||
* 分页查询拣货车列表。
|
||||
*
|
||||
* @param {Object} params 查询参数。
|
||||
* @return {Promise<Object>} 列表结果。
|
||||
*/
|
||||
async list(params = {}) {
|
||||
return await this.service.systems.pick.pickCartList(params);
|
||||
}
|
||||
|
||||
/**
|
||||
* 拣货车编码查重。
|
||||
*
|
||||
* @param {Object} params 查询参数。
|
||||
* @return {Promise<Object>} 查重结果。
|
||||
*/
|
||||
async codeDuplicateCheck(params = {}) {
|
||||
return await this.service.systems.pick.pickCartCodeDuplicateCheck(params);
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = PickCartSystemService;
|
||||
@ -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);
|
||||
}
|
||||
|
||||
@ -11,6 +11,45 @@ const {
|
||||
* 店铺业务服务。
|
||||
*/
|
||||
class ShopsService extends Service {
|
||||
/**
|
||||
* 生成待授权占位店铺名并校验唯一性(最多重试 5 次)。
|
||||
*
|
||||
* @param {Object} payload 入参
|
||||
* @param {number} payload.warehouseId 仓库 ID
|
||||
* @param {string} payload.platformCode 平台编码
|
||||
* @return {Promise<string>} 可用的占位店铺名
|
||||
*/
|
||||
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({
|
||||
|
||||
@ -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 对象
|
||||
});
|
||||
|
||||
|
||||
@ -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,
|
||||
},
|
||||
});
|
||||
|
||||
@ -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<Object>} 包含 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;
|
||||
|
||||
BIN
app_service_systemMethods_index_head.js
Normal file
BIN
app_service_systemMethods_index_head.js
Normal file
Binary file not shown.
@ -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,
|
||||
};
|
||||
|
||||
@ -65,4 +65,4 @@ module.exports = {
|
||||
|
||||
await queryInterface.addColumn(TABLE_NAME, COLUMN_NAME, buildPlatidColumn(Sequelize));
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
@ -0,0 +1,46 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 为快递接口配置表新增模板 ID 字段 template_id。
|
||||
* @param {import('sequelize').QueryInterface} queryInterface 查询接口
|
||||
* @param {import('sequelize')} Sequelize Sequelize 实例
|
||||
* @return {Promise<void>} 无返回值
|
||||
*/
|
||||
module.exports = {
|
||||
/**
|
||||
* 执行迁移:新增 template_id 字段(幂等)。
|
||||
* @param {import('sequelize').QueryInterface} queryInterface 查询接口
|
||||
* @param {import('sequelize')} Sequelize Sequelize 实例
|
||||
* @return {Promise<void>} 无返回值
|
||||
*/
|
||||
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<void>} 无返回值
|
||||
*/
|
||||
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');
|
||||
},
|
||||
};
|
||||
@ -0,0 +1,46 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 为快递接口配置表新增品牌编码字段。
|
||||
* @param {import('sequelize').QueryInterface} queryInterface 查询接口
|
||||
* @param {import('sequelize')} Sequelize Sequelize 实例
|
||||
* @return {Promise<void>} 无返回值
|
||||
*/
|
||||
module.exports = {
|
||||
/**
|
||||
* 执行迁移:新增 brandno 字段(幂等)。
|
||||
* @param {import('sequelize').QueryInterface} queryInterface 查询接口
|
||||
* @param {import('sequelize')} Sequelize Sequelize 实例
|
||||
* @return {Promise<void>} 无返回值
|
||||
*/
|
||||
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<void>} 无返回值
|
||||
*/
|
||||
async down(queryInterface) {
|
||||
const tableName = 'wms_express_interface';
|
||||
const columns = await queryInterface.describeTable(tableName);
|
||||
|
||||
if (!columns.brandno) {
|
||||
return;
|
||||
}
|
||||
|
||||
await queryInterface.removeColumn(tableName, 'brandno');
|
||||
},
|
||||
};
|
||||
@ -0,0 +1,46 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 为快递接口配置表新增服务商类型字段。
|
||||
* @param {import('sequelize').QueryInterface} queryInterface 查询接口
|
||||
* @param {import('sequelize')} Sequelize Sequelize 实例
|
||||
* @return {Promise<void>} 无返回值
|
||||
*/
|
||||
module.exports = {
|
||||
/**
|
||||
* 执行迁移:新增 providertype 字段(幂等)。
|
||||
* @param {import('sequelize').QueryInterface} queryInterface 查询接口
|
||||
* @param {import('sequelize')} Sequelize Sequelize 实例
|
||||
* @return {Promise<void>} 无返回值
|
||||
*/
|
||||
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<void>} 无返回值
|
||||
*/
|
||||
async down(queryInterface) {
|
||||
const tableName = 'wms_express_interface';
|
||||
const columns = await queryInterface.describeTable(tableName);
|
||||
|
||||
if (!columns.providertype) {
|
||||
return;
|
||||
}
|
||||
|
||||
await queryInterface.removeColumn(tableName, 'providertype');
|
||||
},
|
||||
};
|
||||
@ -0,0 +1,46 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 为快递接口配置表新增付款方式字段。
|
||||
* @param {import('sequelize').QueryInterface} queryInterface 查询接口
|
||||
* @param {import('sequelize')} Sequelize Sequelize 实例
|
||||
* @return {Promise<void>} 无返回值
|
||||
*/
|
||||
module.exports = {
|
||||
/**
|
||||
* 执行迁移:新增 paymode 字段(幂等)。
|
||||
* @param {import('sequelize').QueryInterface} queryInterface 查询接口
|
||||
* @param {import('sequelize')} Sequelize Sequelize 实例
|
||||
* @return {Promise<void>} 无返回值
|
||||
*/
|
||||
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<void>} 无返回值
|
||||
*/
|
||||
async down(queryInterface) {
|
||||
const tableName = 'wms_express_interface';
|
||||
const columns = await queryInterface.describeTable(tableName);
|
||||
|
||||
if (!columns.paymode) {
|
||||
return;
|
||||
}
|
||||
|
||||
await queryInterface.removeColumn(tableName, 'paymode');
|
||||
},
|
||||
};
|
||||
@ -0,0 +1,46 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 为快递接口配置表新增服务商ID字段。
|
||||
* @param {import('sequelize').QueryInterface} queryInterface 查询接口
|
||||
* @param {import('sequelize')} Sequelize Sequelize 实例
|
||||
* @return {Promise<void>} 无返回值
|
||||
*/
|
||||
module.exports = {
|
||||
/**
|
||||
* 执行迁移:新增 providerid 字段(幂等)。
|
||||
* @param {import('sequelize').QueryInterface} queryInterface 查询接口
|
||||
* @param {import('sequelize')} Sequelize Sequelize 实例
|
||||
* @return {Promise<void>} 无返回值
|
||||
*/
|
||||
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<void>} 无返回值
|
||||
*/
|
||||
async down(queryInterface) {
|
||||
const tableName = 'wms_express_interface';
|
||||
const columns = await queryInterface.describeTable(tableName);
|
||||
|
||||
if (!columns.providerid) {
|
||||
return;
|
||||
}
|
||||
|
||||
await queryInterface.removeColumn(tableName, 'providerid');
|
||||
},
|
||||
};
|
||||
@ -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<Set<string>>} 表名集合。
|
||||
*/
|
||||
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<Set<string>>} 索引名集合。
|
||||
*/
|
||||
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<void>} 无返回值。
|
||||
*/
|
||||
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<void>} 无返回值。
|
||||
*/
|
||||
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<void>} 无返回值。
|
||||
*/
|
||||
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<void>} 无返回值。
|
||||
*/
|
||||
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<void>} 无返回值。
|
||||
*/
|
||||
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<void>} 无返回值。
|
||||
*/
|
||||
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);
|
||||
}
|
||||
},
|
||||
};
|
||||
@ -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<void>}
|
||||
*/
|
||||
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<void>}
|
||||
*/
|
||||
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`
|
||||
);
|
||||
}
|
||||
};
|
||||
12
db_query.js
12
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) {}
|
||||
|
||||
|
||||
@ -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"
|
||||
}
|
||||
]
|
||||
|
||||
@ -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"
|
||||
}
|
||||
]
|
||||
|
||||
1605
methods/openapi.json
1605
methods/openapi.json
File diff suppressed because it is too large
Load Diff
1865
methods/system.json
1865
methods/system.json
File diff suppressed because it is too large
Load Diff
@ -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);
|
||||
});
|
||||
|
||||
@ -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: '深圳市南山区',
|
||||
|
||||
@ -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);
|
||||
|
||||
@ -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',
|
||||
});
|
||||
}, /暂未实现授权会话换取能力/);
|
||||
}, /获取授权失败:接口异常/);
|
||||
});
|
||||
});
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user