feat: sync workspace changes

This commit is contained in:
liufumingren 2026-04-16 20:00:01 +08:00
parent d442b91ca1
commit 068d760224
147 changed files with 20275 additions and 2427 deletions

View File

@ -1 +0,0 @@
db/

View File

@ -38,7 +38,9 @@ is_background: false
- 公共请求头变化
- 鉴权方式变化
- 每次 API 接口变更(新增 / 修改 / 删除 method、参数、响应、错误码、header、鉴权等)后,除了更新 `methods/*.json` / `docs/*.md`,**还必须追加一条变更记录到对应的 `methods/changes/<docName>.json` 数组**
- 修补json文件时必须强校验 JSON格式的正确性,确保不会引入格式错误导致无法解析的情况
- 默认禁止直接手写 `methods/*.json` / `methods/changes/*.json`,必须先按 `docs/api-doc-update-workflow.md` 生成固定 spec,再执行 `npm run doc:api:update -- --spec=<path>`
- 正式写入前必须先执行 `npm run doc:api:update -- --spec=<path> --dry-run`
- 修补 JSON 文件时必须强校验 JSON 格式正确性,确保不会引入无法解析的问题
- `methods/*.json` 仍是 SSOT,`methods/changes/*.json` 仅记录差异历史
- 变更记录建议字段至少包含:`version`、`date`、`summary`、`methods`、`notes`
5. 如 system 入参有变化,可执行:
@ -60,11 +62,11 @@ node .\script\tmp-struct-system-params.cjs
## 推荐工作流
1. 先定位代码真实实现与调用链
2. 找到对应的 `methods/*.json` / `docs/*.md`
3. 以代码和测试结果为准更新文档
4. 更新文档后同步追加对应的 `methods/changes/<docName>.json` 变更记录
5. 校验 method 名称、参数、响应与代码一致
6. 必要时验证 JSON 格式可正常解析
2. 如 system 入参结构变化,可先执行 `node .\script\tmp-struct-system-params.cjs`
3. 按 `docs/api-doc-update-workflow.md` 生成固定 spec JSON
4. 先执行 `npm run doc:api:update -- --spec=<path> --dry-run`
5. 确认后执行 `npm run doc:api:update -- --spec=<path>` 写入 `methods/*.json` 与 `methods/changes/*.json`
6. 再补充 `docs/*.md` / `README.md`,并校验 method 名称、参数、响应与代码一致
## 常用验证方式
@ -74,6 +76,12 @@ node .\script\tmp-struct-system-params.cjs
node -e "JSON.parse(require('fs').readFileSync('methods/system.json','utf8')); console.log('system.json OK')"
```
### 通过固定 spec dry-run 校验 API 文档写入
```powershell
npm run doc:api:update -- --spec=temp/api-doc-update.json --dry-run
```
### 核对 method 是否已登记
```powershell
@ -85,8 +93,8 @@ Select-String -Path "methods/system.json" -Pattern "storage.receiving.bindDetail
```text
请使用 wms-doc-agent 帮我:
1) 根据代码现状整理接口或业务文档
2) 同步 methods/*.json / docs/*.md / README
3) 校验文档与实现一致
2) 先按 docs/api-doc-update-workflow.md 生成固定 spec,再执行 npm run doc:api:update
3) 同步 docs/*.md / README,并校验文档与实现一致
```
## 输出要求
@ -95,6 +103,7 @@ Select-String -Path "methods/system.json" -Pattern "storage.receiving.bindDetail
- 先给结论,再给修改文件、关键字段、验证结果
- 若同步了 `methods/*.json`,明确说明 method 名称与变更点
- 若接口有变更,需说明是否已同步写入 `methods/changes/*.json`
- 若执行了文档脚本,需明确说明 spec 路径、dry-run 结果与正式写入结果
## 结论

View File

@ -38,7 +38,9 @@ model: GPT-5 mini (copilot)
- 公共请求头变化
- 鉴权方式变化
- 每次 API 接口变更(新增 / 修改 / 删除 method、参数、响应、错误码、header、鉴权等)后,除了更新 `methods/*.json` / `docs/*.md`,**还必须追加一条变更记录到对应的 `methods/changes/<docName>.json` 数组**
- 修补json文件时必须强校验 JSON格式的正确性,确保不会引入格式错误导致无法解析的情况
- 默认禁止直接手写 `methods/*.json` / `methods/changes/*.json`,必须先按 `docs/api-doc-update-workflow.md` 生成固定 spec,再执行 `npm run doc:api:update -- --spec=<path>`
- 正式写入前必须先执行 `npm run doc:api:update -- --spec=<path> --dry-run`
- 修补 JSON 文件时必须强校验 JSON 格式正确性,确保不会引入无法解析的问题
- `methods/*.json` 仍是 SSOT,`methods/changes/*.json` 仅记录差异历史
- 变更记录建议字段至少包含:`version`、`date`、`summary`、`methods`、`notes`
5. 如 system 入参有变化,可执行:
@ -60,11 +62,11 @@ node .\script\tmp-struct-system-params.cjs
## 推荐工作流
1. 先定位代码真实实现与调用链
2. 找到对应的 `methods/*.json` / `docs/*.md`
3. 以代码和测试结果为准更新文档
4. 更新文档后同步追加对应的 `methods/changes/<docName>.json` 变更记录
5. 校验 method 名称、参数、响应与代码一致
6. 必要时验证 JSON 格式可正常解析
2. 如 system 入参结构变化,可先执行 `node .\script\tmp-struct-system-params.cjs`
3. 按 `docs/api-doc-update-workflow.md` 生成固定 spec JSON
4. 先执行 `npm run doc:api:update -- --spec=<path> --dry-run`
5. 确认后执行 `npm run doc:api:update -- --spec=<path>` 写入 `methods/*.json` 与 `methods/changes/*.json`
6. 再补充 `docs/*.md` / `README.md`,并校验 method 名称、参数、响应与代码一致
## 常用验证方式
@ -74,6 +76,12 @@ node .\script\tmp-struct-system-params.cjs
node -e "JSON.parse(require('fs').readFileSync('methods/system.json','utf8')); console.log('system.json OK')"
```
### 通过固定 spec dry-run 校验 API 文档写入
```powershell
npm run doc:api:update -- --spec=temp/api-doc-update.json --dry-run
```
### 核对 method 是否已登记
```powershell
@ -85,8 +93,8 @@ Select-String -Path "methods/system.json" -Pattern "storage.receiving.bindDetail
```text
请使用 wms-doc-agent 帮我:
1) 根据代码现状整理接口或业务文档
2) 同步 methods/*.json / docs/*.md / README
3) 校验文档与实现一致
2) 先按 docs/api-doc-update-workflow.md 生成固定 spec,再执行 npm run doc:api:update
3) 同步 docs/*.md / README,并校验文档与实现一致
```
## 输出要求
@ -95,6 +103,7 @@ Select-String -Path "methods/system.json" -Pattern "storage.receiving.bindDetail
- 先给结论,再给修改文件、关键字段、验证结果
- 若同步了 `methods/*.json`,明确说明 method 名称与变更点
- 若接口有变更,需说明是否已同步写入 `methods/changes/*.json`
- 若执行了文档脚本,需明确说明 spec 路径、dry-run 结果与正式写入结果
## 结论

View File

@ -101,8 +101,8 @@ GitHub Copilot 读取 `.github/agents/*.agent.md`;Cursor 使用 `.cursor/agent
```text
请使用 wms-doc-agent 帮我:
1) 根据代码现状整理接口或业务文档
2) 同步 methods/*.json / docs/*.md / README
3) 校验文档与实现一致
2) 先按 docs/api-doc-update-workflow.md 生成固定 spec,再执行 npm run doc:api:update
3) 同步 docs/*.md / README,并校验 methods/*.json 与 methods/changes/*.json 可解析
```
### 3.6 混合任务 / 不确定归属(强制走 Dispatcher)
@ -196,7 +196,9 @@ Redis 相关能力文档已统一移交给 `wms-redis-agent`。
执行要求(强制):
- **涉及文档编写或同步的任何问题,必须使用 `wms-doc-agent`**
- 文档必须以代码实现、测试结果和现有 JSON 文档为准,不得凭空编写
- system 参数变化可执行:`node .\script\tmp-struct-system-params.cjs`
- 默认禁止直接手写 `methods/*.json` 和 `methods/changes/*.json`;必须先按 [docs/api-doc-update-workflow.md](docs/api-doc-update-workflow.md) 组织 spec,再执行 `npm run doc:api:update -- --spec=<path>`
- system 参数变化可先执行:`node .\script\tmp-struct-system-params.cjs`
- 正式写入前必须先执行:`npm run doc:api:update -- --spec=<path> --dry-run`
- 具体工作流统一见:`.github/agents/文档.agent.md`
## 9. 测试能力移交规则

View File

@ -100,14 +100,20 @@ npm run dev
建议流程:
1. 先完成代码改动(controller/service/model)
2. 同步维护 `methods/system.json` 或 `methods/qimen.json`
3. system 参数改动后执行:
2. 按 [docs/api-doc-update-workflow.md](docs/api-doc-update-workflow.md) 复制固定 spec 到 `temp/`,默认通过 `npm run doc:api:update -- --spec=...` 写入 `methods/*.json`
3. system 参数改动后可先执行:
```powershell
node .\script\tmp-struct-system-params.cjs
```
4. 补充自动提取无法覆盖的信息(description/response/errors/枚举约束)
4. 先执行:
```powershell
npm run doc:api:update -- --spec=temp/api-doc-update.json --dry-run
```
5. 确认无误后执行正式写入,再补充自动提取无法覆盖的信息(description/response/errors/枚举约束)
## 配置说明

23
app.js
View File

@ -1,6 +1,7 @@
// app.js
const path = require('path');
const LocalFileWriter = require('./app/lib/file_writer');
const ensureOrderDeliverySelfCheck = require('./app/lib/order_delivery_selfcheck');
/**
* 挂载应用级扩展能力。
@ -16,30 +17,36 @@ module.exports = app => {
app.logger.info('✅ fileWriter 已挂载到 app.fileWriter');
// 初始化工厂
app.beforeStart(async () => {
// skip factory init when model layer is absent (e.g. during tests)
const OrderDeliveryFactory = require('./app/model/order_delivery_factory');
app.OrderDeliveryFactory = OrderDeliveryFactory(app);
// skip 热区工厂 when model layer is absent (e.g. 部分单测)
if (!app.model) {
app.logger.info('⚠️ skipping factory init: app.model not available');
app.logger.info('⚠️ skipping OrderDelivery/OrderItems factory init: app.model not available');
return;
}
try {
const OrderDeliveryFactory = require('./app/model/order_delivery_factory');
const OrderItemsFactory = require('./app/model/order_items_factory');
app.OrderDeliveryFactory = OrderDeliveryFactory(app);
app.model.OrderDeliveryFactory = app.OrderDeliveryFactory;
app.OrderItemsFactory = OrderItemsFactory(app);
app.model.OrderItemsFactory = app.OrderItemsFactory;
app.logger.info('✅ 工厂类初始化完成');
//await ensureOrderDeliverySelfCheck(app);
} catch (error) {
app.logger.error('❌ 工厂类初始化失败:', error);
}
// 验证缓存方法
if (typeof app.setCacheAsync === 'function') {
app.setCacheAsync('system', 'eggjs');
await app.setCacheAsync('system', 'wms', 10);
const system = await app.getCacheAsync('system');
app.logger.info('✅ 缓存方法验证通过' + system);
if (system !== 'wms') {
app.logger.error('❌ 缓存方法验证失败: setCacheAsync/getCacheAsync 不一致');
} else {
app.logger.info(`✅ 缓存方法验证通过${system}`);
}
}
app.logger.info('✅ l类型' + typeof app.Message);
});
};

View File

@ -13,6 +13,97 @@ function escapeHtml(value) {
.replace(/'/g, '&#39;');
}
/**
* 清洗 window 标签使用的跳转地址,避免注入危险协议或控制字符。
* @param {string} value 待清洗的地址。
* @return {string} 允许使用的地址,非法时返回空字符串。
*/
function sanitizeWindowHref(value) {
const href = String(value || '').trim();
if (!href) {
return '';
}
const hasControlCharacter = Array.from(href).some(character => {
const code = character.charCodeAt(0);
return code <= 0x1f || code === 0x7f;
});
if (hasControlCharacter || /^(javascript|data|vbscript):/i.test(href)) {
return '';
}
return href;
}
/**
* 从 window 标签属性中提取跳转地址。
* @param {string} attributeText 标签属性文本。
* @return {string} 提取到的地址,未找到时返回空字符串。
*/
function extractWindowHref(attributeText) {
const attributes = String(attributeText || '');
const match = attributes.match(/(?:href|data-href|data-window-href)\s*=\s*("([^"]*)"|'([^']*)')/i);
if (!match) {
return '';
}
return match[2] || match[3] || '';
}
/**
* 渲染可点击的 window 自定义元素。
* @param {string} label 元素展示文案。
* @param {string} href 点击后打开的地址。
* @param {string} [className] 额外样式类名。
* @return {string} 生成的 HTML 片段。
*/
function renderWindowElement(label, href, className = '') {
const safeHref = sanitizeWindowHref(href);
const safeLabel = escapeHtml(label || safeHref);
if (!safeHref) {
return safeLabel;
}
const classes = [ 'window-link' ];
if (className) {
classes.push(className);
}
return `<window class="${classes.join(' ')}" role="link" tabindex="0" data-window-href="${escapeHtml(safeHref)}">${safeLabel}</window>`;
}
/**
* 将文本中的 <window> 标签安全渲染为可点击元素。
* @param {string} value 原始文本。
* @return {string} 处理后的 HTML。
*/
function renderTextWithWindowTags(value) {
const text = String(value || '');
if (!text.includes('<window')) {
return escapeHtml(text);
}
const pattern = /<window\b([^>]*)>([\s\S]*?)<\/window>/gi;
let lastIndex = 0;
let rendered = '';
let match;
while ((match = pattern.exec(text)) !== null) {
rendered += escapeHtml(text.slice(lastIndex, match.index));
const attributes = match[1] || '';
const content = match[2] || '';
const href = sanitizeWindowHref(extractWindowHref(attributes) || content.trim());
const label = content.trim() || href;
rendered += renderWindowElement(label, href);
lastIndex = pattern.lastIndex;
}
rendered += escapeHtml(text.slice(lastIndex));
return rendered;
}
function toArray(value) {
return Array.isArray(value) ? value : [];
}
@ -36,6 +127,302 @@ function getDocChangesFilePath(app, docName) {
return path.join(app.baseDir, 'methods', 'changes', `${docName}.json`);
}
/**
* 获取 docs 目录的绝对路径。
* @param {Egg.Application} app Egg 应用实例。
* @return {string} docs 根目录绝对路径。
*/
function getDocsRootPath(app) {
return path.resolve(app.baseDir, 'docs');
}
/**
* 递归解码 URL 路径片段,尽量还原编码穿越路径。
* @param {string} input 待解码的路径片段。
* @return {string|null} 解码后的路径片段,解码失败时返回 null。
*/
function decodeDocsPath(input) {
let value = String(input || '').trim();
if (!value) {
return '';
}
for (let index = 0; index < 3; index += 1) {
try {
const decoded = decodeURIComponent(value);
if (decoded === value) {
break;
}
value = decoded;
} catch (error) {
return null;
}
}
return value;
}
/**
* 将 docs 相对路径转换为可访问 URL。
* @param {string} relativePath docs 相对路径。
* @return {string} 可直接用于 href 的路径。
*/
function toDocsHref(relativePath) {
return String(relativePath || '')
.split(/[\\/]+/)
.filter(Boolean)
.map(segment => encodeURIComponent(segment))
.join('/');
}
/**
* 按扩展名返回 docs 文件的响应类型。
* @param {string} filePath 文件绝对路径。
* @return {string} Content-Type 值。
*/
function getDocsContentType(filePath) {
const ext = path.extname(filePath).toLowerCase();
if (ext === '.md' || ext === '.markdown') {
return 'text/markdown; charset=utf-8';
}
if (ext === '.json') {
return 'application/json; charset=utf-8';
}
return 'text/plain; charset=utf-8';
}
/**
* 解析并校验 docs 文件路径,阻止路径穿越。
* @param {Egg.Application} app Egg 应用实例。
* @param {string} relativePath docs 相对路径。
* @return {{ ok: boolean, filePath?: string, relativePath?: string, message?: string }} 解析结果。
*/
function resolveDocsFilePath(app, relativePath) {
const decodedPath = decodeDocsPath(relativePath);
if (decodedPath === null || !decodedPath) {
return {
ok: false,
message: '无效文档路径',
};
}
if (decodedPath.includes('\\') || path.isAbsolute(decodedPath)) {
return {
ok: false,
message: '无效文档路径',
};
}
const docsRootPath = getDocsRootPath(app);
const filePath = path.resolve(docsRootPath, decodedPath);
const relativeToRoot = path.relative(docsRootPath, filePath);
if (relativeToRoot.startsWith('..') || path.isAbsolute(relativeToRoot)) {
return {
ok: false,
message: '路径越界',
};
}
return {
ok: true,
filePath,
relativePath: decodedPath,
};
}
/**
* 递归收集 docs 目录下的所有文件。
* @param {string} dirPath 当前扫描目录。
* @param {string} baseDir docs 根目录。
* @return {Promise<Array<{ relativePath: string, filePath: string }>>} 文件列表。
*/
async function collectDocsFiles(dirPath, baseDir) {
const entries = await fs.readdir(dirPath, { withFileTypes: true });
const files = [];
for (const entry of entries) {
const entryPath = path.join(dirPath, entry.name);
if (entry.isDirectory()) {
const nestedFiles = await collectDocsFiles(entryPath, baseDir);
files.push(...nestedFiles);
continue;
}
if (entry.isFile()) {
files.push({
relativePath: path.relative(baseDir, entryPath),
filePath: entryPath,
});
}
}
return files;
}
/**
* 生成 docs 索引页 HTML。
* @param {Array<{ relativePath: string }>} files docs 文件列表。
* @return {string} HTML 文档。
*/
function renderDocsIndexPage(files) {
const listHtml = files.length
? files.map(file => {
const href = `/docs/${toDocsHref(file.relativePath)}`;
return `<li>${renderWindowElement(file.relativePath, href, 'doc-file-link')}</li>`;
}).join('')
: '<li class="muted">docs 目录下暂无文件</li>';
return `<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Docs 索引</title>
<style>
:root {
color-scheme: light;
--bg: #f5f7fb;
--panel: #ffffff;
--text: #182230;
--muted: #637083;
--line: #d9e1ec;
--accent: #1756b3;
}
* { box-sizing: border-box; }
body {
margin: 0;
font-family: "Segoe UI", "PingFang SC", "Microsoft YaHei", sans-serif;
color: var(--text);
background: linear-gradient(180deg, #eef4ff 0%, var(--bg) 220px, var(--bg) 100%);
}
main {
max-width: 1080px;
margin: 0 auto;
padding: 32px 20px 40px;
}
.hero {
background: var(--panel);
border: 1px solid var(--line);
border-radius: 16px;
padding: 24px;
box-shadow: 0 10px 30px rgba(22, 50, 98, 0.08);
}
h1 {
margin: 0 0 8px;
font-size: 28px;
}
p {
margin: 0;
color: var(--muted);
line-height: 1.6;
}
ul {
list-style: none;
padding: 0;
margin: 22px 0 0;
display: grid;
gap: 10px;
}
li a {
display: block;
padding: 12px 14px;
border-radius: 12px;
border: 1px solid var(--line);
background: #fbfcff;
color: var(--accent);
text-decoration: none;
word-break: break-all;
}
window.window-link {
display: block;
padding: 12px 14px;
border-radius: 12px;
border: 1px solid var(--line);
background: #fbfcff;
color: var(--accent);
text-decoration: none;
word-break: break-all;
}
window.window-link:hover {
border-color: #b9cdf0;
background: #f2f7ff;
}
window.window-link:focus {
outline: 2px solid #8fb4ea;
outline-offset: 2px;
}
.muted {
color: var(--muted);
}
</style>
</head>
<body>
<main>
<section class="hero">
<h1>docs 目录索引</h1>
<p>以下文件来自 docs 根目录,点击即可直接查看对应内容。</p>
<ul>${listHtml}</ul>
</section>
</main>
<script>
(function() {
function openWindowHref(target) {
var href = target && target.getAttribute('data-window-href');
if (!href) {
return;
}
var popup = window.open(href, '_blank', 'noopener,noreferrer');
if (popup) {
popup.opener = null;
popup.focus();
}
}
document.addEventListener('click', function(event) {
var target = event.target.closest('[data-window-href]');
if (!target) {
return;
}
event.preventDefault();
openWindowHref(target);
});
document.addEventListener('keydown', function(event) {
var target = event.target.closest('[data-window-href]');
if (!target) {
return;
}
if (event.key !== 'Enter' && event.key !== ' ') {
return;
}
event.preventDefault();
openWindowHref(target);
});
})();
</script>
</body>
</html>`;
}
/**
* 生成 docs 文件内容响应。
* @param {Egg.Context} ctx 当前请求上下文。
* @param {string} filePath 文件绝对路径。
* @return {Promise<void>} 无返回值。
*/
async function sendDocsFile(ctx, filePath) {
const content = await fs.readFile(filePath, 'utf8');
ctx.set('Content-Type', getDocsContentType(filePath));
ctx.body = content;
}
function normalizeGroups(docData) {
if (docData && docData.methods && Array.isArray(docData.methods.groups)) {
return docData.methods.groups.map(group => ({
@ -56,6 +443,12 @@ function normalizeGroups(docData) {
return [];
}
/**
* 渲染键值表格。
* @param {Array<object>} items 数据项列表。
* @param {{ name: string, type: string, required: string, description: string }} keyMap 字段映射。
* @return {string} 表格行 HTML。
*/
function renderKeyValueRows(items, keyMap) {
if (!items.length) {
return '<tr><td colspan="4" class="muted">暂无数据</td></tr>';
@ -66,11 +459,16 @@ function renderKeyValueRows(items, keyMap) {
<td>${escapeHtml(item[keyMap.name] || '')}</td>
<td>${escapeHtml(item[keyMap.type] || '')}</td>
<td>${item[keyMap.required] ? '是' : '否'}</td>
<td>${escapeHtml(item[keyMap.description] || '')}</td>
<td>${renderTextWithWindowTags(item[keyMap.description] || '')}</td>
</tr>`;
}).join('');
}
/**
* 渲染全局 Header 控件区域。
* @param {Array<object>} globalHeaders 全局 Header 定义。
* @return {string} HTML 片段。
*/
function renderGlobalHeadersControls(globalHeaders) {
const headers = toArray(globalHeaders);
if (!headers.length) {
@ -94,11 +492,18 @@ function renderGlobalHeadersControls(globalHeaders) {
return `<label class="global-header-item">
<span>${escapeHtml(name)}${required ? ' *' : ''}</span>
${field}
<small class="muted">${escapeHtml(description)} (${escapeHtml(type)})</small>
<small class="muted">${renderTextWithWindowTags(description)} (${escapeHtml(type)})</small>
</label>`;
}).join('')}</div>`;
}
/**
* 渲染单个接口卡片。
* @param {object} item 接口定义。
* @param {string} entryPath 统一入口路径。
* @param {string} moduleName 文档所属模块名。
* @return {string} HTML 片段。
*/
function renderMethodCard(item, entryPath, moduleName) {
const headers = toArray(item.headers);
const params = toArray(item.params);
@ -115,7 +520,7 @@ function renderMethodCard(item, entryPath, moduleName) {
<div class="method-header">
<div>
<h3>${escapeHtml(methodName)}</h3>
<p class="method-desc">${escapeHtml(description)}</p>
<p class="method-desc">${renderTextWithWindowTags(description)}</p>
</div>
<div class="badges">
<span class="badge">入口: ${escapeHtml(entryPath)}</span>
@ -196,6 +601,11 @@ function renderMethodCard(item, entryPath, moduleName) {
</section>`;
}
/**
* 渲染 API 文档页面。
* @param {{ docName: string, docData: object, groups: Array<object>, docs: Array<string>, entryPath: string }} options 渲染参数。
* @return {string} HTML 文档。
*/
function renderHtmlPage({
docName,
docData,
@ -446,6 +856,20 @@ function renderHtmlPage({
background: #eef5ff;
color: #123e79;
}
.window-link {
display: inline-flex;
align-items: center;
gap: 4px;
cursor: pointer;
user-select: none;
}
.window-link:hover {
text-decoration: underline;
}
.window-link:focus {
outline: 2px solid #8fb4ea;
outline-offset: 2px;
}
.doc-content {
min-width: 0;
}
@ -590,8 +1014,8 @@ function renderHtmlPage({
<div class="doc-tools">
<h3>文档资源</h3>
<div class="doc-tools-actions">
<a class="tab" href="${escapeHtml(changesUrl)}" target="_blank" rel="noreferrer">打开变更记录</a>
<a class="tab" href="${escapeHtml(rawUrl)}" target="_blank" rel="noreferrer">打开原文 JSON</a>
${renderWindowElement('打开变更记录', changesUrl, 'doc-resource-link')}
${renderWindowElement('打开原文 JSON', rawUrl, 'doc-resource-link')}
<button type="button" id="previewChangesBtn">预览变更记录</button>
<button type="button" id="previewRawBtn">预览原文 JSON</button>
</div>
@ -633,6 +1057,19 @@ function renderHtmlPage({
var changesUrl = ${JSON.stringify(changesUrl)};
var rawUrl = ${JSON.stringify(rawUrl)};
function openWindowHref(target) {
var href = target && target.getAttribute('data-window-href');
if (!href) {
return;
}
var popup = window.open(href, '_blank', 'noopener,noreferrer');
if (popup) {
popup.opener = null;
popup.focus();
}
}
function nowTimestamp() {
return Math.floor(Date.now() / 1000);
}
@ -850,6 +1287,30 @@ function renderHtmlPage({
});
}
document.addEventListener('click', function(event) {
var target = event.target.closest('[data-window-href]');
if (!target) {
return;
}
event.preventDefault();
openWindowHref(target);
});
document.addEventListener('keydown', function(event) {
var target = event.target.closest('[data-window-href]');
if (!target) {
return;
}
if (event.key !== 'Enter' && event.key !== ' ') {
return;
}
event.preventDefault();
openWindowHref(target);
});
document.addEventListener('click', async function(event) {
var btn = event.target.closest('.send-btn');
if (!btn) return;
@ -927,6 +1388,68 @@ function renderHtmlPage({
}
class DocsController extends Controller {
/**
* 返回 docs 目录索引页面。
* @return {Promise<void>} 无返回值。
*/
async docsIndex() {
const { ctx } = this;
try {
const docsRootPath = getDocsRootPath(this.app);
const files = await collectDocsFiles(docsRootPath, docsRootPath);
files.sort((left, right) => left.relativePath.localeCompare(right.relativePath, 'zh-Hans-CN'));
ctx.set('Content-Type', 'text/html; charset=utf-8');
ctx.body = renderDocsIndexPage(files);
} catch (error) {
ctx.status = 500;
ctx.body = {
code: 500,
message: '读取 docs 目录失败',
error: error.message,
};
}
}
/**
* 读取 docs 目录下的指定文件。
* @return {Promise<void>} 无返回值。
*/
async docsFile() {
const { ctx } = this;
const rawRelativePath = ctx.params[0] || ctx.params.relPath || ctx.params.path || '';
const resolved = resolveDocsFilePath(this.app, rawRelativePath);
if (!resolved.ok) {
ctx.status = 400;
ctx.body = {
code: 400,
message: resolved.message || '无效文档路径',
};
return;
}
try {
await sendDocsFile(ctx, resolved.filePath);
} catch (error) {
if (error.code === 'ENOENT') {
ctx.status = 404;
ctx.body = {
code: 404,
message: `未找到 docs 文件: ${resolved.relativePath}`,
};
return;
}
ctx.status = 500;
ctx.body = {
code: 500,
message: '读取 docs 文件失败',
error: error.message,
};
}
}
async list() {
const { ctx } = this;
try {

View File

@ -9,12 +9,29 @@ class HomeController extends Controller {
await this.ctx.service.systems.print.index.test();
this.ctx.body = 'ok';
}
/**
* Polo API 测试入口,直接透传 PoloApiService.test() 的真实返回结果。
*
* @return {Promise<void>} 无返回值,响应结果直接写入 ctx.body。
*/
async testPoloApi() {
const {
ctx,
} = this;
const result = await ctx.service.systems.poloApi.test();
ctx.body = result;
}
async index() {
const {
ctx,
} = this;
ctx.body = 'pong';
}
/**
* 处理奇门统一入口请求,完成参数校验、XML 解析、仓库编码提取与方法分发。
* @return {Promise<void>} 无返回值。
*/
async qimen() {
const {
ctx,
@ -97,7 +114,16 @@ class HomeController extends Controller {
// 解析XML数据
const xmlArray = await service.qimen.parseXmlToArray(xmlData);
xmlArray.app_key = appkey;
let warehouseCode = xmlArray.request.warehouseCode || '';
const warehouseCode = this.getQimenWarehouseCode(xmlArray);
if (!warehouseCode) {
const errorMsg = 'XML数据格式错误,无法提取有效的warehouseCode';
const responseFormat = getParams.format || 'xml';
const response = this.errorResponse(errorMsg, responseFormat);
ctx.body = response;
ctx.type = responseFormat === 'xml' ? 'application/xml' : 'application/json';
return;
}
logData.body = xmlData;
const erpName = await service.qimen.getErpName(appkey);
@ -105,16 +131,6 @@ class HomeController extends Controller {
warehouseCode: '',
ownerCode: '',
};
if (!warehouseCode || !customerId) {
// 入库单提取
try {
warehouseCode = xmlArray.request?.entryOrder?.warehouseCode ||
xmlArray.request?.deliveryOrder?.warehouseCode ||
'';
} catch (e) {
throw new Error('XML数据格式错误,无法提取warehouseCode');
}
}
if (warehouseCode && customerId) {
// 验证接口是否存在且启用
api_info = await service.qimen.validateApi(appkey, customerId, warehouseCode);
@ -187,6 +203,116 @@ class HomeController extends Controller {
}
}
/**
* 归一化奇门字段值,过滤空白内容和占位符字符串。
* @param {string|number|null|undefined} value 待处理字段值。
* @return {string} 归一化后的字段值。
*/
normalizeQimenFieldValue(value) {
if (value === null || value === undefined) {
return '';
}
const normalizedValue = String(value).trim();
if (!normalizedValue || normalizedValue === 'warehouseCode') {
return '';
}
return normalizedValue;
}
/**
* 递归扫描奇门 XML 树,提取指定字段的有效值,只匹配字段名对应的节点。
* @param {Object|Array|string|number|null|undefined} node 待扫描节点。
* @param {string} fieldName 目标字段名。
* @param {Set<Object>} [visited=new Set()] 循环引用保护集合。
* @return {string} 找到的有效字段值。
*/
findQimenFieldValue(node, fieldName, visited = new Set()) {
if (node === null || node === undefined) {
return '';
}
if (typeof node !== 'object') {
return '';
}
if (visited.has(node)) {
return '';
}
visited.add(node);
if (Array.isArray(node)) {
for (const item of node) {
const value = this.findQimenFieldValue(item, fieldName, visited);
if (value) {
return value;
}
}
return '';
}
if (Object.prototype.hasOwnProperty.call(node, fieldName)) {
const directValue = this.normalizeQimenFieldValue(node[fieldName]);
if (directValue) {
return directValue;
}
const nestedValue = this.findQimenFieldValue(node[fieldName], fieldName, visited);
if (nestedValue) {
return nestedValue;
}
}
for (const [ key, value ] of Object.entries(node)) {
if (key === fieldName) {
continue;
}
if (value === null || value === undefined) {
continue;
}
if (typeof value !== 'object') {
continue;
}
const foundValue = this.findQimenFieldValue(value, fieldName, visited);
if (foundValue) {
return foundValue;
}
}
return '';
}
/**
* 从奇门请求体中提取有效的仓库编码,优先读取 request 下的固定路径,再回退到递归扫描。
* @param {Object} xmlArray 解析后的 XML 数据。
* @return {string} 有效的仓库编码。
*/
getQimenWarehouseCode(xmlArray) {
const request = xmlArray?.request || xmlArray || {};
const fixedPaths = [
request?.deliveryOrder?.warehouseCode,
request?.entryOrder?.warehouseCode,
request.warehouseCode,
];
for (const value of fixedPaths) {
const normalizedValue = this.normalizeQimenFieldValue(value);
if (normalizedValue) {
return normalizedValue;
}
}
return this.findQimenFieldValue(request, 'warehouseCode')
|| this.findQimenFieldValue(xmlArray, 'warehouseCode')
|| '';
}
validateParams(params) {
const required = [ 'method', 'v', 'format', 'timestamp' ];

View File

@ -1,5 +1,219 @@
const soap = require('soap');
const businessDict = require('../dict/businessDict');
const LOCAL_CACHE_CLEANUP_INTERVAL_MS = 60 * 1000;
const LOCAL_CACHE_STATE_KEY = '__wmsLocalCacheState';
/**
* 获取缓存日志记录器。
*
* @param {Object} app 应用实例。
* @return {Object|null} 日志对象。
*/
function getCacheLogger(app) {
return app && (app.logger || app.coreLogger) ? (app.logger || app.coreLogger) : null;
}
/**
* 获取或初始化进程内缓存状态。
*
* @param {Object} app 应用实例。
* @return {Object|null} 进程内缓存状态。
*/
function getLocalCacheState(app) {
if (!app) {
return null;
}
if (!app[LOCAL_CACHE_STATE_KEY]) {
app[LOCAL_CACHE_STATE_KEY] = {
store: new Map(),
cleanupTimer: null,
lastCleanupAt: 0,
};
}
return app[LOCAL_CACHE_STATE_KEY];
}
/**
* 规范化缓存过期秒数。
*
* @param {*} expireSeconds 过期秒数。
* @return {number} 规范化后的秒数。
*/
function normalizeExpireSeconds(expireSeconds) {
const ttl = Number(expireSeconds);
if (!Number.isFinite(ttl) || ttl <= 0) {
return 0;
}
return Math.floor(ttl);
}
/**
* 复制缓存值,避免进程内缓存被外部引用直接修改。
*
* @param {*} value 缓存值。
* @return {*} 复制后的缓存值。
*/
function cloneCacheValue(value) {
if (value === null || value === undefined) {
return value;
}
try {
return JSON.parse(JSON.stringify(value));
} catch (error) {
return value;
}
}
/**
* 清理已经过期的进程内缓存。
*
* @param {Object} state 进程内缓存状态。
* @return {number} 清理的条目数。
*/
function cleanupLocalCache(state) {
if (!state || !state.store) {
return 0;
}
const now = Date.now();
let removedCount = 0;
for (const [ cacheKey, cacheEntry ] of state.store.entries()) {
if (!cacheEntry || cacheEntry.expireAt <= now) {
state.store.delete(cacheKey);
removedCount += 1;
}
}
state.lastCleanupAt = now;
return removedCount;
}
/**
* 启动进程内缓存的定时清理任务。
*
* @param {Object} app 应用实例。
* @return {Object|null} 进程内缓存状态。
*/
function ensureLocalCacheCleanupTimer(app) {
const state = getLocalCacheState(app);
if (!state || state.cleanupTimer) {
return state;
}
state.cleanupTimer = setInterval(() => {
cleanupLocalCache(state);
}, LOCAL_CACHE_CLEANUP_INTERVAL_MS);
if (state.cleanupTimer && typeof state.cleanupTimer.unref === 'function') {
state.cleanupTimer.unref();
}
return state;
}
/**
* 获取 Redis 缓存客户端。
*
* @param {Object} app 应用实例。
* @return {Object|null} Redis 缓存客户端。
*/
function getRedisCacheClient(app) {
try {
return app && app.redis && typeof app.redis.get === 'function' ? app.redis.get('cache') : null;
} catch (error) {
const logger = getCacheLogger(app);
if (logger && typeof logger.warn === 'function') {
logger.warn('[CacheRedisUnavailable] 获取 Redis 缓存客户端失败', error.message);
}
return null;
}
}
/**
* 将值写入进程内缓存。
*
* @param {Object} app 应用实例。
* @param {string} cacheKey 缓存键。
* @param {*} data 缓存数据。
* @param {number} expireSeconds 过期秒数。
*/
function setLocalCacheValue(app, cacheKey, data, expireSeconds) {
const state = ensureLocalCacheCleanupTimer(app);
if (!state) {
return;
}
const ttl = normalizeExpireSeconds(expireSeconds);
if (ttl <= 0) {
state.store.delete(cacheKey);
return;
}
state.store.set(cacheKey, {
value: cloneCacheValue(data),
expireAt: Date.now() + (ttl * 1000),
});
}
/**
* 从进程内缓存读取值。
*
* @param {Object} app 应用实例。
* @param {string} cacheKey 缓存键。
* @return {*} 缓存值或 null。
*/
function getLocalCacheValue(app, cacheKey) {
const state = getLocalCacheState(app);
if (!state) {
return null;
}
const cacheEntry = state.store.get(cacheKey);
if (!cacheEntry) {
return null;
}
if (cacheEntry.expireAt <= Date.now()) {
state.store.delete(cacheKey);
return null;
}
return cloneCacheValue(cacheEntry.value);
}
/**
* 从进程内缓存删除值。
*
* @param {Object} app 应用实例。
* @param {string} cacheKey 缓存键。
*/
function deleteLocalCacheValue(app, cacheKey) {
const state = getLocalCacheState(app);
if (!state) {
return;
}
state.store.delete(cacheKey);
}
/**
* 将 Redis 返回的数据解析为对象。
*
* @param {string} cacheValue Redis 缓存字符串。
* @return {*} 解析后的值。
*/
function parseRedisCacheValue(cacheValue) {
if (cacheValue === undefined || cacheValue === null) {
return null;
}
return JSON.parse(cacheValue);
}
module.exports = {
get businessDict() {
return businessDict;
@ -50,40 +264,83 @@ module.exports = {
const result = await client[methodName + 'Async'](obj);
return result[0];
} catch (error) {
console.error('Error calling SOAP service:', error);
throw error;
}
},
/**
* 写入缓存。
*
* Redis 可用时优先写入 Redis;当 Redis 不可用或写入失败时,自动降级到进程内缓存。
*
* @param {string} cacheKey 缓存键。
* @param {*} data 缓存数据。
* @param {number} [expireSeconds=300] 过期秒数。
* @return {Promise<void>}
*/
async setCacheAsync(cacheKey, data, expireSeconds = 300) {
const cacheRedis = this.redis && this.redis.get ? this.redis.get('cache') : null;
if (!cacheRedis) {
this.logger.warn('[RedisNotAvailable] Cannot set cache, Redis client is not available');
const ttl = normalizeExpireSeconds(expireSeconds);
const cacheRedis = getRedisCacheClient(this);
if (ttl <= 0) {
if (cacheRedis && typeof cacheRedis.del === 'function') {
try {
await cacheRedis.del(cacheKey);
} catch (error) {
const logger = getCacheLogger(this);
if (logger && typeof logger.warn === 'function') {
logger.warn('[CacheRedisDeleteError] Redis 删除缓存失败', error.message, cacheKey);
}
}
}
deleteLocalCacheValue(this, cacheKey);
return;
}
try {
await cacheRedis.setex(cacheKey, expireSeconds, JSON.stringify(data));
this.logger.debug('[CacheSet] Successfully set cache', cacheKey);
} catch (error) {
this.logger.error('[CacheSetError] Failed to set cache', error.message, cacheKey);
}
},
async getCacheAsync(cacheKey) {
const cacheRedis = this.redis && this.redis.get ? this.redis.get('cache') : null;
if (!cacheRedis) {
this.logger.warn('[RedisNotAvailable] Cannot get cache, Redis client is not available');
return null;
if (cacheRedis && typeof cacheRedis.setex === 'function') {
try {
await cacheRedis.setex(cacheKey, ttl, JSON.stringify(data));
setLocalCacheValue(this, cacheKey, data, ttl);
return;
} catch (error) {
const logger = getCacheLogger(this);
if (logger && typeof logger.warn === 'function') {
logger.warn('[CacheRedisSetError] Redis 写入缓存失败,已降级到进程内缓存', error.message, cacheKey);
}
}
}
try {
const data = await cacheRedis.get(cacheKey);
if (data) {
return JSON.parse(data);
setLocalCacheValue(this, cacheKey, data, ttl);
},
/**
* 读取缓存。
*
* Redis 可用时优先读取 Redis;当 Redis 不可用、读取失败或命中为空时,自动回退到进程内缓存。
*
* @param {string} cacheKey 缓存键。
* @return {Promise<*>} 缓存数据,未命中时返回 null。
*/
async getCacheAsync(cacheKey) {
const cacheRedis = getRedisCacheClient(this);
if (cacheRedis && typeof cacheRedis.get === 'function') {
try {
const data = await cacheRedis.get(cacheKey);
if (data === undefined || data === null) {
return null;
}
return parseRedisCacheValue(data);
} catch (error) {
const logger = getCacheLogger(this);
if (logger && typeof logger.warn === 'function') {
logger.warn('[CacheRedisGetError] Redis 读取缓存失败,已回退到进程内缓存', error.message, cacheKey);
}
}
return null;
} catch (error) {
this.logger.error('[CacheGetError] Failed to get cache', error.message, cacheKey);
return null;
}
return getLocalCacheValue(this, cacheKey);
},
};

View File

@ -0,0 +1,19 @@
'use strict';
/**
* 在应用启动阶段触发订单发货表的 managed table schema 自检。
* @param {import('egg').Application} app 应用实例。
* @return {Promise<void>}
*/
module.exports = async app => {
if (!app || !app.OrderDeliveryFactory) {
return;
}
if (typeof app.OrderDeliveryFactory.ensureManagedTableSchemas !== 'function') {
return;
}
await app.OrderDeliveryFactory.ensureManagedTableSchemas();
app.logger.info('✅ 订单工厂目标表自检完成');
};

235
app/lib/polo_api_client.js Normal file
View File

@ -0,0 +1,235 @@
'use strict';
const crypto = require('crypto');
const POLYAPI_CONFIG_CACHE_KEY = 'polo_api_client:polyapi:config';
const POLYAPI_CONFIG_CACHE_TTL_SECONDS = 60 * 60;
/**
* PolyAPI 底层 HTTP 客户端。
* 封装签名、表单编码、请求发送等通用逻辑,与业务无关。
*/
class PoloApiClient {
/**
* @param {object} ctx - Egg 上下文对象。
*/
constructor(ctx) {
this.ctx = ctx;
this._config = null;
this._configPromise = null;
this.contenttype = 'json';
}
/**
* 按需加载并缓存 PolyAPI 配置。
*
* 优先读取应用级缓存;缓存未命中或读取失败时,再回源数据库。
* 数据库查到配置后,会回写到应用级缓存,缓存 TTL 为 1 小时。
*
* @returns {Promise<object|null>} PolyAPI 配置记录。
*/
async getConfig(platid) {
if (this._config) {
return this._config;
}
if (!this._configPromise) {
this._configPromise = this._loadConfig(platid).then(config => {
this._config = config || null;
return this._config;
}).finally(() => {
this._configPromise = null;
});
}
return this._configPromise;
}
/**
* 读取 PolyAPI 配置:先查缓存,未命中则查数据库。
*
* @returns {Promise<object|null>} PolyAPI 配置记录。
*/
async _loadConfig(platid) {
const cachedConfig = await this._getCachedConfig(platid);
if (cachedConfig) {
return cachedConfig;
}
const config = await this._loadConfigFromDatabase(platid);
if (config) {
await this._setCachedConfig(config);
}
return config;
}
/**
* 从应用级缓存读取 PolyAPI 配置。
*
* 缓存读取失败时,返回 null 并由调用方继续回源数据库。
*
* @returns {Promise<object|null>} 缓存中的配置记录。
*/
async _getCachedConfig(platid) {
if (!this.ctx.app || typeof this.ctx.app.getCacheAsync !== 'function') {
return null;
}
try {
return await this.ctx.app.getCacheAsync(`${POLYAPI_CONFIG_CACHE_KEY}:${platid}`);
} catch (error) {
if (this.ctx.logger && typeof this.ctx.logger.warn === 'function') {
this.ctx.logger.warn('[PoloApiClient._getCachedConfig] 读取缓存失败,回退数据库查询: %s', error.message);
}
return null;
}
}
/**
* 查询数据库中的 PolyAPI 配置。
*
* @returns {Promise<object|null>} 数据库中的配置记录。
*/
async _loadConfigFromDatabase(platid) {
if (!this.ctx.app || !this.ctx.app.model || !this.ctx.app.model.ExpressPlatform || typeof this.ctx.app.model.ExpressPlatform.findOne !== 'function') {
return null;
}
return await this.ctx.app.model.ExpressPlatform.findOne({
where: { platid: platid },
});
}
/**
* 将 PolyAPI 配置写回应用级缓存。
*
* @param {object} config - PolyAPI 配置记录。
* @returns {Promise<void>}
*/
async _setCachedConfig(config) {
if (!this.ctx.app || typeof this.ctx.app.setCacheAsync !== 'function') {
return;
}
try {
const cacheValue = config && typeof config.toJSON === 'function' ? config.toJSON() : config;
await this.ctx.app.setCacheAsync(`${POLYAPI_CONFIG_CACHE_KEY}:${config.platid}`, cacheValue, POLYAPI_CONFIG_CACHE_TTL_SECONDS);
} catch (error) {
if (this.ctx.logger && typeof this.ctx.logger.warn === 'function') {
this.ctx.logger.warn('[PoloApiClient._setCachedConfig] 写入缓存失败,继续使用数据库结果: %s', error.message);
}
}
}
/**
* 发起 PolyAPI 表单 POST 请求。
*
* @param {object} options - 请求参数。
* @param {string} options.method - 远端接口方法名。
* @param {number|string} options.platid - 平台 ID。
* @param {object|string} [options.bizcontent={}] - 业务参数内容。
* @returns {Promise<any>} 接口响应 data。
*/
async request(options = {}) {
const {
method,
platid,
bizcontent = {},
} = options;
const config = await this.getConfig(platid);
if (!config) {
throw new Error('未找到 polyapi 配置');
}
const signMap = this._buildSignMap(config, method, platid, bizcontent);
const signText = this._getSignText(signMap, config.app_secret);
const sign = this._md5(signText.toLowerCase());
const formBody = this._encodeForm({ ...signMap, sign });
const response = await this.ctx.curl(String(config.interface_url || ''), {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
},
content: formBody,
});
return response && response.data !== undefined ? response.data : null;
}
// ── 内部方法 ──
/**
* 组装签名所需的请求参数。
*/
_buildSignMap(config, method, platid, bizcontent) {
const normalizedBizcontent = bizcontent && typeof bizcontent === 'object'
? JSON.stringify(bizcontent)
: (bizcontent === undefined || bizcontent === null ? '' : bizcontent);
return {
method,
appkey: config.appkey,
token: config.token,
platid,
version: config.version,
contenttype: this.contenttype,
bizcontent: normalizedBizcontent,
timestamp: this._formatDate(new Date()),
};
}
/**
* 生成签名原文 = secret + key1value1 + key2value2 ... + secret(按 key 字母序)。
*/
_getSignText(signMap, secret) {
let sb = '' + secret;
Object.keys(signMap).sort().forEach(key => {
sb += key + signMap[key];
});
sb += secret;
return sb;
}
/**
* MD5 摘要。
*/
_md5(text, encoding = 'utf8') {
return crypto.createHash('md5').update(text, encoding).digest('hex');
}
/**
* 将参数编码为 application/x-www-form-urlencoded。
*/
_encodeForm(map) {
const params = new URLSearchParams();
for (const key of Object.keys(map)) {
const v = map[key];
params.append(key, v === undefined || v === null ? '' : (typeof v === 'object' ? JSON.stringify(v) : String(v)));
}
return params.toString();
}
/**
* 格式化日期 → yyyy-MM-dd HH:mm:ss。
*/
_formatDate(date) {
const pad = n => (n < 10 ? '0' + n : n);
return date.getFullYear() + '-' + pad(date.getMonth() + 1) + '-' + pad(date.getDate()) + ' '
+ pad(date.getHours()) + ':' + pad(date.getMinutes()) + ':' + pad(date.getSeconds());
}
/**
* 格式化取件日期。
*/
_formatPickupDate(year, month, day) {
const pad = n => (n < 10 ? '0' + n : n);
return `${year}-${pad(month)}-${pad(day)} 18:00:00`;
}
}
module.exports = PoloApiClient;

View File

@ -0,0 +1,93 @@
'use strict';
const MAX_DECIMAL_DIGITS = 20;
/**
* 将分表用的仓库 ID 规范为纯十进制数字串(与 wms_store.id / BIGINT 一致)。
* @param {*} value 待规范化的仓库 ID。
* @return {string} 规范化后的仓库 ID 字符串。
*/
function normalizeWarehouseShardId(value) {
if (value === null || value === undefined || value === '') {
throw new Error('warehouse_id 不能为空');
}
if (typeof value === 'object') {
throw new Error('warehouse_id 必须为数字');
}
const s = String(value).trim();
if (!/^\d+$/.test(s)) {
throw new Error('warehouse_id 必须为数字');
}
if (s === '0') {
throw new Error('warehouse_id 非法');
}
if (s.length > MAX_DECIMAL_DIGITS) {
throw new Error('warehouse_id 超出范围');
}
return s;
}
/**
* 校验 wms_store 中存在对应 ID 且主体为仓库(project = warehouse)。
* @param {import('egg').Application} app 应用实例。
* @param {string} warehouseIdStr normalizeWarehouseShardId 的返回值。
* @return {Promise<void>}
*/
async function assertWarehouseStoreSubject(app, warehouseIdStr) {
if (!app.model || !app.model.Store) {
return;
}
const row = await app.model.Store.findOne({
where: {
id: warehouseIdStr,
project: 'warehouse',
},
attributes: [ 'id' ],
paranoid: true,
});
if (!row) {
throw new Error(`仓库主体不存在或非仓库类型(wms_store.project 须为 warehouse): ${warehouseIdStr}`);
}
}
function validatedSetFor(app) {
if (!app._shardWarehouseIdsValidated) {
app._shardWarehouseIdsValidated = new Set();
}
return app._shardWarehouseIdsValidated;
}
/**
* 规范化并校验仓库分表 ID。
* @param {import('egg').Application} app 应用实例。
* @param {*} raw 原始仓库 ID。
* @return {Promise<string>} 规范化并校验后的仓库 ID 字符串。
*/
async function ensureShardWarehouseId(app, raw) {
const idStr = normalizeWarehouseShardId(raw);
const validatedSet = validatedSetFor(app);
if (validatedSet.has(idStr)) {
return idStr;
}
await assertWarehouseStoreSubject(app, idStr);
validatedSet.add(idStr);
return idStr;
}
/**
* 清理进程内「已校验仓库主体」缓存(例如单测或手动 clear 动态模型缓存时)。
* @param {import('egg').Application} app 应用实例。
* @return {void}
*/
function clearShardWarehouseValidationCache(app) {
if (app && app._shardWarehouseIdsValidated) {
app._shardWarehouseIdsValidated.clear();
}
}
module.exports = {
normalizeWarehouseShardId,
assertWarehouseStoreSubject,
ensureShardWarehouseId,
clearShardWarehouseValidationCache,
};

View File

@ -0,0 +1,75 @@
'use strict';
module.exports = app => {
const { INTEGER, STRING } = app.Sequelize;
const ExpressPlatform = app.model.define('express_platform', {
id: {
type: INTEGER(10),
primaryKey: true,
autoIncrement: true,
allowNull: false,
comment: '接口ID',
},
interface_url: {
type: STRING(500),
allowNull: false,
comment: '外部接口URL',
},
platform_code: {
type: STRING(50),
allowNull: false,
comment: '平台代码,用于应用分流',
},
interface_name: {
type: STRING(200),
allowNull: false,
comment: '接口名称',
},
interface_url_jd: {
type: STRING(500),
allowNull: true,
comment: '京东接口URL',
},
appkey: {
type: STRING(100),
allowNull: true,
comment: '应用Key',
},
app_secret: {
type: STRING(255),
allowNull: true,
field: 'AppSecret',
comment: '应用密钥',
},
token: {
type: STRING(255),
allowNull: true,
comment: '访问令牌',
},
version: {
type: STRING(20),
allowNull: true,
comment: '接口版本',
},
}, {
tableName: 'wms_express_interface',
freezeTableName: true,
underscored: true,
timestamps: false,
paranoid: false,
comment: '快递外部接口配置表',
indexes: [
{
name: 'idx_platform_code',
fields: [ 'platform_code' ],
},
{
name: 'idx_interface_name',
fields: [ 'interface_name' ],
},
],
});
return ExpressPlatform;
};

View File

@ -39,6 +39,7 @@ module.exports = app => {
Object.freeze({ code: 'all', name: '全部事件', business: 'all', description: '订阅后接收所有通知事件' }),
Object.freeze({ code: '*', name: '全部事件(兼容别名)', business: 'all', description: '兼容旧配置,等价于 all' }),
Object.freeze({ code: 'receiving_completed', name: '收货完成', business: 'receiving', description: '收货单完成后的通知' }),
Object.freeze({ code: 'order_cancel_intercepted', name: '订单取消拦截', business: 'order', description: '订单取消失败并触发拦截执行后的通知' }),
Object.freeze({
code: 'store_warehouse_print_quantity_adjusted',
name: '货主面单余额调整',
@ -229,7 +230,11 @@ module.exports = app => {
});
const subjectConfig = app.model.Store && typeof app.model.Store.normalizeSubjectConfig === 'function'
? app.model.Store.normalizeSubjectConfig(store && store.subject_config)
: { max_notice_webhook_count: 5 };
: {
max_notice_webhook_count: 5,
default_express_code: 'STO',
default_platform_code: 'TB',
};
const maxWebhookCount = Number(subjectConfig.max_notice_webhook_count || 5);
const where = {

View File

@ -15,7 +15,7 @@ module.exports = app => {
INSPECTION_STATUS: [ 'none', 'padding', 'running', 'fin', 'error' ],
PRINT_STATUS: [ 'none', 'padding', 'fin', 'error' ],
CLAIM_STATUS: [ 'none', 'padding', 'fin', 'error' ],
OUTBOUND_STATUS: [ 'none', 'padding', 'fin', 'error' ],
OUTBOUND_STATUS: [ 'none', 'padding', 'fin', 'timeout', 'error' ],
LOCK_STATUS: [ 'none', 'warehouse', 'store' ],
INTERCEPT_STATUS: [
'none', 'requesting', 'requested', 'intercepting',
@ -74,6 +74,16 @@ module.exports = app => {
allowNull: true,
comment: '来源平台名称',
},
sys_platform_code: {
type: STRING(50),
allowNull: true,
comment: '系统平台编码',
},
sys_platform_name: {
type: STRING(200),
allowNull: true,
comment: '系统平台名称',
},
create_at: {
type: DATE,
allowNull: true,
@ -184,6 +194,16 @@ module.exports = app => {
allowNull: true,
comment: '物流公司名称',
},
sys_logistics_code: {
type: STRING(50),
allowNull: true,
comment: '系统物流公司编码',
},
sys_logistics_name: {
type: STRING(200),
allowNull: true,
comment: '系统物流公司名称',
},
express_code: {
type: STRING(50),
allowNull: true,
@ -389,7 +409,7 @@ module.exports = app => {
print_status: {
type: ENUM(...StatusEnum.PRINT_STATUS),
allowNull: true,
defaultValue: null,
defaultValue: 'none',
comment: '打印状态机',
},
claim_status: {
@ -407,13 +427,13 @@ module.exports = app => {
lock_status: {
type: ENUM(...StatusEnum.LOCK_STATUS),
allowNull: true,
defaultValue: null,
defaultValue: 'none',
comment: '锁定状态机',
},
intercept_status: {
type: ENUM(...StatusEnum.INTERCEPT_STATUS),
allowNull: true,
defaultValue: null,
defaultValue: 'none',
comment: '拦截状态机',
},
};
@ -439,8 +459,7 @@ module.exports = app => {
},
{
name: 'idx_items',
fields: [ 'items' ],
length: 50,
fields: [{ attribute: 'items', length: 50 }],
},
{
name: 'idx_items_hash',

View File

@ -1,6 +1,109 @@
// app/model/wms_order_delivery_factory.js
'use strict';
const {
ensureShardWarehouseId,
clearShardWarehouseValidationCache,
} = require('../lib/warehouse_shard_guard');
const {
normalizeManagedType,
isOutsourcedType,
normalizeIndexDefinition,
parseNumericConstraint,
buildTableAttributes,
buildTableName: buildManagedTableName,
buildTableComment,
buildTableOptions,
buildIndexOptions,
buildColumnLines,
buildIndexLines,
parseManagedTableName,
} = require('./order_delivery_table_schema');
const LANES = Object.freeze({
M4: 'm4',
M5: 'm5',
});
/**
* 判断两个索引定义是否存在结构差异。
* @param {Object} expectedIndex 预期索引定义。
* @param {Object} actualIndex 实际索引定义。
* @return {boolean} 是否存在结构差异。
*/
function isIndexDefinitionDifferent(expectedIndex, actualIndex) {
const normalizedExpected = normalizeIndexDefinition(expectedIndex);
const normalizedActual = normalizeIndexDefinition(actualIndex);
if (!normalizedActual.name) {
return true;
}
const actualUniqueDefined = Object.prototype.hasOwnProperty.call(actualIndex || {}, 'unique')
|| Object.prototype.hasOwnProperty.call(actualIndex || {}, 'Unique')
|| Object.prototype.hasOwnProperty.call(actualIndex || {}, 'nonUnique');
if (actualUniqueDefined && normalizedExpected.unique !== normalizedActual.unique) {
return true;
}
if (!Array.isArray(actualIndex && actualIndex.fields) || !actualIndex.fields.length) {
return false;
}
if (normalizedExpected.fields.length !== normalizedActual.fields.length) {
return true;
}
for (let index = 0; index < normalizedExpected.fields.length; index += 1) {
const expectedField = normalizedExpected.fields[index];
const actualField = normalizedActual.fields[index];
if (!expectedField.attribute || !actualField.attribute) {
return true;
}
if (expectedField.attribute !== actualField.attribute) {
return true;
}
if (Object.prototype.hasOwnProperty.call(expectedField, 'length') && expectedField.length !== actualField.length) {
return true;
}
}
return false;
}
/**
* 转义 SQL 标识符。
* @param {string} identifier 标识符。
* @return {string} 转义后的标识符。
*/
function quoteIdentifier(identifier) {
return `\`${String(identifier).replace(/`/g, '``')}\``;
}
/**
* 构造表数据约束违规错误。
* @param {string} tableName 表名。
* @param {string} columnName 列名。
* @param {string} violationType 违规类型。
* @param {string} [detail] 违规详情。
* @return {Error} 错误对象。
*/
function buildManagedTableConstraintError(tableName, columnName, violationType, detail = '') {
const suffix = detail ? `, detail=${detail}` : '';
const error = new Error(`数据不满足约束: table=${tableName}, column=${columnName}, violation=${violationType}${suffix}`);
error.code = 'ORDER_DELIVERY_TABLE_CONSTRAINT_VIOLATION';
error.tableName = tableName;
error.columnName = columnName;
error.violationType = violationType;
return error;
}
module.exports = app => {
class OrderDeliveryFactory {
@ -9,6 +112,36 @@ module.exports = app => {
this.app = app;
}
/**
* 获取配送域车道常量。
* @return {Object} 车道常量。
*/
get LANES() {
return LANES;
}
/**
* 判断是否为配送域模型。
* @param {string} type 模型类型。
* @return {boolean} 是否为配送域模型。
*/
isDispatchType(type) {
return type === 'dispatch';
}
/**
* 解析模型类型。
* @param {string} type 模型类型。
* @return {string} 解析后的模型类型。
*/
resolveModelType(type) {
return normalizeManagedType(type);
}
isOutsourcedModel(type) {
return isOutsourcedType(type);
}
/**
* 获取当前表模型
* @param {number} warehouseId 仓库ID
@ -27,6 +160,37 @@ module.exports = app => {
return await this.getOrCreateModel(warehouseId, 'history');
}
/**
* 获取配送域模型。
* @param {number|string} warehouseId 仓库ID。
* @return {Promise<Object>} 配送域模型。
*/
async getDispatchModel(warehouseId) {
return await this.getOrCreateModel(warehouseId, 'dispatch');
}
async getOutsourcedModel(warehouseId) {
return await this.getOrCreateModel(warehouseId, 'outsourced');
}
/**
* 获取配送正常模型。
* @param {number|string} warehouseId 仓库ID。
* @return {Promise<Object>} 配送域模型。
*/
async getM4Model(warehouseId) {
return await this.getDispatchModel(warehouseId);
}
/**
* 获取配送异常模型。
* @param {number|string} warehouseId 仓库ID。
* @return {Promise<Object>} 配送域模型。
*/
async getM5Model(warehouseId) {
return await this.getDispatchModel(warehouseId);
}
/**
* 根据表名直接获取模型
* @param {string} tableName 表名
@ -40,17 +204,18 @@ module.exports = app => {
}
try {
const parsed = parseManagedTableName(tableName);
if (!parsed) {
throw new Error(`表 ${tableName} 不是订单工厂管理表`);
}
const tableExists = await this.checkTableExists(tableName);
if (!tableExists) {
throw new Error(`表 ${tableName} 不存在`);
}
const baseAttributes = this.app.model.OrderDelivery.rawAttributes;
const DynamicModel = this.app.model.define(tableName, baseAttributes, {
tableName,
timestamps: false,
comment: tableName.includes('_history') ? '仓库发货单历史表' : '仓库发货单常用表',
});
const DynamicModel = this.buildManagedModel(parsed.warehouseId, parsed.type, tableName);
await this.ensureManagedTableSchema(tableName, parsed.type, parsed.warehouseId, DynamicModel);
this.modelCache.set(cacheKey, DynamicModel);
return DynamicModel;
@ -67,9 +232,11 @@ module.exports = app => {
* @param {string} type 模型类型
* @return {Promise<Object>} 动态模型
*/
async getOrCreateModel(warehouseId, type = 'current') {
const tableName = this.generateTableName(warehouseId, type);
const cacheKey = `${warehouseId}_${type}`;
async getOrCreateModel(warehouseId, type) {
const warehouseIdStr = await ensureShardWarehouseId(this.app, warehouseId);
const modelType = this.resolveModelType(type);
const tableName = this.generateTableName(warehouseIdStr, modelType);
const cacheKey = `${warehouseIdStr}_${modelType}`;
// 检查缓存
if (this.modelCache.has(cacheKey)) {
@ -77,20 +244,12 @@ module.exports = app => {
}
try {
// 检查表是否存在,不存在则创建
const tableExists = await this.checkTableExists(tableName);
if (!tableExists) {
await this.createPhysicalTable(warehouseId, type);
}
const DynamicModel = this.buildManagedModel(warehouseIdStr, modelType, tableName);
// 创建模型实例
const baseAttributes = this.app.model.OrderDelivery.rawAttributes;
const modelOptions = this.getModelOptions(tableName, warehouseId, type);
const DynamicModel = this.app.model.define(tableName, baseAttributes, modelOptions);
await this.ensureManagedTableSchema(tableName, modelType, warehouseIdStr, DynamicModel);
// 设置关联关系
this.setupAssociations(DynamicModel, warehouseId, type);
this.setupAssociations(DynamicModel, warehouseIdStr, modelType);
// 缓存模型
this.modelCache.set(cacheKey, DynamicModel);
@ -106,28 +265,36 @@ module.exports = app => {
/**
* 获取模型配置选项
* @param {string} tableName 表名
* @param {number} warehouseId 仓库ID
* @param {string} type 模型类型
* @return {Object} Sequelize 模型配置
*/
getModelOptions(tableName, warehouseId, type) {
const options = {
tableName,
timestamps: false,
comment: type === 'history'
? `仓库${warehouseId}发货单历史表`
: `仓库${warehouseId}发货单常用表`,
indexes: this.getIndexes(warehouseId, type),
};
getModelOptions(warehouseId, type) {
return buildTableOptions(this.app, warehouseId, type);
}
// 历史表添加归档时间字段
if (type === 'history') {
options.fields = Object.keys(this.app.model.OrderDelivery.rawAttributes);
options.fields.push('archive_time');
}
/**
* 构建动态模型。
* @param {number|string} warehouseId 仓库ID。
* @param {string} type 模型类型。
* @param {string} tableName 表名。
* @return {Object} 动态模型。
*/
buildManagedModel(warehouseId, type, tableName) {
const modelType = this.resolveModelType(type);
const attributes = this.getTableAttributes(modelType);
const modelOptions = this.getModelOptions(warehouseId, modelType);
return options;
return this.app.model.define(tableName, attributes, modelOptions);
}
/**
* 获取订单工厂管理的属性定义。
* @param {string} type 模型类型。
* @return {Object} 属性定义。
*/
getTableAttributes(type) {
return buildTableAttributes(this.app, type);
}
/**
@ -137,63 +304,89 @@ module.exports = app => {
* @return {Array<Object>} 索引配置
*/
getIndexes(warehouseId, type) {
const prefix = `${warehouseId}_${type}`;
return buildIndexOptions(warehouseId, type);
}
return [
{
name: `idx_${prefix}_store_id`,
fields: [ 'store_id' ],
},
{
name: `idx_${prefix}_warehouse_id`,
fields: [ 'warehouse_id' ],
},
{
name: `idx_${prefix}_delivery_code`,
unique: true,
fields: [ 'delivery_order_code', 'store_id', 'warehouse_id' ],
},
{
name: `idx_${prefix}_items`,
fields: [ 'items' ],
length: 50,
},
{
name: `idx_${prefix}_items_hash`,
fields: [ 'items_hash' ],
},
{
name: `idx_${prefix}_hash_crc`,
fields: [ 'items_hash', 'items_crc', 'warehouse_id' ],
},
{
name: `idx_${prefix}_wave`,
fields: [ 'status', 'wave_id' ],
},
{
name: `idx_${prefix}_statuses`,
fields: [
'status',
'post_status',
'pick_status',
'pack_status',
'outbound_status',
],
},
];
/**
* 获取当前表通用列定义行。
*
* @param {string} type 模型类型
* @return {Array<string>} 当前表列定义行
*/
getCurrentTableColumnLines(type = 'current') {
return buildColumnLines(this.app, type);
}
/**
* 获取当前表通用索引定义行。
*
* @param {number} warehouseId 仓库ID
* @param {string} type 模型类型
* @return {Array<string>} 当前表索引定义行
*/
getCurrentTableIndexLines(warehouseId, type = 'current') {
return buildIndexLines(warehouseId, type);
}
/**
* 获取配送域物理表名。
* @param {number|string} warehouseId 仓库ID。
* @return {Promise<string>} 配送域物理表名。
*/
async getDispatchTableName(warehouseId) {
const warehouseIdStr = await ensureShardWarehouseId(this.app, warehouseId);
return `wms_order_delivery_dispatch_${warehouseIdStr}`;
}
/**
* 获取配送域表列定义行。
* @return {Array<string>} 配送域表列定义行。
*/
getDispatchTableColumnLines() {
return buildColumnLines(this.app, 'dispatch');
}
/**
* 获取配送域表索引定义行。
* @param {string} warehouseIdStr 仓库ID字符串。
* @return {Array<string>} 配送域表索引定义行。
*/
getDispatchTableIndexLines(warehouseIdStr) {
return buildIndexLines(warehouseIdStr, 'dispatch');
}
/**
* 获取配送域索引配置。
* @param {string} warehouseIdStr 仓库ID字符串。
* @return {Array<Object>} Sequelize 索引配置。
*/
getDispatchTableIndexOptions(warehouseIdStr) {
return buildIndexOptions(warehouseIdStr, 'dispatch');
}
/**
* 获取配送域属性定义。
* @return {Object} 配送域属性定义。
*/
getDispatchAttributes() {
return this.getTableAttributes('dispatch');
}
buildDispatchAttributes() {
return this.getDispatchAttributes();
}
/**
* 设置关联关系
* @param {Object} DynamicModel 动态模型
* @param {number} warehouseId 仓库ID
* @param {string} type 模型类型
* @return {Promise<void>}
* @param {Object} DynamicModel 动态模型
* @param {number} warehouseId 仓库ID
* @param {string} type 模型类型
* @return {Promise<void>}
*/
async setupAssociations(DynamicModel, warehouseId, type) {
try {
// 如果存在商品模型工厂,建立关联
if (this.app.model.OrderItemsFactory) {
// 配送域不挂商品明细关联,其余模式保持原行为。
if (!this.isDispatchType(type) && this.app.model.OrderItemsFactory) {
const ItemsModel = await this.app.model.OrderItemsFactory.getOrCreateModel(warehouseId, type);
// 发货单 -> 商品 (1:N)
@ -237,8 +430,8 @@ module.exports = app => {
/**
* 检查表是否存在
* @param {string} tableName 表名
* @return {Promise<boolean>} 是否存在
* @param {string} tableName 表名
* @return {Promise<boolean>} 是否存在
*/
async checkTableExists(tableName) {
const sequelize = this.app.model;
@ -263,113 +456,233 @@ module.exports = app => {
}
}
/**
* 判断目标表是否需要进行结构同步。
* @param {string} tableName 表名。
* @param {string} type 模型类型。
* @param {number|string} warehouseId 仓库ID。
* @param {boolean|null} [tableExists=null] 是否已确认表存在。
* @return {Promise<boolean>} 是否需要同步。
*/
async needsTableSchemaSync(tableName, type, warehouseId, tableExists = null) {
const queryInterface = this.app.model.getQueryInterface();
const managedTableExists = typeof tableExists === 'boolean'
? tableExists
: await this.checkTableExists(tableName);
if (!managedTableExists) {
return true;
}
const [ tables, indexes ] = await Promise.all([
queryInterface.describeTable(tableName),
typeof queryInterface.showIndex === 'function'
? queryInterface.showIndex(tableName)
: Promise.resolve([]),
]);
const expectedAttributes = this.getTableAttributes(type);
const expectedAttributeNames = Object.keys(expectedAttributes);
const actualAttributeNames = Object.keys(tables || {});
if (expectedAttributeNames.length !== actualAttributeNames.length) {
return true;
}
const actualColumnNames = new Set(actualAttributeNames);
for (const columnName of expectedAttributeNames) {
if (!actualColumnNames.has(columnName)) {
return true;
}
}
for (const columnName of expectedAttributeNames) {
const expectedColumn = expectedAttributes[columnName];
const actualColumn = tables[columnName] || {};
const expectedType = expectedColumn.type && typeof expectedColumn.type.toSql === 'function'
? expectedColumn.type.toSql().toLowerCase()
: String(expectedColumn.type || '').toLowerCase();
const actualType = String(actualColumn.type || actualColumn.Type || '').toLowerCase();
const expectedAllowNull = expectedColumn.allowNull !== false;
const actualAllowNull = actualColumn.allowNull !== false;
const expectedDefault = Object.prototype.hasOwnProperty.call(expectedColumn, 'defaultValue')
? expectedColumn.defaultValue
: undefined;
const actualDefault = Object.prototype.hasOwnProperty.call(actualColumn, 'defaultValue')
? actualColumn.defaultValue
: undefined;
if (expectedType && actualType && expectedType !== actualType) {
return true;
}
if (expectedAllowNull !== actualAllowNull) {
return true;
}
const normalizedExpectedDefault = expectedDefault == null ? null : String(expectedDefault);
const normalizedActualDefault = actualDefault == null ? null : String(actualDefault);
if (normalizedExpectedDefault !== normalizedActualDefault) {
return true;
}
}
const expectedIndexes = this.getIndexes(warehouseId, type);
const actualIndexes = Array.isArray(indexes) ? indexes : [];
for (const expectedIndex of expectedIndexes) {
const actualIndex = actualIndexes.find(index => (index.Key_name || index.name) === expectedIndex.name);
if (!actualIndex) {
return true;
}
if (isIndexDefinitionDifferent(expectedIndex, actualIndex)) {
return true;
}
}
return false;
}
/**
* 在结构同步前预检现有数据是否满足非空和数值范围约束。
* @param {string} tableName 表名。
* @param {string} type 模型类型。
* @return {Promise<void>}
*/
async assertManagedTableDataConstraints(tableName, type) {
const queryInterface = this.app.model.getQueryInterface();
const sequelize = this.app.model;
const tableColumns = await queryInterface.describeTable(tableName);
const expectedAttributes = this.getTableAttributes(type);
const columnNames = new Set(Object.keys(tableColumns || {}));
for (const columnName of Object.keys(expectedAttributes)) {
if (!columnNames.has(columnName)) {
continue;
}
const expectedAttribute = expectedAttributes[columnName];
const quotedTableName = quoteIdentifier(tableName);
const quotedColumnName = quoteIdentifier(columnName);
if (expectedAttribute.allowNull === false) {
const [ nullRows ] = await sequelize.query(
`SELECT 1 AS violationFound FROM ${quotedTableName} WHERE ${quotedColumnName} IS NULL LIMIT 1`
);
if (Array.isArray(nullRows) && nullRows.length > 0) {
throw buildManagedTableConstraintError(tableName, columnName, 'NOT_NULL');
}
}
const numericConstraint = parseNumericConstraint(expectedAttribute);
if (!numericConstraint) {
continue;
}
const [ rangeRows ] = await sequelize.query(
`SELECT 1 AS violationFound FROM ${quotedTableName}
WHERE ${quotedColumnName} IS NOT NULL
AND (${quotedColumnName} < :minValue OR ${quotedColumnName} > :maxValue)
LIMIT 1`,
{
replacements: {
minValue: numericConstraint.min,
maxValue: numericConstraint.max,
},
}
);
if (Array.isArray(rangeRows) && rangeRows.length > 0) {
throw buildManagedTableConstraintError(
tableName,
columnName,
'NUMERIC_RANGE',
`expected=[${numericConstraint.min}, ${numericConstraint.max}]`
);
}
}
}
/**
* 确保单个目标表与模型结构一致。
* @param {string} tableName 表名。
* @param {string} type 模型类型。
* @param {number|string} warehouseId 仓库ID。
* @param {Object} [DynamicModel] 已构建的动态模型。
* @return {Promise<boolean>} 是否执行了同步。
*/
async ensureManagedTableSchema(tableName, type, warehouseId, DynamicModel = null) {
const modelType = this.resolveModelType(type);
const dynamicModel = DynamicModel || this.buildManagedModel(warehouseId, modelType, tableName);
const tableExists = await this.checkTableExists(tableName);
const needsSync = tableExists
? await this.needsTableSchemaSync(tableName, modelType, warehouseId, tableExists)
: true;
if (!needsSync) {
return false;
}
if (tableExists) {
await this.assertManagedTableDataConstraints(tableName, modelType);
}
await dynamicModel.sync({ alter: true });
return true;
}
/**
* 扫描并同步订单工厂管理的目标表。
* @return {Promise<void>}
*/
async ensureManagedTableSchemas() {
const tableNames = await this.listManagedTableNames();
for (const tableName of tableNames) {
const parsed = parseManagedTableName(tableName);
if (!parsed) {
continue;
}
await this.ensureManagedTableSchema(tableName, parsed.type, parsed.warehouseId);
}
}
/**
* 获取当前库中已存在的订单工厂目标表。
* @return {Promise<Array<string>>} 目标表名列表。
*/
async listManagedTableNames() {
const [ rows ] = await this.app.model.query(`
SELECT TABLE_NAME AS tableName
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = DATABASE()
AND TABLE_NAME LIKE 'wms_order_delivery_%'
`);
return rows
.map(item => item.tableName)
.filter(tableName => parseManagedTableName(tableName));
}
/**
* 创建物理表
* @param {number} warehouseId 仓库ID
* @param {string} type 模型类型
* @return {Promise<void>}
*/
async createPhysicalTable(warehouseId, type = 'current') {
const tableName = this.generateTableName(warehouseId, type);
const tableComment = type === 'history'
? `仓库${warehouseId}发货单历史表`
: `仓库${warehouseId}发货单常用表`;
async createPhysicalTable(warehouseId, type) {
const modelType = this.resolveModelType(type);
const tableName = this.generateTableName(warehouseId, modelType);
const dynamicModel = this.buildManagedModel(warehouseId, modelType, tableName);
// 添加历史表特有的字段
const historyFields = type === 'history' ?
',\n`archive_time` datetime DEFAULT CURRENT_TIMESTAMP COMMENT \'归档时间\'' : '';
const createTableSQL = `
CREATE TABLE \`${tableName}\` (
\`id\` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT,
\`delivery_order_code\` varchar(50) DEFAULT NULL COMMENT '发货单号',
\`pre_delivery_order_code\` varchar(50) DEFAULT NULL COMMENT '预发货单号',
\`pre_delivery_order_id\` varchar(50) DEFAULT NULL COMMENT '预发货单ID',
\`order_type\` varchar(50) DEFAULT NULL COMMENT '订单类型',
\`warehouse_code\` varchar(50) DEFAULT NULL COMMENT '仓库编码',
\`order_flag\` varchar(200) DEFAULT NULL COMMENT '订单标记',
\`source_platform_code\` varchar(50) DEFAULT NULL COMMENT '来源平台编码',
\`source_platform_name\` varchar(200) DEFAULT NULL COMMENT '来源平台名称',
\`create_at\` datetime DEFAULT NULL COMMENT '创建时间',
\`delete_at\` datetime DEFAULT NULL COMMENT '删除时间',
\`updated_at\` datetime DEFAULT NULL COMMENT '更新时间',
\`place_order_time\` datetime DEFAULT NULL COMMENT '店铺创建订单时间',
\`pay_time\` datetime DEFAULT NULL COMMENT '支付时间',
\`pay_no\` varchar(50) DEFAULT NULL COMMENT '支付单号',
\`service_code\` varchar(50) DEFAULT NULL COMMENT '集包服务编码',
\`operator_name\` varchar(50) DEFAULT NULL COMMENT 'ERP审核人',
\`operate_time\` datetime DEFAULT NULL COMMENT 'ERP审核时间',
\`delivery_time\` datetime DEFAULT NULL COMMENT '发货时间',
\`shop_nick\` varchar(200) DEFAULT NULL COMMENT '店铺名称',
\`seller_nick\` varchar(200) DEFAULT NULL COMMENT '卖家名称',
\`buyer_nick\` varchar(200) DEFAULT NULL COMMENT '买家名称',
\`total_amount\` decimal(18,2) DEFAULT NULL COMMENT '订单总金额',
\`item_amount\` decimal(18,2) DEFAULT NULL COMMENT '商品总金额',
\`discount_amount\` decimal(18,2) DEFAULT NULL COMMENT '订单折扣金额',
\`freight\` decimal(18,2) DEFAULT NULL COMMENT '快递费用',
\`ar_amount\` decimal(18,2) DEFAULT NULL COMMENT '应收金额',
\`got_amount\` decimal(18,2) DEFAULT NULL COMMENT '已收金额',
\`service_fee\` decimal(18,2) DEFAULT NULL COMMENT 'COD服务费',
\`logistics_code\` varchar(50) DEFAULT NULL COMMENT '物流公司编码',
\`logistics_name\` varchar(200) DEFAULT NULL COMMENT '物流公司名称',
\`express_code\` varchar(50) DEFAULT NULL COMMENT '面单号前置',
\`logistics_area_code\` varchar(50) DEFAULT NULL COMMENT '快递区域编码, 大头笔信息',
\`delivery_type\` varchar(255) DEFAULT NULL COMMENT '发货服务类型',
\`is_urgency\` enum('Y','N') DEFAULT 'N' COMMENT '是否紧急',
\`invoice_flag\` enum('Y','N') DEFAULT 'N' COMMENT '是否需要发票',
\`status\` enum('pedding','created','cancel','error') DEFAULT 'created' COMMENT '状态',
\`name\` text COMMENT '收件人姓名',
\`zip_code\` varchar(50) DEFAULT NULL COMMENT '收件人邮编',
\`tel\` text COMMENT '收件人电话',
\`mobile\` text COMMENT '收件人移动电话',
\`email\` text COMMENT '收件人邮箱',
\`country_code\` varchar(255) DEFAULT NULL COMMENT '国家编码',
\`province\` varchar(255) DEFAULT NULL COMMENT '省份',
\`city\` varchar(255) DEFAULT NULL COMMENT '城市',
\`area\` varchar(255) DEFAULT NULL COMMENT '区',
\`town\` varchar(255) DEFAULT NULL COMMENT '镇',
\`detail_address\` varchar(255) DEFAULT NULL COMMENT '详细地址',
\`id_type\` varchar(255) DEFAULT NULL COMMENT '证件类型',
\`id_number\` int(11) DEFAULT NULL COMMENT '证件号码',
\`oaid\` text COMMENT 'OAID',
\`sync_status\` enum('padding','fin','error') DEFAULT 'padding' COMMENT '同步状态',
\`store_id\` bigint(20) UNSIGNED DEFAULT NULL COMMENT '货主id',
\`warehouse_id\` bigint(20) UNSIGNED DEFAULT NULL COMMENT '仓库id',
\`from_key\` int(11) DEFAULT NULL COMMENT '来源键',
\`items\` text COMMENT '商品结构字符串',
\`items_count\` smallint(5) UNSIGNED NOT NULL DEFAULT '0' COMMENT '商品种类数',
\`items_total\` int(10) UNSIGNED NOT NULL DEFAULT '0' COMMENT '商品总数',
\`items_weight\` decimal(10,2) NOT NULL DEFAULT '0.00' COMMENT '总重量',
\`items_hash\` char(32) NOT NULL DEFAULT '' COMMENT '哈希值',
\`items_crc\` int(10) UNSIGNED NOT NULL DEFAULT '0' COMMENT '校验码',
\`wave_id\` bigint(20) NOT NULL DEFAULT '0' COMMENT '波次ID,0表示未分配',
\`post_status\` enum('padding','fin','timeout','error','none') DEFAULT 'none' COMMENT '分配快递号状态机',
\`storage_status\` enum('padding','fin','error','none') DEFAULT 'none' COMMENT '分配储位状态机',
\`pick_status\` enum('padding','fin','error','none') DEFAULT 'none' COMMENT '拣货状态机',
\`pack_status\` enum('none','padding','fin','error') DEFAULT 'none' COMMENT '打包状态机',
\`inspection_status\` enum('none','padding','running','fin','error') DEFAULT 'none' COMMENT '检验状态机',
\`step\` int(10) NOT NULL DEFAULT '0' COMMENT '订单步骤:0未审核,1已审核',
\`print_status\` enum('none','padding','fin','error') DEFAULT NULL COMMENT '打印状态机',
\`claim_status\` enum('none','padding','fin','error') DEFAULT 'none' COMMENT '领取状态机',
\`outbound_status\` enum('none','padding','fin','error') DEFAULT 'none' COMMENT '出库状态机',
\`lock_status\` enum('none','warehouse','store') DEFAULT NULL COMMENT '锁定状态机',
\`intercept_status\` enum('none','requesting','requested','intercepting','intercepted_in_transit','intercepted_at_warehouse','returning','returned','delivered_by_mistake','timeout','cancelled','failed','exception') DEFAULT NULL COMMENT '拦截状态机'
${historyFields},
PRIMARY KEY (\`id\`),
UNIQUE KEY \`idx_${warehouseId}_${type}_delivery_code\` (\`delivery_order_code\`,\`store_id\`,\`warehouse_id\`),
KEY \`idx_${warehouseId}_${type}_store_id\` (\`store_id\`),
KEY \`idx_${warehouseId}_${type}_warehouse_id\` (\`warehouse_id\`),
KEY \`idx_${warehouseId}_${type}_items\` (\`items\`(50)),
KEY \`idx_${warehouseId}_${type}_items_hash\` (\`items_hash\`),
KEY \`idx_${warehouseId}_${type}_hash_crc\` (\`items_hash\`,\`items_crc\`,\`warehouse_id\`),
KEY \`idx_${warehouseId}_${type}_wave\` (\`status\`,\`wave_id\`),
KEY \`idx_${warehouseId}_${type}_statuses\` (\`status\`,\`post_status\`,\`pick_status\`,\`pack_status\`,\`outbound_status\`)
${type === 'history' ? `,KEY \`idx_${warehouseId}_history_archive_time\` (\`archive_time\`)` : ''}
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci COMMENT='${tableComment}';
`;
await this.app.model.query(createTableSQL);
this.app.logger.info(`创建物理表成功: ${tableName}`);
await dynamicModel.sync({ alter: true });
this.app.logger.info(`创建/同步物理表成功: ${tableName}`);
}
/**
@ -387,7 +700,7 @@ module.exports = app => {
step: [ 0, 1 ],
print_status: [ 'none', 'padding', 'fin', 'error' ],
claim_status: [ 'none', 'padding', 'fin', 'error' ],
outbound_status: [ 'none', 'padding', 'fin', 'error' ],
outbound_status: [ 'none', 'padding', 'fin', 'timeout', 'error' ],
lock_status: [ 'none', 'warehouse', 'store' ],
intercept_status: [
'none', 'requesting', 'requested', 'intercepting',
@ -405,8 +718,18 @@ module.exports = app => {
* @return {string} 表名
*/
generateTableName(warehouseId, type) {
const suffix = type === 'history' ? '_history' : '';
return `wms_order_delivery_${warehouseId}${suffix}`;
const modelType = this.resolveModelType(type);
return buildManagedTableName(warehouseId, modelType);
}
/**
* 获取订单工厂管理表的注释。
* @param {number|string} warehouseId 仓库ID。
* @param {string} type 模型类型。
* @return {string} 表注释。
*/
getTableComment(warehouseId, type) {
return buildTableComment(warehouseId, type);
}
/**
@ -414,6 +737,7 @@ module.exports = app => {
*/
clearCache() {
this.modelCache.clear();
clearShardWarehouseValidationCache(this.app);
this.app.logger.info('模型缓存已清理');
}

View File

@ -0,0 +1,521 @@
'use strict';
const MANAGED_TYPES = Object.freeze({
CURRENT: 'current',
HISTORY: 'history',
DISPATCH: 'dispatch',
OUTSOURCED: 'outsourced',
});
const TABLE_PATTERNS = Object.freeze([
{
type: MANAGED_TYPES.DISPATCH,
pattern: /^wms_order_delivery_dispatch_(\d+)$/,
},
{
type: MANAGED_TYPES.HISTORY,
pattern: /^wms_order_delivery_(\d+)_history$/,
},
{
type: MANAGED_TYPES.OUTSOURCED,
pattern: /^wms_order_delivery_(\d+)_outsourced$/,
},
{
type: MANAGED_TYPES.CURRENT,
pattern: /^wms_order_delivery_(\d+)$/,
},
]);
/**
* 规范化订单工厂管理的模型类型。
* @param {string} type 模型类型。
* @return {string} 规范化后的模型类型。
*/
function normalizeManagedType(type) {
return Object.values(MANAGED_TYPES).includes(type) ? type : MANAGED_TYPES.CURRENT;
}
/**
* 判断是否为配送域类型。
* @param {string} type 模型类型。
* @return {boolean} 是否为配送域类型。
*/
function isDispatchType(type) {
return normalizeManagedType(type) === MANAGED_TYPES.DISPATCH;
}
/**
* 判断是否为历史类型。
* @param {string} type 模型类型。
* @return {boolean} 是否为历史类型。
*/
function isHistoryType(type) {
return normalizeManagedType(type) === MANAGED_TYPES.HISTORY;
}
/**
* 判断是否为 outsourced 类型。
* @param {string} type 模型类型。
* @return {boolean} 是否为 outsourced 类型。
*/
function isOutsourcedType(type) {
return normalizeManagedType(type) === MANAGED_TYPES.OUTSOURCED;
}
/**
* 克隆模型属性定义,避免直接修改基础模型对象。
* @param {Object} attributes 原始属性定义。
* @return {Object} 克隆后的属性定义。
*/
function cloneAttributes(attributes) {
return Object.entries(attributes).reduce((result, [ name, attribute ]) => {
result[name] = { ...attribute };
return result;
}, {});
}
/**
* 规范化索引字段定义。
* @param {string|Object} field 字段定义。
* @return {{ attribute: string, length?: number }} 规范化后的字段定义。
*/
function normalizeIndexField(field) {
if (typeof field === 'string') {
return { attribute: field };
}
if (!field || typeof field !== 'object') {
return { attribute: String(field) };
}
const attribute = field.attribute || field.name || field.field || field.columnName || field.column_name;
const normalizedField = {
attribute: attribute ? String(attribute) : '',
};
if (Object.prototype.hasOwnProperty.call(field, 'length') && field.length !== undefined && field.length !== null) {
normalizedField.length = Number(field.length);
}
return normalizedField;
}
/**
* 规范化索引定义。
* @param {Object} index 索引定义。
* @return {{ name: string, unique: boolean, fields: Array<Object> }} 规范化后的索引定义。
*/
function normalizeIndexDefinition(index) {
return {
name: index.name || index.Key_name || index.key_name || '',
unique: Boolean(index.unique || index.Unique || (typeof index.nonUnique === 'number' ? index.nonUnique === 0 : false)),
fields: Array.isArray(index.fields) ? index.fields.map(normalizeIndexField) : [],
};
}
/**
* 规范化 Sequelize 数值类型的 SQL 定义。
* @param {Object} attribute Sequelize 属性定义。
* @return {{ type: string, unsigned: boolean, min: string, max: string, precision?: number, scale?: number }|null} 数值约束信息。
*/
function parseNumericConstraint(attribute) {
let typeSql = '';
if (attribute && attribute.type && typeof attribute.type.toSql === 'function') {
try {
typeSql = attribute.type.toSql();
} catch (error) {
return null;
}
} else {
typeSql = String(attribute && attribute.type || '');
}
const normalizedTypeSql = String(typeSql || '')
.trim()
.replace(/\s+/g, ' ')
.toUpperCase();
if (!normalizedTypeSql) {
return null;
}
const integerMatch = normalizedTypeSql.match(/^(TINYINT|SMALLINT|MEDIUMINT|INT|INTEGER|BIGINT)\s*(?:\(\s*\d+\s*\))?(?:\s+UNSIGNED)?$/i);
if (integerMatch) {
const integerBits = {
TINYINT: 8,
SMALLINT: 16,
MEDIUMINT: 24,
INT: 32,
INTEGER: 32,
BIGINT: 64,
}[integerMatch[1].toUpperCase()];
const unsigned = /\bUNSIGNED\b/i.test(normalizedTypeSql);
const bigBits = BigInt(integerBits);
const max = unsigned
? (2n ** bigBits) - 1n
: (2n ** (bigBits - 1n)) - 1n;
const min = unsigned
? 0n
: -(2n ** (bigBits - 1n));
return {
type: integerMatch[1].toUpperCase(),
unsigned,
min: min.toString(),
max: max.toString(),
};
}
const decimalMatch = normalizedTypeSql.match(/^(DECIMAL|NUMERIC)\s*\(\s*(\d+)\s*,\s*(\d+)\s*\)(?:\s+UNSIGNED)?$/i);
if (decimalMatch) {
const precision = Number(decimalMatch[2]);
const scale = Number(decimalMatch[3]);
const unsigned = /\bUNSIGNED\b/i.test(normalizedTypeSql);
const integerDigits = precision - scale;
if (!Number.isInteger(precision) || !Number.isInteger(scale) || precision <= 0 || scale < 0 || integerDigits <= 0) {
return null;
}
const integerPart = '9'.repeat(integerDigits);
const decimalPart = scale > 0 ? `.${'9'.repeat(scale)}` : '';
return {
type: decimalMatch[1].toUpperCase(),
unsigned,
precision,
scale,
min: `-${integerPart}${decimalPart}`,
max: `${integerPart}${decimalPart}`,
};
}
return null;
}
/**
* 生成默认值 SQL 片段。
* @param {*} defaultValue 默认值。
* @return {string} SQL 片段。
*/
function formatDefaultValue(defaultValue) {
if (defaultValue === null) {
return 'NULL';
}
if (defaultValue === undefined) {
return '';
}
if (defaultValue && typeof defaultValue.toSql === 'function') {
return defaultValue.toSql();
}
if (typeof defaultValue === 'string') {
const escaped = defaultValue.replace(/'/g, "''");
return `'${escaped}'`;
}
if (typeof defaultValue === 'number' || typeof defaultValue === 'bigint') {
return String(defaultValue);
}
if (typeof defaultValue === 'boolean') {
return defaultValue ? '1' : '0';
}
return `'${String(defaultValue).replace(/'/g, "''")}'`;
}
/**
* 将 Sequelize 属性定义转换为 DDL 列片段。
* @param {string} columnName 列名。
* @param {Object} attribute Sequelize 属性定义。
* @return {string} DDL 列片段。
*/
function buildColumnLine(columnName, attribute) {
const parts = [ `\`${columnName}\``, attribute.type && typeof attribute.type.toSql === 'function'
? attribute.type.toSql()
: String(attribute.type || ''),
];
if (attribute.allowNull === false) {
parts.push('NOT NULL');
}
if (attribute.autoIncrement) {
parts.push('AUTO_INCREMENT');
}
if (Object.prototype.hasOwnProperty.call(attribute, 'defaultValue')) {
const defaultSql = formatDefaultValue(attribute.defaultValue);
if (defaultSql) {
parts.push(`DEFAULT ${defaultSql}`);
}
}
if (attribute.comment) {
parts.push(`COMMENT '${String(attribute.comment).replace(/'/g, "''")}'`);
}
return parts.join(' ');
}
/**
* 构建模型属性定义。
* @param {Object} app Egg 应用实例。
* @param {string} type 模型类型。
* @return {Object} 属性定义。
*/
function buildTableAttributes(app, type) {
const modelType = normalizeManagedType(type);
const attributes = cloneAttributes(app.model.OrderDelivery.rawAttributes);
if (isDispatchType(modelType)) {
const { ENUM } = app.Sequelize;
attributes.dispatch_lane = {
type: ENUM('m4', 'm5'),
field: 'dispatch_lane',
allowNull: false,
defaultValue: 'm4',
comment: '配送工作台子域(M4正常/M5异常)',
};
}
if (isHistoryType(modelType)) {
attributes.archive_time = {
type: app.Sequelize.DATE,
field: 'archive_time',
allowNull: true,
defaultValue: null,
comment: '归档时间',
};
}
return attributes;
}
/**
* 构建表名。
* @param {number|string} warehouseId 仓库ID。
* @param {string} type 模型类型。
* @return {string} 表名。
*/
function buildTableName(warehouseId, type) {
const modelType = normalizeManagedType(type);
if (isDispatchType(modelType)) {
return `wms_order_delivery_dispatch_${warehouseId}`;
}
if (isOutsourcedType(modelType)) {
return `wms_order_delivery_${warehouseId}_outsourced`;
}
const suffix = isHistoryType(modelType) ? '_history' : '';
return `wms_order_delivery_${warehouseId}${suffix}`;
}
/**
* 构建表注释。
* @param {number|string} warehouseId 仓库ID。
* @param {string} type 模型类型。
* @return {string} 表注释。
*/
function buildTableComment(warehouseId, type) {
const modelType = normalizeManagedType(type);
if (isDispatchType(modelType)) {
return `仓库${warehouseId}发货单配送域(M4/M5)影子表`;
}
if (isHistoryType(modelType)) {
return `仓库${warehouseId}发货单历史表`;
}
if (isOutsourcedType(modelType)) {
return `仓库${warehouseId}发货单外仓表`;
}
return `仓库${warehouseId}发货单常用表`;
}
/**
* 构建模型选项。
* @param {Object} app Egg 应用实例。
* @param {number|string} warehouseId 仓库ID。
* @param {string} type 模型类型。
* @return {Object} Sequelize 模型选项。
*/
function buildTableOptions(app, warehouseId, type) {
const modelType = normalizeManagedType(type);
const options = {
tableName: buildTableName(warehouseId, modelType),
timestamps: false,
comment: buildTableComment(warehouseId, modelType),
indexes: buildIndexOptions(warehouseId, modelType),
};
if (isHistoryType(modelType)) {
options.fields = Object.keys(buildTableAttributes(app, modelType));
}
return options;
}
/**
* 构建索引选项。
* @param {number|string} warehouseId 仓库ID。
* @param {string} type 模型类型。
* @return {Array<Object>} 索引选项。
*/
function buildIndexOptions(warehouseId, type) {
const modelType = normalizeManagedType(type);
const prefix = `${warehouseId}_${modelType}`;
if (isDispatchType(modelType)) {
const baseIndexes = buildIndexOptions(warehouseId, MANAGED_TYPES.CURRENT);
const dispatchLaneIndex = {
name: `idx_dispatch_${warehouseId}_dispatch_lane`,
fields: [ 'dispatch_lane', 'status' ],
};
return [
baseIndexes[0],
baseIndexes[1],
baseIndexes[2],
dispatchLaneIndex,
...baseIndexes.slice(3),
];
}
const indexes = [
{
name: `idx_${prefix}_store_id`,
fields: [ 'store_id' ],
},
{
name: `idx_${prefix}_warehouse_id`,
fields: [ 'warehouse_id' ],
},
{
name: `idx_${prefix}_delivery_code`,
unique: true,
fields: [ 'delivery_order_code', 'store_id', 'warehouse_id' ],
},
{
name: `idx_${prefix}_items`,
fields: [{ attribute: 'items', length: 50 }],
},
{
name: `idx_${prefix}_items_hash`,
fields: [ 'items_hash' ],
},
{
name: `idx_${prefix}_hash_crc`,
fields: [ 'items_hash', 'items_crc', 'warehouse_id' ],
},
{
name: `idx_${prefix}_wave`,
fields: [ 'status', 'wave_id' ],
},
{
name: `idx_${prefix}_statuses`,
fields: [
'status',
'post_status',
'pick_status',
'pack_status',
'outbound_status',
],
},
];
if (isHistoryType(modelType)) {
indexes.push({
name: `idx_${warehouseId}_history_archive_time`,
fields: [ 'archive_time' ],
});
}
return indexes;
}
/**
* 将索引选项转换为 DDL 片段。
* @param {Object} index 索引定义。
* @return {string} DDL 索引片段。
*/
function buildIndexLine(index) {
const fieldParts = index.fields.map(field => {
const normalizedField = normalizeIndexField(field);
const length = Object.prototype.hasOwnProperty.call(normalizedField, 'length')
? `(${normalizedField.length})`
: '';
return `\`${normalizedField.attribute}\`${length}`;
});
const prefix = index.unique ? 'UNIQUE KEY' : 'KEY';
return `${prefix} \`${index.name}\` (${fieldParts.join(',')})`;
}
/**
* 构建表列定义行。
* @param {Object} app Egg 应用实例。
* @param {string} type 模型类型。
* @return {Array<string>} 列定义行。
*/
function buildColumnLines(app, type) {
return Object.entries(buildTableAttributes(app, type)).map(([ columnName, attribute ]) => buildColumnLine(columnName, attribute));
}
/**
* 构建表索引定义行。
* @param {number|string} warehouseId 仓库ID。
* @param {string} type 模型类型。
* @return {Array<string>} 索引定义行。
*/
function buildIndexLines(warehouseId, type) {
return buildIndexOptions(warehouseId, type).map(buildIndexLine);
}
/**
* 解析订单工厂管理的表名。
* @param {string} tableName 表名。
* @return {{ type: string, warehouseId: string }|null} 解析结果。
*/
function parseManagedTableName(tableName) {
for (const item of TABLE_PATTERNS) {
const match = item.pattern.exec(tableName);
if (match) {
return {
type: item.type,
warehouseId: match[1],
};
}
}
return null;
}
module.exports = {
MANAGED_TYPES,
normalizeManagedType,
isDispatchType,
isHistoryType,
isOutsourcedType,
normalizeIndexField,
normalizeIndexDefinition,
parseNumericConstraint,
buildTableAttributes,
buildTableName,
buildTableComment,
buildTableOptions,
buildIndexOptions,
buildColumnLines,
buildIndexLines,
parseManagedTableName,
};

View File

@ -87,6 +87,11 @@ module.exports = app => {
allowNull: true,
comment: '库存ID',
},
item_snapshot: {
type: JSON,
allowNull: true,
comment: '商品快照',
},
created_at: {
type: Sequelize.DATE,
allowNull: false,

View File

@ -1,6 +1,101 @@
// order_items_factory.js
'use strict';
const {
ensureShardWarehouseId,
clearShardWarehouseValidationCache,
} = require('../lib/warehouse_shard_guard');
/**
* 克隆模型属性定义。
* @param {Object} attributes 属性定义。
* @return {Object} 克隆后的属性定义。
*/
function cloneAttributes(attributes) {
return Object.entries(attributes || {}).reduce((result, [ key, value ]) => {
result[key] = { ...value };
return result;
}, {});
}
/**
* 规范化索引定义。
* @param {Object} index 索引定义。
* @return {Object} 规范化后的索引定义。
*/
function normalizeIndexDefinition(index) {
let unique = false;
if (index && Object.prototype.hasOwnProperty.call(index, 'unique')) {
unique = Boolean(index.unique);
} else if (index && Object.prototype.hasOwnProperty.call(index, 'Unique')) {
unique = Boolean(index.Unique);
} else if (index && Object.prototype.hasOwnProperty.call(index, 'nonUnique')) {
unique = Number(index.nonUnique) === 0;
}
return {
name: index && (index.name || index.Key_name || index.key_name || index.index_name) || '',
unique,
fields: Array.isArray(index && index.fields)
? index.fields.map(field => {
if (typeof field === 'string') {
return {
attribute: field,
};
}
return {
attribute: field.attribute || field.name || field.field || field.columnName || '',
length: field.length,
};
})
: [],
};
}
/**
* 判断两个索引定义是否存在结构差异。
* @param {Object} expectedIndex 预期索引定义。
* @param {Object} actualIndex 实际索引定义。
* @return {boolean} 是否存在结构差异。
*/
function isIndexDefinitionDifferent(expectedIndex, actualIndex) {
const normalizedExpected = normalizeIndexDefinition(expectedIndex);
const normalizedActual = normalizeIndexDefinition(actualIndex);
if (!normalizedActual.name) {
return true;
}
if (normalizedExpected.unique !== normalizedActual.unique) {
return true;
}
if (normalizedExpected.fields.length !== normalizedActual.fields.length) {
return true;
}
for (let index = 0; index < normalizedExpected.fields.length; index += 1) {
const expectedField = normalizedExpected.fields[index];
const actualField = normalizedActual.fields[index];
if (!expectedField.attribute || !actualField.attribute) {
return true;
}
if (expectedField.attribute !== actualField.attribute) {
return true;
}
if (Object.prototype.hasOwnProperty.call(expectedField, 'length') && expectedField.length !== actualField.length) {
return true;
}
}
return false;
}
module.exports = app => {
const { Sequelize } = app;
@ -29,6 +124,15 @@ module.exports = app => {
return await this.getOrCreateModel(warehouseId, 'history');
}
/**
* 获取配送表模型。
* @param {number} warehouseId 仓库ID
* @return {Promise<Object>} 配送表模型
*/
async getDispatchModel(warehouseId) {
return await this.getOrCreateModel(warehouseId, 'dispatch');
}
/**
* 获取或创建模型
* @param {number} warehouseId 仓库ID
@ -36,14 +140,15 @@ module.exports = app => {
* @return {Promise<Object>} 动态模型
*/
async getOrCreateModel(warehouseId, type = 'current') {
const cacheKey = `${warehouseId}_${type}`;
const warehouseIdStr = await ensureShardWarehouseId(this.app, warehouseId);
const cacheKey = `${warehouseIdStr}_${type}`;
// 检查缓存
if (this.modelCache.has(cacheKey)) {
return this.modelCache.get(cacheKey);
}
const tableName = this.generateTableName(warehouseId, type);
const tableName = this.generateTableName(warehouseIdStr, type);
try {
// 防止并发创建表
@ -52,7 +157,7 @@ module.exports = app => {
return this.modelCache.get(cacheKey);
}
const createPromise = this.createModelWithRetry(warehouseId, type, tableName, cacheKey);
const createPromise = this.createModelWithRetry(warehouseIdStr, type, tableName, cacheKey);
this.creatingTables.set(cacheKey, createPromise);
const dynamicModel = await createPromise;
@ -78,34 +183,12 @@ module.exports = app => {
async createModelWithRetry(warehouseId, type, tableName, cacheKey, retryCount = 3) {
for (let i = 0; i < retryCount; i++) {
try {
// 检查表是否存在
const tableExists = await this.checkTableExists(tableName);
if (!tableExists) {
await this.createPhysicalTable(warehouseId, type);
}
const DynamicModel = this.buildDynamicModel(warehouseId, type, tableName);
// 创建模型实例
const mainModel = this.app.model.OrderItems;
const attributes = { ...mainModel.rawAttributes };
// 移除主键的autoIncrement属性,避免动态表冲突
if (attributes.id) {
delete attributes.id.autoIncrement;
}
const DynamicModel = this.app.model.define(tableName, attributes, {
tableName,
timestamps: true,
underscored: true,
paranoid: false,
indexes: this.generateIndexes(warehouseId),
comment: type === 'history'
? `仓库${warehouseId}订单商品历史表`
: `仓库${warehouseId}订单商品常用表`,
});
await this.ensureManagedTableSchema(tableName, type, warehouseId, DynamicModel);
// 复制关联关系
this.copyAssociations(mainModel, DynamicModel);
this.copyAssociations(this.app.model.OrderItems, DynamicModel);
// 缓存模型
this.modelCache.set(cacheKey, DynamicModel);
@ -150,6 +233,56 @@ module.exports = app => {
}
}
/**
* 构建订单商品动态模型。
* @param {number|string} warehouseId 仓库ID。
* @param {string} type 模型类型。
* @param {string} tableName 表名。
* @return {Object} 动态模型。
*/
buildDynamicModel(warehouseId, type, tableName) {
const attributes = this.getTableAttributes(type);
const modelComment = type === 'history'
? `仓库${warehouseId}订单商品历史表`
: type === 'dispatch'
? `仓库${warehouseId}订单商品配送表`
: `仓库${warehouseId}订单商品常用表`;
return this.app.model.define(tableName, attributes, {
tableName,
timestamps: true,
underscored: true,
paranoid: false,
indexes: this.generateIndexes(warehouseId),
comment: modelComment,
});
}
/**
* 获取订单商品模型属性定义。
* @param {string} type 模型类型。
* @return {Object} 属性定义。
*/
getTableAttributes(type) {
const mainModel = this.app.model.OrderItems;
const attributes = cloneAttributes(mainModel && mainModel.rawAttributes);
if (attributes.id) {
delete attributes.id.autoIncrement;
}
if (type === 'history' && !attributes.archive_time) {
attributes.archive_time = {
type: this.app.Sequelize.DATE,
allowNull: true,
defaultValue: this.app.Sequelize.literal('CURRENT_TIMESTAMP'),
comment: '归档时间',
};
}
return attributes;
}
/**
* 生成索引配置
* @param {number} warehouseId 仓库ID
@ -206,7 +339,9 @@ module.exports = app => {
type: Sequelize.QueryTypes.SELECT,
}
);
return !!results;
return Array.isArray(results)
? results.length > 0
: Boolean(results);
} catch (error) {
this.app.logger.error('检查表是否存在失败:', error);
return false;
@ -214,55 +349,130 @@ module.exports = app => {
}
/**
* 创建物理表
* 判断目标表是否需要进行结构同步。
* @param {string} tableName 表名。
* @param {string} type 模型类型。
* @param {number|string} warehouseId 仓库ID。
* @param {boolean|null} [tableExists=null] 是否已确认表存在。
* @return {Promise<boolean>} 是否需要同步。
*/
async needsTableSchemaSync(tableName, type, warehouseId, tableExists = null) {
const queryInterface = this.app.model.getQueryInterface();
const managedTableExists = typeof tableExists === 'boolean'
? tableExists
: await this.checkTableExists(tableName);
if (!managedTableExists) {
return true;
}
const [ tables, indexes ] = await Promise.all([
queryInterface.describeTable(tableName),
typeof queryInterface.showIndex === 'function'
? queryInterface.showIndex(tableName)
: Promise.resolve([]),
]);
const expectedAttributes = this.getTableAttributes(type);
const expectedAttributeNames = Object.keys(expectedAttributes);
const actualAttributeNames = Object.keys(tables || {});
if (expectedAttributeNames.length !== actualAttributeNames.length) {
return true;
}
const actualColumnNames = new Set(actualAttributeNames);
for (const columnName of expectedAttributeNames) {
if (!actualColumnNames.has(columnName)) {
return true;
}
}
for (const columnName of expectedAttributeNames) {
const expectedColumn = expectedAttributes[columnName];
const actualColumn = tables[columnName] || {};
const expectedType = expectedColumn.type && typeof expectedColumn.type.toSql === 'function'
? expectedColumn.type.toSql().toLowerCase()
: String(expectedColumn.type || '').toLowerCase();
const actualType = String(actualColumn.type || actualColumn.Type || '').toLowerCase();
const expectedAllowNull = expectedColumn.allowNull !== false;
const actualAllowNull = actualColumn.allowNull !== false;
const expectedDefault = Object.prototype.hasOwnProperty.call(expectedColumn, 'defaultValue')
? expectedColumn.defaultValue
: undefined;
const actualDefault = Object.prototype.hasOwnProperty.call(actualColumn, 'defaultValue')
? actualColumn.defaultValue
: undefined;
if (expectedType && actualType && expectedType !== actualType) {
return true;
}
if (expectedAllowNull !== actualAllowNull) {
return true;
}
const normalizedExpectedDefault = expectedDefault == null ? null : String(expectedDefault);
const normalizedActualDefault = actualDefault == null ? null : String(actualDefault);
if (normalizedExpectedDefault !== normalizedActualDefault) {
return true;
}
}
const expectedIndexes = this.generateIndexes(warehouseId);
const actualIndexes = Array.isArray(indexes) ? indexes : [];
for (const expectedIndex of expectedIndexes) {
const actualIndex = actualIndexes.find(index => (index.Key_name || index.name) === expectedIndex.name);
if (!actualIndex) {
return true;
}
if (isIndexDefinitionDifferent(expectedIndex, actualIndex)) {
return true;
}
}
return false;
}
/**
* 确保目标表与模型结构一致。
* @param {string} tableName 表名。
* @param {string} type 模型类型。
* @param {number|string} warehouseId 仓库ID。
* @param {Object} [DynamicModel] 已构建的动态模型。
* @return {Promise<boolean>} 是否执行了同步。
*/
async ensureManagedTableSchema(tableName, type, warehouseId, DynamicModel = null) {
const dynamicModel = DynamicModel || this.buildDynamicModel(warehouseId, type, tableName);
const tableExists = await this.checkTableExists(tableName);
const needsSync = tableExists
? await this.needsTableSchemaSync(tableName, type, warehouseId, tableExists)
: true;
if (!needsSync) {
return false;
}
await dynamicModel.sync({ alter: true });
return true;
}
/**
* 创建物理表。
* @param {number} warehouseId 仓库ID
* @param {string} type 模型类型
*/
async createPhysicalTable(warehouseId, type = 'current') {
const tableName = this.generateTableName(warehouseId, type);
const tableComment = type === 'history'
? `仓库${warehouseId}订单商品历史表`
: `仓库${warehouseId}订单商品常用表`;
const dynamicModel = this.buildDynamicModel(warehouseId, type, tableName);
// 历史表特有字段
const historyFields = type === 'history' ?
',`archive_time` datetime DEFAULT CURRENT_TIMESTAMP COMMENT \'归档时间\'' : '';
const createTableSQL = `
CREATE TABLE IF NOT EXISTS \`${tableName}\` (
\`id\` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
\`order_id\` bigint(20) unsigned DEFAULT NULL COMMENT '订单ID',
\`actual_price\` decimal(18,2) NOT NULL DEFAULT '0.00' COMMENT '实际价格',
\`retail_price\` decimal(18,2) DEFAULT NULL COMMENT '零售价格',
\`ext_code\` varchar(50) DEFAULT NULL COMMENT '外部编码',
\`inventory_type\` varchar(50) DEFAULT NULL COMMENT '库存类型',
\`item_code\` varchar(50) DEFAULT NULL COMMENT '商品编码',
\`item_id\` bigint(20) DEFAULT NULL COMMENT '商品ID',
\`item_name\` varchar(200) DEFAULT NULL COMMENT '商品名称',
\`order_line_no\` varchar(50) DEFAULT NULL COMMENT '订单行号',
\`owner_code\` varchar(50) DEFAULT NULL COMMENT '货主编码',
\`plan_qty\` int(11) DEFAULT NULL COMMENT '计划数量',
\`source_order_code\` varchar(50) DEFAULT NULL COMMENT '源订单编码',
\`sub_source_order_code\` varchar(50) DEFAULT NULL COMMENT '子源订单编码',
\`extend_props\` json DEFAULT NULL COMMENT '扩展属性(JSON格式)',
\`stock_id\` bigint(20) DEFAULT NULL COMMENT '库存ID',
\`created_at\` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
\`updated_at\` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间'
${historyFields},
PRIMARY KEY (\`id\`),
KEY \`idx_${warehouseId}_order_id\` (\`order_id\`),
KEY \`idx_${warehouseId}_item_id\` (\`item_id\`),
KEY \`idx_${warehouseId}_item_code\` (\`item_code\`),
KEY \`idx_${warehouseId}_source_order_code\` (\`source_order_code\`),
KEY \`idx_${warehouseId}_stock_id\` (\`stock_id\`),
KEY \`idx_${warehouseId}_owner_code\` (\`owner_code\`),
KEY \`idx_${warehouseId}_order_item\` (\`order_id\`, \`item_id\`),
KEY \`idx_${warehouseId}_created_at\` (\`created_at\`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='${tableComment}';
`;
await this.app.model.query(createTableSQL);
this.app.logger.info(`创建订单商品物理表成功: ${tableName}`);
await dynamicModel.sync({ alter: true });
this.app.logger.info(`创建/同步订单商品物理表成功: ${tableName}`);
}
/**
@ -271,7 +481,11 @@ module.exports = app => {
* @param {string} type 模型类型
*/
generateTableName(warehouseId, type) {
const suffix = type === 'history' ? '_history' : '';
const suffix = type === 'history'
? '_history'
: type === 'dispatch'
? '_dispatch'
: '';
return `wms_order_items_${warehouseId}${suffix}`;
}
@ -283,6 +497,8 @@ module.exports = app => {
clearCache(warehouseId, type) {
const cacheKey = `${warehouseId}_${type}`;
this.modelCache.delete(cacheKey);
this.creatingTables.delete(cacheKey);
clearShardWarehouseValidationCache(this.app);
}
/**
@ -290,6 +506,8 @@ module.exports = app => {
*/
clearAllCache() {
this.modelCache.clear();
this.creatingTables.clear();
clearShardWarehouseValidationCache(this.app);
}
/**

128
app/model/picking.js Normal file
View File

@ -0,0 +1,128 @@
'use strict';
module.exports = app => {
const { BIGINT, STRING, DATE, INTEGER } = app.Sequelize;
const Picking = app.model.define('picking', {
id: {
type: BIGINT(20).UNSIGNED,
primaryKey: true,
autoIncrement: true,
allowNull: false,
comment: '主键ID',
},
order_id: {
type: BIGINT(20).UNSIGNED,
allowNull: false,
comment: '订单ID',
},
order_item_id: {
type: BIGINT(20).UNSIGNED,
allowNull: false,
comment: '订单明细ID',
},
storage_id: {
type: BIGINT(20).UNSIGNED,
allowNull: true,
comment: '库存记录ID',
},
quantity: {
type: INTEGER(10).UNSIGNED,
allowNull: false,
defaultValue: 1,
comment: '分配数量',
},
space_id: {
type: BIGINT(20).UNSIGNED,
allowNull: true,
comment: '库位ID',
},
space_name: {
type: STRING(100),
allowNull: true,
comment: '库位名称',
},
status: {
type: STRING(20),
allowNull: false,
defaultValue: 'pending',
comment: '状态',
},
created_at: {
type: DATE,
allowNull: false,
defaultValue: app.Sequelize.literal('CURRENT_TIMESTAMP'),
comment: '创建时间',
},
updated_at: {
type: DATE,
allowNull: false,
defaultValue: app.Sequelize.literal('CURRENT_TIMESTAMP'),
comment: '更新时间',
},
}, {
tableName: 'wms_picking',
freezeTableName: true,
underscored: true,
timestamps: true,
createdAt: 'created_at',
updatedAt: 'updated_at',
comment: '订单储位分配表',
indexes: [
{
name: 'idx_wms_picking_order_id',
fields: [ 'order_id' ],
},
{
name: 'idx_wms_picking_order_item_id',
fields: [ 'order_item_id' ],
},
{
name: 'idx_wms_picking_storage_id',
fields: [ 'storage_id' ],
},
{
name: 'idx_wms_picking_space_id',
fields: [ 'space_id' ],
},
{
name: 'idx_wms_picking_status',
fields: [ 'status' ],
},
{
name: 'idx_wms_picking_order_item_space',
fields: [ 'order_item_id', 'space_id' ],
},
],
});
Picking.associate = function() {
const { OrderItems, Storage, LocationSpace } = app.model;
if (OrderItems) {
Picking.belongsTo(OrderItems, {
foreignKey: 'order_item_id',
as: 'orderItem',
constraints: false,
});
}
if (Storage) {
Picking.belongsTo(Storage, {
foreignKey: 'storage_id',
as: 'storageRecord',
constraints: false,
});
}
if (LocationSpace) {
Picking.belongsTo(LocationSpace, {
foreignKey: 'space_id',
as: 'space',
constraints: false,
});
}
};
return Picking;
};

View File

@ -191,6 +191,26 @@ module.exports = app => {
type: INTEGER(11).UNSIGNED,
defaultValue: 0,
},
inbound_min_days:{
type: INTEGER(11),
defaultValue: 0,
comment: '入库最小天数要求',
},
outbound_min_days:{
type: INTEGER(11),
defaultValue: 0,
comment: '出库最小天数要求',
},
shelf_life_days:{
type: INTEGER(11),
defaultValue: 0,
comment: '保质期天数',
},
remaining_threshold_days:{
type: INTEGER(11),
defaultValue: 0,
comment: '剩余有效期阈值天数',
},
deleted_at: {
type: DATE,
defaultValue: null,

View File

@ -5,8 +5,19 @@ module.exports = app => {
const DEFAULT_MAX_NOTICE_WEBHOOK_COUNT = 5;
const DEFAULT_SUBJECT_CONFIG = Object.freeze({
max_notice_webhook_count: DEFAULT_MAX_NOTICE_WEBHOOK_COUNT,
default_express_code: 'STO',
default_platform_code: 'TB',
});
const normalizeSubjectConfigText = (value, defaultValue) => {
if (value === undefined || value === null) {
return defaultValue;
}
const normalized = String(value).trim();
return normalized === '' ? defaultValue : normalized;
};
const normalizeBooleanFlag = (value, fieldName) => {
if (value === undefined || value === null || value === '') {
return undefined;
@ -56,6 +67,15 @@ module.exports = app => {
normalized.max_notice_webhook_count = limit;
}
normalized.default_express_code = normalizeSubjectConfigText(
parsed.default_express_code,
DEFAULT_SUBJECT_CONFIG.default_express_code
);
normalized.default_platform_code = normalizeSubjectConfigText(
parsed.default_platform_code,
DEFAULT_SUBJECT_CONFIG.default_platform_code
);
if (Object.prototype.hasOwnProperty.call(parsed, 'webhook_enabled')) {
normalized.webhook_enabled = normalizeBooleanFlag(parsed.webhook_enabled, 'subject_config.webhook_enabled');
}

View File

@ -11,16 +11,11 @@ module.exports = app => {
default: 'standard',
required: false,
description: '控制货主在该仓下的收货校验模式',
options: [ 'standard', 'strict', 'manual' ],
}),
Object.freeze({
key: 'sku_visibility',
name: 'SKU 可见范围',
type: 'enum',
default: 'all',
required: false,
description: '控制货主在该仓下的 SKU 可见策略',
options: [ 'all', 'whitelist', 'blacklist' ],
options: [
Object.freeze({ value: 'standard', label: '标准收货' }),
Object.freeze({ value: 'strict', label: '严格收货' }),
Object.freeze({ value: 'manual', label: '人工收货' }),
],
}),
Object.freeze({
key: 'auto_allocate_bin',
@ -46,6 +41,14 @@ module.exports = app => {
required: false,
description: '是否允许进入临时存放区',
}),
Object.freeze({
key: 'storage_separation',
name: '是否存储分离',
type: 'flag',
default: 1,
required: false,
description: '控制该货主在当前仓库下是否按独立存储策略管理库存',
}),
Object.freeze({
key: 'allow_oversell',
name: '允许超卖',
@ -62,6 +65,22 @@ module.exports = app => {
required: false,
description: '控制货主推送订单创建后是否必须进入审批流程',
}),
Object.freeze({
key: 'default_express_code',
name: '默认快递',
type: 'list',
default: 'STO',
required: false,
description: '货主在当前仓下默认使用的快递编码',
}),
Object.freeze({
key: 'default_platform_code',
name: '默认平台',
type: 'list',
default: 'TB',
required: false,
description: '货主在当前仓下默认使用的平台编码',
}),
Object.freeze({
key: 'print_recharge_price',
name: '面单充值元/单',
@ -99,6 +118,38 @@ module.exports = app => {
return result;
}, {}));
const clonePolicyConfigOptions = options => {
if (!Array.isArray(options)) {
return undefined;
}
return options.map(option => {
if (!option || typeof option !== 'object') {
return option;
}
return { ...option };
});
};
const getPolicyConfigOptionValue = option => {
if (option && typeof option === 'object') {
if (option.value !== undefined && option.value !== null) {
return String(option.value);
}
if (option.code !== undefined && option.code !== null) {
return String(option.code);
}
if (option.key !== undefined && option.key !== null) {
return String(option.key);
}
}
return String(option);
};
const clonePolicyConfigField = field => ({
key: field.key,
name: field.name,
@ -106,7 +157,7 @@ module.exports = app => {
default: field.default,
required: field.required,
description: field.description,
...(Array.isArray(field.options) ? { options: [ ...field.options ] } : {}),
...(Array.isArray(field.options) ? { options: clonePolicyConfigOptions(field.options) } : {}),
...(field.min !== undefined ? { min: field.min } : {}),
...(field.max !== undefined ? { max: field.max } : {}),
...(field.precision !== undefined ? { precision: field.precision } : {}),
@ -114,6 +165,26 @@ module.exports = app => {
...(field.maxLength !== undefined ? { maxLength: field.maxLength } : {}),
});
const normalizePolicyConfigOptionValue = option => {
if (!option || typeof option !== 'object') {
return String(option);
}
if (option.value !== undefined && option.value !== null) {
return String(option.value);
}
if (option.code !== undefined && option.code !== null) {
return String(option.code);
}
if (option.key !== undefined && option.key !== null) {
return String(option.key);
}
return '';
};
const parsePolicyConfig = (value, fieldName = 'policy_config') => {
if (typeof value === 'string') {
try {
@ -167,13 +238,24 @@ module.exports = app => {
try {
if (field.type === 'enum') {
const valueText = String(rawValue).trim();
if (!field.options.includes(valueText)) {
const allowedValues = Array.isArray(field.options)
? field.options.map(getPolicyConfigOptionValue)
: [];
if (!allowedValues.includes(valueText)) {
throw new Error(`${fieldName}.${field.key} 参数不合法`);
}
normalized[field.key] = valueText;
continue;
}
if (field.type === 'list') {
const valueText = String(rawValue).trim();
if (valueText) {
normalized[field.key] = valueText;
}
continue;
}
if (field.type === 'flag') {
if (rawValue === true || rawValue === 1 || rawValue === '1') {
normalized[field.key] = 1;
@ -481,6 +563,47 @@ module.exports = app => {
return POLICY_CONFIG_FIELDS.map(clonePolicyConfigField);
};
StoreWarehouse.getPolicyConfigFieldListWithOptions = async function() {
const fieldList = this.getPolicyConfigFieldList();
const [ expressRows, platformRows ] = await Promise.all([
app.model.Express && typeof app.model.Express.findAll === 'function'
? app.model.Express.findAll({
attributes: [ 'code', 'name' ],
order: [ [ 'code', 'ASC' ] ],
})
: Promise.resolve([]),
app.model.Platform && typeof app.model.Platform.findAll === 'function'
? app.model.Platform.findAll({
attributes: [ 'code', 'name' ],
order: [ [ 'code', 'ASC' ] ],
})
: Promise.resolve([]),
]);
const optionMap = {
default_express_code: expressRows.map(item => ({
value: normalizePolicyConfigOptionValue(item),
label: String(item.name || item.code || ''),
})),
default_platform_code: platformRows.map(item => ({
value: normalizePolicyConfigOptionValue(item),
label: String(item.name || item.code || ''),
})),
};
return fieldList.map(field => {
const options = optionMap[field.key];
if (!options) {
return field;
}
return {
...field,
options,
};
});
};
StoreWarehouse.normalizePolicyConfig = function(value, options = {}) {
return normalizePolicyConfig(value, options);
};

View File

@ -14,6 +14,10 @@ module.exports = app => {
// 系统接口 PDA/WEB 统一入口
router.post('/system', controller.home.system);
// 独立 docs 目录挂载
router.get('/docs', controller.docs.docsIndex);
router.get('/docs/:relPath(.*)', controller.docs.docsFile);
// api文档相关
router.get('/api/docs', controller.docs.list);
router.get('/api/docs/:docName/raw', controller.docs.raw);
@ -30,6 +34,9 @@ module.exports = app => {
// 临时 fileWriter 消费入口
router.get('/__temp/file-writer/consume', controller.tempFileWriter.consume);
// Polo API 测试入口
router.get('/testPoloApi', controller.home.testPoloApi);
// 测试接口
router.get('/testSendData', controller.home.testSendData);
};

View File

@ -0,0 +1,733 @@
'use strict';
const CACHE_KEY_PREFIX = 'notice_stock_remaining_notified';
const LEGACY_CACHE_KEY = 'notice_stock_remaining_notified_list';
const CACHE_TTL_SECONDS = 24 * 60 * 60;
const DAY_MS = 24 * 60 * 60 * 1000;
const NOTICE_EVENT = 'storage_transfer_completed';
/**
* 生成本地日期键,格式为 `YYYYMMDD`。
* @param {Date} [dateValue=new Date()] 日期对象
* @return {string} 日期键
*/
function buildDateKey(dateValue = new Date()) {
const year = String(dateValue.getFullYear());
const month = String(dateValue.getMonth() + 1).padStart(2, '0');
const day = String(dateValue.getDate()).padStart(2, '0');
return `${year}${month}${day}`;
}
/**
* 生成商品维度的日粒度缓存键。
* @param {number} stockId 商品ID
* @param {Date} [dateValue=new Date()] 日期对象
* @return {string} 缓存键
*/
function buildStockDayCacheKey(stockId, dateValue = new Date()) {
const normalizedStockId = toNumber(stockId, 0);
if (normalizedStockId <= 0) {
return '';
}
return `${CACHE_KEY_PREFIX}:stock:${normalizedStockId}:${buildDateKey(dateValue)}`;
}
/**
* 从记录对象中安全读取字段,兼容下划线和驼峰命名。
* @param {object} record 记录对象
* @param {string[]} fieldNames 候选字段名列表
* @return {*} 命中的字段值
*/
function readRecordValue(record, fieldNames) {
if (!record || !Array.isArray(fieldNames)) {
return undefined;
}
for (const fieldName of fieldNames) {
if (!fieldName) {
continue;
}
if (Object.prototype.hasOwnProperty.call(record, fieldName)) {
return record[fieldName];
}
if (record.dataValues && Object.prototype.hasOwnProperty.call(record.dataValues, fieldName)) {
return record.dataValues[fieldName];
}
if (typeof record.getDataValue === 'function') {
try {
const dataValue = record.getDataValue(fieldName);
if (dataValue !== undefined) {
return dataValue;
}
} catch (error) {
// 忽略单个字段读取失败,继续尝试其他候选字段。
}
}
if (typeof record.get === 'function') {
try {
const getterValue = record.get(fieldName);
if (getterValue !== undefined) {
return getterValue;
}
} catch (error) {
// 忽略单个字段读取失败,继续尝试其他候选字段。
}
}
}
return undefined;
}
/**
* 将数值安全转换为数字。
* @param {*} value 原始值
* @param {number} [fallback=0] 转换失败时的兜底值
* @return {number} 数值结果
*/
function toNumber(value, fallback = 0) {
const numberValue = Number(value);
return Number.isFinite(numberValue) ? numberValue : fallback;
}
/**
* 归一化历史全局缓存中的已通知列表。
*
* 注意:该方法仅用于兼容旧格式的观测或迁移,不再参与新去重逻辑,
* 避免旧的全局列表继续抑制当天的通知。
*
* @param {*} rawValue 缓存原始值
* @return {string[]} 标准化后的通知键列表
*/
function normalizeNotifiedList(rawValue) {
if (!rawValue) {
return [];
}
let parsedValue = rawValue;
if (typeof rawValue === 'string') {
try {
parsedValue = JSON.parse(rawValue);
} catch (error) {
return [];
}
}
const list = Array.isArray(parsedValue)
? parsedValue
: (typeof parsedValue === 'object' && parsedValue !== null
? Object.values(parsedValue)
: []);
return list.map(item => {
if (item && typeof item === 'object') {
const stockId = readRecordValue(item, [ 'stock_id', 'stockId' ]);
if (stockId !== undefined && stockId !== null && String(stockId).trim() !== '') {
return `stock:${String(stockId)}`;
}
const itemId = readRecordValue(item, [ 'id', 'storage_id', 'storageId' ]);
if (itemId !== undefined && itemId !== null && String(itemId).trim() !== '') {
return `storage:${String(itemId)}`;
}
}
const normalizedValue = String(item || '').trim();
if (!normalizedValue) {
return '';
}
if (normalizedValue.startsWith('storage:')) {
return normalizedValue;
}
if (/^\d+$/.test(normalizedValue)) {
return `storage:${normalizedValue}`;
}
return normalizedValue;
}).filter(Boolean);
}
/**
* 生成库存记录对应的商品级通知去重键。
* @param {object} storageRecord 库存记录
* @return {string} 去重键
*/
function buildStockNotifyKey(storageRecord) {
const stockId = toNumber(readRecordValue(storageRecord, [ 'stock_id', 'stockId' ]), 0);
return stockId > 0 ? `stock:${stockId}` : '';
}
/**
* 按商品 ID 对库存记录进行分组。
* @param {object[]} storageRows 库存记录列表
* @return {Map<number, object[]>} 分组后的库存记录映射
*/
function groupStorageRowsByStockId(storageRows) {
const groupedStorageRows = new Map();
if (!Array.isArray(storageRows)) {
return groupedStorageRows;
}
for (const storageRow of storageRows) {
const stockId = toNumber(readRecordValue(storageRow, [ 'stock_id', 'stockId' ]), 0);
if (stockId <= 0) {
continue;
}
const stockStorageRows = groupedStorageRows.get(stockId) || [];
stockStorageRows.push(storageRow);
groupedStorageRows.set(stockId, stockStorageRows);
}
return groupedStorageRows;
}
/**
* 格式化日期字符串,优先使用应用内格式化器。
* @param {object} ctx Egg 上下文
* @param {*} value 原始日期值
* @return {string} 格式化后的日期字符串
*/
function formatDate(ctx, value) {
if (!value) {
return '';
}
const dateValue = value instanceof Date ? value : new Date(value);
if (Number.isNaN(dateValue.getTime())) {
return '';
}
if (ctx && ctx.app && typeof ctx.app.formatDate === 'function') {
return ctx.app.formatDate(dateValue);
}
return dateValue.toISOString();
}
/**
* 生成库存效期预警通知内容。
* @param {object} params 参数对象
* @param {object} params.ctx Egg 上下文
* @param {object} params.storageRecord 库存记录
* @param {object} params.stockRecord 商品主数据
* @param {number} params.remainingDays 剩余天数
* @param {number} params.thresholdDays 预警阈值天数
* @return {string} 通知正文
*/
function buildNoticeContent({ ctx, storageRecord, stockRecord, remainingDays, thresholdDays }) {
const storageId = toNumber(readRecordValue(storageRecord, [ 'id', 'storage_id', 'storageId' ]), 0);
const stockId = toNumber(readRecordValue(storageRecord, [ 'stock_id', 'stockId' ]), 0);
const itemCode = String(readRecordValue(stockRecord, [ 'item_code', 'itemCode' ]) || '').trim() || String(stockId || storageId);
const itemName = String(readRecordValue(stockRecord, [ 'item_name', 'itemName' ]) || '').trim() || '未命名商品';
const batchNo = String(readRecordValue(storageRecord, [ 'batch_no', 'batchNo' ]) || '').trim() || '无';
const warehouseId = toNumber(readRecordValue(storageRecord, [ 'warehouse_id', 'warehouseId' ]), 0);
const storeId = toNumber(readRecordValue(storageRecord, [ 'store_id', 'storeId' ]), 0);
const expiryDate = formatDate(ctx, readRecordValue(storageRecord, [ 'expiry_date', 'expiryDate' ]));
const inboundTime = formatDate(ctx, readRecordValue(storageRecord, [ 'inbound_time', 'inboundTime' ]));
const quantity = toNumber(readRecordValue(storageRecord, [ 'quantity' ]), 0);
const availableQuantity = toNumber(readRecordValue(storageRecord, [ 'available_quantity', 'availableQuantity' ]), quantity);
const spaceRecord = readRecordValue(storageRecord, [ 'space' ]) || storageRecord.space || {};
const spaceCode = String(readRecordValue(spaceRecord, [ 'space_code', 'spaceCode' ]) || '').trim();
const spaceName = String(readRecordValue(spaceRecord, [ 'custom_name', 'customName' ]) || '').trim();
const spaceLabel = [ spaceCode, spaceName ].filter(Boolean).join(' / ') || '无';
return [
`库存效期预警:${itemName}`,
`商品编码:${itemCode}`,
`库存ID:${storageId || '未知'}`,
`批次号:${batchNo}`,
`仓库ID:${warehouseId || '未知'}`,
`货主ID:${storeId || '未知'}`,
`库位:${spaceLabel}`,
`库存数量:${quantity}`,
`可用数量:${availableQuantity}`,
`效期日期:${expiryDate || '未知'}`,
`剩余天数:${remainingDays}`,
`预警阈值:${thresholdDays}`,
`入库时间:${inboundTime || '未知'}`,
].join('\n');
}
/**
* 解析库存效期预警通知的发送方法,优先使用 `send`,其次兼容 `index.send`。
* @param {object} ctx Egg 上下文
* @return {Function|null} 可执行的发送方法
*/
function resolveNoticeSendMethod(ctx) {
const noticeService = ctx && ctx.service && ctx.service.systems && ctx.service.systems.notice;
if (!noticeService) {
return null;
}
if (typeof noticeService.send === 'function') {
return noticeService.send.bind(noticeService);
}
if (noticeService.index && typeof noticeService.index.send === 'function') {
return noticeService.index.send.bind(noticeService.index);
}
return null;
}
/**
* 发送库存效期预警通知。
* @param {object} ctx Egg 上下文
* @param {object} payload 通知参数
* @return {Promise<object>} 通知发送结果
*/
async function sendStockRemainingNotice(ctx, payload) {
const sendMethod = resolveNoticeSendMethod(ctx);
if (typeof sendMethod !== 'function') {
throw new Error('通知服务不可用');
}
return await sendMethod(payload);
}
module.exports = {
schedule: {
interval: '30s',
type: 'worker',
immediate: false,
disable: false,
},
/**
* 执行库存效期预警扫描。
* @param {object} ctx Egg 上下文
* @return {Promise<void>}
*/
async task(ctx) {
const scheduleName = 'notice_stock_remaining';
let stockCount = 0;
let storageCount = 0;
let sentCount = 0;
let skippedCount = 0;
const today = new Date();
ctx.logger.info(`[${scheduleName}] 本轮任务启动`, {
scheduleName,
cacheKeyPrefix: CACHE_KEY_PREFIX,
running: Boolean(ctx.app._noticeStockRemainingRunning),
});
if (ctx.app._noticeStockRemainingRunning) {
ctx.logger.info(`[${scheduleName}] 本轮任务跳过,上一轮尚未结束`, {
scheduleName,
cacheKeyPrefix: CACHE_KEY_PREFIX,
running: Boolean(ctx.app._noticeStockRemainingRunning),
});
return;
}
ctx.app._noticeStockRemainingRunning = true;
try {
const legacyCachedValue = typeof ctx.app.getCacheAsync === 'function'
? await ctx.app.getCacheAsync(LEGACY_CACHE_KEY)
: null;
const legacyCacheHit = legacyCachedValue !== null && legacyCachedValue !== undefined;
const legacyNotifiedList = normalizeNotifiedList(legacyCachedValue);
ctx.logger.info('[notice_stock_remaining] 已检查历史通知缓存', {
legacyCacheKey: LEGACY_CACHE_KEY,
cacheHit: legacyCacheHit,
cachedValueType: Array.isArray(legacyCachedValue) ? 'array' : typeof legacyCachedValue,
rawCacheCount: Array.isArray(legacyCachedValue) ? legacyCachedValue.length : 0,
normalizedCount: legacyNotifiedList.length,
cacheKeyMode: 'stock-day',
});
if (legacyCacheHit) {
ctx.logger.warn('[notice_stock_remaining] 检测到旧的全局去重缓存,当前版本不再使用该缓存参与拦截', {
legacyCacheKey: LEGACY_CACHE_KEY,
normalizedCount: legacyNotifiedList.length,
});
}
ctx.logger.debug('[notice_stock_remaining] 日粒度去重已启用', {
cacheKeyPrefix: CACHE_KEY_PREFIX,
dateKey: buildDateKey(today),
});
const stockWhere = {
is_shelf_life_mgmt: 'Y',
remaining_threshold_days: {
[ctx.app.Sequelize.Op.gt]: 0,
},
};
const stockRows = await ctx.model.StockWarehouse.findAll({
attributes: [
'id',
'item_code',
'item_name',
'store_id',
'warehouse_id',
'remaining_threshold_days',
],
where: stockWhere,
order: [[ 'remaining_threshold_days', 'ASC' ], [ 'id', 'ASC' ]],
raw: true,
});
stockCount = Array.isArray(stockRows) ? stockRows.length : 0;
ctx.logger.info('[notice_stock_remaining] 完成商品候选查询', {
stockCount,
});
if (Array.isArray(stockRows)) {
for (const stockRow of stockRows) {
ctx.logger.debug('[notice_stock_remaining] 商品候选明细', {
id: toNumber(readRecordValue(stockRow, [ 'id' ]), 0),
item_code: String(readRecordValue(stockRow, [ 'item_code', 'itemCode' ]) || '').trim(),
remaining_threshold_days: Math.max(0, Math.floor(toNumber(readRecordValue(stockRow, [ 'remaining_threshold_days', 'remainingThresholdDays' ]), 0))),
});
}
}
if (!Array.isArray(stockRows) || stockRows.length === 0) {
ctx.logger.info('[notice_stock_remaining] 未找到开启效期管理且阈值大于 0 的商品');
return;
}
const stockMap = new Map();
let maxThresholdDays = 0;
for (const stockRow of stockRows) {
const stockId = toNumber(readRecordValue(stockRow, [ 'id' ]), 0);
const thresholdDays = Math.max(0, Math.floor(toNumber(readRecordValue(stockRow, [ 'remaining_threshold_days', 'remainingThresholdDays' ]), 0)));
if (stockId <= 0 || thresholdDays <= 0) {
continue;
}
stockMap.set(stockId, {
id: stockId,
item_code: String(readRecordValue(stockRow, [ 'item_code', 'itemCode' ]) || '').trim(),
item_name: String(readRecordValue(stockRow, [ 'item_name', 'itemName' ]) || '').trim(),
store_id: toNumber(readRecordValue(stockRow, [ 'store_id', 'storeId' ]), 0),
warehouse_id: toNumber(readRecordValue(stockRow, [ 'warehouse_id', 'warehouseId' ]), 0),
remaining_threshold_days: thresholdDays,
});
if (thresholdDays > maxThresholdDays) {
maxThresholdDays = thresholdDays;
}
}
const stockIds = Array.from(stockMap.keys());
if (stockIds.length === 0 || maxThresholdDays <= 0) {
ctx.logger.info('[notice_stock_remaining] 商品数据中没有可用的效期预警阈值', {
stockCount,
validStockCount: stockIds.length,
maxThresholdDays,
});
return;
}
const now = new Date();
const maxExpiryDate = new Date(now.getTime() + (maxThresholdDays * DAY_MS));
const storageWhere = {
stock_id: {
[ctx.app.Sequelize.Op.in]: stockIds,
},
is_enabled: 1,
delete_at: null,
quantity: {
[ctx.app.Sequelize.Op.gt]: 0,
},
expiry_date: {
[ctx.app.Sequelize.Op.ne]: null,
[ctx.app.Sequelize.Op.lte]: maxExpiryDate,
},
};
const storageRows = await ctx.model.Storage.findAll({
where: storageWhere,
include: [
{
model: ctx.model.LocationSpace,
as: 'space',
attributes: [ 'space_code', 'custom_name' ],
required: false,
},
],
order: [[ 'expiry_date', 'ASC' ], [ 'inbound_time', 'ASC' ], [ 'id', 'ASC' ]],
});
storageCount = Array.isArray(storageRows) ? storageRows.length : 0;
ctx.logger.info('[notice_stock_remaining] 完成库存候选查询', {
stockCount: stockIds.length,
storageCount,
maxThresholdDays,
});
if (Array.isArray(storageRows)) {
for (const storageRow of storageRows) {
ctx.logger.debug('[notice_stock_remaining] 库存候选明细', {
id: toNumber(readRecordValue(storageRow, [ 'id', 'storage_id', 'storageId' ]), 0),
stock_id: toNumber(readRecordValue(storageRow, [ 'stock_id', 'stockId' ]), 0),
expiry_date: formatDate(ctx, readRecordValue(storageRow, [ 'expiry_date', 'expiryDate' ])),
quantity: toNumber(readRecordValue(storageRow, [ 'quantity' ]), 0),
available_quantity: toNumber(readRecordValue(storageRow, [ 'available_quantity', 'availableQuantity' ]), toNumber(readRecordValue(storageRow, [ 'quantity' ]), 0)),
});
}
}
const groupedStorageRows = groupStorageRowsByStockId(storageRows);
const representativeStorageRows = Array.from(groupedStorageRows.values()).map(stockStorageRows => stockStorageRows[0]);
for (const storageRecord of representativeStorageRows) {
const storageId = toNumber(readRecordValue(storageRecord, [ 'id', 'storage_id', 'storageId' ]), 0);
const stockId = toNumber(readRecordValue(storageRecord, [ 'stock_id', 'stockId' ]), 0);
const notifyKey = buildStockNotifyKey(storageRecord);
const stockDayCacheKey = buildStockDayCacheKey(stockId, today);
const stockRecord = stockMap.get(stockId);
const thresholdDays = stockRecord ? toNumber(readRecordValue(stockRecord, [ 'remaining_threshold_days', 'remainingThresholdDays' ]), 0) : 0;
if (!notifyKey) {
skippedCount += 1;
ctx.logger.debug('[notice_stock_remaining] 跳过代表库存', {
storageId,
stockId,
notifyKey,
reason: 'notifyKey 为空',
});
continue;
}
if (!stockDayCacheKey) {
skippedCount += 1;
ctx.logger.debug('[notice_stock_remaining] 跳过代表库存', {
storageId,
stockId,
notifyKey,
reason: '日粒度缓存键为空',
});
continue;
}
if (!stockRecord) {
skippedCount += 1;
ctx.logger.debug('[notice_stock_remaining] 跳过代表库存', {
storageId,
stockId,
notifyKey,
reason: '未找到对应商品记录',
});
continue;
}
if (typeof ctx.app.getCacheAsync === 'function') {
const cachedNotifiedValue = await ctx.app.getCacheAsync(stockDayCacheKey);
if (cachedNotifiedValue !== null && cachedNotifiedValue !== undefined) {
skippedCount += 1;
ctx.logger.debug('[notice_stock_remaining] 跳过代表库存', {
storageId,
stockId,
notifyKey,
stockDayCacheKey,
reason: '当日已通知过该商品',
});
continue;
}
}
if (thresholdDays <= 0) {
skippedCount += 1;
ctx.logger.debug('[notice_stock_remaining] 跳过代表库存', {
storageId,
stockId,
notifyKey,
thresholdDays,
reason: '商品阈值小于等于 0',
});
continue;
}
const expiryDateValue = readRecordValue(storageRecord, [ 'expiry_date', 'expiryDate' ]);
if (!expiryDateValue) {
skippedCount += 1;
ctx.logger.debug('[notice_stock_remaining] 跳过代表库存', {
storageId,
stockId,
notifyKey,
thresholdDays,
reason: '缺少效期日期',
});
continue;
}
const expiryDate = expiryDateValue instanceof Date ? expiryDateValue : new Date(expiryDateValue);
if (Number.isNaN(expiryDate.getTime())) {
ctx.logger.warn('[notice_stock_remaining] 跳过非法效期日期', {
storageId,
stockId,
expiryDate: String(expiryDateValue),
});
skippedCount += 1;
ctx.logger.debug('[notice_stock_remaining] 跳过代表库存', {
storageId,
stockId,
notifyKey,
thresholdDays,
reason: '效期日期非法',
});
continue;
}
const remainingDays = Math.max(0, Math.ceil((expiryDate.getTime() - now.getTime()) / DAY_MS));
if (remainingDays > thresholdDays) {
skippedCount += 1;
ctx.logger.debug('[notice_stock_remaining] 跳过代表库存', {
storageId,
stockId,
notifyKey,
thresholdDays,
remainingDays,
reason: '剩余天数大于阈值',
});
continue;
}
const warehouseId = toNumber(readRecordValue(storageRecord, [ 'warehouse_id', 'warehouseId' ]) || stockRecord.warehouse_id, 0);
const storeId = toNumber(readRecordValue(storageRecord, [ 'store_id', 'storeId' ]) || stockRecord.store_id, 0);
const title = `库存效期预警:${stockRecord.item_name || '未命名商品'}`;
const content = buildNoticeContent({
ctx,
storageRecord,
stockRecord,
remainingDays,
thresholdDays,
});
ctx.logger.info('[notice_stock_remaining] 进入发送分支', {
storageId,
stockId,
notifyKey,
remainingDays,
thresholdDays,
warehouseId,
storeId,
});
try {
const noticeResult = await sendStockRemainingNotice(ctx, {
warehouseId,
storeId,
subject: {
id: warehouseId,
type: 'warehouse',
name: `仓库${warehouseId || '未知'}`,
},
businessName: 'storage',
event: NOTICE_EVENT,
title,
content,
businessId: stockId,
messageType: 'text',
metadata: {
cacheKey: stockDayCacheKey,
storageId,
stockId,
notifyKey,
businessId: stockId,
thresholdDays,
remainingDays,
warehouseId,
storeId,
stock: {
id: stockRecord.id,
item_code: stockRecord.item_code,
item_name: stockRecord.item_name,
},
storage: {
id: storageId,
batch_no: readRecordValue(storageRecord, [ 'batch_no', 'batchNo' ]) || '',
expiry_date: expiryDate.toISOString(),
},
},
});
if (noticeResult && noticeResult.success === false) {
ctx.logger.warn('[notice_stock_remaining] 通知发送失败,保留待重试状态', {
storageId,
stockId,
notifyKey,
stockDayCacheKey,
remainingDays,
thresholdDays,
result: noticeResult,
});
continue;
}
if (typeof ctx.app.setCacheAsync === 'function') {
await ctx.app.setCacheAsync(stockDayCacheKey, {
notifiedAt: today.toISOString(),
stockId,
notifyKey,
}, CACHE_TTL_SECONDS);
}
sentCount += 1;
ctx.logger.info('[notice_stock_remaining] 库存效期预警已发送', {
storageId,
stockId,
notifyKey,
stockDayCacheKey,
remainingDays,
thresholdDays,
result: noticeResult,
});
} catch (noticeError) {
ctx.logger.error('[notice_stock_remaining] 库存效期预警发送异常', {
storageId,
stockId,
notifyKey,
stockDayCacheKey,
remainingDays,
thresholdDays,
error: noticeError.message,
stack: noticeError.stack,
});
}
}
ctx.logger.info('[notice_stock_remaining] 本轮通知缓存按商品日粒度独立写入,无需整体回写', {
cacheKeyPrefix: CACHE_KEY_PREFIX,
sentCount,
skippedCount,
ttlSeconds: CACHE_TTL_SECONDS,
});
} catch (error) {
ctx.logger.error('[notice_stock_remaining] 执行失败', {
error: error.message,
stack: error.stack,
});
} finally {
ctx.app._noticeStockRemainingRunning = false;
ctx.logger.info('[notice_stock_remaining] 本轮任务结束', {
scheduleName,
cacheKeyPrefix: CACHE_KEY_PREFIX,
stockCount,
storageCount,
sentCount,
skippedCount,
running: Boolean(ctx.app._noticeStockRemainingRunning),
});
}
},
};

View File

@ -0,0 +1,51 @@
'use strict';
const SHORT_TASK_QUERY_TIMEOUT_MS = 15000;
const SHORT_TASK_EXECUTION_TIMEOUT_MS = 30000;
/**
* 每 1 分钟在单 worker 中同步一次正常出库订单到配送表。
*/
module.exports = {
schedule: {
interval: '1m',
type: 'worker',
immediate: false,
disable: false,
},
queryTimeoutMs: SHORT_TASK_QUERY_TIMEOUT_MS,
executionTimeoutMs: SHORT_TASK_EXECUTION_TIMEOUT_MS,
/**
* 执行已出库订单迁移任务。
*
* @param {Object} ctx Egg 上下文。
* @return {Promise<void>} 无返回值。
*/
async task(ctx) {
if (ctx.app._syncOutboundOrdersToDeliveryRunning) {
return;
}
ctx.app._syncOutboundOrdersToDeliveryRunning = true;
try {
const result = await ctx.service.systems.orderDeliveryMigration.syncOutboundOrdersToDelivery({
queryTimeoutMs: SHORT_TASK_QUERY_TIMEOUT_MS,
executionTimeoutMs: SHORT_TASK_EXECUTION_TIMEOUT_MS,
});
if (result && result.retryableFailure) {
ctx.logger.warn(`[sync-outbound-orders-to-delivery] 正常迁移遇到 ${result.retryableFailureType},已标记 ${result.timeoutCount || 0} 条订单为出库超时`);
} else if (result && result.totalCreated > 0) {
ctx.logger.info(`[sync-outbound-orders-to-delivery] 同步 ${result.totalCreated} 条已出库订单`);
}
} catch (error) {
ctx.logger.error(`[sync-outbound-orders-to-delivery] 同步失败: ${error.message}`);
} finally {
ctx.app._syncOutboundOrdersToDeliveryRunning = false;
}
},
};

View File

@ -0,0 +1,51 @@
'use strict';
const LONG_TASK_QUERY_TIMEOUT_MS = 120000;
const LONG_TASK_EXECUTION_TIMEOUT_MS = 300000;
/**
* 每 10 分钟在单 worker 中重试一次出库超时订单到配送表。
*/
module.exports = {
schedule: {
interval: '10m',
type: 'worker',
immediate: false,
disable: false,
},
queryTimeoutMs: LONG_TASK_QUERY_TIMEOUT_MS,
executionTimeoutMs: LONG_TASK_EXECUTION_TIMEOUT_MS,
/**
* 执行出库超时订单重试任务。
*
* @param {Object} ctx Egg 上下文。
* @return {Promise<void>} 无返回值。
*/
async task(ctx) {
if (ctx.app._syncTimeoutOutboundOrdersToDeliveryRunning) {
return;
}
ctx.app._syncTimeoutOutboundOrdersToDeliveryRunning = true;
try {
const result = await ctx.service.systems.orderDeliveryMigration.retryTimeoutOutboundOrdersToDelivery({
queryTimeoutMs: LONG_TASK_QUERY_TIMEOUT_MS,
executionTimeoutMs: LONG_TASK_EXECUTION_TIMEOUT_MS,
});
if (result && result.retryableFailure) {
ctx.logger.warn(`[sync-outbound-timeout-orders-to-delivery] 重试出库超时订单遇到 ${result.retryableFailureType}`);
} else if (result && result.totalCreated > 0) {
ctx.logger.info(`[sync-outbound-timeout-orders-to-delivery] 重试同步 ${result.totalCreated} 条出库超时订单`);
}
} catch (error) {
ctx.logger.error(`[sync-outbound-timeout-orders-to-delivery] 重试失败: ${error.message}`);
} finally {
ctx.app._syncTimeoutOutboundOrdersToDeliveryRunning = false;
}
},
};

View File

@ -58,12 +58,8 @@ class QimenService extends Service {
parseAttributeValue: false,
trimValues: false, // 也关闭trim,保持原始格式
ignoreDeclaration: true,
// 添加标签值处理器,手动控制转换
tagValueProcessor: tagValue => {
// 如果是叶子节点且需要保持字符串格式的标签,可以在这里特殊处理
// 默认返回原始值
return tagValue;
},
// 保持 fast-xml-parser 的真实叶子文本值,避免把标签名误当成字段值。
tagValueProcessor: (tagName, tagValue) => tagValue,
});
try {
@ -233,6 +229,12 @@ class QimenService extends Service {
}
});
}
/**
* 保存奇门请求日志。
* @param {Object} logData 日志数据。
* @param {number} startTime 请求开始时间戳。
* @return {Promise<number|undefined>} 新增日志ID。
*/
async saveQimenLog(logData, startTime) {
const {
ctx,
@ -252,6 +254,7 @@ class QimenService extends Service {
// 使用 egg-mysql 保存日志到数据库
const result = await ctx.app.mysql.get('wms').insert('wms_qimen_log', {
log_id: logData.log_id || ctx.qimenLogId || null,
from_key: logData.from_key || '',
to_key: logData.to_key || '',
method: logData.method || '',

View File

@ -31,13 +31,12 @@ class deliveryorderServer extends MainService {
}
async create(data) {
const info = this.getInfo;
const res = await this.ctx.service.systems.deliveryOrder.addOrder(data, this.getInfo(), 'QM');
const info = this.getInfo();
const res = await this.ctx.service.systems.deliveryOrder.addOrder(data, info, 'QM');
if (res.success) {
return this.success(res.message, { createTime: this.app.formatDate(new Date()), deliveryOrderId: res.data.deliveryOrderId, warehouseCode: info.warehouseCode, logisticsCode: res.data.logisticsCode });
}
return this.fail(res.message, { createTime: this.app.formatDate(new Date()) });
}
async batchcreate() {
return this.fail('批量创建接口未完善');

View File

@ -87,13 +87,143 @@ class orderServer extends MainService {
};
}
async getInterceptExpressInfo(orderId) {
const { ctx } = this;
const normalizedOrderId = Number(orderId || 0);
if (!Number.isFinite(normalizedOrderId) || normalizedOrderId <= 0) {
return [];
}
const orderExpressModel = ctx.model && ctx.model.OrderExpress;
if (!orderExpressModel || typeof orderExpressModel.findAll !== 'function') {
return [];
}
const rows = await orderExpressModel.findAll({
where: {
order_id: normalizedOrderId,
},
attributes: [ 'waybill_code', 'logistics_code', 'logistics_name', 'logistics_interface_id' ],
order: [[ 'id', 'DESC' ]],
raw: true,
});
return (Array.isArray(rows) ? rows : []).map(row => ({
waybill_code: String(row && row.waybill_code || '').trim(),
logistics_code: String(row && row.logistics_code || '').trim(),
logistics_name: String(row && row.logistics_name || '').trim(),
logistics_interface_id: row && row.logistics_interface_id == null ? null : Number(row.logistics_interface_id),
}));
}
async sendCancelInterceptNotice({ orderCode, existingOrder, info }) {
const { ctx } = this;
try {
const express = await this.getInterceptExpressInfo(existingOrder && existingOrder.id);
await ctx.service.systems.notice.send({
event: 'order_cancel_intercepted',
businessName: 'order',
warehouseId: info.warehouseId,
storeId: info.storeId,
subject: {
id: info.storeId,
type: 'store',
},
businessId: orderCode,
messageType: 'text',
title: `订单取消触发拦截:${orderCode}`,
content: `订单 ${orderCode} 因拣货/打印状态未完成,已标记为拦截执行。`,
sender: {
id: ctx.user?.employees_id || ctx.user?.id,
name: ctx.user?.employees_name || '',
},
metadata: {
orderCode,
orderId: existingOrder.id,
pickStatus: String(existingOrder.pick_status || 'none').trim(),
printStatus: String(existingOrder.print_status || 'none').trim(),
interceptStatus: String(existingOrder.intercept_status || 'none').trim(),
express,
},
});
} catch (error) {
ctx.logger.warn(`取消订单拦截通知发送失败: ${error.message}`);
}
}
async cancel(data) {
const { ctx } = this;
const info = this.getInfo();
const orderType = this.orderType[data.request.orderType];
switch (orderType.method) {
case 'ORDER':
return this.success('取消订单成功');
{
const orderCode = String(data?.request?.orderCode || '').trim();
if (!orderCode) {
return this.fail('订单号不能为空');
}
const DeliveryModel = await ctx.model.OrderDeliveryFactory.getCurrentModel(info.warehouseId);
const transaction = await ctx.model.transaction();
try {
const existingOrder = await DeliveryModel.findOne({
where: {
delivery_order_code: orderCode,
warehouse_id: info.warehouseId,
store_id: info.storeId,
},
transaction,
lock: transaction.LOCK.UPDATE,
});
if (!existingOrder) {
await transaction.rollback();
return this.fail('未找到对应的订单');
}
const pickStatus = String(existingOrder.pick_status || 'none').trim();
const printStatus = String(existingOrder.print_status || 'none').trim();
if (pickStatus !== 'none' || printStatus !== 'none') {
await existingOrder.update({
intercept_status: 'intercepting',
updated_at: new Date(),
}, {
transaction,
});
await transaction.commit();
await this.sendCancelInterceptNotice({
orderCode,
existingOrder,
info,
});
return this.fail('取消失败,已通知拦截执行');
}
await existingOrder.update({
status: 'cancel',
outbound_status: 'fin',
step: 4,
updated_at: new Date(),
}, {
transaction,
});
await transaction.commit();
return this.success('取消订单成功');
} catch (error) {
try {
await transaction.rollback();
} catch (rollbackError) {
ctx.logger.error('取消订单回滚失败', rollbackError);
}
ctx.logger.error(`取消订单失败: ${error.message}`);
return this.fail(error.message || '取消订单失败');
}
}
case 'RK':
{
const existingOrder = await ctx.model.EntryOrder.findOne({

View File

@ -11,9 +11,9 @@ class indexService extends MainService {
constructor(ctx) {
super(ctx);
const _noNeedLogin = 'getI18nMessage,putI18nCollect';
const _noNeedRight = 'getI18nMessage,putI18nCollect,fastWhereTree,loadStores,getImages,getCOSUploadConfig,uploadSuccessNotify,getMessageDetail,searchSpace,listInterfaceTypes,recognizeLicensePlate';
const _noNeedRight = 'getI18nMessage,putI18nCollect,fastWhereTree,loadStores,getImages,getCOSUploadConfig,uploadSuccessNotify,getMessageDetail,searchSpace,listInterfaceTypes,getExpressList,getPlatformList,recognizeLicensePlate';
const _noNeedLog = '*';
const _noNeedAuth = 'getI18nMessage,putI18nCollect,fastWhereTree,loadStores,getImages,getMessageDetail,searchSpace,listInterfaceTypes,recognizeLicensePlate';
const _noNeedAuth = 'getI18nMessage,putI18nCollect,fastWhereTree,loadStores,getImages,getMessageDetail,searchSpace,listInterfaceTypes,getExpressList,getPlatformList,recognizeLicensePlate';
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
}
async fastWhereTree(data) {
@ -418,8 +418,15 @@ class indexService extends MainService {
return this.success('ok', { list, total: list.length, code: 200 });
}
async getExpressList() {
const { service } = this;
const result = await service.systems.express.getExpressList();
return this.success('ok', { data: result, code: 200 });
}
return this.success('ok', { data: this.app.config.expressList, code: 200 });
async getPlatformList() {
const { service } = this;
const result = await service.systems.platform.getPlatformList();
return this.success('ok', { data: result, code: 200 });
}
}
module.exports = indexService;

View File

@ -6,64 +6,20 @@ class ArchiveOrderService extends OrderBaseService {
constructor(ctx) {
super(ctx);
const _noNeedLogin = '';
const _noNeedRight = 'getarchiveOrderlist';
const _noNeedLog = 'getarchiveOrderlist';
const _noNeedAuth = 'getarchiveOrderlist';
const _noNeedRight = 'list';
const _noNeedLog = 'list';
const _noNeedAuth = 'list';
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
}
/**
* 获取归档订单列表。
*
* @param {Object} data 请求参数。
* @return {Promise<Object>} 查询结果。
* 归档订单列表。
* @param {Object} data 请求体。
* @param {Object} data.where 标准的查询条件对象,支持复杂查询。
* @return {Promise<Object>} 列表与分页信息。
*/
async getarchiveOrderlist(data = {}) {
try {
const warehouseId = this.ensureWarehouseId(data);
const { DeliveryModel } = await this.getOrderModels(warehouseId);
this.prepareWhereContext(data);
const whereData = this.ctx.where || {};
const where = this.buildWhere(whereData, warehouseId);
const hasOutboundFilter = this.hasWhereValue(whereData, 'outbound_status');
if (!hasOutboundFilter) {
where.outbound_status = 'fin';
}
const { page, pageSize, offset } = this.getPagination(data.pagination);
const result = await DeliveryModel.findAndCountAll({
where,
attributes: [
'id',
'delivery_order_code',
'status',
'step',
'outbound_status',
'delivery_time',
'updated_at',
'store_id',
'warehouse_id',
'buyer_nick',
'logistics_name',
],
offset,
limit: pageSize,
order: [[ 'delivery_time', 'DESC' ], [ 'updated_at', 'DESC' ], [ 'id', 'DESC' ]],
raw: true,
});
return this.success('ok', {
data: this.buildListData(result.rows, result.count, page, pageSize, {
queryInfo: {
defaultArchiveFilter: !hasOutboundFilter,
},
}),
code: 200,
});
} catch (error) {
return this.fail(error.message, { code: 500 });
}
async list(data = {}) {
return await this.listByModule('archiveOrder', data);
}
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,26 @@
'use strict';
const OrderBaseService = require('./base');
class DeliveryExpectionOrderService extends OrderBaseService {
constructor(ctx) {
super(ctx);
const _noNeedLogin = '';
const _noNeedRight = 'list,deliveryExpectionOrder';
const _noNeedLog = 'list';
const _noNeedAuth = 'list,deliveryExpectionOrder';
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
}
/**
* 配送异常订单列表。
* @param {Object} data 请求体。
* @return {Promise<Object>} 列表与分页信息。
*/
async list(data = {}) {
return await this.listByModule('deliveryExpectionOrder', data);
}
}
module.exports = DeliveryExpectionOrderService;

View File

@ -6,66 +6,21 @@ class DeliveryOrderService extends OrderBaseService {
constructor(ctx) {
super(ctx);
const _noNeedLogin = '';
const _noNeedRight = 'getdeliveryOrderlist';
const _noNeedLog = 'getdeliveryOrderlist';
const _noNeedAuth = 'getdeliveryOrderlist';
const _noNeedRight = 'list,deliveryOrder';
const _noNeedLog = 'list';
const _noNeedAuth = 'list,deliveryOrder';
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
}
/**
* 获取已发货订单列表。
*
* @param {Object} data 请求参数。
* @return {Promise<Object>} 查询结果。
* 配送订单列表。
* @param {Object} data 请求体。
* @return {Promise<Object>} 列表与分页信息。
*/
async getdeliveryOrderlist(data = {}) {
try {
const warehouseId = this.ensureWarehouseId(data);
const { Op } = this.app.Sequelize;
const { DeliveryModel } = await this.getOrderModels(warehouseId);
this.prepareWhereContext(data);
const whereData = this.ctx.where || {};
const where = this.buildWhere(whereData, warehouseId);
const hasOutboundFilter = this.hasWhereValue(whereData, 'outbound_status');
if (!hasOutboundFilter) {
where.outbound_status = { [Op.ne]: 'none' };
}
const { page, pageSize, offset } = this.getPagination(data.pagination);
const result = await DeliveryModel.findAndCountAll({
where,
attributes: [
'id',
'delivery_order_code',
'status',
'step',
'outbound_status',
'delivery_time',
'updated_at',
'store_id',
'warehouse_id',
'buyer_nick',
'logistics_name',
],
offset,
limit: pageSize,
order: [[ 'delivery_time', 'DESC' ], [ 'updated_at', 'DESC' ], [ 'id', 'DESC' ]],
raw: true,
});
return this.success('ok', {
data: this.buildListData(result.rows, result.count, page, pageSize, {
queryInfo: {
defaultOutboundFilter: !hasOutboundFilter,
},
}),
code: 200,
});
} catch (error) {
return this.fail(error.message, { code: 500 });
}
async list(data = {}) {
return await this.listByModule('deliveryOrder', data);
}
}
module.exports = DeliveryOrderService;

View File

@ -0,0 +1,26 @@
'use strict';
const OrderBaseService = require('./base');
class EntrustOrderService extends OrderBaseService {
constructor(ctx) {
super(ctx);
const _noNeedLogin = '';
const _noNeedRight = 'list,entrustOrder';
const _noNeedLog = 'list';
const _noNeedAuth = 'list,entrustOrder';
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
}
/**
* 委托外仓订单列表。
* @param {Object} data 请求体。
* @return {Promise<Object>} 列表与分页信息。
*/
async list(data = {}) {
return await this.listByModule('entrustOrder', data);
}
}
module.exports = EntrustOrderService;

View File

@ -6,93 +6,21 @@ class ExpectionOrderService extends OrderBaseService {
constructor(ctx) {
super(ctx);
const _noNeedLogin = '';
const _noNeedRight = 'getexpectionOrderlist';
const _noNeedLog = 'getexpectionOrderlist';
const _noNeedAuth = 'getexpectionOrderlist';
const _noNeedRight = 'list,expectionOrder';
const _noNeedLog = 'list';
const _noNeedAuth = 'list,expectionOrder';
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
}
/**
* 获取异常订单列表。
*
* @param {Object} data 请求参数。
* @return {Promise<Object>} 查询结果。
* 待处理异常订单列表。
* @param {Object} data 请求体。
* @return {Promise<Object>} 列表与分页信息。
*/
async getexpectionOrderlist(data = {}) {
try {
const warehouseId = this.ensureWarehouseId(data);
const { Op } = this.app.Sequelize;
const { DeliveryModel } = await this.getOrderModels(warehouseId);
this.prepareWhereContext(data);
const whereData = this.ctx.where || {};
const where = this.buildWhere(whereData, warehouseId);
const hasExceptionFilter = [
'status',
'post_status',
'storage_status',
'pick_status',
'pack_status',
'inspection_status',
'print_status',
'claim_status',
'outbound_status',
'intercept_status',
].some(key => this.hasWhereValue(whereData, key));
if (!hasExceptionFilter) {
where[Op.or] = [
{ status: 'error' },
{ post_status: 'error' },
{ storage_status: 'error' },
{ pick_status: 'error' },
{ pack_status: 'error' },
{ inspection_status: 'error' },
{ print_status: 'error' },
{ claim_status: 'error' },
{ outbound_status: 'error' },
{ intercept_status: 'exception' },
];
}
const { page, pageSize, offset } = this.getPagination(data.pagination);
const result = await DeliveryModel.findAndCountAll({
where,
attributes: [
'id',
'delivery_order_code',
'status',
'step',
'post_status',
'pick_status',
'pack_status',
'inspection_status',
'outbound_status',
'intercept_status',
'updated_at',
'store_id',
'warehouse_id',
'buyer_nick',
'logistics_name',
],
offset,
limit: pageSize,
order: [[ 'updated_at', 'DESC' ], [ 'id', 'DESC' ]],
raw: true,
});
return this.success('ok', {
data: this.buildListData(result.rows, result.count, page, pageSize, {
queryInfo: {
defaultExceptionFilter: !hasExceptionFilter,
},
}),
code: 200,
});
} catch (error) {
return this.fail(error.message, { code: 500 });
}
async list(data = {}) {
return await this.listByModule('expectionOrder', data);
}
}
module.exports = ExpectionOrderService;

View File

@ -6,210 +6,73 @@ class OrderIndexService extends OrderBaseService {
constructor(ctx) {
super(ctx);
const _noNeedLogin = '';
const _noNeedRight = 'list,detail,listItems,stats,getreviewOrderlist,updateStatus,updateDeliveryTime,reviewOrder';
const _noNeedLog = 'list,detail,listItems,stats,getreviewOrderlist';
const _noNeedAuth = 'list,detail,listItems,stats,getreviewOrderlist,updateStatus,updateDeliveryTime,reviewOrder';
const _noNeedRight = 'list,badgeCount,manualOutboundOrder,detail';
const _noNeedLog = 'list,badgeCount,manualOutboundOrder,detail';
const _noNeedAuth = 'list,badgeCount,manualOutboundOrder,detail';
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
}
/**
* 订单工作台总列表入口。
* @param {Object} data 请求体。
* @return {Promise<Object>} 列表与分页信息。
*/
async list(data = {}) {
try {
const warehouseId = this.ensureWarehouseId(data);
const { DeliveryModel } = await this.getOrderModels(warehouseId);
this.prepareWhereContext(data);
const whereData = this.ctx.where || {};
const where = this.buildWhere(whereData, warehouseId);
const { page, pageSize, offset } = this.getPagination(data.pagination);
const result = await DeliveryModel.findAndCountAll({
where,
offset,
limit: pageSize,
order: [[ 'updated_at', 'DESC' ], [ 'id', 'DESC' ]],
raw: true,
});
return this.success('ok', {
data: this.buildListData(result.rows, result.count, page, pageSize),
code: 200,
});
} catch (error) {
return this.fail(error.message, { code: 500 });
}
}
async detail(data = {}) {
try {
const warehouseId = this.ensureWarehouseId(data);
const { DeliveryModel, OrderItemsModel } = await this.getOrderModels(warehouseId);
const where = this.getOrderLocatorWhere(data, warehouseId);
const order = await DeliveryModel.findOne({ where, raw: true });
if (!order) {
return this.fail('订单不存在', { code: 404 });
}
const items = await OrderItemsModel.findAll({
where: { order_id: order.id },
order: [[ 'id', 'ASC' ]],
raw: true,
});
return this.success('ok', {
data: { order, items },
code: 200,
});
} catch (error) {
return this.fail(error.message, { code: 500 });
}
}
async listItems(data = {}) {
try {
const warehouseId = this.ensureWarehouseId(data);
const { DeliveryModel, OrderItemsModel } = await this.getOrderModels(warehouseId);
const where = this.getOrderLocatorWhere(data, warehouseId);
const order = await DeliveryModel.findOne({
where,
attributes: [ 'id', 'delivery_order_code' ],
raw: true,
});
if (!order) {
return this.fail('订单不存在', { code: 404 });
}
const items = await OrderItemsModel.findAll({
where: { order_id: order.id },
order: [[ 'id', 'ASC' ]],
raw: true,
});
return this.success('ok', {
data: { order, items },
code: 200,
});
} catch (error) {
return this.fail(error.message, { code: 500 });
}
}
async stats(data = {}) {
try {
const warehouseId = this.ensureWarehouseId(data);
const { Sequelize } = this.app;
const { DeliveryModel } = await this.getOrderModels(warehouseId);
this.prepareWhereContext(data);
const whereData = this.ctx.where || {};
const where = this.buildWhere(whereData, warehouseId);
const total = await DeliveryModel.count({ where });
const byStatusRows = await DeliveryModel.findAll({
where,
attributes: [ 'status', [ Sequelize.fn('COUNT', Sequelize.col('id')), 'count' ]],
group: [ 'status' ],
raw: true,
});
const byOutboundRows = await DeliveryModel.findAll({
where,
attributes: [ 'outbound_status', [ Sequelize.fn('COUNT', Sequelize.col('id')), 'count' ]],
group: [ 'outbound_status' ],
raw: true,
});
return this.success('ok', {
data: {
total,
byStatus: byStatusRows,
byOutboundStatus: byOutboundRows,
},
code: 200,
});
} catch (error) {
return this.fail(error.message, { code: 500 });
}
}
async getreviewOrderlist(data = {}) {
return await this.ctx.service.systemMethods.order.reviewOrder.getreviewOrderlist(data);
return await this.listByModule('order', data);
}
/**
* 更新订单状态相关字段。
*
* @param {Object} data 请求参数。
* @return {Promise<Object>} 更新结果。
* 手动出库入口。
* @param {Object} data 请求体。
* @return {Promise<Object>} 迁移结果。
*/
async updateStatus(data = {}) {
try {
const warehouseId = this.ensureWarehouseId(data);
const { DeliveryModel } = await this.getOrderModels(warehouseId);
const where = this.getOrderLocatorWhere(data, warehouseId);
const allowedFields = [
'status',
'post_status',
'storage_status',
'pick_status',
'pack_status',
'inspection_status',
'print_status',
'claim_status',
'outbound_status',
'lock_status',
'intercept_status',
'step',
];
const updateData = {};
for (const key of allowedFields) {
if (data[key] !== undefined && data[key] !== null && data[key] !== '') {
updateData[key] = data[key];
}
}
if (data.delivery_time) {
updateData.delivery_time = this.parseDateTime(data.delivery_time, 'delivery_time');
}
if (!updateData.delivery_time && updateData.outbound_status === 'fin') {
updateData.delivery_time = new Date();
}
if (Object.keys(updateData).length === 0) {
return this.fail('没有可更新字段', { code: 400 });
}
updateData.updated_at = new Date();
const [ affected ] = await DeliveryModel.update(updateData, { where });
if (!affected) {
return this.fail('订单不存在或未更新', { code: 404 });
}
const order = await DeliveryModel.findOne({ where, raw: true });
return this.success('更新成功', { data: order, code: 200 });
} catch (error) {
return this.fail(error.message, { code: 500 });
}
async manualOutboundOrder(data = {}) {
return await this.ctx.service.systems.orderDeliveryMigration.syncOutboundOrdersToDelivery(data);
}
async updateDeliveryTime(data = {}) {
if (!data.delivery_time) {
return this.fail('delivery_time 必填', { code: 400 });
/**
* 获取订单工作台 8 个标签页的角标计数。
* 其中配送、异常与归档相关标签页直接返回 99+。
* @return {Promise<Object>} 角标展示值对象。
*/
async badgeCount() {
const warehouseId = this.getWarehouseId();
if (warehouseId === null || warehouseId === undefined || warehouseId === '') {
throw new Error('缺少当前用户仓库上下文 store_id');
}
const nextData = { ...data };
if (nextData.syncOutboundStatus === true || nextData.syncOutboundStatus === 1 || nextData.syncOutboundStatus === '1') {
nextData.outbound_status = 'fin';
const cacheKey = this.getBadgeCountCacheKey(warehouseId);
const cachedBadgeCount = await this.app.getCacheAsync(cacheKey);
if (cachedBadgeCount && typeof cachedBadgeCount === 'object') {
return cachedBadgeCount;
}
return await this.updateStatus(nextData);
const [ reviewOrder, pendingOrder, outboundOrder, expectionOrder, entrustOrder ] = await Promise.all([
this.getBadgeCountByModule('reviewOrder', warehouseId),
this.getBadgeCountByModule('pendingOrder', warehouseId),
this.getBadgeCountByModule('outboundOrder', warehouseId),
this.getBadgeCountByModule('expectionOrder', warehouseId),
this.getBadgeCountByModule('entrustOrder', warehouseId),
]);
const badgeCount = {
reviewOrder,
pendingOrder,
outboundOrder,
expectionOrder,
entrustOrder,
deliveryOrder: '99+',
deliveryExpectionOrder: '99+',
archiveOrder: '99+',
};
await this.app.setCacheAsync(cacheKey, badgeCount, 30);
return badgeCount;
}
async reviewOrder(data = {}) {
return await this.ctx.service.systemMethods.order.reviewOrder.reviewOrder(data);
}
}
module.exports = OrderIndexService;

View File

@ -0,0 +1,34 @@
'use strict';
const OrderBaseService = require('./base');
class OutboundOrderService extends OrderBaseService {
constructor(ctx) {
super(ctx);
const _noNeedLogin = '';
const _noNeedRight = 'list,outboundOrder,manualOutboundOrder';
const _noNeedLog = 'list,manualOutboundOrder';
const _noNeedAuth = 'list,outboundOrder,manualOutboundOrder';
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
}
/**
* 待出库订单列表。
* @param {Object} data 请求体。
* @return {Promise<Object>} 列表与分页信息。
*/
async list(data = {}) {
return await this.listByModule('outboundOrder', data);
}
/**
* 手动出库入口。
* @param {Object} data 请求体。
* @return {Promise<Object>} 迁移结果。
*/
async manualOutboundOrder(data = {}) {
return await this.ctx.service.systems.orderDeliveryMigration.syncOutboundOrdersToDelivery(data);
}
}
module.exports = OutboundOrderService;

View File

@ -2,75 +2,293 @@
const OrderBaseService = require('./base');
const PENDING_OUTBOUND_STATUS = 'padding';
const PENDING_CANCEL_STATUS = 'cancel';
const PENDING_CANCEL_STEP = 9;
const PENDING_CANCEL_ALLOWED_STEPS = new Set([ 0, 1, 2, 3 ]);
const PENDING_CANCEL_PENDING_STEPS = new Set([ 1, 2 ]);
class PendingOrderService extends OrderBaseService {
constructor(ctx) {
super(ctx);
const _noNeedLogin = '';
const _noNeedRight = 'getpendingOrderlist';
const _noNeedLog = 'getpendingOrderlist';
const _noNeedAuth = 'getpendingOrderlist';
const _noNeedRight = 'list,pendingOrder,reverseReviewOrder,markPendingOutboundOrder,cancelOrder';
const _noNeedLog = 'list,markPendingOutboundOrder,cancelOrder';
const _noNeedAuth = 'list,pendingOrder,reverseReviewOrder,markPendingOutboundOrder,cancelOrder';
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
}
/**
* 获取待处理订单列表。
*
* @param {Object} data 请求参数。
* @return {Promise<Object>} 查询结果。
* 待处理订单列表。
* @param {Object} data 请求体。
* @return {Promise<Object>} 列表与分页信息。
*/
async getpendingOrderlist(data = {}) {
try {
const warehouseId = this.ensureWarehouseId(data);
const { Op } = this.app.Sequelize;
const { DeliveryModel } = await this.getOrderModels(warehouseId);
this.prepareWhereContext(data);
const whereData = this.ctx.where || {};
const where = this.buildWhere(whereData, warehouseId);
async list(data = {}) {
return await this.listByModule('pendingOrder', data);
}
const hasStatusFilter = this.hasWhereValue(whereData, 'status');
const hasOutboundFilter = this.hasWhereValue(whereData, 'outbound_status');
/**
* 将待处理订单反审回待审核状态。
* @param {Object} data 请求体。
* @return {Promise<Object>} 更新后的订单信息。
*/
async reverseReviewOrder(data = {}) {
return await this.updateOrderInspectionState(data, 'none');
}
if (!hasStatusFilter) {
where.status = { [Op.in]: [ 'pedding', 'created' ] };
}
if (!hasOutboundFilter) {
where.outbound_status = 'none';
}
/**
* 将待处理订单批量标记为待出库。
* @param {Object} data 请求体。
* @param {number[]} data.ids 订单ID 数组。
* @return {Promise<Object>} 更新后的订单信息。
*/
async markPendingOutboundOrder(data = {}) {
const requestData = this.isPlainObject(data) ? data : {};
const warehouseId = this.getWarehouseId();
const orderIds = this.normalizePendingOutboundOrderIds(requestData);
const { page, pageSize, offset } = this.getPagination(data.pagination);
const result = await DeliveryModel.findAndCountAll({
where,
attributes: [
'id',
'delivery_order_code',
'status',
'step',
'outbound_status',
'inspection_status',
'updated_at',
'store_id',
'warehouse_id',
'buyer_nick',
'logistics_name',
],
offset,
limit: pageSize,
order: [[ 'updated_at', 'DESC' ], [ 'id', 'DESC' ]],
raw: true,
});
return this.success('ok', {
data: this.buildListData(result.rows, result.count, page, pageSize, {
queryInfo: {
defaultPendingStatusFilter: !hasStatusFilter,
defaultPendingOutboundFilter: !hasOutboundFilter,
},
}),
code: 200,
});
} catch (error) {
return this.fail(error.message, { code: 500 });
if (orderIds.length === 0) {
throw new Error('订单ID不能为空');
}
const model = await this.getOrderModel('order', warehouseId);
const where = this.buildOrderWhere(orderIds, warehouseId);
const existingOrders = await model.findAll({
where,
raw: true,
});
if (!Array.isArray(existingOrders) || existingOrders.length === 0) {
return this.success('取消成功', {
updated_count: 0,
ids: [],
});
}
if (existingOrders.length !== orderIds.length) {
throw new Error('订单不存在或不属于当前仓库');
}
const now = new Date();
const updateValues = {
outbound_status: PENDING_OUTBOUND_STATUS,
updated_at: now,
};
const updateResult = await model.update(updateValues, {
where,
});
const affectedRows = Array.isArray(updateResult) ? Number(updateResult[0] || 0) : Number(updateResult || 0);
if (affectedRows <= 0) {
throw new Error('订单不存在或不属于当前仓库');
}
const updatedOrders = await model.findAll({
where,
raw: true,
});
if (!Array.isArray(updatedOrders) || updatedOrders.length === 0) {
throw new Error('订单不存在或不属于当前仓库');
}
const orderMap = new Map(updatedOrders.map(order => [ Number(order.id), order ]));
const normalizedOrders = orderIds
.map(orderId => orderMap.get(orderId))
.filter(Boolean)
.map(order => ({
id: order.id,
outbound_status: order.outbound_status,
updated_at: order.updated_at,
}));
if (normalizedOrders.length === 0) {
throw new Error('订单不存在或不属于当前仓库');
}
const firstOrder = normalizedOrders[0];
return {
id: firstOrder.id,
outbound_status: firstOrder.outbound_status,
updated_at: firstOrder.updated_at,
updated_count: affectedRows,
ids: normalizedOrders.map(order => order.id),
};
}
/**
* 将待处理订单取消,并关闭到已取消状态。
* 仅允许取消当前仓库内处于待审核、待处理、待处理异常语义的订单。
* @param {Object} data 请求体。
* @param {number[]} data.ids 订单ID 数组。
* @return {Promise<Object>} 更新后的订单信息。
*/
async cancelOrder(data = {}) {
const requestData = this.isPlainObject(data) ? data : {};
const warehouseId = this.getWarehouseId();
const orderIds = this.normalizePendingCancelOrderIds(requestData);
if (orderIds.length === 0) {
throw new Error('订单ID不能为空');
}
const model = await this.getOrderModel('order', warehouseId);
const where = this.buildOrderWhere(orderIds, warehouseId);
const existingOrders = await model.findAll({
where,
raw: true,
});
if (!Array.isArray(existingOrders) || existingOrders.length === 0) {
return this.success('取消成功', {
updated_count: 0,
ids: [],
});
}
if (existingOrders.length !== orderIds.length) {
throw new Error('订单不存在或不属于当前仓库');
}
const nonCancelableOrder = existingOrders.find(order => !this.isCancelablePendingOrder(order));
if (nonCancelableOrder) {
throw new Error('订单当前状态不允许取消');
}
const now = new Date();
const updateValues = {
status: PENDING_CANCEL_STATUS,
step: PENDING_CANCEL_STEP,
updated_at: now,
};
const updateResult = await model.update(updateValues, {
where,
});
const affectedRows = Array.isArray(updateResult) ? Number(updateResult[0] || 0) : Number(updateResult || 0);
if (affectedRows <= 0) {
throw new Error('订单不存在或不属于当前仓库');
}
const updatedOrders = await model.findAll({
where,
raw: true,
});
if (!Array.isArray(updatedOrders) || updatedOrders.length === 0) {
throw new Error('订单不存在或不属于当前仓库');
}
const orderMap = new Map(updatedOrders.map(order => [ Number(order.id), order ]));
const normalizedOrders = orderIds
.map(orderId => orderMap.get(orderId))
.filter(Boolean)
.map(order => ({
id: order.id,
status: order.status,
step: Number(order.step ?? PENDING_CANCEL_STEP),
updated_at: order.updated_at,
}));
if (normalizedOrders.length === 0) {
throw new Error('订单不存在或不属于当前仓库');
}
const firstOrder = normalizedOrders[0];
return {
id: firstOrder.id,
status: firstOrder.status,
step: firstOrder.step,
updated_at: firstOrder.updated_at,
updated_count: affectedRows,
ids: normalizedOrders.map(order => order.id),
};
}
/**
* 规范待处理出库订单ID入参,仅接受 ids 数组且元素必须为正整数。
* @param {Object} data 请求体。
* @return {number[]} 订单ID 数组。
*/
normalizePendingOutboundOrderIds(data = {}) {
const requestData = this.isPlainObject(data) ? data : {};
const unexpectedKeys = Object.keys(requestData).filter(key => key !== 'ids');
if (unexpectedKeys.length > 0) {
throw new Error('待处理出库接口仅支持 ids 数组入参,不再支持 id、order_id、逗号字符串或其他兼容字段');
}
if (!Array.isArray(requestData.ids)) {
throw new Error('待处理出库接口仅支持 ids 数组入参');
}
const normalizedIds = requestData.ids.map(value => {
if (!Number.isInteger(value) || value <= 0) {
throw new Error('ids 仅支持正整数数组');
}
return value;
});
return Array.from(new Set(normalizedIds));
}
/**
* 规范待处理取消订单ID入参,仅接受 ids 数组且元素必须为正整数。
* @param {Object} data 请求体。
* @return {number[]} 订单ID 数组。
*/
normalizePendingCancelOrderIds(data = {}) {
const requestData = this.isPlainObject(data) ? data : {};
const unexpectedKeys = Object.keys(requestData).filter(key => key !== 'ids');
if (unexpectedKeys.length > 0) {
throw new Error('待处理取消接口仅支持 ids 数组入参,不再支持 id、order_id、逗号字符串或其他兼容字段');
}
if (!Array.isArray(requestData.ids)) {
throw new Error('待处理取消接口仅支持 ids 数组入参');
}
const normalizedIds = requestData.ids.map(value => {
if (!Number.isInteger(value) || value <= 0) {
throw new Error('ids 仅支持正整数数组');
}
return value;
});
return Array.from(new Set(normalizedIds));
}
/**
* 判断订单是否允许从待处理模块取消。
* 仅允许处于待审核、待处理、待处理异常语义的订单取消。
* @param {Object} order 订单记录。
* @return {boolean} 是否允许取消。
*/
isCancelablePendingOrder(order = {}) {
const step = Number(order.step);
const status = String(order.status || '').trim().toLowerCase();
const outboundStatus = String(order.outbound_status || '').trim();
if (status === PENDING_CANCEL_STATUS) {
return false;
}
if (!PENDING_CANCEL_ALLOWED_STEPS.has(step)) {
return false;
}
if (PENDING_CANCEL_PENDING_STEPS.has(step) && outboundStatus === PENDING_OUTBOUND_STATUS) {
return false;
}
return true;
}
}

View File

@ -6,139 +6,28 @@ class ReviewOrderService extends OrderBaseService {
constructor(ctx) {
super(ctx);
const _noNeedLogin = '';
const _noNeedRight = 'getreviewOrderlist,reviewOrder';
const _noNeedLog = 'getreviewOrderlist';
const _noNeedAuth = 'getreviewOrderlist,reviewOrder';
const _noNeedRight = 'list,reviewOrder,';
const _noNeedLog = 'list,reviewOrder';
const _noNeedAuth = 'list,reviewOrder';
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
}
/**
* 将审核状态映射为订单步骤。
*
* @param {string} reviewStatus 审核状态。
* @return {number} 订单步骤值。
* 待审核订单列表。
* @param {Object} data 请求体。
* @return {Promise<Object>} 列表与分页信息。
*/
mapReviewStatusToStep(reviewStatus) {
const status = String(reviewStatus || 'none').trim();
if (status === 'fin') {
return 1;
}
if (status === 'running' || status === 'padding') {
return 2;
}
if (status === 'error') {
return 3;
}
return 0;
}
/**
* 获取待审核订单列表。
*
* @param {Object} data 请求参数。
* @return {Promise<Object>} 查询结果。
*/
async getreviewOrderlist(data = {}) {
try {
const warehouseId = this.ensureWarehouseId(data);
const { Op } = this.app.Sequelize;
const { DeliveryModel } = await this.getOrderModels(warehouseId);
this.prepareWhereContext(data);
const whereData = this.ctx.where || {};
const where = this.buildWhere(whereData, warehouseId);
const hasInspectionFilter = this.hasWhereValue(whereData, 'inspection_status');
if (!hasInspectionFilter) {
where.inspection_status = { [Op.ne]: 'none' };
}
if (this.hasWhereValue(whereData, 'operator_name')) {
const operatorName = this.getWhereValue(whereData, 'operator_name');
where.operator_name = { [Op.like]: `%${operatorName}%` };
}
this.applyDateRange(
where,
'operate_time',
this.getWhereValue(whereData, 'operate_time_start'),
this.getWhereValue(whereData, 'operate_time_end')
);
const { page, pageSize, offset } = this.getPagination(data.pagination);
const result = await DeliveryModel.findAndCountAll({
where,
attributes: [
'id',
'delivery_order_code',
'status',
'step',
'inspection_status',
'operator_name',
'operate_time',
'updated_at',
'store_id',
'warehouse_id',
'buyer_nick',
'logistics_name',
],
offset,
limit: pageSize,
order: [[ 'operate_time', 'DESC' ], [ 'updated_at', 'DESC' ], [ 'id', 'DESC' ]],
raw: true,
});
return this.success('ok', {
data: this.buildListData(result.rows, result.count, page, pageSize, {
queryInfo: {
defaultInspectionFilter: !hasInspectionFilter,
},
}),
code: 200,
});
} catch (error) {
return this.fail(error.message, { code: 500 });
}
async list(data = {}) {
return await this.listByModule('reviewOrder', data);
}
/**
* 更新订单审核状态。
*
* @param {Object} data 请求参数。
* @return {Promise<Object>} 更新结果。
* @param {Object} data 请求体。
* @return {Promise<Object>} 更新后的订单信息。
*/
async reviewOrder(data = {}) {
try {
const warehouseId = this.ensureWarehouseId(data);
const { DeliveryModel } = await this.getOrderModels(warehouseId);
const where = this.getOrderLocatorWhere(data, warehouseId);
const reviewStatus = String(
data.review_status ?? data.reviewStatus ?? data.inspection_status ?? 'fin'
).trim();
const allowedReviewStatus = new Set([ 'none', 'padding', 'running', 'fin', 'error' ]);
if (!allowedReviewStatus.has(reviewStatus)) {
return this.fail('review_status 参数不合法', { code: 400 });
}
const updateData = {
inspection_status: reviewStatus,
step: this.mapReviewStatusToStep(reviewStatus),
operator_name: data.operator_name || this.ctx.user?.real_name || this.ctx.user?.username || null,
operate_time: data.operate_time ? this.parseDateTime(data.operate_time, 'operate_time') : new Date(),
updated_at: new Date(),
};
const [ affected ] = await DeliveryModel.update(updateData, { where });
if (!affected) {
return this.fail('订单不存在或未更新', { code: 404 });
}
const order = await DeliveryModel.findOne({ where, raw: true });
return this.success('审核成功', { data: order, code: 200 });
} catch (error) {
return this.fail(error.message, { code: 500 });
}
return await this.updateReviewOrder(data);
}
}

View File

@ -0,0 +1,47 @@
'use strict';
const OrderBaseService = require('./base');
/**
* 系统方法层:订单储位分配入口。
* 仅负责参数归一化与调用底层公共 service。
*/
class StorageAllocationService extends OrderBaseService {
constructor(ctx) {
super(ctx);
const _noNeedLogin = '';
const _noNeedRight = 'allocateStorage';
const _noNeedLog = 'allocateStorage';
const _noNeedAuth = 'allocateStorage';
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
}
/**
* 批量分配订单储位。
*
* @param {Object} data 请求体。
* @return {Promise<Object>} 统一 success 包装。
*/
async allocateStorage(data = {}) {
const { service } = this;
const requestData = this.isPlainObject(data) ? data : {};
const normalizedData = {
allow_storage_location: requestData.allow_storage_location
?? requestData.allowStorageLocation
?? requestData.is_allow_storage
?? requestData.isAllowStorage,
order_ids: requestData.order_ids
?? requestData.orderIds
?? requestData.ids
?? requestData.order_id
?? requestData.orderId
?? requestData.id,
warehouse_id: requestData.warehouse_id ?? requestData.warehouseId,
};
const result = await service.systems.orderStorageAllocation.allocateStorage(normalizedData);
return this.success('ok', result);
}
}
module.exports = StorageAllocationService;

View File

@ -0,0 +1,61 @@
'use strict';
const MainService = require('../../main');
/**
* 系统方法层:storage.expiry(库存有效期列表包装层)。
* 职责:拆解 where 与分页参数,调用库存有效期业务服务并统一包装响应。
*/
class StorageExpiryMethodService extends MainService {
constructor(ctx) {
super(ctx);
const _noNeedLogin = '';
const _noNeedRight = 'list';
const _noNeedLog = 'list';
const _noNeedAuth = 'list';
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
}
/**
* 查询库存有效期预警列表。
*
* @param {Object} data 请求体
* @param {Object} [data.where] 查询条件
* @param {Object} [data.pagination] 分页参数
* @return {Promise<Object>} 统一 success 包装响应
*/
async list(data = {}) {
const { service } = this;
const { pagination } = data;
const { where } = this.prepareWhereContext(data, {
specialFieldMap: {
item_code: {
bucket: 'stock',
},
goods_code: {
bucket: 'stock',
},
item_name: {
bucket: 'stock',
},
sku_property: {
bucket: 'stock',
},
stock_unit: {
bucket: 'stock',
},
is_shelf_life_mgmt: {
bucket: 'stock',
field: 'is_shelf_life_mgmt',
},
remaining_threshold_days: {
bucket: 'stock',
},
},
});
const result = await service.systems.storage.expiry.list(where, pagination);
return this.success('ok', result);
}
}
module.exports = StorageExpiryMethodService;

View File

@ -82,8 +82,8 @@ class InventoryMethodService extends MainService {
async list(data = {}) {
const { service } = this;
const { pagination, sort, group_by_batch } = data;
const { where } = this.prepareWhereContext(data);
const result = await service.systems.storage.inventory.getInventoryList(where, pagination, sort, group_by_batch);
this.prepareWhereContext(data);
const result = await service.systems.storage.inventory.getInventoryList(pagination, sort, group_by_batch);
return this.success('ok', result);
}
}

View File

@ -1,83 +0,0 @@
'use strict';
const OrderBaseService = require('../order/base');
/**
* 系统方法层:storage.stockout(非订单出库单接口包装层)。
*/
class StorageStockoutService extends OrderBaseService {
constructor(ctx) {
super(ctx);
const _noNeedLogin = '';
const _noNeedRight = 'list,toOrder,listItems';
const _noNeedLog = 'list,toOrder,listItems';
const _noNeedAuth = 'list,toOrder,listItems';
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
}
async list(data = {}) {
try {
const warehouseId = this.ensureWarehouseId(data);
const { DeliveryModel } = await this.getOrderModels(warehouseId);
this.prepareWhereContext(data);
const whereData = this.ctx.where || {};
const where = this.buildWhere(whereData, warehouseId);
// 默认只查询订单类型为 STOCKOUT 的出库单
if (!whereData.order_type && !where.order_type) {
where.order_type = 'STOCKOUT';
}
const { page, pageSize, offset } = this.getPagination(data.pagination);
const result = await DeliveryModel.findAndCountAll({
where,
offset,
limit: pageSize,
order: [[ 'updated_at', 'DESC' ], [ 'id', 'DESC' ]],
raw: true,
});
return this.success('ok', {
data: this.buildListData(result.rows, result.count, page, pageSize),
code: 200,
});
} catch (error) {
return this.fail(error.message, { code: 500 });
}
}
async toOrder() {
return this.fail('占位接口,暂未开放', { code: 405, placeholder: true });
}
async listItems(data = {}) {
try {
const warehouseId = this.ensureWarehouseId(data);
const { DeliveryModel, OrderItemsModel } = await this.getOrderModels(warehouseId);
const where = this.getOrderLocatorWhere(data, warehouseId);
const order = await DeliveryModel.findOne({
where,
attributes: [ 'id', 'delivery_order_code' ],
raw: true,
});
if (!order) {
return this.fail('订单不存在', { code: 404 });
}
const items = await OrderItemsModel.findAll({
where: { order_id: order.id },
order: [[ 'id', 'ASC' ]],
raw: true,
});
return this.success('ok', {
data: { order, items },
code: 200,
});
} catch (error) {
return this.fail(error.message, { code: 500 });
}
}
}
module.exports = StorageStockoutService;

View File

@ -1,5 +1,6 @@
'use strict';
const Service = require('egg').Service;
const { normalizeWarehouseShardId } = require('../../lib/warehouse_shard_guard');
const DELIVERY_ORDER_STEP = Object.freeze({
PENDING_REVIEW: 0,
@ -11,7 +12,174 @@ const DELIVERY_ORDER_STEP = Object.freeze({
CLOSED: 9,
});
const DEFAULT_STORE_SUBJECT_CONFIG = Object.freeze({
max_notice_webhook_count: 5,
default_express_code: 'STO',
default_platform_code: 'TB',
});
const STORE_SUBJECT_CONFIG_CACHE_TTL_SECONDS = 600;
class DeliveryOrderService extends Service {
getStoreSubjectConfigCacheKey(storeId) {
return `delivery_order:store:${Number(storeId || 0)}:subject_config`;
}
normalizeStoreSubjectConfig(rawValue) {
const storeModel = (this.app.model && this.app.model.Store) || (this.ctx.model && this.ctx.model.Store);
if (storeModel && typeof storeModel.normalizeSubjectConfig === 'function') {
return storeModel.normalizeSubjectConfig(rawValue);
}
return {
...DEFAULT_STORE_SUBJECT_CONFIG,
...(rawValue && typeof rawValue === 'object' && !Array.isArray(rawValue) ? rawValue : {}),
};
}
async getStoreSubjectConfig(storeId) {
const normalizedStoreId = Number(storeId || 0);
if (!Number.isFinite(normalizedStoreId) || normalizedStoreId <= 0) {
return this.normalizeStoreSubjectConfig(null);
}
const cacheKey = this.getStoreSubjectConfigCacheKey(normalizedStoreId);
if (this.app && typeof this.app.getCacheAsync === 'function') {
try {
const cachedValue = await this.app.getCacheAsync(cacheKey);
if (cachedValue && typeof cachedValue === 'object') {
return this.normalizeStoreSubjectConfig(cachedValue);
}
} catch (error) {
this.ctx.logger.warn('[DeliveryOrderService.getStoreSubjectConfig] read cache failed: %s', error.message);
}
}
const storeModel = (this.app.model && this.app.model.Store) || (this.ctx.model && this.ctx.model.Store);
if (!storeModel || typeof storeModel.findByPk !== 'function') {
return this.normalizeStoreSubjectConfig(null);
}
try {
const store = await storeModel.findByPk(normalizedStoreId, {
attributes: [ 'id', 'subject_config' ],
});
const normalizedConfig = this.normalizeStoreSubjectConfig(store && store.subject_config);
if (this.app && typeof this.app.setCacheAsync === 'function') {
await this.app.setCacheAsync(cacheKey, normalizedConfig, STORE_SUBJECT_CONFIG_CACHE_TTL_SECONDS);
}
return normalizedConfig;
} catch (error) {
this.ctx.logger.warn('[DeliveryOrderService.getStoreSubjectConfig] load subject_config failed: %s', error.message);
return this.normalizeStoreSubjectConfig(null);
}
}
findCodeOption(list, code) {
const normalizedCode = String(code || '').trim();
if (!normalizedCode || !Array.isArray(list)) {
return null;
}
return list.find(item => item && String(item.code || item.value || '').trim() === normalizedCode) || null;
}
getOptionName(option) {
if (!option || typeof option !== 'object') {
return '';
}
return String(option.name || option.label || option.code || option.value || '').trim();
}
async resolvePlatformSnapshot(sourcePlatformCode, storeSubjectConfig, info = {}) {
const platformList = await this.ctx.service.systems.platform.getPlatformList();
const externalCode = String(sourcePlatformCode || '').trim();
const defaultCode = String(storeSubjectConfig && storeSubjectConfig.default_platform_code || '').trim();
const matchedPlatform = this.findCodeOption(platformList, externalCode);
if (matchedPlatform) {
return {
sysPlatformCode: String(matchedPlatform.code || matchedPlatform.value || externalCode).trim(),
sysPlatformName: this.getOptionName(matchedPlatform),
};
}
const fallbackPlatform = this.findCodeOption(platformList, defaultCode);
if (fallbackPlatform) {
this.ctx.logger.warn('[DeliveryOrderService.prepareOrderData] invalid platform code fallback to store default', {
deliveryOrderCode: info.deliveryOrderCode,
warehouseId: info.warehouseId,
storeId: info.storeId,
sourcePlatformCode: externalCode,
defaultPlatformCode: defaultCode,
});
return {
sysPlatformCode: String(fallbackPlatform.code || fallbackPlatform.value || defaultCode).trim(),
sysPlatformName: this.getOptionName(fallbackPlatform),
};
}
this.ctx.logger.warn('[DeliveryOrderService.prepareOrderData] platform default not found in platform service list', {
deliveryOrderCode: info.deliveryOrderCode,
warehouseId: info.warehouseId,
storeId: info.storeId,
sourcePlatformCode: externalCode,
defaultPlatformCode: defaultCode,
});
return {
sysPlatformCode: defaultCode || externalCode,
sysPlatformName: '',
};
}
async resolveExpressSnapshot(logisticsCode, storeSubjectConfig, info = {}) {
const expressList = await this.ctx.service.systems.express.getExpressList();
const externalCode = String(logisticsCode || '').trim();
const defaultCode = String(storeSubjectConfig && storeSubjectConfig.default_express_code || '').trim();
const matchedExpress = this.findCodeOption(expressList, externalCode);
if (matchedExpress) {
return {
sysLogisticsCode: String(matchedExpress.code || matchedExpress.value || externalCode).trim(),
sysLogisticsName: this.getOptionName(matchedExpress),
};
}
const fallbackExpress = this.findCodeOption(expressList, defaultCode);
if (fallbackExpress) {
this.ctx.logger.warn('[DeliveryOrderService.prepareOrderData] invalid logistics code fallback to store default', {
deliveryOrderCode: info.deliveryOrderCode,
warehouseId: info.warehouseId,
storeId: info.storeId,
logisticsCode: externalCode,
defaultExpressCode: defaultCode,
});
return {
sysLogisticsCode: String(fallbackExpress.code || fallbackExpress.value || defaultCode).trim(),
sysLogisticsName: this.getOptionName(fallbackExpress),
};
}
this.ctx.logger.warn('[DeliveryOrderService.prepareOrderData] express default not found in express service list', {
deliveryOrderCode: info.deliveryOrderCode,
warehouseId: info.warehouseId,
storeId: info.storeId,
logisticsCode: externalCode,
defaultExpressCode: defaultCode,
});
return {
sysLogisticsCode: defaultCode || externalCode,
sysLogisticsName: '',
};
}
/**
* 创建发货单。
*
@ -21,14 +189,18 @@ class DeliveryOrderService extends Service {
*/
async addOrder(data, info) {
const { ctx } = this;
if (!info.warehouseId) {
let warehouseIdStr;
try {
warehouseIdStr = normalizeWarehouseShardId(info.warehouseId);
} catch (e) {
return {
success: false,
message: '订单创建失败: 非法参数',
message: `订单创建失败: ${e.message}`,
data: null,
};
}
const DeliveryModel = await ctx.model.OrderDeliveryFactory.getCurrentModel(info.warehouseId);
info = { ...info, warehouseId: warehouseIdStr };
const DeliveryModel = await ctx.model.OrderDeliveryFactory.getCurrentModel(warehouseIdStr);
const { deliveryOrder, orderLines } = data.request;
// 开启事务
@ -189,12 +361,12 @@ class DeliveryOrderService extends Service {
: DELIVERY_ORDER_STEP.PENDING_REVIEW;
}
/**
* 生成订单结构哈希值。
*
* @param {Object} itemsInfo 订单明细信息。
* @return {string} 结构哈希值。
*/
/**
* 生成订单结构哈希值。
*
* @param {Object} itemsInfo 订单明细信息。
* @return {string} 结构哈希值。
*/
generateItemsHash(itemsInfo) {
const crypto = require('crypto');
@ -239,7 +411,7 @@ class DeliveryOrderService extends Service {
* @return {Promise<Object>} 可入库的订单数据。
*/
async prepareOrderData(deliveryOrder, info, step = DELIVERY_ORDER_STEP.PENDING_REVIEW) {
const { ctx, service } = this;
const { service } = this;
const {
deliveryOrderCode,
preDeliveryOrderCode,
@ -273,34 +445,17 @@ class DeliveryOrderService extends Service {
receiverInfo,
} = deliveryOrder;
let platformCode = sourcePlatformCode;
let platformName = sourcePlatformName;
try {
// 验证平台代码是否存在
const platformInfo = await service.systems.platform.checkPlatformExists(
sourcePlatformCode,
info.warehouseId
);
if (platformInfo) {
// 平台存在,使用数据库中的平台信息
platformCode = platformInfo.code;
platformName = platformInfo.name;
ctx.logger.info(`平台验证通过: ${sourcePlatformCode} -> ${platformCode} (${platformName})`);
} else {
// 平台不存在,抛出错误
throw new Error(`平台代码 ${sourcePlatformCode} 在仓库 ${info.warehouseId} 中不存在`);
}
} catch (error) {
ctx.logger.error(`平台验证失败: ${error.message}`, {
platformCode: sourcePlatformCode,
warehouseId: info.warehouseId,
deliveryOrderCode,
});
throw error; // 抛出错误,让上层捕获
}
const storeSubjectConfig = await this.getStoreSubjectConfig(info.storeId);
const platformSnapshot = await this.resolvePlatformSnapshot(sourcePlatformCode, storeSubjectConfig, {
deliveryOrderCode,
warehouseId: info.warehouseId,
storeId: info.storeId,
});
const expressSnapshot = await this.resolveExpressSnapshot(logisticsCode, storeSubjectConfig, {
deliveryOrderCode,
warehouseId: info.warehouseId,
storeId: info.storeId,
});
return {
delivery_order_code: deliveryOrderCode,
@ -309,9 +464,10 @@ class DeliveryOrderService extends Service {
order_type: orderType,
warehouse_code: warehouseCode,
order_flag: orderFlag || '',
// 使用验证后的平台信息
source_platform_code: platformCode,
source_platform_name: platformName,
source_platform_code: sourcePlatformCode || '',
source_platform_name: sourcePlatformName || '',
sys_platform_code: platformSnapshot.sysPlatformCode,
sys_platform_name: platformSnapshot.sysPlatformName,
create_at: createTime ? new Date(createTime) : new Date(),
place_order_time: placeOrderTime ? new Date(placeOrderTime) : null,
pay_time: payTime ? new Date(payTime) : null,
@ -327,8 +483,10 @@ class DeliveryOrderService extends Service {
freight: freight ? parseFloat(freight) : 0,
ar_amount: arAmount ? parseFloat(arAmount) : 0,
got_amount: gotAmount ? parseFloat(gotAmount) : 0,
logistics_code: logisticsCode,
logistics_name: logisticsName,
logistics_code: logisticsCode || '',
logistics_name: logisticsName || '',
sys_logistics_code: expressSnapshot.sysLogisticsCode,
sys_logistics_name: expressSnapshot.sysLogisticsName,
express_code: expressCode || '',
logistics_area_code: logisticsAreaCode || '',
is_urgency: isUrgency || 'N',
@ -494,7 +652,7 @@ class DeliveryOrderService extends Service {
ext_code: line.extCode || '',
inventory_type: line.inventoryType || '',
item_code: line.itemCode || '',
item_id: line.itemId || null,
item_id: itemId,
item_name: line.itemName || '',
order_line_no: line.orderLineNo || `${i + 1}`,
owner_code: line.ownerCode || '',
@ -504,6 +662,8 @@ class DeliveryOrderService extends Service {
extend_props: line.extendProps ?
(typeof line.extendProps === 'string' ? line.extendProps : JSON.stringify(line.extendProps))
: null,
stock_id: stockId,
item_snapshot: this.buildOrderItemSnapshot(wms_stock, line),
// 可选:记录重量信息到明细
item_weight: stockWeightMap.get(stockId) || 0,
});
@ -585,6 +745,31 @@ class DeliveryOrderService extends Service {
};
}
buildOrderItemSnapshot(stockRecord = {}, line = {}) {
return {
id: Number(stockRecord.id || 0) || null,
stock_id: Number(stockRecord.stock_id || 0) || null,
item_code: String(stockRecord.item_code || line.itemCode || '').trim(),
item_name: String(stockRecord.item_name || line.itemName || '').trim(),
goods_code: String(stockRecord.goods_code || '').trim(),
sku_property: String(stockRecord.sku_property || '').trim(),
barcode: String(stockRecord.barcode || '').trim(),
brand_name: String(stockRecord.brand_name || '').trim(),
category_id: Number(stockRecord.category_id || 0) || null,
category_name: String(stockRecord.category_name || '').trim(),
item_type: String(stockRecord.item_type || '').trim(),
stock_unit: String(stockRecord.stock_unit || '').trim(),
inventory_type: String(line.inventoryType || '').trim(),
retail_price: this.safeParseFloat(stockRecord.retail_price, this.safeParseFloat(line.retailPrice, 0)),
gross_weight: this.safeParseFloat(stockRecord.gross_weight, 0),
net_weight: this.safeParseFloat(stockRecord.net_weight, 0),
length: this.safeParseFloat(stockRecord.length, 0),
width: this.safeParseFloat(stockRecord.width, 0),
height: this.safeParseFloat(stockRecord.height, 0),
volume: this.safeParseFloat(stockRecord.volume, 0),
};
}
// 添加工具方法
safeParseFloat(value, defaultValue = 0) {
if (value === null || value === undefined) return defaultValue;

View File

@ -521,7 +521,7 @@ class ExcelService extends Service {
});
await fs.promises.mkdir(path.dirname(resolvedFilePath), { recursive: true });
await fs.promises.writeFile(resolvedFilePath, buffer);
await this.writeAtomicBufferFile(resolvedFilePath, buffer);
return {
filePath: resolvedFilePath,
@ -530,6 +530,30 @@ class ExcelService extends Service {
};
}
async writeAtomicBufferFile(targetPath, buffer) {
const directory = path.dirname(targetPath);
const tempPath = path.join(
directory,
`.${path.basename(targetPath)}.${process.pid}.${Date.now()}.${crypto.randomBytes(6).toString('hex')}.tmp`
);
await fs.promises.writeFile(tempPath, buffer);
try {
await fs.promises.rename(tempPath, targetPath);
} catch (error) {
if (error && (error.code === 'EEXIST' || error.code === 'EPERM' || error.code === 'EBUSY')) {
await fs.promises.rm(targetPath, { force: true });
await fs.promises.rename(tempPath, targetPath);
return;
}
throw error;
} finally {
await fs.promises.rm(tempPath, { force: true }).catch(() => {});
}
}
sanitizeFilename(filename = 'export.xlsx', fallbackExt = '.xlsx') {
const normalizedName = String(filename || '').trim() || `export${fallbackExt}`;
const rawExt = path.extname(normalizedName);

View File

@ -0,0 +1,69 @@
'use strict';
const { Service } = require('egg');
const DEFAULT_CACHE_TTL_SECONDS = 600;
class ExpressService extends Service {
getExpressListCacheKey() {
return 'express:list';
}
normalizeExpressRow(row) {
if (!row || typeof row !== 'object') {
return null;
}
const code = String(row.code || '').trim();
if (!code) {
return null;
}
return {
code,
name: String(row.name || '').trim(),
value: code,
label: String(row.name || code).trim(),
};
}
async loadExpressListFromDatabase() {
const rows = await this.ctx.model.Express.findAll({
attributes: [ 'code', 'name' ],
order: [[ 'code', 'ASC' ]],
raw: true,
});
if (!Array.isArray(rows)) {
return [];
}
return rows
.map(row => this.normalizeExpressRow(row))
.filter(Boolean);
}
async getExpressList() {
const cacheKey = this.getExpressListCacheKey();
try {
const cachedList = await this.app.getCacheAsync(cacheKey);
if (cachedList !== null && cachedList !== undefined) {
return Array.isArray(cachedList) ? cachedList : [];
}
const expressList = await this.loadExpressListFromDatabase();
await this.app.setCacheAsync(cacheKey, expressList, DEFAULT_CACHE_TTL_SECONDS);
return expressList;
} catch (error) {
this.ctx.logger.error('[ExpressService.getExpressList] 获取快递列表失败', {
error: error.message,
stack: error.stack,
});
throw error;
}
}
}
module.exports = ExpressService;

View File

@ -24,6 +24,7 @@ const DEFAULT_REGISTERED_EVENT_CODES = Object.freeze([
'all',
'*',
'receiving_completed',
'order_cancel_intercepted',
'store_warehouse_print_quantity_adjusted',
]);
const DRIVER_TYPE_ALIASES = Object.freeze({
@ -586,6 +587,8 @@ class NoticeService extends Service {
const config = this.toObject(value, {});
return {
max_notice_webhook_count: DEFAULT_MAX_NOTICE_WEBHOOK_COUNT,
default_express_code: 'STO',
default_platform_code: 'TB',
...config,
};
};

View File

@ -0,0 +1,643 @@
'use strict';
const MainService = require('../main');
const OUTBOUND_STATUS = 'fin';
const OUTBOUND_STATUS_TIMEOUT = 'timeout';
const OUTBOUND_STEP = 4;
const DISPATCH_LANE = 'm4';
const MAX_BATCH_SIZE = 1000;
const CURRENT_TABLE_PATTERN = /^wms_order_delivery_(\d+)$/;
const RETRYABLE_DATABASE_ERROR_CODES = new Set([ 1205, 1213, 'ER_LOCK_WAIT_TIMEOUT', 'ER_LOCK_DEADLOCK' ]);
/**
* 订单出库后迁移到配送表的同步服务。
*/
class OrderDeliveryMigrationService extends MainService {
/**
* 同步当前仓库分表中已出库订单到配送表。
*
* @param {Object} data 请求参数。
* @param {number|Array<number|string>} [data.warehouseId] 单个仓库ID或仓库ID列表。
* @param {Array<number|string>} [data.warehouseIds] 仓库ID列表。
* @return {Promise<Object>} 同步结果。
*/
async syncOutboundOrdersToDelivery(data = {}) {
return this.syncOutboundOrdersByStatus(data, {
outboundStatuses: [ OUTBOUND_STATUS ],
persistTimeoutState: true,
});
}
/**
* 重试出库超时订单并继续迁移到配送表。
*
* @param {Object} data 请求参数。
* @param {number|Array<number|string>} [data.warehouseId] 单个仓库ID或仓库ID列表。
* @param {Array<number|string>} [data.warehouseIds] 仓库ID列表。
* @return {Promise<Object>} 同步结果。
*/
async retryTimeoutOutboundOrdersToDelivery(data = {}) {
return this.syncOutboundOrdersByStatus(data, {
outboundStatuses: [ OUTBOUND_STATUS_TIMEOUT ],
persistTimeoutState: false,
});
}
/**
* 按指定出库状态同步订单到配送表。
*
* @param {Object} data 请求参数。
* @param {number|Array<number|string>} [data.warehouseId] 单个仓库ID或仓库ID列表。
* @param {Array<number|string>} [data.warehouseIds] 仓库ID列表。
* @param {Object} [options] 迁移控制参数。
* @param {Array<string>} [options.outboundStatuses] 需要迁移的出库状态。
* @param {number} [options.queryTimeoutMs] 单条数据库查询的超时时间。
* @param {number} [options.executionTimeoutMs] 单仓库批次的执行超时时间。
* @param {boolean} [options.persistTimeoutState] 失败后是否将源订单标记为出库超时。
* @return {Promise<Object>} 同步结果。
*/
async syncOutboundOrdersByStatus(data = {}, options = {}) {
const requestData = this.isPlainObject(data) ? data : {};
const explicitWarehouseIds = this.normalizeWarehouseIds(requestData);
const warehouseIds = explicitWarehouseIds.length > 0
? explicitWarehouseIds
: await this.listCurrentWarehouseIds();
const results = [];
let remaining = MAX_BATCH_SIZE;
let totalSelected = 0;
let totalCreated = 0;
let totalSkipped = 0;
let totalTimeout = 0;
for (const warehouseId of warehouseIds) {
if (remaining <= 0) {
break;
}
const batchLimit = Math.min(remaining, MAX_BATCH_SIZE);
const batchResult = await this.syncOutboundOrdersForWarehouse(warehouseId, batchLimit, options);
results.push(batchResult);
totalSelected += batchResult.selectedCount;
totalCreated += batchResult.createdCount;
totalSkipped += batchResult.skippedCount;
totalTimeout += Number(batchResult.timeoutCount || 0);
remaining -= batchResult.selectedCount;
}
return {
warehouseIds,
batchSize: MAX_BATCH_SIZE,
outboundStatuses: this.normalizeOutboundStatuses(options.outboundStatuses),
totalSelected,
totalCreated,
totalSkipped,
totalTimeout,
results,
};
}
/**
* 规范化仓库ID列表。
*
* @param {Object} data 请求参数。
* @return {Array<number>} 仓库ID列表。
*/
normalizeWarehouseIds(data = {}) {
if (!this.isPlainObject(data)) {
return [];
}
const candidateValues = Array.isArray(data.warehouseIds)
? data.warehouseIds
: [ data.warehouseId ?? data.warehouse_id ].filter(value => value !== undefined && value !== null && value !== '');
return Array.from(new Set(candidateValues
.map(value => Number(value))
.filter(value => Number.isFinite(value) && value > 0)))
.sort((left, right) => left - right);
}
/**
* 获取当前库中存在的订单工作台仓库ID。
*
* @return {Promise<Array<number>>} 仓库ID列表。
*/
async listCurrentWarehouseIds() {
const factory = this.ctx.model && this.ctx.model.OrderDeliveryFactory;
if (!factory || typeof factory.listManagedTableNames !== 'function') {
return [];
}
const tableNames = await factory.listManagedTableNames();
return Array.from(new Set((Array.isArray(tableNames) ? tableNames : [])
.map(tableName => {
const matched = CURRENT_TABLE_PATTERN.exec(String(tableName || ''));
return matched ? Number(matched[1]) : null;
})
.filter(value => Number.isFinite(value) && value > 0)))
.sort((left, right) => left - right);
}
/**
* 规范化需要迁移的出库状态。
*
* @param {Array<string>|string} outboundStatuses 目标状态。
* @return {Array<string>} 规范化后的状态列表。
*/
normalizeOutboundStatuses(outboundStatuses = [ OUTBOUND_STATUS ]) {
const candidates = Array.isArray(outboundStatuses)
? outboundStatuses
: [ outboundStatuses ];
const normalizedStatuses = Array.from(new Set(candidates
.map(value => String(value || '').trim())
.filter(Boolean)));
return normalizedStatuses.length > 0 ? normalizedStatuses : [ OUTBOUND_STATUS ];
}
/**
* 构造 Sequelize 查询参数。
*
* @param {Object|null} transaction 事务对象。
* @param {number} [queryTimeoutMs] 查询超时时间。
* @return {Object} Sequelize 查询参数。
*/
buildMigrationQueryOptions(transaction, queryTimeoutMs) {
const queryOptions = {};
if (transaction) {
queryOptions.transaction = transaction;
}
const normalizedTimeoutMs = Number(queryTimeoutMs);
if (Number.isFinite(normalizedTimeoutMs) && normalizedTimeoutMs > 0) {
queryOptions.timeout = normalizedTimeoutMs;
}
return queryOptions;
}
/**
* 识别可重试的出库迁移错误。
*
* @param {Error} error 运行时错误。
* @return {{ retryable: boolean, category: string, message: string }} 错误分类结果。
*/
getOutboundMigrationErrorInfo(error) {
const errorMessage = String(error && error.message || '');
const errorName = String(error && error.name || '');
const parentError = error && error.parent ? error.parent : null;
const errorCode = parentError && (parentError.code || parentError.errno)
? parentError.code || parentError.errno
: error && (error.code || error.errno);
const normalizedMessage = errorMessage.toLowerCase();
if (errorName === 'SequelizeTimeoutError' || errorName === 'TimeoutError' || errorCode === 'ETIMEDOUT') {
return {
retryable: true,
category: 'timeout',
message: errorMessage,
};
}
if (errorName === 'SequelizeDatabaseError') {
if (normalizedMessage.includes('lock wait timeout')) {
return {
retryable: true,
category: 'lock_wait_timeout',
message: errorMessage,
};
}
if (RETRYABLE_DATABASE_ERROR_CODES.has(errorCode) || normalizedMessage.includes('deadlock')) {
return {
retryable: true,
category: 'deadlock',
message: errorMessage,
};
}
}
return {
retryable: false,
category: 'other',
message: errorMessage,
};
}
/**
* 将指定仓库内的源订单标记为出库超时。
*
* @param {number} warehouseId 仓库ID。
* @param {Array<number>} orderIds 源订单ID列表。
* @param {number} [queryTimeoutMs] 更新语句超时时间。
* @return {Promise<number>} 受影响行数。
*/
async markOutboundOrdersTimeout(warehouseId, orderIds, queryTimeoutMs) {
const normalizedWarehouseId = Number(warehouseId);
const normalizedOrderIds = Array.from(new Set((Array.isArray(orderIds) ? orderIds : [])
.map(value => Number(value))
.filter(value => Number.isFinite(value) && value > 0)));
if (!Number.isFinite(normalizedWarehouseId) || normalizedWarehouseId <= 0) {
throw new Error('仓库ID不能为空');
}
if (normalizedOrderIds.length === 0) {
return 0;
}
const orderFactory = this.ctx.model && this.ctx.model.OrderDeliveryFactory;
if (!orderFactory || typeof orderFactory.getCurrentModel !== 'function') {
throw new Error('订单工厂未初始化');
}
const sourceOrderModel = await orderFactory.getCurrentModel(normalizedWarehouseId);
const { Op } = this.ctx.app.Sequelize;
const updateValues = {
outbound_status: OUTBOUND_STATUS_TIMEOUT,
step: OUTBOUND_STEP,
updated_at: new Date(),
};
const updateResult = await sourceOrderModel.update(updateValues, {
where: {
warehouse_id: normalizedWarehouseId,
id: {
[Op.in]: normalizedOrderIds,
},
},
...this.buildMigrationQueryOptions(null, queryTimeoutMs),
});
return Array.isArray(updateResult) ? Number(updateResult[0] || 0) : Number(updateResult || 0);
}
/**
* 构造配送表去重键。
*
* @param {Object} row 订单行数据。
* @return {string} 去重键。
*/
buildDispatchKey(row) {
if (!this.isPlainObject(row)) {
return '';
}
const deliveryOrderCode = String(row.delivery_order_code || '').trim();
const storeId = String(row.store_id || '').trim();
const warehouseId = String(row.warehouse_id || '').trim();
if (!deliveryOrderCode || !storeId || !warehouseId) {
return '';
}
return `${deliveryOrderCode}::${storeId}::${warehouseId}`;
}
/**
* 构造配送表插入行。
*
* @param {Object} row 当前订单工作台数据。
* @return {Object} 可写入配送表的数据。
*/
buildDispatchRow(row) {
const payload = {
...(row || {}),
};
delete payload.dispatch_lane;
return {
...payload,
dispatch_lane: DISPATCH_LANE,
};
}
/**
* 构造商品明细迁移行。
*
* @param {Object} row 当前订单商品明细行。
* @param {number} targetOrderId 配送表订单ID。
* @return {Object} 可写入配送明细表的数据。
*/
buildDispatchItemRow(row, targetOrderId) {
return {
...(row || {}),
order_id: targetOrderId,
};
}
/**
* 获取订单与商品明细迁移所需的模型。
*
* @param {number} warehouseId 仓库ID。
* @return {Promise<Object>} 迁移模型集合。
*/
async getMigrationModels(warehouseId) {
const orderFactory = this.ctx.model && this.ctx.model.OrderDeliveryFactory;
const itemsFactory = this.ctx.model && this.ctx.model.OrderItemsFactory;
if (!orderFactory || typeof orderFactory.getCurrentModel !== 'function' || typeof orderFactory.getDispatchModel !== 'function') {
throw new Error('订单工厂未初始化');
}
if (!itemsFactory || typeof itemsFactory.getCurrentModel !== 'function' || typeof itemsFactory.getDispatchModel !== 'function') {
throw new Error('订单商品工厂未初始化');
}
return {
sourceOrderModel: await orderFactory.getCurrentModel(warehouseId),
targetOrderModel: await orderFactory.getDispatchModel(warehouseId),
sourceItemModel: await itemsFactory.getCurrentModel(warehouseId),
targetItemModel: await itemsFactory.getDispatchModel(warehouseId),
};
}
/**
* 将配送表订单行转换为订单ID映射。
*
* @param {Array<Object>} rows 配送表订单行。
* @return {Map<string, number>} 业务键到订单ID的映射。
*/
buildTargetOrderIdMap(rows) {
return new Map((Array.isArray(rows) ? rows : [])
.map(row => {
const key = this.buildDispatchKey(row);
const orderId = Number(row && row.id);
if (!key || !Number.isFinite(orderId) || orderId <= 0) {
return null;
}
return [ key, orderId ];
})
.filter(Boolean));
}
/**
* 同步指定仓库的已出库订单。
*
* @param {number|string} warehouseId 仓库ID。
* @param {number} [limit=1000] 单次处理数量上限。
* @param {Object} [options] 迁移控制参数。
* @param {Array<string>} [options.outboundStatuses] 需要迁移的出库状态。
* @param {number} [options.queryTimeoutMs] 单条数据库查询的超时时间。
* @param {number} [options.executionTimeoutMs] 单仓库批次的执行超时时间。
* @param {boolean} [options.persistTimeoutState] 失败后是否将源订单标记为出库超时。
* @return {Promise<Object>} 同步结果。
*/
async syncOutboundOrdersForWarehouse(warehouseId, limit = MAX_BATCH_SIZE, options = {}) {
const normalizedWarehouseId = Number(warehouseId);
if (!Number.isFinite(normalizedWarehouseId) || normalizedWarehouseId <= 0) {
throw new Error('仓库ID不能为空');
}
const batchLimit = Math.min(
Math.max(Number(limit) || MAX_BATCH_SIZE, 1),
MAX_BATCH_SIZE
);
const outboundStatuses = this.normalizeOutboundStatuses(options.outboundStatuses);
const queryTimeoutMs = Number(options.queryTimeoutMs);
const executionTimeoutMs = Number(options.executionTimeoutMs);
const persistTimeoutState = Boolean(options.persistTimeoutState);
const deadlineAt = Number.isFinite(executionTimeoutMs) && executionTimeoutMs > 0
? Date.now() + executionTimeoutMs
: 0;
const transaction = await this.ctx.model.transaction();
const { Op } = this.ctx.app.Sequelize;
let sourceRows = [];
let selectedSourceOrderIds = [];
const assertMigrationDeadline = stage => {
if (deadlineAt > 0 && Date.now() > deadlineAt) {
const timeoutError = new Error(`仓库 ${normalizedWarehouseId} ${stage} 执行超时`);
timeoutError.code = 'OUTBOUND_MIGRATION_TIMEOUT';
throw timeoutError;
}
};
try {
assertMigrationDeadline('出库迁移');
const {
sourceOrderModel,
targetOrderModel,
sourceItemModel,
targetItemModel,
} = await this.getMigrationModels(normalizedWarehouseId);
assertMigrationDeadline('查询源订单');
sourceRows = await sourceOrderModel.findAll({
where: {
warehouse_id: normalizedWarehouseId,
outbound_status: {
[Op.in]: outboundStatuses,
},
step: OUTBOUND_STEP,
},
order: [[ 'id', 'ASC' ]],
limit: batchLimit,
raw: true,
...this.buildMigrationQueryOptions(transaction, queryTimeoutMs),
});
selectedSourceOrderIds = Array.from(new Set((Array.isArray(sourceRows) ? sourceRows : [])
.map(row => Number(row && row.id))
.filter(value => Number.isFinite(value) && value > 0)));
if (!Array.isArray(sourceRows) || sourceRows.length === 0) {
await transaction.commit();
return {
warehouseId: normalizedWarehouseId,
selectedCount: 0,
createdCount: 0,
skippedCount: 0,
timeoutCount: 0,
};
}
const invalidSourceRows = sourceRows.filter(row => !this.buildDispatchKey(row));
if (invalidSourceRows.length > 0) {
const invalidRowIds = invalidSourceRows
.map(row => Number(row && row.id))
.filter(value => Number.isFinite(value) && value > 0);
throw new Error(`选中的源订单存在缺少 delivery_order_code/store_id/warehouse_id 的记录${invalidRowIds.length > 0 ? `: ${invalidRowIds.join(', ')}` : ''}`);
}
const validSourceRows = sourceRows;
const sourceOrderRowMap = new Map(validSourceRows
.map(row => [ Number(row.id), row ])
.filter(([ rowId, row ]) => Number.isFinite(rowId) && rowId > 0 && this.buildDispatchKey(row)));
const deliveryOrderCodes = Array.from(new Set(validSourceRows
.map(row => String(row.delivery_order_code || '').trim())
.filter(Boolean)));
const sourceOrderIds = Array.from(sourceOrderRowMap.keys());
let existingRows = [];
if (deliveryOrderCodes.length > 0) {
assertMigrationDeadline('查询配送表订单');
existingRows = await targetOrderModel.findAll({
where: {
warehouse_id: normalizedWarehouseId,
delivery_order_code: {
[Op.in]: deliveryOrderCodes,
},
},
raw: true,
...this.buildMigrationQueryOptions(transaction, queryTimeoutMs),
});
}
const existingKeySet = new Set((Array.isArray(existingRows) ? existingRows : [])
.map(row => this.buildDispatchKey(row))
.filter(Boolean));
const rowsToCreate = validSourceRows
.filter(row => !existingKeySet.has(this.buildDispatchKey(row)))
.map(row => this.buildDispatchRow(row));
if (rowsToCreate.length > 0) {
assertMigrationDeadline('创建配送表订单');
await targetOrderModel.bulkCreate(rowsToCreate, {
...this.buildMigrationQueryOptions(transaction, queryTimeoutMs),
ignoreDuplicates: true,
});
}
assertMigrationDeadline('查询配送表订单');
const targetRows = deliveryOrderCodes.length > 0
? await targetOrderModel.findAll({
where: {
warehouse_id: normalizedWarehouseId,
delivery_order_code: {
[Op.in]: deliveryOrderCodes,
},
},
raw: true,
...this.buildMigrationQueryOptions(transaction, queryTimeoutMs),
})
: [];
const targetOrderIdMap = this.buildTargetOrderIdMap(targetRows);
if (sourceOrderIds.length > 0) {
assertMigrationDeadline('查询商品明细');
const sourceItems = await sourceItemModel.findAll({
where: {
order_id: {
[Op.in]: sourceOrderIds,
},
},
order: [[ 'id', 'ASC' ]],
raw: true,
...this.buildMigrationQueryOptions(transaction, queryTimeoutMs),
});
const validSourceItems = Array.isArray(sourceItems)
? sourceItems.filter(item => Number.isFinite(Number(item && item.id)))
: [];
const rowsToCreateItems = validSourceItems.map(item => {
const sourceOrder = sourceOrderRowMap.get(Number(item.order_id));
const targetOrderId = targetOrderIdMap.get(this.buildDispatchKey(sourceOrder));
if (!Number.isFinite(targetOrderId) || targetOrderId <= 0) {
throw new Error(`无法找到订单 ${item.order_id} 对应的配送表订单ID`);
}
return this.buildDispatchItemRow(item, targetOrderId);
});
if (rowsToCreateItems.length > 0) {
assertMigrationDeadline('创建商品明细');
await targetItemModel.bulkCreate(rowsToCreateItems, {
...this.buildMigrationQueryOptions(transaction, queryTimeoutMs),
ignoreDuplicates: true,
});
}
assertMigrationDeadline('删除源商品明细');
await sourceItemModel.destroy({
where: {
id: {
[Op.in]: validSourceItems.map(item => Number(item.id)).filter(value => Number.isFinite(value) && value > 0),
},
},
...this.buildMigrationQueryOptions(transaction, queryTimeoutMs),
});
}
if (sourceOrderIds.length > 0) {
assertMigrationDeadline('删除源订单');
await sourceOrderModel.destroy({
where: {
id: {
[Op.in]: sourceOrderIds,
},
},
...this.buildMigrationQueryOptions(transaction, queryTimeoutMs),
});
}
await transaction.commit();
return {
warehouseId: normalizedWarehouseId,
selectedCount: sourceRows.length,
createdCount: rowsToCreate.length,
skippedCount: sourceRows.length - rowsToCreate.length,
timeoutCount: 0,
};
} catch (error) {
await transaction.rollback();
const migrationErrorInfo = this.getOutboundMigrationErrorInfo(error);
const shouldPersistTimeoutState = persistTimeoutState && migrationErrorInfo.retryable && selectedSourceOrderIds.length > 0;
if (shouldPersistTimeoutState) {
const timeoutCount = await this.markOutboundOrdersTimeout(
normalizedWarehouseId,
selectedSourceOrderIds,
queryTimeoutMs
);
return {
warehouseId: normalizedWarehouseId,
selectedCount: sourceRows.length,
createdCount: 0,
skippedCount: 0,
timeoutCount,
retryableFailure: true,
retryableFailureType: migrationErrorInfo.category,
retryableFailureMessage: migrationErrorInfo.message,
};
}
if (migrationErrorInfo.retryable) {
return {
warehouseId: normalizedWarehouseId,
selectedCount: sourceRows.length,
createdCount: 0,
skippedCount: 0,
timeoutCount: 0,
retryableFailure: true,
retryableFailureType: migrationErrorInfo.category,
retryableFailureMessage: migrationErrorInfo.message,
};
}
throw error;
}
}
}
module.exports = OrderDeliveryMigrationService;

View File

@ -0,0 +1,89 @@
'use strict';
const OrderBaseService = require('../systemMethods/order/base');
const OUTBOUND_STATUS = 'fin';
const OUTBOUND_STEP = 4;
/**
* 订单出库状态服务。
* 仅用于内部把订单标记为出库,不对外暴露通用 method。
*/
class OrderOutboundService extends OrderBaseService {
/**
* 将订单标记为出库。
*
* 兼容单条与批量入参,支持 id、order_id、ids 三种订单 ID 写法。
* 仅更新出库状态相关字段:outbound_status、step、delivery_time、updated_at。
*
* @param {Object} data 请求体。
* @return {Promise<Object>} 更新后的订单信息,包含出库状态与更新数量。
*/
async markOutboundOrder(data = {}) {
const requestData = this.isPlainObject(data) ? data : {};
const warehouseId = this.getWarehouseId();
const orderIds = this.normalizeOrderIds(requestData);
if (orderIds.length === 0) {
throw new Error('订单ID不能为空');
}
const model = await this.getOrderModel('order', warehouseId);
const now = new Date();
const where = this.buildOrderWhere(orderIds, warehouseId);
const updateValues = {
outbound_status: OUTBOUND_STATUS,
step: OUTBOUND_STEP,
delivery_time: now,
updated_at: now,
};
const updateResult = await model.update(updateValues, {
where,
});
const affectedRows = Array.isArray(updateResult) ? Number(updateResult[0] || 0) : Number(updateResult || 0);
if (affectedRows <= 0) {
throw new Error('订单不存在或不属于当前仓库');
}
const updatedOrders = await model.findAll({
where,
raw: true,
});
if (!Array.isArray(updatedOrders) || updatedOrders.length === 0) {
throw new Error('订单不存在或不属于当前仓库');
}
const orderMap = new Map(updatedOrders.map(order => [ Number(order.id), order ]));
const normalizedOrders = orderIds
.map(orderId => orderMap.get(orderId))
.filter(Boolean)
.map(order => ({
id: order.id,
outbound_status: order.outbound_status,
step: Number(order.step ?? OUTBOUND_STEP),
delivery_time: order.delivery_time,
updated_at: order.updated_at,
}));
if (normalizedOrders.length === 0) {
throw new Error('订单不存在或不属于当前仓库');
}
const firstOrder = normalizedOrders[0];
return {
id: firstOrder.id,
outbound_status: firstOrder.outbound_status,
step: firstOrder.step,
delivery_time: firstOrder.delivery_time,
updated_at: firstOrder.updated_at,
updated_count: affectedRows,
ids: normalizedOrders.map(order => order.id),
};
}
}
module.exports = OrderOutboundService;

View File

@ -0,0 +1,43 @@
'use strict';
const OrderBaseService = require('../systemMethods/order/base');
class OrderPendingExceptionService extends OrderBaseService {
/**
* 将订单标记为待处理异常。
*
* 兼容单条与批量入参,支持 id、order_id、ids 三种订单 ID 写法。
* 异常文本会保留在订单标记字段上,供待处理异常列表展示或追踪;审核/反审只负责状态流转,不会主动清空该字段。
*
* @param {Object} data 请求体。
* @return {Promise<Object>} 更新后的订单信息,包含异常文本与更新数量。
*/
async markPendingException(data = {}) {
const requestData = this.isPlainObject(data) ? data : {};
const exceptionText = String(
requestData.exception_text
?? requestData.exception_reason
?? requestData.remark
?? requestData.reason
?? ''
).trim();
if (!exceptionText) {
throw new Error('异常文本不能为空');
}
const result = await this.updateOrderInspectionState(requestData, 'error', {
extraUpdateValues: {
order_flag: exceptionText,
},
});
return {
...result,
exception_text: exceptionText,
order_flag: exceptionText,
};
}
}
module.exports = OrderPendingExceptionService;

View File

@ -0,0 +1,636 @@
'use strict';
const MainService = require('../main');
const STORAGE_STATUS_FIN = 'fin';
const STORAGE_STATUS_ERROR = 'error';
const ORDER_STEP_EXCEPTION = 3;
/**
* 将输入值规范化为布尔值。
*
* @param {unknown} value 待转换的值。
* @param {boolean} [defaultValue=false] 空值时的默认布尔值。
* @return {boolean} 是否为真。
*/
function normalizeBooleanFlag(value, defaultValue = false) {
if (value === undefined || value === null || value === '') {
return defaultValue;
}
if (typeof value === 'boolean') {
return value;
}
if (typeof value === 'number') {
return value === 1;
}
if (typeof value === 'string') {
return [ '1', 'Y', 'YES', 'TRUE', 'ON' ].includes(value.trim().toUpperCase());
}
return false;
}
/**
* 将输入值转换为有限数字。
*
* @param {unknown} value 待转换的值。
* @param {number} [defaultValue=0] 默认值。
* @return {number} 转换后的数字。
*/
function toNumber(value, defaultValue = 0) {
const normalized = Number(value);
return Number.isFinite(normalized) ? normalized : defaultValue;
}
/**
* 将模型记录转换为普通对象。
*
* @param {unknown} record 模型记录。
* @return {Object|null} 普通对象。
*/
function toPlainRecord(record) {
if (!record) {
return null;
}
if (typeof record.get === 'function') {
return record.get({ plain: true });
}
return record;
}
/**
* 解析日期值并返回时间戳。
*
* @param {unknown} value 日期值。
* @return {number} 时间戳或 Number.MAX_SAFE_INTEGER。
*/
function toTimeValue(value) {
if (!value) {
return Number.MAX_SAFE_INTEGER;
}
const timeValue = new Date(value).getTime();
return Number.isFinite(timeValue) ? timeValue : Number.MAX_SAFE_INTEGER;
}
/**
* 对可分配库存按优先级排序。
*
* @param {Object} left 左侧库存。
* @param {Object} right 右侧库存。
* @param {boolean} prioritizeStorage 是否优先使用存储储位。
* @return {number} 排序结果。
*/
function compareStorageRows(left, right, prioritizeStorage) {
const leftPickPriority = prioritizeStorage ? (left.is_preferred_pick ? 1 : 0) : 0;
const rightPickPriority = prioritizeStorage ? (right.is_preferred_pick ? 1 : 0) : 0;
if (leftPickPriority !== rightPickPriority) {
return leftPickPriority - rightPickPriority;
}
const leftHasProductionDate = Boolean(left.production_date);
const rightHasProductionDate = Boolean(right.production_date);
if (leftHasProductionDate !== rightHasProductionDate) {
return leftHasProductionDate ? -1 : 1;
}
if (leftHasProductionDate && rightHasProductionDate) {
const productionDiff = toTimeValue(left.production_date) - toTimeValue(right.production_date);
if (productionDiff !== 0) {
return productionDiff;
}
}
const inboundDiff = toTimeValue(left.inbound_time) - toTimeValue(right.inbound_time);
if (inboundDiff !== 0) {
return inboundDiff;
}
return toNumber(left.id, 0) - toNumber(right.id, 0);
}
/**
* 生成库存不足提示文本。
*
* @param {Array<Object>} shortageItems 缺货条目。
* @return {string} 提示文本。
*/
function buildShortageMessage(shortageItems = []) {
const parts = shortageItems
.filter(item => item && Number(item.stock_id) > 0)
.map(item => `sku(${item.stock_id}),数量:${item.required_quantity},库位数量:${item.allocated_quantity}`);
return parts.length > 0 ? `库存不足:${parts.join('|')}` : '';
}
/**
* 规范化订单 ID 列表。
*
* @param {Object} data 请求体。
* @return {number[]} 订单 ID 列表。
*/
function normalizeOrderIds(data = {}) {
const requestData = data && typeof data === 'object' ? data : {};
const rawValues = [];
if (Array.isArray(requestData.order_ids)) {
rawValues.push(...requestData.order_ids);
} else if (Array.isArray(requestData.orderIds)) {
rawValues.push(...requestData.orderIds);
} else if (Array.isArray(requestData.ids)) {
rawValues.push(...requestData.ids);
} else if (typeof requestData.order_ids === 'string') {
rawValues.push(...requestData.order_ids.split(','));
} else if (typeof requestData.orderIds === 'string') {
rawValues.push(...requestData.orderIds.split(','));
} else if (typeof requestData.ids === 'string') {
rawValues.push(...requestData.ids.split(','));
} else if (requestData.order_ids !== undefined && requestData.order_ids !== null && requestData.order_ids !== '') {
rawValues.push(requestData.order_ids);
} else if (requestData.orderIds !== undefined && requestData.orderIds !== null && requestData.orderIds !== '') {
rawValues.push(requestData.orderIds);
} else if (requestData.ids !== undefined && requestData.ids !== null && requestData.ids !== '') {
rawValues.push(requestData.ids);
} else if (requestData.order_id !== undefined && requestData.order_id !== null && requestData.order_id !== '') {
rawValues.push(requestData.order_id);
} else if (requestData.orderId !== undefined && requestData.orderId !== null && requestData.orderId !== '') {
rawValues.push(requestData.orderId);
} else if (requestData.id !== undefined && requestData.id !== null && requestData.id !== '') {
rawValues.push(requestData.id);
}
const orderIds = rawValues
.map(value => Number(String(value).trim()))
.filter(value => Number.isFinite(value) && value > 0);
return Array.from(new Set(orderIds));
}
/**
* 订单储位分配公共服务。
* 负责订单、库存、库位的分配编排,并写入 wms_picking。
*/
class OrderStorageAllocationService extends MainService {
/**
* 按订单批量分配储位。
*
* 入参支持以下字段:
* - `allow_storage_location` / `allowStorageLocation` / `is_allow_storage` / `isAllowStorage`
* - `order_ids` / `orderIds` / `ids` / `order_id` / `orderId` / `id`
* - `warehouse_id` / `warehouseId`(可选,默认使用当前上下文仓库)
*
* 分配规则:
* - 先过滤掉已经完成储位分配的订单
* - 允许时优先使用存储储位,再使用分拣储位
* - FIFO 先按生产日期,再按入库时间
* - 库存不足时按订单顺序尽量分配,并将不足订单标记为异常
*
* @param {Object} data 请求体。
* @return {Promise<Object>} 分配结果。
*/
async allocatePicking(data = {}) {
const { ctx, app } = this;
const requestData = this.isPlainObject(data) ? data : {};
const warehouseId = toNumber(requestData.warehouse_id ?? requestData.warehouseId ?? ctx.user?.store_id, 0);
const orderIds = normalizeOrderIds(requestData);
const allowStorageLocation = normalizeBooleanFlag(
requestData.allow_storage_location
?? requestData.allowStorageLocation
?? requestData.is_allow_storage
?? requestData.isAllowStorage
);
if (warehouseId <= 0) {
return {
code: 400,
message: '缺少仓库上下文',
data: null,
};
}
if (orderIds.length === 0) {
return {
code: 400,
message: '订单ID不能为空',
data: null,
};
}
const transaction = await ctx.model.transaction();
const { Op } = app.Sequelize;
const now = new Date();
try {
const orderModel = await ctx.model.OrderDeliveryFactory.getCurrentModel(warehouseId);
const orderItemModel = await ctx.model.OrderItemsFactory.getCurrentModel(warehouseId);
const pickingModel = ctx.model.Picking;
if (!pickingModel || typeof pickingModel.bulkCreate !== 'function') {
throw new Error('wms_picking 模型不可用');
}
const orderRows = await orderModel.findAll({
where: {
id: {
[Op.in]: orderIds,
},
warehouse_id: warehouseId,
},
transaction,
lock: transaction.LOCK.UPDATE,
raw: true,
});
const orderMap = new Map();
for (const orderRow of Array.isArray(orderRows) ? orderRows : []) {
const plainOrder = toPlainRecord(orderRow);
if (!plainOrder || !Number(plainOrder.id)) {
continue;
}
orderMap.set(Number(plainOrder.id), plainOrder);
}
const pendingOrderIds = [];
const skippedOrders = [];
for (const orderId of orderIds) {
const orderRow = orderMap.get(orderId);
if (!orderRow) {
skippedOrders.push({
order_id: orderId,
status: 'skipped',
skipped_reason: 'not_found',
});
continue;
}
if (String(orderRow.storage_status || 'none') === STORAGE_STATUS_FIN) {
skippedOrders.push({
order_id: orderId,
status: 'skipped',
storage_status: orderRow.storage_status,
skipped_reason: 'already_allocated',
});
continue;
}
pendingOrderIds.push(orderId);
}
if (pendingOrderIds.length === 0) {
await transaction.commit();
return {
code: 200,
message: '没有需要分配的订单',
data: {
warehouse_id: warehouseId,
allow_storage_location: allowStorageLocation,
requested_order_ids: orderIds,
pending_order_ids: [],
skipped_orders: skippedOrders,
orders: skippedOrders,
picking_count: 0,
},
};
}
const orderItemRows = await orderItemModel.findAll({
where: {
order_id: {
[Op.in]: pendingOrderIds,
},
},
transaction,
lock: transaction.LOCK.UPDATE,
raw: true,
});
const orderItemsByOrderId = new Map();
const stockIdSet = new Set();
for (const orderItemRow of Array.isArray(orderItemRows) ? orderItemRows : []) {
const plainItem = toPlainRecord(orderItemRow);
if (!plainItem || !Number(plainItem.order_id)) {
continue;
}
const orderId = Number(plainItem.order_id);
const orderItems = orderItemsByOrderId.get(orderId) || [];
orderItems.push(plainItem);
orderItemsByOrderId.set(orderId, orderItems);
const stockId = Number(plainItem.stock_id || 0);
if (stockId > 0) {
stockIdSet.add(stockId);
}
}
const stockIds = Array.from(stockIdSet);
if (stockIds.length > 0) {
await ctx.model.StockWarehouse.findAll({
where: {
id: {
[Op.in]: stockIds,
},
warehouse_id: warehouseId,
is_valid: 'Y',
deleted_at: null,
},
transaction,
lock: transaction.LOCK.UPDATE,
raw: true,
});
}
const storageRows = stockIds.length > 0
? await ctx.model.Storage.findAll({
where: {
warehouse_id: warehouseId,
stock_id: {
[Op.in]: stockIds,
},
is_enabled: 1,
delete_at: null,
available_quantity: {
[Op.gt]: 0,
},
},
include: [
{
model: ctx.model.LocationSpace,
as: 'space',
required: true,
attributes: [ 'id', 'space_code', 'custom_name', 'is_preferred_pick', 'pick_sequence', 'pick_priority' ],
include: [
{
model: ctx.model.LocationType,
as: 'locationType',
required: true,
attributes: [ 'id', 'type_code', 'type_name', 'allow_allocation', 'is_active' ],
where: {
allow_allocation: 1,
is_active: 1,
},
},
],
},
],
transaction,
lock: transaction.LOCK.UPDATE,
order: [[ 'id', 'ASC' ]],
})
: [];
const storageRowsByStockId = new Map();
for (const storageRow of Array.isArray(storageRows) ? storageRows : []) {
const plainStorage = toPlainRecord(storageRow);
if (!plainStorage || !Number(plainStorage.id) || !Number(plainStorage.stock_id)) {
continue;
}
const space = toPlainRecord(plainStorage.space) || {};
const locationType = toPlainRecord(space.locationType) || {};
const normalizedStorage = {
...plainStorage,
quantity: toNumber(plainStorage.quantity, 0),
locked_quantity: toNumber(plainStorage.locked_quantity, 0),
available_quantity: toNumber(plainStorage.available_quantity, 0),
production_date: plainStorage.production_date || null,
inbound_time: plainStorage.inbound_time || null,
space,
locationType,
space_name: String(space.custom_name || space.space_code || '').trim(),
is_preferred_pick: normalizeBooleanFlag(space.is_preferred_pick),
};
const stockId = Number(normalizedStorage.stock_id);
const currentStorageRows = storageRowsByStockId.get(stockId) || [];
currentStorageRows.push(normalizedStorage);
storageRowsByStockId.set(stockId, currentStorageRows);
}
const policyCache = new Map();
const pickingRows = [];
const stockAllocationMap = new Map();
const storageAllocationMap = new Map();
const orderResults = [];
for (const orderId of pendingOrderIds) {
const orderRow = orderMap.get(orderId);
if (!orderRow) {
continue;
}
const orderItems = (orderItemsByOrderId.get(orderId) || [])
.slice()
.sort((left, right) => {
const leftLineNo = toNumber(left.order_line_no, 0);
const rightLineNo = toNumber(right.order_line_no, 0);
if (leftLineNo !== rightLineNo) {
return leftLineNo - rightLineNo;
}
return toNumber(left.id, 0) - toNumber(right.id, 0);
});
const shortageItems = [];
let allocatedQuantityForOrder = 0;
for (const orderItem of orderItems) {
const stockId = toNumber(orderItem.stock_id, 0);
const requiredQuantity = toNumber(orderItem.plan_qty ?? orderItem.planQty ?? orderItem.count ?? 0, 0);
if (stockId <= 0 || requiredQuantity <= 0) {
shortageItems.push({
stock_id: stockId,
required_quantity: requiredQuantity > 0 ? requiredQuantity : 0,
allocated_quantity: 0,
});
continue;
}
const policyEntry = policyCache.has(stockId)
? policyCache.get(stockId)
: await ctx.service.systems.stockStore.getStoreWarehousePolicyConfigByStockId(stockId, transaction);
policyCache.set(stockId, policyEntry);
const storageSeparationEnabled = normalizeBooleanFlag(policyEntry?.policyConfig?.storage_separation, true);
const allowStorageSpace = allowStorageLocation || !storageSeparationEnabled;
const candidateStorageRows = (storageRowsByStockId.get(stockId) || [])
.filter(storageRow => allowStorageSpace || storageRow.is_preferred_pick)
.slice()
.sort((left, right) => compareStorageRows(left, right, allowStorageSpace));
let remainingQuantity = requiredQuantity;
let allocatedQuantityForItem = 0;
for (const storageRow of candidateStorageRows) {
if (remainingQuantity <= 0) {
break;
}
const currentAvailable = toNumber(storageRow.available_quantity, 0);
if (currentAvailable <= 0) {
continue;
}
const allocationQuantity = Math.min(remainingQuantity, currentAvailable);
if (allocationQuantity <= 0) {
continue;
}
await ctx.service.systems.storage.lockQuantity(storageRow.id, allocationQuantity, { transaction });
storageRow.available_quantity = currentAvailable - allocationQuantity;
storageRow.locked_quantity = toNumber(storageRow.locked_quantity, 0) + allocationQuantity;
remainingQuantity -= allocationQuantity;
allocatedQuantityForItem += allocationQuantity;
allocatedQuantityForOrder += allocationQuantity;
storageAllocationMap.set(storageRow.id, (storageAllocationMap.get(storageRow.id) || 0) + allocationQuantity);
stockAllocationMap.set(stockId, (stockAllocationMap.get(stockId) || 0) + allocationQuantity);
pickingRows.push({
order_id: orderId,
order_item_id: toNumber(orderItem.id, 0),
storage_id: storageRow.id,
quantity: allocationQuantity,
space_id: toNumber(storageRow.space_id, 0) || null,
space_name: String(storageRow.space_name || '').trim(),
status: 'pending',
created_at: now,
updated_at: now,
});
}
if (remainingQuantity > 0) {
shortageItems.push({
stock_id: stockId,
required_quantity: requiredQuantity,
allocated_quantity: allocatedQuantityForItem,
});
}
}
const shortageMessage = buildShortageMessage(shortageItems);
const orderUpdateValues = shortageMessage
? {
storage_status: STORAGE_STATUS_ERROR,
step: ORDER_STEP_EXCEPTION,
order_flag: shortageMessage,
updated_at: now,
}
: {
storage_status: STORAGE_STATUS_FIN,
order_flag: '',
updated_at: now,
};
await orderModel.update(orderUpdateValues, {
where: {
id: orderId,
warehouse_id: warehouseId,
},
transaction,
});
orderResults.push({
order_id: orderId,
storage_status: orderUpdateValues.storage_status,
allocated_quantity: allocatedQuantityForOrder,
shortage_message: shortageMessage || '',
status: shortageMessage ? 'error' : 'success',
});
}
for (const [ stockId, quantity ] of stockAllocationMap.entries()) {
if (quantity <= 0) {
continue;
}
const stockRecord = await ctx.model.StockWarehouse.findByPk(stockId, {
transaction,
});
if (!stockRecord) {
throw new Error(`库存主记录不存在: ${stockId}`);
}
await stockRecord.increment('locked_quantity', {
by: quantity,
transaction,
silent: true,
});
await stockRecord.reload({ transaction });
}
if (pickingRows.length > 0) {
await pickingModel.bulkCreate(pickingRows, {
transaction,
});
}
await transaction.commit();
const errorOrderResults = orderResults.filter(item => item.status === 'error');
const successOrderResults = orderResults.filter(item => item.status === 'success');
const shortageMessages = errorOrderResults
.map(item => item.shortage_message)
.filter(Boolean);
return {
code: 200,
message: shortageMessages.length > 0
? '储位分配完成,部分订单库存不足'
: '储位分配完成',
data: {
warehouse_id: warehouseId,
allow_storage_location: allowStorageLocation,
requested_order_ids: orderIds,
pending_order_ids: pendingOrderIds,
allocated_order_ids: successOrderResults.map(item => item.order_id),
shortage_order_ids: errorOrderResults.map(item => item.order_id),
skipped_orders: skippedOrders,
orders: [ ...skippedOrders, ...orderResults ],
picking_count: pickingRows.length,
stock_lock_summary: Array.from(stockAllocationMap.entries()).map(([ stockId, quantity ]) => ({
stock_id: stockId,
locked_quantity: quantity,
})),
storage_lock_summary: Array.from(storageAllocationMap.entries()).map(([ storageId, quantity ]) => ({
storage_id: storageId,
locked_quantity: quantity,
})),
shortage_messages: shortageMessages,
},
};
} catch (error) {
await transaction.rollback();
throw error;
}
}
/**
* 兼容旧调用名称的储位分配入口。
*
* @param {Object} data 请求体。
* @return {Promise<Object>} 分配结果。
*/
async allocateStorage(data = {}) {
return await this.allocatePicking(data);
}
}
module.exports = OrderStorageAllocationService;

View File

@ -1,7 +1,73 @@
// app/service/system/platform.js
const Service = require('egg').Service;
const DEFAULT_PLATFORM_LIST_CACHE_TTL_SECONDS = 600;
class PlatformService extends Service {
getPlatformListCacheKey() {
return 'platform:list';
}
normalizePlatformRow(row) {
if (!row || typeof row !== 'object') {
return null;
}
const code = String(row.code || '').trim();
if (!code) {
return null;
}
const name = String(row.name || '').trim();
const defaultExpressInterface = String(row.default_express_interface || '').trim();
return {
code,
name,
default_express_interface: defaultExpressInterface,
value: code,
label: name || code,
};
}
async loadPlatformListFromDatabase() {
const rows = await this.ctx.model.Platform.findAll({
attributes: [ 'code', 'name', 'default_express_interface' ],
order: [[ 'code', 'ASC' ]],
raw: true,
});
if (!Array.isArray(rows)) {
return [];
}
return rows
.map(row => this.normalizePlatformRow(row))
.filter(Boolean);
}
async getPlatformList() {
const cacheKey = this.getPlatformListCacheKey();
try {
const cachedList = await this.app.getCacheAsync(cacheKey);
if (cachedList !== null && cachedList !== undefined) {
return Array.isArray(cachedList) ? cachedList : [];
}
const platformList = await this.loadPlatformListFromDatabase();
await this.app.setCacheAsync(cacheKey, platformList, DEFAULT_PLATFORM_LIST_CACHE_TTL_SECONDS);
return platformList;
} catch (error) {
this.ctx.logger.error('[PlatformService.getPlatformList] 获取平台列表失败', {
error: error.message,
stack: error.stack,
});
throw error;
}
}
/**
* 检查平台是否存在
* 逻辑:

View File

@ -1,198 +1,173 @@
'use strict';
const Service = require('egg').Service;
const poloApiConfig = require('../../../config/poloapi');
const crypto = require('crypto');
const PoloApiClient = require('../../lib/polo_api_client');
class PoloApiService extends Service {
/**
* @param {object} ctx - Egg 上下文对象。
*/
constructor(ctx) {
super(ctx);
this.configPoloApi = poloApiConfig;
this.client = new PoloApiClient(ctx);
}
// 批量组装订单JSON
getJsonDatas(expressConfig, list) {
const cal = new Date();
const year = cal.getFullYear();
const month = cal.getMonth() + 1;
const day = cal.getDate() + 3;
const day1 = cal.getDate() + 4;
const sb1 = this._formatPickupDate(year, month, day);
const sb2 = this._formatPickupDate(year, month, day1);
/**
* 测试 Polo API 请求并返回请求结果。
*
* @returns {Promise<any>} request() 的返回结果。
*/
async test() {
return this.client.request({
method: 'Differ.JH.LogisticsPlatFeatures',
platid: 556,
bizcontent: {},
});
}
async test2() {
return this.client.request({
method: 'Differ.JH.LogisticsPlatFeatures',
platid: 556,
bizcontent: {},
});
}
/**
* 快手取号。
*
* @param {object} [options={}] - 快手取号入参。
* @param {string} [options.express_id=''] - 快手平台对应的承运商编码。
* @param {object} [options.wmsOrder={}] - WMS 订单信息。
* @param {object} [options.expressConfig={}] - 发件方与店铺配置。
* @returns {Promise<any>} 接口响应 data。
*/
async kuaishou(options = {}) {
const {
express_id = '',
wmsOrder = {},
expressConfig = {},
} = options;
const {
sourceId = '',
sourceOrderCode = '',
postcode = '',
wareHouseId = 0,
storeId = 0,
items = '',
goodsCount = 0,
orderWeight = 0,
address = '',
name = '',
expAreaName = '',
cityName = '',
province = '',
tempMobile = '',
tel = '',
} = wmsOrder;
const {
storeName = '',
address: senderAddress = '',
senderName = '',
districtName = '',
cityName: senderCityName = '',
senderTel = '',
provinceName = '',
siteCode = '',
clientId = '',
} = expressConfig;
const orders = [];
for (const wmsOrder of list) {
let txLogisticID = wmsOrder.sourceId;
txLogisticID = txLogisticID.length < 6 ? txLogisticID.padStart(6, '0') : txLogisticID;
if (wmsOrder.postcode === 'p10') {
if (txLogisticID.length > 19) txLogisticID = txLogisticID.slice(-19);
} else {
if (txLogisticID.length > 28) txLogisticID = txLogisticID.slice(-28);
const platid = 556;
const method = 'Differ.JH.Logistics.PostOrder';
const shoptype = 'JH_001';
const sourceIdText = String(sourceId || '');
const sourceOrderCodeText = String(sourceOrderCode || '');
const [senderArea = '', senderTown = ''] = String(districtName || '').split(';');
const mobile = tempMobile || tel || '';
const cpcode = express_id || '';
const txLogisticID = sourceIdText.replace(/_/g, '');
let cnname = '';
if (!(wareHouseId === 5400 || storeId === 58303)) {
const firstItem = String(items || '').split('|')[0] || '';
const itemFields = firstItem.split(',');
if (itemFields.length > 2) {
cnname = itemFields[2];
}
txLogisticID = txLogisticID.replace(/_/g, '');
// 快递公司代码
const cpcode = this.configPoloApi.postCodeMap[wmsOrder.postcode] || '';
// 商品名
let cnname = '';
const ycflag = !(wmsOrder.wareHouseId === 5400 || wmsOrder.storeId === 58303);
if (ycflag) {
const items = wmsOrder.items || '';
const splitStr = items.split('|');
if (splitStr.length > 0) {
const s = splitStr[0];
const sArr = s.split(',');
if (sArr.length > 2) cnname = sArr[2];
}
} else {
cnname = 'sp';
}
// 收件人手机号
const mobile = wmsOrder.tempMobile || wmsOrder.tel || '';
/*
order对象结构(41-77):
{
businessplat, ismultiplepieces, businesstype, cpcode, customercode, customername,
goods: [goods对象结构(49-56)],
logisticsproductname, logistictype, mainsubpaymode, needencrypt, numpackage,
orderno, ordersource, ordertype, plattradeno, ProviderID, providercode,
receiver: receiver对象结构(59-65), sender: sender对象结构(66-75), shipperno, sitecode, Inputsite, transtype
}
goods对象结构(49-56):
{
cnname, count, unit, currencytype, Unit, weight, price
}
receiver对象结构(59-65):
{
address, name, area, city, mobile, province
}
sender对象结构(66-75):
{
country, Company, address, name, area, town, city, phone, mobile, tel, province
}
*/
// 组装订单对象(下标范围:约第41-77行)
const order = { // [order对象开始 41]
businessplat: 'OTHERS', // 41
ismultiplepieces: '0',
businesstype: 'JH_Normal',
cpcode,
customercode: '',
customername: expressConfig.storeProperty || '测试',
goods: [{ // [goods对象开始 49]
cnname,
count: String(wmsOrder.goodsCount),
unit: '属性',
currencytype: 'CNY',
Unit: '',
weight: String(wmsOrder.orderWeight),
price: '0.0',
}], // [goods对象结束 56]
logisticsproductname: 'JH_02',
logistictype: cpcode,
mainsubpaymode: '1',
needencrypt: '1',
numpackage: '1',
orderno: wmsOrder.sourceOrderCode || (wmsOrder.id && wmsOrder.id.length > 13 ? wmsOrder.id.substring(0, 14) : wmsOrder.id),
ordersource: 'KUAI_SHOU',
ordertype: 'JH_Normal',
plattradeno: wmsOrder.sourceOrderCode || txLogisticID,
ProviderID: wmsOrder.postcode === 'p03' ? 1327 : (wmsOrder.postcode === 'p04' ? 1499 : ''),
providercode: cpcode,
receiver: { // [receiver对象开始 59]
address: wmsOrder.address,
name: wmsOrder.name,
area: wmsOrder.expAreaName,
city: wmsOrder.cityName,
mobile,
province: wmsOrder.province,
}, // [receiver对象结束 65]
sender: { // [sender对象开始 66]
country: 'CN',
Company: expressConfig.storeName,
address: expressConfig.address,
name: expressConfig.senderName,
area: expressConfig.districtName && expressConfig.districtName.indexOf(';') === -1 ? expressConfig.districtName : expressConfig.districtName.split(';')[0],
town: expressConfig.districtName && expressConfig.districtName.indexOf(';') !== -1 ? expressConfig.districtName.split(';')[1] : undefined,
city: expressConfig.cityName,
phone: expressConfig.senderTel,
mobile: expressConfig.senderTel,
tel: expressConfig.senderTel,
province: expressConfig.provinceName,
}, // [sender对象结束 75]
shipperno: [ 'p22', 'p35', 'p10' ].includes(wmsOrder.postcode) ? expressConfig.siteCode : expressConfig.clientId,
sitecode: expressConfig.siteCode || '',
Inputsite: expressConfig.siteCode || '',
transtype: '0',
// 省略部分特殊字段和extraInfo,后续可补充
}; // [order对象结束 77]
// 特殊字段
if (wmsOrder.postcode === 'p10') {
order.pickUpDate = sb1;
order.pickUpEndDate = sb2;
}
orders.push(order);
} else {
cnname = 'sp';
}
const body = JSON.stringify({ orders, shoptype: 'JH_001' });
// 组装url参数
const urlParams = {
method: 'Differ.JH.Logistics.PostOrder',
appkey: this.configPoloApi.appKey,
token: expressConfig.sessionKey,
platid: this.configPoloApi.platid,
version: this.configPoloApi.version,
bizcontent: encodeURIComponent(body),
contenttype: this.configPoloApi.contenttype,
timestamp: encodeURIComponent(this._formatDate(new Date())),
const order = {
businessplat: 'OTHERS',
ismultiplepieces: '0',
businesstype: 'JH_Normal',
cpcode,
customercode: '',
customername: storeName || '测试',
goods: [{
cnname,
count: String(goodsCount),
unit: '属性',
currencytype: 'CNY',
Unit: '',
weight: String(orderWeight),
price: '0.0',
}],
logisticsproductname: 'JH_02',
logistictype: cpcode,
mainsubpaymode: '1',
needencrypt: '1',
numpackage: '1',
orderno: sourceOrderCodeText || (sourceIdText.length > 13 ? sourceIdText.substring(0, 14) : sourceIdText),
ordersource: 'KUAI_SHOU',
ordertype: 'JH_Normal',
plattradeno: sourceOrderCodeText || txLogisticID,
ProviderID: postcode === 'p03' ? 1327 : (postcode === 'p04' ? 1499 : ''),
providercode: cpcode,
receiver: {
address,
name,
area: expAreaName,
city: cityName,
mobile,
province,
},
sender: {
country: 'CN',
Company: storeName,
address: senderAddress,
name: senderName,
area: senderArea,
town: senderTown,
city: senderCityName,
phone: senderTel,
mobile: senderTel,
tel: senderTel,
province: provinceName,
},
shipperno: ['p22', 'p35', 'p10'].includes(postcode) ? siteCode : clientId,
sitecode: siteCode || '',
Inputsite: siteCode || '',
transtype: '0',
};
// 签名
const signMap = { ...urlParams, bizcontent: body, timestamp: this._formatDate(new Date()) };
const signText = this.getSignText(signMap, this.configPoloApi.appSecret);
urlParams.sign = this.md5Encrypt(signText.toLowerCase(), 'utf8');
// 返回请求体和参数
return { body, urlParams };
}
if (postcode === 'p10') {
const pickupDate = new Date();
pickupDate.setDate(pickupDate.getDate() + 3);
const pickupEndDate = new Date();
pickupEndDate.setDate(pickupEndDate.getDate() + 4);
const pad = value => (value < 10 ? `0${value}` : String(value));
order.pickUpDate = `${pickupDate.getFullYear()}-${pad(pickupDate.getMonth() + 1)}-${pad(pickupDate.getDate())} 18:00:00`;
order.pickUpEndDate = `${pickupEndDate.getFullYear()}-${pad(pickupEndDate.getMonth() + 1)}-${pad(pickupEndDate.getDate())} 18:00:00`;
}
// 单个订单JSON(略,结构同上,建议复用 getJsonDatas 逻辑)
getJsonData(expressConfig, wmsOrder) {
// 可根据 type 判断调用 getJsonDatas 或单独组装
return this.getJsonDatas(expressConfig, [ wmsOrder ]);
}
// 生成签名字符串
getSignText(signMap, secret) {
let sb = '' + secret;
Object.keys(signMap).sort().forEach(key => {
sb += key + signMap[key];
return this.client.request({
method,
platid,
bizcontent: {
orders: [order],
shoptype,
},
});
sb += secret;
return sb;
}
// MD5加密
md5Encrypt(text, encoding = 'utf8') {
return crypto.createHash('md5').update(text, encoding).digest('hex');
}
// 工具:格式化日期
_formatDate(date) {
// 仅支持 yyyy-MM-dd HH:mm:ss
const pad = n => (n < 10 ? '0' + n : n);
return date.getFullYear() + '-' + pad(date.getMonth() + 1) + '-' + pad(date.getDate()) + ' '
+ pad(date.getHours()) + ':' + pad(date.getMinutes()) + ':' + pad(date.getSeconds());
}
// 工具:组装取件日期
_formatPickupDate(year, month, day) {
const pad = n => (n < 10 ? '0' + n : n);
return `${year}-${pad(month)}-${pad(day)} 18:00:00`;
}
}

View File

@ -86,11 +86,24 @@ class QimenQueryService extends Service {
const separator = baseUrl.includes('?') ? '&' : '?';
return `${baseUrl}${separator}${queryString}`;
}
async sendRequest(url, requestData) {
/**
* 发送奇门请求并在成功或失败时落库日志。
* @param {string} url 请求地址。
* @param {string} requestData 请求报文。
* @param {Object} [logData={}] 日志基础数据。
* @return {Promise<{queryId: *, res: string}>} 请求结果。
*/
async sendRequest(url, requestData, logData = {}) {
const startTime = Date.now();
const { service } = this;
const logData = {};
logData.body = requestData;
const requestLogData = Object.assign({
body: requestData,
result: '',
log_id: this.ctx.qimenLogId || null,
}, logData);
requestLogData.body = requestLogData.body || requestData;
requestLogData.result = requestLogData.result || '';
requestLogData.log_id = requestLogData.log_id || this.ctx.qimenLogId || null;
let httpquery = null;
if (url.indexOf('https://') > -1) {
httpquery = https;
@ -117,6 +130,8 @@ class QimenQueryService extends Service {
throw new Error('XML内容为空');
}
} catch (error) {
requestLogData.result = error.stack || `${error.name || 'Error'}: ${error.message || String(error)}`;
await service.qimen.saveQimenLog(requestLogData, startTime);
throw error;
}
const header = {
@ -128,26 +143,39 @@ class QimenQueryService extends Service {
method: 'POST',
headers: header,
};
const res = await new Promise((resolve, reject) => {
const req = httpquery.request(url, options, response => {
let datas = '';
response.on('data', chunk => {
datas += chunk;
});
response.on('end', () => {
resolve(datas);
});
});
let res;
try {
res = await new Promise((resolve, reject) => {
let req;
try {
req = httpquery.request(url, options, response => {
let datas = '';
response.on('data', chunk => {
datas += chunk;
});
response.on('end', () => {
resolve(datas);
});
});
} catch (error) {
reject(error);
return;
}
req.on('error', error => {
reject(error);
});
req.on('error', error => {
reject(error);
});
req.write(requestXml);
req.end();
});
logData.result = res;
const queryId = await service.qimen.saveQimenLog(logData, startTime);
req.write(requestXml);
req.end();
});
} catch (error) {
requestLogData.result = error.stack || `${error.name || 'Error'}: ${error.message || String(error)}`;
await service.qimen.saveQimenLog(requestLogData, startTime);
throw error;
}
requestLogData.result = res;
const queryId = await service.qimen.saveQimenLog(requestLogData, startTime);
return { queryId, res };
}
}

View File

@ -2181,6 +2181,20 @@ class stockStoreService extends Service {
}
}
/**
* 获取仓库商品详情。
*
* @param {object} data - 查询参数。
* @param {number|string} data.id - 商品 ID。
* @return {Promise<object|null>} 商品详情。
*/
/**
* 查询库存商品详情。
*
* @param {Object} data 请求参数。
* @param {number|string} data.id 库存商品 ID。
* @return {Promise<Object|null>} 库存商品详情。
*/
async getInfo(data) {
const {
ctx,
@ -2223,6 +2237,10 @@ class stockStoreService extends Service {
'box_width',
'box_height',
'box_volume',
'inbound_min_days',
'outbound_min_days',
'remaining_threshold_days',
'shelf_life_days',
'store_id',
],
raw: true,
@ -2230,6 +2248,12 @@ class stockStoreService extends Service {
stock.enable_box_spec = !!stock.enable_box_spec;
return stock;
}
/**
* 更新仓库商品资料,并在启用保质期管理时校验保质期相关字段。
*
* @param {Object} data 请求体,包含商品主键及待更新字段。
* @return {Promise<Object>} 返回更新后的商品详情。
*/
async saveWarehouseStock(data) {
const { ctx, service } = this;
const warehouseId = ctx.user.store_id;
@ -2242,11 +2266,25 @@ class stockStoreService extends Service {
enable_box_spec, box_unit, quantity_per_box,
box_gross_weight, box_net_weight, box_length,
box_width, box_height, box_volume, box_remark, id,
shelf_life_days, inbound_min_days, outbound_min_days, remaining_threshold_days,
} = data;
const prohibited_id_tmp = !prohibited_id ? null : parseInt(prohibited_id);
// 1. 参数验证
this.validateSaveParams(data);
if (is_shelf_life_mgmt === 'Y') {
const shelfLifeFields = [
[ 'shelf_life_days', shelf_life_days ],
[ 'inbound_min_days', inbound_min_days ],
[ 'outbound_min_days', outbound_min_days ],
[ 'remaining_threshold_days', remaining_threshold_days ],
];
const invalidShelfLifeFields = shelfLifeFields.filter(item => Number(item[1]) <= 0);
if (invalidShelfLifeFields.length > 0) {
throw new Error('启用保质期管理时,shelf_life_days、inbound_min_days、outbound_min_days、remaining_threshold_days 都必须存在且大于 0');
}
}
let transaction;
try {
// 2. 开启事务
@ -2265,7 +2303,6 @@ class stockStoreService extends Service {
if (!stock_info) {
throw new Error('商品不存在');
}
// 4. 准备更新数据
const updateData = {
item_code,
@ -2297,6 +2334,10 @@ class stockStoreService extends Service {
box_height,
box_volume,
box_remark,
shelf_life_days,
inbound_min_days,
outbound_min_days,
remaining_threshold_days,
updated_at: new Date(),
};
// 5. 清除空值
@ -2715,6 +2756,15 @@ class stockStoreService extends Service {
});
return { message: '删除成功', code: 200 };
}
/**
* 快捷搜索仓库商品并补全库存管理标记。
* @param {Object} data 请求体
* @param {string} [data.keyword] 搜索关键字
* @param {number|string} [data.store_id] 货主ID
* @param {boolean} [data.with_stock=false] 是否返回关联库存数据
* @param {boolean} [data.is_batch=false] with_stock=true 时是否按批次返回
* @return {Promise<Object>} 搜索结果,data 为商品数组
*/
async search(data) {
const { keyword, store_id = null, with_stock = false, is_batch = false } = data;
const { ctx, app } = this;
@ -2789,6 +2839,10 @@ class stockStoreService extends Service {
'id', 'item_code', 'goods_code', 'item_name',
'sku_property', 'stock_unit', 'quantity',
'locked_quantity', 'brand_name', 'item_type',
'inbound_min_days', 'outbound_min_days',
'shelf_life_days', 'remaining_threshold_days',
'is_batch_mgmt',
'is_shelf_life_mgmt',
],
order: [[ 'create_at', 'DESC' ]],
limit: 50,
@ -2802,6 +2856,16 @@ class stockStoreService extends Service {
// 提取所有条形码
result.barcodes = result.barcodes?.map(b => b.barcode) || [];
const batchMgmtValue = result.is_batch_mgmt;
result.is_batch_mgmt_enabled = typeof batchMgmtValue === 'boolean'
? batchMgmtValue
: [ 'Y', '1', 'TRUE', 'T', 'YES' ].includes(String(batchMgmtValue).trim().toUpperCase());
delete result.is_batch_mgmt;
const shelfLifeMgmtValue = result.is_shelf_life_mgmt;
result.is_shelf_life_mgmt = typeof shelfLifeMgmtValue === 'boolean'
? shelfLifeMgmtValue
: [ 'Y', '1', 'TRUE', 'T', 'YES' ].includes(String(shelfLifeMgmtValue).trim().toUpperCase());
return result;
});

View File

@ -0,0 +1,199 @@
'use strict';
const Service = require('egg').Service;
const { parseWhereConditions } = require('../../../lib/query_condition_parser');
const DAY_MS = 24 * 60 * 60 * 1000;
/**
* 库存有效期列表服务。
* 以库存记录为主表,关联商品资料后按当前仓库与效期阈值规则分页查询。
*/
class StorageExpiryService extends Service {
/**
* 查询库存有效期预警列表。
*
* @param {Object} [where={}] 查询条件
* @param {Object} [pageParams={}] 分页参数
* @param {number} [pageParams.page=1] 当前页码
* @param {number} [pageParams.pageSize=20] 每页条数
* @return {Promise<Object>} 查询结果
*/
async list(where = {}, pageParams = {}) {
const { ctx, app } = this;
const warehouseId = Number(ctx.user && ctx.user.store_id) || 0;
if (!warehouseId) {
return {
code: 400,
message: '当前用户未绑定仓库',
data: {
list: [],
pagination: {
page: 1,
pageSize: 20,
total: 0,
totalPages: 0,
hasPrevious: false,
hasNext: false,
},
},
};
}
const page = Math.max(Number(pageParams.page) || 1, 1);
const pageSize = Math.max(Number(pageParams.pageSize) || 20, 1);
const offset = (page - 1) * pageSize;
const { Op, literal } = app.Sequelize;
const specialFieldMap = {
item_code: {
bucket: 'stock',
},
goods_code: {
bucket: 'stock',
},
item_name: {
bucket: 'stock',
},
sku_property: {
bucket: 'stock',
},
stock_unit: {
bucket: 'stock',
},
is_shelf_life_mgmt: {
bucket: 'stock',
field: 'is_shelf_life_mgmt',
},
remaining_threshold_days: {
bucket: 'stock',
},
};
const parsed = ctx.whereParsed && Array.isArray(ctx.whereParsed.dynamicConditions)
? ctx.whereParsed
: parseWhereConditions({
where,
app,
specialFieldMap,
}).result;
const dynamicConditions = Array.isArray(parsed.dynamicConditions)
? parsed.dynamicConditions
: [];
const stockConditions = Array.isArray(parsed.bucketConditions && parsed.bucketConditions.stock)
? parsed.bucketConditions.stock
: [];
const storageWhere = {
[Op.and]: [
{ warehouse_id: warehouseId },
{ is_enabled: 1 },
{ delete_at: null },
{ quantity: { [Op.gt]: 0 } },
{ expiry_date: { [Op.ne]: null } },
literal('DATEDIFF(`wms_storage`.`expiry_date`, CURDATE()) <= `stock`.`remaining_threshold_days`'),
],
};
if (dynamicConditions.length > 0) {
storageWhere[Op.and].push({ [Op.and]: dynamicConditions });
}
const stockWhere = {
[Op.and]: [
{ is_valid: 'Y' },
{ delete_at: null },
{ warehouse_id: warehouseId },
{ is_shelf_life_mgmt: 'Y' },
{ remaining_threshold_days: { [Op.gt]: 0 } },
],
};
if (stockConditions.length > 0) {
stockWhere[Op.and].push({ [Op.and]: stockConditions });
}
const { count, rows } = await ctx.model.Storage.findAndCountAll({
where: storageWhere,
include: [
{
model: ctx.model.StockWarehouse,
as: 'stock',
required: true,
attributes: [
'id',
'item_code',
'goods_code',
'item_name',
'sku_property',
'stock_unit',
'store_id',
'warehouse_id',
'is_shelf_life_mgmt',
'remaining_threshold_days',
],
where: stockWhere,
},
{
model: ctx.model.LocationSpace,
as: 'space',
required: false,
attributes: [ 'id', 'space_code', 'custom_name' ],
},
],
order: [
[ 'expiry_date', 'ASC' ],
[ 'inbound_time', 'ASC' ],
[ 'id', 'ASC' ],
],
offset,
limit: pageSize,
distinct: true,
subQuery: false,
});
const now = Date.now();
const list = rows.map(row => {
const plain = row.get({ plain: true });
const expiryTime = plain.expiry_date ? new Date(plain.expiry_date).getTime() : null;
const thresholdDays = Number(plain.stock && plain.stock.remaining_threshold_days) || 0;
const remainingDays = expiryTime === null || Number.isNaN(expiryTime)
? null
: Math.max(0, Math.ceil((expiryTime - now) / DAY_MS));
return {
...plain,
threshold_days: thresholdDays,
remaining_days: remainingDays,
is_expired: expiryTime !== null && !Number.isNaN(expiryTime) ? expiryTime < now : false,
created_at: plain.created_at ? app.formatDate(plain.created_at) : null,
updated_at: plain.updated_at ? app.formatDate(plain.updated_at) : null,
inbound_time: plain.inbound_time ? app.formatDate(plain.inbound_time) : null,
production_date: plain.production_date ? app.formatDate(plain.production_date) : null,
expiry_date: plain.expiry_date ? app.formatDate(plain.expiry_date) : null,
};
});
const totalPages = pageSize > 0 ? Math.ceil(count / pageSize) : 0;
return {
code: 200,
message: '查询成功',
data: {
list,
pagination: {
page,
pageSize,
total: count,
totalPages,
hasPrevious: page > 1,
hasNext: page < totalPages,
},
},
};
}
}
module.exports = StorageExpiryService;

View File

@ -1,6 +1,204 @@
'use strict';
const Service = require('egg').Service;
const DAY_MS = 24 * 60 * 60 * 1000;
/**
* 计算库存批次的保质期预警状态。
*
* @param {Object} stock 商品库存资料
* @param {string|Date|null} expiryDate 批次到期日期
* @param {number} [nowMs=Date.now()] 当前时间戳
* @return {{remainingDays: (number|null), isTriggered: boolean}} 预警信息
*/
function getShelfLifeWarningState(stock = {}, expiryDate = null, nowMs = Date.now()) {
const expiryTime = expiryDate ? new Date(expiryDate).getTime() : null;
const remainingDays = expiryTime === null || Number.isNaN(expiryTime)
? null
: Math.max(0, Math.ceil((expiryTime - nowMs) / DAY_MS));
const isShelfLifeMgmt = stock.is_shelf_life_mgmt === 'Y' || stock.is_shelf_life_mgmt === true;
const thresholdDays = Number(stock.remaining_threshold_days) || 0;
return {
remainingDays,
isTriggered: Boolean(isShelfLifeMgmt && thresholdDays > 0 && remainingDays !== null && remainingDays <= thresholdDays),
};
}
/**
* 将库存商品上的标记值规范化为布尔值。
*
* @param {unknown} value 待转换的标记值
* @return {boolean} 是否为真值
*/
function toBooleanFlag(value) {
if (typeof value === 'boolean') {
return value;
}
if (typeof value === 'number') {
return value === 1;
}
if (typeof value === 'string') {
return [ 'Y', '1', 'TRUE', 'T', 'YES' ].includes(value.trim().toUpperCase());
}
return false;
}
/**
* 将模型查询结果转换为普通对象。
*
* @param {unknown} record 模型记录或普通对象
* @return {Object|null} 普通对象
*/
function toPlainRecord(record) {
if (!record) {
return null;
}
if (typeof record.get === 'function') {
return record.get({ plain: true });
}
return record;
}
/**
* 批量加载库存商品的条码与图片附属信息。
*
* @param {Object} ctx 当前请求上下文
* @param {number[]} stockIds 商品ID列表
* @return {Promise<{barcodesByStockId: Map<number, string[]>, imagesByStockId: Map<number, string[]>}>} 附属信息映射
*/
async function loadStockAttachments(ctx, stockIds = []) {
const uniqueStockIds = [ ...new Set(
Array.isArray(stockIds)
? stockIds.map(item => Number(item)).filter(Boolean)
: []
) ];
const barcodesByStockId = new Map();
const imagesByStockId = new Map();
if (!uniqueStockIds.length) {
return { barcodesByStockId, imagesByStockId };
}
const hasStockBarcodeModel = ctx.model && ctx.model.StockBarcode && typeof ctx.model.StockBarcode.findAll === 'function';
if (hasStockBarcodeModel) {
try {
const barcodeRows = await ctx.model.StockBarcode.findAll({
where: {
stock_id: {
[ctx.app.Sequelize.Op.in]: uniqueStockIds,
},
},
attributes: [ 'stock_id', 'barcode' ],
raw: true,
});
for (const item of barcodeRows || []) {
const row = toPlainRecord(item);
if (!row) {
continue;
}
const stockId = Number(row.stock_id);
const barcode = row.barcode ? String(row.barcode) : '';
if (!stockId || !barcode) {
continue;
}
if (!barcodesByStockId.has(stockId)) {
barcodesByStockId.set(stockId, []);
}
barcodesByStockId.get(stockId).push(barcode);
}
} catch (error) {
ctx.logger?.warn?.('[storage.inventory] 查询商品条码失败,已降级为空数组', {
error: error.message,
});
}
}
const hasFileReferenceModel = ctx.model && ctx.model.FileReference && typeof ctx.model.FileReference.findAll === 'function';
const hasFileModel = Boolean(ctx.model && ctx.model.File);
if (hasFileReferenceModel && hasFileModel) {
try {
const imageRows = await ctx.model.FileReference.findAll({
where: {
business_type: 'stock',
business_id: {
[ctx.app.Sequelize.Op.in]: uniqueStockIds,
},
},
include: [{
model: ctx.model.File,
as: 'file',
attributes: [ 'file_url' ],
required: false,
}],
});
for (const item of imageRows || []) {
const row = toPlainRecord(item);
if (!row) {
continue;
}
const stockId = Number(row.business_id);
const imageUrl = (row.file && row.file.file_url) || row.file_url || row.url || row.file_path || '';
if (!stockId || !imageUrl) {
continue;
}
if (!imagesByStockId.has(stockId)) {
imagesByStockId.set(stockId, []);
}
imagesByStockId.get(stockId).push(String(imageUrl));
}
} catch (error) {
ctx.logger?.warn?.('[storage.inventory] 查询商品图片失败,已降级为空数组', {
error: error.message,
});
}
}
return {
barcodesByStockId,
imagesByStockId,
};
}
/**
* 为库存列表补充商品附属信息。
*
* @param {Object} ctx 当前请求上下文
* @param {Object[]} list 库存列表
* @return {Promise<void>}
*/
async function enrichInventoryStockAttachments(ctx, list = []) {
const stockIds = list.map(item => Number(item?.stock?.id || item?.stock_id || 0)).filter(Boolean);
const { barcodesByStockId, imagesByStockId } = await loadStockAttachments(ctx, stockIds);
for (const item of list) {
const stockId = Number(item?.stock?.id || item?.stock_id || 0);
if (!stockId) {
continue;
}
if (!item.stock) {
item.stock = {};
}
item.stock.barcodes = barcodesByStockId.get(stockId) || [];
item.stock.images = imagesByStockId.get(stockId) || [];
}
}
class InventoryService extends Service {
@ -169,7 +367,9 @@ class InventoryService extends Service {
// 5c. 写入/更新 wms_storage 库存位置表
const spaceId = detail.space_id || 1; // 明细有库位则用,否则默认库位
const batchNo = detail.batch_number || receiving.receiving_number || entryOrderCode;
const batchNo = String(detail.batch_number || '').trim() || String(receiving.receiving_number || '').trim() || entryOrderCode;
const productionDate = detail.production_date || null;
const expiryDate = detail.expiry_date || null;
const inventoryType = 'ZP'; // 默认正品
// 查找是否已有相同 库位+SKU+批次+类型 的库存记录
@ -192,6 +392,10 @@ class InventoryService extends Service {
quantity: app.Sequelize.literal(`quantity + ${inboundQty}`),
available_quantity: app.Sequelize.literal(`available_quantity + ${inboundQty}`),
entry_order_id: entryOrder.id,
batch_no: batchNo,
production_date: productionDate,
expiry_date: expiryDate,
updated_at: new Date(),
}, {
where: { id: storageRecord.id },
transaction,
@ -208,8 +412,8 @@ class InventoryService extends Service {
quantity: inboundQty,
locked_quantity: 0,
available_quantity: inboundQty,
production_date: detail.production_date || null,
expiry_date: detail.expiry_date || null,
production_date: productionDate,
expiry_date: expiryDate,
inbound_time: new Date(),
inbound_order_no: entryOrderCode,
receiving_id: receivingId,
@ -1730,14 +1934,24 @@ class InventoryService extends Service {
}
/**
* 库存列表查询。
* @param {Object} pageParams 分页参数
* @param {Object} sortParams 排序参数
* @param {boolean} groupByBatch 是否按批次
* 查询库存列表。
*
* 支持按批次明细或合并模式返回库存,并补充商品条码、图片附件、保质期预警和货主名称。
* 货主名称来源于货主签约表的 store_remask 字段,最终以 stock.store_name 输出。
*
* @param {Object} [pageParams={}] 分页参数
* @param {number} [pageParams.page=1] 页码
* @param {number} [pageParams.pageSize=20] 每页数量
* @param {Object} [sortParams={}] 排序参数
* @param {string} [sortParams.sortField='created_at'] 排序字段
* @param {string} [sortParams.sortOrder='DESC'] 排序方向
* @param {boolean} [groupByBatch=false] 是否按批次明细返回
* @return {Promise<{list: Object[], pagination: {page: number, pageSize: number, total: number, totalPages: number}}>} 库存列表结果
*/
async getInventoryList(pageParams = {}, sortParams = {}, groupByBatch = false) {
const { ctx, app } = this;
const { Op, fn, col, literal } = app.Sequelize;
const nowMs = Date.now();
const warehouseId = ctx.user.store_id;
const { page = 1, pageSize = 20 } = pageParams;
@ -1772,7 +1986,24 @@ class InventoryService extends Service {
{
model: ctx.model.StockWarehouse,
as: 'stock',
attributes: [ 'id', 'item_code', 'item_name', 'sku_property', 'stock_unit' ],
attributes: [
'id',
'item_code',
'item_name',
'sku_property',
'stock_unit',
'is_batch_mgmt',
'is_shelf_life_mgmt',
'remaining_threshold_days',
],
include: [
{
model: ctx.model.StoreWarehouse,
as: 'store_stock',
attributes: [ 'store_id', 'store_remask' ],
required: false,
},
],
required: false,
},
{
@ -1786,14 +2017,24 @@ class InventoryService extends Service {
const list = rows.map(item => {
const row = item.get({ plain: true });
const shelfLifeWarningState = getShelfLifeWarningState(row.stock || {}, row.expiry_date, nowMs);
if (row.stock) {
row.stock.is_batch_mgmt_enabled = toBooleanFlag(row.stock.is_batch_mgmt);
row.stock.store_name = row.stock.store_stock?.store_remask || null;
delete row.stock.store_stock;
delete row.stock.is_batch_mgmt;
}
row.created_at = row.created_at ? app.formatDate(row.created_at) : '';
row.updated_at = row.updated_at ? app.formatDate(row.updated_at) : '';
row.inbound_time = row.inbound_time ? app.formatDate(row.inbound_time) : '';
row.production_date = row.production_date ? app.formatDate(row.production_date) : '';
row.expiry_date = row.expiry_date ? app.formatDate(row.expiry_date) : '';
row.is_shelf_life_warning_triggered = shelfLifeWarningState.isTriggered;
return row;
});
await enrichInventoryStockAttachments(ctx, list);
return {
list,
pagination: {
@ -1822,6 +2063,8 @@ class InventoryService extends Service {
'inventory_type',
'warehouse_id',
'store_id',
[ fn('MIN', col('wms_storage.production_date')), 'production_date' ],
[ fn('MIN', col('wms_storage.expiry_date')), 'expiry_date' ],
[ fn('SUM', col('wms_storage.quantity')), 'quantity' ],
[ fn('SUM', col('wms_storage.locked_quantity')), 'locked_quantity' ],
[ fn('SUM', col('wms_storage.available_quantity')), 'available_quantity' ],
@ -1837,7 +2080,24 @@ class InventoryService extends Service {
{
model: ctx.model.StockWarehouse,
as: 'stock',
attributes: [ 'id', 'item_code', 'item_name', 'sku_property', 'stock_unit' ],
attributes: [
'id',
'item_code',
'item_name',
'sku_property',
'stock_unit',
'is_batch_mgmt',
'is_shelf_life_mgmt',
'remaining_threshold_days',
],
include: [
{
model: ctx.model.StoreWarehouse,
as: 'store_stock',
attributes: [ 'store_id', 'store_remask' ],
required: false,
},
],
required: false,
},
{
@ -1852,11 +2112,23 @@ class InventoryService extends Service {
});
const list = rows.map(row => {
const shelfLifeWarningState = getShelfLifeWarningState(row.stock || {}, row.expiry_date, nowMs);
if (row.stock) {
row.stock.is_batch_mgmt_enabled = toBooleanFlag(row.stock.is_batch_mgmt);
row.stock.store_name = row.stock.store_stock?.store_remask || null;
delete row.stock.store_stock;
delete row.stock.is_batch_mgmt;
}
row.first_inbound_time = row.first_inbound_time ? app.formatDate(row.first_inbound_time) : '';
row.last_inbound_time = row.last_inbound_time ? app.formatDate(row.last_inbound_time) : '';
row.production_date = row.production_date ? app.formatDate(row.production_date) : '';
row.expiry_date = row.expiry_date ? app.formatDate(row.expiry_date) : '';
row.is_shelf_life_warning_triggered = shelfLifeWarningState.isTriggered;
return row;
});
await enrichInventoryStockAttachments(ctx, list);
return {
list,
pagination: {

View File

@ -2,6 +2,15 @@
const Service = require('egg').Service;
const { parseWhereConditions } = require('../../../lib/query_condition_parser');
const DAY_MS = 24 * 60 * 60 * 1000;
function getStartOfDayMs(value) {
const date = new Date(value);
if (Number.isNaN(date.getTime())) return null;
date.setHours(0, 0, 0, 0);
return date.getTime();
}
class ReceivingService extends Service {
/**
* 查询收货单列表。
@ -2763,6 +2772,21 @@ class ReceivingService extends Service {
'box_quantity', 'pallet_quantity', 'receiving_status', 'storage_status',
'batch_number', 'production_date', 'expiry_date', 'remark',
],
include: [{
model: ctx.model.StockWarehouse,
as: 'system_product',
required: false,
attributes: [
'id',
'item_name',
'item_code',
'is_batch_mgmt',
'is_shelf_life_mgmt',
'inbound_min_days',
'shelf_life_days',
'remaining_threshold_days',
],
}],
}],
});
@ -2821,6 +2845,80 @@ class ReceivingService extends Service {
};
}
const batchManagedDetails = receiving.details.filter(detail => detail.system_product && detail.system_product.is_batch_mgmt === 'Y');
const missingBatchNumberDetails = batchManagedDetails.filter(detail => !String(detail.batch_number || '').trim());
if (missingBatchNumberDetails.length > 0) {
await transaction.rollback();
return {
success: false,
code: 'BATCH_NUMBER_REQUIRED',
message: '批次管理商品必须填写批次号',
data: {
invalid_details: missingBatchNumberDetails.map(detail => ({
detail_id: detail.id,
item_name: detail.product_name || detail.system_product?.item_name || '未命名商品',
batch_number: detail.batch_number || '',
production_date: detail.production_date || null,
expiry_date: detail.expiry_date || null,
})),
},
};
}
const missingBatchDetails = batchManagedDetails.filter(detail => !detail.production_date || !detail.expiry_date);
if (missingBatchDetails.length > 0) {
await transaction.rollback();
return {
success: false,
code: 'PRODUCTION_DATE_REQUIRED',
message: '批次管理商品必须填写生产日期和有效期',
data: {
invalid_details: missingBatchDetails.map(detail => ({
detail_id: detail.id,
item_name: detail.product_name || detail.system_product?.item_name || '未命名商品',
batch_number: detail.batch_number || '',
production_date: detail.production_date || null,
expiry_date: detail.expiry_date || null,
})),
},
};
}
const todayStartMs = getStartOfDayMs(new Date());
const invalidExpiryDetails = batchManagedDetails.filter(detail => {
const minReceiveDays = Number(detail.system_product?.inbound_min_days) || 0;
if (minReceiveDays <= 0) return false;
const expiryTime = new Date(detail.expiry_date).getTime();
if (Number.isNaN(expiryTime)) return false;
return (expiryTime - (minReceiveDays * DAY_MS)) < todayStartMs;
});
if (invalidExpiryDetails.length > 0) {
await transaction.rollback();
const firstInvalid = invalidExpiryDetails[0];
const minReceiveDays = Number(firstInvalid.system_product?.inbound_min_days) || 0;
return {
success: false,
code: 'EXPIRY_DATE_TOO_SOON',
message: `商品“${firstInvalid.product_name || firstInvalid.system_product?.item_name || '未命名商品'}”的有效期不足最小允许收货天数(${minReceiveDays}天),无法完成收货`,
data: {
invalid_details: invalidExpiryDetails.map(detail => ({
detail_id: detail.id,
item_name: detail.product_name || detail.system_product?.item_name || '未命名商品',
batch_number: detail.batch_number || '',
production_date: detail.production_date || null,
expiry_date: detail.expiry_date || null,
inbound_min_days: Number(detail.system_product?.inbound_min_days) || 0,
})),
},
};
}
// 5. 准备明细图片与统计信息(照片/条码/重量不再强制要求)
const unmatchedDetails = receiving.details.filter(d => !d.system_product_id);
const detailsIds = receiving.details.map(item => item.id);

View File

@ -10,6 +10,8 @@ class StoreService extends Service {
return {
max_notice_webhook_count: 5,
default_express_code: 'STO',
default_platform_code: 'TB',
};
}

View File

@ -257,6 +257,19 @@ class SettingStoreWarehouseService extends Service {
return storeWarehouseModel.getPolicyConfigFieldList();
}
/**
* 获取带动态选项的策略配置字段清单。
*
* @return {Promise<Array>} 策略配置字段数组。
*/
async getPolicyConfigFieldMetaList() {
const storeWarehouseModel = this.ctx.model && this.ctx.model.StoreWarehouse;
if (!storeWarehouseModel || typeof storeWarehouseModel.getPolicyConfigFieldListWithOptions !== 'function') {
return this.getPolicyConfigFieldList();
}
return storeWarehouseModel.getPolicyConfigFieldListWithOptions();
}
/**
* 规范化策略配置内容。
*
@ -1711,7 +1724,7 @@ class SettingStoreWarehouseService extends Service {
async getPolicyConfigFields() {
return {
code: 200,
data: this.getPolicyConfigFieldList(),
data: await this.getPolicyConfigFieldMetaList(),
};
}

View File

@ -15,8 +15,10 @@ module.exports = {
package: 'egg-jwt',
},
sequelize: {
// disable real database connection during unit tests
enable: process.env.NODE_ENV !== 'test',
// disable real database connection during unit tests unless opt-in (see order_delivery_dispatch_factory.test.js)
enable:
process.env.NODE_ENV !== 'test' ||
process.env.DISPATCH_FACTORY_TEST_MYSQL === '1',
package: 'egg-sequelize',
},
cors: {

View File

@ -1,29 +0,0 @@
// config/poloapi.js
// 快手/PolyAPI相关固定配置
module.exports = {
appKey: '8e770a60b9684c558f40e4796a96710f',
appSecret: 'c9cb1df531b441a8872c60ffb7f900a6',
platid: '633',
version: '1.5',
contenttype: 'json',
urls: 'https://api.polyapi.com/openapi/do',
// 快递公司代码映射
postCodeMap: {
p01: 'YTO',
p02: 'STO',
p03: 'YUNDA',
p04: 'ZTO',
p05: 'SF',
p06: 'TTKDEX',
p07: 'EMS',
p10: 'JD',
p22: 'POSTB',
p35: 'POST_DSBK',
p09: 'huitongkuaidi',
p26: 'debangwuliu',
p32: 'JT',
p34: 'FENGWANG',
},
// 如有更多固定配置,可继续补充
};

View File

@ -5,7 +5,7 @@ module.exports = {
* 为发货单主表及分表新增 audit_status 字段。
* 若存在 inspection_status,则将 audit_status 放在其后;否则按默认位置新增,保证兼容旧库结构。
* @param {import('sequelize').QueryInterface} queryInterface Sequelize 查询接口
* @returns {Promise<void>} 无返回值
* @return {Promise<void>} 无返回值
*/
async up(queryInterface) {
const [ tables ] = await queryInterface.sequelize.query(`
@ -54,7 +54,7 @@ module.exports = {
* 回滚删除发货单主表及分表的 audit_status 字段。
* 仅在字段存在时删除,保证回滚幂等且安全。
* @param {import('sequelize').QueryInterface} queryInterface Sequelize 查询接口
* @returns {Promise<void>} 无返回值
* @return {Promise<void>} 无返回值
*/
async down(queryInterface) {
const [ tables ] = await queryInterface.sequelize.query(`
@ -85,4 +85,4 @@ module.exports = {
}
}
},
};
};

View File

@ -48,7 +48,7 @@ module.exports = {
* 为发货单主表及分表新增 step 字段,并从 audit_status 回填后删除 audit_status。
*
* @param {import('sequelize').QueryInterface} queryInterface Sequelize 查询接口。
* @returns {Promise<void>} 无返回值。
* @return {Promise<void>} 无返回值。
*/
async up(queryInterface) {
const tables = await findOrderDeliveryTables(queryInterface);
@ -86,7 +86,7 @@ module.exports = {
* 回滚恢复 audit_status 字段,并根据 step 回填后删除 step。
*
* @param {import('sequelize').QueryInterface} queryInterface Sequelize 查询接口。
* @returns {Promise<void>} 无返回值。
* @return {Promise<void>} 无返回值。
*/
async down(queryInterface) {
const tables = await findOrderDeliveryTables(queryInterface);

View File

@ -79,10 +79,10 @@ const STATUS_MACHINE_COLUMNS = [
];
/**
* @param {import('sequelize').QueryInterface} queryInterface
* @param {string} tableName
* @param {string} columnName
* @return {Promise<boolean>}
* @param {import('sequelize').QueryInterface} queryInterface Sequelize 查询接口。
* @param {string} tableName 数据表名。
* @param {string} columnName 字段名。
* @return {Promise<boolean>} 是否存在指定字段。
*/
async function hasColumn(queryInterface, tableName, columnName) {
const [ columns ] = await queryInterface.sequelize.query(
@ -99,9 +99,9 @@ async function hasColumn(queryInterface, tableName, columnName) {
}
/**
* @param {import('sequelize').QueryInterface} queryInterface
* @param {string} tableName
* @return {Promise<boolean>}
* @param {import('sequelize').QueryInterface} queryInterface Sequelize 查询接口。
* @param {string} tableName 数据表名。
* @return {Promise<boolean>} 数据表是否存在。
*/
async function tableExists(queryInterface, tableName) {
const [ rows ] = await queryInterface.sequelize.query(
@ -117,10 +117,10 @@ async function tableExists(queryInterface, tableName) {
}
/**
* @param {import('sequelize').QueryInterface} queryInterface
* @param {string} tableName
* @param {string} preferredAfter
* @return {Promise<string|null>}
* @param {import('sequelize').QueryInterface} queryInterface Sequelize 查询接口。
* @param {string} tableName 数据表名。
* @param {string} preferredAfter 优先追加到其后的字段名。
* @return {Promise<string|null>} 可直接拼接到 SQL 中的 AFTER 片段,或空字符串。
*/
async function resolveAfterClause(queryInterface, tableName, preferredAfter) {
if (preferredAfter && (await hasColumn(queryInterface, tableName, preferredAfter))) {
@ -133,8 +133,8 @@ module.exports = {
/**
* 仅为基表 `wms_order_delivery` 按需补状态机相关列;已存在则跳过。
*
* @param {import('sequelize').QueryInterface} queryInterface
* @returns {Promise<void>}
* @param {import('sequelize').QueryInterface} queryInterface Sequelize 查询接口。
* @return {Promise<void>} 无返回值。
*/
async up(queryInterface) {
if (!(await tableExists(queryInterface, TABLE))) {
@ -155,8 +155,8 @@ module.exports = {
/**
* 逆序删除本文件声明的状态机列(若存在)。见文件头注释。
*
* @param {import('sequelize').QueryInterface} queryInterface
* @returns {Promise<void>}
* @param {import('sequelize').QueryInterface} queryInterface Sequelize 查询接口。
* @return {Promise<void>} 无返回值。
*/
async down(queryInterface) {
if (!(await tableExists(queryInterface, TABLE))) {

View File

@ -0,0 +1,32 @@
'use strict';
module.exports = {
async up(queryInterface) {
const [ columns ] = await queryInterface.sequelize.query("SHOW COLUMNS FROM `wms_store` LIKE 'subject_config'");
if (columns.length === 0) {
return;
}
await queryInterface.sequelize.query(`
UPDATE wms_store
SET subject_config = JSON_INSERT(
COALESCE(subject_config, JSON_OBJECT()),
'$.default_express_code', 'STO',
'$.default_platform_code', 'TB'
)
`);
},
async down(queryInterface) {
const [ columns ] = await queryInterface.sequelize.query("SHOW COLUMNS FROM `wms_store` LIKE 'subject_config'");
if (columns.length === 0) {
return;
}
await queryInterface.sequelize.query(`
UPDATE wms_store
SET subject_config = JSON_REMOVE(subject_config, '$.default_express_code', '$.default_platform_code')
WHERE subject_config IS NOT NULL
`);
},
};

View File

@ -0,0 +1,74 @@
'use strict';
module.exports = {
async up(queryInterface, Sequelize) {
const { INTEGER, STRING } = Sequelize;
const [ tables ] = await queryInterface.sequelize.query(
"SHOW TABLES LIKE 'wms_express_interface'"
);
if (tables.length > 0) {
console.log('Table wms_express_interface already exists, skipping creation');
return;
}
await queryInterface.createTable('wms_express_interface', {
id: {
type: INTEGER(10),
primaryKey: true,
autoIncrement: true,
allowNull: false,
comment: '接口ID',
},
interface_url: {
type: STRING(500),
allowNull: false,
comment: '外部接口URL',
},
platform_code: {
type: STRING(50),
allowNull: false,
comment: '平台代码,用于应用分流',
},
interface_name: {
type: STRING(200),
allowNull: false,
comment: '接口名称',
},
}, {
engine: 'InnoDB',
charset: 'utf8mb4',
collate: 'utf8mb4_unicode_ci',
comment: '快递外部接口配置表',
});
const safeCreateIndex = async (tableName, fields, options) => {
const [ existingIndexes ] = await queryInterface.sequelize.query(
`SHOW INDEX FROM ${tableName} WHERE Key_name = '${options.name}'`
);
if (existingIndexes.length === 0) {
await queryInterface.addIndex(tableName, fields, options);
}
};
await safeCreateIndex('wms_express_interface', [ 'platform_code' ], {
name: 'idx_platform_code',
});
await safeCreateIndex('wms_express_interface', [ 'interface_name' ], {
name: 'idx_interface_name',
});
},
async down(queryInterface) {
const [ tables ] = await queryInterface.sequelize.query(
"SHOW TABLES LIKE 'wms_express_interface'"
);
if (tables.length > 0) {
await queryInterface.dropTable('wms_express_interface');
}
},
};

View File

@ -0,0 +1,118 @@
'use strict';
module.exports = {
async up(queryInterface, Sequelize) {
const { BIGINT, STRING, DATE } = Sequelize;
const tableName = 'wms_picking';
const [ tables ] = await queryInterface.sequelize.query(
`SHOW TABLES LIKE '${tableName}'`
);
if (tables.length === 0) {
await queryInterface.createTable(tableName, {
id: {
type: BIGINT(20).UNSIGNED,
primaryKey: true,
autoIncrement: true,
allowNull: false,
comment: '主键ID',
},
order_id: {
type: BIGINT(20).UNSIGNED,
allowNull: false,
comment: '订单ID',
},
order_item_id: {
type: BIGINT(20).UNSIGNED,
allowNull: false,
comment: '订单明细ID',
},
storage_id: {
type: BIGINT(20).UNSIGNED,
allowNull: true,
comment: '库存记录ID',
},
space_id: {
type: BIGINT(20).UNSIGNED,
allowNull: true,
comment: '库位ID',
},
space_name: {
type: STRING(100),
allowNull: true,
comment: '库位名称',
},
status: {
type: STRING(20),
allowNull: false,
defaultValue: 'pending',
comment: '状态',
},
created_at: {
type: DATE,
allowNull: false,
defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'),
comment: '创建时间',
},
updated_at: {
type: DATE,
allowNull: false,
defaultValue: Sequelize.literal('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'),
comment: '更新时间',
},
}, {
engine: 'InnoDB',
charset: 'utf8mb4',
collate: 'utf8mb4_general_ci',
comment: '订单储位分配表',
});
} else {
console.log('Table wms_picking already exists, ensuring indexes');
}
const safeCreateIndex = async (fields, options) => {
const [ existingIndexes ] = await queryInterface.sequelize.query(
`SHOW INDEX FROM ${tableName} WHERE Key_name = '${options.name}'`
);
if (existingIndexes.length === 0) {
await queryInterface.addIndex(tableName, fields, options);
}
};
await safeCreateIndex([ 'order_id' ], {
name: 'idx_wms_picking_order_id',
});
await safeCreateIndex([ 'order_item_id' ], {
name: 'idx_wms_picking_order_item_id',
});
await safeCreateIndex([ 'storage_id' ], {
name: 'idx_wms_picking_storage_id',
});
await safeCreateIndex([ 'space_id' ], {
name: 'idx_wms_picking_space_id',
});
await safeCreateIndex([ 'status' ], {
name: 'idx_wms_picking_status',
});
await safeCreateIndex([ 'order_item_id', 'space_id' ], {
name: 'idx_wms_picking_order_item_space',
});
},
async down(queryInterface) {
const tableName = 'wms_picking';
const [ tables ] = await queryInterface.sequelize.query(
`SHOW TABLES LIKE '${tableName}'`
);
if (tables.length > 0) {
await queryInterface.dropTable(tableName);
}
},
};

View File

@ -0,0 +1,32 @@
'use strict';
module.exports = {
async up(queryInterface, Sequelize) {
const tableName = 'wms_picking';
const { INTEGER } = Sequelize;
const [ quantityColumns ] = await queryInterface.sequelize.query(
`SHOW COLUMNS FROM \`${tableName}\` LIKE 'quantity'`
);
if (quantityColumns.length === 0) {
await queryInterface.addColumn(tableName, 'quantity', {
type: INTEGER(10).UNSIGNED,
allowNull: false,
defaultValue: 1,
comment: '分配数量',
});
}
},
async down(queryInterface) {
const tableName = 'wms_picking';
const [ quantityColumns ] = await queryInterface.sequelize.query(
`SHOW COLUMNS FROM \`${tableName}\` LIKE 'quantity'`
);
if (quantityColumns.length > 0) {
await queryInterface.removeColumn(tableName, 'quantity');
}
},
};

BIN
day.log

Binary file not shown.

View File

@ -0,0 +1,56 @@
{
"docName": "<system|qimen|gateway>",
"docMeta": {
"updatedAt": "<YYYY-MM-DD>",
"version": "<doc-version>"
},
"group": {
"groupName": "<分组名称>",
"module": "<group-module>"
},
"methods": [
{
"method": "<module.method>",
"description": "<接口说明>",
"isNeedAuth": false,
"isNeedLogin": true,
"headers": [],
"params": [
{
"name": "<param-name>",
"type": "string",
"required": true,
"source": "body",
"description": "<参数说明>"
}
],
"response": [
{
"name": "<field-name>",
"type": "string",
"required": true,
"description": "<返回字段说明>"
}
],
"errors": [
{
"code": 400,
"message": "<错误说明>"
}
]
}
],
"change": {
"version": "<YYYY.MM.DD-docName-xx>",
"date": "<YYYY-MM-DD>",
"summary": "<本次变更摘要>",
"methods": [
"<module.method>"
],
"notes": [
"<变更说明 1>",
"<变更说明 2>"
],
"type": "updated"
}
}

View File

@ -0,0 +1,103 @@
# API 文档 JSON 固定写入流程
## 现有 JSON 结构
仓库内现有 API 文档分两类:
1. `methods/<docName>.json`
- 根节点是对象
- 关键字段固定为 `module`、`description`、`version`、`updatedAt`、`headers`、`methods.groups`
- `methods.groups` 为数组,每个 group 固定为 `groupName`、`module`、`list`
- `list` 中每个 method 固定包含 `method`、`description`、`isNeedAuth`、`isNeedLogin`、`headers`、`params`、`response`、`errors`
2. `methods/changes/<docName>.json`
- 根节点是数组
- 每条变更记录建议固定包含 `version`、`date`、`summary`、`methods`、`notes`
- 可选补充 `type`
## 固定输入 spec
后续 API 文档写入统一通过脚本读取一个 spec JSON 完成,spec 结构固定如下:
```json
{
"docName": "system",
"docMeta": {
"updatedAt": "2026-04-15",
"version": "0.3.5"
},
"group": {
"groupName": "基础模块",
"module": "index"
},
"methods": [
{
"method": "index.example",
"description": "接口说明",
"isNeedAuth": false,
"isNeedLogin": true,
"headers": [],
"params": [],
"response": [],
"errors": []
}
],
"change": {
"version": "2026.04.15-system-06",
"date": "2026-04-15",
"summary": "一句话说明本次接口文档变更",
"methods": [
"index.example"
],
"notes": [
"补充关键字段说明。"
],
"type": "updated"
}
}
```
说明:
- `docName` 目前必须对应已存在的 `methods/system.json`、`methods/qimen.json`、`methods/gateway.json`
- `group` 用于定位或创建目标分组
- `methods` 为要写入的完整 method 文档对象数组,脚本按 `method` 字段 upsert
- `change` 默认必填;仅当明确是纯格式修复且不需要追加历史时,才允许加 `--doc-only`
## 固定命令
先做 dry-run:
```powershell
npm run doc:api:update -- --spec=temp/api-doc-update.json --dry-run
```
确认无误后执行写入:
```powershell
npm run doc:api:update -- --spec=temp/api-doc-update.json
```
纯文档主文件修补且不追加 changes 时:
```powershell
npm run doc:api:update -- --spec=temp/api-doc-update.json --doc-only
```
## 脚本保证
`script/update-api-doc.cjs` 会执行以下动作:
- 校验 spec JSON 是否符合固定结构
- 校验目标 `methods/*.json` 与 `methods/changes/*.json` 是否可解析
- 按 group + method 做 upsert,避免手写 JSON 时把括号、逗号、层级写坏
- 检查 change version 是否重复
- 保留目标 JSON 原有缩进与换行风格
## 推荐流程
1. 先核对代码与测试,确认真实接口契约
2. 如果是 system 参数结构变化,可先执行 `node .\script\tmp-struct-system-params.cjs`
3. 按 [docs/api-doc-update-spec.example.json](docs/api-doc-update-spec.example.json) 复制一份 spec 到 `temp/`
4. 先执行 dry-run,再执行正式写入
5. 最后补充必要的 `docs/*.md` 或 `README.md`

View File

@ -14,6 +14,7 @@
当前已落地事件:
- `receiving_completed`:收货完成通知
- `order_cancel_intercepted`:订单取消失败并触发拦截执行通知
- `store_warehouse_print_quantity_adjusted`:货主面单余额人工调整通知
---
@ -51,9 +52,10 @@ await ctx.service.systems.notice.send({
| event | 含义 |
|---|---|
| `receiving_completed` | 收货单完成通知 |
| `order_cancel_intercepted` | 订单取消失败并触发拦截执行通知 |
| `store_warehouse_print_quantity_adjusted` | 货主面单余额人工调整通知 |
> 当前正式注册的业务事件包括 `receiving_completed`、`store_warehouse_print_quantity_adjusted`。
> 当前正式注册的业务事件包括 `receiving_completed`、`order_cancel_intercepted`、`store_warehouse_print_quantity_adjusted`。
对于外部订阅方来说,判断消息类型时,优先看:
@ -136,7 +138,9 @@ Content-Type: application/json
"name": "广州仓",
"code": "",
"config": {
"max_notice_webhook_count": 5
"max_notice_webhook_count": 5,
"default_express_code": "STO",
"default_platform_code": "TB"
}
},
"store": {
@ -240,6 +244,7 @@ Content-Type: application/json
下一步可继续补充:
- `receiving_cancelled`
- `order_cancelled`
- `stock_low`
- `stock_changed`
- `entry_order_created`

View File

@ -60,6 +60,8 @@ await ctx.service.systems.notice.send(options)
| 字段 | 说明 |
|---|---|
| `max_notice_webhook_count` | 当前主体最多允许绑定 / 触达的消息推送接口数量,默认 `5` |
| `default_express_code` | 默认快递编码,默认 `STO` |
| `default_platform_code` | 默认平台编码,默认 `TB` |
---
@ -83,8 +85,9 @@ await ctx.service.systems.notice.send(options)
| event | 说明 |
|---|---|
| `receiving_completed` | 收货单完成通知 |
| `order_cancel_intercepted` | 订单取消失败并触发拦截执行的通知 |
> 当前正式注册的业务事件仅保留 `receiving_completed`;`all` / `*` 作为通配订阅值继续保留。收货完成事件的独立 API 文档见:`docs/notification-event-api.md`。
> 当前正式注册的业务事件包括 `receiving_completed`、`order_cancel_intercepted`;`all` / `*` 作为通配订阅值继续保留。收货完成事件的独立 API 文档见:`docs/notification-event-api.md`。
---
@ -139,7 +142,9 @@ await ctx.service.systems.notice.send(options)
"name": "广州仓",
"code": "",
"config": {
"max_notice_webhook_count": 5
"max_notice_webhook_count": 5,
"default_express_code": "STO",
"default_platform_code": "TB"
}
},
"store": {
@ -178,9 +183,12 @@ await ctx.service.systems.notice.send(options)
| `all` | 接收全部已注册通知 |
| `*` | 兼容旧配置,等价于 `all` |
| `receiving_completed` | 只接收收货完成事件 |
| `order_cancel_intercepted` | 只接收订单取消拦截事件 |
> 若需新增其他事件,必须先在 `app/model/notification_webhook.js` 完成注册,否则发送入口会直接拒绝。
当前订单取消拦截通知由 `app/service/qimenMethods/order.js` 在拣货状态或打印状态未结束时发送,事件码为 `order_cancel_intercepted`。
---
## 8. 命中与分发规则

View File

@ -0,0 +1,186 @@
# 订单工作台 List 接口说明
本文档说明订单工作台(Order Workbench)中可用的 list 接口、参数约定、返回结构与行为要点。
**变更记录**
- 本次已在 methods/system.json 中补充以下 method 定义,并在 methods/changes/system.json 中追加变更记录(参见变更文件),用于对外说明新增的 list 接口与分页/where 支持。
**新增/确认的接口(method 名称,主入口)**
- order.list —— 订单工作台总列表入口(汇总所有分组)
- order.reviewOrder.list —— 待审核订单工作台(step=0)
- order.pendingOrder.list —— 待处理订单工作台(step in [1,2])
- order.expectionOrder.list —— 待处理异常订单工作台(step=3)
- order.entrustOrder.list —— 委托外仓订单工作台(outsourced 模型)
- order.deliveryOrder.list —— 配送订单工作台(dispatch 模型,dispatch_lane=m4)
- order.deliveryExpectionOrder.list —— 配送异常订单工作台(dispatch 模型,dispatch_lane=m5)
- order.archiveOrder.list —— 归档订单工作台(history 模型)
兼容说明:代码中存在若干旧兼容入口(例如 getreviewOrderlist、getdeliveryOrderlist、getpendingOrderlist、getexpectionOrderlist、getentrustOrderlist、getarchiveOrderlist 等),这些为兼容旧调用保留的旧名入口,不作为首选主入口;建议新调用使用上文列出的主入口。
**工作台语义(简要)**
- order.list:总列表入口,返回跨分组的订单集合,适用于需要不分组的通用搜索/分页场景。
- reviewOrder:待审核(审核步骤为未审核)工作台,用于审核操作筛选与展示(默认 step=0)。审核提交接口仅接收 ids,批量审核,严格同仓校验,不做兼容。
- pendingOrder:待处理工作台,通常包含需要人工或系统继续处理的订单(默认 step in [1,2])。
- expectionOrder:异常工单集合(默认 step=3),用于定位异常状态订单。
- entrustOrder:委托外仓相关订单,使用 outsourced 模型。
- deliveryOrder / deliveryExpectionOrder:配送相关工作台,使用 dispatch 模型,分别以 dispatch_lane=m4 / m5 筛选。
- archiveOrder:归档历史订单,使用 history 模型。
实现要点(参考实现位于 app/service/systemMethods/order/*):
- 模块实现会根据模块名选择不同物理模型(current / dispatch / outsourced / history),由 OrderBaseService#getOrderModel 决定。
- 每个模块还定义了 `defaultWhere`(例如 reviewOrder 的 step=0 等),请求的 `where` 会与模块默认条件合并后一起用于构造最终查询。
参数说明(公共约定)
- pagination: object
- pagination.page: number(可选),页码,从 1 开始,默认 1。
- pagination.pageSize: number(可选),每页条数,默认 20。注意:服务端对 pageSize 做上限截断,最大不可超过 200(见下)。
- where: object(可选)
- 统一的筛选条件对象;支持两种写法:
- 标准化结构:{ field: { operator: 'eq'|'in'|'like'|..., value: ..., type?: 'string'|'number' } }
- 简写:{ field: value }(会被自动转换为 { operator: 'eq', value } 或在传数组时转换为 in)
- 服务端会先对 where 做 normalize(兼容简写与 values 字段),再走 parseWhereConditions 生成底层查询条件,最后与模块的 defaultWhere 合并(后者优先级低于请求入参)。
- 常见可用字段:id、delivery_order_code、order_status、dispatch_lane、quickWhere 等(具体过滤字段以实现解析器支持为准)。
- sort: object(可选)
- 支持 sortField / sortOrder 或 field / order;实现层会映射到允许的字段集合(如 id、step、status、delivery_time、updated_at 等),默认按 updated_at DESC, id DESC。
分页/大小限制
- 默认 pageSize=20。
- 最大 pageSize: 200(服务端在 normalizePagination 中对 pageSize 做截断,防止单次请求返回过大数据)。调用方仍应合理控制 pageSize,避免前端一次性请求过多数据。
返回结构(公共约定)
- list: array — 当前页的记录数组(每项为订单对象的序列化行,字段视具体模型与序列化而定)。
- pagination: object
- pagination.page: number — 当前页
- pagination.pageSize: number — 每页条数(实际返回值为服务端截断后的值)
- pagination.total: number — 符合条件的总记录数
- pagination.totalPages: number
- pagination.hasPrevious / hasNext: boolean
订单列表 raw 字段字典(通用)
- 说明:以下字段为所有订单列表的 raw 基础字段;`order.deliveryOrder.list` 和 `order.deliveryExpectionOrder.list` 额外包含 `dispatch_lane`;服务层还会补充 `express_numbers` 与 `waybill_codes` 两个派生字段,二者内容一致,都是该订单绑定的多个快递号。
| 字段 | 类型 | 中文语义 | 枚举/说明 |
| --- | --- | --- | --- |
| id | number | 订单主键 ID | 订单记录主键 |
| delivery_order_code | string | 发货单号 | 订单单号 |
| pre_delivery_order_code | string | 预发货单号 | 预发货阶段单号 |
| pre_delivery_order_id | string | 预发货单ID | 预发货记录关联 ID |
| order_type | string | 订单类型 | 业务类型标识 |
| warehouse_code | string | 仓库编码 | 仓库基础编码 |
| order_flag | string | 订单标记 | 订单标签/标记信息 |
| source_platform_code | string | 来源平台编码 | 原始平台编码 |
| source_platform_name | string | 来源平台名称 | 原始平台名称 |
| sys_platform_code | string | 系统平台编码 | 系统内平台编码 |
| sys_platform_name | string | 系统平台名称 | 系统内平台名称 |
| create_at | string | 创建时间 | ISO 时间字符串 |
| delete_at | string | 删除时间 | ISO 时间字符串,通常为空 |
| updated_at | string | 更新时间 | ISO 时间字符串 |
| place_order_time | string | 店铺创建订单时间 | 平台下单时间 |
| pay_time | string | 支付时间 | 支付完成时间 |
| pay_no | string | 支付单号 | 支付流水号 |
| service_code | string | 集包服务编码 | 集包/服务编码 |
| operator_name | string | ERP审核人 | 审核人姓名 |
| operate_time | string | ERP审核时间 | 审核时间 |
| delivery_time | string | 发货时间 | 发货完成时间 |
| shop_nick | string | 店铺名称 | 店铺昵称 |
| seller_nick | string | 卖家名称 | 卖家昵称 |
| buyer_nick | string | 买家名称 | 买家昵称 |
| total_amount | number | 订单总金额 | 金额字段,保留两位小数 |
| item_amount | number | 商品总金额 | 金额字段,保留两位小数 |
| discount_amount | number | 订单折扣金额 | 金额字段,保留两位小数 |
| freight | number | 快递费用 | 金额字段,保留两位小数 |
| ar_amount | number | 应收金额 | 金额字段,保留两位小数 |
| got_amount | number | 已收金额 | 金额字段,保留两位小数 |
| service_fee | number | COD服务费 | 金额字段,保留两位小数 |
| logistics_code | string | 物流公司编码 | 物流公司编码 |
| logistics_name | string | 物流公司名称 | 物流公司名称 |
| sys_logistics_code | string | 系统物流公司编码 | 系统内物流编码 |
| sys_logistics_name | string | 系统物流公司名称 | 系统内物流名称 |
| express_code | string | 面单号前置 | 面单号前缀 |
| logistics_area_code | string | 快递区域编码 | 大头笔/区域编码 |
| delivery_type | string | 发货服务类型 | 发货方式 |
| is_urgency | enum | 是否紧急 | Y=是,N=否 |
| invoice_flag | enum | 是否需要发票 | Y=需要,N=不需要 |
| status | enum | 订单状态 | pedding=待处理,created=已创建,cancel=已取消,error=异常 |
| name | string | 收件人姓名 | 收件人 |
| zip_code | string | 收件人邮编 | 邮编 |
| tel | string | 收件人电话 | 电话号码 |
| mobile | string | 收件人移动电话 | 手机号 |
| email | string | 收件人邮箱 | 邮箱 |
| country_code | string | 国家编码 | 国家/地区编码 |
| province | string | 省份 | 收件地址省 |
| city | string | 城市 | 收件地址市 |
| area | string | 区 | 收件地址区 |
| town | string | 镇 | 收件地址镇 |
| detail_address | string | 详细地址 | 街道/门牌详情 |
| id_type | string | 证件类型 | 证件类型 |
| id_number | number | 证件号码 | 证件号 |
| oaid | string | OAID | 设备/终端标识 |
| sync_status | enum | 同步状态 | padding=待同步,fin=完成,error=失败 |
| store_id | number | 货主ID | 货主主键 |
| warehouse_id | number | 仓库ID | 仓库主键 |
| from_key | number | 来源键 | 来源系统键值 |
| items | string | 商品JSON字符串 | 原始商品明细 JSON |
| items_count | number | 商品种类数 | SKU 种类数 |
| items_total | number | 商品总数 | 商品件数总和 |
| items_weight | number | 总重量(kg) | 总重量 |
| items_hash | string | MD5哈希值(32位) | 商品明细哈希 |
| items_crc | number | CRC32校验码 | 商品明细校验码 |
| wave_id | number | 波次ID | 0 表示未分配 |
| post_status | enum | 分配快递号状态机 | padding=处理中,fin=完成,timeout=超时,error=失败,none=未开始 |
| storage_status | enum | 分配储位状态机 | padding=处理中,fin=完成,error=失败,none=未开始 |
| pick_status | enum | 拣货状态机 | padding=处理中,fin=完成,error=失败,none=未开始 |
| pack_status | enum | 打包状态机 | none=未开始,padding=处理中,fin=完成,error=失败 |
| inspection_status | enum | 检验状态机 | none=未开始,padding=处理中,running=进行中,fin=完成,error=失败 |
| step | number | 订单步骤 | 0=未审核,1=已审核,2=处理中,3=驳回/异常,4=配送中,5=已完成,9=已关闭 |
| print_status | enum | 打印状态机 | none=未开始,padding=处理中,fin=完成,error=失败 |
| claim_status | enum | 领取状态机 | none=未开始,padding=处理中,fin=完成,error=失败 |
| outbound_status | enum | 出库状态机 | none=未开始,padding=处理中,fin=完成,timeout=超时,error=失败 |
| lock_status | enum | 锁定状态机 | none=未锁定,warehouse=仓库锁定,store=货主锁定 |
| intercept_status | enum | 拦截状态机 | none=未拦截,requesting=请求中,requested=已请求,intercepting=拦截中,intercepted_in_transit=运输中拦截成功,intercepted_at_warehouse=仓库拦截成功,returning=退回中,returned=已退回,delivered_by_mistake=误签收,timeout=超时,cancelled=已取消,failed=失败,exception=异常 |
| dispatch_lane | string | 配送通道/分区 | 仅配送相关列表可能出现,常用于区分 m4 / m5 等通道 |
| express_numbers | array[string] | 快递号列表 | 服务层聚合字段,内容来自 wms_order_express.waybill_code |
| waybill_codes | array[string] | 运单号列表 | 与 express_numbers 内容一致,为兼容前端使用保留 |
补充说明
- `express_numbers` 和 `waybill_codes` 都来自订单绑定的多条快递记录,适合前端直接渲染“多个快递号”。
- `sys_platform_name`、`sys_logistics_name` 已由服务层归一化输出,前端无需再回表查询。
- `dispatch_lane` 仅在 `order.deliveryOrder.list` / `order.deliveryExpectionOrder.list` 这两个配送类列表中出现;其余列表通常不返回该字段。
其他注意事项
- `where` 的解析与支持的特殊字段由 parseWhereConditions 决定;若需要支持新的复杂筛选(如跨表/聚合条件),请先在解析器和后端模型中确认可支持的 specialFieldMap 与解析策略。
- 推荐使用标准化 where 结构({ operator, value })以避免歧义;历史简写会被自动规范化,但可读性较差。
- 兼容入口(get*)保留以兼容历史客户端,但文档与新开发均建议使用上述主入口方法名;兼容入口可能在不同 module 下存在重复实现(index + 子模块),以兼容不同调用路径。
方法清单(已在 methods/system.json 中登记)
- order.list
- order.reviewOrder.list
- order.pendingOrder.list
- order.expectionOrder.list
- order.entrustOrder.list
- order.deliveryOrder.list
- order.deliveryExpectionOrder.list
- order.archiveOrder.list
是否需要补充其它文档同步?
- 建议同步更新:
- 若有门户/前端 API 文档站(自动生成或展示 methods/system.json 的地方),应部署或刷新以展现新增条目。
- 若存在 SDK 或对接说明(如 qimen 或第三方对接文档),如使用到工作台 list 场景也建议补充示例请求与常用 where 范例。
示例请求(简要)
请求体示例:
{
"pagination": { "page": 1, "pageSize": 50 },
"where": { "delivery_order_code": { "operator": "like", "value": "ABC" }, "create_time_start": { "value": "2026-04-01" } },
"sort": { "sortField": "updated_at", "sortOrder": "DESC" }
}
响应示例(简要):
{
"list": [ /* 订单对象数组 */ ],
"pagination": { "page":1, "pageSize":50, "total":1234, "totalPages":25, "hasPrevious":false, "hasNext":true }
}
--
文档维护者:WMS 文档代理

View File

@ -0,0 +1,80 @@
# 库存效期模块(定时预警任务)
本文档基于源码实现(单一事实来源),定位与说明项目中关于库存效期扫描与预警的定时任务行为。实现文件:app/schedule/notice_stock_remaining.js。
## 概要
- 任务名称/文件:`app/schedule/notice_stock_remaining.js`
- 调度配置:`interval: '30s'`、`type: 'worker'`、`immediate: false`(见文件头部 schedule 配置)
- 目的:扫描启用保质期管理的仓库商品与对应库存(wms_stock_warehouse / wms_storage),对即将到期的库存发送效期预警通知,并通过缓存进行去重。
## 主要实现要点(按代码实现逐项说明)
1. 并发保护
- 使用进程级标记 `ctx.app._noticeStockRemainingRunning`,若上一轮尚未结束则跳过本次运行。
2. 通知去重缓存
- 缓存键:`notice_stock_remaining_notified_list`(文件常量 `CACHE_KEY`)。
- 缓存 TTL:24 小时(`CACHE_TTL_SECONDS = 24 * 60 * 60`)。
- 缓存存储格式兼容数组或对象,读取后标准化为 `storage:{id}` 格式的键集合用于去重。
3. 读取候选商品(wms_stock_warehouse)
- 查询条件(stockWhere):
- `is_shelf_life_mgmt: 'Y'`
- `remaining_threshold_days: { [Op.gt]: 0 }`(使用 `Sequelize.Op.gt`)
- 查询字段:`id, item_code, item_name, store_id, warehouse_id, remaining_threshold_days`
- 排序:`remaining_threshold_days ASC, id ASC`
- 结果用于构建 `stockMap`(包含每个 stock 的阈值),并计算 `maxThresholdDays`(用于缩小后续库存扫描时间窗口)。
4. 计算候选库存时间窗口
- 以当前时间 `now`,计算 `maxExpiryDate = new Date(now.getTime() + maxThresholdDays * DAY_MS)`,其中 `DAY_MS = 24 * 60 * 60 * 1000`。
5. 查询候选库存记录(wms_storage)
- 查询条件(storageWhere):
- `stock_id` 在上一步筛选得到的 `stockIds` 列表中
- `is_enabled: 1`
- `delete_at: null`(paranoid 软删除过滤)
- `quantity: { [Op.gt]: 0 }`
- `expiry_date: { [Op.ne]: null, [Op.lte]: maxExpiryDate }`(到期日非空且小于等于计算窗口)
- include:关联 `LocationSpace`(别名 `space`),属性取 `space_code, custom_name`,`required: false`。
- 排序:`expiry_date ASC, inbound_time ASC, id ASC`。
- 注意:实现中调用的是 `findAll`(无分页),因此会拉取匹配的全部候选记录并在内存中逐条处理。
6. 单条记录处理与判断逻辑
- 对每条 `storageRecord`:
- 生成去重键 `notifyKey = storage:{storageId}`(若无法解析 id 则跳过)。
- 若该 `notifyKey` 已存在于缓存集合则跳过(避免重复通知)。
- 根据 `stockMap` 获取本条记录对应商品的 `thresholdDays`(阈值天数);若不存在或阈值 <= 0 则跳过。
- 读取 `expiry_date`,将其解析为 Date;若无或解析失败则跳过并记录 warn。
- 计算剩余天数:`remainingDays = Math.max(0, Math.ceil((expiryDate - now) / DAY_MS))`。
- 若 `remainingDays > thresholdDays` 则跳过(未达到阈值);否则组装通知并发送。
7. 通知发送与元数据
- 使用通知服务:`ctx.service.systems.notice.send(payload)`。代码中若 `noticeResult.success === false` 则认为发送失败并保留重试;异常时记录错误并继续处理下一条。
- 通知 payload 包含(示例字段):
- `warehouseId`, `storeId`, `subject`(id/type/name), `businessName: 'storage'`, `event`(常量 `storage_transfer_completed`),`title`, `content`, `businessId: storageId`, `messageType: 'text'`
- `metadata`:包含 `cacheKey`, `storageId`, `stockId`, `notifyKey`, `thresholdDays`, `remainingDays`, `warehouseId`, `storeId`, `stock: { id, item_code, item_name }`, `storage: { id, batch_no, expiry_date (ISO) }`
8. 回写去重缓存
- 成功发送后,将 `notifyKey` 添加到 `updatedNotifiedList` 并在本轮结束后使用 `ctx.app.setCacheAsync(CACHE_KEY, dedupedList, CACHE_TTL_SECONDS)` 回写缓存(如果 `setCacheAsync` 可用)。
9. 日志与统计
- 任务会记录候选商品数、候选库存数、实际发送计数与跳过计数;发送失败与异常会记录 warn/error 日志。
## 与公开 API 的关系
- 任务为内部定时任务(非 system API),其查询条件与模型字段直接对应数据库表 `wms_stock_warehouse` 与 `wms_storage`。
- 若需要通过 API 查询某个商品的库存明细(包含批次与过期信息),请使用已有的 system 方法 `stock.warehouse.getStockDetail`(该接口支持 `pagination` 与 `group_by_batch`,API 文档位于 `methods/system.json`),与本任务的扫描逻辑互为补充:任务用于主动推送预警,API 用于按需查询。
## 注意事项(运维/集成)
- 通知发送依赖 `ctx.service.systems.notice`,在无该服务或返回异常时任务仅记录日志。
- 任务扫描不分页:对于极大库存量的仓库,建议评估 `maxThresholdDays` 与索引(`idx_expiry_date` 已存在于模型)对查询性能的影响,或考虑将查询改为分片/分页处理。
- 去重缓存使用全局缓存接口 `getCacheAsync` / `setCacheAsync`,请保证缓存后台(如 Redis)可用以避免重复通知泛滥。
## 实现位置(代码参考)
- 定时任务文件:app/schedule/notice_stock_remaining.js
- 依赖模型:app/model/stock_warehouse.js、app/model/storage.js、app/model/location_space.js
- 依赖服务:ctx.service.systems.notice

View File

@ -217,3 +217,111 @@ curl -X POST "http://127.0.0.1:6060/system?method=storage.receiving.bindDetailPr
- 自动刷新收货单统计数据
适合作为收货单明细与系统商品标准匹配接口对外说明使用。
---
## 11. 接口:storage.receiving.detailChange
### 11.1 接口用途
用于修改收货单明细(明细行)中的数量、箱规、批次与商品信息,并触发收货单统计与相关联动(例如库存/统计刷新与操作日志)。典型场景为:前端在录入收货明细后,补录实际收货数量、箱数、托盘数、批次/生产/到期信息或回写条码与商品名称等。
> 注意:方法在 system 层以 `POST /system?method=storage.receiving.detailChange` 调用,需包含 `Authorization: Bearer <token>`,仓库上下文来源于 `ctx.user.store_id`。
### 11.2 请求参数
| 字段 | 类型 | 必填 | 说明 |
|---|---:|---:|---|
| `id` | `number` | 是 | 收货明细 ID(必填) |
| `receiving_id` | `number` | 是 | 收货单 ID(必填) |
| `actual_quantity` | `number` | 否 | 实际收货数量 |
| `batch_number` | `string` | 否 | 批次号 |
| `production_date` | `string` | 否 | 生产日期(ISO 或可解析的日期字符串) |
| `expiry_date` | `string` | 否 | 到期日期(ISO 或可解析的日期字符串)。若传入的 `expiry_date` 小于当前日期,接口会拒绝并返回 400(见错误码) |
| `box_quantity` | `number` | 否 | 箱数 |
| `boxes_per_pallet` | `number` | 否 | 每托盘箱数 |
| `pallet_quantity` | `number` | 否 | 托盘数 |
| `space_id` | `number` | 否 | 目标库位 ID(可用于回写库位) |
| `remark` | `string` | 否 | 备注 |
| `system_product_id` | `number` | 否 | 系统商品 ID(StockWarehouse.id)。若提供,系统会回填条码、重量、箱规、商品名称与快照等;若不提供,可单独更新 `barcode`/`product_name` |
| `barcode` | `string` | 否 | 条码(当未传 `system_product_id` 时,可单独更新) |
| `product_name` | `string` | 否 | 商品名称(当未传 `system_product_id` 时,可单独更新) |
| `box_width` | `number` | 否 | 箱宽(单位按系统约定) |
| `box_height` | `number` | 否 | 箱高 |
| `box_length` | `number` | 否 | 箱长 |
| `weight` | `number` | 否 | 毛重/重量 |
> 说明:`id` 与 `receiving_id` 为必须校验项,其他字段为可选—仅在传入时会写入/覆盖对应明细字段。传入 `system_product_id` 时,系统优先使用系统商品信息回填字段(前端可只传 `system_product_id` 来自动回填)。
### 11.3 请求示例
```json
{
"id": 501,
"receiving_id": 123,
"actual_quantity": 10,
"batch_number": "B20260401",
"production_date": "2026-04-01",
"expiry_date": "2027-04-01",
"box_quantity": 2,
"boxes_per_pallet": 10,
"pallet_quantity": 0,
"space_id": 1001,
"remark": "样例备注",
"system_product_id": 8888
}
```
### 11.4 返回结构(成功)
成功时返回 `code: 200`,`message` 为 `修改成功`,`data` 中包含基础标识与关键展示字段:
```json
{
"code": 200,
"message": "修改成功",
"data": {
"id": 501,
"receiving_id": 123,
"actual_quantity": 1,
"product_name": "测试商品",
"barcode": "",
"system_product_id": null,
"updated_at": "2026-04-01T00:00:00.000Z"
}
}
```
返回字段说明:
- `data.id`:收货明细 ID
- `data.receiving_id`:收货单 ID
- `data.actual_quantity`:明细当前的实际收货数量(根据实现,此处返回服务端查询到的明细值)
- `data.product_name`:商品名称(若 `system_product_id` 回填则为系统商品名称)
- `data.barcode`:条码
- `data.system_product_id`:回填或当前关联的系统商品 ID
- `data.updated_at`:明细记录的更新时间
### 11.5 常见错误码
| code | message 示例 | 含义 |
|---:|---|---|
| `400` | `收货明细ID不能为空` | 未传 `id` |
| `400` | `收货单ID不能为空` | 未传 `receiving_id` |
| `400` | `到期日期已过期,不能录入收货` | `expiry_date` 小于当前日期时返回(禁止录入已过期批次) |
| `400` | `箱数不能为负数` / `托盘数不能为负数` | 非法的箱规数值 |
| `404` | `收货明细不存在` | 明细不存在或不属于当前仓库/收货单状态不允许操作 |
| `500` | `修改失败,请稍后重试` | 服务端异常 |
---
### 11.6 业务要点与实现说明
- 若传入 `system_product_id`,服务端尝试读取 `StockWarehouse`(同仓库)并回填:`barcode`(若前端未显式传入),`weight`,`boxes_per_pallet`、`box_height`、`box_width`、`box_length`(若启用箱规),以及 `product_snapshot` 中的货主快照信息。
- 若未传 `system_product_id`,但传入 `barcode` 或 `product_name`,服务端仍允许更新这两个字段(并把 `system_product_id` 置为 `null`)。
- 接口会在成功写入明细后触发收货单统计刷新(`updateReceivingStats`)并写操作日志(`RECEIVING_UPDATE_DETAIL`)。
- 系统存在一个库存效期预警定时任务,逻辑上会扫描启用保质期管理且设置了剩余天数阈值的商品,并按库存到期日筛选候选记录后进行去重通知发送;其判断条件主要依赖 `wms_stock_warehouse.is_shelf_life_mgmt = 'Y'`、`remaining_threshold_days > 0`,以及 `wms_storage.expiry_date`(小于等于当前时间加最大阈值天数)。
---

View File

@ -1,4 +1,162 @@
[
{
"version": "2026.04.15-system-07",
"date": "2026-04-15",
"summary": "将 docs/order-workbench-list-api.md 引用统一为 window 链接格式",
"methods": [
"order.list",
"order.reviewOrder.list",
"order.pendingOrder.list",
"order.outboundOrder.list",
"order.expectionOrder.list",
"order.entrustOrder.list",
"order.deliveryOrder.list",
"order.deliveryExpectionOrder.list"
],
"notes": [
"将所有 methods/system.json 中指向 docs/order-workbench-list-api.md 的说明统一替换为 <window>docs/order-workbench-list-api.md</window> 格式,以便 HTML 渲染识别为 window 链接。",
"仅修改 methods/system.json 的文档字段,不涉及任何业务代码或接口契约变化。"
],
"type": "updated"
},
{
"version": "2026.04.15-system-06",
"date": "2026-04-15",
"summary": "订单工作台列表文档补全 raw 字段字典与中文语义说明",
"methods": [
"order.list",
"order.reviewOrder.list",
"order.pendingOrder.list",
"order.outboundOrder.list",
"order.expectionOrder.list",
"order.entrustOrder.list",
"order.deliveryOrder.list",
"order.deliveryExpectionOrder.list",
"order.archiveOrder.list"
],
"notes": [
"在 docs/order-workbench-list-api.md 中补充所有订单列表通用 raw 字段字典,明确每个字段的中文语义与 enum 取值。",
"补充 express_numbers / waybill_codes 两个服务层派生字段说明,便于前端直接渲染多个快递号。",
"methods/system.json 中所有订单 list 的 response.list 描述已指向该字段字典章节。"
],
"type": "updated"
},
{
"version": "2026.04.15-system-05",
"date": "2026-04-15",
"summary": "基础模块新增快递/平台列表查询接口并设置为不鉴权,复用缓存 service",
"methods": [
"index.getExpressList",
"index.getPlatformList"
],
"notes": [
"新增 index.getExpressList,归属基础模块(module=index),对应 app/service/systems/express.js 中的 getExpressList。",
"index.getExpressList 设置为不鉴权,不需要 Authorization 头。",
"新增 index.getPlatformList,归属基础模块(module=index),对应 app/service/systems/platform.js 中的 getPlatformList。",
"index.getPlatformList 设置为不鉴权,不需要 Authorization 头。",
"快递列表与平台列表都支持缓存优先,缓存未命中时回源数据库并写入缓存。",
"平台列表支持缓存优先,缓存未命中时回源 wms_platform 并写入缓存。"
],
"type": "added"
},
{
"version": "2026.04.15-system-02",
"date": "2026-04-15",
"summary": "签约策略字段元信息新增 default_express_code / default_platform_code list 选项",
"methods": [
"storeWarehouse.store.getPolicyConfigFields"
],
"notes": [
"getPolicyConfigFields 现在返回 default_express_code 与 default_platform_code 两个 list 字段,并从 wms_express / wms_platform 读取选项列表。",
"默认值仍保留为 default_express_code=STO、default_platform_code=TB。"
],
"type": "updated"
},
{
"version": "2026.04.15-system-03",
"date": "2026-04-15",
"summary": "签约策略字段移除 sku_visibility,receive_mode options 改为 value/label 结构",
"methods": [
"storeWarehouse.store.savePolicyConfig",
"storeWarehouse.store.getPolicyConfigFields"
],
"notes": [
"策略字段定义不再包含 sku_visibility,历史值读取时仍会被归一化忽略。",
"receive_mode 的 options 改为 [{ value, label }] 格式,便于前端直接渲染。"
],
"type": "updated"
},
{
"version": "2026.04.15-system-04",
"date": "2026-04-15",
"summary": "按文件模块拆分 order 目录系统文档分组,覆盖订单工作台入口及各子模块方法",
"methods": [
"order.list",
"order.manualOutboundOrder",
"order.badgeCount",
"order.outboundOrder.manualOutboundOrder",
"order.reviewOrder.list",
"order.reviewOrder.reviewOrder",
"order.pendingOrder.list",
"order.pendingOrder.reverseReviewOrder",
"order.pendingOrder.markPendingOutboundOrder",
"order.pendingOrder.cancelOrder",
"order.outboundOrder.list",
"order.expectionOrder.list",
"order.entrustOrder.list",
"order.deliveryOrder.list",
"order.deliveryExpectionOrder.list",
"order.archiveOrder.list"
],
"notes": [
"按 app/service/systemMethods/order 下的实际对外方法补全 methods/system.json 文档,只覆盖 system,不处理 qimen。",
"order 文档已按 index / reviewOrder / pendingOrder / outboundOrder / expectionOrder / entrustOrder / deliveryOrder / deliveryExpectionOrder / archiveOrder 拆成多个模块分组。",
"同步根据当前代码意图补充 params / response / errors,且不再把 index.js 已移除的兼容接口写回文档。"
],
"type": "updated"
},
{
"version": "2026.04.15-system-01",
"date": "2026-04-15",
"summary": "货主主体配置默认补齐 default_express_code / default_platform_code",
"methods": [
"store.createStore",
"store.createWarehouse"
],
"notes": [
"当 subject_config 未传或缺少字段时,自动补齐 default_express_code=STO、default_platform_code=TB,并保留现有的 max_notice_webhook_count 默认值。",
"同步更新 methods/system.json 中 store.createStore 与 store.createWarehouse 的参数说明。"
],
"type": "updated"
},
{
"version": "2026.04.14-system-01",
"date": "2026-04-14",
"summary": "库存列表新增货主名称字段 stock.store_name",
"methods": [
"storage.inventory.list"
],
"notes": [
"在 methods/system.json 的 storage.inventory.list response 中补充 stock.store_name:来源于签约表 store_remask,若无签约关系则为 null。",
"只同步文档,不修改业务代码。"
],
"type": "updated"
},
{
"version": "2026.04.13-system-01",
"date": "2026-04-13",
"summary": "补全 storage.receiving.detailChange 的入参/出参契约与错误码说明",
"methods": [
"storage.receiving.detailChange"
],
"notes": [
"在 methods/system.json 中补充 storage.receiving.detailChange 的 params/response/errors,明确 id 与 receiving_id 必填。",
"说明 expiry_date 小于当前日期时返回 400 且 message 为 \"到期日期已过期,不能录入收货\"。",
"说明当传入 system_product_id 时会回填条码、重量、箱规、商品名称与 product_snapshot;未传时 barcode/product_name 也可单独更新。",
"同步补充文档:docs/storage-receiving-api.md 中新增 detailChange 段落。"
],
"type": "updated"
},
{
"version": "2026.04.07-system-01",
"date": "2026-04-07",
@ -441,4 +599,56 @@
],
"type": "changed"
}
]
,
{
"version": "2026.04.13-system-02",
"date": "2026-04-13",
"summary": "stock.warehouse.search 返回新增效期管理字段并保留 is_shelf_life_mgmt",
"methods": [
"stock.warehouse.search"
],
"notes": [
"响应 data[] 中新增字段:inbound_min_days、outbound_min_days、shelf_life_days、remaining_threshold_days(均为 number,单位:天)。",
"保留并说明 is_shelf_life_mgmt 布尔字段(boolean),表示是否启用效期管理(true=启用)。",
"仅更新文档(methods/system.json 与变更记录),代码行为不变。"
],
"type": "updated"
},
{
"version": "2026.04.13-system-02",
"date": "2026-04-13",
"summary": "新增 storage.expiry.list 库存有效期列表查询接口",
"methods": [
"storage.expiry.list"
],
"notes": [
"该接口查询 wms_storage,关联 stockWarehouse 和 locationSpace,并按当前仓库与 remaining_threshold_days / expiry_date 过滤。"
],
"type": "added"
},
{
"version": "2026.04.13-system-03",
"date": "2026-04-13",
"summary": "新增 storage.inventory.list 库存列表返回效期字段与预警标记",
"methods": [
"storage.inventory.list"
],
"notes": [
"库存列表响应增加生产日期、过期日期、效期预警是否触发字段",
"预警标记仅在商品启用保质期管理且到期日满足阈值条件时为 true"
],
"type": "updated"
},
{
"version": "2026.04.14-system-01",
"date": "2026-04-14",
"summary": "更新 index.searchSpace 文档",
"methods": [
"index.searchSpace"
],
"notes": [
"补充 index.searchSpace 的 params/response,按 ctx.user.store_id 作为仓库上下文;keyword 为可选字符串,对 space_code 与 custom_barcode 做 %keyword% 模糊匹配;返回字段 id、space_code、custom_barcode、custom_name,最多 50 条;仅文档同步,无代码变更。"
],
"type": "updated"
}
]

File diff suppressed because it is too large Load Diff

View File

@ -74,7 +74,7 @@
---
## 1. 目标与范围(含 M7)
## 1. 目标与范围(含 outsourced)
### 1.1 工作台模块一览
@ -83,18 +83,18 @@
| M1 待审核 | 需审核后进入后续履约 | **仅 current** |
| M2 待处理 | 仓内/出库前正常队列 | **仅 current** |
| M3 待处理异常 | 出库前各环节异常 | **仅 current** |
| M4 配送订单 | 配送链路正常态 | **配送域工厂(待建)**,约 3 自然月 |
| M5 配送异常 | 配送链路异常(M4 子集) | **同上** |
| M4 配送订单 | 配送链路正常态 | **配送域工厂(首期已落地)**:单表 `wms_order_delivery_dispatch_{wh}` + 列 `dispatch_lane=m4`;**不按自然月拆物理表** |
| M5 配送异常 | 配送链路异常(M4 子集) | **同上表**,`dispatch_lane=m5` 筛选;归档/近三月策略走 **查询与任务**,不必多分表 |
| M6 归档订单 | 冷数据 | **history**(>3 月等策略) |
| **M7 外仓发货** | 本仓不履约、推送外仓/三方履约;**暂无完整状态机** | **可与 current 扩展标记 + 外仓任务表** 或独立子域(待设计) |
| **outsourced 外仓发货** | 本仓不履约、推送外仓/三方履约;**已纳入 `OrderDeliveryFactory` 管理的 managed table / schema self-check 体系** | **由工厂统一管理,启动自检自动对齐结构**;仍可结合 current 扩展标记 + 外仓任务表落地 |
### 1.2 数据分层(与 §0 对齐)
| 层级 | 表 / 模型 | 时间 / 策略 |
|------|-----------|-------------|
| 热区 M1~M3 / M7(规划) | `wms_order_delivery_{wh}`、`wms_order_items_{wh}`(current) | 当日或未闭环;**创建时分流 M1 vs M2 由货主配置决定**;**到期仅克隆续单**,不进 M6(§2.4) |
| 配送区 M4/M5 | **配送域工厂**(独立于 current 的强分区存储) | **按自然月**;滚动 **3 个自然月** |
| 冷数据 M6 | `*_history`(仅承接 **M4/M5** 迁入) | **超过 3 个月**等策略;**仅允许 M4/M5 进入 M6**;M1/M2/M3/M7 **不走 M6 物理归档路径**(见 §2.4) |
| 热区 M1~M3 / outsourced(规划) | `wms_order_delivery_{wh}`、`wms_order_items_{wh}`(current) | 当日或未闭环;**创建时分流 M1 vs M2 由货主配置决定**;**到期仅克隆续单**,不进 M6(§2.4) |
| 配送区 M4/M5 | **`wms_order_delivery_dispatch_{wh}`**(`OrderDeliveryFactory` 的 dispatch 模式) | **单物理表**;M4/M5 用 **`dispatch_lane`**;**不按自然月拆表**;「约 3 个月」保留为 **列表/归档任务的时间条件**(见 §2.5 落地说明) |
| 冷数据 M6 | `*_history`(仅承接 **M4/M5** 迁入) | **超过 3 个月**等策略;**仅允许 M4/M5 进入 M6**;M1/M2/M3/outsourced **不走 M6 物理归档路径**(见 §2.4) |
---
@ -103,16 +103,16 @@
### 2.1 订单创建:进入 M1 或 M2
- **规则**:创建时读取 **货主(store)配置**,决定初始进入 **M1(待审核)** 或 **M2(待处理)**。
- **M1 → M2**:必须通过 **仓内库存校验**(满足可履约)**或** 选择 **推送 M7(外仓发货)** 路径之一;具体字段与接口待定义。
- **M2 ⊥ M7(强制互斥)**:同一订单 **不得** 同时处于本仓待处理与外仓履约;进入或退出 M2/M7 的切换 **必须在单条(或可串行化的)数据库事务内完成**(状态位 + 外仓任务表等一并提交),失败 **整体回滚**,禁止半开状态。
- **M7**:当前 **无完整状态机**;与 M4 的衔接仍遵守 §2.2 单向规则。
- **M1 → M2**:必须通过 **仓内库存校验**(满足可履约)**或** 选择 **推送 outsourced(外仓发货)** 路径之一;具体字段与接口待定义。
- **M2 ⊥ outsourced(强制互斥)**:同一订单 **不得** 同时处于本仓待处理与外仓履约;进入或退出 M2/outsourced 的切换 **必须在单条(或可串行化的)数据库事务内完成**(状态位 + 外仓任务表等一并提交),失败 **整体回滚**,禁止半开状态。
- **outsourced**:当前 **无完整状态机**;与 M4 的衔接仍遵守 §2.2 单向规则。
### 2.2 进入 M4 的约束(核心)
| 从 → 到 | 是否允许 | 说明 |
|---------|----------|------|
| **M2 → M4** | **允许(单向)** | M2、**M7 仅允许单向落入 M4** |
| **M7 → M4** | **允许(单向)** | 外仓发货完成后,依赖 **外部通知** 与出库状态机推进 |
| **M2 → M4** | **允许(单向)** | M2、**outsourced 仅允许单向落入 M4** |
| **outsourced → M4** | **允许(单向)** | 外仓发货完成后,依赖 **外部通知** 与出库状态机推进 |
| **M1 → M4** | **禁止** | 须先 **切到 M2** 且 **状态机到达出库** 后,再经 **外部通知发货完成** 落入 M4 |
| **M3 → M4** | **禁止** | 须先 **消除异常并回到 M2**,再走与 M2 相同路径进入 M4 |
| **取消订单 → M4** | **允许(专用)** | 见 **§2.3a**:标记取消态后 **直进 M4**,**不可逆**、**零例外** |
@ -120,7 +120,7 @@
### 2.3 M4 / M5 与外部机制
- **M4 ↔ M5 切换**:由 **外部机制** 驱动(承运商回传、网关、人工标记等),不在此文档展开协议。
- **M4/M5 与 M1~M3**:除下节「补发副本」外,**同一订单在 M1/M2/M3/M7 与 M4/M5 不重复占位**:**M1~M3(及 M7)为唯一工作台态**;**M4/M5 为配送域单独态**(可理解为 **配送域一条影子/主数据**,与 current 热行通过 `order_id` / `delivery_order_code` / 快照关联)。
- **M4/M5 与 M1~M3**:除下节「补发副本」外,**同一订单在 M1/M2/M3/outsourced 与 M4/M5 不重复占位**:**M1~M3(及 outsourced)为唯一工作台态**;**M4/M5 为配送域单独态**(可理解为 **配送域一条影子/主数据**,与 current 热行通过 `order_id` / `delivery_order_code` / 快照关联)。
### 2.3a 订单取消(特殊路径:标记后进 M4)
@ -132,14 +132,15 @@
- **时间策略**:**所有订单类型均受时间维度约束,不另开例外**;**进入 M6(物理归档)后不可逆**,**不允许任何例外**(不设司法解冻、不设未归档回退通道)。
- **谁可以进 M6(物理)**:**仅 M4、M5** 对应的配送域数据(及与其绑定的明细快照)允许在满足保留期后 **迁入 `history` / 冷存储**。
- **谁不可以进 M6**:**M1、M2、M3、M7** 热区行 **不允许** 走与 M4/M5 **相同的** M6(history)迁入通道;**到期后仅允许「克隆续单」**:通过 **新行(新主键)** 承接后续履约,原行 **仅改标记**(§2.7),**不得**删/软删、**不得**将原行迁入 M6。
- **谁不可以进 M6**:**M1、M2、M3、outsourced** 热区行 **不允许** 走与 M4/M5 **相同的** M6(history)迁入通道;**到期后仅允许「克隆续单」**:通过 **新行(新主键)** 承接后续履约,原行 **仅改标记**(§2.7),**不得**删/软删、**不得**将原行迁入 M6。
- **克隆续单 / 补单(首期)**:**不与奇门等平台同步**;定位为 **补单**,由 **人工在仓内/运营侧处理**;系统可提供列表与标记能力,**接口与对账范围以本仓 WMS 为准**。
- **M4/M5 → M6**:以 **出库时间**(如 `delivery_time` / 出库确认时间)为主键条件之一,满足 **>3 个月**(与 §1.2 口径对齐)后迁入 history;过程 **不可逆**。
### 2.5 配送域工厂(规划)
### 2.5 配送域工厂(首期落地 + 后续)
- **单独工厂**:M4/M5 **不共用** `OrderDeliveryFactory` 的 current 物理表;新建 **配送域工厂**,**model 定义仍由工厂类统一加载/缓存/分表键管理**(与现有工厂模式一致),**事务边界与分区键强绑定**(**事务驱动强分区**:单事务内读写同一分区键,如 `warehouseId + yyyyMM`)。
- **自然月**:表名或 MySQL PARTITION 与 **自然月** 对齐,保留 **3 个自然月** 滚动窗口。
- **已实现**:`app/model/order_delivery_factory.js` 的 dispatch 模式;物理表 **`wms_order_delivery_dispatch_{warehouseId}`**(与热区 `wms_order_delivery_{wh}` 命名同族,中间段 **`dispatch`**);**M4/M5 同表**,列 **`dispatch_lane` ENUM('m4','m5')** 区分;**不按自然月拆物理表**。`getDispatchModel(wh)` 为主入口;`getM4Model`/`getM5Model` 复用同一 dispatch 模式返回 **同一模型**。**outsourced 也已经纳入同一工厂管理,应用启动时会通过自检自动对齐 managed table 结构**。
- **单测**:`test/app/model/order_delivery_dispatch_factory.test.js`;需连库时 `DISPATCH_FACTORY_TEST_MYSQL=1`(见 `config/plugin.js`);留表排查 `KEEP_DISPATCH_FACTORY_TABLES=1`。
- **仍待**:与 current 的 **副本同步 / 事件驱动**;**强分区事务** 口径改为「单事务内同一 `warehouse_id` + 配送域表」即可(不再绑定 `yyyyMM` 表名);`wms_order_express` 与配送域行关联方案;M6 迁入仍以 **出库时间 + 保留期** 驱动(§2.4)。
### 2.6 M4/M5 副本回归 M1 / M2 / M3(补发 / 部分履约)
@ -160,9 +161,9 @@
|------|------|
| M1 ⊥ (M2 ∪ M3) | 不变 |
| M2 ⊥ M3 | 不变 |
| **M2 ⊥ M7** | **强制互斥**;切换须 **事务**(§2.1) |
| **M2 ⊥ outsourced** | **强制互斥**;切换须 **事务**(§2.1) |
| M5 ⊆ M4 | 不变 |
| **M1~M3 / M7(热区)** | **同一订单唯一展示态**(互斥集合内择一) |
| **M1~M3 / outsourced(热区)** | **同一订单唯一展示态**(互斥集合内择一) |
| **M4 / M5** | **配送域内**可与热区并存为 **影子数据**;列表层需约定「主工作台只显示一侧」避免重复操作 |
| **M6** | **仅 M4/M5 可物理迁入**;**不可逆、零例外**;热区到期 **不进 M6**,**仅允许克隆续单**(§2.4) |
@ -172,12 +173,12 @@
### 3.1 列表查询(各模块)
**目标**:最小可用字段集 + **足够前端判断订单状态**(含 M7 外仓标记若存在)。
**目标**:最小可用字段集 + **足够前端判断订单状态**(含 outsourced 外仓标记若存在)。
**原则**:
- 列表不返回大体积 `items` TEXT;仅标识、各 `*_status`、`outbound_status`、`inspection_status`、`step`、`updated_at` / `delivery_time`、货主/仓编码等。
- 实现:**按模块常量 `LIST_FIELDS`**;M4/M5/M7 在配送域或扩展表就绪后各自维护一份。
- 实现:**按模块常量 `LIST_FIELDS`**;M4/M5/outsourced 在配送域或扩展表就绪后各自维护一份。
### 3.2 明细查询
@ -206,35 +207,38 @@
| 2026-04-10 | **无业务代码 / 无 migration 变更**。新增只读交付物:`docs/order-cancel-db-checklist.md`(§0.7 跑库步骤)、`docs/order-state-machine-dictionary.md`(状态机字典 **v0 骨架**,与 `app/model/order_delivery.js` 摘录一致)。**数仓映射、实际跑库结果** 仍待下一小阶段。 |
| 2026-04-10 | **小阶段 A-1(影响面)**:新增 `docs/order-delivery-migration-impact.md`。**结论**:在未跑库确认缺列、且未敲定「取消进 M4」专用列前,**不自动提交 ALTER migration**;若清单验证列已齐,可先 **零表变更** 做应用筛选。详见该文档 **§1**。 |
| 2026-04-10 | **小阶段 A-2(wms-db-agent 只读诊断)**:已对 `wms` 库跑清单;结果写入 **`docs/order-cancel-db-checklist.md` §5**。要点:**分表** `100000`/`1000028` 目标列齐全,可先不增列做筛选;**基表**缺三列、**勿**当业务表用;**无 `_history` 样本**;`chcp 65001` 防 JSON 解析失败。 |
| 2026-04-11 | **基表状态列**:migration `20260410200000-add-status-columns-to-wms-order-delivery-base.js`(按需补列,与热区分表对齐)。**配送域**:`OrderDeliveryFactory` 的 dispatch 模式单表 `wms_order_delivery_dispatch_{wh}` + `dispatch_lane`;当前按单表落地,不再保留「m4/m5 分表 + 自然月表名」方案;单测与 `DISPATCH_FACTORY_TEST_MYSQL` 见上文 §2.5。 |
| 2026-04-11 | **outsourced 收敛**:`outsourced` 纳入 `OrderDeliveryFactory` 的 managed table / schema self-check 体系,沿用启动自检自动对齐结构;旧兼容 shim 已移除,文档与代码统一收口到工厂管理。 |
### 阶段 A — 文档与规则冻结
- [ ] 货主配置:「创建进 M1 / M2」的配置项落库位置与变更流程。
- [ ] M1→M2:库存校验 API、M7 推送接口与回写字段。
- [x] 货主配置:「创建进 M1 / M2」的配置项落库位置与变更流程。
- [ ] M1→M2:库存校验 API、outsourced 推送接口与回写字段。
- [ ] 外部「发货完成」通知与状态机字段的映射表(落到 `outbound_status` / `step` 等)。
- [x] **§0.7 清单文档**:`docs/order-cancel-db-checklist.md`(各环境人工执行)。
- [x] **§0.7 跑库(本机 wms 一次)**:见 `docs/order-cancel-db-checklist.md` §5;**分表列齐**;**其它仓/生产须复跑**。
- [ ] **§0.7 缺列 migration**:若产品仍要独立「取消进 M4」列或基表对齐,再开 migration;更新模型与工厂 DDL。
- [x] **§0.7 基表状态列 migration**(与分表枚举对齐):`database/migrations/20260410200000-add-status-columns-to-wms-order-delivery-base.js`(已合并进仓库;其它环境须自行 `db:migrate`)。**独立「取消进 M4」业务列** 仍待产品定名后再 migration。
- [x] **状态机字典 v0 骨架**:`docs/order-state-machine-dictionary.md`(与数仓/报表的 **字段映射表** 仍待补)。
- [x] **订单表 DDL 影响面分析**:`docs/order-delivery-migration-impact.md`(结论:**未自动做 migration**,待跑库 + 列名后由你决策)。
- [x] **订单表 DDL 影响面分析**:`docs/order-delivery-migration-impact.md`(初版静态结论;**2026-04-11** 起基表状态列以已合并 migration 为准,文档全文若与现网不一致须择机修订)。
### 阶段 B — 配送域工厂(3 自然月 + 强分区事务)
- [ ] 配送域工厂类设计(命名、目录、`app.js` 挂载)。
- [ ] M4/M5 表结构、与 current 的 **副本同步** 或 **事件驱动** 方案。
- [ ] `wms_order_express` 与配送域 **order_id + 分区键** 一致性方案。
- [x] 配送域建表能力(`OrderDeliveryFactory` 的 dispatch 模式):表 **`wms_order_delivery_dispatch_{warehouseId}`**,**`dispatch_lane`** 区分 M4/M5。
- [x] M4/M5 **单表** DDL 与动态模型(首期)。
- [ ] 与 current 的 **副本同步** 或 **事件驱动** 方案(未做)。
- [ ] `wms_order_express` 与配送域 **order_id**(及仓)一致性方案。
### 阶段 C — 归档 M6 + 时间消除
- [ ] **仅 M4/M5**:配送域 → history 的 **出库时间** 驱动任务;**不可逆** 校验与审计(**零例外**)。
- [ ] **M1/M2/M3/M7**:到期 **仅克隆续单** 流程(新行 + 原行标记);**禁止** 迁入 M6;前端 **空态/引导续单** 文案。
- [ ] **M1/M2/M3/outsourced**:到期 **仅克隆续单** 流程(新行 + 原行标记);**禁止** 迁入 M6;前端 **空态/引导续单** 文案。
- [ ] **取消进 M4**:状态机字段字典、事务边界、与常规 M4 列表的 **展示分区**(避免与正常配送混淆)。
- [ ] 全库 **禁止 DELETE/软删** 副本与主单的 ORM/脚本审计;运维修正走 **状态机变更**(§2.7);**审批流** 见 **§5a 预留**。
### 阶段 D — 补发副本与目标更新
- [ ] 补发单模型、原单引用、部分行、目标更新字段;**原行仅标记,禁止删/软删**。
- [ ] 事务:副本创建 + 热区插入 + 配送域标记 **同一强分区键内** 或可补偿 Saga;与 **M2↔M7 事务切换** 共用事务规范文档。
- [ ] 事务:副本创建 + 热区插入 + 配送域标记 **同一强分区键内** 或可补偿 Saga;与 **M2↔outsourced 事务切换** 共用事务规范文档。
### 阶段 E — API / 测试
@ -273,11 +277,12 @@
| 日期 | 说明 |
|------|------|
| (首版) | 根据讨论整理计划草案 |
| 补充 | 增加 §0 当前表/模型/工厂/关联分析;M7、创建分流、进入 M4 约束、外部驱动 M4/M5、时间进 M6、配送域独立工厂与强分区事务、M4/M5 按出库时间进 M6、补发副本回归 M1/2/3 |
| 补充 | **M2⊥M7 且事务进出**;**M6 仅 M4/M5 可物理迁入、不可逆**;热区到期不进 M6;**全副本禁止删/软删、仅标记或克隆**;§2.7 硬约束、§1.2/阶段 C/待补充项同步 |
| 补充 | 增加 §0 当前表/模型/工厂/关联分析;outsourced、创建分流、进入 M4 约束、外部驱动 M4/M5、时间进 M6、配送域独立工厂与强分区事务、M4/M5 按出库时间进 M6、补发副本回归 M1/2/3 |
| 补充 | **M2⊥outsourced 且事务进出**;**M6 仅 M4/M5 可物理迁入、不可逆**;热区到期不进 M6;**全副本禁止删/软删、仅标记或克隆**;§2.7 硬约束、§1.2/阶段 C/待补充项同步 |
| 补充 | 热区到期 **仅克隆续单**;**§2.3a 取消→标记→直进 M4、不可逆零例外**;**运维「克隆」= 状态机合法变更** 写入 §2.2/§2.7/阶段 C |
| 补充 | **§0.7** 取消状态机与分表核对/缺列 migration;**克隆续单不奇门同步、首期人工补单**;**字段字典与数仓报表同步**;**§5a 运维审批预留** |
| 补充 | **§5 重写**:区分 **规则层已满足** vs **交付层未完成**;原 checklist 拆入 §5.1 / §5.2 并指向 §4 |
| 2026-04-10 | **小阶段 A-0**:新增 `docs/order-cancel-db-checklist.md`、`docs/order-state-machine-dictionary.md`;§0.7 / §4 阶段 A / §5.2 同步;无代码变更 |
| 2026-04-10 | **小阶段 A-1**:`docs/order-delivery-migration-impact.md`;**未提交 migration**(待你根据跑库 + 列名决策) |
| 2026-04-10 | **小阶段 A-2**:wms-db-agent 只读诊断;`order-cancel-db-checklist.md` §5;**未提交 migration** |
| 2026-04-11 | **配送域单表工厂** + **基表 migration**;§1.2 / §2.5 / §4 阶段 B 勾选与表述同步 |

View File

@ -46,6 +46,8 @@
"file-writer:pressure": "node ./temp/generated-tests/file-writer-pressure.generated.test.cjs",
"debug:webhook:receiver": "node ./script/debug-webhook-receiver.cjs",
"debug:webhook:receiving": "node ./script/debug-send-receiving-webhooks.cjs",
"doc:api:update": "node ./script/update-api-doc.cjs",
"doc:api:update:dry": "node ./script/update-api-doc.cjs --dry-run",
"deploy:init": "node ./script/deploy-init.cjs production",
"deploy:init:dry": "node ./script/deploy-init.cjs production --dry-run",
"deploy:precheck": "node ./script/deploy-precheck.cjs",
@ -67,6 +69,7 @@
"setup:hooks": "node ./script/setup-git-hooks.cjs",
"test": "npm run lint -- --fix && npm run test:local",
"test:local": "egg-bin test",
"test:dispatch-factory": "egg-bin test test/app/model/order_delivery_dispatch_factory.test.js",
"cov": "egg-bin cov",
"lint": "eslint .",
"permission:sync:system-api": "node ./script/sync-system-api-permission.cjs",

View File

@ -1 +1 @@
{"startedAt":1775826309321,"recordCount":2}
{"startedAt":1776007031826,"recordCount":1}

View File

@ -1,7 +1,7 @@
{
"filePath": "D:\\wms\\runtime\\file-writer\\qimen-logs\\2026\\04\\10\\qimen-logs-MINGREN-worker-p4496-0001.log",
"offset": 6149,
"processedCount": 2,
"completedAt": "2026-04-10T14:20:54.561Z",
"updatedAt": "2026-04-11T09:08:50.539Z"
"filePath": "D:\\wms\\runtime\\file-writer\\qimen-logs\\2026\\04\\12\\qimen-logs-MINGREN-worker-p42648-0001.log",
"offset": 1713,
"processedCount": 1,
"completedAt": "2026-04-12T14:54:22.636Z",
"updatedAt": "2026-04-16T11:59:44.134Z"
}

View File

@ -0,0 +1,7 @@
{
"filePath": "D:\\wms\\runtime\\file-writer\\qimen-logs\\2026\\04\\10\\qimen-logs-MINGREN-worker-p4496-0001.log",
"offset": 6149,
"processedCount": 2,
"completedAt": "2026-04-10T14:20:54.561Z",
"updatedAt": "2026-04-11T21:11:35.725Z"
}

View File

@ -0,0 +1 @@
{"log_id":"QL-1776005200436-dfa9d6","from_key":"24869601","to_key":23535631,"method":"deliveryorder.create","sign":"74F6AD27E9412E9F1DABEBD72FBB0FD6","costomer_id":"jky2025102001","v":"2.0","url":"http://127.0.0.1:6060/qimen?app_key=24869601&method=deliveryorder.create&v=2.0&format=xml&sign_method=md5&timestamp=1776005200&customerId=jky2025102001&sign=74F6AD27E9412E9F1DABEBD72FBB0FD6","created_at":"2026-04-12T14:46:40.436Z","body":"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<request>\n <deliveryOrder>\n <deliveryOrderCode>TRACE_OUTBOUND_1776005196546_B37AA0C5</deliveryOrderCode>\n <sourcePlatformCode>TAOBAO</sourcePlatformCode>\n <sourcePlatformName>淘宝</sourcePlatformName>\n <warehouseCode>100000</warehouseCode>\n <orderType>JYCK</orderType>\n <receiverInfo>\n <name>自动化验证收件人</name>\n <mobile>13800138000</mobile>\n <province>广东省</province>\n <city>广州市</city>\n <area>黄埔区</area>\n <town>知识城街道</town>\n <detailAddress>自动化验证地址 TRACE_OUTBOUND_1776005196546_B37AA0C5</detailAddress>\n <zipCode>510000</zipCode>\n </receiverInfo>\n </deliveryOrder>\n <orderLines>\n <orderLine>\n <itemId>101391</itemId>\n <itemCode>023802</itemCode>\n <itemName>空包</itemName>\n <planQty>1</planQty>\n <orderLineNo>1</orderLineNo>\n </orderLine>\n </orderLines>\n</request>","result":"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<response>\n <flag>failure</flag>\n <code>0</code>\n <message>奇门吉客云ERP客户编码jky2025102001仓库编码warehouseCode未绑定到你的货主或未启用,请联系仓库绑定</message>\n</response>","use_time":92}

View File

@ -0,0 +1,7 @@
{
"filePath": "D:\\wms\\runtime\\file-writer\\qimen-logs\\2026\\04\\12\\qimen-logs-MINGREN-worker-p38224-0001.log",
"offset": 1713,
"processedCount": 1,
"completedAt": "2026-04-12T14:46:52.525Z",
"updatedAt": "2026-04-12T14:46:52.525Z"
}

View File

@ -0,0 +1,4 @@
{"log_id":"QL-1776005884434-818312","from_key":"24869601","to_key":23535631,"method":"deliveryorder.create","sign":"C591375BD641DD47560872675F5CCA0E","costomer_id":"jky2025102001","v":"2.0","url":"http://127.0.0.1:6060/qimen?app_key=24869601&method=deliveryorder.create&v=2.0&format=xml&sign_method=md5&timestamp=1776005884&customerId=jky2025102001&sign=C591375BD641DD47560872675F5CCA0E","created_at":"2026-04-12T14:58:04.434Z","body":"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<request>\n <deliveryOrder>\n <deliveryOrderCode>TRACE_OUTBOUND_1776005880432_FA93FDAF</deliveryOrderCode>\n <sourcePlatformCode>TAOBAO</sourcePlatformCode>\n <sourcePlatformName>淘宝</sourcePlatformName>\n <warehouseCode>100000</warehouseCode>\n <orderType>JYCK</orderType>\n <receiverInfo>\n <name>自动化验证收件人</name>\n <mobile>13800138000</mobile>\n <province>广东省</province>\n <city>广州市</city>\n <area>黄埔区</area>\n <town>知识城街道</town>\n <detailAddress>自动化验证地址 TRACE_OUTBOUND_1776005880432_FA93FDAF</detailAddress>\n <zipCode>510000</zipCode>\n </receiverInfo>\n </deliveryOrder>\n <orderLines>\n <orderLine>\n <itemId>101391</itemId>\n <itemCode>023802</itemCode>\n <itemName>空包</itemName>\n <planQty>1</planQty>\n <orderLineNo>1</orderLineNo>\n </orderLine>\n </orderLines>\n</request>","result":"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<response>\n <flag>failure</flag>\n <code>0</code>\n <message>奇门吉客云ERP客户编码jky2025102001仓库编码warehouseCode未绑定到你的货主或未启用,请联系仓库绑定</message>\n</response>","use_time":91}
{"log_id":"QL-1776006129287-77b8d4","from_key":"24869601","to_key":23535631,"method":"deliveryorder.create","sign":"A0B72528AC9B54B0DDA564298B20E7C0","costomer_id":"jky2025102001","v":"2.0","url":"http://127.0.0.1:6060/qimen?app_key=24869601&method=deliveryorder.create&v=2.0&format=xml&sign_method=md5&timestamp=1776006129&customerId=jky2025102001&sign=A0B72528AC9B54B0DDA564298B20E7C0","created_at":"2026-04-12T15:02:09.287Z","body":"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<request>\n <deliveryOrder>\n <deliveryOrderCode>TRACE_OUTBOUND_1776006125376_39EA41AC</deliveryOrderCode>\n <sourcePlatformCode>TB</sourcePlatformCode>\n <sourcePlatformName>淘宝</sourcePlatformName>\n <warehouseCode>100000</warehouseCode>\n <orderType>JYCK</orderType>\n <receiverInfo>\n <name>自动化验证收件人</name>\n <mobile>13800138000</mobile>\n <province>广东省</province>\n <city>广州市</city>\n <area>黄埔区</area>\n <town>知识城街道</town>\n <detailAddress>自动化验证地址 TRACE_OUTBOUND_1776006125376_39EA41AC</detailAddress>\n <zipCode>510000</zipCode>\n </receiverInfo>\n </deliveryOrder>\n <orderLines>\n <orderLine>\n <itemId>101391</itemId>\n <itemCode>023802</itemCode>\n <itemName>空包</itemName>\n <planQty>1</planQty>\n <orderLineNo>1</orderLineNo>\n </orderLine>\n </orderLines>\n</request>","result":"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<response>\n <flag>failure</flag>\n <code>0</code>\n <message>奇门吉客云ERP客户编码jky2025102001仓库编码warehouseCode未绑定到你的货主或未启用,请联系仓库绑定</message>\n</response>","use_time":88}
{"log_id":"QL-1776006776809-5dbb53","from_key":"24869601","to_key":23535631,"method":"deliveryorder.create","sign":"65632055E9198D2C8E466A44D0EF0D4C","costomer_id":"jky2025102001","v":"2.0","url":"http://127.0.0.1:6060/qimen?app_key=24869601&method=deliveryorder.create&v=2.0&format=xml&sign_method=md5&timestamp=1776006776&customerId=jky2025102001&sign=65632055E9198D2C8E466A44D0EF0D4C","created_at":"2026-04-12T15:12:56.809Z","body":"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<request>\n <deliveryOrder>\n <deliveryOrderCode>TRACE_OUTBOUND_1776006772829_A0ADB113</deliveryOrderCode>\n <sourcePlatformCode>TB</sourcePlatformCode>\n <sourcePlatformName>淘宝</sourcePlatformName>\n <warehouseCode>100000</warehouseCode>\n <orderType>JYCK</orderType>\n <receiverInfo>\n <name>自动化验证收件人</name>\n <mobile>13800138000</mobile>\n <province>广东省</province>\n <city>广州市</city>\n <area>黄埔区</area>\n <town>知识城街道</town>\n <detailAddress>自动化验证地址 TRACE_OUTBOUND_1776006772829_A0ADB113</detailAddress>\n <zipCode>510000</zipCode>\n </receiverInfo>\n </deliveryOrder>\n <orderLines>\n <orderLine>\n <itemId>101391</itemId>\n <itemCode>023802</itemCode>\n <itemName>空包</itemName>\n <planQty>1</planQty>\n <orderLineNo>1</orderLineNo>\n </orderLine>\n </orderLines>\n</request>","result":"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<response>\n <flag>failure</flag>\n <code>0</code>\n <message>奇门吉客云ERP客户编码jky2025102001仓库编码warehouseCode未绑定到你的货主或未启用,请联系仓库绑定</message>\n</response>","use_time":95}
{"log_id":"QL-1776007031740-155ce0","from_key":"24869601","to_key":23535631,"method":"deliveryorder.create","sign":"AE833C70C726B4B6664544B5A7B412EF","costomer_id":"jky2025102001","v":"2.0","url":"http://127.0.0.1:6060/qimen?app_key=24869601&method=deliveryorder.create&v=2.0&format=xml&sign_method=md5&timestamp=1776007031&customerId=jky2025102001&sign=AE833C70C726B4B6664544B5A7B412EF","created_at":"2026-04-12T15:17:11.740Z","body":"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<request>\n <deliveryOrder>\n <deliveryOrderCode>TRACE_OUTBOUND_1776007027818_0E2C252D</deliveryOrderCode>\n <sourcePlatformCode>TB</sourcePlatformCode>\n <sourcePlatformName>淘宝</sourcePlatformName>\n <warehouseCode>100000</warehouseCode>\n <orderType>JYCK</orderType>\n <receiverInfo>\n <name>自动化验证收件人</name>\n <mobile>13800138000</mobile>\n <province>广东省</province>\n <city>广州市</city>\n <area>黄埔区</area>\n <town>知识城街道</town>\n <detailAddress>自动化验证地址 TRACE_OUTBOUND_1776007027818_0E2C252D</detailAddress>\n <zipCode>510000</zipCode>\n </receiverInfo>\n </deliveryOrder>\n <orderLines>\n <orderLine>\n <itemId>1000218</itemId>\n <itemCode>023802</itemCode>\n <itemName>空包</itemName>\n <planQty>1</planQty>\n <orderLineNo>1</orderLineNo>\n </orderLine>\n </orderLines>\n</request>","result":"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<response>\n <flag>failure</flag>\n <code>0</code>\n <message>奇门吉客云ERP客户编码jky2025102001仓库编码warehouseCode未绑定到你的货主或未启用,请联系仓库绑定</message>\n</response>","use_time":86}

View File

@ -0,0 +1 @@
{"log_id":"QL-1776005653930-b9f1fa","from_key":"24869601","to_key":23535631,"method":"deliveryorder.create","sign":"4AB934D12D74B558BE1060D5525EFF7B","costomer_id":"jky2025102001","v":"2.0","url":"http://127.0.0.1:6060/qimen?app_key=24869601&method=deliveryorder.create&v=2.0&format=xml&sign_method=md5&timestamp=1776005653&customerId=jky2025102001&sign=4AB934D12D74B558BE1060D5525EFF7B","created_at":"2026-04-12T14:54:13.931Z","body":"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<request>\n <deliveryOrder>\n <deliveryOrderCode>TRACE_OUTBOUND_1776005649940_B0FA5A9A</deliveryOrderCode>\n <sourcePlatformCode>TAOBAO</sourcePlatformCode>\n <sourcePlatformName>淘宝</sourcePlatformName>\n <warehouseCode>100000</warehouseCode>\n <orderType>JYCK</orderType>\n <receiverInfo>\n <name>自动化验证收件人</name>\n <mobile>13800138000</mobile>\n <province>广东省</province>\n <city>广州市</city>\n <area>黄埔区</area>\n <town>知识城街道</town>\n <detailAddress>自动化验证地址 TRACE_OUTBOUND_1776005649940_B0FA5A9A</detailAddress>\n <zipCode>510000</zipCode>\n </receiverInfo>\n </deliveryOrder>\n <orderLines>\n <orderLine>\n <itemId>101391</itemId>\n <itemCode>023802</itemCode>\n <itemName>空包</itemName>\n <planQty>1</planQty>\n <orderLineNo>1</orderLineNo>\n </orderLine>\n </orderLines>\n</request>","result":"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<response>\n <flag>failure</flag>\n <code>0</code>\n <message>奇门吉客云ERP客户编码jky2025102001仓库编码warehouseCode未绑定到你的货主或未启用,请联系仓库绑定</message>\n</response>","use_time":93}

View File

@ -0,0 +1,7 @@
{
"filePath": "D:\\wms\\runtime\\file-writer\\qimen-logs\\2026\\04\\12\\qimen-logs-MINGREN-worker-p42648-0001.log",
"offset": 1713,
"processedCount": 1,
"completedAt": "2026-04-12T14:54:22.636Z",
"updatedAt": "2026-04-12T14:54:22.636Z"
}

387
script/update-api-doc.cjs Normal file
View File

@ -0,0 +1,387 @@
const fs = require('fs');
const path = require('path');
const ROOT = process.cwd();
const METHODS_DIR = path.join(ROOT, 'methods');
const CHANGES_DIR = path.join(METHODS_DIR, 'changes');
function parseArgs(argv) {
const args = {
specPath: '',
dryRun: false,
docOnly: false,
help: false,
};
for (const item of argv) {
if (item === '--dry-run') {
args.dryRun = true;
continue;
}
if (item === '--doc-only') {
args.docOnly = true;
continue;
}
if (item === '--help' || item === '-h') {
args.help = true;
continue;
}
if (item.startsWith('--spec=')) {
const raw = String(item.slice('--spec='.length)).trim();
args.specPath = raw ? path.resolve(ROOT, raw) : '';
continue;
}
}
if (!args.help && !args.specPath) {
throw new Error('Missing required --spec=<path> argument.');
}
return args;
}
function printHelp() {
console.log([
'Usage:',
' npm run doc:api:update -- --spec=temp/api-doc-update.json',
' npm run doc:api:update -- --spec=temp/api-doc-update.json --dry-run',
' npm run doc:api:update -- --spec=temp/api-doc-update.json --doc-only',
'',
'Options:',
' --spec=<path> Path to the fixed update spec JSON file.',
' --dry-run Validate and print the planned changes without writing files.',
' --doc-only Update methods/<docName>.json only and skip methods/changes/<docName>.json.',
].join('\n'));
}
function isPlainObject(value) {
return value !== null && typeof value === 'object' && !Array.isArray(value);
}
function assert(condition, message) {
if (!condition) {
throw new Error(message);
}
}
function readJsonFile(filePath) {
const raw = fs.readFileSync(filePath, 'utf8');
return {
json: JSON.parse(raw),
indent: detectIndent(raw),
eol: detectEol(raw),
};
}
function detectIndent(raw) {
const match = raw.match(/^([ \t]+)"[^"]+":/m);
return match ? match[1] : ' ';
}
function detectEol(raw) {
return raw.includes('\r\n') ? '\r\n' : '\n';
}
function writeJsonFile(filePath, value, indent, eol) {
const formatted = JSON.stringify(value, null, indent).replace(/\n/g, eol);
fs.writeFileSync(filePath, `${formatted}${eol}`, 'utf8');
}
function ensureString(value, fieldPath) {
assert(typeof value === 'string' && value.trim(), `${fieldPath} must be a non-empty string.`);
}
function ensureBoolean(value, fieldPath) {
assert(typeof value === 'boolean', `${fieldPath} must be a boolean.`);
}
function ensureArray(value, fieldPath) {
assert(Array.isArray(value), `${fieldPath} must be an array.`);
}
function ensureStringArray(value, fieldPath) {
ensureArray(value, fieldPath);
value.forEach((item, index) => ensureString(item, `${fieldPath}[${index}]`));
}
function validateListOption(option, fieldPath) {
assert(isPlainObject(option), `${fieldPath} must be an object.`);
const hasValue = Object.prototype.hasOwnProperty.call(option, 'value');
assert(hasValue, `${fieldPath}.value is required.`);
}
function validateNamedField(field, fieldPath, allowSource) {
assert(isPlainObject(field), `${fieldPath} must be an object.`);
ensureString(field.name, `${fieldPath}.name`);
ensureString(field.type, `${fieldPath}.type`);
ensureBoolean(field.required, `${fieldPath}.required`);
ensureString(field.description, `${fieldPath}.description`);
if (allowSource && Object.prototype.hasOwnProperty.call(field, 'source')) {
ensureString(field.source, `${fieldPath}.source`);
}
if (Object.prototype.hasOwnProperty.call(field, 'list')) {
ensureArray(field.list, `${fieldPath}.list`);
field.list.forEach((item, index) => validateListOption(item, `${fieldPath}.list[${index}]`));
}
}
function validateErrorField(field, fieldPath) {
assert(isPlainObject(field), `${fieldPath} must be an object.`);
assert(Object.prototype.hasOwnProperty.call(field, 'code'), `${fieldPath}.code is required.`);
ensureString(field.message, `${fieldPath}.message`);
}
function validateMethodDoc(methodDoc, fieldPath) {
assert(isPlainObject(methodDoc), `${fieldPath} must be an object.`);
ensureString(methodDoc.method, `${fieldPath}.method`);
ensureString(methodDoc.description, `${fieldPath}.description`);
ensureBoolean(methodDoc.isNeedAuth, `${fieldPath}.isNeedAuth`);
ensureBoolean(methodDoc.isNeedLogin, `${fieldPath}.isNeedLogin`);
ensureArray(methodDoc.headers, `${fieldPath}.headers`);
ensureArray(methodDoc.params, `${fieldPath}.params`);
ensureArray(methodDoc.response, `${fieldPath}.response`);
ensureArray(methodDoc.errors, `${fieldPath}.errors`);
methodDoc.headers.forEach((item, index) => validateNamedField(item, `${fieldPath}.headers[${index}]`, false));
methodDoc.params.forEach((item, index) => validateNamedField(item, `${fieldPath}.params[${index}]`, true));
methodDoc.response.forEach((item, index) => validateNamedField(item, `${fieldPath}.response[${index}]`, false));
methodDoc.errors.forEach((item, index) => validateErrorField(item, `${fieldPath}.errors[${index}]`));
}
function validateChange(change, fieldPath) {
assert(isPlainObject(change), `${fieldPath} must be an object.`);
ensureString(change.version, `${fieldPath}.version`);
ensureString(change.date, `${fieldPath}.date`);
ensureString(change.summary, `${fieldPath}.summary`);
ensureStringArray(change.methods, `${fieldPath}.methods`);
ensureStringArray(change.notes, `${fieldPath}.notes`);
if (Object.prototype.hasOwnProperty.call(change, 'type')) {
ensureString(change.type, `${fieldPath}.type`);
}
}
function validateCurrentDoc(doc, fieldPath) {
assert(isPlainObject(doc), `${fieldPath} must be an object.`);
assert(isPlainObject(doc.methods), `${fieldPath}.methods must be an object.`);
ensureArray(doc.methods.groups, `${fieldPath}.methods.groups`);
}
function validateCurrentChanges(changes, fieldPath) {
ensureArray(changes, fieldPath);
}
function validateSpec(spec, args) {
assert(isPlainObject(spec), 'Spec root must be an object.');
ensureString(spec.docName, 'spec.docName');
assert(/^[a-z0-9_-]+$/i.test(spec.docName), 'spec.docName must contain only letters, numbers, underscore, or dash.');
const docPath = path.join(METHODS_DIR, `${spec.docName}.json`);
const changePath = path.join(CHANGES_DIR, `${spec.docName}.json`);
assert(fs.existsSync(docPath), `Target doc file not found: ${docPath}`);
if (!args.docOnly) {
assert(fs.existsSync(changePath), `Target change file not found: ${changePath}`);
}
if (Object.prototype.hasOwnProperty.call(spec, 'docMeta')) {
assert(isPlainObject(spec.docMeta), 'spec.docMeta must be an object.');
if (Object.prototype.hasOwnProperty.call(spec.docMeta, 'updatedAt')) {
ensureString(spec.docMeta.updatedAt, 'spec.docMeta.updatedAt');
}
if (Object.prototype.hasOwnProperty.call(spec.docMeta, 'version')) {
ensureString(spec.docMeta.version, 'spec.docMeta.version');
}
}
assert(isPlainObject(spec.group), 'spec.group must be an object.');
ensureString(spec.group.groupName, 'spec.group.groupName');
ensureString(spec.group.module, 'spec.group.module');
ensureArray(spec.methods, 'spec.methods');
assert(spec.methods.length > 0, 'spec.methods must contain at least one method doc.');
const methodNames = new Set();
spec.methods.forEach((item, index) => {
validateMethodDoc(item, `spec.methods[${index}]`);
assert(!methodNames.has(item.method), `Duplicate method in spec.methods: ${item.method}`);
methodNames.add(item.method);
});
if (!args.docOnly) {
validateChange(spec.change, 'spec.change');
} else if (Object.prototype.hasOwnProperty.call(spec, 'change')) {
validateChange(spec.change, 'spec.change');
}
return {
docName: spec.docName,
docPath,
changePath,
docMeta: spec.docMeta || {},
group: spec.group,
methods: spec.methods,
change: spec.change || null,
};
}
function findGroupIndex(groups, groupSpec) {
const byModule = groups.findIndex(group => group && group.module === groupSpec.module);
if (byModule >= 0) return byModule;
return groups.findIndex(group => group && group.groupName === groupSpec.groupName);
}
function findMethodLocation(groups, methodName) {
for (let groupIndex = 0; groupIndex < groups.length; groupIndex += 1) {
const group = groups[groupIndex];
const list = group && Array.isArray(group.list) ? group.list : [];
const methodIndex = list.findIndex(item => item && item.method === methodName);
if (methodIndex >= 0) {
return { groupIndex, methodIndex };
}
}
return null;
}
function cloneJson(value) {
return JSON.parse(JSON.stringify(value));
}
function applyDocUpdate(doc, groupSpec, methods, docMeta) {
const groups = doc.methods.groups;
let groupIndex = findGroupIndex(groups, groupSpec);
if (groupIndex < 0) {
groups.push({
groupName: groupSpec.groupName,
module: groupSpec.module,
list: [],
});
groupIndex = groups.length - 1;
}
const targetGroup = groups[groupIndex];
targetGroup.groupName = groupSpec.groupName;
targetGroup.module = groupSpec.module;
if (!Array.isArray(targetGroup.list)) {
targetGroup.list = [];
}
const summary = {
inserted: [],
updated: [],
moved: [],
};
for (const methodDoc of methods) {
const nextMethod = cloneJson(methodDoc);
const existingLocation = findMethodLocation(groups, methodDoc.method);
if (!existingLocation) {
targetGroup.list.push(nextMethod);
summary.inserted.push(methodDoc.method);
continue;
}
if (existingLocation.groupIndex === groupIndex) {
targetGroup.list[existingLocation.methodIndex] = nextMethod;
summary.updated.push(methodDoc.method);
continue;
}
groups[existingLocation.groupIndex].list.splice(existingLocation.methodIndex, 1);
targetGroup.list.push(nextMethod);
summary.moved.push(methodDoc.method);
}
if (docMeta.updatedAt) {
doc.updatedAt = docMeta.updatedAt;
}
if (docMeta.version) {
doc.version = docMeta.version;
}
return summary;
}
function appendChange(changes, change) {
const exists = changes.some(item => item && item.version === change.version);
assert(!exists, `Duplicate change version detected: ${change.version}`);
changes.push(cloneJson(change));
}
function main() {
const args = parseArgs(process.argv.slice(2));
if (args.help) {
printHelp();
return;
}
assert(fs.existsSync(args.specPath), `Spec file not found: ${args.specPath}`);
const specRaw = fs.readFileSync(args.specPath, 'utf8');
const spec = JSON.parse(specRaw);
const normalized = validateSpec(spec, args);
const docState = readJsonFile(normalized.docPath);
validateCurrentDoc(docState.json, normalized.docPath);
let changeState = null;
if (!args.docOnly) {
changeState = readJsonFile(normalized.changePath);
validateCurrentChanges(changeState.json, normalized.changePath);
}
const docNext = cloneJson(docState.json);
const summary = applyDocUpdate(docNext, normalized.group, normalized.methods, normalized.docMeta);
JSON.parse(JSON.stringify(docNext));
let changeNext = null;
if (!args.docOnly) {
changeNext = cloneJson(changeState.json);
appendChange(changeNext, normalized.change);
JSON.parse(JSON.stringify(changeNext));
}
console.log(`docName: ${normalized.docName}`);
console.log(`group: ${normalized.group.module} (${normalized.group.groupName})`);
console.log(`inserted: ${summary.inserted.length ? summary.inserted.join(', ') : '-'}`);
console.log(`updated: ${summary.updated.length ? summary.updated.join(', ') : '-'}`);
console.log(`moved: ${summary.moved.length ? summary.moved.join(', ') : '-'}`);
if (!args.docOnly && normalized.change) {
console.log(`change version: ${normalized.change.version}`);
}
if (args.dryRun) {
console.log('dry-run: validated successfully, no files were written.');
return;
}
writeJsonFile(normalized.docPath, docNext, docState.indent, docState.eol);
console.log(`wrote: ${path.relative(ROOT, normalized.docPath)}`);
if (!args.docOnly) {
writeJsonFile(normalized.changePath, changeNext, changeState.indent, changeState.eol);
console.log(`wrote: ${path.relative(ROOT, normalized.changePath)}`);
}
}
if (require.main === module) {
try {
main();
} catch (error) {
console.error(error.message || error);
process.exitCode = 1;
}
}
module.exports = {
applyDocUpdate,
parseArgs,
validateSpec,
};

View File

@ -8,6 +8,47 @@ function hasSemanticKey(keys, candidates) {
}
describe('test/app/controller/docs.test.js', () => {
it('GET /docs should return an index page with docs file links', async () => {
const res = await app.httpRequest()
.get('/docs')
.expect('Content-Type', /html/)
.expect(200);
assert.match(res.text, /docs 目录索引/);
assert.match(res.text, /<window\b[^>]*data-window-href="\/docs\/order-workbench-list-api\.md"/i);
assert.doesNotMatch(res.text, /<li>\s*<a\b[^>]*href="\/docs\/order-workbench-list-api\.md"/i);
});
it('GET /docs/order-workbench-list-api.md should return markdown content', async () => {
const res = await app.httpRequest()
.get('/docs/order-workbench-list-api.md')
.expect('Content-Type', /text\/markdown/)
.expect(200);
assert.match(res.text, /^# 订单工作台 List 接口说明/m);
});
it('GET /docs should block path traversal attempts', async () => {
const res = await app.httpRequest()
.get('/docs/%2e%2e%2fapp.js')
.expect('Content-Type', /json/)
.expect(400);
assert.equal(Number(res.body.code), 400);
assert.match(String(res.body.message || ''), /无效|越界|path/i);
});
it('GET /api/docs/system should still be available', async () => {
const res = await app.httpRequest()
.get('/api/docs/system')
.expect('Content-Type', /html/)
.expect(200);
assert.match(res.text, /系统接口|API 文档/);
assert.match(res.text, /\/api\/docs\/system\/raw/);
assert.match(res.text, /<window\b[^>]*data-window-href="\/api\/docs\/system\/raw"/i);
});
it('GET /api/docs/system/changes should return 200 and a change-history JSON array', async () => {
const res = await app.httpRequest()
.get('/api/docs/system/changes')
@ -42,9 +83,9 @@ describe('test/app/controller/docs.test.js', () => {
.expect(200);
const html = res.text;
assert.match(html, /\/api\/docs\/system\/changes/, '页面中应提供 /api/docs/system/changes 入口');
assert.match(html, /<window\b[^>]*data-window-href="\/api\/docs\/system\/changes"/i, '页面中应提供 /api/docs/system/changes 的 window 入口');
assert.match(html, /查看变更记录|变更记录|changelog/i, '页面中应出现“查看变更记录”或同等入口文案');
assert.match(html, /\/api\/docs\/system\/raw/, '页面中应提供 /api/docs/system/raw 入口');
assert.match(html, /<window\b[^>]*data-window-href="\/api\/docs\/system\/raw"/i, '页面中应提供 /api/docs/system/raw 的 window 入口');
assert.match(html, /查看\s*JSON|raw\s*json/i, '页面中应出现“查看 JSON”入口');
});

View File

@ -7,14 +7,16 @@ const {
invokeGatewayMethod,
} = require('../../support/system_method_client');
const YE4S_TEST_USER_ID = Number(process.env.SYSTEM_TEST_YE4S_USER_ID);
describe('test/app/controller/gateway.user.bindAccountByTempCode.test.js', function() {
let YE4S_TEST_USER_ID;
assert.ok(
Number.isInteger(YE4S_TEST_USER_ID) && YE4S_TEST_USER_ID > 0,
'SYSTEM_TEST_YE4S_USER_ID 必须显式提供且为正整数'
);
before(function() {
YE4S_TEST_USER_ID = Number(process.env.SYSTEM_TEST_YE4S_USER_ID);
if (!Number.isInteger(YE4S_TEST_USER_ID) || YE4S_TEST_USER_ID <= 0) {
this.skip();
}
});
describe('test/app/controller/gateway.user.bindAccountByTempCode.test.js', () => {
it('should scan, bind, unbind, and bind again for ye4s user', async () => {
const { token } = await getAuthToken();

View File

@ -1,7 +1,9 @@
const { strict: assert } = require('node:assert');
const path = require('node:path');
const { statSync } = require('node:fs');
const { app } = require('egg-mock/bootstrap');
const { app, mm } = require('egg-mock/bootstrap');
const HomeController = require('../../../app/controller/home');
const PoloApiService = require('../../../app/service/systems/polo_api');
describe('test/app/controller/home.test.js', () => {
it('should assert', async () => {
@ -20,4 +22,99 @@ describe('test/app/controller/home.test.js', () => {
.expect('pong')
.expect(200);
});
it('should GET /testPoloApi return poloApi.test result directly', async () => {
const expectedResult = {
ok: true,
data: {
message: 'real result passthrough',
},
};
let callCount = 0;
try {
mm(PoloApiService.prototype, 'test', async () => {
callCount += 1;
return expectedResult;
});
const res = await app.httpRequest()
.get('/testPoloApi')
.expect('Content-Type', /json/)
.expect(200);
assert.deepEqual(res.body, expectedResult);
assert.equal(callCount, 1);
} finally {
mm.restore();
}
});
it('should extract qimen warehouseCode from controller helper', async () => {
const controller = Object.create(HomeController.prototype);
assert.equal(
controller.getQimenWarehouseCode({
request: {
deliveryOrder: {
warehouseCode: '100000',
},
},
}),
'100000'
);
assert.equal(
controller.getQimenWarehouseCode({
request: {
warehouseCode: 'warehouseCode',
deliveryOrder: {
warehouseCode: '100000',
},
},
}),
'100000'
);
assert.equal(
controller.getQimenWarehouseCode({
request: {
warehouseCode: 'warehouseCode',
deliveryOrder: {
warehouseCode: 'warehouseCode',
},
},
}),
''
);
assert.equal(
controller.getQimenWarehouseCode({
request: {
deliveryOrder: {
warehouseCode: '',
},
},
}),
''
);
});
it('should ignore unrelated string nodes when extracting qimen warehouseCode', async () => {
const controller = Object.create(HomeController.prototype);
assert.equal(
controller.getQimenWarehouseCode({
request: {
deliveryOrder: {
warehouseCode: 'warehouseCode',
orderStatus: '100000',
note: '真实请求里不应被这些字符串节点误命中',
},
traceId: '100000',
},
}),
''
);
});
});

View File

@ -0,0 +1,432 @@
'use strict';
const assert = require('node:assert/strict');
const crypto = require('node:crypto');
const {
getAuthToken,
invokeSystemMethod,
invokeQimenMethod,
} = require('../../support/system_method_client');
const EXTRA_HEADERS = {
platform: 'web',
project: 'all',
};
const FIXED_RELATION = {
storeId: 1000000,
warehouseId: 100000,
};
const FALLBACK_ROLE_IDS = [ 4, 6, 30 ];
/**
* 将字符串转义为 XML 安全文本。
* @param {string|number|null|undefined} value 待转义值。
* @return {string} 转义后的 XML 文本。
*/
function escapeXml(value) {
return String(value === null || value === undefined ? '' : value).replace(/[<>&'\"]/g, character => {
switch (character) {
case '<':
return '&lt;';
case '>':
return '&gt;';
case '&':
return '&amp;';
case '\'':
return '&apos;';
case '"':
return '&quot;';
default:
return character;
}
});
}
/**
* 从候选列表中挑选固定测试签约关系。
* @param {Array<object>} relations 签约关系列表。
* @return {object|null} 固定测试关系。
*/
function pickFixedTestRelation(relations) {
if (!Array.isArray(relations)) {
return null;
}
return relations.find(item => Number(item.store_id) === FIXED_RELATION.storeId
&& Number(item.warehouse_id) === FIXED_RELATION.warehouseId) || null;
}
/**
* 从接口配置列表中挑选一个已启用的 QM_WMS 配置。
* @param {Array<object>} configs 接口配置列表。
* @return {object|null} 可用奇门配置。
*/
function pickEnabledQimenConfig(configs) {
if (!Array.isArray(configs)) {
return null;
}
return configs.find(item => Number(item.is_enabled) === 1
&& (item.interface_category === 'QM_WMS' || item.interface_type?.interface_category === 'QM_WMS')) || null;
}
/**
* 从库存搜索结果中挑选一个可用 SKU。
* @param {Array<object>} stocks 库存搜索结果。
* @return {object|null} 可用 SKU。
*/
function pickUsableStock(stocks) {
if (!Array.isArray(stocks)) {
return null;
}
const resolveAvailableQuantity = item => {
const directAvailableFields = [
item?.available_quantity,
item?.availableQuantity,
item?.available,
];
for (const value of directAvailableFields) {
const numeric = Number(value);
if (Number.isFinite(numeric) && numeric > 0) {
return numeric;
}
}
const quantity = Number(item?.quantity);
const lockedQuantity = Number(item?.locked_quantity ?? item?.lockedQuantity ?? item?.lockQuantity);
if (Number.isFinite(quantity) && quantity > 0) {
const resolvedLocked = Number.isFinite(lockedQuantity) ? lockedQuantity : 0;
return Math.max(0, quantity - resolvedLocked);
}
const storageList = Array.isArray(item?.storage) ? item.storage : [];
for (const storageItem of storageList) {
const storageAvailable = Number(storageItem?.available_quantity ?? storageItem?.availableQuantity ?? storageItem?.available);
if (Number.isFinite(storageAvailable) && storageAvailable > 0) {
return storageAvailable;
}
const storageQuantity = Number(storageItem?.quantity);
const storageLocked = Number(storageItem?.locked_quantity ?? storageItem?.lockedQuantity);
if (Number.isFinite(storageQuantity) && storageQuantity > 0) {
const resolvedStorageLocked = Number.isFinite(storageLocked) ? storageLocked : 0;
const available = Math.max(0, storageQuantity - resolvedStorageLocked);
if (available > 0) {
return available;
}
}
}
return 0;
};
return stocks.find(item => resolveAvailableQuantity(item) > 0) || null;
}
/**
* 构建待审核订单的 XML 请求体。
* @param {Object} payload 请求参数。
* @return {string} XML 请求体。
*/
function buildDeliveryOrderXml(payload) {
const { deliveryOrderCode, warehouseCode, stock, planQty, orderType, receiverInfo } = payload;
return `<?xml version="1.0" encoding="UTF-8"?>
<request>
<deliveryOrder>
<deliveryOrderCode>${escapeXml(deliveryOrderCode)}</deliveryOrderCode>
<sourcePlatformCode>TAOBAO</sourcePlatformCode>
<sourcePlatformName>淘宝</sourcePlatformName>
<warehouseCode>${escapeXml(warehouseCode)}</warehouseCode>
<orderType>${escapeXml(orderType)}</orderType>
<receiverInfo>
<name>${escapeXml(receiverInfo.name)}</name>
<mobile>${escapeXml(receiverInfo.mobile)}</mobile>
<province>${escapeXml(receiverInfo.province)}</province>
<city>${escapeXml(receiverInfo.city)}</city>
<area>${escapeXml(receiverInfo.area)}</area>
<town>${escapeXml(receiverInfo.town)}</town>
<detailAddress>${escapeXml(receiverInfo.detailAddress)}</detailAddress>
<zipCode>${escapeXml(receiverInfo.zipCode)}</zipCode>
</receiverInfo>
</deliveryOrder>
<orderLines>
<orderLine>
<itemId>${escapeXml(stock.id)}</itemId>
<itemCode>${escapeXml(stock.item_code)}</itemCode>
<itemName>${escapeXml(stock.item_name)}</itemName>
<planQty>${escapeXml(planQty)}</planQty>
<orderLineNo>1</orderLineNo>
</orderLine>
</orderLines>
</request>`;
}
/**
* 切换到可访问仓库订单和库存接口的仓库角色。
* @param {string} token 当前登录 token。
* @return {Promise<{token: string, roleId: number}|null>} 切换结果。
*/
async function switchToWarehouseRole(token) {
const infoRes = await invokeSystemMethod('user.info', {}, token, EXTRA_HEADERS);
assert.equal(infoRes.status, 200, `user.info HTTP 状态异常: ${JSON.stringify(infoRes.body)}`);
assert.equal(infoRes.body.flag, 'success', `user.info 返回失败: ${JSON.stringify(infoRes.body)}`);
assert.equal(infoRes.body.code, 200, `user.info code 异常: ${JSON.stringify(infoRes.body)}`);
const employees = Array.isArray(infoRes.body?.data?.employees) ? infoRes.body.data.employees : [];
const candidateRoleIds = [
...new Set([
...employees
.filter(item => item && item.role_type === 'warehouse' && Number(item.id))
.map(item => Number(item.id)),
...FALLBACK_ROLE_IDS,
].filter(Boolean)),
];
for (const roleId of candidateRoleIds) {
const changeRes = await invokeSystemMethod('user.changeRole', {
roleId,
}, token, EXTRA_HEADERS);
if (changeRes.status !== 200 || changeRes.body?.flag !== 'success' || Number(changeRes.body?.code) !== 200) {
continue;
}
const switchedToken = changeRes.body?.data?.token || token;
const relationProbeRes = await invokeSystemMethod('storeWarehouse.store.list', {
page: 1,
page_size: 50,
}, switchedToken, EXTRA_HEADERS);
const stockProbeRes = await invokeSystemMethod('stock.warehouse.search', {
keyword: '',
store_id: FIXED_RELATION.storeId,
with_stock: true,
is_batch: false,
}, switchedToken, EXTRA_HEADERS);
if (relationProbeRes.status === 200
&& relationProbeRes.body?.flag === 'success'
&& Number(relationProbeRes.body?.code) === 200
&& pickFixedTestRelation(relationProbeRes.body?.data?.list)
&& stockProbeRes.status === 200
&& stockProbeRes.body?.flag === 'success'
&& Number(stockProbeRes.body?.code) === 200) {
return {
token: switchedToken,
roleId,
};
}
}
return null;
}
describe('test/app/controller/qimen.deliveryorder.reviewFlow.test.js', () => {
it('should create, review and move a delivery order through the real qimen flow', async function() {
const auth = await getAuthToken({ forceLogin: true });
const switched = await switchToWarehouseRole(auth.token);
if (!switched) {
this.skip();
return;
}
let relation = null;
let qimenConfig = null;
let stock = null;
let originalPolicyConfig = null;
let contractId = null;
const deliveryOrderCode = `QIMEN_REVIEW_${Date.now()}_${crypto.randomBytes(4).toString('hex').toUpperCase()}`;
try {
const relationListRes = await invokeSystemMethod('storeWarehouse.store.list', {
page: 1,
page_size: 50,
}, switched.token, EXTRA_HEADERS);
assert.equal(relationListRes.status, 200, `查询签约关系列表 HTTP 状态异常: ${JSON.stringify(relationListRes.body)}`);
assert.equal(relationListRes.body.flag, 'success', `查询签约关系列表失败: ${JSON.stringify(relationListRes.body)}`);
assert.equal(Number(relationListRes.body.code), 200, `查询签约关系列表 code 异常: ${JSON.stringify(relationListRes.body)}`);
relation = pickFixedTestRelation(relationListRes.body?.data?.list);
if (!relation) {
this.skip();
return;
}
contractId = Number(relation.id || 0);
originalPolicyConfig = relation.policy_config && typeof relation.policy_config === 'object'
? { ...relation.policy_config }
: null;
if (!originalPolicyConfig) {
this.skip();
return;
}
const apiConfigRes = await invokeSystemMethod('storeWarehouse.store.listApiConfig', {
id: contractId,
}, switched.token, EXTRA_HEADERS);
assert.equal(apiConfigRes.status, 200, `查询接口配置列表 HTTP 状态异常: ${JSON.stringify(apiConfigRes.body)}`);
assert.equal(apiConfigRes.body.flag, 'success', `查询接口配置列表失败: ${JSON.stringify(apiConfigRes.body)}`);
assert.equal(Number(apiConfigRes.body.code), 200, `查询接口配置列表 code 异常: ${JSON.stringify(apiConfigRes.body)}`);
qimenConfig = pickEnabledQimenConfig(apiConfigRes.body?.data?.list);
if (!qimenConfig
|| !String(qimenConfig.qimen_app_key || '').trim()
|| !String(qimenConfig.qimen_customer_id || '').trim()
|| !String(qimenConfig.qimen_warehouse_code || '').trim()) {
this.skip();
return;
}
const stockSearchRes = await invokeSystemMethod('stock.warehouse.search', {
keyword: '',
store_id: FIXED_RELATION.storeId,
with_stock: true,
is_batch: false,
}, switched.token, EXTRA_HEADERS);
assert.equal(stockSearchRes.status, 200, `查询库存搜索 HTTP 状态异常: ${JSON.stringify(stockSearchRes.body)}`);
assert.equal(stockSearchRes.body.flag, 'success', `查询库存搜索失败: ${JSON.stringify(stockSearchRes.body)}`);
assert.equal(Number(stockSearchRes.body.code), 200, `查询库存搜索 code 异常: ${JSON.stringify(stockSearchRes.body)}`);
stock = pickUsableStock(stockSearchRes.body?.data?.data || stockSearchRes.body?.data?.list || []);
if (!stock) {
this.skip();
return;
}
const nextPolicyConfig = {
...originalPolicyConfig,
need_order_approval: 1,
};
const savePolicyRes = await invokeSystemMethod('storeWarehouse.store.savePolicyConfig', {
id: contractId,
policy_config: nextPolicyConfig,
}, switched.token, EXTRA_HEADERS);
assert.equal(savePolicyRes.status, 200, `临时设置审核策略 HTTP 状态异常: ${JSON.stringify(savePolicyRes.body)}`);
assert.equal(savePolicyRes.body.flag, 'success', `临时设置审核策略失败: ${JSON.stringify(savePolicyRes.body)}`);
assert.equal(Number(savePolicyRes.body.code), 200, `临时设置审核策略 code 异常: ${JSON.stringify(savePolicyRes.body)}`);
assert.equal(Number(savePolicyRes.body?.data?.policy_config?.need_order_approval || 0), 1, '临时策略必须把 need_order_approval 置为 1');
const receiverInfo = {
name: '自动化测试收件人',
mobile: '13800138000',
province: '广东省',
city: '广州市',
area: '黄埔区',
town: '知识城街道',
detailAddress: `自动化测试地址 ${deliveryOrderCode}`,
zipCode: '510000',
};
const requestXml = buildDeliveryOrderXml({
deliveryOrderCode,
warehouseCode: String(qimenConfig.qimen_warehouse_code || '').trim(),
stock,
planQty: 1,
orderType: 'JYCK',
receiverInfo,
});
const createRes = await invokeQimenMethod('deliveryorder.create', requestXml, {
appKey: String(qimenConfig.qimen_app_key || '').trim(),
customerId: String(qimenConfig.qimen_customer_id || '').trim(),
contentType: 'application/xml',
format: 'xml',
signMethod: 'md5',
});
assert.equal(createRes.status, 200, `qimen 创建待审核订单 HTTP 状态异常: ${createRes.body}`);
const createResponse = createRes.parsed?.response || createRes.parsed || {};
assert.equal(String(createResponse.flag || ''), 'success', `qimen 创建待审核订单失败。请求 XML:\n${requestXml}\n响应原文:\n${createRes.body}`);
assert.match(String(createRes.body || ''), /deliveryOrderId|createTime|success/i, `qimen 创建响应缺少预期字段。请求 XML:\n${requestXml}\n响应原文:\n${createRes.body}`);
const reviewListRes = await invokeSystemMethod('order.reviewOrder.list', {
pagination: {
page: 1,
pageSize: 20,
},
where: {
delivery_order_code: deliveryOrderCode,
},
}, switched.token, EXTRA_HEADERS);
assert.equal(reviewListRes.status, 200, `待审核列表 HTTP 状态异常: ${JSON.stringify(reviewListRes.body)}`);
assert.equal(reviewListRes.body.flag, 'success', `待审核列表查询失败: ${JSON.stringify(reviewListRes.body)}`);
assert.equal(Number(reviewListRes.body.code), 200, `待审核列表 code 异常: ${JSON.stringify(reviewListRes.body)}`);
const reviewItems = Array.isArray(reviewListRes.body?.data?.list) ? reviewListRes.body.data.list : [];
const createdReviewOrder = reviewItems.find(item => String(item.delivery_order_code) === deliveryOrderCode);
assert.ok(createdReviewOrder, `待审核列表未命中刚创建的订单。响应原文: ${JSON.stringify(reviewListRes.body)}`);
assert.equal(Number(createdReviewOrder.step), 0, `新建订单应处于待审核 step=0。响应原文: ${JSON.stringify(reviewListRes.body)}`);
const reviewActionRes = await invokeSystemMethod('order.reviewOrder.reviewOrder', {
ids: [ Number(createdReviewOrder.id) ],
}, switched.token, EXTRA_HEADERS);
assert.equal(reviewActionRes.status, 200, `审核接口 HTTP 状态异常: ${JSON.stringify(reviewActionRes.body)}`);
assert.equal(reviewActionRes.body.flag, 'success', `审核接口调用失败: ${JSON.stringify(reviewActionRes.body)}`);
assert.equal(Number(reviewActionRes.body.code), 200, `审核接口 code 异常: ${JSON.stringify(reviewActionRes.body)}`);
assert.equal(Number(reviewActionRes.body?.data?.step), 1, `审核后订单 step 应变为 1。响应原文: ${JSON.stringify(reviewActionRes.body)}`);
const pendingListRes = await invokeSystemMethod('order.pendingOrder.list', {
pagination: {
page: 1,
pageSize: 20,
},
where: {
delivery_order_code: deliveryOrderCode,
},
}, switched.token, EXTRA_HEADERS);
assert.equal(pendingListRes.status, 200, `待处理列表 HTTP 状态异常: ${JSON.stringify(pendingListRes.body)}`);
assert.equal(pendingListRes.body.flag, 'success', `待处理列表查询失败: ${JSON.stringify(pendingListRes.body)}`);
assert.equal(Number(pendingListRes.body.code), 200, `待处理列表 code 异常: ${JSON.stringify(pendingListRes.body)}`);
const pendingItems = Array.isArray(pendingListRes.body?.data?.list) ? pendingListRes.body.data.list : [];
const pendingOrder = pendingItems.find(item => String(item.delivery_order_code) === deliveryOrderCode);
assert.ok(pendingOrder, `待处理列表未命中已审核订单。响应原文: ${JSON.stringify(pendingListRes.body)}`);
assert.ok([ 1, 2 ].includes(Number(pendingOrder.step)), `审核后订单 step 应处于待处理范围。响应原文: ${JSON.stringify(pendingListRes.body)}`);
const reviewAfterRes = await invokeSystemMethod('order.reviewOrder.list', {
pagination: {
page: 1,
pageSize: 20,
},
where: {
delivery_order_code: deliveryOrderCode,
},
}, switched.token, EXTRA_HEADERS);
assert.equal(reviewAfterRes.status, 200, `复查待审核列表 HTTP 状态异常: ${JSON.stringify(reviewAfterRes.body)}`);
assert.equal(reviewAfterRes.body.flag, 'success', `复查待审核列表失败: ${JSON.stringify(reviewAfterRes.body)}`);
assert.equal(Number(reviewAfterRes.body.code), 200, `复查待审核列表 code 异常: ${JSON.stringify(reviewAfterRes.body)}`);
const reviewAfterItems = Array.isArray(reviewAfterRes.body?.data?.list) ? reviewAfterRes.body.data.list : [];
const reviewAfterOrder = reviewAfterItems.find(item => String(item.delivery_order_code) === deliveryOrderCode);
assert.equal(reviewAfterOrder, undefined, `审核完成后不应再命中待审核列表。响应原文: ${JSON.stringify(reviewAfterRes.body)}`);
} finally {
if (contractId && originalPolicyConfig) {
const restoreRes = await invokeSystemMethod('storeWarehouse.store.savePolicyConfig', {
id: contractId,
policy_config: originalPolicyConfig,
}, switched.token, EXTRA_HEADERS);
assert.equal(restoreRes.status, 200, `恢复原 policy_config 的 HTTP 状态异常: ${JSON.stringify(restoreRes.body)}`);
assert.equal(restoreRes.body.flag, 'success', `恢复原 policy_config 失败: ${JSON.stringify(restoreRes.body)}`);
assert.equal(Number(restoreRes.body.code), 200, `恢复原 policy_config code 异常: ${JSON.stringify(restoreRes.body)}`);
}
}
});
});

View File

@ -0,0 +1,172 @@
'use strict';
const assert = require('node:assert/strict');
const OrderIndexService = require('../../../app/service/systemMethods/order/index');
const { buildRows, createOrderHarness, matchesWhere } = require('../../support/order_service_test_helper');
function createBadgeCountHarness(rowsByModule = {}) {
const { service, captures } = createOrderHarness(OrderIndexService, {
rowsByModule,
});
const cacheStore = new Map();
const cacheStats = {
getCalls: 0,
setCalls: 0,
};
service.app.getCacheAsync = async cacheKey => {
cacheStats.getCalls += 1;
if (!cacheStore.has(cacheKey)) {
return null;
}
return cacheStore.get(cacheKey);
};
service.app.setCacheAsync = async (cacheKey, value) => {
cacheStats.setCalls += 1;
cacheStore.set(cacheKey, value);
};
return {
service,
captures,
cacheStats,
};
}
describe('test/app/controller/system.order.badgeCount.test.js', () => {
it('should return 8 badge fields and keep delivery/archive as 99+', async () => {
const { service, captures } = createBadgeCountHarness({
reviewOrder: buildRows(99, () => ({
step: 0,
dispatch_lane: 'm4',
})),
pendingOrder: buildRows(100, () => ({
step: 1,
outbound_status: 'none',
dispatch_lane: 'm4',
})),
outboundOrder: buildRows(1, () => ({
step: 1,
outbound_status: 'padding',
dispatch_lane: 'm4',
})),
expectionOrder: buildRows(2, () => ({
step: 3,
dispatch_lane: 'm4',
})),
entrustOrder: buildRows(1, () => ({
step: 1,
dispatch_lane: 'm4',
})),
});
const result = await service.badgeCount();
assert.deepEqual(Object.keys(result), [
'reviewOrder',
'pendingOrder',
'outboundOrder',
'expectionOrder',
'entrustOrder',
'deliveryOrder',
'deliveryExpectionOrder',
'archiveOrder',
]);
assert.equal(result.reviewOrder, 99);
assert.equal(result.pendingOrder, '99+');
assert.equal(result.outboundOrder, 1);
assert.equal(result.expectionOrder, 2);
assert.equal(result.entrustOrder, 1);
assert.equal(result.deliveryOrder, '99+');
assert.equal(result.deliveryExpectionOrder, '99+');
assert.equal(result.archiveOrder, '99+');
assert.deepEqual(captures.map(item => item.moduleName), [
'reviewOrder',
'pendingOrder',
'outboundOrder',
'expectionOrder',
'entrustOrder',
]);
assert.ok(matchesWhere({ warehouse_id: 100000, step: 0 }, captures[0].countWhere));
assert.ok(matchesWhere({ warehouse_id: 100000, step: 1, outbound_status: 'none' }, captures[1].countWhere));
assert.ok(matchesWhere({ warehouse_id: 100000, step: 1, outbound_status: 'padding' }, captures[2].countWhere));
assert.ok(matchesWhere({ warehouse_id: 100000, step: 3 }, captures[3].countWhere));
assert.ok(matchesWhere({ warehouse_id: 100000 }, captures[4].countWhere));
});
it('should use cache and avoid repeated count queries', async () => {
const { service, captures, cacheStats } = createBadgeCountHarness({
reviewOrder: buildRows(2, () => ({
step: 0,
dispatch_lane: 'm4',
})),
pendingOrder: buildRows(2, () => ({
step: 1,
outbound_status: 'none',
dispatch_lane: 'm4',
})),
outboundOrder: buildRows(2, () => ({
step: 1,
outbound_status: 'none',
dispatch_lane: 'm4',
})),
expectionOrder: buildRows(1, () => ({
step: 3,
dispatch_lane: 'm4',
})),
entrustOrder: buildRows(1, () => ({
step: 1,
dispatch_lane: 'm4',
})),
});
const firstResult = await service.badgeCount();
const firstCaptureCount = captures.length;
const secondResult = await service.badgeCount();
assert.deepEqual(secondResult, firstResult);
assert.equal(captures.length, firstCaptureCount);
assert.equal(cacheStats.setCalls, 1);
assert.equal(cacheStats.getCalls, 2);
});
it('should keep exact counts within 99 and convert larger counts to 99+', async () => {
const { service } = createBadgeCountHarness({
reviewOrder: buildRows(1, () => ({
step: 0,
dispatch_lane: 'm4',
})),
pendingOrder: buildRows(100, () => ({
step: 1,
outbound_status: 'none',
dispatch_lane: 'm4',
})),
outboundOrder: buildRows(99, () => ({
step: 1,
outbound_status: 'none',
dispatch_lane: 'm4',
})),
expectionOrder: buildRows(3, () => ({
step: 3,
dispatch_lane: 'm4',
})),
entrustOrder: buildRows(1, () => ({
step: 1,
dispatch_lane: 'm4',
})),
});
const result = await service.badgeCount();
assert.equal(result.reviewOrder, 1);
assert.equal(result.pendingOrder, '99+');
assert.equal(result.outboundOrder, 99);
assert.equal(result.expectionOrder, 3);
assert.equal(result.entrustOrder, 1);
});
});

View File

@ -1,83 +1,33 @@
'use strict';
const assert = require('node:assert/strict');
const {
getAuthToken,
invokeSystemMethod,
} = require('../../support/system_method_client');
const ReviewOrderService = require('../../../app/service/systemMethods/order/reviewOrder');
const { buildRows, createOrderHarness } = require('../../support/order_service_test_helper');
const EXTRA_HEADERS = {
platform: 'web',
project: 'all',
};
describe('test/app/controller/system.order.reviewOrder.list.test.js', () => {
it('should return list/pagination for reviewOrder.list', async () => {
const { service, captures } = createOrderHarness(ReviewOrderService, {
rowsByModule: {
reviewOrder: buildRows(1, () => ({
step: 0,
dispatch_lane: 'm4',
})),
},
});
const FALLBACK_ROLE_IDS = [ 4, 6, 30 ];
async function switchToWarehouseRoleWithOrderData(token) {
let currentToken = token;
const infoRes = await invokeSystemMethod('user.info', {}, currentToken, EXTRA_HEADERS);
assert.equal(infoRes.status, 200);
assert.equal(infoRes.body.flag, 'success');
assert.equal(infoRes.body.code, 200);
const employees = Array.isArray(infoRes.body?.data?.employees) ? infoRes.body.data.employees : [];
const warehouseRoles = employees.filter(item => item && item.role_type === 'warehouse' && Number(item.id));
const candidateRoleIds = [ ...new Set([
...warehouseRoles.map(item => Number(item.id)),
...FALLBACK_ROLE_IDS,
].filter(Boolean)) ];
assert.ok(candidateRoleIds.length > 0, '当前账号没有可尝试的仓库角色');
for (const roleId of candidateRoleIds) {
const changeRes = await invokeSystemMethod('user.changeRole', {
roleId,
}, currentToken, EXTRA_HEADERS);
if (changeRes.status !== 200 || changeRes.body?.flag !== 'success' || changeRes.body?.code !== 200) {
continue;
}
currentToken = changeRes.body?.data?.token || currentToken;
const statsRes = await invokeSystemMethod('order.stats', {
where: {},
}, currentToken, EXTRA_HEADERS);
assert.equal(statsRes.status, 200);
assert.equal(statsRes.body.flag, 'success');
assert.equal(statsRes.body.code, 200);
const total = Number(statsRes.body?.data?.total || 0);
if (total > 0) {
return {
token: currentToken,
};
}
}
throw new Error('未找到有订单数据的仓库角色');
}
describe('test/app/controller/system.order.getreviewOrderlist.test.js', () => {
it('should call order.getreviewOrderlist with platform=web project=all', async () => {
const { token } = await getAuthToken();
const switched = await switchToWarehouseRoleWithOrderData(token);
const res = await invokeSystemMethod('order.getreviewOrderlist', {
const result = await service.list({
pagination: {
page: 1,
pageSize: 10,
pageSize: 1,
},
where: {},
}, switched.token, EXTRA_HEADERS);
});
assert.equal(res.status, 200);
assert.equal(res.body.flag, 'success');
assert.equal(res.body.code, 200);
assert.ok(res.body.data);
assert.ok(Array.isArray(res.body.data.list));
assert.ok(res.body.data.pagination);
assert.equal(typeof res.body.data.pagination.total, 'number');
assert.equal(captures[0].moduleName, 'reviewOrder');
assert.ok(Array.isArray(result.list));
assert.ok(result.pagination);
assert.equal(result.pagination.page, 1);
assert.equal(result.pagination.pageSize, 1);
assert.equal(result.list.length, 1);
});
});

View File

@ -1,198 +1,64 @@
'use strict';
const assert = require('node:assert/strict');
const {
getAuthToken,
invokeSystemMethod,
} = require('../../support/system_method_client');
const EXTRA_HEADERS = {
platform: 'web',
project: 'all',
};
const ALLOWED_REVIEW_STATUS = new Set([ 'none', 'padding', 'running', 'fin', 'error' ]);
const FALLBACK_ROLE_IDS = [ 4, 6, 30 ];
function mapReviewStatusToStep(reviewStatus) {
const status = String(reviewStatus || 'none').trim();
if (status === 'fin') {
return 1;
}
if (status === 'running' || status === 'padding') {
return 2;
}
if (status === 'error') {
return 3;
}
return 0;
}
async function switchToWarehouseRoleWithOrderData(token) {
let currentToken = token;
const infoRes = await invokeSystemMethod('user.info', {}, currentToken, EXTRA_HEADERS);
assert.equal(infoRes.status, 200);
assert.equal(infoRes.body.flag, 'success');
assert.equal(infoRes.body.code, 200);
const employees = Array.isArray(infoRes.body?.data?.employees) ? infoRes.body.data.employees : [];
const warehouseRoles = employees.filter(item => item && item.role_type === 'warehouse' && Number(item.id));
const candidateRoleIds = [ ...new Set([
...warehouseRoles.map(item => Number(item.id)),
...FALLBACK_ROLE_IDS,
].filter(Boolean)) ];
assert.ok(candidateRoleIds.length > 0, '当前账号没有可尝试的仓库角色');
for (const roleId of candidateRoleIds) {
const changeRes = await invokeSystemMethod('user.changeRole', {
roleId,
}, currentToken, EXTRA_HEADERS);
if (changeRes.status !== 200 || changeRes.body?.flag !== 'success' || changeRes.body?.code !== 200) {
continue;
}
currentToken = changeRes.body?.data?.token || currentToken;
const statsRes = await invokeSystemMethod('order.stats', {
where: {},
}, currentToken, EXTRA_HEADERS);
assert.equal(statsRes.status, 200);
assert.equal(statsRes.body.flag, 'success');
assert.equal(statsRes.body.code, 200);
const total = Number(statsRes.body?.data?.total || 0);
if (total > 0) {
return {
token: currentToken,
roleId,
total,
};
}
}
throw new Error('未找到有订单数据的仓库角色');
}
const OrderIndexService = require('../../../app/service/systemMethods/order/index');
const { buildRows, createOrderHarness } = require('../../support/order_service_test_helper');
describe('test/app/controller/system.order.namespaced.test.js', () => {
it('should query all namespaced order lists', async () => {
const { token } = await getAuthToken();
const switched = await switchToWarehouseRoleWithOrderData(token);
it('should return list/pagination for order.list', async () => {
const { service, captures } = createOrderHarness(OrderIndexService, {
rowsByModule: {
order: buildRows(1, () => ({
step: 1,
dispatch_lane: 'm4',
})),
},
});
const methods = [
'order.reviewOrder.getreviewOrderlist',
'order.deliveryOrder.getdeliveryOrderlist',
'order.pendingOrder.getpendingOrderlist',
'order.expectionOrder.getexpectionOrderlist',
'order.archiveOrder.getarchiveOrderlist',
];
for (const method of methods) {
const res = await invokeSystemMethod(method, {
pagination: {
page: 1,
pageSize: 10,
},
where: {},
}, switched.token, EXTRA_HEADERS);
assert.equal(res.status, 200, `${method} http status 异常`);
assert.equal(res.body.flag, 'success', `${method} flag 异常`);
assert.equal(res.body.code, 200, `${method} code 异常`);
assert.ok(res.body.data, `${method} 缺少 data`);
assert.ok(Array.isArray(res.body.data.list), `${method} list 不是数组`);
assert.ok(res.body.data.pagination, `${method} 缺少 pagination`);
assert.equal(typeof res.body.data.pagination.total, 'number', `${method} total 不是 number`);
}
});
it('should review order through namespaced method and restore status', async () => {
const { token } = await getAuthToken();
const switched = await switchToWarehouseRoleWithOrderData(token);
const listRes = await invokeSystemMethod('order.list', {
const result = await service.list({
pagination: {
page: 1,
pageSize: 1,
},
where: {},
}, switched.token, EXTRA_HEADERS);
where: {
step: 1,
},
});
assert.equal(listRes.status, 200);
assert.equal(listRes.body.flag, 'success');
assert.equal(listRes.body.code, 200);
const capture = captures[0];
const order = Array.isArray(listRes.body?.data?.list) ? listRes.body.data.list[0] : null;
assert.ok(order, '订单列表为空,无法测试目录化 reviewOrder');
assert.ok(order.id, '订单缺少 id,无法测试目录化 reviewOrder');
const originalStatus = ALLOWED_REVIEW_STATUS.has(String(order.inspection_status || ''))
? String(order.inspection_status)
: 'none';
const targetStatus = originalStatus === 'fin' ? 'running' : 'fin';
const reviewRes = await invokeSystemMethod('order.reviewOrder.reviewOrder', {
id: Number(order.id),
review_status: targetStatus,
}, switched.token, EXTRA_HEADERS);
assert.equal(reviewRes.status, 200);
assert.equal(reviewRes.body.flag, 'success');
assert.equal(reviewRes.body.code, 200);
assert.equal(Number(reviewRes.body?.data?.id || 0), Number(order.id));
assert.equal(reviewRes.body?.data?.inspection_status, targetStatus);
assert.equal(Number(reviewRes.body?.data?.step), mapReviewStatusToStep(targetStatus));
const restoreRes = await invokeSystemMethod('order.reviewOrder.reviewOrder', {
id: Number(order.id),
review_status: originalStatus,
}, switched.token, EXTRA_HEADERS);
assert.equal(restoreRes.status, 200);
assert.equal(restoreRes.body.flag, 'success');
assert.equal(restoreRes.body.code, 200);
assert.equal(restoreRes.body?.data?.inspection_status, originalStatus);
assert.equal(Number(restoreRes.body?.data?.step), mapReviewStatusToStep(originalStatus));
assert.equal(capture.moduleName, 'order');
assert.equal(result.pagination.pageSize, 1);
assert.equal(result.list.length, 1);
});
it('should return step in delivery orders and support filtering', async () => {
const { token } = await getAuthToken();
const switched = await switchToWarehouseRoleWithOrderData(token);
it('should hide deprecated order compatibility aliases', async () => {
const { service } = createOrderHarness(OrderIndexService, {
rowsByModule: {
order: buildRows(1, () => ({
step: 1,
dispatch_lane: 'm4',
})),
},
});
const listRes = await invokeSystemMethod('order.deliveryOrder.getdeliveryOrderlist', {
pagination: { page: 1, pageSize: 10 },
where: {},
}, switched.token, EXTRA_HEADERS);
const deprecatedMethods = [
'reviewOrder',
'pendingOrder',
'outboundOrder',
'expectionOrder',
'entrustOrder',
'deliveryOrder',
'deliveryExpectionOrder',
'archiveOrder',
];
assert.equal(listRes.status, 200);
assert.equal(listRes.body.flag, 'success');
assert.equal(listRes.body.code, 200);
const orders = listRes.body?.data?.list;
assert.ok(Array.isArray(orders));
if (orders.length > 0) {
assert.ok(Object.prototype.hasOwnProperty.call(orders[0], 'step'), '发货单应包含 step 字段');
const sampleStep = Number(orders[0].step);
const filteredRes = await invokeSystemMethod('order.deliveryOrder.getdeliveryOrderlist', {
pagination: { page: 1, pageSize: 10 },
where: { step: sampleStep },
}, switched.token, EXTRA_HEADERS);
assert.equal(filteredRes.status, 200);
assert.equal(filteredRes.body.flag, 'success');
assert.equal(filteredRes.body.code, 200);
const filteredOrders = filteredRes.body?.data?.list;
assert.ok(Array.isArray(filteredOrders));
if (filteredOrders.length > 0) {
assert.ok(
filteredOrders.every(order => Number(order.step) === sampleStep),
`按 step=${sampleStep} 过滤后,所有订单都应是该状态`
);
}
for (const methodName of deprecatedMethods) {
assert.equal(typeof service[methodName], 'undefined', `${methodName} 仍被暴露`);
}
assert.equal(typeof service.list, 'function');
assert.equal(typeof service.badgeCount, 'function');
assert.equal(typeof service.manualOutboundOrder, 'function');
});
});

View File

@ -0,0 +1,90 @@
'use strict';
const assert = require('node:assert/strict');
const OrderIndexService = require('../../../app/service/systemMethods/order/index');
const { buildRows, createOrderHarness } = require('../../support/order_service_test_helper');
describe('test/app/controller/system.order.outbound.exposure.test.js', () => {
it('should keep manualOutboundOrder exposed and remove deprecated outboundOrder alias', async () => {
const { service } = createOrderHarness(OrderIndexService, {
rowsByModule: {
order: buildRows(1, () => ({
step: 1,
dispatch_lane: 'm4',
})),
},
});
const methodNames = [
'markOutboundOrder',
'manualOutboundOrder',
];
assert.equal(typeof service.markOutboundOrder, 'undefined');
assert.equal(typeof service.outboundOrder, 'undefined');
assert.equal(typeof service.manualOutboundOrder, 'function');
const methodsManifest = require('../../../methods/system.json');
const exposedMethodNames = methodsManifest.methods.groups
.flatMap(group => (Array.isArray(group.list) ? group.list : []))
.map(item => item.method);
const hasInternalOutboundMethod = exposedMethodNames.some(methodName => {
return methodName === 'order.markOutboundOrder';
});
const hasDeprecatedOutboundAlias = exposedMethodNames.some(methodName => {
return methodName === 'order.outboundOrder';
});
assert.equal(hasInternalOutboundMethod, false);
assert.equal(hasDeprecatedOutboundAlias, false);
for (const methodName of methodNames) {
if (methodName === 'markOutboundOrder') {
continue;
}
assert.equal(typeof service[methodName], 'function');
}
});
it('should pass batch params through manualOutboundOrder to orderDeliveryMigration and return its result', async () => {
const { ctx, service } = createOrderHarness(OrderIndexService, {
rowsByModule: {
order: buildRows(1),
},
});
const requestData = {
warehouseId: 100000,
warehouseIds: [ 100000, 100001 ],
queryTimeoutMs: 12345,
executionTimeoutMs: 23456,
batchSize: 20,
customFlag: 'keep-as-is',
};
const expectedResult = {
ok: true,
totalCreated: 8,
};
let receivedPayload = null;
ctx.service = {
systems: {
orderDeliveryMigration: {
async syncOutboundOrdersToDelivery(data) {
receivedPayload = data;
return expectedResult;
},
},
},
};
const result = await service.manualOutboundOrder(requestData);
assert.strictEqual(receivedPayload, requestData);
assert.deepEqual(result, expectedResult);
});
});

Some files were not shown because too many files have changed in this diff Show More