Compare commits
15 Commits
403a73b250
...
2e29f302de
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2e29f302de | ||
|
|
41bede5391 | ||
|
|
a75612c22d | ||
|
|
373bb84294 | ||
|
|
58cc5bb7b6 | ||
|
|
ebaf5d0051 | ||
|
|
7b0004a7e3 | ||
|
|
3442ed5243 | ||
|
|
2189911073 | ||
|
|
05177d00f7 | ||
|
|
0a54f8028b | ||
|
|
3100bddce1 | ||
|
|
d36a46c5ab | ||
|
|
54065d7ee1 | ||
|
|
15e109f992 |
File diff suppressed because one or more lines are too long
@ -8,6 +8,7 @@
|
||||
- Method 路由映射说明:`AI_METHOD_ROUTING.md`
|
||||
- system 接口文档源:`methods/system.json`
|
||||
- qimen 接口文档源:`methods/qimen.json`
|
||||
- 配置驱动报表配置说明:`docs/report-config-guide.md`
|
||||
- 日报:`day.log`
|
||||
|
||||
## 项目目录结构
|
||||
@ -39,6 +40,7 @@
|
||||
- `AI_METHOD_ROUTING.md`:接口入口与 method 到代码文件的映射。
|
||||
- `methods/system.json`:system 接口定义(headers、groups、params、response、errors)。
|
||||
- `methods/qimen.json`:qimen 接口定义(按奇门协议组织)。
|
||||
- `docs/report-config-guide.md`:配置驱动通用报表(wms_report_definition 三段 JSON 配置、内置查询器口径)与货主定时投递说明。
|
||||
- `day.log`:每日工作留痕。
|
||||
|
||||
## 快速开始
|
||||
|
||||
171
app/lib/report/day_window.js
Normal file
171
app/lib/report/day_window.js
Normal file
@ -0,0 +1,171 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 报表「日窗口」纯函数工具模块(无 ctx 依赖,可单测)。
|
||||
*
|
||||
* 日窗口定义:[D 07:00, D+1 07:00) 半开区间(毫秒时间戳),
|
||||
* 与旧 PHP《7日出入库数据》(Wms.php putout_putin_storage7) 的
|
||||
* 07:00 切日口径保持一致,统一使用服务器本地时区(不依赖 UTC)。
|
||||
*/
|
||||
|
||||
const DEFAULT_DAY_COUNT = 7;
|
||||
const DEFAULT_CUTOVER_HOUR = 7;
|
||||
|
||||
/**
|
||||
* 数字补零为两位字符串。
|
||||
* @param {number} value 数值
|
||||
* @return {string} 补零后的两位字符串
|
||||
*/
|
||||
function pad2(value) {
|
||||
return String(value).padStart(2, '0');
|
||||
}
|
||||
|
||||
/**
|
||||
* 按本地时区构建连续的日窗口列表(最旧在前)。
|
||||
*
|
||||
* 规则:
|
||||
* 1. 每个窗口为 [D 07:00, D+1 07:00)(cutoverHour 可配置),start 含、end 不含;
|
||||
* 2. 最新窗口是「包含 now 的窗口」:now 当日已过切点时从今日切点起算,
|
||||
* 未过切点时从昨日切点起算;
|
||||
* 3. 窗口共 dayCount 个,按时间从旧到新排列;
|
||||
* 4. 通过 `new Date(y, m, d + offset, hour)` 构造,规避夏令时导致的 24h 步进偏差。
|
||||
*
|
||||
* @param {Object} [options={}] 构建选项
|
||||
* @param {number} [options.dayCount=7] 窗口数量
|
||||
* @param {number} [options.cutoverHour=7] 切点小时(0-23)
|
||||
* @param {number|Date} [options.now=Date.now()] 参考时刻
|
||||
* @return {Array<{start: number, end: number}>} 日窗口列表(毫秒,最旧在前)
|
||||
*/
|
||||
function buildDayWindows({ dayCount = DEFAULT_DAY_COUNT, cutoverHour = DEFAULT_CUTOVER_HOUR, now = Date.now() } = {}) {
|
||||
const normalizedCount = Math.max(1, Math.floor(Number(dayCount) || DEFAULT_DAY_COUNT));
|
||||
const normalizedHour = Math.min(23, Math.max(0, Math.floor(Number(cutoverHour) || 0)));
|
||||
const current = new Date(Number(now) || Date.now());
|
||||
|
||||
// 今天切点:本地时区当日 07:00
|
||||
let anchor = new Date(
|
||||
current.getFullYear(),
|
||||
current.getMonth(),
|
||||
current.getDate(),
|
||||
normalizedHour,
|
||||
0,
|
||||
0,
|
||||
0
|
||||
);
|
||||
|
||||
// 未到今日切点:最新窗口尚未开始,从昨日切点起算
|
||||
if (current.getTime() < anchor.getTime()) {
|
||||
anchor = new Date(
|
||||
anchor.getFullYear(),
|
||||
anchor.getMonth(),
|
||||
anchor.getDate() - 1,
|
||||
normalizedHour,
|
||||
0,
|
||||
0,
|
||||
0
|
||||
);
|
||||
}
|
||||
|
||||
const windows = [];
|
||||
for (let index = 0; index < normalizedCount; index += 1) {
|
||||
// 最旧在前:dayOffset 从 -(count-1) 递增到 0
|
||||
const dayOffset = index - (normalizedCount - 1);
|
||||
const start = new Date(
|
||||
anchor.getFullYear(),
|
||||
anchor.getMonth(),
|
||||
anchor.getDate() + dayOffset,
|
||||
normalizedHour,
|
||||
0,
|
||||
0,
|
||||
0
|
||||
);
|
||||
const end = new Date(
|
||||
anchor.getFullYear(),
|
||||
anchor.getMonth(),
|
||||
anchor.getDate() + dayOffset + 1,
|
||||
normalizedHour,
|
||||
0,
|
||||
0,
|
||||
0
|
||||
);
|
||||
windows.push({
|
||||
start: start.getTime(),
|
||||
end: end.getTime(),
|
||||
});
|
||||
}
|
||||
|
||||
return windows;
|
||||
}
|
||||
|
||||
/**
|
||||
* 按 PHP date() 风格的 token 格式化窗口开始日期(本地时区,无前导零)。
|
||||
*
|
||||
* 支持的 token:
|
||||
* Y=四位年;y=两位年;m=补零月;n=无前导零月;d=补零日;j=无前导零日;
|
||||
* H=补零小时;i=补零分钟;s=补零秒。其余字符原样保留。
|
||||
*
|
||||
* @param {Array<{start: number, end: number}>} windows 日窗口列表
|
||||
* @param {number} index 窗口下标
|
||||
* @param {string} [pattern='Y/n/j'] 日期格式模板(如 '2026/8/23')
|
||||
* @return {string} 格式化后的日期字符串
|
||||
*/
|
||||
function formatWindowStart(windows, index, pattern = 'Y/n/j') {
|
||||
const windowItem = Array.isArray(windows) ? windows[index] : null;
|
||||
if (!windowItem || !Number.isFinite(Number(windowItem.start))) {
|
||||
return '';
|
||||
}
|
||||
|
||||
const date = new Date(Number(windowItem.start));
|
||||
const tokens = {
|
||||
Y: String(date.getFullYear()),
|
||||
y: String(date.getFullYear()).slice(2),
|
||||
m: pad2(date.getMonth() + 1),
|
||||
n: String(date.getMonth() + 1),
|
||||
d: pad2(date.getDate()),
|
||||
j: String(date.getDate()),
|
||||
H: pad2(date.getHours()),
|
||||
i: pad2(date.getMinutes()),
|
||||
s: pad2(date.getSeconds()),
|
||||
};
|
||||
|
||||
return String(pattern || 'Y/n/j').replace(/[YymndjHis]/g, character => tokens[character]);
|
||||
}
|
||||
|
||||
/**
|
||||
* 取时刻的本地 'HH:mm'(补零)。
|
||||
* @param {Date|number} date 日期对象或毫秒时间戳
|
||||
* @return {string} 'HH:mm' 格式字符串
|
||||
*/
|
||||
function hhmmOf(date) {
|
||||
const normalizedDate = date instanceof Date ? date : new Date(Number(date) || Date.now());
|
||||
return `${pad2(normalizedDate.getHours())}:${pad2(normalizedDate.getMinutes())}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 取时刻的本地自然日('YYYY-MM-DD')。
|
||||
* @param {Date|number} date 日期对象或毫秒时间戳
|
||||
* @return {string} 'YYYY-MM-DD' 格式字符串
|
||||
*/
|
||||
function scheduleDateOf(date) {
|
||||
const normalizedDate = date instanceof Date ? date : new Date(Number(date) || Date.now());
|
||||
return `${normalizedDate.getFullYear()}-${pad2(normalizedDate.getMonth() + 1)}-${pad2(normalizedDate.getDate())}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 从窗口参数对象解析 dayCount/cutoverHour,供查询器与元数据接口共用。
|
||||
* 口径与查询器保持一致:dayCount 缺省 7(<=0 视为 7),cutoverHour 缺省 7 且钳制到 0-23。
|
||||
* @param {Object} [params={}] 窗口参数(支持 dayCount/day_count、cutoverHour/cutover_hour)
|
||||
* @return {{dayCount: number, cutoverHour: number}} 归一化窗口参数
|
||||
*/
|
||||
function resolveWindowConfig(params = {}) {
|
||||
const dayCount = Math.max(1, Math.floor(Number(params.dayCount || params.day_count || 7)));
|
||||
const cutoverHour = Math.min(23, Math.max(0, Math.floor(Number(params.cutoverHour ?? params.cutover_hour ?? 7))));
|
||||
return { dayCount, cutoverHour };
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
buildDayWindows,
|
||||
formatWindowStart,
|
||||
hhmmOf,
|
||||
scheduleDateOf,
|
||||
resolveWindowConfig,
|
||||
};
|
||||
167
app/lib/report/formatters.js
Normal file
167
app/lib/report/formatters.js
Normal file
@ -0,0 +1,167 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 报表单元格格式化器注册表(纯函数模块,无 ctx 依赖,可单测)。
|
||||
*
|
||||
* 设计约定:
|
||||
* 1. 所有格式化器首参为单元格原始值(value),其余参数为格式化参数;
|
||||
* 2. 数值计算统一走「截断取整」(等价旧 PHP 的 intval 语义,向零取整);
|
||||
* 3. 低库存补偿口径与旧 PHP《7日出入库数据》保持一致:
|
||||
* 可用库存 < 20 且 7 日入库 < 20 时视为低库存,触发补偿与预警。
|
||||
*/
|
||||
|
||||
/**
|
||||
* 安全转数值:非有限数值一律按 0 处理。
|
||||
* @param {*} value 原始值
|
||||
* @return {number} 数值
|
||||
*/
|
||||
function toFiniteNumber(value) {
|
||||
const number = Number(value);
|
||||
return Number.isFinite(number) ? number : 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* 截断取整(PHP intval 语义,向零取整)。
|
||||
* @param {*} value 原始值
|
||||
* @return {number} 整数
|
||||
*/
|
||||
function integer(value) {
|
||||
return Math.trunc(toFiniteNumber(value));
|
||||
}
|
||||
|
||||
/**
|
||||
* 零值占位:0 / '0' / null / undefined / '' 统一显示为 '-'。
|
||||
* 说明:'0' 一并转 '-',与 PHP empty('0') 为真的旧口径保持一致。
|
||||
* @param {*} value 原始值
|
||||
* @return {*} 非零原值或 '-'
|
||||
*/
|
||||
function zeroToDash(value) {
|
||||
if (value === 0 || value === '0' || value === null || value === undefined || value === '') {
|
||||
return '-';
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
/**
|
||||
* 布尔转中文:真值 → '是',假值 → '否'。
|
||||
* 说明:''、0、'0'、null、undefined、false 均视为假,与 PHP 布尔语义对齐。
|
||||
* @param {*} flag 原始值
|
||||
* @return {string} '是' 或 '否'
|
||||
*/
|
||||
function yesNo(flag) {
|
||||
const falsy = flag === false
|
||||
|| flag === null
|
||||
|| flag === undefined
|
||||
|| flag === ''
|
||||
|| flag === 0
|
||||
|| flag === '0'
|
||||
|| String(flag).toLowerCase() === 'false';
|
||||
return falsy ? '否' : '是';
|
||||
}
|
||||
|
||||
/**
|
||||
* 7 日日均 ×10 取整(保留一位小数但避免浮点误差)。
|
||||
* 公式:int(total / days * 10),与旧 PHP intval($ck / 7 * 10) 一致。
|
||||
* @param {*} value 周期合计值
|
||||
* @param {*} days 天数
|
||||
* @return {number} 日均×10 的整数
|
||||
*/
|
||||
function avgDaysPerWeek(value, days) {
|
||||
const total = toFiniteNumber(value);
|
||||
const dayCount = toFiniteNumber(days);
|
||||
if (dayCount <= 0) {
|
||||
return 0;
|
||||
}
|
||||
return Math.trunc((total / dayCount) * 10);
|
||||
}
|
||||
|
||||
/**
|
||||
* 建议补货量(含低库存补偿):
|
||||
* 基础值 int(ck_total / 7 * 10);仅当低库存(available < 20 且 rk_total < 20)时
|
||||
* 补偿到不低于 30(保证低库存货主获得最小补货建议)。
|
||||
* @param {*} ckTotal 7 日总出库
|
||||
* @param {*} available 可用库存
|
||||
* @param {*} rkTotal 7 日总入库
|
||||
* @return {number} 建议补货量
|
||||
*/
|
||||
function suggestWithCompensate(ckTotal, available, rkTotal) {
|
||||
const base = Math.trunc((toFiniteNumber(ckTotal) / 7) * 10);
|
||||
const availableNumber = toFiniteNumber(available);
|
||||
const rkNumber = toFiniteNumber(rkTotal);
|
||||
if (availableNumber < 20 && rkNumber < 20) {
|
||||
return Math.max(base, 30);
|
||||
}
|
||||
return base;
|
||||
}
|
||||
|
||||
/**
|
||||
* 库存预警判定(布尔):
|
||||
* 1. 按 7 日均出库 ×4 折算的周转阈值高于可用库存(int(ck/7*4) - available > 0);
|
||||
* 2. 或处于低库存状态(available < 20 且 rk_total < 20)。
|
||||
* 展示时建议叠加 yesNo 格式化器转中文。
|
||||
* @param {*} ckTotal 7 日总出库
|
||||
* @param {*} available 可用库存
|
||||
* @param {*} rkTotal 7 日总入库
|
||||
* @return {boolean} 是否预警
|
||||
*/
|
||||
function warnOf(ckTotal, available, rkTotal) {
|
||||
const threshold = Math.trunc((toFiniteNumber(ckTotal) / 7) * 4);
|
||||
return threshold - toFiniteNumber(available) > 0
|
||||
|| (toFiniteNumber(available) < 20 && toFiniteNumber(rkTotal) < 20);
|
||||
}
|
||||
|
||||
/**
|
||||
* 文本前缀工厂:返回一个给文本加前缀的格式化函数。
|
||||
* 典型用法:`'` 前缀防科学计数法(Excel 将长数字串强制按文本展示)。
|
||||
* @param {string} [prefix=''] 前缀
|
||||
* @return {Function} 格式化函数 (value) => `${prefix}${value}`
|
||||
*/
|
||||
function textPrefix(prefix = '') {
|
||||
return value => `${String(prefix || '')}${value === null || value === undefined ? '' : String(value)}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 格式化器注册表(配置驱动报表按名称引用)。
|
||||
* @type {Object<string, Function>}
|
||||
*/
|
||||
const FORMATTERS = Object.freeze({
|
||||
textPrefix: (value, prefix) => textPrefix(prefix)(value),
|
||||
zeroToDash,
|
||||
yesNo,
|
||||
integer,
|
||||
avgDaysPerWeek,
|
||||
suggestWithCompensate,
|
||||
warnOf,
|
||||
});
|
||||
|
||||
/**
|
||||
* 按名称应用格式化器。
|
||||
* @param {string} name 格式化器名称
|
||||
* @param {*} value 单元格原始值
|
||||
* @param {...*} args 格式化器额外参数
|
||||
* @return {*} 格式化结果
|
||||
* @throws {Error} 未知格式化器名称时抛出
|
||||
*/
|
||||
function applyFormat(name, value, ...args) {
|
||||
const formatterName = String(name || '').trim();
|
||||
if (!formatterName) {
|
||||
return value;
|
||||
}
|
||||
const formatter = FORMATTERS[formatterName];
|
||||
if (typeof formatter !== 'function') {
|
||||
throw new Error(`未知的报表格式化器: ${formatterName}`);
|
||||
}
|
||||
return formatter(value, ...args);
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
FORMATTERS,
|
||||
applyFormat,
|
||||
textPrefix,
|
||||
zeroToDash,
|
||||
yesNo,
|
||||
integer,
|
||||
avgDaysPerWeek,
|
||||
suggestWithCompensate,
|
||||
warnOf,
|
||||
};
|
||||
101
app/lib/report/notifyTemplate.js
Normal file
101
app/lib/report/notifyTemplate.js
Normal file
@ -0,0 +1,101 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 货主报表文本通知模板渲染器(纯函数模块,无 ctx 依赖,可单测)。
|
||||
*
|
||||
* 标签白名单(其余 {xxx} 一律不替换,保存入口由 reportDelivery.savePlan 校验拦截):
|
||||
* - {time} 发送时间,格式 YYYY-MM-DD HH:mm
|
||||
* - {url} 报表文件下载链接(url 为空时替换为兜底文案)
|
||||
* - {report_name} 报表名称
|
||||
* - {biz_date} 数据日期 YYYY-MM-DD
|
||||
*/
|
||||
|
||||
/** 模板标签白名单 */
|
||||
const ALLOWED_TAGS = Object.freeze([ 'time', 'url', 'report_name', 'biz_date' ]);
|
||||
|
||||
/**
|
||||
* url 为空时的兜底文案。
|
||||
* 理由:生成结果 url 可能因异步上传尚未就绪,以占位文案保证通知可达,
|
||||
* 避免因链接缺失引发整链路失败重试风暴;实际链接可在投递记录中查看。
|
||||
*/
|
||||
const EMPTY_URL_FALLBACK = '文件生成中,稍后可在投递记录中查看';
|
||||
|
||||
/** 模板标签匹配正则:{xxx} 占位 */
|
||||
const TAG_PATTERN = /\{([^{}]+)\}/g;
|
||||
|
||||
/**
|
||||
* 提取模板中出现过的全部标签名(按出现顺序,含重复项)。
|
||||
* @param {string} template 模板字符串
|
||||
* @return {Array<string>} 标签名数组
|
||||
*/
|
||||
function extractTagNames(template) {
|
||||
const names = [];
|
||||
const source = String(template || '');
|
||||
let match = TAG_PATTERN.exec(source);
|
||||
while (match) {
|
||||
names.push(String(match[1]).trim());
|
||||
match = TAG_PATTERN.exec(source);
|
||||
}
|
||||
return names;
|
||||
}
|
||||
|
||||
/**
|
||||
* 校验模板标签是否全部位于白名单内(未知标签不替换、保存时拒绝)。
|
||||
* @param {string} template 模板字符串
|
||||
* @return {{valid: boolean, invalidTags: Array<string>}} 校验结果(invalidTags 已去重)
|
||||
*/
|
||||
function validateNotifyTemplate(template) {
|
||||
const names = extractTagNames(template);
|
||||
const invalidSet = new Set();
|
||||
for (const name of names) {
|
||||
if (!ALLOWED_TAGS.includes(name)) {
|
||||
invalidSet.add(name);
|
||||
}
|
||||
}
|
||||
return { valid: invalidSet.size === 0, invalidTags: [ ...invalidSet ] };
|
||||
}
|
||||
|
||||
/**
|
||||
* 渲染通知模板:仅替换白名单标签,未知标签原样保留(保存入口已校验拦截)。
|
||||
* @param {string} template 模板字符串
|
||||
* @param {Object} [context={}] 渲染上下文
|
||||
* @param {string} [context.time=''] 发送时间(YYYY-MM-DD HH:mm)
|
||||
* @param {string} [context.url=''] 报表文件下载链接(空则替换为兜底文案)
|
||||
* @param {string} [context.reportName=''] 报表名称
|
||||
* @param {string} [context.bizDate=''] 数据日期(YYYY-MM-DD)
|
||||
* @return {string} 渲染后的通知文本
|
||||
*/
|
||||
function renderNotifyTemplate(template, context = {}) {
|
||||
const url = String((context && context.url) || '').trim() || EMPTY_URL_FALLBACK;
|
||||
const replacements = {
|
||||
time: String((context && context.time) || ''),
|
||||
url,
|
||||
report_name: String((context && context.reportName) || ''),
|
||||
biz_date: String((context && context.bizDate) || ''),
|
||||
};
|
||||
return String(template || '').replace(TAG_PATTERN, (raw, name) => {
|
||||
const key = String(name).trim();
|
||||
return Object.prototype.hasOwnProperty.call(replacements, key) ? replacements[key] : raw;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 格式化发送时间为 YYYY-MM-DD HH:mm(服务器本地时区)。
|
||||
* @param {Date} [date=new Date()] 时刻
|
||||
* @return {string} 格式化后的时间字符串
|
||||
*/
|
||||
function formatNotifyTime(date) {
|
||||
const target = date instanceof Date ? date : new Date();
|
||||
const pad = value => String(value).padStart(2, '0');
|
||||
return `${target.getFullYear()}-${pad(target.getMonth() + 1)}-${pad(target.getDate())} `
|
||||
+ `${pad(target.getHours())}:${pad(target.getMinutes())}`;
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
ALLOWED_TAGS,
|
||||
EMPTY_URL_FALLBACK,
|
||||
extractTagNames,
|
||||
validateNotifyTemplate,
|
||||
renderNotifyTemplate,
|
||||
formatNotifyTime,
|
||||
};
|
||||
233
app/lib/report/render.js
Normal file
233
app/lib/report/render.js
Normal file
@ -0,0 +1,233 @@
|
||||
'use strict';
|
||||
|
||||
const { applyFormat } = require('./formatters');
|
||||
const { formatWindowStart } = require('./day_window');
|
||||
|
||||
/**
|
||||
* 报表渲染翻译层(纯函数模块,无 ctx 依赖,可单测)。
|
||||
*
|
||||
* 输入:报表类型 type 的硬编码字段注册清单(fields,按勾选顺序)+ 查询器产出的数据 rows;
|
||||
* 输出:适配 `app/service/systems/excel.js` 的 sheets 参数结构
|
||||
* ({ name, columns, rows, merges, styledRows, textColumns? })。
|
||||
*
|
||||
* 约定(与 excel.js 的 buildExcelJsWorkbook 对齐):
|
||||
* 1. 数据以 AOA(二维数组)形式输出,表头行内联在 rows 首位,columns 恒传空数组;
|
||||
* 2. merges 统一输出 {s:{r,c}, e:{r,c}} 结构(excel.js 两套构建器均支持);
|
||||
* 3. textColumns 输出 0 基列索引,由 excel.js 落地为文本单元格。
|
||||
*
|
||||
* 列规则(全部由字段注册清单硬编码决定,无 sheet_config 自定义):
|
||||
* 1. string 字段 → 静态列(header=label),asText=true 时加入 textColumns;
|
||||
* 2. number 字段 → 静态列,统一 zeroToDash(0/''/null 显示 '-');
|
||||
* 3. boolean 字段 → 静态列,统一 yesNo(真→是,假→否);
|
||||
* 4. array 字段 → 窗口展开列:per=窗口数,pair=children keys,表头第 1 行按窗口
|
||||
* 输出 '{date}' 日期(Y/n/j 无前导零)并在每窗口 pair.length>1 时横向合并,
|
||||
* 表头第 2 行按 children label 填充;子字段为 number 时单元格统一 zeroToDash;
|
||||
* 5. 存在展开列时启用两行表头,其余列表头纵向合并(如 A1:A2)。
|
||||
*/
|
||||
|
||||
/**
|
||||
* 判断字段是否为普通对象。
|
||||
* @param {*} field 待判断字段
|
||||
* @return {boolean} 是否普通对象
|
||||
*/
|
||||
function isPlainObject(field) {
|
||||
return Boolean(field) && typeof field === 'object' && !Array.isArray(field);
|
||||
}
|
||||
|
||||
/**
|
||||
* 规范化字段注册清单:仅保留含 key 的对象,key 统一为字符串。
|
||||
* @param {Array<Object>} fields 字段清单(注册表 fields,按勾选顺序)
|
||||
* @return {Array<Object>} 规范化字段清单
|
||||
*/
|
||||
function normalizeFields(fields) {
|
||||
if (!Array.isArray(fields)) {
|
||||
return [];
|
||||
}
|
||||
return fields
|
||||
.filter(field => isPlainObject(field) && String(field.key || '').trim())
|
||||
.map(field => ({ ...field, key: String(field.key).trim() }));
|
||||
}
|
||||
|
||||
/**
|
||||
* 按类型字段清单构建列计划(含窗口展开与表头合并)。
|
||||
* @param {Object} [options={}] 构建选项
|
||||
* @param {Array<Object>} [options.fields=[]] 字段注册清单(按勾选顺序)
|
||||
* @param {Array<Object>} [options.windows=[]] 日窗口列表(展开列 per 取窗口数)
|
||||
* @return {{columns: Array<Object>, headerRowCount: number, generatedMerges: Array<Object>}} 列计划
|
||||
*/
|
||||
function buildColumnPlan({ fields = [], windows = [] } = {}) {
|
||||
const safeFields = normalizeFields(fields);
|
||||
const safeWindows = Array.isArray(windows) ? windows : [];
|
||||
const expandPer = Math.max(1, safeWindows.length || 7);
|
||||
|
||||
const columns = [];
|
||||
const generatedMerges = [];
|
||||
let expandStartColumn = -1;
|
||||
|
||||
for (const field of safeFields) {
|
||||
if (field.type === 'array') {
|
||||
const children = Array.isArray(field.children) ? field.children : [];
|
||||
const pair = children.length > 0 ? children : [{ key: 'value', label: '值', type: 'string' }];
|
||||
expandStartColumn = columns.length;
|
||||
for (let windowIndex = 0; windowIndex < expandPer; windowIndex += 1) {
|
||||
for (let pairIndex = 0; pairIndex < pair.length; pairIndex += 1) {
|
||||
columns.push({
|
||||
type: 'expand',
|
||||
windowIndex,
|
||||
pairIndex,
|
||||
pair: pair[pairIndex] && isPlainObject(pair[pairIndex]) ? pair[pairIndex] : {},
|
||||
headerRow1Template: '{date}',
|
||||
headerRow2List: pair.map(child => String((child && child.label) || '')),
|
||||
});
|
||||
}
|
||||
if (pair.length > 1) {
|
||||
// 每窗口多列表头横向合并(如 D1:E1 … P1:Q1)
|
||||
const groupStart = expandStartColumn + windowIndex * pair.length;
|
||||
generatedMerges.push({
|
||||
s: { r: 0, c: groupStart },
|
||||
e: { r: 0, c: groupStart + pair.length - 1 },
|
||||
});
|
||||
}
|
||||
}
|
||||
continue;
|
||||
}
|
||||
columns.push({
|
||||
type: field.type === 'array' ? 'static' : (field.type || 'string'),
|
||||
header: String(field.label || field.key || ''),
|
||||
field: field.key,
|
||||
asText: field.asText === true,
|
||||
});
|
||||
}
|
||||
|
||||
const hasExpandColumn = columns.some(column => column.type === 'expand');
|
||||
const headerRowCount = hasExpandColumn ? 2 : 1;
|
||||
|
||||
// 两行表头下,非展开列按列纵向合并(A1:A2 等)
|
||||
if (headerRowCount === 2) {
|
||||
columns.forEach((column, columnIndex) => {
|
||||
if (column.type !== 'expand') {
|
||||
generatedMerges.push({
|
||||
s: { r: 0, c: columnIndex },
|
||||
e: { r: 1, c: columnIndex },
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
columns,
|
||||
headerRowCount,
|
||||
generatedMerges,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 构建表头第 1 行(展开列按窗口开始日期输出 'Y/n/j' 无前导零)。
|
||||
* @param {Array<Object>} columns 列计划
|
||||
* @param {Array<Object>} windows 日窗口列表
|
||||
* @return {Array<string>} 表头第 1 行
|
||||
*/
|
||||
function buildHeaderRow1(columns, windows = []) {
|
||||
return columns.map(column => {
|
||||
if (column.type === 'expand') {
|
||||
return formatWindowStart(windows, column.windowIndex, 'Y/n/j');
|
||||
}
|
||||
return column.header;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 构建表头第 2 行(单行表头模式下返回 null;展开列按 pair label 填充)。
|
||||
* @param {Array<Object>} columns 列计划
|
||||
* @param {number} headerRowCount 表头行数
|
||||
* @return {Array<string>|null} 表头第 2 行
|
||||
*/
|
||||
function buildHeaderRow2(columns, headerRowCount) {
|
||||
if (headerRowCount !== 2) {
|
||||
return null;
|
||||
}
|
||||
return columns.map(column => {
|
||||
if (column.type === 'expand') {
|
||||
const list = column.headerRow2List;
|
||||
return list.length > 0 ? list[column.pairIndex % list.length] || '' : '';
|
||||
}
|
||||
return '';
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 渲染单个单元格(按列类型与字段类型硬编码格式化口径)。
|
||||
* @param {Object} column 列计划
|
||||
* @param {Object} row 数据行
|
||||
* @return {*} 单元格值
|
||||
*/
|
||||
function renderCell(column, row = {}) {
|
||||
if (column.type === 'expand') {
|
||||
const daily = Array.isArray(row.daily) ? row.daily : [];
|
||||
const day = daily[column.windowIndex];
|
||||
const value = day && typeof day === 'object' ? day[column.pair.key] : 0;
|
||||
return applyFormat(column.pair.type === 'number' ? 'zeroToDash' : '', value);
|
||||
}
|
||||
|
||||
const value = row[column.field];
|
||||
if (column.type === 'boolean') {
|
||||
return applyFormat('yesNo', value);
|
||||
}
|
||||
if (column.type === 'number') {
|
||||
return applyFormat('zeroToDash', value);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
/**
|
||||
* 按类型字段注册清单渲染 sheet(配置极简:无 sheet_config 自定义列/合并/样式)。
|
||||
*
|
||||
* @param {Object} [options={}] 渲染选项
|
||||
* @param {string} [options.type=''] 报表类型(查询器注册 key,仅透传不参与渲染口径)
|
||||
* @param {string} [options.title='报表'] sheet 名称(报表标题)
|
||||
* @param {Array<Object>} [options.fields=[]] 字段注册清单(按勾选顺序)
|
||||
* @param {Array<Object>} [options.rows=[]] 查询器产出的数据行
|
||||
* @param {Array<Object>} [options.windows=[]] 日窗口列表
|
||||
* @return {Object} excel.js sheet 参数
|
||||
* ({name, columns, rows, merges, styledRows},存在 asText 列时附带 textColumns)
|
||||
*/
|
||||
function renderSheetByType({ type = '', title = '报表', fields = [], rows = [], windows = [] } = {}) {
|
||||
void type;
|
||||
const plan = buildColumnPlan({ fields, windows });
|
||||
const safeRows = Array.isArray(rows) ? rows : [];
|
||||
|
||||
const headerRow1 = buildHeaderRow1(plan.columns, windows);
|
||||
const headerRow2 = buildHeaderRow2(plan.columns, plan.headerRowCount);
|
||||
|
||||
const aoaRows = [ headerRow1 ];
|
||||
if (headerRow2) {
|
||||
aoaRows.push(headerRow2);
|
||||
}
|
||||
for (const row of safeRows) {
|
||||
aoaRows.push(plan.columns.map(column => renderCell(column, row)));
|
||||
}
|
||||
|
||||
// asText 列收集为 0 基列索引,交由 excel.js 落地文本单元格(无 asText 时不输出)
|
||||
const textColumns = plan.columns
|
||||
.map((column, columnIndex) => (column.asText ? columnIndex : -1))
|
||||
.filter(columnIndex => columnIndex >= 0);
|
||||
|
||||
const result = {
|
||||
name: String(title || '报表'),
|
||||
columns: [],
|
||||
rows: aoaRows,
|
||||
merges: plan.generatedMerges,
|
||||
styledRows: [],
|
||||
};
|
||||
|
||||
if (textColumns.length > 0) {
|
||||
result.textColumns = textColumns;
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
renderSheetByType,
|
||||
buildColumnPlan,
|
||||
};
|
||||
35
app/lib/waybill_code.js
Normal file
35
app/lib/waybill_code.js
Normal file
@ -0,0 +1,35 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 运单号公共工具。
|
||||
* 统一处理一单多件分段单号(如 JDX057941864338-1-1-)的包裹序号后缀剥离与 like 通配符转义,
|
||||
* 保证「剥离后缀后主体运单号必须等值匹配」的业务规则在各扫描入口保持一致。
|
||||
*/
|
||||
|
||||
/**
|
||||
* 剥离运单号尾部的包裹序号段(一单多件分段格式:-包裹序号-总件数[-])。
|
||||
* 例如 'JDX057941864338-1-1-' → 'JDX057941864338';
|
||||
* 'JDX057941864338' 无分段后缀时原样返回。
|
||||
*
|
||||
* @param {string} waybillCode 运单号
|
||||
* @return {string} 剥离分段后缀后的主体运单号
|
||||
*/
|
||||
function stripWaybillSegmentSuffix(waybillCode) {
|
||||
return String(waybillCode || '').trim().replace(/(?:-\d+){2,}-?$/, '');
|
||||
}
|
||||
|
||||
/**
|
||||
* 转义 like 匹配中的通配符(% _ \),避免用户输入中的特殊字符扩大匹配范围。
|
||||
* 用于「主体运单号 + -%」前缀匹配场景,确保主体部分被等值比较。
|
||||
*
|
||||
* @param {string} value 待转义的字符串
|
||||
* @return {string} 转义后的字符串
|
||||
*/
|
||||
function escapeLikeWildcards(value) {
|
||||
return String(value || '').replace(/[%_\\]/g, m => `\\${m}`);
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
stripWaybillSegmentSuffix,
|
||||
escapeLikeWildcards,
|
||||
};
|
||||
@ -143,6 +143,12 @@ module.exports = app => {
|
||||
defaultValue: 0,
|
||||
comment: '费用是否记录',
|
||||
},
|
||||
is_virtual_inbound: {
|
||||
type: TINYINT(1),
|
||||
allowNull: false,
|
||||
defaultValue: 0,
|
||||
comment: '是否虚拟入库:0=否 1=是',
|
||||
},
|
||||
store_name: {
|
||||
type: STRING(200),
|
||||
allowNull: true,
|
||||
|
||||
@ -568,6 +568,17 @@ function buildIndexOptions(warehouseId, type) {
|
||||
name: `idx_${prefix}_hash_crc`,
|
||||
fields: [ 'items_hash', 'items_crc', 'warehouse_id' ],
|
||||
},
|
||||
// wave_id 前导索引仅 current 分表需要:dispatch 通过 baseIndexes 自动继承;
|
||||
// history/outsourced 分表未在迁移中加该索引,模型不得生成预期定义,
|
||||
// 否则运行时 drift 同步会向其自动补建索引,造成模型与实际库不一致。
|
||||
...(modelType === MANAGED_TYPES.CURRENT
|
||||
? [
|
||||
{
|
||||
name: `idx_${prefix}_wave_id`,
|
||||
fields: [ 'wave_id' ],
|
||||
},
|
||||
]
|
||||
: []),
|
||||
{
|
||||
name: `idx_${prefix}_wave`,
|
||||
fields: [ 'status', 'wave_id' ],
|
||||
|
||||
86
app/model/report_definition.js
Normal file
86
app/model/report_definition.js
Normal file
@ -0,0 +1,86 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 报表模板定义 Model。
|
||||
* 报表采用「配置驱动」:name/type(注册方法 key)/file_name(导出文件名模板)/fields(勾选字段),
|
||||
* 唯一性由主键 id 承担,新报表只需加配置行,免发版。
|
||||
*
|
||||
* @param {import('egg').Application} app Egg 应用实例。
|
||||
* @return {import('sequelize').ModelCtor<import('sequelize').Model>} Sequelize 模型。
|
||||
*/
|
||||
module.exports = app => {
|
||||
const { BIGINT, STRING, TINYINT, DATE } = app.Sequelize;
|
||||
|
||||
const ReportDefinition = app.model.define('report_definition', {
|
||||
id: {
|
||||
type: BIGINT(20).UNSIGNED,
|
||||
primaryKey: true,
|
||||
autoIncrement: true,
|
||||
allowNull: false,
|
||||
comment: '主键',
|
||||
},
|
||||
name: {
|
||||
type: STRING(100),
|
||||
allowNull: false,
|
||||
comment: '报表名称',
|
||||
},
|
||||
type: {
|
||||
type: STRING(50),
|
||||
allowNull: false,
|
||||
comment: '报表类型(内置查询器注册 key,如 stockFlow)',
|
||||
},
|
||||
file_name: {
|
||||
type: STRING(200),
|
||||
allowNull: false,
|
||||
comment: '导出文件名模板(支持 {date} 占位,如 7日出入库_{date}.xlsx)',
|
||||
},
|
||||
fields: {
|
||||
type: app.Sequelize.JSON,
|
||||
allowNull: true,
|
||||
comment: '勾选的字段 key 数组(列头/合并/样式/格式化由类型硬编码字段规格决定)',
|
||||
},
|
||||
is_enabled: {
|
||||
type: TINYINT(1),
|
||||
allowNull: false,
|
||||
defaultValue: 1,
|
||||
comment: '是否启用:0=停用 1=启用',
|
||||
},
|
||||
remark: {
|
||||
type: STRING(500),
|
||||
allowNull: true,
|
||||
comment: '备注',
|
||||
},
|
||||
created_at: {
|
||||
type: DATE,
|
||||
allowNull: false,
|
||||
defaultValue: app.Sequelize.literal('CURRENT_TIMESTAMP'),
|
||||
comment: '创建时间',
|
||||
},
|
||||
updated_at: {
|
||||
type: DATE,
|
||||
allowNull: false,
|
||||
defaultValue: app.Sequelize.literal('CURRENT_TIMESTAMP'),
|
||||
comment: '更新时间',
|
||||
},
|
||||
deleted_at: {
|
||||
type: DATE,
|
||||
allowNull: true,
|
||||
comment: '软删除时间',
|
||||
},
|
||||
}, {
|
||||
tableName: 'wms_report_definition',
|
||||
freezeTableName: true,
|
||||
underscored: true,
|
||||
timestamps: true,
|
||||
createdAt: 'created_at',
|
||||
updatedAt: 'updated_at',
|
||||
deletedAt: 'deleted_at',
|
||||
paranoid: true,
|
||||
comment: '报表模板定义表',
|
||||
indexes: [
|
||||
{ name: 'idx_deleted_at', fields: [ 'deleted_at' ] },
|
||||
],
|
||||
});
|
||||
|
||||
return ReportDefinition;
|
||||
};
|
||||
134
app/model/report_delivery_log.js
Normal file
134
app/model/report_delivery_log.js
Normal file
@ -0,0 +1,134 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 报表投递记录 Model。
|
||||
* 状态机 pending → exporting → delivered/failed/cancelled;
|
||||
* 失败按退避重试(retry_count/next_retry_at),幂等键
|
||||
* uk_store_report_biz_time 保证同一货主同一报表定义同一数据日期同一时间点不重复投递;
|
||||
* report_definition_id 关联报表定义,report_name 为投递时报表名称快照(审计回放)。
|
||||
*
|
||||
* @param {import('egg').Application} app Egg 应用实例。
|
||||
* @return {import('sequelize').ModelCtor<import('sequelize').Model>} Sequelize 模型。
|
||||
*/
|
||||
module.exports = app => {
|
||||
const { BIGINT, INTEGER, STRING, DATE, DATEONLY } = app.Sequelize;
|
||||
|
||||
const ReportDeliveryLog = app.model.define('report_delivery_log', {
|
||||
id: {
|
||||
type: BIGINT(20).UNSIGNED,
|
||||
primaryKey: true,
|
||||
autoIncrement: true,
|
||||
allowNull: false,
|
||||
comment: '主键',
|
||||
},
|
||||
warehouse_id: {
|
||||
type: BIGINT(20).UNSIGNED,
|
||||
allowNull: false,
|
||||
defaultValue: 0,
|
||||
comment: '仓库ID(生成报表时注入的仓库维度)',
|
||||
},
|
||||
store_id: {
|
||||
type: BIGINT(20).UNSIGNED,
|
||||
allowNull: false,
|
||||
comment: '货主ID(wms_store.id)',
|
||||
},
|
||||
report_definition_id: {
|
||||
type: BIGINT(20).UNSIGNED,
|
||||
allowNull: false,
|
||||
comment: '报表定义ID(wms_report_definition.id)',
|
||||
},
|
||||
report_name: {
|
||||
type: STRING(100),
|
||||
allowNull: true,
|
||||
comment: '报表名称快照(投递时的定义 name,审计回放)',
|
||||
},
|
||||
biz_date: {
|
||||
type: DATEONLY,
|
||||
allowNull: false,
|
||||
comment: '数据日期(T-1 自然日)',
|
||||
},
|
||||
time_point: {
|
||||
type: STRING(5),
|
||||
allowNull: false,
|
||||
comment: '命中的投递时间点(HH:mm)',
|
||||
},
|
||||
status: {
|
||||
type: STRING(20),
|
||||
allowNull: false,
|
||||
defaultValue: 'pending',
|
||||
comment: '状态:pending/exporting/delivered/failed/cancelled',
|
||||
},
|
||||
channel: {
|
||||
type: STRING(20),
|
||||
allowNull: false,
|
||||
defaultValue: 'inbox',
|
||||
comment: '投递渠道快照:inbox=站内信群(wecom/link 已弃用)',
|
||||
},
|
||||
file_url: {
|
||||
type: STRING(500),
|
||||
allowNull: true,
|
||||
comment: '报表文件下载链接(COS 带有效期)',
|
||||
},
|
||||
retry_count: {
|
||||
type: INTEGER(3),
|
||||
allowNull: false,
|
||||
defaultValue: 0,
|
||||
comment: '重试次数',
|
||||
},
|
||||
next_retry_at: {
|
||||
type: DATE,
|
||||
allowNull: true,
|
||||
comment: '下次可投递时间(失败退避)',
|
||||
},
|
||||
error_message: {
|
||||
type: STRING(500),
|
||||
allowNull: true,
|
||||
comment: '最近一次失败原因',
|
||||
},
|
||||
delivered_at: {
|
||||
type: DATE,
|
||||
allowNull: true,
|
||||
comment: '投递成功时间',
|
||||
},
|
||||
notify_targets: {
|
||||
type: app.Sequelize.JSON,
|
||||
allowNull: true,
|
||||
comment: '投递目标快照:{group_ids:[],member_ids:[]}(本次实际发送的群/成员,审计回放)',
|
||||
},
|
||||
created_at: {
|
||||
type: DATE,
|
||||
allowNull: false,
|
||||
defaultValue: app.Sequelize.literal('CURRENT_TIMESTAMP'),
|
||||
comment: '创建时间',
|
||||
},
|
||||
updated_at: {
|
||||
type: DATE,
|
||||
allowNull: false,
|
||||
defaultValue: app.Sequelize.literal('CURRENT_TIMESTAMP'),
|
||||
comment: '更新时间',
|
||||
},
|
||||
deleted_at: {
|
||||
type: DATE,
|
||||
allowNull: true,
|
||||
comment: '软删除时间',
|
||||
},
|
||||
}, {
|
||||
tableName: 'wms_report_delivery_log',
|
||||
freezeTableName: true,
|
||||
underscored: true,
|
||||
timestamps: true,
|
||||
createdAt: 'created_at',
|
||||
updatedAt: 'updated_at',
|
||||
deletedAt: 'deleted_at',
|
||||
paranoid: true,
|
||||
comment: '报表投递记录表',
|
||||
indexes: [
|
||||
{ name: 'uk_store_report_biz_time', unique: true, fields: [ 'store_id', 'report_definition_id', 'biz_date', 'time_point', 'deleted_at' ] },
|
||||
{ name: 'idx_status_id', fields: [ 'status', 'id' ] },
|
||||
{ name: 'idx_status_updated_at', fields: [ 'status', 'updated_at' ] },
|
||||
{ name: 'idx_deleted_at', fields: [ 'deleted_at' ] },
|
||||
],
|
||||
});
|
||||
|
||||
return ReportDeliveryLog;
|
||||
};
|
||||
115
app/model/report_delivery_plan.js
Normal file
115
app/model/report_delivery_plan.js
Normal file
@ -0,0 +1,115 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 货主报表投递计划 Model。
|
||||
* 每个货主(store_id)对每个报表定义(report_definition_id)可配置每日多个投递时间点
|
||||
* (schedule_times JSON 数组),由分钟级扫描调度按 HH:mm 命中后生成并投递报表。
|
||||
*
|
||||
* @param {import('egg').Application} app Egg 应用实例。
|
||||
* @return {import('sequelize').ModelCtor<import('sequelize').Model>} Sequelize 模型。
|
||||
*/
|
||||
module.exports = app => {
|
||||
const { BIGINT, INTEGER, STRING, TINYINT, DATE } = app.Sequelize;
|
||||
|
||||
const ReportDeliveryPlan = app.model.define('report_delivery_plan', {
|
||||
id: {
|
||||
type: BIGINT(20).UNSIGNED,
|
||||
primaryKey: true,
|
||||
autoIncrement: true,
|
||||
allowNull: false,
|
||||
comment: '主键',
|
||||
},
|
||||
store_id: {
|
||||
type: BIGINT(20).UNSIGNED,
|
||||
allowNull: false,
|
||||
comment: '货主ID(wms_store.id)',
|
||||
},
|
||||
report_definition_id: {
|
||||
type: BIGINT(20).UNSIGNED,
|
||||
allowNull: false,
|
||||
comment: '报表定义ID(wms_report_definition.id)',
|
||||
},
|
||||
name: {
|
||||
type: STRING(100),
|
||||
allowNull: true,
|
||||
comment: '计划名称(前端展示用,缺省时可用报表名称兜底)',
|
||||
},
|
||||
schedule_times: {
|
||||
type: app.Sequelize.JSON,
|
||||
allowNull: false,
|
||||
comment: '每日投递时间点数组,如 ["08:30","17:00"](HH:mm)',
|
||||
},
|
||||
channel: {
|
||||
type: STRING(20),
|
||||
allowNull: false,
|
||||
defaultValue: 'inbox',
|
||||
comment: '投递渠道:inbox=站内信群(wecom/link 已弃用)',
|
||||
},
|
||||
enabled: {
|
||||
type: TINYINT(1),
|
||||
allowNull: false,
|
||||
defaultValue: 1,
|
||||
comment: '是否启用:0=停用 1=启用',
|
||||
},
|
||||
late_grace_minutes: {
|
||||
type: INTEGER(11),
|
||||
allowNull: false,
|
||||
defaultValue: 60,
|
||||
comment: '补投宽限分钟:重启/漏跑后在该窗口内补投,超窗作废',
|
||||
},
|
||||
notify_template: {
|
||||
type: STRING(500),
|
||||
allowNull: true,
|
||||
comment: '文本通知模板,支持 {time}/{url}/{report_name}/{biz_date} 标签',
|
||||
},
|
||||
notify_group_ids: {
|
||||
type: app.Sequelize.JSON,
|
||||
allowNull: true,
|
||||
comment: '通知群ID数组(wms_inbox_group.id,多选;空=不指定群)',
|
||||
},
|
||||
notify_member_ids: {
|
||||
type: app.Sequelize.JSON,
|
||||
allowNull: true,
|
||||
comment: '通知成员ID数组(外部IM用户ID,多选;目标侧支持数组)',
|
||||
},
|
||||
remark: {
|
||||
type: STRING(500),
|
||||
allowNull: true,
|
||||
comment: '备注',
|
||||
},
|
||||
created_at: {
|
||||
type: DATE,
|
||||
allowNull: false,
|
||||
defaultValue: app.Sequelize.literal('CURRENT_TIMESTAMP'),
|
||||
comment: '创建时间',
|
||||
},
|
||||
updated_at: {
|
||||
type: DATE,
|
||||
allowNull: false,
|
||||
defaultValue: app.Sequelize.literal('CURRENT_TIMESTAMP'),
|
||||
comment: '更新时间',
|
||||
},
|
||||
deleted_at: {
|
||||
type: DATE,
|
||||
allowNull: true,
|
||||
comment: '软删除时间',
|
||||
},
|
||||
}, {
|
||||
tableName: 'wms_report_delivery_plan',
|
||||
freezeTableName: true,
|
||||
underscored: true,
|
||||
timestamps: true,
|
||||
createdAt: 'created_at',
|
||||
updatedAt: 'updated_at',
|
||||
deletedAt: 'deleted_at',
|
||||
paranoid: true,
|
||||
comment: '货主报表投递计划表',
|
||||
indexes: [
|
||||
{ name: 'uk_store_report_definition', unique: true, fields: [ 'store_id', 'report_definition_id', 'deleted_at' ] },
|
||||
{ name: 'idx_enabled_deleted', fields: [ 'enabled', 'deleted_at' ] },
|
||||
{ name: 'idx_deleted_at', fields: [ 'deleted_at' ] },
|
||||
],
|
||||
});
|
||||
|
||||
return ReportDeliveryPlan;
|
||||
};
|
||||
@ -62,6 +62,7 @@ module.exports = app => {
|
||||
default_location_id: null,
|
||||
single_order_pack_max_minutes: 3,
|
||||
group_order_pack_max_minutes: 40,
|
||||
return_unpack_max_record_minutes: 5,
|
||||
inventory_warning_rules: DEFAULT_INVENTORY_WARNING_RULES,
|
||||
auto_outbound_rules: DEFAULT_AUTO_OUTBOUND_RULES,
|
||||
cutoff_order_enabled: 1,
|
||||
@ -267,6 +268,17 @@ module.exports = app => {
|
||||
normalized.group_order_pack_max_minutes = groupOrderPackMaxMinutes;
|
||||
}
|
||||
|
||||
const rawReturnUnpackMaxRecordMinutes = parsed.return_unpack_max_record_minutes;
|
||||
if (rawReturnUnpackMaxRecordMinutes === undefined || rawReturnUnpackMaxRecordMinutes === null || rawReturnUnpackMaxRecordMinutes === '') {
|
||||
normalized.return_unpack_max_record_minutes = DEFAULT_SUBJECT_CONFIG.return_unpack_max_record_minutes;
|
||||
} else {
|
||||
const returnUnpackMaxRecordMinutes = Number(rawReturnUnpackMaxRecordMinutes);
|
||||
if (!Number.isInteger(returnUnpackMaxRecordMinutes) || returnUnpackMaxRecordMinutes <= 0) {
|
||||
throw new Error('subject_config.return_unpack_max_record_minutes 必须是大于 0 的整数');
|
||||
}
|
||||
normalized.return_unpack_max_record_minutes = returnUnpackMaxRecordMinutes;
|
||||
}
|
||||
|
||||
const rawExcludeRemarks = parsed.auto_allocate_express_exclude_remarks;
|
||||
if (rawExcludeRemarks === undefined || rawExcludeRemarks === null || rawExcludeRemarks === '') {
|
||||
normalized.auto_allocate_express_exclude_remarks = [];
|
||||
|
||||
42
app/schedule/report_delivery_dispatch.js
Normal file
42
app/schedule/report_delivery_dispatch.js
Normal file
@ -0,0 +1,42 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 货主报表定时投递调度。
|
||||
* 每分钟在单 worker 中扫描一次 wms_report_delivery_plan,
|
||||
* 命中投递时间点(含宽限)后幂等生成并投递报表(进程内布尔防重入)。
|
||||
*/
|
||||
module.exports = {
|
||||
schedule: {
|
||||
interval: '1m',
|
||||
type: 'worker',
|
||||
immediate: false,
|
||||
disable: false,
|
||||
},
|
||||
|
||||
/**
|
||||
* 执行报表投递调度。
|
||||
* @param {Object} ctx Egg 上下文。
|
||||
* @return {Promise<void>} 无返回值。
|
||||
*/
|
||||
async task(ctx) {
|
||||
if (ctx.app._reportDeliveryDispatchRunning) {
|
||||
return;
|
||||
}
|
||||
|
||||
ctx.app._reportDeliveryDispatchRunning = true;
|
||||
|
||||
try {
|
||||
const summary = await ctx.service.systems.reportDelivery.dispatch();
|
||||
|
||||
ctx.logger.info(
|
||||
`[report-delivery-dispatch] 本轮投递完成:扫描 ${summary && summary.scanned || 0} 个计划,`
|
||||
+ `投递 ${summary && summary.delivered || 0},失败 ${summary && summary.failed || 0},`
|
||||
+ `跳过 ${summary && summary.skipped || 0}`
|
||||
);
|
||||
} catch (error) {
|
||||
ctx.logger.error(`[report-delivery-dispatch] 投递调度执行失败: ${error.message}`);
|
||||
} finally {
|
||||
ctx.app._reportDeliveryDispatchRunning = false;
|
||||
}
|
||||
},
|
||||
};
|
||||
@ -9,11 +9,13 @@ const MainService = require('../main');
|
||||
class InboxSystemService extends MainService {
|
||||
/**
|
||||
* 群管理子入口,供 /system dispatcher 按 inbox.group.* 路径访问。
|
||||
* @return {{list: Function, disable: Function, update: Function, reset: Function, messages: Function, checkAuth: Function}}
|
||||
* @return {{list: Function, quickList: Function, members: Function, disable: Function, update: Function, reset: Function, messages: Function, checkAuth: Function}} 群管理子入口方法集合。
|
||||
*/
|
||||
get group() {
|
||||
return {
|
||||
list: data => this.groupList(data),
|
||||
quickList: data => this.groupQuickList(data),
|
||||
members: data => this.groupMembers(data),
|
||||
disable: data => this.groupDisable(data),
|
||||
update: data => this.groupUpdate(data),
|
||||
reset: data => this.groupReset(data),
|
||||
@ -24,7 +26,7 @@ class InboxSystemService extends MainService {
|
||||
|
||||
/**
|
||||
* 消息管理子入口,供 /system dispatcher 按 inbox.message.* 路径访问。
|
||||
* @return {{list: Function, detail: Function, thread: Function, reply: Function, stats: Function, checkAuth: Function}}
|
||||
* @return {{list: Function, detail: Function, thread: Function, reply: Function, stats: Function, checkAuth: Function}} 消息管理子入口方法集合。
|
||||
*/
|
||||
get message() {
|
||||
const { ctx } = this;
|
||||
@ -100,6 +102,61 @@ class InboxSystemService extends MainService {
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 群快速查询(下拉选择用,不分页)。
|
||||
* 双维度可选过滤,均不传时返回所有仓库/货主的群:
|
||||
* - store_id:货主维度,透传为底层参数 storeId;
|
||||
* - warehouse_id:仓库维度,透传为底层参数 warehouseId;
|
||||
* - 两者可同时传(AND 关系),也可都不传(不加对应过滤条件)。
|
||||
*
|
||||
* @param {Object} data 请求数据。
|
||||
* @param {string} [data.keyword] 关键词,模糊匹配群名称与外部群ID。
|
||||
* @param {string} [data.groupType] 按群类型筛选:store / warehouse / express。
|
||||
* @param {number} [data.limit=20] 返回条数上限,最大 100。
|
||||
* @param {number|string} [data.store_id] 货主ID(可选,对应 wms_inbox_group.store_id 列)。
|
||||
* @param {number|string} [data.warehouse_id] 仓库ID(可选,对应 wms_inbox_group.warehouse_id 列)。
|
||||
* @return {Promise<Object>} { list: 群快速列表 }。
|
||||
*/
|
||||
async groupQuickList(data = {}) {
|
||||
const { ctx } = this;
|
||||
const {
|
||||
keyword, groupType, limit,
|
||||
store_id: storeId,
|
||||
warehouse_id: warehouseId,
|
||||
} = data;
|
||||
|
||||
return await ctx.service.systems.inbox.group.quickList({
|
||||
storeId,
|
||||
warehouseId,
|
||||
keyword,
|
||||
groupType,
|
||||
limit,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询一个或多个群的成员列表(下拉选择用,多群聚合)。
|
||||
* warehouseId 从 ctx.user.store_id 自动注入,不信任前端传值。
|
||||
*
|
||||
* @param {Object} data 请求数据。
|
||||
* @param {Array<number|string>} data.groupIds 群内部主键ID数组(必填,非空且每个元素为正整数)。
|
||||
* @param {string} [data.keyword] 关键词,模糊匹配 user_name / user_id。
|
||||
* @param {number} [data.limit=20] 返回条数上限,最大 100。
|
||||
* @return {Promise<Object>} { list: 群成员列表 }。
|
||||
*/
|
||||
async groupMembers(data = {}) {
|
||||
const { ctx } = this;
|
||||
const { groupIds, keyword, limit } = data;
|
||||
const warehouseId = Number(ctx.user?.store_id || 0);
|
||||
|
||||
return await ctx.service.systems.inbox.group.members({
|
||||
groupIds,
|
||||
warehouseId,
|
||||
keyword,
|
||||
limit,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 禁用 / 解禁群。
|
||||
* warehouseId 从 ctx.user.store_id 自动注入。
|
||||
|
||||
@ -3,6 +3,7 @@
|
||||
const OrderBaseService = require('./base');
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const { stripWaybillSegmentSuffix, escapeLikeWildcards } = require('../../../lib/waybill_code');
|
||||
|
||||
const DEBUG_LOG = path.join(__dirname, '..', '..', '..', '..', 'temp', 'quickSearch_debug.log');
|
||||
|
||||
@ -62,7 +63,8 @@ class DeliveryOrderService extends OrderBaseService {
|
||||
|
||||
/**
|
||||
* 订单快速搜索。
|
||||
* 跨表联合搜索:运单号(wms_order_express,精确)、发货单号/外部订单号/平台交易单号(dispatch 表,模糊)。
|
||||
* 跨表联合搜索:运单号(wms_order_express,精确匹配,含剥离一单多件分段后缀后的主体等值匹配)、
|
||||
* 发货单号/外部订单号/平台交易单号(dispatch 表,模糊)。
|
||||
* 返回匹配的订单列表(最多 20 条),包含订单关键信息及关联运单号。
|
||||
*
|
||||
* @param {Object} data 请求体。
|
||||
@ -96,10 +98,19 @@ class DeliveryOrderService extends OrderBaseService {
|
||||
|
||||
// ====== 第一步:express 表 OR 搜索 ======
|
||||
dbg('--- Step1: express OR query ---');
|
||||
// 业务规则:运单号先剥离一单多件包裹序号后缀(如 -1-1-),主体必须等值匹配,
|
||||
// 不得落入模糊 like;发货单号/平台交易单号保留模糊匹配能力
|
||||
const waybillBase = stripWaybillSegmentSuffix(keyword);
|
||||
const escapedWaybillBase = escapeLikeWildcards(waybillBase);
|
||||
const waybillConditions = [
|
||||
{ waybill_code: keyword },
|
||||
...(waybillBase !== keyword ? [{ waybill_code: waybillBase }] : []),
|
||||
...(escapedWaybillBase ? [{ waybill_code: { [Op.like]: `${escapedWaybillBase}-%` } }] : []),
|
||||
];
|
||||
const expressWhere = {
|
||||
warehouse_id: warehouseId,
|
||||
[Op.or]: [
|
||||
{ waybill_code: keyword },
|
||||
...waybillConditions,
|
||||
{ delivery_order_code: { [Op.like]: `%${keyword}%` } },
|
||||
{ source_order_codes: { [Op.like]: `%${keyword}%` } },
|
||||
],
|
||||
|
||||
@ -565,11 +565,13 @@ class WaveService extends OrderBaseService {
|
||||
/**
|
||||
* 获取当天前缀下的下一个波次序号(原子取号)。
|
||||
*
|
||||
* 基于序列表 wms_number_sequence 的单条 upsert 原子递增:
|
||||
* INSERT ... VALUES (LAST_INSERT_ID(:seed + 1)) ON DUPLICATE KEY UPDATE
|
||||
* current_seq = LAST_INSERT_ID(GREATEST(current_seq, :seed) + 1)
|
||||
* 基于序列表 wms_number_sequence 的 upsert 原子递增(唯一键 uk_warehouse_biz_date 串行化并发事务):
|
||||
* INSERT ... VALUES (:seed + 1) ON DUPLICATE KEY UPDATE
|
||||
* current_seq = GREATEST(current_seq, :seed) + 1
|
||||
* 其中 :seed 为当日该前缀主表已有最大序号,保证与历史编号对齐;
|
||||
* 同事务(同连接)内回读 LAST_INSERT_ID() 取回本次分配序号,并发下不再撞号。
|
||||
* upsert 后通过带锁当前读(SELECT ... FOR UPDATE)回读 current_seq,
|
||||
* 避免 REPEATABLE READ 快照读读到旧值导致撞号或跳号。
|
||||
* 注意:不再依赖 LAST_INSERT_ID() 回读,因为 fresh INSERT 时其会被序列表自增主键覆盖。
|
||||
*
|
||||
* @param {string} prefix 波次编号前缀。
|
||||
* @param {string} datePart 日期片段(YYYYMMDD)。
|
||||
@ -602,8 +604,8 @@ class WaveService extends OrderBaseService {
|
||||
// 原子取号:全局维度(warehouse_id=0)按「前缀+日期」递增,唯一键串行化并发事务
|
||||
await this.ctx.model.query(
|
||||
`INSERT INTO wms_number_sequence (warehouse_id, biz_type, date_part, current_seq, created_at, updated_at)
|
||||
VALUES (:warehouseId, :bizType, :datePart, LAST_INSERT_ID(:seed + 1), NOW(), NOW())
|
||||
ON DUPLICATE KEY UPDATE current_seq = LAST_INSERT_ID(GREATEST(current_seq, :seed) + 1), updated_at = NOW()`,
|
||||
VALUES (:warehouseId, :bizType, :datePart, :seed + 1, NOW(), NOW())
|
||||
ON DUPLICATE KEY UPDATE current_seq = GREATEST(current_seq, :seed) + 1, updated_at = NOW()`,
|
||||
{
|
||||
replacements: {
|
||||
warehouseId: 0,
|
||||
@ -615,14 +617,24 @@ class WaveService extends OrderBaseService {
|
||||
}
|
||||
);
|
||||
|
||||
// 带锁当前读回读:同事务已通过 upsert 持有该行排他锁(或经唯一键冲突等待串行化),
|
||||
// FOR UPDATE 返回本事务最新写入值或最新提交版本,不受旧快照影响
|
||||
const seqRows = await this.ctx.model.query(
|
||||
'SELECT LAST_INSERT_ID() AS seq',
|
||||
`SELECT current_seq
|
||||
FROM wms_number_sequence
|
||||
WHERE warehouse_id = :warehouseId AND biz_type = :bizType AND date_part = :datePart
|
||||
FOR UPDATE`,
|
||||
{
|
||||
replacements: {
|
||||
warehouseId: 0,
|
||||
bizType,
|
||||
datePart: normalizedDatePart,
|
||||
},
|
||||
type: this.ctx.model.QueryTypes.SELECT,
|
||||
transaction,
|
||||
}
|
||||
);
|
||||
const sequence = Number(seqRows && seqRows[0] && seqRows[0].seq || 0);
|
||||
const sequence = Number(seqRows && seqRows[0] && seqRows[0].current_seq || 0);
|
||||
if (!Number.isInteger(sequence) || sequence <= 0) {
|
||||
return 1;
|
||||
}
|
||||
@ -4926,6 +4938,8 @@ class WaveService extends OrderBaseService {
|
||||
* 批量解除波次任务提交接口。
|
||||
*
|
||||
* 仅处理当前登录仓库下的波次与订单,提交后异步执行。
|
||||
* 提交前校验:波次属于活动拣货任务、波次内存在已拣货完成或拣货中的订单、
|
||||
* 或波次状态已进入拣货中及后续环节时,拒绝取消波次。
|
||||
*
|
||||
* @param {Object} data 请求参数。
|
||||
* @param {number|string} [data.warehouse_id] 仓库ID(可选,若传入必须与当前上下文一致)。
|
||||
@ -4973,6 +4987,64 @@ class WaveService extends OrderBaseService {
|
||||
throw new Error('波次属于活动拣货任务,请通过任务取消接口处理');
|
||||
}
|
||||
|
||||
// 业务规则校验:波次内存在已拣货完成或拣货中的订单时禁止取消波次
|
||||
const orderModelForGuard = await this.getOrderModel('pendingOrder', warehouseId);
|
||||
const pickedOrderRows = await orderModelForGuard.findAll({
|
||||
attributes: [ 'id', 'wave_id', 'wave_no', 'pick_status' ],
|
||||
where: {
|
||||
warehouse_id: warehouseId,
|
||||
wave_id: { [Op.in]: normalizedWaveIds },
|
||||
pick_status: { [Op.in]: [ 'padding', 'fin' ] },
|
||||
},
|
||||
raw: true,
|
||||
});
|
||||
const normalizedPickedOrderRows = Array.isArray(pickedOrderRows) ? pickedOrderRows : [];
|
||||
if (normalizedPickedOrderRows.length > 0) {
|
||||
const blockedWaveIds = [ ...new Set(normalizedPickedOrderRows
|
||||
.map(row => Number(row && row.wave_id || 0))
|
||||
.filter(waveId => Number.isInteger(waveId) && waveId > 0)) ];
|
||||
const blockedOrderIds = normalizedPickedOrderRows
|
||||
.map(row => Number(row && row.id || 0))
|
||||
.filter(orderId => Number.isInteger(orderId) && orderId > 0);
|
||||
const shownOrderIds = blockedOrderIds.slice(0, 20).join(', ');
|
||||
const orderIdSuffix = blockedOrderIds.length > 20 ? ' 等' : '';
|
||||
return this.fail(
|
||||
`波次内存在已拣货完成或拣货中的订单,禁止取消波次:波次 ${blockedWaveIds.join(', ')},订单 ${shownOrderIds}${orderIdSuffix}`,
|
||||
{
|
||||
wave_ids: blockedWaveIds,
|
||||
order_ids: blockedOrderIds,
|
||||
},
|
||||
400
|
||||
);
|
||||
}
|
||||
|
||||
// 兜底校验:波次状态已进入拣货中及后续环节(拣货中/拣货完成/复核完成/打包完成)时禁止取消
|
||||
const advancedWaveRows = await this.ctx.model.query(
|
||||
`SELECT wave_id, wave_no, wave_status
|
||||
FROM wms_wave_batch
|
||||
WHERE warehouse_id = :warehouseId
|
||||
AND wave_id IN (:waveIds)
|
||||
AND wave_status >= 3`,
|
||||
{
|
||||
replacements: {
|
||||
warehouseId,
|
||||
waveIds: normalizedWaveIds,
|
||||
},
|
||||
type: this.ctx.model.QueryTypes.SELECT,
|
||||
}
|
||||
);
|
||||
const normalizedAdvancedWaveRows = Array.isArray(advancedWaveRows) ? advancedWaveRows : [];
|
||||
if (normalizedAdvancedWaveRows.length > 0) {
|
||||
const blockedWaveIds = normalizedAdvancedWaveRows
|
||||
.map(row => Number(row && row.wave_id || 0))
|
||||
.filter(waveId => Number.isInteger(waveId) && waveId > 0);
|
||||
return this.fail(
|
||||
`波次已进入拣货或后续环节,禁止取消波次:波次 ${blockedWaveIds.join(', ')}`,
|
||||
{ wave_ids: blockedWaveIds },
|
||||
400
|
||||
);
|
||||
}
|
||||
|
||||
const requestedTaskId = this.normalizeBatchCancelTaskId(data);
|
||||
const taskId = requestedTaskId || this.generateBatchCancelTaskId(warehouseId);
|
||||
const existingTask = await this.getBatchCancelTaskProgress(taskId);
|
||||
@ -8248,6 +8320,9 @@ class WaveService extends OrderBaseService {
|
||||
/**
|
||||
* 执行批量解除波次后台任务。
|
||||
*
|
||||
* 逐个波次处理:波次已进入拣货中及后续环节、或波次内存在已拣货完成/拣货中的订单时,
|
||||
* 跳过该波次并记录到 skipped_waves,避免删除已拣货波次;其余波次正常取消。
|
||||
*
|
||||
* @param {Object} params 任务参数。
|
||||
* @param {string} params.taskId 任务ID。
|
||||
* @param {number|string} [params.warehouseId] 仓库ID(兜底)。
|
||||
@ -8310,7 +8385,7 @@ class WaveService extends OrderBaseService {
|
||||
|
||||
const orderModel = await this.getOrderModel('pendingOrder', warehouseId);
|
||||
const querySql = `
|
||||
SELECT wave_id, wave_no
|
||||
SELECT wave_id, wave_no, wave_status
|
||||
FROM wms_wave_batch
|
||||
WHERE warehouse_id = :warehouseId
|
||||
AND wave_id IN (:ids)
|
||||
@ -8327,6 +8402,7 @@ class WaveService extends OrderBaseService {
|
||||
.map(row => ({
|
||||
wave_id: Number(row && row.wave_id || 0),
|
||||
wave_no: String(row && row.wave_no || '').trim(),
|
||||
wave_status: Number(row && row.wave_status || 0),
|
||||
}))
|
||||
.filter(item => Number.isInteger(item.wave_id) && item.wave_id > 0);
|
||||
|
||||
@ -8343,6 +8419,8 @@ class WaveService extends OrderBaseService {
|
||||
affected_wave_ids: [],
|
||||
affected_order_count: 0,
|
||||
canceled_wave_count: 0,
|
||||
skipped_wave_ids: [],
|
||||
skipped_wave_count: 0,
|
||||
duration_ms: Date.now() - startTime,
|
||||
},
|
||||
});
|
||||
@ -8354,13 +8432,64 @@ class WaveService extends OrderBaseService {
|
||||
let canceledWaveCount = 0;
|
||||
const affectedWaveIds = [];
|
||||
const removedOrderIdSet = new Set();
|
||||
const skippedWaves = [];
|
||||
|
||||
for (const wave of targetWaves) {
|
||||
const waveId = Number(wave.wave_id || 0);
|
||||
const waveNo = String(wave.wave_no || '').trim() || '未知波次';
|
||||
const waveStatus = Number(wave.wave_status || 0);
|
||||
|
||||
// 兜底校验:波次已进入拣货中及后续环节时跳过取消,避免删除已拣货波次
|
||||
if (waveStatus >= 3) {
|
||||
skippedWaves.push({
|
||||
wave_id: waveId,
|
||||
wave_no: waveNo,
|
||||
reason: 'wave_status_blocked',
|
||||
wave_status: waveStatus,
|
||||
});
|
||||
processedWaveCount += 1;
|
||||
await this.setBatchCancelTaskProgress(normalizedTaskId, 'running', {
|
||||
warehouse_id: warehouseId,
|
||||
total_wave_count: targetWaves.length,
|
||||
processed_wave_count: processedWaveCount,
|
||||
progress_percent: Math.min(100, Math.round((processedWaveCount / targetWaves.length) * 100)),
|
||||
});
|
||||
continue;
|
||||
}
|
||||
|
||||
const transaction = await this.ctx.model.transaction();
|
||||
|
||||
try {
|
||||
// 业务规则校验:波次内存在已拣货完成或拣货中的订单时跳过取消,防止删除已拣货波次
|
||||
const pickedOrderGuardRows = await orderModel.findAll({
|
||||
attributes: [ 'id', 'pick_status' ],
|
||||
where: {
|
||||
wave_id: waveId,
|
||||
pick_status: { [Op.in]: [ 'padding', 'fin' ] },
|
||||
},
|
||||
raw: true,
|
||||
transaction,
|
||||
});
|
||||
|
||||
const normalizedPickedOrderGuardRows = Array.isArray(pickedOrderGuardRows) ? pickedOrderGuardRows : [];
|
||||
if (normalizedPickedOrderGuardRows.length > 0) {
|
||||
await transaction.rollback();
|
||||
skippedWaves.push({
|
||||
wave_id: waveId,
|
||||
wave_no: waveNo,
|
||||
reason: 'picked_orders_exist',
|
||||
picked_order_count: normalizedPickedOrderGuardRows.length,
|
||||
});
|
||||
processedWaveCount += 1;
|
||||
await this.setBatchCancelTaskProgress(normalizedTaskId, 'running', {
|
||||
warehouse_id: warehouseId,
|
||||
total_wave_count: targetWaves.length,
|
||||
processed_wave_count: processedWaveCount,
|
||||
progress_percent: Math.min(100, Math.round((processedWaveCount / targetWaves.length) * 100)),
|
||||
});
|
||||
continue;
|
||||
}
|
||||
|
||||
const affectedOrderRows = await orderModel.findAll({
|
||||
attributes: [ 'id', 'wave_id', 'wave_no' ],
|
||||
where: {
|
||||
@ -8476,6 +8605,9 @@ class WaveService extends OrderBaseService {
|
||||
affected_wave_ids: affectedWaveIds,
|
||||
affected_order_count: affectedOrderCount,
|
||||
canceled_wave_count: canceledWaveCount,
|
||||
skipped_wave_ids: skippedWaves.map(item => item.wave_id),
|
||||
skipped_wave_count: skippedWaves.length,
|
||||
skipped_waves: skippedWaves,
|
||||
duration_ms: Date.now() - startTime,
|
||||
},
|
||||
});
|
||||
@ -8502,6 +8634,9 @@ class WaveService extends OrderBaseService {
|
||||
affected_wave_ids: affectedWaveIds,
|
||||
affected_order_count: affectedOrderCount,
|
||||
canceled_wave_count: canceledWaveCount,
|
||||
skipped_wave_ids: skippedWaves.map(item => item.wave_id),
|
||||
skipped_wave_count: skippedWaves.length,
|
||||
skipped_waves: skippedWaves,
|
||||
duration_ms: durationMs,
|
||||
},
|
||||
});
|
||||
@ -12426,13 +12561,17 @@ class WaveService extends OrderBaseService {
|
||||
/**
|
||||
* 公共拣货任务取消流程。
|
||||
*
|
||||
* 仅允许取消状态为 0/1/2/3 的任务。取消后会回收拣货车绑定。
|
||||
* 仅允许取消状态为 0/1 的任务。取消后会回收拣货车绑定,并物理删除该任务
|
||||
* 的任务-订单关联记录(wms_wave_pick_task_order),避免订单回池后残留脏数据。
|
||||
*
|
||||
* 按任务来源区分行为:
|
||||
* - source=1(PDA 抓取):释放关联波次(清空订单 wave_id、删除 wms_wave_batch),
|
||||
* 使订单可重新参与后续策略抓取;状态为 2/3 时还会回退拣货状态。
|
||||
* - source=0/1(PDA 抓取):释放关联波次(清空订单 wave_id、删除 wms_wave_batch),
|
||||
* 使订单可重新参与后续策略抓取。
|
||||
* - source=2(后台/扫描创建):不释放波次,仅作废任务(更新状态为 9、解绑拣货车)。
|
||||
*
|
||||
* 所有来源均会清理任务-波次关联(wms_wave_pick_task_wave)与任务-订单关联记录
|
||||
* (wms_wave_pick_task_order)。
|
||||
*
|
||||
* @param {Object} [params={}] 取消参数。
|
||||
* @param {Array<number>} params.taskIds 任务ID列表。
|
||||
* @param {number} params.warehouseId 仓库ID。
|
||||
@ -12690,6 +12829,21 @@ class WaveService extends OrderBaseService {
|
||||
});
|
||||
}
|
||||
|
||||
// 清理任务-订单关联记录(所有来源都需要):
|
||||
// 任务取消后订单回池,wms_wave_pick_task_order 的关联记录属于脏数据,必须物理删除,
|
||||
// 否则会污染后续任务进度统计、复核状态批量更新及车标快照兜底查询
|
||||
await this.ctx.model.query(`
|
||||
DELETE FROM wms_wave_pick_task_order
|
||||
WHERE task_id = :taskId
|
||||
AND warehouse_id = :warehouseId
|
||||
`, {
|
||||
replacements: {
|
||||
taskId,
|
||||
warehouseId,
|
||||
},
|
||||
transaction,
|
||||
});
|
||||
|
||||
// 当任务状态为待复核(2)或已完成(3)时,回退订单拣货状态(仅 PDA 抓取)
|
||||
if (!isScanCreated && [ 2, 3 ].includes(taskStatus)) {
|
||||
await this.ctx.model.query(`
|
||||
|
||||
294
app/service/systemMethods/report.js
Normal file
294
app/service/systemMethods/report.js
Normal file
@ -0,0 +1,294 @@
|
||||
'use strict';
|
||||
|
||||
const MainService = require('../main');
|
||||
const ReportDeliveryPlanMethodService = require('./report/deliveryPlan');
|
||||
const ReportDeliveryLogMethodService = require('./report/deliveryLog');
|
||||
const ReportDefinitionMethodService = require('./report/definition');
|
||||
|
||||
const REPORT_GENERATE_TASK_CACHE_KEY_PREFIX = 'report_generate_task_';
|
||||
const REPORT_GENERATE_TASK_CACHE_TTL_SECONDS = 1800;
|
||||
|
||||
/**
|
||||
* 系统方法层:report(配置驱动通用报表接口包装层)。
|
||||
* 仅做出口包装与导出任务编排,业务逻辑下沉 systems/report。
|
||||
*/
|
||||
class ReportMethodService extends MainService {
|
||||
/**
|
||||
* 初始化 report 方法层:配置免鉴权清单,并挂载子目录服务实例。
|
||||
* report.js 与 report/ 子目录同名并存时,egg 会把子目录服务作为静态属性挂在类构造器上,
|
||||
* ctx 层实例化后静态属性不可见,需按 storeWarehouse 同款模式在实例上显式挂载,
|
||||
* 保证 /system 网关可按 report.deliveryPlan.* / report.deliveryLog.* 路径解析。
|
||||
* @param {Egg.Context} ctx Egg 上下文对象。
|
||||
*/
|
||||
constructor(ctx) {
|
||||
super(ctx);
|
||||
const _noNeedLogin = '';
|
||||
const _noNeedRight = 'generate,generateTaskProgress,meta';
|
||||
const _noNeedLog = 'generate,generateTaskProgress';
|
||||
const _noNeedAuth = 'generate,generateTaskProgress,meta';
|
||||
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
|
||||
// 显式挂载子目录服务实例(与 storeWarehouse.js 挂载 store/warehouse 的模式一致)
|
||||
this.deliveryPlan = new ReportDeliveryPlanMethodService(ctx);
|
||||
this.deliveryLog = new ReportDeliveryLogMethodService(ctx);
|
||||
this.definition = new ReportDefinitionMethodService(ctx);
|
||||
}
|
||||
|
||||
/**
|
||||
* 提交报表导出异步任务(手动导出)。
|
||||
* warehouse_id 由服务端从登录上下文自动注入,前端无需传递。
|
||||
* @param {Object} data 请求体
|
||||
* @param {number} data.report_id 报表定义ID(必填,兼容 reportId)
|
||||
* @param {number} [data.reportId] 报表定义ID(驼峰写法,优先级高于 report_id)
|
||||
* @param {number} [data.store_id] 货主ID(可选,货主维度报表时传入)
|
||||
* @param {Object} [data.params] 查询器业务参数(如 bizDate)
|
||||
* @return {Promise<Object>} 统一 success 包装,data 为导出任务信息
|
||||
*/
|
||||
async generate(data = {}) {
|
||||
const { service } = this;
|
||||
const {
|
||||
report_id: reportIdSnake,
|
||||
reportId: reportIdCamel,
|
||||
store_id: storeIdSnake,
|
||||
storeId: storeIdCamel,
|
||||
params = {},
|
||||
} = data;
|
||||
|
||||
const reportId = Number(reportIdCamel ?? reportIdSnake ?? 0) || 0;
|
||||
if (!Number.isInteger(reportId) || reportId <= 0) {
|
||||
return this.fail('报表ID report_id 必须为正整数');
|
||||
}
|
||||
|
||||
// 服务端注入仓库维度(禁止前端传 warehouse_id)
|
||||
const warehouseId = Number(this.ctx.user && this.ctx.user.store_id) || 0;
|
||||
const storeId = Number(storeIdCamel ?? storeIdSnake ?? 0) || 0;
|
||||
|
||||
const taskId = this.generateExportTaskId();
|
||||
const taskPayload = {
|
||||
task_id: taskId,
|
||||
status: 'submitted',
|
||||
progress: 0,
|
||||
message: '导出任务已提交',
|
||||
result: null,
|
||||
error: '',
|
||||
};
|
||||
|
||||
await this.setExportTaskProgress(taskId, taskPayload);
|
||||
|
||||
setImmediate(async () => {
|
||||
try {
|
||||
await this.setExportTaskProgress(taskId, {
|
||||
task_id: taskId,
|
||||
status: 'running',
|
||||
progress: 10,
|
||||
message: '导出任务执行中',
|
||||
result: null,
|
||||
error: '',
|
||||
});
|
||||
|
||||
const result = await service.systems.report.generate({
|
||||
reportId,
|
||||
storeId: storeId > 0 ? storeId : null,
|
||||
warehouseId,
|
||||
params,
|
||||
});
|
||||
|
||||
await this.setExportTaskProgress(taskId, {
|
||||
task_id: taskId,
|
||||
status: 'success',
|
||||
progress: 100,
|
||||
message: '导出任务完成',
|
||||
result,
|
||||
error: '',
|
||||
});
|
||||
} catch (error) {
|
||||
const errorMessage = error && error.message ? error.message : `${error}`;
|
||||
await this.setExportTaskProgress(taskId, {
|
||||
task_id: taskId,
|
||||
status: 'failed',
|
||||
progress: 100,
|
||||
message: '导出任务失败',
|
||||
result: null,
|
||||
error: errorMessage,
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
return this.success('ok', {
|
||||
...taskPayload,
|
||||
update_time: Date.now(),
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询报表前端可读的列元数据(全量注册字段 + 勾选标记 + 窗口参数,不执行真实数据查询)。
|
||||
* @param {Object} data 请求体
|
||||
* @param {number} data.report_id 报表定义ID(必填,兼容 reportId)
|
||||
* @param {number} [data.reportId] 报表定义ID(驼峰写法,优先级高于 report_id)
|
||||
* @return {Promise<Object>} 统一 success 包装,data 为报表元数据
|
||||
*/
|
||||
async meta(data = {}) {
|
||||
const { service } = this;
|
||||
const {
|
||||
report_id: reportIdSnake,
|
||||
reportId: reportIdCamel,
|
||||
} = data;
|
||||
|
||||
const reportId = Number(reportIdCamel ?? reportIdSnake ?? 0) || 0;
|
||||
if (!Number.isInteger(reportId) || reportId <= 0) {
|
||||
return this.fail('报表ID report_id 必须为正整数');
|
||||
}
|
||||
|
||||
const reportMeta = await service.systems.report.getMeta({ reportId });
|
||||
const { id, ...rest } = reportMeta;
|
||||
|
||||
return this.success('ok', {
|
||||
report_id: id,
|
||||
...rest,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询报表导出任务进度。
|
||||
* @param {Object} data 请求体
|
||||
* @param {string} [data.task_id] 任务ID(下划线写法)
|
||||
* @param {string} [data.taskId] 任务ID(驼峰写法)
|
||||
* @return {Promise<Object>} 统一 success 包装
|
||||
*/
|
||||
async generateTaskProgress(data = {}) {
|
||||
const taskId = this.normalizeExportTaskId(data);
|
||||
if (!taskId) {
|
||||
return this.success('ok', {
|
||||
task_id: '',
|
||||
status: 'not_found',
|
||||
progress: 0,
|
||||
message: '任务不存在',
|
||||
result: null,
|
||||
error: '',
|
||||
download_url: '',
|
||||
update_time: Date.now(),
|
||||
});
|
||||
}
|
||||
|
||||
const cachedTask = await this.getExportTaskProgress(taskId);
|
||||
if (!cachedTask) {
|
||||
return this.success('ok', {
|
||||
task_id: taskId,
|
||||
status: 'not_found',
|
||||
progress: 0,
|
||||
message: '任务不存在',
|
||||
result: null,
|
||||
error: '',
|
||||
download_url: '',
|
||||
update_time: Date.now(),
|
||||
});
|
||||
}
|
||||
|
||||
const safeResult = this.isPlainObject(cachedTask.result) ? cachedTask.result : {};
|
||||
const downloadUrl = String(
|
||||
safeResult.url
|
||||
|| safeResult.cndUrl
|
||||
|| safeResult.cosUrl
|
||||
|| safeResult.fileKey
|
||||
|| ''
|
||||
);
|
||||
|
||||
return this.success('ok', {
|
||||
task_id: taskId,
|
||||
...cachedTask,
|
||||
download_url: downloadUrl,
|
||||
});
|
||||
}
|
||||
|
||||
// ==================== 导出任务辅助方法(局部实现,不新增公共代码) ====================
|
||||
|
||||
/**
|
||||
* 生成报表导出任务ID。
|
||||
* @return {string} 导出任务ID
|
||||
*/
|
||||
generateExportTaskId() {
|
||||
const warehouseId = this.ctx?.user?.store_id || 'unknown';
|
||||
const timestamp = Date.now();
|
||||
const randomToken = Math.random().toString(36).slice(2, 10);
|
||||
return `report_generate_${warehouseId}_${timestamp}_${randomToken}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 归一化导出任务ID。
|
||||
* @param {Object} data 请求体
|
||||
* @return {string} 归一化后的任务ID
|
||||
*/
|
||||
normalizeExportTaskId(data = {}) {
|
||||
const normalizedData = this.isPlainObject(data) ? data : {};
|
||||
return String(normalizedData.task_id || normalizedData.taskId || '').trim();
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取导出任务缓存键。
|
||||
* @param {string} taskId 任务ID
|
||||
* @return {string} 缓存键
|
||||
*/
|
||||
getExportTaskCacheKey(taskId = '') {
|
||||
const normalizedTaskId = String(taskId || '').trim();
|
||||
if (!normalizedTaskId) {
|
||||
return '';
|
||||
}
|
||||
return `${REPORT_GENERATE_TASK_CACHE_KEY_PREFIX}${normalizedTaskId}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 写入导出任务进度缓存。
|
||||
* @param {string} taskId 任务ID
|
||||
* @param {Object} payload 任务状态载荷
|
||||
* @return {Promise<void>} 无返回值
|
||||
*/
|
||||
async setExportTaskProgress(taskId = '', payload = {}) {
|
||||
const cacheKey = this.getExportTaskCacheKey(taskId);
|
||||
if (!cacheKey || typeof this.app.setCacheAsync !== 'function') {
|
||||
return;
|
||||
}
|
||||
|
||||
const safePayload = this.isPlainObject(payload) ? payload : {};
|
||||
const progressPayload = {
|
||||
task_id: String(taskId || '').trim(),
|
||||
status: String(safePayload.status || 'submitted').trim() || 'submitted',
|
||||
progress: Number.isFinite(Number(safePayload.progress)) ? Math.min(100, Math.max(0, Math.round(Number(safePayload.progress)))) : 0,
|
||||
message: String(safePayload.message || ''),
|
||||
result: safePayload.result ?? null,
|
||||
error: String(safePayload.error || ''),
|
||||
update_time: Date.now(),
|
||||
};
|
||||
|
||||
try {
|
||||
await this.app.setCacheAsync(cacheKey, progressPayload, REPORT_GENERATE_TASK_CACHE_TTL_SECONDS);
|
||||
} catch (error) {
|
||||
const errorMessage = error && error.message ? error.message : `${error}`;
|
||||
this.ctx.logger.warn(`[report.generate] 写入导出任务缓存失败: ${errorMessage}`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 读取导出任务进度缓存。
|
||||
* @param {string} taskId 任务ID
|
||||
* @return {Promise<Object|null>} 任务缓存
|
||||
*/
|
||||
async getExportTaskProgress(taskId = '') {
|
||||
const cacheKey = this.getExportTaskCacheKey(taskId);
|
||||
if (!cacheKey || typeof this.app.getCacheAsync !== 'function') {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
const cached = await this.app.getCacheAsync(cacheKey);
|
||||
if (!this.isPlainObject(cached)) {
|
||||
return null;
|
||||
}
|
||||
return cached;
|
||||
} catch (error) {
|
||||
const errorMessage = error && error.message ? error.message : `${error}`;
|
||||
this.ctx.logger.warn(`[report.generateTaskProgress] 读取导出任务缓存失败: ${errorMessage}`);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = ReportMethodService;
|
||||
137
app/service/systemMethods/report/definition.js
Normal file
137
app/service/systemMethods/report/definition.js
Normal file
@ -0,0 +1,137 @@
|
||||
'use strict';
|
||||
|
||||
const MainService = require('../../main');
|
||||
|
||||
/**
|
||||
* 系统方法层:report.definition(报表定义管理接口包装层)。
|
||||
* 仅做出口包装与参数解构,业务逻辑下沉 systems/report。
|
||||
*/
|
||||
class ReportDefinitionMethodService extends MainService {
|
||||
constructor(ctx) {
|
||||
super(ctx);
|
||||
const _noNeedLogin = '';
|
||||
// typeList 为只读公共元数据:免权限/免鉴权/免日志(与 report.meta 惯例一致),仍要求登录;
|
||||
// save/list/delete 属定义管理类操作:不声明免权限,仅通配符角色(超级管理员/仓库管理员)可用,
|
||||
// 后续由 wms_permission 同步流程按需授权,不扩大任何角色授权范围
|
||||
const _noNeedRight = 'typeList';
|
||||
const _noNeedLog = 'typeList';
|
||||
const _noNeedAuth = 'typeList';
|
||||
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询报表类型注册清单(内置查询器 + 标题/描述/窗口参数 + 全量字段清单)。
|
||||
* 免权限只读(仅登录),供前端报表配置页渲染类型下拉与字段勾选。
|
||||
* @param {Object} data 请求体(无必填参数,兼容空对象)
|
||||
* @return {Promise<Object>} 统一 success 包装,data 为 { list: Array<Object> } 注册类型清单
|
||||
*/
|
||||
async typeList(data = {}) {
|
||||
void data;
|
||||
const { service } = this;
|
||||
const types = await service.systems.report.listRegisteredTypes();
|
||||
return this.success('ok', {
|
||||
list: types,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 新增/更新报表定义(按 id upsert:未传 id 视为新增,未传字段不覆盖)。
|
||||
* @param {Object} data 请求体
|
||||
* @param {number} [data.id] 报表定义ID(正整数;不传视为新增)
|
||||
* @param {string} data.name 报表名称(必填,≤100)
|
||||
* @param {string} data.type 报表类型(注册方法 key,如 stockFlow;新增必填)
|
||||
* @param {string} data.file_name 导出文件名模板(支持 {date};新增必填,≤200,兼容 fileName)
|
||||
* @param {Array<string>} data.fields 勾选字段 key 数组(新增必填,须为该类型注册字段子集)
|
||||
* @param {number} [data.is_enabled] 是否启用(0/1)
|
||||
* @param {string} [data.remark] 备注(≤500)
|
||||
* @return {Promise<Object>} 统一 success 包装,data 为保存后的报表定义视图
|
||||
*/
|
||||
async save(data = {}) {
|
||||
const { service } = this;
|
||||
const {
|
||||
id,
|
||||
name,
|
||||
type,
|
||||
file_name: fileNameSnake,
|
||||
fileName: fileNameCamel,
|
||||
fields,
|
||||
is_enabled: isEnabled,
|
||||
remark,
|
||||
} = data;
|
||||
|
||||
// 仅附加入参中存在的字段(undefined 不进入参数对象),保持「未传不覆盖」语义
|
||||
const saveArgs = { id, name, type };
|
||||
const normalizedFileName = fileNameCamel !== undefined ? fileNameCamel : fileNameSnake;
|
||||
if (normalizedFileName !== undefined) {
|
||||
saveArgs.fileName = normalizedFileName;
|
||||
}
|
||||
if (fields !== undefined) {
|
||||
saveArgs.fields = fields;
|
||||
}
|
||||
if (isEnabled !== undefined) {
|
||||
saveArgs.isEnabled = isEnabled;
|
||||
}
|
||||
if (remark !== undefined) {
|
||||
saveArgs.remark = remark;
|
||||
}
|
||||
|
||||
try {
|
||||
const result = await service.systems.report.saveDefinition(saveArgs);
|
||||
return this.success('ok', result);
|
||||
} catch (error) {
|
||||
return this.fail(error.message || '报表定义保存失败');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 分页查询报表定义列表。
|
||||
* @param {Object} data 请求体
|
||||
* @param {Object} [data.where] 查询条件(name 模糊关键字、type/is_enabled 精确)
|
||||
* @param {Object} [data.pagination] 分页 { page, pageSize }
|
||||
* @param {Object} [data.sort] 排序 { sortField, sortOrder }(白名单:id/name/type/is_enabled/created_at/updated_at)
|
||||
* @return {Promise<Object>} 统一 success 包装,data 为 { list, total, page, pageSize }
|
||||
*/
|
||||
async list(data = {}) {
|
||||
const { service } = this;
|
||||
const { whereValue = {} } = this.prepareWhereContext(data);
|
||||
const {
|
||||
name: nameKeyword,
|
||||
type,
|
||||
is_enabled: isEnabled,
|
||||
} = whereValue;
|
||||
const { pagination = {}, sort = {} } = data;
|
||||
|
||||
try {
|
||||
const result = await service.systems.report.listDefinitions({
|
||||
nameKeyword,
|
||||
type,
|
||||
isEnabled,
|
||||
pagination,
|
||||
sort,
|
||||
});
|
||||
return this.success('ok', result);
|
||||
} catch (error) {
|
||||
return this.fail(error.message || '报表定义列表查询失败');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 软删除报表定义(存在启用中的投递计划引用时拦截)。
|
||||
* @param {Object} data 请求体
|
||||
* @param {number} data.id 报表定义ID(必填,正整数)
|
||||
* @return {Promise<Object>} 统一 success 包装,data 为 { id, deleted }
|
||||
*/
|
||||
async delete(data = {}) {
|
||||
const { service } = this;
|
||||
const { id } = data;
|
||||
|
||||
try {
|
||||
const result = await service.systems.report.deleteDefinition({ id });
|
||||
return this.success('ok', result);
|
||||
} catch (error) {
|
||||
return this.fail(error.message || '报表定义删除失败');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = ReportDefinitionMethodService;
|
||||
50
app/service/systemMethods/report/deliveryLog.js
Normal file
50
app/service/systemMethods/report/deliveryLog.js
Normal file
@ -0,0 +1,50 @@
|
||||
'use strict';
|
||||
|
||||
const MainService = require('../../main');
|
||||
|
||||
/**
|
||||
* 系统方法层:report.deliveryLog(货主报表投递记录审计查询接口包装层)。
|
||||
* 仅做出口包装与参数解构,业务逻辑下沉 systems/reportDelivery。
|
||||
*/
|
||||
class ReportDeliveryLogMethodService extends MainService {
|
||||
constructor(ctx) {
|
||||
super(ctx);
|
||||
const _noNeedLogin = '';
|
||||
// 审计查询属于管理类操作:不声明免权限,仅通配符角色(超级管理员/仓库管理员)可用,
|
||||
// 后续由 wms_permission 同步流程按需授权,不扩大任何角色授权范围
|
||||
const _noNeedRight = '';
|
||||
const _noNeedLog = '';
|
||||
const _noNeedAuth = '';
|
||||
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
|
||||
}
|
||||
|
||||
/**
|
||||
* 分页查询投递记录(审计)。
|
||||
* @param {Object} data 请求体
|
||||
* @param {Object} [data.where] 查询条件(store_id/report_id/status)
|
||||
* @param {Object} [data.pagination] 分页 { page, pageSize }
|
||||
* @param {Object} [data.sort] 排序 { sortField, sortOrder }
|
||||
* @return {Promise<Object>} 统一 success 包装
|
||||
*/
|
||||
async list(data = {}) {
|
||||
const { service } = this;
|
||||
const { whereValue = {} } = this.prepareWhereContext(data);
|
||||
const {
|
||||
store_id: storeId,
|
||||
report_id: reportId,
|
||||
status,
|
||||
} = whereValue;
|
||||
const { pagination = {}, sort = {} } = data;
|
||||
|
||||
const result = await service.systems.reportDelivery.listLogs({
|
||||
storeId,
|
||||
reportId,
|
||||
status,
|
||||
pagination,
|
||||
sort,
|
||||
});
|
||||
return this.success('ok', result);
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = ReportDeliveryLogMethodService;
|
||||
130
app/service/systemMethods/report/deliveryPlan.js
Normal file
130
app/service/systemMethods/report/deliveryPlan.js
Normal file
@ -0,0 +1,130 @@
|
||||
'use strict';
|
||||
|
||||
const MainService = require('../../main');
|
||||
|
||||
/**
|
||||
* 系统方法层:report.deliveryPlan(货主报表投递计划接口包装层)。
|
||||
* 仅做出口包装与参数解构,业务逻辑下沉 systems/reportDelivery。
|
||||
*/
|
||||
class ReportDeliveryPlanMethodService extends MainService {
|
||||
constructor(ctx) {
|
||||
super(ctx);
|
||||
const _noNeedLogin = '';
|
||||
// 计划管理属于管理类操作:不声明免权限,仅通配符角色(超级管理员/仓库管理员)可用,
|
||||
// 后续由 wms_permission 同步流程按需授权,不扩大任何角色授权范围
|
||||
const _noNeedRight = '';
|
||||
const _noNeedLog = '';
|
||||
const _noNeedAuth = '';
|
||||
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
|
||||
}
|
||||
|
||||
/**
|
||||
* 新增/更新投递计划(货主+报表定义ID唯一,存在则更新)。
|
||||
* @param {Object} data 请求体
|
||||
* @param {number} data.store_id 货主ID(必填)
|
||||
* @param {number} data.report_id 报表定义ID(必填,兼容 reportId)
|
||||
* @param {Array<string>} data.schedule_times 每日投递时间点数组(HH:mm,自动去重排序)
|
||||
* @param {string} [data.channel='inbox'] 投递渠道(仅支持 inbox)
|
||||
* @param {number} [data.late_grace_minutes=60] 补投宽限分钟(0-1440)
|
||||
* @param {string|null} [data.name] 计划名称(可空;未传不覆盖,null/空串清空,非空 trim ≤100)
|
||||
* @param {string} [data.remark] 备注
|
||||
* @param {string} [data.notify_template] 文本通知模板(≤500,白名单标签 {time}/{url}/{report_name}/{biz_date})
|
||||
* @param {Array<number>} [data.notify_group_ids] 通知群ID数组(wms_inbox_group.id,≤20)
|
||||
* @param {Array<string>} [data.notify_member_ids] 通知成员ID数组(外部IM用户ID,≤100)
|
||||
* @return {Promise<Object>} 统一 success 包装
|
||||
*/
|
||||
async save(data = {}) {
|
||||
const { service } = this;
|
||||
const {
|
||||
store_id: storeId,
|
||||
report_id: reportIdSnake,
|
||||
reportId: reportIdCamel,
|
||||
schedule_times: scheduleTimes,
|
||||
channel,
|
||||
late_grace_minutes: lateGraceMinutes,
|
||||
name,
|
||||
remark,
|
||||
notify_template: notifyTemplate,
|
||||
notify_group_ids: notifyGroupIds,
|
||||
notify_member_ids: notifyMemberIds,
|
||||
} = data;
|
||||
|
||||
// 基础参数解构透传;通知类参数仅在入参存在时附加,
|
||||
// 保持旧调用形状与既有回归断言一致(undefined 不进入参数对象)
|
||||
const saveArgs = {
|
||||
storeId,
|
||||
reportId: reportIdCamel !== undefined ? reportIdCamel : reportIdSnake,
|
||||
scheduleTimes,
|
||||
channel,
|
||||
lateGraceMinutes,
|
||||
remark,
|
||||
};
|
||||
if (name !== undefined) {
|
||||
saveArgs.name = name;
|
||||
}
|
||||
if (notifyTemplate !== undefined) {
|
||||
saveArgs.notifyTemplate = notifyTemplate;
|
||||
}
|
||||
if (notifyGroupIds !== undefined) {
|
||||
saveArgs.notifyGroupIds = notifyGroupIds;
|
||||
}
|
||||
if (notifyMemberIds !== undefined) {
|
||||
saveArgs.notifyMemberIds = notifyMemberIds;
|
||||
}
|
||||
|
||||
const result = await service.systems.reportDelivery.savePlan(saveArgs);
|
||||
return this.success('ok', result);
|
||||
}
|
||||
|
||||
/**
|
||||
* 快速复制投递计划到其他货主(目标已存在相同报表定义计划时跳过,不覆盖不报错)。
|
||||
* @param {Object} data 请求体
|
||||
* @param {number} data.id 源计划ID(必填,正整数)
|
||||
* @param {Array<number>} data.store_ids 目标货主ID数组(必填,兼容 storeIds 驼峰)
|
||||
* @return {Promise<Object>} 统一 success 包装,data={ created, skipped }
|
||||
*/
|
||||
async copy(data = {}) {
|
||||
const { service } = this;
|
||||
const {
|
||||
id,
|
||||
store_ids: storeIdsSnake,
|
||||
storeIds: storeIdsCamel,
|
||||
} = data;
|
||||
|
||||
// 兼容 storeIds 驼峰入参,优先取驼峰形式,保持与 save 的 reportId 兼容口径一致
|
||||
const storeIds = storeIdsCamel !== undefined ? storeIdsCamel : storeIdsSnake;
|
||||
|
||||
const result = await service.systems.reportDelivery.copyPlan({ id, storeIds });
|
||||
return this.success('ok', result);
|
||||
}
|
||||
|
||||
/**
|
||||
* 分页查询投递计划列表。
|
||||
* @param {Object} data 请求体
|
||||
* @param {Object} [data.where] 查询条件(store_id/report_id/enabled)
|
||||
* @param {Object} [data.pagination] 分页 { page, pageSize }
|
||||
* @param {Object} [data.sort] 排序 { sortField, sortOrder }
|
||||
* @return {Promise<Object>} 统一 success 包装
|
||||
*/
|
||||
async list(data = {}) {
|
||||
const { service } = this;
|
||||
const { whereValue = {} } = this.prepareWhereContext(data);
|
||||
const {
|
||||
store_id: storeId,
|
||||
report_id: reportId,
|
||||
enabled,
|
||||
} = whereValue;
|
||||
const { pagination = {}, sort = {} } = data;
|
||||
|
||||
const result = await service.systems.reportDelivery.listPlans({
|
||||
storeId,
|
||||
reportId,
|
||||
enabled,
|
||||
pagination,
|
||||
sort,
|
||||
});
|
||||
return this.success('ok', result);
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = ReportDeliveryPlanMethodService;
|
||||
@ -2,6 +2,9 @@
|
||||
|
||||
const MainService = require('../main');
|
||||
|
||||
const RETURN_UNPACK_EXPORT_TASK_CACHE_KEY_PREFIX = 'return_unpack_export_task_';
|
||||
const RETURN_UNPACK_EXPORT_TASK_CACHE_TTL_SECONDS = 1800;
|
||||
|
||||
/**
|
||||
* 系统方法层:returnUnpack(退回拆包模块接口包装层)。
|
||||
* 主要职责:统一包装系统方法接口,处理权限、where 解析等公共逻辑,
|
||||
@ -12,12 +15,13 @@ class ReturnUnpackMethodService extends MainService {
|
||||
super(ctx);
|
||||
// 免登录方法列表:空(全部需要登录)
|
||||
const _noNeedLogin = '';
|
||||
// 免权限方法列表:空(全部走 API 权限校验;detail 走固定 ID 548 客服授权,与设计一致)
|
||||
const _noNeedRight = '';
|
||||
// 免日志方法列表:空(全部记录日志)
|
||||
const _noNeedLog = '';
|
||||
// 免鉴权(仓库有效期检查)方法列表:空(全部检查有效期)
|
||||
const _noNeedAuth = '';
|
||||
// 免权限方法列表:export/exportTaskProgress 免权限(异步任务模式,与 order.export 口径一致,无 wms_permission 记录);
|
||||
// 其余走 API 权限校验(detail 走固定 ID 548 客服授权,与设计一致)
|
||||
const _noNeedRight = 'export,exportTaskProgress';
|
||||
// 免日志方法列表:导出与进度查询不记录操作日志(与订单导出口径一致)
|
||||
const _noNeedLog = 'export,exportTaskProgress';
|
||||
// 免鉴权(仓库有效期检查)方法列表:导出与进度查询不检查仓库有效期(与订单导出口径一致)
|
||||
const _noNeedAuth = 'export,exportTaskProgress';
|
||||
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
|
||||
}
|
||||
|
||||
@ -247,6 +251,262 @@ class ReturnUnpackMethodService extends MainService {
|
||||
return this._call(() => this.service.systems.returnUnpack.detail(Number(id)), '查询详情失败');
|
||||
}
|
||||
|
||||
/**
|
||||
* 提交退回拆包导出任务(异步任务模式,与 order.export 口径一致)。
|
||||
* 入参 where/sort 与 list 完全一致;提交后立即返回 task_id,
|
||||
* 后台异步生成双 Sheet Excel(正常退回运单号列表 + 明细表)并上传,
|
||||
* 通过 exportTaskProgress 查询进度与下载链接。
|
||||
*
|
||||
* @param {Object} data 请求体。
|
||||
* @param {Object} [data.where] 筛选条件(与 list 的 where 语义一致)。
|
||||
* @param {Object} [data.sort] 排序参数(与 list 的 sort 语义一致)。
|
||||
* @return {Promise<Object>} 统一成功包装响应(含 task_id/status/progress 等任务信息)。
|
||||
*/
|
||||
async export(data = {}) {
|
||||
const { service } = this;
|
||||
const { sort } = data;
|
||||
const { where } = this.prepareWhereContext(data, {});
|
||||
|
||||
// 仓库隔离:由服务端从当前上下文自动注入,禁止前端传入
|
||||
const warehouseId = Number(this.ctx.user && this.ctx.user.store_id || 0);
|
||||
const enforcedWhere = { ...where };
|
||||
if (warehouseId > 0) {
|
||||
enforcedWhere.warehouse_id = { operator: 'eq', value: warehouseId };
|
||||
}
|
||||
|
||||
const taskId = this.generateExportTaskId(warehouseId);
|
||||
const taskPayload = {
|
||||
task_id: taskId,
|
||||
status: 'submitted',
|
||||
progress: 0,
|
||||
current_count: 0,
|
||||
total_count: 0,
|
||||
message: '退回拆包导出任务已提交',
|
||||
result: null,
|
||||
error: '',
|
||||
};
|
||||
|
||||
await this.setExportTaskProgress(taskId, taskPayload);
|
||||
|
||||
setImmediate(async () => {
|
||||
try {
|
||||
await this.setExportTaskProgress(taskId, {
|
||||
task_id: taskId,
|
||||
status: 'running',
|
||||
progress: 5,
|
||||
current_count: 0,
|
||||
total_count: 0,
|
||||
message: '退回拆包导出任务执行中',
|
||||
result: null,
|
||||
error: '',
|
||||
});
|
||||
|
||||
const result = await service.systems.returnUnpack.exportUnpack({
|
||||
where: enforcedWhere,
|
||||
sort,
|
||||
warehouseId,
|
||||
onProgress: async progress => {
|
||||
const safeProgress = this.isPlainObject(progress) ? progress : {};
|
||||
await this.setExportTaskProgress(taskId, {
|
||||
task_id: taskId,
|
||||
status: safeProgress.status || 'running',
|
||||
progress: safeProgress.progress,
|
||||
current_count: safeProgress.currentCount,
|
||||
total_count: safeProgress.totalCount,
|
||||
message: safeProgress.message || '退回拆包导出任务执行中',
|
||||
result: safeProgress.result || null,
|
||||
error: '',
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
await this.setExportTaskProgress(taskId, {
|
||||
task_id: taskId,
|
||||
status: 'success',
|
||||
progress: 100,
|
||||
current_count: result.current_count || 0,
|
||||
total_count: result.total_count || 0,
|
||||
message: '退回拆包导出任务完成',
|
||||
result,
|
||||
error: '',
|
||||
});
|
||||
} catch (error) {
|
||||
const errorMessage = error && error.message ? error.message : `${error}`;
|
||||
await this.setExportTaskProgress(taskId, {
|
||||
task_id: taskId,
|
||||
status: 'failed',
|
||||
progress: 100,
|
||||
current_count: 0,
|
||||
total_count: 0,
|
||||
message: '退回拆包导出任务失败',
|
||||
result: null,
|
||||
error: errorMessage,
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
return this.success('ok', {
|
||||
...taskPayload,
|
||||
update_time: Date.now(),
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询退回拆包导出任务进度(与 order.exportTaskProgress 口径一致)。
|
||||
*
|
||||
* @param {Object} data 请求体。
|
||||
* @param {string} [data.task_id] 任务ID(下划线写法)。
|
||||
* @param {string} [data.taskId] 任务ID(驼峰写法)。
|
||||
* @return {Promise<Object>} 统一成功包装响应
|
||||
* (含 task_id/status/progress/current_count/total_count/message/error/download_url/update_time)。
|
||||
*/
|
||||
async exportTaskProgress(data = {}) {
|
||||
const taskId = this.normalizeExportTaskId(data);
|
||||
if (!taskId) {
|
||||
return this.success('ok', {
|
||||
task_id: '',
|
||||
status: 'not_found',
|
||||
progress: 0,
|
||||
current_count: 0,
|
||||
total_count: 0,
|
||||
message: '任务不存在',
|
||||
result: null,
|
||||
error: '',
|
||||
download_url: '',
|
||||
update_time: Date.now(),
|
||||
});
|
||||
}
|
||||
|
||||
const cachedTask = await this.getExportTaskProgress(taskId);
|
||||
if (!cachedTask) {
|
||||
return this.success('ok', {
|
||||
task_id: taskId,
|
||||
status: 'not_found',
|
||||
progress: 0,
|
||||
current_count: 0,
|
||||
total_count: 0,
|
||||
message: '任务不存在',
|
||||
result: null,
|
||||
error: '',
|
||||
download_url: '',
|
||||
update_time: Date.now(),
|
||||
});
|
||||
}
|
||||
|
||||
const safeResult = this.isPlainObject(cachedTask.result) ? cachedTask.result : {};
|
||||
const downloadUrl = String(
|
||||
safeResult.url
|
||||
|| safeResult.cdnUrl
|
||||
|| safeResult.cosUrl
|
||||
|| safeResult.fileKey
|
||||
|| ''
|
||||
);
|
||||
|
||||
return this.success('ok', {
|
||||
task_id: taskId,
|
||||
...cachedTask,
|
||||
download_url: downloadUrl,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成退回拆包导出任务ID。
|
||||
* @param {number|string} [warehouseId=''] 仓库ID(缺省兜底取当前上下文 store_id)。
|
||||
* @return {string} 导出任务ID。
|
||||
*/
|
||||
generateExportTaskId(warehouseId = '') {
|
||||
const normalizedWarehouseId = warehouseId || this.ctx?.user?.store_id || 'unknown';
|
||||
const timestamp = Date.now();
|
||||
const randomToken = Math.random().toString(36).slice(2, 10);
|
||||
return `return_unpack_export_${normalizedWarehouseId}_${timestamp}_${randomToken}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 归一化退回拆包导出任务ID。
|
||||
* @param {Object} data 请求体。
|
||||
* @param {string} [data.task_id] 任务ID(下划线写法)。
|
||||
* @param {string} [data.taskId] 任务ID(驼峰写法)。
|
||||
* @return {string} 归一化后的任务ID。
|
||||
*/
|
||||
normalizeExportTaskId(data = {}) {
|
||||
const normalizedData = this.isPlainObject(data) ? data : {};
|
||||
return String(normalizedData.task_id || normalizedData.taskId || '').trim();
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取退回拆包导出任务缓存键。
|
||||
* @param {string} taskId 任务ID。
|
||||
* @return {string} 缓存键。
|
||||
*/
|
||||
getExportTaskCacheKey(taskId = '') {
|
||||
const normalizedTaskId = String(taskId || '').trim();
|
||||
if (!normalizedTaskId) {
|
||||
return '';
|
||||
}
|
||||
return `${RETURN_UNPACK_EXPORT_TASK_CACHE_KEY_PREFIX}${normalizedTaskId}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 写入退回拆包导出任务进度缓存(Redis TTL 30 分钟)。
|
||||
* @param {string} taskId 任务ID。
|
||||
* @param {Object} payload 任务状态载荷。
|
||||
* @return {Promise<void>} 无返回值。
|
||||
*/
|
||||
async setExportTaskProgress(taskId = '', payload = {}) {
|
||||
const cacheKey = this.getExportTaskCacheKey(taskId);
|
||||
if (!cacheKey || typeof this.app.setCacheAsync !== 'function') {
|
||||
return;
|
||||
}
|
||||
|
||||
const safePayload = this.isPlainObject(payload) ? payload : {};
|
||||
const normalizeCount = value => {
|
||||
const numericValue = Number(value);
|
||||
return Number.isFinite(numericValue) && numericValue >= 0 ? Math.round(numericValue) : 0;
|
||||
};
|
||||
const progressPayload = {
|
||||
task_id: String(taskId || '').trim(),
|
||||
status: String(safePayload.status || 'submitted').trim() || 'submitted',
|
||||
progress: Number.isFinite(Number(safePayload.progress)) ? Math.min(100, Math.max(0, Math.round(Number(safePayload.progress)))) : 0,
|
||||
current_count: normalizeCount(safePayload.current_count),
|
||||
total_count: normalizeCount(safePayload.total_count),
|
||||
message: String(safePayload.message || ''),
|
||||
result: safePayload.result ?? null,
|
||||
error: String(safePayload.error || ''),
|
||||
update_time: Date.now(),
|
||||
};
|
||||
|
||||
try {
|
||||
await this.app.setCacheAsync(cacheKey, progressPayload, RETURN_UNPACK_EXPORT_TASK_CACHE_TTL_SECONDS);
|
||||
} catch (error) {
|
||||
const errorMessage = error && error.message ? error.message : `${error}`;
|
||||
this.ctx.logger.warn(`[returnUnpack.export] 写入导出任务缓存失败: ${errorMessage}`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 读取退回拆包导出任务进度缓存。
|
||||
* @param {string} taskId 任务ID。
|
||||
* @return {Promise<Object|null>} 任务缓存,未命中返回 null。
|
||||
*/
|
||||
async getExportTaskProgress(taskId = '') {
|
||||
const cacheKey = this.getExportTaskCacheKey(taskId);
|
||||
if (!cacheKey || typeof this.app.getCacheAsync !== 'function') {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
const cached = await this.app.getCacheAsync(cacheKey);
|
||||
if (!this.isPlainObject(cached)) {
|
||||
return null;
|
||||
}
|
||||
return cached;
|
||||
} catch (error) {
|
||||
const errorMessage = error && error.message ? error.message : `${error}`;
|
||||
this.ctx.logger.warn(`[returnUnpack.export] 读取导出任务缓存失败: ${errorMessage}`);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除拆包单(删,后台管理,不限制状态)。
|
||||
*
|
||||
|
||||
@ -135,6 +135,7 @@ class ExcelService extends Service {
|
||||
buildWorksheet(sheetConfig = {}) {
|
||||
const {
|
||||
merges = [],
|
||||
textColumns = [],
|
||||
} = sheetConfig;
|
||||
const {
|
||||
aoaData,
|
||||
@ -151,6 +152,8 @@ class ExcelService extends Service {
|
||||
worksheet['!merges'] = merges;
|
||||
}
|
||||
|
||||
this.applyTextColumnsToSheetJs(worksheet, textColumns);
|
||||
|
||||
return worksheet;
|
||||
}
|
||||
|
||||
@ -198,6 +201,7 @@ class ExcelService extends Service {
|
||||
merges = [],
|
||||
embeddedImages = [],
|
||||
styledRows = [],
|
||||
textColumns = [],
|
||||
} = sheetConfig;
|
||||
const {
|
||||
normalizedColumns,
|
||||
@ -258,6 +262,10 @@ class ExcelService extends Service {
|
||||
this.applyStyledRows(worksheet, styledRows);
|
||||
}
|
||||
|
||||
if (Array.isArray(textColumns) && textColumns.length > 0) {
|
||||
this.applyTextColumnsToExcelJs(worksheet, textColumns);
|
||||
}
|
||||
|
||||
if (Array.isArray(embeddedImages) && embeddedImages.length > 0) {
|
||||
await this.addEmbeddedImages(workbook, worksheet, embeddedImages);
|
||||
}
|
||||
@ -437,6 +445,74 @@ class ExcelService extends Service {
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* SheetJS 路径:将 textColumns 指定列落地为文本单元格。
|
||||
* 单元格类型强制为文本(t:'s')、值转字符串,并附加文本数字格式(z:'@'),
|
||||
* 防止长数字串被 Excel 按数值展示成科学计数法。
|
||||
* @param {Object} worksheet SheetJS 工作表对象
|
||||
* @param {Array<number>} [textColumns=[]] 0 基文本列索引列表
|
||||
* @return {void} 无返回值
|
||||
*/
|
||||
applyTextColumnsToSheetJs(worksheet, textColumns = []) {
|
||||
if (!worksheet || !Array.isArray(textColumns) || textColumns.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
const columnSet = new Set(
|
||||
textColumns.map(index => Math.max(0, Math.floor(Number(index) || 0)))
|
||||
);
|
||||
const range = XLSX.utils.decode_range(worksheet['!ref'] || 'A1');
|
||||
|
||||
for (let row = range.s.r; row <= range.e.r; row += 1) {
|
||||
for (const column of columnSet) {
|
||||
if (column > range.e.c) {
|
||||
continue;
|
||||
}
|
||||
const address = XLSX.utils.encode_cell({ r: row, c: column });
|
||||
const cell = worksheet[address];
|
||||
if (!cell) {
|
||||
continue;
|
||||
}
|
||||
if (cell.v !== null && cell.v !== undefined) {
|
||||
cell.t = 's';
|
||||
cell.v = String(cell.v);
|
||||
}
|
||||
cell.z = '@';
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* ExcelJS 路径:将 textColumns 指定列落地为文本单元格。
|
||||
* 单元格值转为字符串(原始对象类型除外),并设置文本数字格式 numFmt='@',
|
||||
* 防止长数字串被 Excel 按数值展示成科学计数法。
|
||||
* @param {Object} worksheet ExcelJS 工作表对象
|
||||
* @param {Array<number>} [textColumns=[]] 0 基文本列索引列表
|
||||
* @return {void} 无返回值
|
||||
*/
|
||||
applyTextColumnsToExcelJs(worksheet, textColumns = []) {
|
||||
if (!worksheet || !Array.isArray(textColumns) || textColumns.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
const columnSet = new Set(
|
||||
textColumns.map(index => Math.max(1, Math.floor(Number(index) || 0) + 1))
|
||||
);
|
||||
|
||||
for (let row = 1; row <= worksheet.rowCount; row += 1) {
|
||||
worksheet.getRow(row).eachCell({ includeEmpty: false }, (cell, columnNumber) => {
|
||||
if (!columnSet.has(columnNumber)) {
|
||||
return;
|
||||
}
|
||||
const value = cell.value;
|
||||
if (value !== null && value !== undefined && typeof value !== 'object') {
|
||||
cell.value = String(value);
|
||||
}
|
||||
cell.numFmt = '@';
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
async addEmbeddedImages(workbook, worksheet, embeddedImages = []) {
|
||||
for (const imageConfig of embeddedImages) {
|
||||
if (!imageConfig) {
|
||||
|
||||
@ -193,6 +193,180 @@ class InboxGroupService extends Service {
|
||||
return { total: count, list };
|
||||
}
|
||||
|
||||
/**
|
||||
* 群快速查询(下拉选择用,不分页)。
|
||||
* 关键词同时模糊匹配群名称与外部群ID,按创建时间倒序返回轻量字段,
|
||||
* 软删除记录由 paranoid 自动排除。
|
||||
* 双维度可选过滤,均不传时 where 不含这两列、返回所有仓库/货主的群:
|
||||
* - store_id(货主维度)↔ wms_inbox_group.store_id 列;
|
||||
* - warehouse_id(仓库维度)↔ wms_inbox_group.warehouse_id 列;
|
||||
* - 两者可同时传(AND 关系),也可都不传(不加对应过滤条件)。
|
||||
*
|
||||
* @param {Object} data 请求数据。
|
||||
* @param {number|string} [data.storeId] 货主ID(可选,来自 API 入参 store_id,映射到 wms_inbox_group.store_id 列;
|
||||
* 传入时须为可解析的正整数,否则抛错「store_id 无效」;不传或为空时不加货主过滤)。
|
||||
* @param {number|string} [data.warehouseId] 仓库ID(可选,来自 API 入参 warehouse_id,映射到 wms_inbox_group.warehouse_id 列;
|
||||
* 传入时须为可解析的正整数,否则抛错「warehouse_id 无效」;不传或为空时不加仓库过滤)。
|
||||
* @param {string} [data.keyword] 关键词,模糊匹配 group_name / group_id。
|
||||
* @param {string} [data.groupType] 按群类型筛选:store / warehouse / express。
|
||||
* @param {number} [data.limit=20] 返回条数上限,最大 100。
|
||||
* @return {Promise<{list: Array<{id: number, group_id: (string|null), group_name: string, group_type: (string|null), sub_type: (string|null), is_blocked: number}>}>} 群快速列表。
|
||||
*/
|
||||
async quickList(data = {}) {
|
||||
const { ctx } = this;
|
||||
const { InboxGroup } = ctx.model;
|
||||
const { Op } = ctx.app.Sequelize;
|
||||
|
||||
const keyword = String(data.keyword || '').trim();
|
||||
const groupType = String(data.groupType || '').trim();
|
||||
const limit = Math.min(100, Math.max(1, Number(data.limit) || 20));
|
||||
|
||||
const where = {};
|
||||
|
||||
// store_id(货主维度,对应 wms_inbox_group.store_id 列)可选:
|
||||
// 传入时校验为可解析的正整数,设置 where.store_id;不传或为空串时不加货主过滤
|
||||
const storeIdRaw = String(data.storeId ?? '').trim();
|
||||
if (storeIdRaw) {
|
||||
const storeId = Number(storeIdRaw);
|
||||
if (!Number.isInteger(storeId) || storeId <= 0) throw new Error('store_id 无效');
|
||||
where.store_id = storeId;
|
||||
}
|
||||
|
||||
// warehouse_id(仓库维度,对应 wms_inbox_group.warehouse_id 列)可选:
|
||||
// 传入时校验为可解析的正整数,设置 where.warehouse_id;不传或为空串时不加仓库过滤
|
||||
const warehouseIdRaw = String(data.warehouseId ?? '').trim();
|
||||
if (warehouseIdRaw) {
|
||||
const warehouseId = Number(warehouseIdRaw);
|
||||
if (!Number.isInteger(warehouseId) || warehouseId <= 0) throw new Error('warehouse_id 无效');
|
||||
where.warehouse_id = warehouseId;
|
||||
}
|
||||
|
||||
if (groupType) where.group_type = groupType;
|
||||
if (keyword) {
|
||||
where[Op.or] = [
|
||||
{ group_name: { [Op.like]: `%${keyword}%` } },
|
||||
{ group_id: { [Op.like]: `%${keyword}%` } },
|
||||
];
|
||||
}
|
||||
|
||||
const rows = await InboxGroup.findAll({
|
||||
attributes: [ 'id', 'group_id', 'group_name', 'group_type', 'sub_type', 'is_blocked' ],
|
||||
where,
|
||||
order: [[ 'created_at', 'DESC' ]],
|
||||
limit,
|
||||
raw: true,
|
||||
});
|
||||
|
||||
return { list: rows };
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询一个或多个群的成员列表(下拉选择用,多群聚合)。
|
||||
* 先用内部主键数组 + 仓库批量校验群存在(软删自动排除,attributes 只取 id/group_id,
|
||||
* 找不到任何匹配群抛「群不存在或无权限操作」),再收集所有群的外部群ID(去重、剔除空值),
|
||||
* 按外部群ID集合在消息表中聚合去重成员:取每个 user_id 最新一条消息的 user_name
|
||||
* (消息按 id 倒序,首次出现的即最新),关键词在聚合后对 user_name / user_id 做包含匹配,
|
||||
* 最后截断到 limit 条。外部群ID集合为空时直接返回空列表。
|
||||
* 局限说明:多群共享同一聚合池,最多取最近 500 条消息,更早消息中的成员不会出现在结果中;
|
||||
* user_id 为 NULL / 空串的消息被排除;关键词匹配大小写不敏感。
|
||||
*
|
||||
* @param {Object} data 请求数据。
|
||||
* @param {Array<number|string>} data.groupIds wms_inbox_group 内部主键ID数组(必填,非空且每个元素为正整数)。
|
||||
* @param {number} data.warehouseId 仓库ID(必填,由 controller 注入)。
|
||||
* @param {string} [data.keyword] 关键词,模糊匹配 user_name / user_id。
|
||||
* @param {number} [data.limit=20] 返回条数上限,最大 100。
|
||||
* @return {Promise<{list: Array<{user_id: string, user_name: string}>}>} 群成员列表。
|
||||
*/
|
||||
async members(data = {}) {
|
||||
const { ctx } = this;
|
||||
const { InboxGroup, InboxMessage } = ctx.model;
|
||||
const { Op } = ctx.app.Sequelize;
|
||||
|
||||
const warehouseId = Number(data.warehouseId);
|
||||
if (!warehouseId) throw new Error('warehouseId 无效');
|
||||
|
||||
// groupIds 校验:非空数组且每个元素为数字或可解析数字字符串的正整数
|
||||
const rawGroupIds = data.groupIds;
|
||||
if (!Array.isArray(rawGroupIds) || rawGroupIds.length === 0) {
|
||||
throw new Error('groupIds 无效');
|
||||
}
|
||||
const groupIds = rawGroupIds.map(item => {
|
||||
if (typeof item !== 'number' && typeof item !== 'string') return NaN;
|
||||
return Number(item);
|
||||
});
|
||||
if (groupIds.some(id => !Number.isInteger(id) || id <= 0)) {
|
||||
throw new Error('groupIds 无效');
|
||||
}
|
||||
|
||||
// 批量校验群存在(软删自动排除),attributes 只取 id / group_id
|
||||
const groups = await InboxGroup.findAll({
|
||||
attributes: [ 'id', 'group_id' ],
|
||||
where: { id: { [Op.in]: groupIds }, warehouse_id: warehouseId },
|
||||
raw: true,
|
||||
});
|
||||
if (!groups || groups.length === 0) {
|
||||
throw new Error('群不存在或无权限操作');
|
||||
}
|
||||
|
||||
// 收集所有群的外部群ID(去重、剔除空值),全部为空则没有可关联的消息成员
|
||||
const externalGroupIds = [ ...new Set(
|
||||
groups.map(g => String(g.group_id || '').trim()).filter(Boolean)
|
||||
) ];
|
||||
if (externalGroupIds.length === 0) {
|
||||
return { list: [] };
|
||||
}
|
||||
|
||||
const keyword = String(data.keyword || '').trim();
|
||||
const limit = Math.min(100, Math.max(1, Number(data.limit) || 20));
|
||||
|
||||
// 拉取多群最近消息集合(软删除由 paranoid 自动排除),共享同一聚合池。
|
||||
// 局限说明:聚合池最多取最近 500 条消息,更早消息中的成员不会出现在结果中。
|
||||
// user_id 同时排除 NULL 与空串(用字段级 Op.and 避免同名键覆盖),
|
||||
// 防止脏数据进入聚合池并输出 "null"/"" 成员。
|
||||
const messages = await InboxMessage.findAll({
|
||||
attributes: [ 'id', 'user_id', 'user_name' ],
|
||||
where: {
|
||||
warehouse_id: warehouseId,
|
||||
group_id: { [Op.in]: externalGroupIds },
|
||||
user_id: {
|
||||
[Op.and]: [
|
||||
{ [Op.ne]: null },
|
||||
{ [Op.ne]: '' },
|
||||
],
|
||||
},
|
||||
},
|
||||
order: [[ 'id', 'DESC' ]],
|
||||
limit: 500,
|
||||
raw: true,
|
||||
});
|
||||
|
||||
// 按 user_id 去重:消息已按 id 倒序,首次出现即该用户最新消息。
|
||||
// JS 层兜底:跳过 null/undefined user_id,防止 String(null) 变成 "null" 输出。
|
||||
const memberMap = new Map();
|
||||
for (const msg of messages) {
|
||||
if (msg.user_id === null || msg.user_id === undefined) continue;
|
||||
const userId = String(msg.user_id).trim();
|
||||
if (!userId || memberMap.has(userId)) continue;
|
||||
memberMap.set(userId, String(msg.user_name || '').trim());
|
||||
}
|
||||
|
||||
let list = Array.from(memberMap.entries())
|
||||
.map(([ user_id, user_name ]) => ({ user_id, user_name }));
|
||||
|
||||
// 关键词在聚合结果上过滤 user_name / user_id:
|
||||
// 统一转小写后做包含匹配,与 quickList 的 SQL LIKE(MySQL 默认大小写不敏感)语义一致
|
||||
if (keyword) {
|
||||
const lowerKeyword = keyword.toLowerCase();
|
||||
list = list.filter(item => {
|
||||
const userName = String(item.user_name || '').toLowerCase();
|
||||
const userId = String(item.user_id || '').toLowerCase();
|
||||
return userName.includes(lowerKeyword) || userId.includes(lowerKeyword);
|
||||
});
|
||||
}
|
||||
|
||||
return { list: list.slice(0, limit) };
|
||||
}
|
||||
|
||||
/**
|
||||
* 禁用 / 解禁群。
|
||||
*
|
||||
|
||||
@ -263,14 +263,19 @@ class NoticeService extends Service {
|
||||
const codes = notificationWebhookModel.getAvailableEventCodes()
|
||||
.map(item => String(item || '').trim().toLowerCase())
|
||||
.filter(Boolean);
|
||||
return codes.length > 0 ? codes : [ ...DEFAULT_REGISTERED_EVENT_CODES ];
|
||||
// 默认注册事件码始终生效(与模型配置合并,便于服务内按现有模式追加新事件码)
|
||||
return codes.length > 0
|
||||
? [ ...new Set([ ...codes, ...DEFAULT_REGISTERED_EVENT_CODES ]) ]
|
||||
: [ ...DEFAULT_REGISTERED_EVENT_CODES ];
|
||||
}
|
||||
|
||||
if (Array.isArray(notificationWebhookModel.AVAILABLE_EVENTS)) {
|
||||
const codes = notificationWebhookModel.AVAILABLE_EVENTS
|
||||
.map(item => String(item && item.code || '').trim().toLowerCase())
|
||||
.filter(Boolean);
|
||||
return codes.length > 0 ? codes : [ ...DEFAULT_REGISTERED_EVENT_CODES ];
|
||||
return codes.length > 0
|
||||
? [ ...new Set([ ...codes, ...DEFAULT_REGISTERED_EVENT_CODES ]) ]
|
||||
: [ ...DEFAULT_REGISTERED_EVENT_CODES ];
|
||||
}
|
||||
|
||||
return [ ...DEFAULT_REGISTERED_EVENT_CODES ];
|
||||
@ -924,6 +929,7 @@ class NoticeService extends Service {
|
||||
warehouse_id: warehouseId,
|
||||
[Op.or]: conditions,
|
||||
},
|
||||
order: [[ 'id', 'ASC' ]],
|
||||
raw: true,
|
||||
});
|
||||
|
||||
@ -934,6 +940,7 @@ class NoticeService extends Service {
|
||||
group_name: row.group_name || '',
|
||||
group_type: row.group_type || '',
|
||||
sub_type: row.sub_type || '',
|
||||
ext_data: row.ext_data || null,
|
||||
}));
|
||||
} catch (error) {
|
||||
this.ctx.logger.warn(`[NoticeService.findSubscribedGroups] 查询订阅群失败: ${error.message}`);
|
||||
@ -1167,7 +1174,9 @@ class NoticeService extends Service {
|
||||
storeId: group.group_type === 'store' ? payload.storeId : null,
|
||||
group,
|
||||
content: `${failPrefix}${baseContent}${fileLine}`.trim(),
|
||||
extId: payload.businessId || payload.traceId,
|
||||
// ext_id 幂等键需含事件维度:同一业务单在不同事件(创建/完成/审核)应各落一条消息,避免被幂等复用吞掉
|
||||
extId: payload.businessId ? `${payload.businessId}:${payload.event}` : payload.traceId,
|
||||
extData: group.ext_data || null,
|
||||
});
|
||||
});
|
||||
const results = await Promise.all(tasks);
|
||||
|
||||
@ -34,6 +34,7 @@ const ORDER_EXPORT_COLUMNS = Object.freeze([
|
||||
{ header: '波次序号', key: 'wave_index', width: 12 },
|
||||
{ header: '货主', key: 'store_id', width: 20 },
|
||||
{ header: '平台', key: 'sys_platform_name', width: 16 },
|
||||
{ header: '来源', key: 'create_channel', width: 12 },
|
||||
{ header: '店铺昵称', key: 'shop_nick', width: 20 },
|
||||
{ header: '收件人', key: 'receiver_name', width: 16 },
|
||||
{ header: '收件人电话', key: 'receiver_mobile', width: 18 },
|
||||
@ -81,6 +82,7 @@ const ORDER_EXPORT_ITEM_COLUMNS = Object.freeze([
|
||||
{ header: '波次序号', key: 'wave_index', width: 12 },
|
||||
{ header: '货主', key: 'store_id', width: 20 },
|
||||
{ header: '平台', key: 'sys_platform_name', width: 16 },
|
||||
{ header: '来源', key: 'create_channel', width: 12 },
|
||||
{ header: '店铺昵称', key: 'shop_nick', width: 20 },
|
||||
{ header: '收件人', key: 'receiver_name', width: 16 },
|
||||
{ header: '收件人电话', key: 'receiver_mobile', width: 18 },
|
||||
@ -281,6 +283,8 @@ class OrderExportService extends OrderBaseService {
|
||||
|
||||
/**
|
||||
* 校验并规范导出表头字段入参(中文表头数组)。
|
||||
* 白名单基于 ORDER_EXPORT_ALL_COLUMN_HEADERS(两模式列头并集),
|
||||
* 新增列(如“来源”)在列配置中登记后即自动可用。
|
||||
* 不传/空数组返回空数组(表示输出全部列);存在非法表头时抛错。
|
||||
* @param {Array<string>|*} rawColumns 原始入参。
|
||||
* @return {Array<string>} 去重后的表头数组。
|
||||
@ -452,6 +456,7 @@ class OrderExportService extends OrderBaseService {
|
||||
wave_index: this.normalizeExportCellValue(safeOrderRow.wave_index ?? 0),
|
||||
store_id: this.normalizeExportCellValue(storeRemark || safeOrderRow.store_name || safeOrderRow.store_id),
|
||||
sys_platform_name: this.normalizeExportCellValue(safeOrderRow.sys_platform_name),
|
||||
create_channel: this.formatCreateChannelLabel(String(safeOrderRow.create_channel || '')),
|
||||
shop_nick: this.normalizeExportCellValue(safeOrderRow.shop_nick),
|
||||
receiver_name: this.normalizeExportCellValue(safeOrderRow.name || ''),
|
||||
receiver_mobile: this.normalizeExportCellValue(safeOrderRow.mobile || safeOrderRow.tel || ''),
|
||||
|
||||
@ -1,6 +1,15 @@
|
||||
'use strict';
|
||||
|
||||
const Service = require('egg').Service;
|
||||
const { stripWaybillSegmentSuffix, escapeLikeWildcards } = require('../../lib/waybill_code');
|
||||
|
||||
/**
|
||||
* 快捷搜索运单号模糊降级的最小关键词长度。
|
||||
* 运单号通常较长(如 JDX057941864338),短于该长度的输入(如单字符 "7")没有模糊搜索意义,
|
||||
* 且 %短词% 极易误命中海量历史单号(实测 "7" 可命中 24149 行),
|
||||
* 违背「不完整短串不得命中订单」的业务约束,因此禁止短词降级进入 %kw% 模糊分支。
|
||||
*/
|
||||
const QUICK_WHERE_WAYBILL_FUZZY_MIN_LENGTH = 4;
|
||||
|
||||
/**
|
||||
* 打包任务服务层(仓库侧)。
|
||||
@ -48,11 +57,11 @@ class OrderPackingService extends Service {
|
||||
* @param {Object} where 筛选条件对象
|
||||
* @param {Object} [where.status] 任务状态:0=待处理 1=打包中 2=已完成 3=异常
|
||||
* @param {Object} [where.pack_mode] 打包模式:1=散单 2=团购
|
||||
* @param {Object} [where.waybill_code] 运单号(通过 wms_order_express 解析 order_id 后过滤,支持 eq/like)
|
||||
* @param {Object} [where.waybill_code] 运单号(通过 wms_order_express 解析 order_id 后过滤;先剥离一单多件分段后缀,主体运单号等值匹配)
|
||||
* @param {Object} [where.wave_no] 波次号(模糊匹配)
|
||||
* @param {Object} [where.order_id] 订单ID(精确匹配)
|
||||
* @param {Object} [where.workbench_id] 工作台ID(精确匹配)
|
||||
* @param {Object} [where.quickWhere] 快捷搜索:支持波次号模糊匹配;运单号通过 express→order→wave 链路解析(团购按波次号查、散单按订单ID查)
|
||||
* @param {Object} [where.quickWhere] 快捷搜索:支持波次号模糊匹配;运单号通过 express→order→wave 链路解析(团购按波次号查、散单按订单ID查;运单号先剥离分段后缀等值匹配,精确未命中且关键词长度≥4 时才降级模糊,短词禁止降级避免误命中)
|
||||
* @param {Object} [where.start_time] 开始打包时间范围,支持 {operator:'between', value:[start,end]}
|
||||
* @param {Object} [where.start_time_start] 开始打包时间起始(兼容旧写法)
|
||||
* @param {Object} [where.start_time_end] 开始打包时间结束(兼容旧写法)
|
||||
@ -102,20 +111,25 @@ class OrderPackingService extends Service {
|
||||
}
|
||||
|
||||
// 运单号筛选:通过 wms_order_express 表解析 order_id,再按 order_id 过滤(wms_pack_task.waybill_code 通常为空)
|
||||
// 业务规则:先剥离一单多件包裹序号后缀(如 -1-1-),剩余主体运单号必须等值匹配,不得落入模糊 like 分支
|
||||
if (where.waybill_code) {
|
||||
const waybillValue = where.waybill_code?.value ?? where.waybill_code;
|
||||
const waybillOperator = (where.waybill_code?.operator || 'like').toLowerCase();
|
||||
if (waybillValue && String(waybillValue).trim()) {
|
||||
const trimmedValue = String(waybillValue).trim();
|
||||
// 剥离分段后缀得到主体运单号(JDX057941864338-1-1- → JDX057941864338)
|
||||
const baseWaybill = stripWaybillSegmentSuffix(trimmedValue);
|
||||
const escapedBase = escapeLikeWildcards(baseWaybill);
|
||||
// 等值匹配集合:完整单号等值 + 主体单号等值 + 主体单号前缀段(主体相同、分段序号不同)
|
||||
const waybillConditions = [
|
||||
{ waybill_code: trimmedValue },
|
||||
...(baseWaybill !== trimmedValue ? [{ waybill_code: baseWaybill }] : []),
|
||||
...(escapedBase ? [{ waybill_code: { [Op.like]: `${escapedBase}-%` } }] : []),
|
||||
];
|
||||
const expressWhere = {
|
||||
warehouse_id: warehouseId,
|
||||
delete_at: null,
|
||||
[Op.or]: waybillConditions,
|
||||
};
|
||||
if (waybillOperator === 'eq') {
|
||||
expressWhere.waybill_code = trimmedValue;
|
||||
} else {
|
||||
expressWhere.waybill_code = { [Op.like]: `%${trimmedValue}%` };
|
||||
}
|
||||
const expressRecords = await ctx.model.OrderExpress.findAll({
|
||||
where: expressWhere,
|
||||
attributes: [ 'order_id' ],
|
||||
@ -167,15 +181,39 @@ class OrderPackingService extends Service {
|
||||
|
||||
// 2. 运单号解析:express → order → wave
|
||||
// 团购波次 → 按 wave_no 查 packing 表;散单 → 按 order_id 查 packing 表
|
||||
const expressRecords = await ctx.model.OrderExpress.findAll({
|
||||
// 业务规则:先剥离包裹序号后缀(如 -1-1-),主体运单号等值匹配为最高优先级;
|
||||
// 精确未命中时才降级为模糊 like,保留快捷搜索能力
|
||||
const baseKw = stripWaybillSegmentSuffix(kw);
|
||||
const escapedKw = escapeLikeWildcards(baseKw);
|
||||
const exactWaybillConditions = [
|
||||
{ waybill_code: kw },
|
||||
...(baseKw !== kw ? [{ waybill_code: baseKw }] : []),
|
||||
...(escapedKw ? [{ waybill_code: { [Op.like]: `${escapedKw}-%` } }] : []),
|
||||
];
|
||||
let expressRecords = await ctx.model.OrderExpress.findAll({
|
||||
where: {
|
||||
waybill_code: { [Op.like]: `%${kw}%` },
|
||||
[Op.or]: exactWaybillConditions,
|
||||
warehouse_id: warehouseId,
|
||||
delete_at: null,
|
||||
},
|
||||
attributes: [ 'order_id' ],
|
||||
raw: true,
|
||||
});
|
||||
// 精确未命中 → 降级为模糊匹配(兼容快捷搜索输入非完整运单号的场景)
|
||||
// 关键词校验:短词(trim 后长度小于 QUICK_WHERE_WAYBILL_FUZZY_MIN_LENGTH,含纯单字符)
|
||||
// 禁止降级进入 %kw% 模糊分支——运单号通常较长,%短词% 极易误命中大量历史单号,
|
||||
// 违背「不完整短串不得命中订单」的业务约束,此时运单号解析保持空结果
|
||||
if (expressRecords.length === 0 && kw.length >= QUICK_WHERE_WAYBILL_FUZZY_MIN_LENGTH) {
|
||||
expressRecords = await ctx.model.OrderExpress.findAll({
|
||||
where: {
|
||||
waybill_code: { [Op.like]: `%${kw}%` },
|
||||
warehouse_id: warehouseId,
|
||||
delete_at: null,
|
||||
},
|
||||
attributes: [ 'order_id' ],
|
||||
raw: true,
|
||||
});
|
||||
}
|
||||
|
||||
if (expressRecords.length > 0) {
|
||||
const orderIds = [ ...new Set(expressRecords.map(r => r.order_id).filter(Boolean)) ];
|
||||
|
||||
610
app/service/systems/report.js
Normal file
610
app/service/systems/report.js
Normal file
@ -0,0 +1,610 @@
|
||||
'use strict';
|
||||
|
||||
const { Service } = require('egg');
|
||||
const { renderSheetByType } = require('../../lib/report/render');
|
||||
const { scheduleDateOf } = require('../../lib/report/day_window');
|
||||
const QUERIES = require('./report/queries');
|
||||
|
||||
/**
|
||||
* 配置驱动通用报表引擎(systems 层)。
|
||||
*
|
||||
* 链路:wms_report_definition(配置:type/file_name/fields) → 内置查询器(QUERIES 注册表)
|
||||
* → render.js(按类型硬编码字段规格渲染) → excel.generateAndUpload / generateBuffer(产物)。
|
||||
* 本服务仅做编排与出口包装,具体口径由查询器实现并注释假设;
|
||||
* 定义唯一性由 id(主键)承担,plan/log 均按 report_definition_id 关联。
|
||||
*/
|
||||
class ReportService extends Service {
|
||||
/**
|
||||
* 按 ID 读取启用的报表定义(is_enabled=1,软删自动排除)。
|
||||
* @param {number|string} id 报表定义ID(正整数)
|
||||
* @return {Promise<Object>} 报表定义视图(fields 已解析为字符串数组)
|
||||
* @throws {Error} ID 非法、模型不可用或定义不存在/停用时抛出
|
||||
*/
|
||||
async getDefinition(id) {
|
||||
const { ctx } = this;
|
||||
const model = ctx.model && ctx.model.ReportDefinition;
|
||||
if (!model || typeof model.findOne !== 'function') {
|
||||
throw new Error('报表定义模型 ReportDefinition 不可用');
|
||||
}
|
||||
const normalizedId = Number(id) || 0;
|
||||
if (!Number.isInteger(normalizedId) || normalizedId <= 0) {
|
||||
throw new Error('报表ID report_id 必须为正整数');
|
||||
}
|
||||
const row = await model.findOne({
|
||||
where: {
|
||||
id: normalizedId,
|
||||
is_enabled: 1,
|
||||
},
|
||||
raw: true,
|
||||
});
|
||||
if (!row) {
|
||||
throw new Error(`报表定义不存在或已停用: id=${normalizedId}`);
|
||||
}
|
||||
return this.definitionToView(row);
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析 fields 字段:数组原样返回、JSON 字符串解析,其余按空数组兜底(元素统一为字符串)。
|
||||
* @param {*} value 字段原始值
|
||||
* @return {Array<string>} 字段 key 数组
|
||||
*/
|
||||
parseFieldsField(value) {
|
||||
let list = value;
|
||||
if (typeof value === 'string' && value.trim()) {
|
||||
try {
|
||||
list = JSON.parse(value);
|
||||
} catch (error) {
|
||||
this.ctx.logger.warn(`[report] 报表定义 fields JSON 解析失败: ${error.message}`);
|
||||
return [];
|
||||
}
|
||||
}
|
||||
if (!Array.isArray(list)) {
|
||||
return [];
|
||||
}
|
||||
return list
|
||||
.map(item => String(item || '').trim())
|
||||
.filter(Boolean);
|
||||
}
|
||||
|
||||
/**
|
||||
* 报表定义记录转视图对象(fields 统一解析为字符串数组,时间字段透传)。
|
||||
* @param {Object} row 报表定义记录(实例或 raw)
|
||||
* @return {Object|null} 视图对象(记录为空时返回 null)
|
||||
*/
|
||||
definitionToView(row) {
|
||||
if (!row) {
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
id: Number(row.id) || 0,
|
||||
name: String(row.name || ''),
|
||||
type: String(row.type || ''),
|
||||
file_name: String(row.file_name || ''),
|
||||
fields: this.parseFieldsField(row.fields),
|
||||
is_enabled: Number(row.is_enabled ?? 1),
|
||||
remark: String(row.remark || ''),
|
||||
created_at: row.created_at || null,
|
||||
updated_at: row.updated_at || null,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 读取注册表描述条目(未知类型抛可读错误)。
|
||||
* @param {string} type 报表类型(注册方法 key)
|
||||
* @return {{key: string, title: string, description: string, window: Object, fields: Array<Object>}} 描述条目
|
||||
* @throws {Error} 类型未注册时抛出
|
||||
*/
|
||||
resolveTypeEntry(type) {
|
||||
const normalizedType = String(type || '').trim();
|
||||
const entries = typeof QUERIES.describe === 'function' ? QUERIES.describe() : [];
|
||||
const entry = entries.find(item => item && item.key === normalizedType);
|
||||
if (!entry) {
|
||||
throw new Error(`未知的报表类型: ${normalizedType}`);
|
||||
}
|
||||
return entry;
|
||||
}
|
||||
|
||||
/**
|
||||
* 读取查询器函数(未知类型抛错)。
|
||||
* @param {string} type 报表类型(注册方法 key)
|
||||
* @return {Function} 查询器函数
|
||||
*/
|
||||
resolveQuerier(type) {
|
||||
const normalizedType = String(type || '').trim();
|
||||
const querier = QUERIES[normalizedType];
|
||||
if (typeof querier !== 'function') {
|
||||
throw new Error(`未知的报表类型: ${normalizedType}`);
|
||||
}
|
||||
return querier;
|
||||
}
|
||||
|
||||
/**
|
||||
* 输出注册表全量清单(供 method 层 report.definition.typeList 复用)。
|
||||
* @return {Array<{key: string, title: string, description: string, window: Object, fields: Array<Object>}>} 注册清单
|
||||
*/
|
||||
listRegisteredTypes() {
|
||||
return typeof QUERIES.describe === 'function' ? QUERIES.describe() : [];
|
||||
}
|
||||
|
||||
/**
|
||||
* 校验勾选字段均为该类型注册字段的子集(顶层字段 key),非法 key 列出可读错误。
|
||||
* @param {string} type 报表类型(注册方法 key)
|
||||
* @param {Array<string>} fields 勾选字段 key 数组
|
||||
* @return {Array<string>} 去重后的合法字段 key 数组(保持传入顺序)
|
||||
* @throws {Error} 含非法字段 key 时抛出
|
||||
*/
|
||||
validateTypeFields(type, fields) {
|
||||
const entry = this.resolveTypeEntry(type);
|
||||
const registeredKeys = new Set((Array.isArray(entry.fields) ? entry.fields : []).map(field => field && field.key));
|
||||
const safeFields = Array.isArray(fields) ? fields : [];
|
||||
const seen = new Set();
|
||||
const normalized = [];
|
||||
const illegal = [];
|
||||
for (const item of safeFields) {
|
||||
const key = String(item || '').trim();
|
||||
if (!key) {
|
||||
continue;
|
||||
}
|
||||
if (!registeredKeys.has(key)) {
|
||||
if (!illegal.includes(key)) {
|
||||
illegal.push(key);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (!seen.has(key)) {
|
||||
seen.add(key);
|
||||
normalized.push(key);
|
||||
}
|
||||
}
|
||||
if (illegal.length > 0) {
|
||||
throw new Error(
|
||||
`fields 含非法字段: ${illegal.join(', ')}`
|
||||
+ `(报表类型 ${type} 可用字段: ${[ ...registeredKeys ].join(', ') || '-'})`
|
||||
);
|
||||
}
|
||||
return normalized;
|
||||
}
|
||||
|
||||
/**
|
||||
* 按字段 key 顺序解析注册字段规格(用于渲染列顺序)。
|
||||
* @param {Object} entry 注册表描述条目
|
||||
* @param {Array<string>} fields 勾选字段 key 数组
|
||||
* @return {Array<Object>} 按勾选顺序排列的字段规格清单
|
||||
*/
|
||||
resolveOrderedFields(entry, fields) {
|
||||
const entryFields = Array.isArray(entry.fields) ? entry.fields : [];
|
||||
const fieldMap = new Map(entryFields.map(field => [ field && field.key, field ]));
|
||||
const safeFields = Array.isArray(fields) ? fields : [];
|
||||
return safeFields
|
||||
.map(key => fieldMap.get(key))
|
||||
.filter(Boolean);
|
||||
}
|
||||
|
||||
/**
|
||||
* 构建导出文件名(支持 file_name 模板的 {date} 占位)。
|
||||
* @param {Object} definition 报表定义视图
|
||||
* @param {string} [bizDate=''] 数据日期(YYYY-MM-DD,缺省用今天)
|
||||
* @return {string} 文件名
|
||||
*/
|
||||
buildFilename(definition, bizDate = '') {
|
||||
const dateText = String(bizDate || '').trim() || scheduleDateOf(new Date());
|
||||
const template = String((definition && definition.file_name) || '').trim()
|
||||
|| `${String((definition && definition.name) || 'report')}_${dateText}.xlsx`;
|
||||
const filename = template.includes('{date}')
|
||||
? template.replace(/\{date\}/g, dateText)
|
||||
: template;
|
||||
return filename.endsWith('.xlsx') || filename.endsWith('.xls') ? filename : `${filename}.xlsx`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询数据并翻译为 excel.js 的 sheets 参数(generate/generateBuffer 共用)。
|
||||
* @param {Object} options 入参
|
||||
* @param {number|string} options.reportId 报表定义ID
|
||||
* @param {number|null} [options.storeId] 货主ID
|
||||
* @param {number|null} [options.warehouseId] 仓库ID
|
||||
* @param {Object} [options.params] 查询器业务参数(如 bizDate)
|
||||
* @return {Promise<{sheets: Array<Object>, filename: string, queryData: Object}>} 翻译结果
|
||||
*/
|
||||
async buildWorkbookSheets({ reportId, storeId = null, warehouseId = null, params = {} }) {
|
||||
const definition = await this.getDefinition(reportId);
|
||||
const entry = this.resolveTypeEntry(definition.type);
|
||||
const querier = this.resolveQuerier(definition.type);
|
||||
|
||||
const queryData = await querier({
|
||||
ctx: this.ctx,
|
||||
storeId,
|
||||
warehouseId,
|
||||
params: params || {},
|
||||
});
|
||||
|
||||
const orderedFields = this.resolveOrderedFields(entry, definition.fields);
|
||||
const sheet = renderSheetByType({
|
||||
type: definition.type,
|
||||
title: entry.title,
|
||||
fields: orderedFields,
|
||||
rows: Array.isArray(queryData.rows) ? queryData.rows : [],
|
||||
windows: Array.isArray(queryData.windows) ? queryData.windows : [],
|
||||
});
|
||||
|
||||
return {
|
||||
sheets: [ sheet ],
|
||||
filename: this.buildFilename(definition, params && params.bizDate),
|
||||
queryData,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成报表 Excel 并上传,返回 fileKey/url(供手动导出与货主投递复用)。
|
||||
* @param {Object} options 入参
|
||||
* @param {number|string} options.reportId 报表定义ID
|
||||
* @param {number|null} [options.storeId] 货主ID
|
||||
* @param {number|null} [options.warehouseId] 仓库ID
|
||||
* @param {Object} [options.params] 查询器业务参数(如 bizDate)
|
||||
* @return {Promise<{fileKey: string, url: string, filename: string, size: number}>} 上传结果
|
||||
*/
|
||||
async generate({ reportId, storeId = null, warehouseId = null, params = {} }) {
|
||||
const { sheets, filename } = await this.buildWorkbookSheets({
|
||||
reportId,
|
||||
storeId,
|
||||
warehouseId,
|
||||
params,
|
||||
});
|
||||
|
||||
const uploadResult = await this.ctx.service.systems.excel.generateAndUpload({
|
||||
filename,
|
||||
dir: `exports/report/${String(reportId).trim()}`,
|
||||
category: 'document',
|
||||
sheets,
|
||||
});
|
||||
|
||||
const fileKey = String(uploadResult.fileKey || uploadResult.fileName || '').trim();
|
||||
const url = String(
|
||||
uploadResult.url
|
||||
|| uploadResult.cdnUrl
|
||||
|| uploadResult.cosUrl
|
||||
|| fileKey
|
||||
|| ''
|
||||
).trim();
|
||||
|
||||
return {
|
||||
fileKey,
|
||||
url,
|
||||
filename: String(uploadResult.filename || filename),
|
||||
size: Number(uploadResult.size) || 0,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成报表 Excel 缓冲(内部入口,供后续复用/直推下载)。
|
||||
* @param {Object} options 入参
|
||||
* @param {number|string} options.reportId 报表定义ID
|
||||
* @param {number|null} [options.storeId] 货主ID
|
||||
* @param {number|null} [options.warehouseId] 仓库ID
|
||||
* @param {Object} [options.params] 查询器业务参数(如 bizDate)
|
||||
* @return {Promise<{buffer: Buffer, filename: string, contentType: string}>} 缓冲结果
|
||||
*/
|
||||
async generateBuffer({ reportId, storeId = null, warehouseId = null, params = {} }) {
|
||||
const { sheets, filename } = await this.buildWorkbookSheets({
|
||||
reportId,
|
||||
storeId,
|
||||
warehouseId,
|
||||
params,
|
||||
});
|
||||
|
||||
const buffer = await this.ctx.service.systems.excel.generateBuffer({
|
||||
bookType: 'xlsx',
|
||||
sheets,
|
||||
});
|
||||
|
||||
return {
|
||||
buffer,
|
||||
filename,
|
||||
contentType: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 读取报表前端可读的列元数据(全量注册字段 + 勾选标记 + 窗口参数,不执行真实数据查询)。
|
||||
* @param {Object} options 入参
|
||||
* @param {number|string} options.reportId 报表定义ID
|
||||
* @return {Promise<Object>} { id, name, type, file_name, window: {dayCount, cutoverHour}, fields }
|
||||
*/
|
||||
async getMeta({ reportId }) {
|
||||
const definition = await this.getDefinition(reportId);
|
||||
const entry = this.resolveTypeEntry(definition.type);
|
||||
const selectedSet = new Set(definition.fields);
|
||||
|
||||
return {
|
||||
id: definition.id,
|
||||
name: definition.name,
|
||||
type: definition.type,
|
||||
file_name: definition.file_name,
|
||||
window: {
|
||||
dayCount: Number((entry.window && entry.window.dayCount) || 7),
|
||||
cutoverHour: Number((entry.window && entry.window.cutoverHour) || 7),
|
||||
},
|
||||
fields: (Array.isArray(entry.fields) ? entry.fields : []).map(field => ({
|
||||
...field,
|
||||
selected: selectedSet.has(field.key),
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 新增/更新报表定义(按 id upsert;未传 id 视为新增)。
|
||||
* 更新语义:未传入的字段(undefined)不覆盖既有值;传入非法值会校验报错。
|
||||
* 校验项:name 必填、type 必须为注册表已有类型、file_name 必填(新增时)、
|
||||
* fields 必须为该类型注册字段的子集。
|
||||
* @param {Object} options 入参
|
||||
* @param {number} [options.id] 报表定义ID(正整数;不传视为新增)
|
||||
* @param {string} options.name 报表名称(必填,≤100)
|
||||
* @param {string} options.type 报表类型(注册方法 key,如 stockFlow;新增必填)
|
||||
* @param {string} options.fileName 导出文件名模板(支持 {date};新增必填,≤200)
|
||||
* @param {Array<string>} options.fields 勾选字段 key 数组(新增必填,须为该类型注册字段子集)
|
||||
* @param {number} [options.isEnabled] 是否启用(0/1)
|
||||
* @param {string} [options.remark] 备注(≤500)
|
||||
* @return {Promise<Object>} 保存后的报表定义视图
|
||||
* @throws {Error} 参数非法、类型未知或字段非法时抛出业务可读错误
|
||||
*/
|
||||
async saveDefinition({
|
||||
id,
|
||||
name = '',
|
||||
type,
|
||||
fileName,
|
||||
fields,
|
||||
isEnabled,
|
||||
remark,
|
||||
} = {}) {
|
||||
const { ctx } = this;
|
||||
const model = ctx.model && ctx.model.ReportDefinition;
|
||||
if (!model || typeof model.findOne !== 'function') {
|
||||
throw new Error('报表定义模型 ReportDefinition 不可用');
|
||||
}
|
||||
|
||||
const normalizedId = id === undefined || id === null || id === ''
|
||||
? null
|
||||
: Number(id) || 0;
|
||||
if (normalizedId !== null && (!Number.isInteger(normalizedId) || normalizedId <= 0)) {
|
||||
throw new Error('报表ID id 必须为正整数');
|
||||
}
|
||||
|
||||
const normalizedName = String(name || '').trim();
|
||||
if (!normalizedName) {
|
||||
throw new Error('报表名称 name 不能为空');
|
||||
}
|
||||
if (normalizedName.length > 100) {
|
||||
throw new Error('报表名称 name 不能超过 100 字符');
|
||||
}
|
||||
|
||||
// 软删记录也纳入查找(按 id 主键查重,paranoid: false 支持恢复),
|
||||
// 并复用既有记录 type 完成 fields 校验(避免重复查库)
|
||||
const existing = normalizedId !== null
|
||||
? await this.findDefinitionById(model, normalizedId)
|
||||
: null;
|
||||
if (normalizedId !== null && !existing) {
|
||||
throw new Error(`报表定义不存在: id=${normalizedId}`);
|
||||
}
|
||||
|
||||
// 未传 type(undefined)不校验也不覆盖既有值;显式传空/未知类型仍报错
|
||||
let normalizedType;
|
||||
if (type !== undefined) {
|
||||
normalizedType = String(type || '').trim();
|
||||
this.resolveTypeEntry(normalizedType);
|
||||
}
|
||||
|
||||
// 未传 fields(undefined)不校验;显式传值须为该类型注册字段子集
|
||||
let normalizedFields;
|
||||
if (fields !== undefined) {
|
||||
if (!Array.isArray(fields)) {
|
||||
throw new Error('报表字段 fields 必须为数组');
|
||||
}
|
||||
// 校验查询器取本次 type,其次取既有记录 type
|
||||
const fieldsValidationType = normalizedType !== undefined
|
||||
? normalizedType
|
||||
: (existing && existing.type);
|
||||
if (!fieldsValidationType) {
|
||||
throw new Error('报表类型 type 不能为空');
|
||||
}
|
||||
normalizedFields = this.validateTypeFields(fieldsValidationType, fields);
|
||||
}
|
||||
|
||||
// 未传 fileName(undefined)不覆盖既有值;新增时必填
|
||||
let normalizedFileName;
|
||||
if (fileName !== undefined) {
|
||||
normalizedFileName = String(fileName || '').trim();
|
||||
if (!normalizedFileName) {
|
||||
throw new Error('导出文件名 file_name 不能为空');
|
||||
}
|
||||
if (normalizedFileName.length > 200) {
|
||||
throw new Error('导出文件名 file_name 不能超过 200 字符');
|
||||
}
|
||||
}
|
||||
|
||||
if (isEnabled !== undefined) {
|
||||
const enabledNum = Number(isEnabled);
|
||||
if (enabledNum !== 0 && enabledNum !== 1) {
|
||||
throw new Error('is_enabled 仅支持 0/1');
|
||||
}
|
||||
}
|
||||
|
||||
// 新增时必须提供 type/file_name/fields(existing 已在上方按 id 查询一次)
|
||||
if (!existing) {
|
||||
if (normalizedType === undefined) {
|
||||
throw new Error('报表类型 type 不能为空');
|
||||
}
|
||||
if (normalizedFileName === undefined) {
|
||||
throw new Error('导出文件名 file_name 不能为空');
|
||||
}
|
||||
if (normalizedFields === undefined) {
|
||||
throw new Error('报表字段 fields 不能为空');
|
||||
}
|
||||
}
|
||||
|
||||
const payload = {
|
||||
name: normalizedName,
|
||||
};
|
||||
if (normalizedType !== undefined) {
|
||||
payload.type = normalizedType;
|
||||
}
|
||||
if (normalizedFileName !== undefined) {
|
||||
payload.file_name = normalizedFileName;
|
||||
}
|
||||
if (normalizedFields !== undefined) {
|
||||
payload.fields = normalizedFields;
|
||||
}
|
||||
if (isEnabled !== undefined) {
|
||||
payload.is_enabled = Number(isEnabled) ? 1 : 0;
|
||||
}
|
||||
if (remark !== undefined) {
|
||||
payload.remark = String(remark || '').slice(0, 500);
|
||||
}
|
||||
|
||||
let saved;
|
||||
if (existing) {
|
||||
if (existing.deleted_at) {
|
||||
// 命中软删记录:恢复后按入参更新
|
||||
await existing.restore();
|
||||
}
|
||||
await existing.update(payload);
|
||||
saved = existing;
|
||||
} else {
|
||||
const created = await model.create(payload);
|
||||
saved = created && created.toJSON ? created.toJSON() : created;
|
||||
}
|
||||
|
||||
return this.definitionToView(saved);
|
||||
}
|
||||
|
||||
/**
|
||||
* 按 ID 查找报表定义(paranoid: false,软删记录也返回,供恢复与校验复用)。
|
||||
* @param {Object} model ReportDefinition 模型
|
||||
* @param {number|null} id 报表定义ID(null 时直接返回 null)
|
||||
* @return {Promise<Object|null>} 记录实例(含软删记录),不存在返回 null
|
||||
*/
|
||||
async findDefinitionById(model, id) {
|
||||
if (id === null || Number(id) <= 0) {
|
||||
return null;
|
||||
}
|
||||
return model.findOne({
|
||||
where: { id: Number(id) },
|
||||
paranoid: false,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 分页查询报表定义列表(name 模糊、type/is_enabled 精确,sortField 白名单)。
|
||||
* @param {Object} [options={}] 入参
|
||||
* @param {string} [options.nameKeyword=''] name 模糊关键字
|
||||
* @param {string} [options.type=''] 报表类型精确筛选(注册方法 key)
|
||||
* @param {number|string} [options.isEnabled=null] 启用状态精确筛选(0/1)
|
||||
* @param {Object} [options.pagination={}] 分页 { page, pageSize }
|
||||
* @param {Object} [options.sort={}] 排序 { sortField, sortOrder }
|
||||
* @return {Promise<{list: Array<Object>, total: number, page: number, pageSize: number}>} 列表结果
|
||||
*/
|
||||
async listDefinitions({
|
||||
nameKeyword = '',
|
||||
type = '',
|
||||
isEnabled = null,
|
||||
pagination = {},
|
||||
sort = {},
|
||||
} = {}) {
|
||||
const { ctx } = this;
|
||||
const model = ctx.model && ctx.model.ReportDefinition;
|
||||
if (!model) {
|
||||
throw new Error('报表定义模型 ReportDefinition 不可用');
|
||||
}
|
||||
const { Op } = ctx.app.Sequelize;
|
||||
|
||||
const escapeLike = value => String(value || '').replace(/[\\%_]/g, match => `\\${match}`);
|
||||
|
||||
const where = {};
|
||||
const normalizedNameKeyword = String(nameKeyword || '').trim();
|
||||
if (normalizedNameKeyword) {
|
||||
where.name = { [Op.like]: `%${escapeLike(normalizedNameKeyword)}%` };
|
||||
}
|
||||
const normalizedType = String(type || '').trim();
|
||||
if (normalizedType) {
|
||||
this.resolveTypeEntry(normalizedType);
|
||||
where.type = normalizedType;
|
||||
}
|
||||
if (isEnabled !== null && isEnabled !== undefined && isEnabled !== '') {
|
||||
where.is_enabled = Number(isEnabled) ? 1 : 0;
|
||||
}
|
||||
|
||||
const page = Math.max(1, Math.floor(Number(pagination.page) || 1));
|
||||
const pageSize = Math.min(200, Math.max(1, Math.floor(Number(pagination.pageSize) || 20)));
|
||||
|
||||
const allowedSortFields = [ 'id', 'name', 'type', 'is_enabled', 'created_at', 'updated_at' ];
|
||||
const sortField = String(sort.sortField || sort.sort_field || 'id').trim();
|
||||
const sortOrder = String(sort.sortOrder || sort.sort_order || 'desc').trim().toLowerCase() === 'asc' ? 'ASC' : 'DESC';
|
||||
const order = allowedSortFields.includes(sortField)
|
||||
? [[ sortField, sortOrder ]]
|
||||
: [[ 'id', 'DESC' ]];
|
||||
|
||||
const [ rows, total ] = await Promise.all([
|
||||
model.findAll({
|
||||
where,
|
||||
order,
|
||||
offset: (page - 1) * pageSize,
|
||||
limit: pageSize,
|
||||
raw: true,
|
||||
}),
|
||||
model.count({ where }),
|
||||
]);
|
||||
|
||||
return {
|
||||
list: (Array.isArray(rows) ? rows : []).map(row => this.definitionToView(row)),
|
||||
total: Number(total) || 0,
|
||||
page,
|
||||
pageSize,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 软删除报表定义。
|
||||
* 删除前检查投递计划引用:仅拦截「启用中」的计划,停用计划不阻断——
|
||||
* 停用计划不再生产投递任务,历史投递日志按 report_definition_id 关联不受定义删除影响。
|
||||
* 重复删除同一 ID 按幂等成功处理,避免前端重复点击报错。
|
||||
* @param {Object} options 入参
|
||||
* @param {number|string} options.id 报表定义ID(必填,正整数)
|
||||
* @return {Promise<{id: number, deleted: number}>} 删除结果(deleted 恒为 1)
|
||||
* @throws {Error} ID 非法、定义不存在或存在启用中的投递计划引用时抛出业务可读错误
|
||||
*/
|
||||
async deleteDefinition({ id } = {}) {
|
||||
const { ctx } = this;
|
||||
const model = ctx.model && ctx.model.ReportDefinition;
|
||||
if (!model) {
|
||||
throw new Error('报表定义模型 ReportDefinition 不可用');
|
||||
}
|
||||
const normalizedId = Number(id) || 0;
|
||||
if (!Number.isInteger(normalizedId) || normalizedId <= 0) {
|
||||
throw new Error('报表ID id 必须为正整数');
|
||||
}
|
||||
|
||||
// 引用拦截:仅统计启用中的投递计划(enabled=1)
|
||||
const planModel = ctx.model && ctx.model.ReportDeliveryPlan;
|
||||
if (planModel && typeof planModel.count === 'function') {
|
||||
const activePlanCount = await planModel.count({
|
||||
where: {
|
||||
report_definition_id: normalizedId,
|
||||
enabled: 1,
|
||||
},
|
||||
});
|
||||
if (activePlanCount > 0) {
|
||||
throw new Error(`存在 ${activePlanCount} 个启用的投递计划引用该报表,请先停用计划`);
|
||||
}
|
||||
}
|
||||
|
||||
const existing = await this.findDefinitionById(model, normalizedId);
|
||||
if (!existing) {
|
||||
throw new Error(`报表定义不存在: id=${normalizedId}`);
|
||||
}
|
||||
if (existing.deleted_at) {
|
||||
return { id: normalizedId, deleted: 1 };
|
||||
}
|
||||
await existing.destroy();
|
||||
return { id: normalizedId, deleted: 1 };
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = ReportService;
|
||||
57
app/service/systems/report/queries/index.js
Normal file
57
app/service/systems/report/queries/index.js
Normal file
@ -0,0 +1,57 @@
|
||||
'use strict';
|
||||
|
||||
const sevenDayStockFlow = require('./sevenDayStockFlow');
|
||||
|
||||
/**
|
||||
* 报表内置查询器注册表。
|
||||
* key 对应 wms_report_definition.type;
|
||||
* 新增查询器时在此登记,签名统一为
|
||||
* async ({ ctx, storeId, warehouseId, params }) => ({ windows, rows, meta })。
|
||||
* 每个查询器需在模块上挂载静态字段清单 `fields`(如 module.exports.fields)
|
||||
* 与缺省窗口参数 `defaultWindow`,供报表引擎 report.meta / report.definition.typeList 读取。
|
||||
* 注意:该对象会作为 service 模块导出,egg 加载器需要在其上挂载
|
||||
* `Symbol(EGG_LOADER_ITEM_FULLPATH)` 等内部符号,因此禁止对导出对象使用
|
||||
* Object.freeze / Object.seal / Object.preventExtensions。
|
||||
* @type {Object<string, Function>}
|
||||
*/
|
||||
const QUERIES = {
|
||||
stockFlow: sevenDayStockFlow,
|
||||
};
|
||||
|
||||
/**
|
||||
* 注册表描述元数据:key/title/description/window/fields。
|
||||
* @type {Array<{key: string, title: string, description: string, window: Object, fields: Array<Object>}>}
|
||||
*/
|
||||
const DESCRIPTIONS = [
|
||||
{
|
||||
key: 'stockFlow',
|
||||
title: '库存变化以及补货报表',
|
||||
description: '按日窗口聚合出入库流水与正品库存,输出每 SKU 每日出/入库、可用/总库存、'
|
||||
+ '锁定数、待出、日均出/入库、预计可售天数、建议补货量与库存预警',
|
||||
window: {
|
||||
...(sevenDayStockFlow.defaultWindow || { dayCount: 7, cutoverHour: 7 }),
|
||||
},
|
||||
fields: (Array.isArray(sevenDayStockFlow.fields) ? sevenDayStockFlow.fields : []).map(field => ({ ...field })),
|
||||
},
|
||||
];
|
||||
|
||||
/**
|
||||
* 输出注册表可读描述(含全量字段清单),供 report.definition.typeList / report.meta 复用。
|
||||
* 返回副本,避免调用方误改注册表元数据。
|
||||
* @return {Array<{key: string, title: string, description: string, window: Object, fields: Array<Object>}>} 注册描述列表
|
||||
*/
|
||||
function describe() {
|
||||
return DESCRIPTIONS.map(entry => ({
|
||||
...entry,
|
||||
window: { ...(entry.window || {}) },
|
||||
fields: (Array.isArray(entry.fields) ? entry.fields : []).map(field => ({
|
||||
...field,
|
||||
children: Array.isArray(field.children) ? field.children.map(child => ({ ...child })) : undefined,
|
||||
})),
|
||||
}));
|
||||
}
|
||||
|
||||
// egg 加载器要求导出对象可扩展,describe 作为方法属性挂在 QUERIES 上
|
||||
QUERIES.describe = describe;
|
||||
|
||||
module.exports = QUERIES;
|
||||
282
app/service/systems/report/queries/sevenDayStockFlow.js
Normal file
282
app/service/systems/report/queries/sevenDayStockFlow.js
Normal file
@ -0,0 +1,282 @@
|
||||
'use strict';
|
||||
|
||||
const { buildDayWindows, resolveWindowConfig } = require('../../../../lib/report/day_window');
|
||||
const { avgDaysPerWeek, suggestWithCompensate, warnOf } = require('../../../../lib/report/formatters');
|
||||
|
||||
/**
|
||||
* 库存变化以及补货报表查询器的静态字段清单(前端可读列元数据)。
|
||||
* key 与查询器返回的行字段一一对应;computed=true 表示由查询器预计算、非原始表字段;
|
||||
* asText=true 表示渲染层将该列落地为 Excel 文本单元格(长数字串防科学计数法);
|
||||
* daily 为数组类型,children 描述每日出入库子字段。
|
||||
* @type {Array<Object>}
|
||||
*/
|
||||
const FIELDS = Object.freeze([
|
||||
{ key: 'stock_id', label: '库存ID', type: 'number' },
|
||||
{ key: 'item_code', label: '商品编码', type: 'string', asText: true },
|
||||
{ key: 'item_name', label: '商品名称', type: 'string' },
|
||||
{ key: 'barcode', label: '条码', type: 'string', asText: true },
|
||||
{
|
||||
key: 'daily',
|
||||
label: '每日出入库',
|
||||
type: 'array',
|
||||
children: [
|
||||
{ key: 'ck', label: '出库数', type: 'number' },
|
||||
{ key: 'rk', label: '入库数', type: 'number' },
|
||||
],
|
||||
},
|
||||
{ key: 'ck_total', label: '出库合计', type: 'number' },
|
||||
{ key: 'rk_total', label: '入库合计', type: 'number' },
|
||||
{ key: 'available', label: '可用库存', type: 'number' },
|
||||
{ key: 'total', label: '总库存', type: 'number' },
|
||||
{ key: 'pending', label: '待出库存', type: 'number' },
|
||||
{ key: 'locked', label: '锁定数', type: 'number' },
|
||||
{ key: 'ck_avg', label: '出库日均(×10)', type: 'number', computed: true },
|
||||
{ key: 'rk_avg', label: '入库日均(×10)', type: 'number', computed: true },
|
||||
{ key: 'stock_days', label: '预计可售天数', type: 'number', computed: true },
|
||||
{ key: 'suggest', label: '建议补货量', type: 'number', computed: true },
|
||||
{ key: 'warn', label: '库存预警', type: 'boolean', computed: true },
|
||||
]);
|
||||
|
||||
/**
|
||||
* stockFlow 查询器缺省窗口参数(与旧 7 日出入库口径一致,可被 params 覆盖)。
|
||||
* @type {{dayCount: number, cutoverHour: number}}
|
||||
*/
|
||||
const DEFAULT_WINDOW = Object.freeze({ dayCount: 7, cutoverHour: 7 });
|
||||
|
||||
/**
|
||||
* 内置查询器:库存变化以及补货报表(旧 PHP《7日出入库数据》Wms.php putout_putin_storage7 口径)。
|
||||
*
|
||||
* 口径与假设(供测试复核):
|
||||
* 1. 窗口:dayCount 个 [D cutoverHour:00, D+1 cutoverHour:00) 本地时区窗口
|
||||
* (缺省 7 天、07:00 切点,可由 params.dayCount/cutoverHour 覆盖);
|
||||
* 2. 流水:wms_stock_transaction,transaction_type IN (INBOUND, OUTBOUND),显式排除 LOCK/UNLOCK,
|
||||
* 按 created_at 落入窗口,INBOUND→rk、OUTBOUND→ck;
|
||||
* 3. 可用/总库存口径:wms_storage(库位级正品明细),inventory_type='ZP'、is_enabled=1、未删除,
|
||||
* SUM(quantity)=总库存、SUM(available_quantity)=可用库存、SUM(locked_quantity)=锁定数,
|
||||
* 待出库存=总库存-可用库存;与 wms_stock_warehouse 主表的 quantity/locked_quantity 可能存在口径差异;
|
||||
* 4. 条码口径:wms_stock_barcodes 多值取字典序第一条(表内无主条码标志,旧 PHP 取 MIN(barcode) 语义);
|
||||
* 5. 行范围:窗口内有流水 或 有正品库存 的 SKU 均出列,按 item_code 升序、stock_id 升序;
|
||||
* 6. 日均口径:ck_avg/rk_avg = int(合计/天数×10)(formatters.avgDaysPerWeek);
|
||||
* 7. 预计可售天数:出库日均>0 时 int(可用库存×10/出库日均×10),无出库时为 null;
|
||||
* 8. suggest/warn 由 formatters 注册表计算(低库存补偿:available<20 且 rk_total<20)。
|
||||
*
|
||||
* @param {Object} args 查询器入参
|
||||
* @param {Object} args.ctx Egg 上下文
|
||||
* @param {number|null} args.storeId 货主ID(可选,<=0 时不按货主过滤)
|
||||
* @param {number|null} args.warehouseId 仓库ID(必填)
|
||||
* @param {Object} [args.params={}] 业务参数(dayCount/cutoverHour 窗口覆盖等)
|
||||
* @return {Promise<{windows: Array<Object>, rows: Array<Object>, meta: Object}>} 查询结果
|
||||
*/
|
||||
async function sevenDayStockFlow({ ctx, storeId = null, warehouseId = null, params = {} }) {
|
||||
const { app } = ctx;
|
||||
const { Op } = app.Sequelize;
|
||||
|
||||
const { dayCount, cutoverHour } = resolveWindowConfig(params || {});
|
||||
const windows = buildDayWindows({ dayCount, cutoverHour });
|
||||
|
||||
const normalizedWarehouseId = Number(warehouseId) || 0;
|
||||
if (normalizedWarehouseId <= 0) {
|
||||
throw new Error('stockFlow 查询器缺少仓库维度 warehouseId');
|
||||
}
|
||||
const normalizedStoreId = Number(storeId) || 0;
|
||||
|
||||
const windowStart = windows[0].start;
|
||||
const windowEnd = windows[windows.length - 1].end;
|
||||
|
||||
// 1) 流水聚合(排除 LOCK/UNLOCK)
|
||||
const transactionWhere = {
|
||||
warehouse_id: normalizedWarehouseId,
|
||||
transaction_type: { [Op.in]: [ 'INBOUND', 'OUTBOUND' ] },
|
||||
created_at: {
|
||||
[Op.gte]: new Date(windowStart),
|
||||
[Op.lt]: new Date(windowEnd),
|
||||
},
|
||||
};
|
||||
if (normalizedStoreId > 0) {
|
||||
transactionWhere.store_id = normalizedStoreId;
|
||||
}
|
||||
|
||||
const transactionRows = await ctx.model.StockTransaction.findAll({
|
||||
where: transactionWhere,
|
||||
attributes: [ 'stock_id', 'transaction_type', 'quantity', 'created_at' ],
|
||||
raw: true,
|
||||
});
|
||||
|
||||
// stockId → { daily: [{ck, rk}], ckTotal, rkTotal }
|
||||
const flowMap = new Map();
|
||||
const upsertSlot = stockId => {
|
||||
if (!flowMap.has(stockId)) {
|
||||
flowMap.set(stockId, {
|
||||
daily: Array.from({ length: dayCount }, () => ({ ck: 0, rk: 0 })),
|
||||
ckTotal: 0,
|
||||
rkTotal: 0,
|
||||
});
|
||||
}
|
||||
return flowMap.get(stockId);
|
||||
};
|
||||
|
||||
for (const row of transactionRows) {
|
||||
const stockId = Number(row.stock_id);
|
||||
if (!Number.isInteger(stockId) || stockId <= 0) {
|
||||
continue;
|
||||
}
|
||||
const quantity = Number(row.quantity) || 0;
|
||||
const createdMs = new Date(row.created_at).getTime();
|
||||
let windowIndex = -1;
|
||||
for (let index = 0; index < windows.length; index += 1) {
|
||||
if (createdMs >= windows[index].start && createdMs < windows[index].end) {
|
||||
windowIndex = index;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (windowIndex < 0) {
|
||||
continue;
|
||||
}
|
||||
const slot = upsertSlot(stockId);
|
||||
if (row.transaction_type === 'OUTBOUND') {
|
||||
slot.daily[windowIndex].ck += quantity;
|
||||
slot.ckTotal += quantity;
|
||||
} else {
|
||||
slot.daily[windowIndex].rk += quantity;
|
||||
slot.rkTotal += quantity;
|
||||
}
|
||||
}
|
||||
|
||||
// 2) 可用/总库存(正品库位明细聚合)
|
||||
const storageWhere = {
|
||||
warehouse_id: normalizedWarehouseId,
|
||||
inventory_type: 'ZP',
|
||||
is_enabled: 1,
|
||||
};
|
||||
if (normalizedStoreId > 0) {
|
||||
storageWhere.store_id = normalizedStoreId;
|
||||
}
|
||||
|
||||
const inventoryRows = await ctx.model.Storage.findAll({
|
||||
where: storageWhere,
|
||||
attributes: [
|
||||
'stock_id',
|
||||
[ app.Sequelize.fn('SUM', app.Sequelize.col('quantity')), 'total_quantity' ],
|
||||
[ app.Sequelize.fn('SUM', app.Sequelize.col('locked_quantity')), 'total_locked' ],
|
||||
[ app.Sequelize.fn('SUM', app.Sequelize.col('available_quantity')), 'total_available' ],
|
||||
],
|
||||
group: [ 'stock_id' ],
|
||||
raw: true,
|
||||
});
|
||||
|
||||
const inventoryMap = new Map();
|
||||
for (const row of inventoryRows) {
|
||||
const stockId = Number(row.stock_id);
|
||||
if (!Number.isInteger(stockId) || stockId <= 0) {
|
||||
continue;
|
||||
}
|
||||
const totalQuantity = Number(row.total_quantity) || 0;
|
||||
const totalAvailable = Number(row.total_available) || 0;
|
||||
inventoryMap.set(stockId, {
|
||||
total: totalQuantity,
|
||||
available: totalAvailable,
|
||||
locked: Number(row.total_locked) || 0,
|
||||
pending: totalQuantity - totalAvailable,
|
||||
});
|
||||
}
|
||||
|
||||
// 3) 商品资料与条码(条码多值取字典序第一条,假设:无主条码标志,等价旧 PHP MIN(barcode))
|
||||
const stockIds = [ ...new Set([ ...flowMap.keys(), ...inventoryMap.keys() ]) ];
|
||||
let stockRows = [];
|
||||
let barcodeRows = [];
|
||||
if (stockIds.length > 0) {
|
||||
[ stockRows, barcodeRows ] = await Promise.all([
|
||||
ctx.model.StockWarehouse.findAll({
|
||||
where: { id: { [Op.in]: stockIds } },
|
||||
attributes: [ 'id', 'item_code', 'item_name' ],
|
||||
raw: true,
|
||||
}),
|
||||
ctx.model.StockBarcode.findAll({
|
||||
where: { stock_id: { [Op.in]: stockIds } },
|
||||
attributes: [ 'stock_id', 'barcode' ],
|
||||
order: [[ 'barcode', 'ASC' ]],
|
||||
raw: true,
|
||||
}),
|
||||
]);
|
||||
}
|
||||
|
||||
const stockMap = new Map();
|
||||
for (const row of stockRows) {
|
||||
stockMap.set(Number(row.id), {
|
||||
itemCode: String(row.item_code || '').trim(),
|
||||
itemName: String(row.item_name || '').trim(),
|
||||
});
|
||||
}
|
||||
|
||||
const barcodeMap = new Map();
|
||||
for (const row of barcodeRows) {
|
||||
const stockId = Number(row.stock_id);
|
||||
const barcode = String(row.barcode || '').trim();
|
||||
// 查询已按 barcode 升序,首个即字典序第一条
|
||||
if (!barcodeMap.has(stockId) && barcode) {
|
||||
barcodeMap.set(stockId, barcode);
|
||||
}
|
||||
}
|
||||
|
||||
// 4) 组装数据行
|
||||
const rows = stockIds.map(stockId => {
|
||||
const flow = flowMap.get(stockId) || {
|
||||
daily: Array.from({ length: dayCount }, () => ({ ck: 0, rk: 0 })),
|
||||
ckTotal: 0,
|
||||
rkTotal: 0,
|
||||
};
|
||||
const inventory = inventoryMap.get(stockId) || { total: 0, available: 0, locked: 0, pending: 0 };
|
||||
const stock = stockMap.get(stockId) || { itemCode: '', itemName: '' };
|
||||
const available = inventory.available;
|
||||
const total = inventory.total;
|
||||
const ckTotal = flow.ckTotal;
|
||||
const rkTotal = flow.rkTotal;
|
||||
const ckAvg = avgDaysPerWeek(ckTotal, dayCount);
|
||||
const rkAvg = avgDaysPerWeek(rkTotal, dayCount);
|
||||
// 预计可售天数:日均出库 = ckAvg/10,避免浮点误差改用 (available×10)/ckAvg 取整
|
||||
const stockDays = ckAvg > 0 ? Math.floor((available * 10) / ckAvg) : null;
|
||||
|
||||
return {
|
||||
stock_id: stockId,
|
||||
item_code: stock.itemCode,
|
||||
item_name: stock.itemName,
|
||||
barcode: barcodeMap.get(stockId) || '',
|
||||
daily: flow.daily,
|
||||
ck_total: ckTotal,
|
||||
rk_total: rkTotal,
|
||||
available,
|
||||
total,
|
||||
pending: inventory.pending,
|
||||
locked: inventory.locked,
|
||||
ck_avg: ckAvg,
|
||||
rk_avg: rkAvg,
|
||||
stock_days: stockDays,
|
||||
suggest: suggestWithCompensate(ckTotal, available, rkTotal),
|
||||
warn: warnOf(ckTotal, available, rkTotal),
|
||||
};
|
||||
});
|
||||
|
||||
rows.sort((left, right) => {
|
||||
if (left.item_code !== right.item_code) {
|
||||
return left.item_code < right.item_code ? -1 : 1;
|
||||
}
|
||||
return left.stock_id - right.stock_id;
|
||||
});
|
||||
|
||||
return {
|
||||
windows,
|
||||
rows,
|
||||
meta: {
|
||||
warehouseId: normalizedWarehouseId,
|
||||
storeId: normalizedStoreId,
|
||||
dayCount,
|
||||
cutoverHour,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
module.exports = sevenDayStockFlow;
|
||||
// 静态字段清单挂到查询器模块上,供报表引擎与注册表 describe 读取(不执行真实数据查询)
|
||||
module.exports.fields = FIELDS;
|
||||
// 缺省窗口参数挂到查询器模块上,供注册表 describe 与 report.meta 读取
|
||||
module.exports.defaultWindow = DEFAULT_WINDOW;
|
||||
1475
app/service/systems/reportDelivery.js
Normal file
1475
app/service/systems/reportDelivery.js
Normal file
File diff suppressed because it is too large
Load Diff
@ -1,7 +1,18 @@
|
||||
'use strict';
|
||||
|
||||
const crypto = require('node:crypto');
|
||||
const fs = require('node:fs');
|
||||
const fsp = require('node:fs/promises');
|
||||
const os = require('node:os');
|
||||
const path = require('node:path');
|
||||
const ExcelJS = require('exceljs');
|
||||
const Service = require('egg').Service;
|
||||
|
||||
/** 退回拆包导出主表分页拉取大小 */
|
||||
const RETURN_UNPACK_EXPORT_PAGE_SIZE = 500;
|
||||
/** 退回拆包导出明细分批拉取大小 */
|
||||
const RETURN_UNPACK_DETAIL_BATCH_SIZE = 100;
|
||||
|
||||
/**
|
||||
* 退回拆包模块业务逻辑层。
|
||||
* 负责 wms_return_unpack(主表)/ wms_return_unpack_detail(明细)/ wms_return_unpack_video(视频)/
|
||||
@ -509,7 +520,57 @@ class ReturnUnpackService extends Service {
|
||||
}
|
||||
|
||||
/**
|
||||
* 提交确认:未完成拆包单转 completed 终态,回写结束时间,
|
||||
* 按仓库配置的拆包最大录制时长约束提交结束时间。
|
||||
* 候选结束时间超过 开始时间+上限时长 时,截断为上限时间点。
|
||||
* 开始时间缺失、配置非法或读取失败时不约束,原样返回。
|
||||
*
|
||||
* @param {Object} unpack 拆包单主表记录(需含 id / warehouse_id / start_time)。
|
||||
* @param {Date} candidateEndTime 候选结束时间。
|
||||
* @return {Promise<Date>} 约束后的结束时间。
|
||||
*/
|
||||
async _resolveSubmitEndTime(unpack, candidateEndTime) {
|
||||
const { ctx } = this;
|
||||
const candidate = candidateEndTime instanceof Date ? candidateEndTime : new Date(candidateEndTime);
|
||||
|
||||
if (!unpack || !Number.isFinite(candidate.getTime())) {
|
||||
return candidateEndTime;
|
||||
}
|
||||
|
||||
const startMs = new Date(unpack.start_time).getTime();
|
||||
if (!Number.isFinite(startMs)) {
|
||||
return candidateEndTime;
|
||||
}
|
||||
|
||||
let limitMinutes = null;
|
||||
try {
|
||||
const warehouseId = Number(unpack.warehouse_id || 0);
|
||||
const subjectConfig = await ctx.service.systems.deliveryOrder.getStoreSubjectConfig(warehouseId);
|
||||
limitMinutes = Number(subjectConfig && subjectConfig.return_unpack_max_record_minutes);
|
||||
} catch (error) {
|
||||
ctx.logger.warn(`[returnUnpack.submit] 读取仓库拆包时长配置失败: ${error.message}`);
|
||||
}
|
||||
|
||||
// 未配置有效时长时不约束结束时间
|
||||
if (!Number.isInteger(limitMinutes) || limitMinutes <= 0) {
|
||||
return candidateEndTime;
|
||||
}
|
||||
|
||||
const maxEndMs = startMs + limitMinutes * 60 * 1000;
|
||||
if (candidate.getTime() > maxEndMs) {
|
||||
const cappedEndTime = new Date(maxEndMs);
|
||||
ctx.logger.info(
|
||||
`[returnUnpack.submit] 结束时间超过拆包录制上限,截断为上限时间 unpack_id=${unpack.id} ` +
|
||||
`limitMinutes=${limitMinutes} candidate=${candidate.toISOString()} end=${cappedEndTime.toISOString()}`
|
||||
);
|
||||
return cappedEndTime;
|
||||
}
|
||||
|
||||
return candidateEndTime;
|
||||
}
|
||||
|
||||
/**
|
||||
* 提交确认:未完成拆包单转 completed 终态,回写结束时间(超过仓库配置的
|
||||
* 拆包最大录制时长时自动截断为开始时间+上限),
|
||||
* 并同步更新退回查询记录 is_back=1(标记该运单号已退回)。
|
||||
*
|
||||
* @param {Object} params 提交参数。
|
||||
@ -523,8 +584,9 @@ class ReturnUnpackService extends Service {
|
||||
this._assertUnpacking(unpack);
|
||||
|
||||
const now = new Date();
|
||||
const endTime = await this._resolveSubmitEndTime(unpack, now);
|
||||
await ctx.model.ReturnUnpack.update(
|
||||
{ status: 'completed', end_time: now },
|
||||
{ status: 'completed', end_time: endTime },
|
||||
{ where: { id: unpack.id } }
|
||||
);
|
||||
|
||||
@ -899,6 +961,431 @@ class ReturnUnpackService extends Service {
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 导出退回拆包数据(双 Sheet:正常退回运单号列表 + 明细表)。
|
||||
* 复用 list 的 where/sort 语义;仓库隔离由方法层注入 warehouse_id,此处再强制兑底;
|
||||
* 分页拉取主表全量数据后批量关联明细/货主名称/快递类型,流式生成 Excel 并上传。
|
||||
*
|
||||
* @param {Object} options 导出选项。
|
||||
* @param {Object} [options.where] 标准化 where 条件(与 list 一致)。
|
||||
* @param {Object} [options.sort] 排序参数(与 list 一致)。
|
||||
* @param {number} [options.warehouseId] 仓库ID(由方法层从上下文注入)。
|
||||
* @param {Function} [options.onProgress] 进度回调。
|
||||
* @return {Promise<Object>} 上传结果与统计信息(含 url/cdnUrl/cosUrl/fileKey/current_count/total_count/total_details/sheet_count,
|
||||
* url 优先取上传服务返回的完整 URL,兜底取落库记录 file_url/fileUrl,最后才回退 COS key)。
|
||||
*/
|
||||
async exportUnpack(options = {}) {
|
||||
const { ctx, app } = this;
|
||||
const { Op } = app.Sequelize;
|
||||
const safeOptions = options && typeof options === 'object' && !Array.isArray(options) ? options : {};
|
||||
const where = safeOptions.where && typeof safeOptions.where === 'object' ? { ...safeOptions.where } : {};
|
||||
const sort = safeOptions.sort && typeof safeOptions.sort === 'object' ? { ...safeOptions.sort } : {};
|
||||
const warehouseId = Number(safeOptions.warehouseId || 0);
|
||||
const progressHandler = typeof safeOptions.onProgress === 'function'
|
||||
? safeOptions.onProgress
|
||||
: async () => {};
|
||||
|
||||
if (!Number.isFinite(warehouseId) || warehouseId <= 0) {
|
||||
throw this.createBusinessError('缺少仓库上下文', 400);
|
||||
}
|
||||
|
||||
// 复用 list 的 where/sort 语义,并强制仓库隔离(服务端注入,前端无需传 warehouse_id)
|
||||
const queryWhere = this._buildListWhere(where, Op);
|
||||
queryWhere.warehouse_id = warehouseId;
|
||||
const order = this._buildListOrder(sort, 'return_unpack');
|
||||
|
||||
const totalCount = await ctx.model.ReturnUnpack.count({ where: queryWhere });
|
||||
|
||||
await progressHandler({
|
||||
status: 'running',
|
||||
progress: totalCount > 0 ? 10 : 85,
|
||||
currentCount: 0,
|
||||
totalCount,
|
||||
message: totalCount > 0 ? `已命中 ${totalCount} 条拆包单,开始导出` : '未命中数据,开始生成空文件',
|
||||
});
|
||||
|
||||
// ---- 分页拉取主表全量数据 ----
|
||||
const allUnpackRows = [];
|
||||
let page = 1;
|
||||
while (allUnpackRows.length < totalCount) {
|
||||
const rows = await ctx.model.ReturnUnpack.findAll({
|
||||
where: queryWhere,
|
||||
order,
|
||||
limit: RETURN_UNPACK_EXPORT_PAGE_SIZE,
|
||||
offset: (page - 1) * RETURN_UNPACK_EXPORT_PAGE_SIZE,
|
||||
raw: true,
|
||||
});
|
||||
if (!Array.isArray(rows) || rows.length === 0) {
|
||||
break;
|
||||
}
|
||||
allUnpackRows.push(...rows);
|
||||
page += 1;
|
||||
await progressHandler({
|
||||
status: 'running',
|
||||
progress: Math.min(30, 10 + Math.round((allUnpackRows.length / Math.max(totalCount, 1)) * 20)),
|
||||
currentCount: allUnpackRows.length,
|
||||
totalCount,
|
||||
message: `正在拉取拆包单列表,已完成 ${allUnpackRows.length}/${totalCount}`,
|
||||
});
|
||||
}
|
||||
|
||||
// ---- 批量拉取明细(按 unpack_id 分批) ----
|
||||
const unpackIds = allUnpackRows
|
||||
.map(row => Number(row.id))
|
||||
.filter(id => Number.isInteger(id) && id > 0);
|
||||
/** @type {Map<number, Array<Object>>} */
|
||||
const detailsMap = new Map();
|
||||
if (unpackIds.length > 0) {
|
||||
const totalBatches = Math.ceil(unpackIds.length / RETURN_UNPACK_DETAIL_BATCH_SIZE);
|
||||
for (let batchIdx = 0; batchIdx < unpackIds.length; batchIdx += RETURN_UNPACK_DETAIL_BATCH_SIZE) {
|
||||
const batchIds = unpackIds.slice(batchIdx, batchIdx + RETURN_UNPACK_DETAIL_BATCH_SIZE);
|
||||
const details = await ctx.model.ReturnUnpackDetail.findAll({
|
||||
where: { unpack_id: { [Op.in]: batchIds } },
|
||||
order: [[ 'unpack_id', 'ASC' ], [ 'id', 'ASC' ]],
|
||||
raw: true,
|
||||
});
|
||||
for (const detail of details) {
|
||||
const key = Number(detail.unpack_id);
|
||||
if (!detailsMap.has(key)) {
|
||||
detailsMap.set(key, []);
|
||||
}
|
||||
detailsMap.get(key).push(detail);
|
||||
}
|
||||
const currentBatch = Math.floor(batchIdx / RETURN_UNPACK_DETAIL_BATCH_SIZE) + 1;
|
||||
await progressHandler({
|
||||
status: 'running',
|
||||
progress: Math.min(50, 30 + Math.round((currentBatch / totalBatches) * 20)),
|
||||
currentCount: allUnpackRows.length,
|
||||
totalCount,
|
||||
message: `正在拉取拆包明细,已完成批次 ${currentBatch}/${totalBatches}`,
|
||||
});
|
||||
}
|
||||
}
|
||||
const totalDetails = allUnpackRows.reduce(
|
||||
(sum, row) => sum + (detailsMap.get(Number(row.id)) || []).length,
|
||||
0
|
||||
);
|
||||
|
||||
// ---- 批量解析货主名称与快递类型 ----
|
||||
const storeNameMap = await this._resolveStoreNameMap(allUnpackRows, Op);
|
||||
const expressNameMap = await this._resolveExpressNameMap(allUnpackRows, Op);
|
||||
|
||||
await progressHandler({
|
||||
status: 'running',
|
||||
progress: 55,
|
||||
currentCount: allUnpackRows.length,
|
||||
totalCount,
|
||||
message: '正在生成 Excel 文件...',
|
||||
});
|
||||
|
||||
// ---- 生成 Excel(流式写入,两个 Sheet) ----
|
||||
const tempDir = await fsp.mkdtemp(path.join(os.tmpdir(), 'wms-return-unpack-export-'));
|
||||
const now = new Date();
|
||||
const dateToken = `${now.getFullYear()}${String(now.getMonth() + 1).padStart(2, '0')}${String(now.getDate()).padStart(2, '0')}${String(now.getHours()).padStart(2, '0')}${String(now.getMinutes()).padStart(2, '0')}${String(now.getSeconds()).padStart(2, '0')}`;
|
||||
const filename = `退回拆包导出_${dateToken}.xlsx`;
|
||||
const filePath = path.join(tempDir, filename);
|
||||
const workbook = new ExcelJS.stream.xlsx.WorkbookWriter({
|
||||
filename: filePath,
|
||||
useStyles: false,
|
||||
useSharedStrings: false,
|
||||
});
|
||||
|
||||
const normalizeCellValue = value => {
|
||||
if (value === null || value === undefined) return '';
|
||||
if (value instanceof Date) return app.formatDate ? app.formatDate(value) : value.toISOString();
|
||||
return value;
|
||||
};
|
||||
const formatDateOnly = value => (value ? app.formatDate(value, 'YYYY-MM-DD') : '');
|
||||
const formatDateTime = value => (value ? app.formatDate(value) : '');
|
||||
|
||||
try {
|
||||
// Sheet 1: 正常退回运单号列表
|
||||
const sheet1 = workbook.addWorksheet('正常退回运单号列表');
|
||||
const mainColumns = [
|
||||
{ header: '货主', key: 'store_name', width: 20 },
|
||||
{ header: '快递号', key: 'waybill_code', width: 22 },
|
||||
{ header: '商品类数', key: 'total_items', width: 12 },
|
||||
{ header: '商品总数', key: 'total_quantity', width: 12 },
|
||||
{ header: '记录人员', key: 'unpacker_name', width: 14 },
|
||||
{ header: '记录日期', key: 'unpack_date', width: 14 },
|
||||
{ header: '开始时间', key: 'start_time', width: 20 },
|
||||
{ header: '结束时间', key: 'end_time', width: 20 },
|
||||
{ header: '是否原单', key: 'is_original_return', width: 10 },
|
||||
{ header: '快递类型', key: 'express', width: 14 },
|
||||
{ header: '自定义店铺', key: 'shop_name', width: 20 },
|
||||
{ header: '平台单号', key: 'source_order_codes', width: 24 },
|
||||
];
|
||||
sheet1.columns = mainColumns;
|
||||
|
||||
for (const row of allUnpackRows) {
|
||||
const storeId = Number(row.store_id || 0);
|
||||
const expressId = Number(row.order_express_id || 0);
|
||||
sheet1.addRow({
|
||||
store_name: normalizeCellValue(storeId > 0 ? (storeNameMap.get(storeId) || '') : ''),
|
||||
waybill_code: normalizeCellValue(row.waybill_code),
|
||||
total_items: row.total_items,
|
||||
total_quantity: row.total_quantity,
|
||||
unpacker_name: normalizeCellValue(row.unpacker_name),
|
||||
unpack_date: formatDateOnly(row.unpack_date),
|
||||
start_time: formatDateTime(row.start_time),
|
||||
end_time: formatDateTime(row.end_time),
|
||||
is_original_return: row.order_express_id ? '是' : '否',
|
||||
express: normalizeCellValue(expressId > 0 ? (expressNameMap.get(expressId) || '') : ''),
|
||||
shop_name: normalizeCellValue(row.shop_name),
|
||||
source_order_codes: normalizeCellValue(row.source_order_codes),
|
||||
}).commit();
|
||||
}
|
||||
sheet1.commit();
|
||||
|
||||
await progressHandler({
|
||||
status: 'running',
|
||||
progress: 70,
|
||||
currentCount: allUnpackRows.length,
|
||||
totalCount,
|
||||
message: '正在写入拆包明细...',
|
||||
});
|
||||
|
||||
// Sheet 2: 明细表
|
||||
const sheet2 = workbook.addWorksheet('明细表');
|
||||
const detailColumns = [
|
||||
{ header: '货主', key: 'store_name', width: 20 },
|
||||
{ header: '快递号', key: 'waybill_code', width: 22 },
|
||||
{ header: '商品名称', key: 'item_name', width: 24 },
|
||||
{ header: '商品编码', key: 'item_code', width: 18 },
|
||||
{ header: '条码', key: 'barcode', width: 20 },
|
||||
{ header: '颜色', key: 'color', width: 12 },
|
||||
{ header: '规格', key: 'spec', width: 20 },
|
||||
{ header: '数量', key: 'quantity', width: 10 },
|
||||
{ header: '是否残次', key: 'is_damaged', width: 10 },
|
||||
{ header: '记录人员ID', key: 'unpacker_id', width: 14 },
|
||||
{ header: '记录日期', key: 'unpack_date', width: 14 },
|
||||
{ header: '备注', key: 'remark', width: 30 },
|
||||
{ header: '是否原单', key: 'is_original_return', width: 10 },
|
||||
{ header: '快递类型', key: 'express', width: 14 },
|
||||
{ header: '自定义店铺', key: 'shop_name', width: 20 },
|
||||
{ header: '平台单号', key: 'source_order_codes', width: 24 },
|
||||
];
|
||||
sheet2.columns = detailColumns;
|
||||
|
||||
let detailWrittenCount = 0;
|
||||
for (const row of allUnpackRows) {
|
||||
const storeId = Number(row.store_id || 0);
|
||||
const expressId = Number(row.order_express_id || 0);
|
||||
const storeName = storeId > 0 ? (storeNameMap.get(storeId) || '') : '';
|
||||
const expressName = expressId > 0 ? (expressNameMap.get(expressId) || '') : '';
|
||||
const details = detailsMap.get(Number(row.id)) || [];
|
||||
for (const detail of details) {
|
||||
sheet2.addRow({
|
||||
store_name: normalizeCellValue(storeName),
|
||||
waybill_code: normalizeCellValue(row.waybill_code),
|
||||
item_name: normalizeCellValue(detail.item_name),
|
||||
item_code: normalizeCellValue(detail.item_code),
|
||||
barcode: normalizeCellValue(detail.barcode),
|
||||
color: this._extractDetailColor(detail),
|
||||
spec: normalizeCellValue(detail.spec),
|
||||
quantity: detail.quantity,
|
||||
is_damaged: detail.product_status === 'damaged' ? '是' : '否',
|
||||
unpacker_id: row.unpacker_id,
|
||||
unpack_date: formatDateOnly(row.unpack_date),
|
||||
remark: normalizeCellValue(detail.remark),
|
||||
is_original_return: row.order_express_id ? '是' : '否',
|
||||
express: normalizeCellValue(expressName),
|
||||
shop_name: normalizeCellValue(row.shop_name),
|
||||
source_order_codes: normalizeCellValue(row.source_order_codes),
|
||||
}).commit();
|
||||
}
|
||||
detailWrittenCount += 1;
|
||||
if (detailWrittenCount % RETURN_UNPACK_DETAIL_BATCH_SIZE === 0 || detailWrittenCount === allUnpackRows.length) {
|
||||
await progressHandler({
|
||||
status: 'running',
|
||||
progress: Math.min(90, 70 + Math.round((detailWrittenCount / Math.max(allUnpackRows.length, 1)) * 20)),
|
||||
currentCount: allUnpackRows.length,
|
||||
totalCount,
|
||||
message: `正在写入拆包明细,已完成 ${detailWrittenCount}/${allUnpackRows.length} 条拆包单`,
|
||||
});
|
||||
}
|
||||
}
|
||||
sheet2.commit();
|
||||
|
||||
await workbook.commit();
|
||||
|
||||
await progressHandler({
|
||||
status: 'running',
|
||||
progress: 92,
|
||||
currentCount: allUnpackRows.length,
|
||||
totalCount,
|
||||
message: '正在上传文件...',
|
||||
});
|
||||
|
||||
// ---- 上传文件 ----
|
||||
const uploadService = ctx?.service?.systems?.upload;
|
||||
if (!uploadService || typeof uploadService.uploadFile !== 'function') {
|
||||
throw new Error('上传服务不可用');
|
||||
}
|
||||
|
||||
const stat = await fsp.stat(filePath);
|
||||
const randomToken = crypto.randomBytes(6).toString('hex');
|
||||
const uploadKey = `exports/return_unpack/${warehouseId}/${Date.now()}_${randomToken}.xlsx`;
|
||||
const uploadStream = fs.createReadStream(filePath);
|
||||
uploadStream.filename = filename;
|
||||
uploadStream.mimeType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
|
||||
uploadStream.fileSize = stat.size;
|
||||
|
||||
const uploadResult = await uploadService.uploadFile(uploadStream, {
|
||||
key: uploadKey,
|
||||
category: 'document',
|
||||
mimetype: 'xls,xlsx,csv',
|
||||
});
|
||||
|
||||
let fileRecord = null;
|
||||
if (typeof uploadService.uploadSuccessNotify === 'function') {
|
||||
fileRecord = await uploadService.uploadSuccessNotify({
|
||||
url: uploadResult.fileName,
|
||||
fileKey: uploadResult.fileName,
|
||||
fileName: filename,
|
||||
fileType: 'document',
|
||||
mimeType: uploadStream.mimeType,
|
||||
fileSize: stat.size,
|
||||
userId: ctx.userId,
|
||||
description: `退回拆包导出(仓库${warehouseId}),共${totalCount}条拆包单`,
|
||||
});
|
||||
}
|
||||
|
||||
// 优先取 uploadFile 返回的完整 URL,其次取 uploadSuccessNotify 落库记录(兼容 data 包裹),最后才回退 COS key
|
||||
const safeUploadResult = typeof uploadResult === 'object' && uploadResult !== null ? uploadResult : {};
|
||||
const resolvedFileRecord = (fileRecord && (fileRecord.data || fileRecord)) || null;
|
||||
const fileUrlFromRecord = resolvedFileRecord
|
||||
? (resolvedFileRecord.file_url || resolvedFileRecord.fileUrl || resolvedFileRecord.url || '')
|
||||
: '';
|
||||
const uploadResultUrl = safeUploadResult.url || safeUploadResult.cdnUrl || safeUploadResult.cosUrl || '';
|
||||
|
||||
const uploadInfo = {
|
||||
filename,
|
||||
fileKey: safeUploadResult.fileName || uploadKey,
|
||||
url: uploadResultUrl || fileUrlFromRecord || safeUploadResult.fileName || uploadKey,
|
||||
cdnUrl: safeUploadResult.cdnUrl || safeUploadResult.url || '',
|
||||
cosUrl: safeUploadResult.cosUrl || '',
|
||||
current_count: allUnpackRows.length,
|
||||
total_count: totalCount,
|
||||
total_details: totalDetails,
|
||||
sheet_count: 2,
|
||||
};
|
||||
|
||||
await progressHandler({
|
||||
status: 'success',
|
||||
progress: 100,
|
||||
currentCount: allUnpackRows.length,
|
||||
totalCount,
|
||||
message: '导出任务完成',
|
||||
result: uploadInfo,
|
||||
});
|
||||
|
||||
return uploadInfo;
|
||||
} catch (error) {
|
||||
const workbookStream = workbook.stream;
|
||||
if (workbookStream && typeof workbookStream.destroy === 'function') {
|
||||
workbookStream.destroy();
|
||||
}
|
||||
throw error;
|
||||
} finally {
|
||||
// 清理临时文件(不存在或删除失败均忽略)
|
||||
try { await fsp.rm(tempDir, { recursive: true, force: true }); } catch (err) { /* ignore */ }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 批量解析货主名称映射(store_id → wms_store.company_name)。
|
||||
* @param {Array<Object>} rows 主表行数组。
|
||||
* @param {Object} Op Sequelize Op 对象。
|
||||
* @return {Promise<Map<number, string>>} store_id → 货主名称映射。
|
||||
*/
|
||||
async _resolveStoreNameMap(rows = [], Op) {
|
||||
const { ctx } = this;
|
||||
const storeIds = [ ...new Set(
|
||||
(Array.isArray(rows) ? rows : [])
|
||||
.map(row => Number(row && row.store_id || 0))
|
||||
.filter(id => Number.isInteger(id) && id > 0)
|
||||
) ];
|
||||
/** @type {Map<number, string>} */
|
||||
const nameMap = new Map();
|
||||
if (storeIds.length === 0) {
|
||||
return nameMap;
|
||||
}
|
||||
try {
|
||||
const stores = await ctx.model.Store.findAll({
|
||||
where: { id: { [Op.in]: storeIds } },
|
||||
attributes: [ 'id', 'company_name' ],
|
||||
raw: true,
|
||||
});
|
||||
for (const store of stores) {
|
||||
nameMap.set(Number(store.id), store.company_name ? String(store.company_name) : '');
|
||||
}
|
||||
} catch (err) {
|
||||
ctx.logger.warn(`[returnUnpack.export] 批量解析货主名称失败: ${err.message}`);
|
||||
}
|
||||
return nameMap;
|
||||
}
|
||||
|
||||
/**
|
||||
* 批量解析快递类型映射(order_express_id → wms_order_express.logistics_name)。
|
||||
* @param {Array<Object>} rows 主表行数组。
|
||||
* @param {Object} Op Sequelize Op 对象。
|
||||
* @return {Promise<Map<number, string>>} order_express_id → 快递类型映射。
|
||||
*/
|
||||
async _resolveExpressNameMap(rows = [], Op) {
|
||||
const { ctx } = this;
|
||||
const expressIds = [ ...new Set(
|
||||
(Array.isArray(rows) ? rows : [])
|
||||
.map(row => Number(row && row.order_express_id || 0))
|
||||
.filter(id => Number.isInteger(id) && id > 0)
|
||||
) ];
|
||||
/** @type {Map<number, string>} */
|
||||
const nameMap = new Map();
|
||||
if (expressIds.length === 0) {
|
||||
return nameMap;
|
||||
}
|
||||
try {
|
||||
const expresses = await ctx.model.OrderExpress.findAll({
|
||||
where: { id: { [Op.in]: expressIds } },
|
||||
attributes: [ 'id', 'logistics_name' ],
|
||||
raw: true,
|
||||
});
|
||||
for (const express of expresses) {
|
||||
nameMap.set(Number(express.id), express.logistics_name ? String(express.logistics_name) : '');
|
||||
}
|
||||
} catch (err) {
|
||||
ctx.logger.warn(`[returnUnpack.export] 批量解析快递类型失败: ${err.message}`);
|
||||
}
|
||||
return nameMap;
|
||||
}
|
||||
|
||||
/**
|
||||
* 从明细快照/规格中提取颜色(优先 product_snapshot.sku_property,兜底 spec 字段)。
|
||||
* 颜色约定以「颜色:xxx」形式出现在 SKU 规格串中,未命中返回空字符串。
|
||||
* @param {Object} detail 明细行。
|
||||
* @return {string} 颜色文本,未命中返回空字符串。
|
||||
*/
|
||||
_extractDetailColor(detail = {}) {
|
||||
let spec = detail && detail.spec ? String(detail.spec) : '';
|
||||
const snapshot = detail && detail.product_snapshot;
|
||||
if (snapshot) {
|
||||
try {
|
||||
const parsed = typeof snapshot === 'string' ? JSON.parse(snapshot) : snapshot;
|
||||
if (parsed && typeof parsed === 'object' && !Array.isArray(parsed) && parsed.sku_property) {
|
||||
spec = String(parsed.sku_property);
|
||||
}
|
||||
} catch (err) {
|
||||
// 快照解析失败时退回 spec 字段
|
||||
}
|
||||
}
|
||||
const normalized = String(spec || '').trim();
|
||||
if (!normalized) {
|
||||
return '';
|
||||
}
|
||||
const match = normalized.match(/颜色[::]\s*([^;;,,]+)/);
|
||||
return match && match[1] ? String(match[1]).trim() : '';
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询拆包单详情:主表 + 明细 + 视频 + 退回收到单 + 原订单详情(原单退回时)。
|
||||
*
|
||||
@ -1690,11 +2177,13 @@ class ReturnUnpackService extends Service {
|
||||
/**
|
||||
* 生成拆包单号(原子取号)。
|
||||
* 格式:RP + YYYYMMDD + 6位序号(如 RP20260813000001)。
|
||||
* 取号基于序列表 wms_number_sequence 的单条 upsert 原子递增:
|
||||
* INSERT ... VALUES (LAST_INSERT_ID(:seed + 1)) ON DUPLICATE KEY UPDATE
|
||||
* current_seq = LAST_INSERT_ID(GREATEST(current_seq, :seed) + 1)
|
||||
* 取号基于序列表 wms_number_sequence 的 upsert 原子递增(唯一键 uk_warehouse_biz_date 串行化并发事务):
|
||||
* INSERT ... VALUES (:seed + 1) ON DUPLICATE KEY UPDATE
|
||||
* current_seq = GREATEST(current_seq, :seed) + 1
|
||||
* 其中 :seed 为当日主表已有最大序号,保证历史数据对齐(首日启用不撞已有单号);
|
||||
* 同事务(同连接)内回读 LAST_INSERT_ID() 取回本次分配序号,并发下无撞号。
|
||||
* upsert 后通过带锁当前读(SELECT ... FOR UPDATE)回读 current_seq,
|
||||
* 避免 REPEATABLE READ 快照读读到旧值导致撞号或跳号。
|
||||
* 注意:不再依赖 LAST_INSERT_ID() 回读,因为 fresh INSERT 时其会被序列表自增主键覆盖。
|
||||
*
|
||||
* @param {number} warehouseId 仓库ID。
|
||||
* @return {Promise<string>} 拆包单号。
|
||||
@ -1723,25 +2212,31 @@ class ReturnUnpackService extends Service {
|
||||
);
|
||||
const seed = Number(seedRows && seedRows[0] && seedRows[0].max_seq) || 0;
|
||||
|
||||
// 原子取号:单条 upsert 内递增并设置连接级 LAST_INSERT_ID
|
||||
// 原子取号:单条 upsert 内按唯一键串行化并发事务递增 current_seq
|
||||
await ctx.model.query(
|
||||
`INSERT INTO wms_number_sequence (warehouse_id, biz_type, date_part, current_seq, created_at, updated_at)
|
||||
VALUES (:warehouseId, :bizType, :datePart, LAST_INSERT_ID(:seed + 1), NOW(), NOW())
|
||||
ON DUPLICATE KEY UPDATE current_seq = LAST_INSERT_ID(GREATEST(current_seq, :seed) + 1), updated_at = NOW()`,
|
||||
VALUES (:warehouseId, :bizType, :datePart, :seed + 1, NOW(), NOW())
|
||||
ON DUPLICATE KEY UPDATE current_seq = GREATEST(current_seq, :seed) + 1, updated_at = NOW()`,
|
||||
{
|
||||
replacements: { warehouseId, bizType, datePart, seed },
|
||||
transaction,
|
||||
}
|
||||
);
|
||||
|
||||
// 带锁当前读回读:同事务已通过 upsert 持有该行排他锁(或经唯一键冲突等待串行化),
|
||||
// FOR UPDATE 返回本事务最新写入值或最新提交版本,不受旧快照影响
|
||||
const rows = await ctx.model.query(
|
||||
'SELECT LAST_INSERT_ID() AS seq',
|
||||
`SELECT current_seq
|
||||
FROM wms_number_sequence
|
||||
WHERE warehouse_id = :warehouseId AND biz_type = :bizType AND date_part = :datePart
|
||||
FOR UPDATE`,
|
||||
{
|
||||
replacements: { warehouseId, bizType, datePart },
|
||||
type: ctx.model.QueryTypes.SELECT,
|
||||
transaction,
|
||||
}
|
||||
);
|
||||
return Number(rows && rows[0] && rows[0].seq) || 1;
|
||||
return Number(rows && rows[0] && rows[0].current_seq) || 1;
|
||||
});
|
||||
|
||||
if (sequence > 999999) {
|
||||
|
||||
@ -292,6 +292,15 @@ const WAREHOUSE_SETTING_FIELDS = Object.freeze([
|
||||
description: '团购打包最大时长,单位:分钟,默认 40',
|
||||
min: 1,
|
||||
}),
|
||||
Object.freeze({
|
||||
key: 'return_unpack_max_record_minutes',
|
||||
name: '拆包最大录制时长(分钟)',
|
||||
type: 'integer',
|
||||
default: 5,
|
||||
required: false,
|
||||
description: '拆包最大录制时长,单位:分钟,默认 5;超过上限时提交的结束时间自动截断为开始时间+上限',
|
||||
min: 1,
|
||||
}),
|
||||
Object.freeze({
|
||||
key: 'default_location_id',
|
||||
name: '默认库位',
|
||||
|
||||
@ -1517,6 +1517,7 @@ class EntryService extends Service {
|
||||
* 快捷直入/虚拟入库:将入库单明细直入到虚拟库位(space_id=2),跳过收货、质检等正常流程。
|
||||
* 有绑定收货单时,只取收货单中与入库单明细有交集(按 stock_id 判断)且剩余可入数量的部分直入,
|
||||
* 并回写收货单明细已入库数量;未绑定收货单时按明细计划数量全量直入。
|
||||
* 有绑定收货单时回写 is_virtual_inbound=0(非虚拟入库),无绑定收货单时回写 is_virtual_inbound=1(虚拟入库)。
|
||||
* 采用"先同步后写库"两段式:① 先发奇门/OpenAPI 回传,② 回传成功后再开启事务写库存。
|
||||
* @param {Object} data 请求体
|
||||
* @param {number} data.id 入库单ID
|
||||
@ -1843,6 +1844,8 @@ class EntryService extends Service {
|
||||
await eo.update({
|
||||
order_status: 'COMPLETED',
|
||||
sync_status: 'SUCCESS',
|
||||
// 有绑定收货单 → 非虚拟入库(0);无绑定收货单 → 虚拟入库(1)
|
||||
is_virtual_inbound: receivingIds.length > 0 ? 0 : 1,
|
||||
sync_message: JSON.stringify({
|
||||
completedAt: new Date(),
|
||||
totalQuantity: totalInboundQty,
|
||||
|
||||
@ -1249,7 +1249,7 @@ class ReceivingService extends Service {
|
||||
if (excelService && typeof excelService.generateAndUpload === 'function') {
|
||||
const receivingNumber = String(r.receiving_number || r.id).replace(/[\\/:*?"<>|]/g, '_');
|
||||
reviewReport = await excelService.generateAndUpload({
|
||||
filename: `审核明细_${receivingNumber}.xlsx`,
|
||||
filename: `receiving_review_${receivingNumber}.xlsx`,
|
||||
dir: `exports/receiving/reviewed/${warehouse_id}`,
|
||||
category: 'document',
|
||||
saveRecord: true,
|
||||
@ -1535,10 +1535,13 @@ class ReceivingService extends Service {
|
||||
trackingNumber ? `快递单号:${trackingNumber} 已登记` : '快递单号:无',
|
||||
];
|
||||
|
||||
const receiverName = this.resolveReceivingCreatorName(receiving);
|
||||
|
||||
const contentLines = [
|
||||
`收货单号:${receivingNumber} 正在收货`,
|
||||
`货主:${storeLabel}`,
|
||||
...vehicleInfoLines,
|
||||
`收货人:${receiverName || '无'}`,
|
||||
];
|
||||
const content = [ ...contentLines ].join('\n') + '。';
|
||||
const storeContent = [ ...contentLines, `快速查看:${storeFrontendUrl}/storage/receiving_owner?id=${receivingNumber}` ].join('\n') + '。';
|
||||
@ -1572,6 +1575,34 @@ class ReceivingService extends Service {
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析收货单创建人(收货人)姓名:优先 creator_snapshot 快照,回退当前操作人。
|
||||
* @param {Object} receiving 收货单快照
|
||||
* @return {string} 姓名,无则空字符串
|
||||
*/
|
||||
resolveReceivingCreatorName(receiving = {}) {
|
||||
const { ctx } = this;
|
||||
const rawSnapshot = receiving.creator_snapshot || null;
|
||||
let name = '';
|
||||
|
||||
if (typeof rawSnapshot === 'string' && rawSnapshot.trim()) {
|
||||
try {
|
||||
const snapshot = JSON.parse(rawSnapshot);
|
||||
name = String(snapshot && (snapshot.name || snapshot.employees_name || snapshot.real_name) || '').trim();
|
||||
} catch (_) {
|
||||
/* 快照解析失败忽略 */
|
||||
}
|
||||
} else if (rawSnapshot && typeof rawSnapshot === 'object') {
|
||||
name = String(rawSnapshot.name || rawSnapshot.employees_name || rawSnapshot.real_name || '').trim();
|
||||
}
|
||||
|
||||
if (!name) {
|
||||
name = String((ctx.user && ctx.user.employees_name) || '').trim();
|
||||
}
|
||||
|
||||
return name;
|
||||
}
|
||||
|
||||
/**
|
||||
* 发送审核完成通知(receiving_reviewed),支持文字/文件两种类型。
|
||||
* @param {Object} options 发送参数
|
||||
@ -1608,9 +1639,6 @@ class ReceivingService extends Service {
|
||||
const reportUrl = String(
|
||||
(reviewReport && (reviewReport.url || reviewReport.cdnUrl || reviewReport.cosUrl || reviewReport.fileUrl)) || ''
|
||||
).trim();
|
||||
const reportFileName = String(
|
||||
(reviewReport && (reviewReport.filename || reviewReport.fileKey || reviewReport.key)) || `审核明细_${receivingNumber}.xlsx`
|
||||
).trim();
|
||||
|
||||
const detailList = Array.isArray(details) ? details : [];
|
||||
const codeMap = itemCodeMap instanceof Map ? itemCodeMap : new Map();
|
||||
@ -1627,21 +1655,18 @@ class ReceivingService extends Service {
|
||||
} else if (productLines.length > 0) {
|
||||
contentLines.push('', '商品:', ...productLines);
|
||||
}
|
||||
contentLines.push('', '请及时提交入库单入库');
|
||||
contentLines.push('', `请及时提交入库单入库,入库单务必备注${receivingNumber}`);
|
||||
const content = contentLines.join('\n') + '。';
|
||||
|
||||
return await noticeService.send({
|
||||
warehouseId,
|
||||
storeId: Number.isFinite(storeId) && storeId > 0 ? storeId : undefined,
|
||||
messageType: reportUrl ? 'file' : 'text',
|
||||
messageType: 'text',
|
||||
businessName: 'receiving',
|
||||
event: 'receiving_reviewed',
|
||||
channel: 'warehouse',
|
||||
title: `收货单${receivingNumber}完成收货审核`,
|
||||
content,
|
||||
url: reportUrl || undefined,
|
||||
fileName: reportUrl ? reportFileName : '',
|
||||
mimeType: reportUrl ? 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' : '',
|
||||
businessId: receiving.id,
|
||||
subject: {
|
||||
id: warehouseId,
|
||||
@ -1662,7 +1687,8 @@ class ReceivingService extends Service {
|
||||
}
|
||||
|
||||
/**
|
||||
* 反查货主商品编码:收货明细 system_product_id 对应 wms_stock_store.stock_id,取 item_code 作为商品编码。
|
||||
* 反查商品编码:收货明细 system_product_id 优先反查 wms_stock_store.stock_id 取 item_code;
|
||||
* 无对应货主商品资料时兜底取 wms_stock_warehouse.item_code(库存商品维度)。
|
||||
* @param {Array<Object>} details 收货明细列表(含 system_product_id)
|
||||
* @return {Promise<Map<number, string>>} system_product_id → item_code
|
||||
*/
|
||||
@ -1677,15 +1703,21 @@ class ReceivingService extends Service {
|
||||
) ];
|
||||
if (stockIds.length === 0) return codeMap;
|
||||
|
||||
const rows = await ctx.model.StockStore.findAll({
|
||||
where: {
|
||||
stock_id: { [Op.in]: stockIds },
|
||||
delete_at: null,
|
||||
},
|
||||
attributes: [ 'stock_id', 'item_code' ],
|
||||
order: [[ 'id', 'ASC' ]],
|
||||
raw: true,
|
||||
});
|
||||
// 1. 货主商品资料:wms_stock_store.stock_id → item_code(失败不影响主流程)
|
||||
let rows = [];
|
||||
try {
|
||||
rows = await ctx.model.StockStore.findAll({
|
||||
where: {
|
||||
stock_id: { [Op.in]: stockIds },
|
||||
delete_at: null,
|
||||
},
|
||||
attributes: [ 'stock_id', 'item_code' ],
|
||||
order: [[ 'id', 'ASC' ]],
|
||||
raw: true,
|
||||
});
|
||||
} catch (storeErr) {
|
||||
ctx.logger.warn(`[resolveReviewDetailItemCodeMap] 反查货主商品资料失败: ${storeErr.message}`);
|
||||
}
|
||||
|
||||
rows.forEach(row => {
|
||||
const stockId = Number(row.stock_id);
|
||||
@ -1694,6 +1726,30 @@ class ReceivingService extends Service {
|
||||
if (itemCode) codeMap.set(stockId, itemCode);
|
||||
});
|
||||
|
||||
// 2. 兜底:无对应 stock_store 时取 wms_stock_warehouse.item_code
|
||||
const missingStockIds = stockIds.filter(id => !codeMap.has(id));
|
||||
if (missingStockIds.length > 0) {
|
||||
try {
|
||||
const warehouseRows = await ctx.model.StockWarehouse.findAll({
|
||||
where: {
|
||||
id: { [Op.in]: missingStockIds },
|
||||
deleted_at: null,
|
||||
},
|
||||
attributes: [ 'id', 'item_code' ],
|
||||
raw: true,
|
||||
});
|
||||
|
||||
warehouseRows.forEach(row => {
|
||||
const stockId = Number(row.id);
|
||||
if (!stockId || codeMap.has(stockId)) return;
|
||||
const itemCode = String(row.item_code || '').trim();
|
||||
if (itemCode) codeMap.set(stockId, itemCode);
|
||||
});
|
||||
} catch (warehouseErr) {
|
||||
ctx.logger.warn(`[resolveReviewDetailItemCodeMap] 兜底反查仓库商品失败: ${warehouseErr.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
return codeMap;
|
||||
}
|
||||
|
||||
@ -2126,6 +2182,7 @@ class ReceivingService extends Service {
|
||||
store_name: result.store_name,
|
||||
license_plate: result.license_plate,
|
||||
tracking_number: result.tracking_number,
|
||||
creator_snapshot: result.creator_snapshot,
|
||||
},
|
||||
});
|
||||
} catch (noticeErr) {
|
||||
@ -2489,6 +2546,7 @@ class ReceivingService extends Service {
|
||||
store_name: storeName,
|
||||
license_plate: receiving.license_plate,
|
||||
tracking_number: receiving.tracking_number,
|
||||
creator_snapshot: receiving.creator_snapshot,
|
||||
},
|
||||
});
|
||||
} catch (noticeErr) {
|
||||
@ -3367,6 +3425,7 @@ class ReceivingService extends Service {
|
||||
store_name: storeName,
|
||||
license_plate: receiving.license_plate,
|
||||
tracking_number: receiving.tracking_number,
|
||||
creator_snapshot: receiving.creator_snapshot,
|
||||
},
|
||||
});
|
||||
} catch (noticeErr) {
|
||||
|
||||
@ -224,25 +224,55 @@ class WarehouseNotifyService extends Service {
|
||||
}
|
||||
|
||||
/**
|
||||
* 向指定群推送系统级业务通知(复用 notify.reply,type=system)。
|
||||
* 向指定群(可选)与成员(可选)推送系统级业务通知(复用 notify.reply,type=system)。
|
||||
* 对方接口只处理 content 内容,推送体仅保留协议必需字段:
|
||||
* type / content / ext_id / group_id / group_name / timestamp。
|
||||
* type / content / ext_id / group_id / group_name / user_id / timestamp。
|
||||
* 推送前写入 wms_inbox_message(direction=outbound,source_type=system),
|
||||
* 推送后按结果回写 push_status(2=已送达 / 3=失败)与 push_response。
|
||||
*
|
||||
* 向后兼容:不传 userIds 且传入 group 时,行为与旧版本完全一致
|
||||
* (校验、幂等 ext_id、落库字段、推送体均不变)。
|
||||
*
|
||||
* @param {Object} options 推送参数。
|
||||
* @param {number} options.warehouseId 仓库 ID。
|
||||
* @param {number} [options.storeId] 货主 ID。
|
||||
* @param {Object} options.group 目标群 { group_id, group_name }。
|
||||
* @param {Object|null} [options.group=null] 目标群 { group_id, group_name, ext_data }
|
||||
* (新增允许为 null:仅成员推送场景)。
|
||||
* @param {Array<string>|null} [options.userIds=null] 目标成员外部 IM 用户 ID 数组
|
||||
* (新增,目标侧协议支持 user_id 数组:整体透传不循环拆发)。
|
||||
* @param {string} [options.content=''] 通知正文。
|
||||
* @param {number|string} [options.extId] 业务单号(用于幂等 ext_id)。
|
||||
* @param {Object} [options.extData] 群扩展数据(渠道信息,落库与推送透传)。
|
||||
* @return {Promise<Object>} 推送结果(含 messageId)。
|
||||
*/
|
||||
async pushSystemMessage({ warehouseId, storeId = null, group, content = '', extId = null } = {}) {
|
||||
async pushSystemMessage({
|
||||
warehouseId,
|
||||
storeId = null,
|
||||
group = null,
|
||||
userIds = null,
|
||||
content = '',
|
||||
extId = null,
|
||||
extData = null,
|
||||
} = {}) {
|
||||
const { ctx } = this;
|
||||
const groupId = String((group && group.group_id) || '').trim();
|
||||
const groupName = String((group && group.group_name) || '').trim();
|
||||
// 成员ID规范化:仅接受字符串数组,去重并过滤空值(向后兼容:旧调用不传时为空数组)
|
||||
const normalizedUserIds = Array.isArray(userIds)
|
||||
? [ ...new Set(userIds.map(item => String(item || '').trim()).filter(Boolean)) ]
|
||||
: [];
|
||||
|
||||
if (!groupId || !groupName) {
|
||||
// 向后兼容:无群且无成员时保持旧版 skip 语义(原判断 !groupId || !groupName)
|
||||
if (!groupId && normalizedUserIds.length === 0) {
|
||||
return {
|
||||
success: false,
|
||||
skipped: true,
|
||||
reason: '目标群缺少 group_id 或 group_name',
|
||||
warehouseId,
|
||||
};
|
||||
}
|
||||
// 指定了群但缺群名:与旧版一致返回 skip(群维度协议要求 group_name)
|
||||
if (groupId && !groupName) {
|
||||
return {
|
||||
success: false,
|
||||
skipped: true,
|
||||
@ -251,9 +281,19 @@ class WarehouseNotifyService extends Service {
|
||||
};
|
||||
}
|
||||
|
||||
// 幂等 ext_id:业务单号 + 群维度,网络重推时复用同一条消息记录
|
||||
// 幂等 ext_id:业务单号 + 事件 + 目标维度(群优先、仅成员时按成员集合),
|
||||
// 网络重推时复用同一条消息记录;超长时降级哈希兜底
|
||||
const sourceExtId = String(extId || `sys:notice:${Date.now()}:${Math.random().toString(36).slice(2, 8)}`);
|
||||
const uniqueExtId = `sys:notice:${sourceExtId}:${groupId}`;
|
||||
const memberKey = normalizedUserIds.length > 0 ? `members:${normalizedUserIds.join(',')}` : '';
|
||||
const targetKey = groupId || memberKey;
|
||||
let uniqueExtId = `sys:notice:${sourceExtId}:${targetKey}`;
|
||||
if (uniqueExtId.length > 128) {
|
||||
const digest = crypto.createHash('md5')
|
||||
.update(uniqueExtId)
|
||||
.digest('hex')
|
||||
.slice(0, 12);
|
||||
uniqueExtId = `sys:notice:${sourceExtId.slice(0, 100)}:${digest}`;
|
||||
}
|
||||
|
||||
const InboxMessage = ctx.model && ctx.model.InboxMessage;
|
||||
const normalizedContent = String(content || '').trim() || '系统通知';
|
||||
@ -278,12 +318,14 @@ class WarehouseNotifyService extends Service {
|
||||
source_type: 'system',
|
||||
source_extra: 'notice',
|
||||
target_type: 'api',
|
||||
group_id: groupId,
|
||||
group_id: groupId || null,
|
||||
// 成员数组仅随推送体 user_id 透传并记录在 report_delivery_log.notify_targets 快照中,
|
||||
// 消息表 user_id 列(STRING(100))不承载数组,避免超长截断
|
||||
user_id: null,
|
||||
group_name: groupName,
|
||||
group_name: groupName || null,
|
||||
user_name: null,
|
||||
content: normalizedContent,
|
||||
ext_data: null,
|
||||
ext_data: extData || null,
|
||||
flags: {},
|
||||
push_status: 1,
|
||||
push_started_at: new Date(),
|
||||
@ -295,17 +337,26 @@ class WarehouseNotifyService extends Service {
|
||||
}
|
||||
}
|
||||
|
||||
// 推送体:群字段仅指定群时携带;成员 user_id 直接传数组(目标侧协议支持),不循环拆发
|
||||
const pushData = {
|
||||
type: 'system',
|
||||
content: normalizedContent,
|
||||
ext_id: sourceExtId,
|
||||
ext_data: extData || null,
|
||||
timestamp: Math.floor(Date.now() / 1000),
|
||||
};
|
||||
if (groupId) {
|
||||
pushData.group_id = groupId;
|
||||
pushData.group_name = groupName;
|
||||
}
|
||||
if (normalizedUserIds.length > 0) {
|
||||
pushData.user_id = normalizedUserIds;
|
||||
}
|
||||
|
||||
const result = await this.push({
|
||||
warehouseId,
|
||||
method: 'notify.reply',
|
||||
data: {
|
||||
type: 'system',
|
||||
content: normalizedContent,
|
||||
ext_id: sourceExtId,
|
||||
group_id: groupId,
|
||||
group_name: groupName,
|
||||
timestamp: Math.floor(Date.now() / 1000),
|
||||
},
|
||||
data: pushData,
|
||||
});
|
||||
|
||||
// 回写推送状态(失败仅记日志,不影响业务)
|
||||
|
||||
@ -154,7 +154,7 @@ class WaybillService extends MainService {
|
||||
* 主单号通过 SELF JOIN 同 order_id 下 business_key=1 的记录获取。
|
||||
*
|
||||
* @param {Object} [options={}] 查询参数。
|
||||
* @param {Object} [options.where] 筛选条件,支持 waybillCode / mainWaybillCode / orderId / orderNo / logisticsCode / logisticsInterfaceId / platformCode / status / isBack / isIntercept / isGalaxyReceive / packageMaterialId / hasWeighingWeight / keyword / createdAt({operator:'between', value:[start,end]},兼容 createAt 别名)/ createdAtStart / createdAtEnd(旧写法兼容)。
|
||||
* @param {Object} [options.where] 筛选条件,支持 waybillCode(字符串模糊匹配 / 字符串数组精确匹配)/ mainWaybillCode / orderId / orderNo / logisticsCode / logisticsInterfaceId / platformCode / status / isBack / isIntercept / isGalaxyReceive / packageMaterialId / hasWeighingWeight / keyword / createdAt({operator:'between', value:[start,end]},兼容 createAt 别名)/ createdAtStart / createdAtEnd(旧写法兼容)。
|
||||
* @param {Object} [options.pagination] 分页参数 { page, pageSize },默认 page=1, pageSize=20。
|
||||
* @param {Object} [options.sort] 排序参数 { field, order },默认 create_at desc。
|
||||
* @return {Promise<Object>} 运单列表与分页信息 { list, pagination }。
|
||||
@ -222,9 +222,16 @@ class WaybillService extends MainService {
|
||||
}
|
||||
}
|
||||
|
||||
// 运单号模糊搜索
|
||||
// 运单号搜索:数组精确匹配(Op.in),字符串保持模糊匹配(Op.like)
|
||||
const waybillCode = val(where.waybillCode);
|
||||
if (waybillCode && String(waybillCode).trim()) {
|
||||
if (Array.isArray(waybillCode)) {
|
||||
const waybillCodeList = waybillCode
|
||||
.map(item => (item === undefined || item === null ? '' : String(item).trim()))
|
||||
.filter(item => item !== '');
|
||||
if (waybillCodeList.length > 0) {
|
||||
queryWhere.waybill_code = { [Op.in]: waybillCodeList };
|
||||
}
|
||||
} else if (waybillCode && String(waybillCode).trim()) {
|
||||
queryWhere.waybill_code = { [Op.like]: `%${String(waybillCode).trim()}%` };
|
||||
}
|
||||
|
||||
@ -756,8 +763,16 @@ class WaybillService extends MainService {
|
||||
}
|
||||
}
|
||||
|
||||
// 运单号搜索:数组精确匹配(Op.in),字符串保持模糊匹配(Op.like),与 list 保持一致
|
||||
const waybillCodeExport = val(where.waybillCode);
|
||||
if (waybillCodeExport && String(waybillCodeExport).trim()) {
|
||||
if (Array.isArray(waybillCodeExport)) {
|
||||
const waybillCodeListExport = waybillCodeExport
|
||||
.map(item => (item === undefined || item === null ? '' : String(item).trim()))
|
||||
.filter(item => item !== '');
|
||||
if (waybillCodeListExport.length > 0) {
|
||||
queryWhere.waybill_code = { [Op.in]: waybillCodeListExport };
|
||||
}
|
||||
} else if (waybillCodeExport && String(waybillCodeExport).trim()) {
|
||||
queryWhere.waybill_code = { [Op.like]: `%${String(waybillCodeExport).trim()}%` };
|
||||
}
|
||||
const orderIdExport = val(where.orderId);
|
||||
|
||||
@ -4,6 +4,11 @@ const Service = require('egg').Service;
|
||||
|
||||
const { isInterceptedOrderStatus } = require('../../lib/intercept_guard');
|
||||
|
||||
/** @type {string} 工作台波次订单实时计数缓存 key 前缀(最终 key:{前缀}:{warehouseId}:{waveId}) */
|
||||
const WAVE_ORDER_COUNT_CACHE_KEY_PREFIX = 'cache:workbench:wave_order_count';
|
||||
/** @type {number} 工作台波次订单实时计数缓存 TTL(秒),TTL 内分表 COUNT 只执行一次 */
|
||||
const WAVE_ORDER_COUNT_CACHE_TTL_SECONDS = 15;
|
||||
|
||||
class WorkbenchService extends Service {
|
||||
/**
|
||||
* 查询工作台列表(仓库隔离 + 软删除过滤)
|
||||
@ -213,10 +218,15 @@ class WorkbenchService extends Service {
|
||||
}
|
||||
|
||||
/**
|
||||
* 实时统计波次下的订单数量(遍历 current + dispatch 分表)
|
||||
* @param {number} warehouseId
|
||||
* @param {number} waveId
|
||||
* @returns {Promise<number>}
|
||||
* 实时统计波次下的订单数量(并发遍历 current + dispatch 分表)
|
||||
*
|
||||
* current 与 dispatch 两张分表的 COUNT 相互独立,使用 Promise.all 并发执行,
|
||||
* 将缓存未命中时的实时统计耗时从两张表串行累加压缩为单表耗时级别;
|
||||
* 单张分表查询失败时按 0 处理,不影响另一张表的统计结果。
|
||||
*
|
||||
* @param {number} warehouseId 仓库ID
|
||||
* @param {number} waveId 波次ID
|
||||
* @return {Promise<number>} 波次下 current + dispatch 两张分表的订单总数
|
||||
*/
|
||||
async _countWaveOrders(warehouseId, waveId) {
|
||||
const { ctx } = this;
|
||||
@ -225,15 +235,56 @@ class WorkbenchService extends Service {
|
||||
{ label: 'current', getModel: () => orderDeliveryFactory.getCurrentModel(warehouseId) },
|
||||
{ label: 'dispatch', getModel: () => orderDeliveryFactory.getDispatchModel(warehouseId) },
|
||||
];
|
||||
let total = 0;
|
||||
for (const entry of tableOrders) {
|
||||
const counts = await Promise.all(tableOrders.map(async entry => {
|
||||
try {
|
||||
const model = await entry.getModel();
|
||||
if (!model) continue;
|
||||
const count = await model.count({ where: { wave_id: waveId, warehouse_id: warehouseId } });
|
||||
total += count;
|
||||
} catch (_err) { continue; }
|
||||
if (!model) return 0;
|
||||
return await model.count({ where: { wave_id: waveId, warehouse_id: warehouseId } });
|
||||
} catch (_err) { return 0; }
|
||||
}));
|
||||
return counts.reduce((total, count) => total + count, 0);
|
||||
}
|
||||
|
||||
/**
|
||||
* 团购波次订单实时计数(带 Redis 短 TTL 缓存兜底)
|
||||
*
|
||||
* 分表 COUNT 无可用索引时扫描行数大、耗时长(生产实测 680~730ms/次)。
|
||||
* wave_batch.total_orders 为多处异步维护的快照值,存在漂移风险,不能直接替代实时计数,
|
||||
* 因此对实时计数结果按 (warehouseId, waveId) 维度做短 TTL 缓存:
|
||||
* TTL 内重复查询直接命中缓存,缓存不可用或读取失败时降级为实时统计。
|
||||
*
|
||||
* @param {number} warehouseId 仓库ID
|
||||
* @param {number} waveId 波次ID
|
||||
* @return {Promise<number>} 波次下 current + dispatch 两张分表的订单总数
|
||||
*/
|
||||
async _countWaveOrdersCached(warehouseId, waveId) {
|
||||
const { ctx, app } = this;
|
||||
const cacheKey = `${WAVE_ORDER_COUNT_CACHE_KEY_PREFIX}:${warehouseId}:${waveId}`;
|
||||
|
||||
if (app && typeof app.getCacheAsync === 'function') {
|
||||
try {
|
||||
const cached = await app.getCacheAsync(cacheKey);
|
||||
if (cached !== null && cached !== undefined) {
|
||||
const parsed = Number(cached);
|
||||
if (Number.isFinite(parsed) && parsed >= 0) {
|
||||
return parsed;
|
||||
}
|
||||
}
|
||||
} catch (cacheReadErr) {
|
||||
ctx.logger.warn('[Workbench._countWaveOrdersCached] 读取缓存失败,降级为实时计数: %s', cacheReadErr.message);
|
||||
}
|
||||
}
|
||||
|
||||
const total = await this._countWaveOrders(warehouseId, waveId);
|
||||
|
||||
if (app && typeof app.setCacheAsync === 'function') {
|
||||
try {
|
||||
await app.setCacheAsync(cacheKey, total, WAVE_ORDER_COUNT_CACHE_TTL_SECONDS);
|
||||
} catch (cacheWriteErr) {
|
||||
ctx.logger.warn('[Workbench._countWaveOrdersCached] 写入缓存失败,不影响本次返回: %s', cacheWriteErr.message);
|
||||
}
|
||||
}
|
||||
|
||||
return total;
|
||||
}
|
||||
|
||||
@ -1257,8 +1308,11 @@ class WorkbenchService extends Service {
|
||||
|
||||
/**
|
||||
* 条码查订单:条码 → wms_order_express → 待处理/配送订单详情
|
||||
* 散单(isSandan=1)时在响应 order 对象中额外返回 intercept_flag / pack_flag 两个 0/1 标志:
|
||||
* 拦截状态(intercept_status)不等于 none 时 intercept_flag=1,否则 0;
|
||||
* 打包状态(pack_status)不等于 none 时 pack_flag=1,否则 0。
|
||||
* @param {Object} params - { barcode, warehouseId }
|
||||
* @returns {Promise<Object>}
|
||||
* @return {Promise<Object>} 查询结果 { barcode, waybill_code, isSandan, store_remark, express, order, items, source_table, batch? }
|
||||
*/
|
||||
async _queryOrder(params) {
|
||||
const { ctx } = this;
|
||||
@ -1357,11 +1411,12 @@ class WorkbenchService extends Service {
|
||||
// wave_type=1 → 团购单(isSandan=0); 其他(2=散单等) → 散单(isSandan=1)
|
||||
if (Number(waveType) === 1) {
|
||||
isSandan = 0;
|
||||
// 仅团购单组装波次总量:实时统计带短 TTL 缓存;
|
||||
// 散单不再触发分表 COUNT,避免 680ms+ 的无用扫描
|
||||
totalBatchOrders = await this._countWaveOrdersCached(warehouseId, waveId);
|
||||
} else {
|
||||
isSandan = 1;
|
||||
}
|
||||
// 实时统计波次订单数
|
||||
totalBatchOrders = await this._countWaveOrders(warehouseId, waveId);
|
||||
}
|
||||
} catch (waveErr) {
|
||||
ctx.logger.warn('[Workbench._queryOrder] 查询波次信息失败 waveId=%d: %s', waveId, waveErr.message);
|
||||
@ -1452,6 +1507,12 @@ class WorkbenchService extends Service {
|
||||
}
|
||||
}
|
||||
|
||||
// 步骤6:散单标志位计算(拦截/打包状态空值归一化为 none,非 none 记 1,否则 0)
|
||||
const normalizedInterceptStatus = String(orderRow.intercept_status || '').trim() || 'none';
|
||||
const normalizedPackStatus = String(orderRow.pack_status || '').trim() || 'none';
|
||||
const interceptFlag = normalizedInterceptStatus === 'none' ? 0 : 1;
|
||||
const packFlag = normalizedPackStatus === 'none' ? 0 : 1;
|
||||
|
||||
const result = {
|
||||
barcode: normalizedBarcode,
|
||||
waybill_code: waybillCode,
|
||||
@ -1475,6 +1536,7 @@ class WorkbenchService extends Service {
|
||||
post_status: orderRow.post_status,
|
||||
pick_status: orderRow.pick_status,
|
||||
pack_status: orderRow.pack_status,
|
||||
intercept_status: orderRow.intercept_status,
|
||||
recheck_status: orderRow.recheck_status,
|
||||
outbound_status: orderRow.outbound_status,
|
||||
items_count: orderRow.items_count,
|
||||
@ -1489,6 +1551,12 @@ class WorkbenchService extends Service {
|
||||
source_table: sourceTable,
|
||||
};
|
||||
|
||||
// 散单附加拦截/打包 0/1 标志(原始状态字段仍保留在 order 中,不破坏既有调用方)
|
||||
if (isSandan === 1) {
|
||||
result.order.intercept_flag = interceptFlag;
|
||||
result.order.pack_flag = packFlag;
|
||||
}
|
||||
|
||||
// 团购单附加波次总量信息
|
||||
if (isSandan === 0) {
|
||||
result.batch = {
|
||||
|
||||
@ -3,10 +3,21 @@
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
|
||||
/**
|
||||
* 判断值是否为普通对象(非数组、非 null)。
|
||||
* @param {*} value 待判断的值。
|
||||
* @return {boolean} 是普通对象返回 true。
|
||||
*/
|
||||
function isPlainObject(value) {
|
||||
return !!value && typeof value === 'object' && !Array.isArray(value);
|
||||
}
|
||||
|
||||
/**
|
||||
* 深合并两个普通对象,返回新对象,不修改入参。
|
||||
* @param {object} target 目标对象。
|
||||
* @param {object} source 来源对象。
|
||||
* @return {object} 合并后的新对象。
|
||||
*/
|
||||
function mergeDeep(target, source) {
|
||||
const output = isPlainObject(target) ? { ...target } : {};
|
||||
if (!isPlainObject(source)) {
|
||||
@ -26,6 +37,11 @@ function mergeDeep(target, source) {
|
||||
return output;
|
||||
}
|
||||
|
||||
/**
|
||||
* 加载 Egg 配置文件,兼容工厂函数与普通对象两种形式。
|
||||
* @param {string} configPath 配置文件绝对路径。
|
||||
* @return {object} 解析后的配置对象,文件不存在时返回空对象。
|
||||
*/
|
||||
function loadEggConfig(configPath) {
|
||||
if (!fs.existsSync(configPath)) {
|
||||
return {};
|
||||
@ -39,6 +55,13 @@ function loadEggConfig(configPath) {
|
||||
return isPlainObject(config) ? config : {};
|
||||
}
|
||||
|
||||
/**
|
||||
* 从 Egg 配置中解析指定名称的 MySQL 客户端。
|
||||
* @param {object} appConfig Egg 应用配置。
|
||||
* @param {string} clientName MySQL 客户端名称。
|
||||
* @return {object} 解析出的 MySQL 客户端连接配置。
|
||||
* @throws {Error} 找不到指定客户端时抛出异常。
|
||||
*/
|
||||
function resolveMysqlClient(appConfig, clientName) {
|
||||
const clients = appConfig && appConfig.mysql && appConfig.mysql.clients;
|
||||
if (clients && clients[clientName]) {
|
||||
@ -52,8 +75,62 @@ function resolveMysqlClient(appConfig, clientName) {
|
||||
throw new Error(`MySQL client "${clientName}" not found in Egg config.`);
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析数据库连接目标标记,防止 NODE_ENV 残留导致误连生产库。
|
||||
* 优先级:WMS_DB_TARGET(显式标记) > NODE_ENV(兜底判断)。
|
||||
* @param {string | undefined} envTarget 显式目标标记(WMS_DB_TARGET 环境变量值)。
|
||||
* @param {string | undefined} nodeEnv NODE_ENV 环境变量值。
|
||||
* @return {{ target: string, source: string, explicit: boolean }} 解析结果:target 为 'production' 或 'local',source 为判定来源,explicit 表示是否显式指定。
|
||||
*/
|
||||
function resolveDbTarget(envTarget, nodeEnv) {
|
||||
const explicit = String(envTarget || '').trim().toLowerCase();
|
||||
if (explicit === 'production' || explicit === 'prod') {
|
||||
return { target: 'production', source: 'WMS_DB_TARGET', explicit: true };
|
||||
}
|
||||
if (explicit === 'local' || explicit === 'dev' || explicit === 'development') {
|
||||
return { target: 'local', source: 'WMS_DB_TARGET', explicit: true };
|
||||
}
|
||||
if (explicit) {
|
||||
console.warn(`[DB-CONFIG] 未知的 WMS_DB_TARGET="${explicit}",已忽略并回退到 NODE_ENV 判断;可选值:local | production`);
|
||||
}
|
||||
|
||||
const nodeEnvLower = String(nodeEnv || '').trim().toLowerCase();
|
||||
return {
|
||||
target: nodeEnvLower === 'production' ? 'production' : 'local',
|
||||
source: nodeEnvLower === 'production' ? 'NODE_ENV' : 'default',
|
||||
explicit: false,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 打印数据库连接目标提示(输出到 stderr,避免污染 stdout 上的 JSON 结果)。
|
||||
* production 目标额外打印醒目告警,提醒操作者确认连接目标。
|
||||
* @param {{ host: string, port: (number|string), database: string }} client 解析后的 MySQL 连接配置。
|
||||
* @param {{ target: string, source: string }} resolved 目标解析结果。
|
||||
* @return {void}
|
||||
*/
|
||||
function printDbTargetNotice(client, resolved) {
|
||||
const detail = `host=${client.host} port=${client.port} database=${client.database} (判定来源: ${resolved.source})`;
|
||||
if (resolved.target === 'production') {
|
||||
console.warn('');
|
||||
console.warn('!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!');
|
||||
console.warn('[DB-CONFIG] ⚠ 警告:当前解析为【生产数据库】连接目标');
|
||||
console.warn(`[DB-CONFIG] ⚠ ${detail}`);
|
||||
console.warn('[DB-CONFIG] ⚠ 请确认这是预期环境;如属误判,请设置 WMS_DB_TARGET=local 强制使用开发库配置。');
|
||||
console.warn('!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!');
|
||||
console.warn('');
|
||||
} else {
|
||||
console.warn(`[DB-CONFIG] 数据库连接目标: ${detail}`);
|
||||
}
|
||||
}
|
||||
|
||||
const projectRoot = path.resolve(__dirname, '..');
|
||||
|
||||
// 解析连接目标:显式标记 WMS_DB_TARGET 优先于 NODE_ENV 兜底判断,
|
||||
// 避免终端残留 NODE_ENV=production 导致迁移/脚本误连生产库
|
||||
const dbTarget = resolveDbTarget(process.env.WMS_DB_TARGET, process.env.NODE_ENV);
|
||||
const isProductionTarget = dbTarget.target === 'production';
|
||||
|
||||
let mysqlClient;
|
||||
if (process.env.DB_HOST) {
|
||||
mysqlClient = {
|
||||
@ -63,13 +140,13 @@ if (process.env.DB_HOST) {
|
||||
password: process.env.DB_PASSWORD,
|
||||
database: process.env.DB_NAME || 'wms',
|
||||
};
|
||||
printDbTargetNotice(mysqlClient, { target: 'manual', source: 'DB_HOST' });
|
||||
} else {
|
||||
const defaultConfig = loadEggConfig(path.join(projectRoot, 'config', 'config.default.js'));
|
||||
const isProduction = process.env.NODE_ENV === 'production';
|
||||
const localConfig = isProduction ? {} : loadEggConfig(path.join(projectRoot, 'config', 'config.local.js'));
|
||||
const localConfig = isProductionTarget ? {} : loadEggConfig(path.join(projectRoot, 'config', 'config.local.js'));
|
||||
const appConfig = mergeDeep(defaultConfig, localConfig);
|
||||
const clientName = process.env.SEQUELIZE_DB_CLIENT || 'wms';
|
||||
if (isProduction) {
|
||||
if (isProductionTarget) {
|
||||
const sequelizeConfig = appConfig && appConfig.sequelize;
|
||||
if (sequelizeConfig && sequelizeConfig.host) {
|
||||
mysqlClient = {
|
||||
@ -85,6 +162,7 @@ if (process.env.DB_HOST) {
|
||||
} else {
|
||||
mysqlClient = resolveMysqlClient(appConfig, clientName);
|
||||
}
|
||||
printDbTargetNotice(mysqlClient, dbTarget);
|
||||
}
|
||||
|
||||
const baseConfig = {
|
||||
@ -108,4 +186,6 @@ module.exports = {
|
||||
development: { ...baseConfig },
|
||||
test: { ...baseConfig },
|
||||
production: { ...baseConfig },
|
||||
// 解析出的连接目标元信息,供迁移脚本等调用方做断言与提示(不影响 sequelize-cli 读取 env 配置)
|
||||
dbTarget,
|
||||
};
|
||||
|
||||
@ -0,0 +1,40 @@
|
||||
'use strict';
|
||||
|
||||
const TABLE = 'wms_entry_order';
|
||||
|
||||
/**
|
||||
* 入库单主表新增 is_virtual_inbound 字段:
|
||||
* 标记该入库单是否为虚拟入库(0=否,1=是)。
|
||||
* 快捷直入时,无绑定收货单的入库单为虚拟入库,有绑定收货单的为非虚拟入库。
|
||||
*/
|
||||
module.exports = {
|
||||
/**
|
||||
* 执行迁移:新增 is_virtual_inbound 字段。
|
||||
* @param {import('sequelize').QueryInterface} queryInterface 查询接口
|
||||
* @param {import('sequelize')} Sequelize Sequelize 实例
|
||||
* @return {Promise<void>} 无返回值
|
||||
*/
|
||||
up: async (queryInterface, Sequelize) => {
|
||||
const columns = await queryInterface.describeTable(TABLE);
|
||||
if (!columns.is_virtual_inbound) {
|
||||
await queryInterface.addColumn(TABLE, 'is_virtual_inbound', {
|
||||
type: Sequelize.TINYINT(1),
|
||||
allowNull: false,
|
||||
defaultValue: 0,
|
||||
comment: '是否虚拟入库:0=否 1=是',
|
||||
});
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* 回滚迁移:删除 is_virtual_inbound 字段。
|
||||
* @param {import('sequelize').QueryInterface} queryInterface 查询接口
|
||||
* @return {Promise<void>} 无返回值
|
||||
*/
|
||||
down: async queryInterface => {
|
||||
const columns = await queryInterface.describeTable(TABLE);
|
||||
if (columns.is_virtual_inbound) {
|
||||
await queryInterface.removeColumn(TABLE, 'is_virtual_inbound');
|
||||
}
|
||||
},
|
||||
};
|
||||
@ -0,0 +1,321 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 创建报表投递三表:报表模板定义 / 货主投递计划 / 投递记录。
|
||||
*
|
||||
* 背景:货主侧 7 日出入库报表采用「配置驱动 + 定时投递」方案:
|
||||
* 报表模板可配置上新(免发版),每个货主可配置每日多个投递时间点,
|
||||
* 由分钟级扫描调度命中后生成报表并按渠道投递。
|
||||
*
|
||||
* 三表职责:
|
||||
* - wms_report_definition:报表模板定义(code/name/scope + output/source/sheet 三段 JSON 配置)
|
||||
* - wms_report_delivery_plan:货主每日投递计划(schedule_times JSON 时间点数组)
|
||||
* - wms_report_delivery_log:投递记录(pending→exporting→delivered/failed/cancelled 状态机 + 退避重试)
|
||||
*
|
||||
* 约定:
|
||||
* - 逻辑关联、无物理外键(与项目现状一致)
|
||||
* - 唯一索引按项目惯例含 deleted_at,避免软删后重建撞唯一键
|
||||
* - 幂等键 uk_store_report_biz_time 保证同一货主同一报表同一数据日期同一时间点不重复投递
|
||||
*/
|
||||
|
||||
const TABLE_DEFINITION = 'wms_report_definition';
|
||||
const TABLE_PLAN = 'wms_report_delivery_plan';
|
||||
const TABLE_LOG = 'wms_report_delivery_log';
|
||||
|
||||
module.exports = {
|
||||
async up(queryInterface, Sequelize) {
|
||||
const { BIGINT, INTEGER, STRING, TINYINT, DATE, DATEONLY, ENUM } = Sequelize;
|
||||
const tables = await queryInterface.showAllTables();
|
||||
const tableNames = tables.map(t => (typeof t === 'string' ? t : t.tableName));
|
||||
|
||||
if (!tableNames.includes(TABLE_DEFINITION)) {
|
||||
await queryInterface.createTable(TABLE_DEFINITION, {
|
||||
id: {
|
||||
type: BIGINT(20).UNSIGNED,
|
||||
primaryKey: true,
|
||||
autoIncrement: true,
|
||||
allowNull: false,
|
||||
comment: '主键',
|
||||
},
|
||||
code: {
|
||||
type: STRING(100),
|
||||
allowNull: false,
|
||||
comment: '报表编码,全局唯一(如 week_inout_7d)',
|
||||
},
|
||||
name: {
|
||||
type: STRING(100),
|
||||
allowNull: false,
|
||||
comment: '报表名称',
|
||||
},
|
||||
scope: {
|
||||
type: ENUM('warehouse', 'store', 'open'),
|
||||
allowNull: false,
|
||||
defaultValue: 'warehouse',
|
||||
comment: '适用维度:warehouse=仓库 store=货主 open=通用',
|
||||
},
|
||||
description: {
|
||||
type: STRING(500),
|
||||
allowNull: true,
|
||||
comment: '报表描述',
|
||||
},
|
||||
output_config: {
|
||||
type: Sequelize.JSON,
|
||||
allowNull: true,
|
||||
comment: '输出配置(文件名/目录等)',
|
||||
},
|
||||
source_config: {
|
||||
type: Sequelize.JSON,
|
||||
allowNull: true,
|
||||
comment: '数据源配置(查询器 key + 窗口参数)',
|
||||
},
|
||||
sheet_config: {
|
||||
type: Sequelize.JSON,
|
||||
allowNull: true,
|
||||
comment: '工作表配置(列定义/合并/样式/行过滤/列级 format)',
|
||||
},
|
||||
is_enabled: {
|
||||
type: TINYINT(1),
|
||||
allowNull: false,
|
||||
defaultValue: 1,
|
||||
comment: '是否启用:0=停用 1=启用',
|
||||
},
|
||||
remark: {
|
||||
type: STRING(500),
|
||||
allowNull: true,
|
||||
comment: '备注',
|
||||
},
|
||||
created_at: {
|
||||
type: DATE,
|
||||
allowNull: false,
|
||||
defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'),
|
||||
comment: '创建时间',
|
||||
},
|
||||
updated_at: {
|
||||
type: DATE,
|
||||
allowNull: false,
|
||||
defaultValue: Sequelize.literal('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'),
|
||||
comment: '更新时间',
|
||||
},
|
||||
deleted_at: {
|
||||
type: DATE,
|
||||
allowNull: true,
|
||||
comment: '软删除时间',
|
||||
},
|
||||
}, {
|
||||
comment: '报表模板定义表',
|
||||
engine: 'InnoDB',
|
||||
charset: 'utf8mb4',
|
||||
collate: 'utf8mb4_general_ci',
|
||||
});
|
||||
|
||||
await queryInterface.addIndex(TABLE_DEFINITION, [ 'code', 'deleted_at' ], {
|
||||
unique: true,
|
||||
name: 'uk_code',
|
||||
});
|
||||
await queryInterface.addIndex(TABLE_DEFINITION, [ 'deleted_at' ], {
|
||||
name: 'idx_deleted_at',
|
||||
});
|
||||
}
|
||||
|
||||
if (!tableNames.includes(TABLE_PLAN)) {
|
||||
await queryInterface.createTable(TABLE_PLAN, {
|
||||
id: {
|
||||
type: BIGINT(20).UNSIGNED,
|
||||
primaryKey: true,
|
||||
autoIncrement: true,
|
||||
allowNull: false,
|
||||
comment: '主键',
|
||||
},
|
||||
store_id: {
|
||||
type: BIGINT(20).UNSIGNED,
|
||||
allowNull: false,
|
||||
comment: '货主ID(wms_store.id)',
|
||||
},
|
||||
report_code: {
|
||||
type: STRING(100),
|
||||
allowNull: false,
|
||||
comment: '报表编码(wms_report_definition.code)',
|
||||
},
|
||||
schedule_times: {
|
||||
type: Sequelize.JSON,
|
||||
allowNull: false,
|
||||
comment: '每日投递时间点数组,如 ["08:30","17:00"](HH:mm)',
|
||||
},
|
||||
channel: {
|
||||
type: STRING(20),
|
||||
allowNull: false,
|
||||
defaultValue: 'wecom',
|
||||
comment: '投递渠道:wecom=企业微信 inbox=站内信群 link=链接',
|
||||
},
|
||||
enabled: {
|
||||
type: TINYINT(1),
|
||||
allowNull: false,
|
||||
defaultValue: 1,
|
||||
comment: '是否启用:0=停用 1=启用',
|
||||
},
|
||||
late_grace_minutes: {
|
||||
type: INTEGER(11),
|
||||
allowNull: false,
|
||||
defaultValue: 60,
|
||||
comment: '补投宽限分钟:重启/漏跑后在该窗口内补投,超窗作废',
|
||||
},
|
||||
remark: {
|
||||
type: STRING(500),
|
||||
allowNull: true,
|
||||
comment: '备注',
|
||||
},
|
||||
created_at: {
|
||||
type: DATE,
|
||||
allowNull: false,
|
||||
defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'),
|
||||
comment: '创建时间',
|
||||
},
|
||||
updated_at: {
|
||||
type: DATE,
|
||||
allowNull: false,
|
||||
defaultValue: Sequelize.literal('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'),
|
||||
comment: '更新时间',
|
||||
},
|
||||
deleted_at: {
|
||||
type: DATE,
|
||||
allowNull: true,
|
||||
comment: '软删除时间',
|
||||
},
|
||||
}, {
|
||||
comment: '货主报表投递计划表',
|
||||
engine: 'InnoDB',
|
||||
charset: 'utf8mb4',
|
||||
collate: 'utf8mb4_general_ci',
|
||||
});
|
||||
|
||||
await queryInterface.addIndex(TABLE_PLAN, [ 'store_id', 'report_code', 'deleted_at' ], {
|
||||
unique: true,
|
||||
name: 'uk_store_report_code',
|
||||
});
|
||||
await queryInterface.addIndex(TABLE_PLAN, [ 'enabled', 'deleted_at' ], {
|
||||
name: 'idx_enabled_deleted',
|
||||
});
|
||||
await queryInterface.addIndex(TABLE_PLAN, [ 'deleted_at' ], {
|
||||
name: 'idx_deleted_at',
|
||||
});
|
||||
}
|
||||
|
||||
if (!tableNames.includes(TABLE_LOG)) {
|
||||
await queryInterface.createTable(TABLE_LOG, {
|
||||
id: {
|
||||
type: BIGINT(20).UNSIGNED,
|
||||
primaryKey: true,
|
||||
autoIncrement: true,
|
||||
allowNull: false,
|
||||
comment: '主键',
|
||||
},
|
||||
warehouse_id: {
|
||||
type: BIGINT(20).UNSIGNED,
|
||||
allowNull: false,
|
||||
defaultValue: 0,
|
||||
comment: '仓库ID(生成报表时注入的仓库维度)',
|
||||
},
|
||||
store_id: {
|
||||
type: BIGINT(20).UNSIGNED,
|
||||
allowNull: false,
|
||||
comment: '货主ID(wms_store.id)',
|
||||
},
|
||||
report_code: {
|
||||
type: STRING(100),
|
||||
allowNull: false,
|
||||
comment: '报表编码(wms_report_definition.code)',
|
||||
},
|
||||
biz_date: {
|
||||
type: DATEONLY,
|
||||
allowNull: false,
|
||||
comment: '数据日期(T-1 自然日)',
|
||||
},
|
||||
time_point: {
|
||||
type: STRING(5),
|
||||
allowNull: false,
|
||||
comment: '命中的投递时间点(HH:mm)',
|
||||
},
|
||||
status: {
|
||||
type: STRING(20),
|
||||
allowNull: false,
|
||||
defaultValue: 'pending',
|
||||
comment: '状态:pending/exporting/delivered/failed/cancelled',
|
||||
},
|
||||
channel: {
|
||||
type: STRING(20),
|
||||
allowNull: false,
|
||||
defaultValue: 'wecom',
|
||||
comment: '投递渠道快照:wecom=企业微信 inbox=站内信群 link=链接',
|
||||
},
|
||||
file_url: {
|
||||
type: STRING(500),
|
||||
allowNull: true,
|
||||
comment: '报表文件下载链接(COS 带有效期)',
|
||||
},
|
||||
retry_count: {
|
||||
type: INTEGER(3),
|
||||
allowNull: false,
|
||||
defaultValue: 0,
|
||||
comment: '重试次数',
|
||||
},
|
||||
next_retry_at: {
|
||||
type: DATE,
|
||||
allowNull: true,
|
||||
comment: '下次可投递时间(失败退避)',
|
||||
},
|
||||
error_message: {
|
||||
type: STRING(500),
|
||||
allowNull: true,
|
||||
comment: '最近一次失败原因',
|
||||
},
|
||||
delivered_at: {
|
||||
type: DATE,
|
||||
allowNull: true,
|
||||
comment: '投递成功时间',
|
||||
},
|
||||
created_at: {
|
||||
type: DATE,
|
||||
allowNull: false,
|
||||
defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'),
|
||||
comment: '创建时间',
|
||||
},
|
||||
updated_at: {
|
||||
type: DATE,
|
||||
allowNull: false,
|
||||
defaultValue: Sequelize.literal('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'),
|
||||
comment: '更新时间',
|
||||
},
|
||||
deleted_at: {
|
||||
type: DATE,
|
||||
allowNull: true,
|
||||
comment: '软删除时间',
|
||||
},
|
||||
}, {
|
||||
comment: '报表投递记录表',
|
||||
engine: 'InnoDB',
|
||||
charset: 'utf8mb4',
|
||||
collate: 'utf8mb4_general_ci',
|
||||
});
|
||||
|
||||
await queryInterface.addIndex(TABLE_LOG, [ 'store_id', 'report_code', 'biz_date', 'time_point', 'deleted_at' ], {
|
||||
unique: true,
|
||||
name: 'uk_store_report_biz_time',
|
||||
});
|
||||
await queryInterface.addIndex(TABLE_LOG, [ 'status', 'id' ], {
|
||||
name: 'idx_status_id',
|
||||
});
|
||||
await queryInterface.addIndex(TABLE_LOG, [ 'status', 'updated_at' ], {
|
||||
name: 'idx_status_updated_at',
|
||||
});
|
||||
await queryInterface.addIndex(TABLE_LOG, [ 'deleted_at' ], {
|
||||
name: 'idx_deleted_at',
|
||||
});
|
||||
}
|
||||
},
|
||||
|
||||
async down(queryInterface) {
|
||||
await queryInterface.dropTable(TABLE_LOG);
|
||||
await queryInterface.dropTable(TABLE_PLAN);
|
||||
await queryInterface.dropTable(TABLE_DEFINITION);
|
||||
},
|
||||
};
|
||||
@ -0,0 +1,77 @@
|
||||
'use strict';
|
||||
|
||||
const TABLE_PLAN = 'wms_report_delivery_plan';
|
||||
const TABLE_LOG = 'wms_report_delivery_log';
|
||||
|
||||
/**
|
||||
* 报表投递通知能力增强:
|
||||
* - wms_report_delivery_plan 新增 notify_template(文本通知模板)、
|
||||
* notify_group_ids(通知群ID数组)、notify_member_ids(通知成员ID数组)
|
||||
* - wms_report_delivery_log 新增 notify_targets(本次实际投递的群/成员快照,审计回放)
|
||||
*
|
||||
* 全部字段可空,不影响存量投递计划与投递记录。
|
||||
*/
|
||||
module.exports = {
|
||||
/**
|
||||
* 执行迁移:依次新增通知相关字段(幂等:已存在则跳过)。
|
||||
* @param {import('sequelize').QueryInterface} queryInterface 查询接口
|
||||
* @param {import('sequelize')} Sequelize Sequelize 实例
|
||||
* @return {Promise<void>} 无返回值
|
||||
*/
|
||||
up: async (queryInterface, Sequelize) => {
|
||||
const planColumns = await queryInterface.describeTable(TABLE_PLAN);
|
||||
if (!planColumns.notify_template) {
|
||||
await queryInterface.addColumn(TABLE_PLAN, 'notify_template', {
|
||||
type: Sequelize.STRING(500),
|
||||
allowNull: true,
|
||||
comment: '文本通知模板,支持 {time}/{url}/{report_name}/{biz_date} 标签',
|
||||
});
|
||||
}
|
||||
if (!planColumns.notify_group_ids) {
|
||||
await queryInterface.addColumn(TABLE_PLAN, 'notify_group_ids', {
|
||||
type: Sequelize.JSON,
|
||||
allowNull: true,
|
||||
comment: '通知群ID数组(wms_inbox_group.id,多选;空=不指定群)',
|
||||
});
|
||||
}
|
||||
if (!planColumns.notify_member_ids) {
|
||||
await queryInterface.addColumn(TABLE_PLAN, 'notify_member_ids', {
|
||||
type: Sequelize.JSON,
|
||||
allowNull: true,
|
||||
comment: '通知成员ID数组(外部IM用户ID,多选;目标侧支持数组)',
|
||||
});
|
||||
}
|
||||
|
||||
const logColumns = await queryInterface.describeTable(TABLE_LOG);
|
||||
if (!logColumns.notify_targets) {
|
||||
await queryInterface.addColumn(TABLE_LOG, 'notify_targets', {
|
||||
type: Sequelize.JSON,
|
||||
allowNull: true,
|
||||
comment: '投递目标快照:{group_ids:[],member_ids:[]}(本次实际发送的群/成员,审计回放)',
|
||||
});
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* 回滚迁移:按新增顺序的逆序删除字段(幂等:不存在则跳过)。
|
||||
* @param {import('sequelize').QueryInterface} queryInterface 查询接口
|
||||
* @return {Promise<void>} 无返回值
|
||||
*/
|
||||
down: async queryInterface => {
|
||||
const planColumns = await queryInterface.describeTable(TABLE_PLAN);
|
||||
if (planColumns.notify_member_ids) {
|
||||
await queryInterface.removeColumn(TABLE_PLAN, 'notify_member_ids');
|
||||
}
|
||||
if (planColumns.notify_group_ids) {
|
||||
await queryInterface.removeColumn(TABLE_PLAN, 'notify_group_ids');
|
||||
}
|
||||
if (planColumns.notify_template) {
|
||||
await queryInterface.removeColumn(TABLE_PLAN, 'notify_template');
|
||||
}
|
||||
|
||||
const logColumns = await queryInterface.describeTable(TABLE_LOG);
|
||||
if (logColumns.notify_targets) {
|
||||
await queryInterface.removeColumn(TABLE_LOG, 'notify_targets');
|
||||
}
|
||||
},
|
||||
};
|
||||
@ -0,0 +1,55 @@
|
||||
'use strict';
|
||||
|
||||
const TABLE_PLAN = 'wms_report_delivery_plan';
|
||||
const TABLE_LOG = 'wms_report_delivery_log';
|
||||
|
||||
/**
|
||||
* 报表投递渠道收敛为 inbox(wecom/link 已弃用)。
|
||||
*
|
||||
* - wms_report_delivery_plan.channel:默认值 wecom → inbox,comment 收敛
|
||||
* - wms_report_delivery_log.channel:默认值 wecom → inbox,comment 收敛
|
||||
* - 存量数据归一化:channel IN ('wecom','link') 的行统一更新为 'inbox'
|
||||
*
|
||||
* down 仅回退列默认值与 comment;数据 UPDATE 不回退(历史行无法还原原渠道)。
|
||||
*/
|
||||
module.exports = {
|
||||
async up(queryInterface, Sequelize) {
|
||||
// 1. 计划表:默认值 + comment 收敛
|
||||
await queryInterface.changeColumn(TABLE_PLAN, 'channel', {
|
||||
type: Sequelize.STRING(20),
|
||||
allowNull: false,
|
||||
defaultValue: 'inbox',
|
||||
comment: '投递渠道:inbox=站内信群(wecom/link 已弃用)',
|
||||
});
|
||||
await queryInterface.sequelize.query(
|
||||
`UPDATE ${TABLE_PLAN} SET channel = 'inbox' WHERE channel IN ('wecom', 'link')`
|
||||
);
|
||||
|
||||
// 2. 记录表:默认值 + comment 收敛
|
||||
await queryInterface.changeColumn(TABLE_LOG, 'channel', {
|
||||
type: Sequelize.STRING(20),
|
||||
allowNull: false,
|
||||
defaultValue: 'inbox',
|
||||
comment: '投递渠道快照:inbox=站内信群(wecom/link 已弃用)',
|
||||
});
|
||||
await queryInterface.sequelize.query(
|
||||
`UPDATE ${TABLE_LOG} SET channel = 'inbox' WHERE channel IN ('wecom', 'link')`
|
||||
);
|
||||
},
|
||||
|
||||
async down(queryInterface, Sequelize) {
|
||||
// 仅回退默认值与 comment;存量数据不回退(已归一化为 inbox 的行无法还原原渠道)
|
||||
await queryInterface.changeColumn(TABLE_PLAN, 'channel', {
|
||||
type: Sequelize.STRING(20),
|
||||
allowNull: false,
|
||||
defaultValue: 'wecom',
|
||||
comment: '投递渠道:wecom=企业微信 inbox=站内信群 link=链接',
|
||||
});
|
||||
await queryInterface.changeColumn(TABLE_LOG, 'channel', {
|
||||
type: Sequelize.STRING(20),
|
||||
allowNull: false,
|
||||
defaultValue: 'wecom',
|
||||
comment: '投递渠道快照:wecom=企业微信 inbox=站内信群 link=链接',
|
||||
});
|
||||
},
|
||||
};
|
||||
@ -0,0 +1,121 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 为群选择 / 群成员选择下拉接口创建 API 权限记录并授权。
|
||||
*
|
||||
* 权限明细(固定 ID,当前迁移内 max_id=565):
|
||||
* 566 — inbox.group.quickList API:群快速查询
|
||||
* 567 — inbox.group.members API:群成员列表
|
||||
*
|
||||
* 角色授权(客服组-主管及以上):
|
||||
* 26(仓库组-主管) → 28(客服组-主管) → 29(生产组-主管) → 8(经理)
|
||||
* 超级管理员(7)/仓库管理员(2) 已持有 * 通配符,自动拥有,无需处理
|
||||
*
|
||||
* 幂等:INSERT IGNORE 创建权限记录;角色权限数组追加后去重排序,已存在跳过。
|
||||
*/
|
||||
|
||||
const TABLE = 'wms_permission';
|
||||
const ROLE_TABLE = 'wms_role';
|
||||
const COLUMNS = 'id, path, component, name, redirect, meta_title, meta_icon, hidden, always_show, parent_id, type, sort, status, created_at, update_at';
|
||||
|
||||
/** 权限ID → 授权角色ID列表(不含通配符角色) */
|
||||
const PERMISSION_ROLES = {
|
||||
566: [ 26, 28, 29, 8 ],
|
||||
567: [ 26, 28, 29, 8 ],
|
||||
};
|
||||
|
||||
module.exports = {
|
||||
// eslint-disable-next-line no-unused-vars
|
||||
async up(queryInterface, Sequelize) {
|
||||
// ── 1. 创建 API 权限记录(固定 ID)──
|
||||
const apis = [
|
||||
[ 566, 'inbox.group.quickList', 'API:群快速查询' ],
|
||||
[ 567, 'inbox.group.members', 'API:群成员列表' ],
|
||||
];
|
||||
|
||||
for (const [ id, path, metaTitle ] of apis) {
|
||||
await queryInterface.sequelize.query(
|
||||
`INSERT IGNORE INTO \`${TABLE}\` (${COLUMNS}) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW())`,
|
||||
{ replacements: [ id, path, null, path, null, metaTitle, null, 0, 0, null, 'api', 0, 1 ] }
|
||||
);
|
||||
}
|
||||
|
||||
// ── 2. 角色授权注入 ──
|
||||
for (const permId of Object.keys(PERMISSION_ROLES).map(Number)) {
|
||||
for (const roleId of PERMISSION_ROLES[permId]) {
|
||||
const rows = await queryInterface.sequelize.query(
|
||||
`SELECT id, permissions FROM \`${ROLE_TABLE}\` WHERE id = ?`,
|
||||
{ replacements: [ roleId ], type: queryInterface.sequelize.QueryTypes.SELECT }
|
||||
);
|
||||
const record = Array.isArray(rows) ? rows[0] : null;
|
||||
if (!record) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// 通配符角色跳过
|
||||
if (record.permissions === '*') {
|
||||
continue;
|
||||
}
|
||||
|
||||
let perms;
|
||||
try {
|
||||
perms = typeof record.permissions === 'string'
|
||||
? JSON.parse(record.permissions)
|
||||
: record.permissions;
|
||||
} catch (e) {
|
||||
perms = null;
|
||||
}
|
||||
|
||||
if (!Array.isArray(perms)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!perms.includes(permId)) {
|
||||
perms.push(permId);
|
||||
perms.sort((a, b) => Number(a) - Number(b));
|
||||
await queryInterface.sequelize.query(
|
||||
`UPDATE \`${ROLE_TABLE}\` SET permissions = ? WHERE id = ?`,
|
||||
{ replacements: [ JSON.stringify(perms), roleId ] }
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
// eslint-disable-next-line no-unused-vars
|
||||
async down(queryInterface, Sequelize) {
|
||||
await queryInterface.sequelize.query(
|
||||
'DELETE FROM `wms_permission` WHERE id IN (566, 567)'
|
||||
);
|
||||
|
||||
const permIds = [ 566, 567 ];
|
||||
for (const roleId of Object.values(PERMISSION_ROLES).flat()) {
|
||||
const rows = await queryInterface.sequelize.query(
|
||||
`SELECT id, permissions FROM \`${ROLE_TABLE}\` WHERE id = ?`,
|
||||
{ replacements: [ roleId ], type: queryInterface.sequelize.QueryTypes.SELECT }
|
||||
);
|
||||
const record = Array.isArray(rows) ? rows[0] : null;
|
||||
if (!record || record.permissions === '*') {
|
||||
continue;
|
||||
}
|
||||
|
||||
let perms;
|
||||
try {
|
||||
perms = typeof record.permissions === 'string'
|
||||
? JSON.parse(record.permissions)
|
||||
: record.permissions;
|
||||
} catch (e) {
|
||||
perms = null;
|
||||
}
|
||||
if (!Array.isArray(perms) || !perms.some(p => permIds.includes(p))) {
|
||||
continue;
|
||||
}
|
||||
|
||||
perms = perms.filter(p => !permIds.includes(p));
|
||||
await queryInterface.sequelize.query(
|
||||
`UPDATE \`${ROLE_TABLE}\` SET permissions = ? WHERE id = ?`,
|
||||
{ replacements: [ JSON.stringify(perms), roleId ] }
|
||||
);
|
||||
}
|
||||
},
|
||||
};
|
||||
@ -0,0 +1,133 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* queryOrder 波次计数性能优化:为 current/dispatch 分表增加 wave_id 前导索引。
|
||||
*
|
||||
* 背景:
|
||||
* - app/service/systems/workbench.js 的 _countWaveOrders 会对 current + dispatch 两族分表执行
|
||||
* `SELECT COUNT(*) FROM ... WHERE wave_id=? AND warehouse_id=?`;
|
||||
* - 现有索引 `idx_{wh}_current_wave` 为 (status, wave_id),前导列 status 不在谓词中,
|
||||
* 生产 dispatch 分表(约 25.38 万行 / 524MB)需全表扫描约 12.69 万行;
|
||||
* - 本迁移动态枚举 `wms_order_delivery_{wh}` 与 `wms_order_delivery_{wh}_dispatch`,
|
||||
* 为每张分表新增二级索引 `idx_{wh}_current_wave_id (wave_id)`。
|
||||
*
|
||||
* 设计说明:
|
||||
* - 分表按仓库隔离,warehouse_id 在单张分表内为常量,索引无需包含 warehouse_id;
|
||||
* - 使用 ALGORITHM=INPLACE, LOCK=NONE(MySQL 5.6+ 支持在线加二级索引),
|
||||
* 不重建表、不锁写,适合低峰期执行;
|
||||
* - 幂等:索引已存在则跳过;索引命名与 app/model/order_delivery_table_schema.js
|
||||
* 的 buildIndexOptions 即将补充的定义一致,避免应用运行时 drift 同步重复建索引。
|
||||
*
|
||||
* ⚠️ 本文件为「未执行」草案,仅在用户完成风险确认后,通过迁移流程执行。
|
||||
*/
|
||||
|
||||
const SHARD_PATTERNS = [
|
||||
{ type: 'current', pattern: /^wms_order_delivery_(\d+)$/ },
|
||||
{ type: 'dispatch', pattern: /^wms_order_delivery_(\d+)_dispatch$/ },
|
||||
];
|
||||
|
||||
/**
|
||||
* 解析分表名。
|
||||
* @param {string} tableName 表名。
|
||||
* @return {{ type: string, warehouseId: string }|null} 解析结果。
|
||||
*/
|
||||
function parseShardTableName(tableName) {
|
||||
for (const item of SHARD_PATTERNS) {
|
||||
const match = item.pattern.exec(tableName);
|
||||
if (match) {
|
||||
return { type: item.type, warehouseId: match[1] };
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 构建 wave_id 前导索引名(与 buildIndexOptions 命名一致)。
|
||||
* @param {string} warehouseId 仓库ID。
|
||||
* @return {string} 索引名。
|
||||
*/
|
||||
function buildWaveIdIndexName(warehouseId) {
|
||||
return `idx_${warehouseId}_current_wave_id`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 列举库内所有 current/dispatch 分表。
|
||||
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
|
||||
* @return {Promise<Array<string>>} 分表名列表。
|
||||
*/
|
||||
async function listManagedShards(queryInterface) {
|
||||
const [ rows ] = await queryInterface.sequelize.query(
|
||||
'SELECT TABLE_NAME AS tableName FROM INFORMATION_SCHEMA.TABLES '
|
||||
+ 'WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME LIKE \'wms_order_delivery\\_%\' '
|
||||
+ 'ORDER BY TABLE_NAME'
|
||||
);
|
||||
return (rows || [])
|
||||
.map(row => String(row.tableName || row.TABLE_NAME || ''))
|
||||
.filter(name => parseShardTableName(name));
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断索引是否已存在。
|
||||
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
|
||||
* @param {string} tableName 表名。
|
||||
* @param {string} indexName 索引名。
|
||||
* @return {Promise<boolean>} 是否存在。
|
||||
*/
|
||||
async function indexExists(queryInterface, tableName, indexName) {
|
||||
const indexes = await queryInterface.showIndex(tableName);
|
||||
return (indexes || []).some(index => {
|
||||
const name = String(index && (index.name || index.Key_name || index.key_name) || '');
|
||||
return name.toLowerCase() === String(indexName).toLowerCase();
|
||||
});
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
/**
|
||||
* 执行迁移:为 current/dispatch 分表增加 wave_id 前导索引。
|
||||
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
|
||||
* @return {Promise<void>} 无返回值。
|
||||
*/
|
||||
async up(queryInterface) {
|
||||
const shards = await listManagedShards(queryInterface);
|
||||
const results = [];
|
||||
|
||||
for (const tableName of shards) {
|
||||
const parsed = parseShardTableName(tableName);
|
||||
const indexName = buildWaveIdIndexName(parsed.warehouseId);
|
||||
|
||||
if (await indexExists(queryInterface, tableName, indexName)) {
|
||||
results.push({ tableName, action: 'skip', reason: 'exists' });
|
||||
continue;
|
||||
}
|
||||
|
||||
await queryInterface.sequelize.query(
|
||||
`ALTER TABLE \`${tableName}\` ADD INDEX \`${indexName}\` (\`wave_id\`), ALGORITHM=INPLACE, LOCK=NONE`
|
||||
);
|
||||
results.push({ tableName, action: 'added', indexName });
|
||||
}
|
||||
|
||||
console.log('[20260830100000-add-wave-id-index] up results:', JSON.stringify(results));
|
||||
},
|
||||
|
||||
/**
|
||||
* 回滚迁移:移除 wave_id 前导索引。
|
||||
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
|
||||
* @return {Promise<void>} 无返回值。
|
||||
*/
|
||||
async down(queryInterface) {
|
||||
const shards = await listManagedShards(queryInterface);
|
||||
|
||||
for (const tableName of shards) {
|
||||
const parsed = parseShardTableName(tableName);
|
||||
const indexName = buildWaveIdIndexName(parsed.warehouseId);
|
||||
|
||||
if (!(await indexExists(queryInterface, tableName, indexName))) {
|
||||
continue;
|
||||
}
|
||||
|
||||
await queryInterface.sequelize.query(
|
||||
`ALTER TABLE \`${tableName}\` DROP INDEX \`${indexName}\`, ALGORITHM=INPLACE, LOCK=NONE`
|
||||
);
|
||||
}
|
||||
},
|
||||
};
|
||||
@ -0,0 +1,166 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 报表定义模型重构:code 关联 → 主键 id 关联。
|
||||
*
|
||||
* 背景:报表定义模型已重构(definition 以主键 id 唯一,删除 code/scope/description
|
||||
* 及 output_config/source_config/sheet_config 三个 JSON 配置列,新增 type/file_name/fields;
|
||||
* plan/log 改用 report_definition_id 关联定义),本迁移同步数据库结构。
|
||||
*
|
||||
* 三步改造:
|
||||
* 1. wms_report_definition:删 uk_code,加 type/file_name/fields 三列,回填 id=1
|
||||
* 存量数据,物理删除已软删的 e2e 演示行(id=2),删除 code/scope/description
|
||||
* 及三个 JSON 配置列,最后去掉 type 默认值(新配置必须显式声明类型);
|
||||
* 2. wms_report_delivery_plan:加 report_definition_id 并回填,唯一键
|
||||
* uk_store_report_code → uk_store_report_definition;
|
||||
* 3. wms_report_delivery_log:加 report_definition_id/report_name 并回填,
|
||||
* 唯一键 uk_store_report_biz_time 改为基于 report_definition_id。
|
||||
*
|
||||
* 执行顺序说明(关键约束):plan/log 的回填依赖 definition.code 关联
|
||||
* (JOIN ... ON d.code = p.report_code),因此 definition 旧列(含 code)的删除
|
||||
* 被延后到 plan/log 回填核验通过之后执行,最终表结构与规格逐项一致。
|
||||
*
|
||||
* down 不可逆:旧列及其数据已被物理删除,无法从库内还原,故 down 直接抛错,
|
||||
* 如需回退请从备份恢复。
|
||||
*/
|
||||
|
||||
const TABLE_DEFINITION = 'wms_report_definition';
|
||||
const TABLE_PLAN = 'wms_report_delivery_plan';
|
||||
const TABLE_LOG = 'wms_report_delivery_log';
|
||||
|
||||
// id=1 存量报表勾选字段 key 数组(与代码侧 stockFlow 查询器字段规格一致)
|
||||
const STOCK_FLOW_FIELDS = [
|
||||
'item_code', 'item_name', 'barcode', 'daily', 'ck_total', 'rk_total', 'available',
|
||||
'total', 'pending', 'locked', 'ck_avg', 'rk_avg', 'stock_days', 'suggest', 'warn',
|
||||
];
|
||||
|
||||
module.exports = {
|
||||
async up(queryInterface) {
|
||||
const { sequelize } = queryInterface;
|
||||
const q = sql => sequelize.query(sql);
|
||||
const log = msg => console.log(`[report-definition-by-id] ${msg}`);
|
||||
|
||||
/**
|
||||
* 执行计数校验 SQL,返回行数;不满足期望时抛错,阻止后续破坏性 DDL。
|
||||
* @param {string} sql 返回 cnt 列的 SELECT COUNT 语句。
|
||||
* @param {number} expected 期望的行数。
|
||||
* @param {string} message 校验失败时的错误描述。
|
||||
*/
|
||||
const assertCount = async (sql, expected, message) => {
|
||||
const [ rows ] = await q(sql);
|
||||
const count = Number(rows[0].cnt);
|
||||
console.log(`[report-definition-by-id] 核验:${message}(实际 ${count},期望 ${expected})`);
|
||||
if (count !== expected) {
|
||||
throw new Error(`[report-definition-by-id] ${message} 核验失败:实际 ${count},期望 ${expected}`);
|
||||
}
|
||||
};
|
||||
|
||||
// ============ Step 1(前半):wms_report_definition 结构准备 ============
|
||||
// 1.1 删除 uk_code 唯一索引(code 即将废弃)
|
||||
await queryInterface.removeIndex(TABLE_DEFINITION, 'uk_code');
|
||||
log('definition:已删除唯一索引 uk_code');
|
||||
|
||||
// 1.2 新增 type / file_name / fields 三列(按规格顺序放在 name 之后)
|
||||
await q(`ALTER TABLE \`${TABLE_DEFINITION}\`
|
||||
ADD COLUMN \`type\` VARCHAR(50) NOT NULL DEFAULT 'stockFlow' COMMENT '报表类型(内置查询器注册 key)' AFTER \`name\`,
|
||||
ADD COLUMN \`file_name\` VARCHAR(200) NOT NULL DEFAULT '' COMMENT '导出文件名模板(支持 {date} 占位)' AFTER \`type\`,
|
||||
ADD COLUMN \`fields\` JSON NULL COMMENT '勾选字段 key 数组' AFTER \`file_name\``);
|
||||
log('definition:已新增 type/file_name/fields 三列');
|
||||
|
||||
// 1.3 回填 id=1 存量数据(7日出入库报表)
|
||||
await q(`UPDATE \`${TABLE_DEFINITION}\` SET
|
||||
\`type\` = 'stockFlow',
|
||||
\`file_name\` = '7日出入库_{date}',
|
||||
\`fields\` = JSON_ARRAY(${STOCK_FLOW_FIELDS.map(f => `'${f}'`).join(', ')})
|
||||
WHERE \`id\` = 1`);
|
||||
log('definition:已回填 id=1 的 type/file_name/fields');
|
||||
|
||||
// 1.4 物理删除已软删的 e2e 演示行(id=2)
|
||||
await q(`DELETE FROM \`${TABLE_DEFINITION}\`
|
||||
WHERE \`id\` = 2 AND \`deleted_at\` IS NOT NULL AND \`code\` = 'e2e_demo_report'`);
|
||||
log('definition:已删除软删状态下的 e2e 演示行(id=2)');
|
||||
|
||||
// ============ Step 2:wms_report_delivery_plan 改 id 关联 ============
|
||||
// 2.1 新增 report_definition_id(按规格顺序放在 store_id 之后)
|
||||
await q(`ALTER TABLE \`${TABLE_PLAN}\`
|
||||
ADD COLUMN \`report_definition_id\` BIGINT(20) UNSIGNED NOT NULL DEFAULT 0
|
||||
COMMENT '报表定义ID(wms_report_definition.id)' AFTER \`store_id\``);
|
||||
log('plan:已新增 report_definition_id');
|
||||
|
||||
// 2.2 按 code 关联回填(必须在 definition.code 删除前完成)
|
||||
await q(`UPDATE \`${TABLE_PLAN}\` p
|
||||
JOIN \`${TABLE_DEFINITION}\` d ON d.\`code\` = p.\`report_code\`
|
||||
SET p.\`report_definition_id\` = d.\`id\``);
|
||||
log('plan:已按 code 关联回填 report_definition_id');
|
||||
|
||||
// 2.3 核验:report_definition_id=0 的行数必须为 0,否则抛出异常
|
||||
await assertCount(
|
||||
`SELECT COUNT(*) AS cnt FROM \`${TABLE_PLAN}\` WHERE \`report_definition_id\` = 0`,
|
||||
0,
|
||||
'plan 回填后 report_definition_id=0 的行数必须为 0'
|
||||
);
|
||||
|
||||
// 2.4 删除旧唯一键与 report_code,建立新唯一键
|
||||
await queryInterface.removeIndex(TABLE_PLAN, 'uk_store_report_code');
|
||||
await q(`ALTER TABLE \`${TABLE_PLAN}\` DROP COLUMN \`report_code\``);
|
||||
await q(`ALTER TABLE \`${TABLE_PLAN}\`
|
||||
ADD UNIQUE INDEX \`uk_store_report_definition\` (\`store_id\`, \`report_definition_id\`, \`deleted_at\`)`);
|
||||
log('plan:已切换唯一键 uk_store_report_definition 并删除 report_code');
|
||||
|
||||
// ============ Step 3:wms_report_delivery_log 改 id 关联 ============
|
||||
// 3.1 新增 report_definition_id / report_name(按规格顺序放在 store_id 之后)
|
||||
await q(`ALTER TABLE \`${TABLE_LOG}\`
|
||||
ADD COLUMN \`report_definition_id\` BIGINT(20) UNSIGNED NOT NULL DEFAULT 0
|
||||
COMMENT '报表定义ID(wms_report_definition.id)' AFTER \`store_id\`,
|
||||
ADD COLUMN \`report_name\` VARCHAR(100) NULL
|
||||
COMMENT '报表名称快照(投递时定义 name)' AFTER \`report_definition_id\``);
|
||||
log('log:已新增 report_definition_id/report_name');
|
||||
|
||||
// 3.2 按 code 关联回填(必须在 definition.code 删除前完成)
|
||||
await q(`UPDATE \`${TABLE_LOG}\` l
|
||||
JOIN \`${TABLE_DEFINITION}\` d ON d.\`code\` = l.\`report_code\`
|
||||
SET l.\`report_definition_id\` = d.\`id\`, l.\`report_name\` = d.\`name\``);
|
||||
log('log:已按 code 关联回填 report_definition_id/report_name');
|
||||
|
||||
// 3.3 核验:report_definition_id=0 的行数必须为 0,否则抛出异常
|
||||
await assertCount(
|
||||
`SELECT COUNT(*) AS cnt FROM \`${TABLE_LOG}\` WHERE \`report_definition_id\` = 0`,
|
||||
0,
|
||||
'log 回填后 report_definition_id=0 的行数必须为 0'
|
||||
);
|
||||
|
||||
// 3.4 删除旧唯一键与 report_code,建立新唯一键
|
||||
await queryInterface.removeIndex(TABLE_LOG, 'uk_store_report_biz_time');
|
||||
await q(`ALTER TABLE \`${TABLE_LOG}\` DROP COLUMN \`report_code\``);
|
||||
await q(`ALTER TABLE \`${TABLE_LOG}\`
|
||||
ADD UNIQUE INDEX \`uk_store_report_biz_time\`
|
||||
(\`store_id\`, \`report_definition_id\`, \`biz_date\`, \`time_point\`, \`deleted_at\`)`);
|
||||
log('log:已切换唯一键 uk_store_report_biz_time 并删除 report_code');
|
||||
|
||||
// ============ Step 1(后半):删除 definition 旧列并收尾 ============
|
||||
// plan/log 回填已核验通过,此时删除 definition 旧列(含 code)是安全的
|
||||
await q(`ALTER TABLE \`${TABLE_DEFINITION}\`
|
||||
DROP COLUMN \`code\`,
|
||||
DROP COLUMN \`scope\`,
|
||||
DROP COLUMN \`description\`,
|
||||
DROP COLUMN \`output_config\`,
|
||||
DROP COLUMN \`source_config\`,
|
||||
DROP COLUMN \`sheet_config\``);
|
||||
log('definition:已删除 code/scope/description 及三个 JSON 配置列');
|
||||
|
||||
// 去掉 type 默认值:新配置行必须显式声明报表类型
|
||||
await q(`ALTER TABLE \`${TABLE_DEFINITION}\` ALTER COLUMN \`type\` DROP DEFAULT`);
|
||||
log('definition:已去掉 type 默认值');
|
||||
|
||||
log('全部完成');
|
||||
},
|
||||
|
||||
async down() {
|
||||
// 本迁移破坏性删除旧列数据(code/scope/description 及三个 JSON 配置列、
|
||||
// e2e 演示行、plan/log 的 report_code 列),库内已无原始数据可还原,不可自动回滚。
|
||||
throw new Error(
|
||||
'[report-definition-by-id] 本迁移不可逆:definition 旧列及其数据、e2e 演示行、plan/log 的 report_code 列已被删除,'
|
||||
+ '库内无法还原原始数据。如需回退,请从备份恢复数据库或手工重建相关列与数据。'
|
||||
);
|
||||
},
|
||||
};
|
||||
@ -0,0 +1,56 @@
|
||||
'use strict';
|
||||
|
||||
const TABLE_PLAN = 'wms_report_delivery_plan';
|
||||
|
||||
/**
|
||||
* 为报表投递计划表新增计划名称字段 name。
|
||||
*
|
||||
* 背景:报表投递计划在管理端列表/详情展示时需要展示计划名称(前端展示用),
|
||||
* 因此为 wms_report_delivery_plan 新增 name 列,按规格位于 report_definition_id 之后。
|
||||
*
|
||||
* 全部存量计划允许 name 为空(可空列),不影响既有投递计划与投递逻辑。
|
||||
*/
|
||||
module.exports = {
|
||||
/**
|
||||
* 执行迁移:新增 name 列(幂等:已存在则跳过)。
|
||||
*
|
||||
* 说明:sequelize 的 addColumn 不支持指定列位置(AFTER),
|
||||
* 为满足「位于 report_definition_id 之后」的规格要求,
|
||||
* 使用原生 DDL 控制列位置,与项目既有迁移
|
||||
* (restructure-report-definition-by-id)的做法一致。
|
||||
*
|
||||
* @param {import('sequelize').QueryInterface} queryInterface 查询接口
|
||||
* @return {Promise<void>} 无返回值
|
||||
*/
|
||||
async up(queryInterface) {
|
||||
const { sequelize } = queryInterface;
|
||||
const columns = await queryInterface.describeTable(TABLE_PLAN);
|
||||
|
||||
// 幂等保护:已存在 name 列时跳过
|
||||
if (columns.name) {
|
||||
return;
|
||||
}
|
||||
|
||||
await sequelize.query(
|
||||
`ALTER TABLE \`${TABLE_PLAN}\`
|
||||
ADD COLUMN \`name\` VARCHAR(100) NULL COMMENT '计划名称(前端展示用)'
|
||||
AFTER \`report_definition_id\``
|
||||
);
|
||||
},
|
||||
|
||||
/**
|
||||
* 回滚迁移:删除 name 列(幂等:不存在则跳过)。
|
||||
* @param {import('sequelize').QueryInterface} queryInterface 查询接口
|
||||
* @return {Promise<void>} 无返回值
|
||||
*/
|
||||
async down(queryInterface) {
|
||||
const columns = await queryInterface.describeTable(TABLE_PLAN);
|
||||
|
||||
// 幂等保护:不存在 name 列时跳过
|
||||
if (!columns.name) {
|
||||
return;
|
||||
}
|
||||
|
||||
await queryInterface.removeColumn(TABLE_PLAN, 'name');
|
||||
},
|
||||
};
|
||||
@ -0,0 +1,59 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 为站内信群表补充货主维度查询索引。
|
||||
*
|
||||
* 背景:inbox.group.quickList 接口支持双维度过滤:
|
||||
* - store_id(货主维度)→ wms_inbox_group.store_id 列
|
||||
* - warehouse_id(仓库维度)→ wms_inbox_group.warehouse_id 列
|
||||
* 两者可单独或同时(AND)过滤。store_id 列此前无索引,
|
||||
* 单独按货主过滤或与仓库 AND 过滤时会走全表扫描。
|
||||
*
|
||||
* wms_inbox_group:
|
||||
* - idx_store_id: (store_id)
|
||||
* 用于按货主维度过滤群列表。warehouse_id 维度已由唯一索引
|
||||
* uk_warehouse_group_id(warehouse_id, group_id) 的前导列覆盖,无需新增仓库单列索引;
|
||||
* 双条件 AND 场景由 idx_store_id 与 uk_warehouse_group_id 组合命中,
|
||||
* 群表数据量小,单列索引已足够,不引入复合索引以控制索引维护成本。
|
||||
*/
|
||||
|
||||
const TABLE_NAME = 'wms_inbox_group';
|
||||
const INDEX_NAME = 'idx_store_id';
|
||||
|
||||
async function indexExists(queryInterface, tableName, indexName) {
|
||||
const indexes = await queryInterface.showIndex(tableName);
|
||||
return (indexes || []).some(i => (typeof i === 'string' ? i : i.name) === indexName);
|
||||
}
|
||||
|
||||
async function addIndexIfNotExists(queryInterface, tableName, indexName, options = {}) {
|
||||
if (await indexExists(queryInterface, tableName, indexName)) {
|
||||
console.log(`[idx] ${tableName}.${indexName} 已存在,跳过`);
|
||||
return;
|
||||
}
|
||||
await queryInterface.addIndex(tableName, options.fields, {
|
||||
name: indexName,
|
||||
unique: !!options.unique,
|
||||
});
|
||||
console.log(`[idx] ${tableName}.${indexName} 已创建`);
|
||||
}
|
||||
|
||||
async function dropIndexIfExists(queryInterface, tableName, indexName) {
|
||||
if (await indexExists(queryInterface, tableName, indexName)) {
|
||||
await queryInterface.removeIndex(tableName, indexName);
|
||||
console.log(`[idx] ${tableName}.${indexName} 已删除`);
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
// eslint-disable-next-line no-unused-vars
|
||||
async up(queryInterface, Sequelize) {
|
||||
await addIndexIfNotExists(queryInterface, TABLE_NAME, INDEX_NAME, {
|
||||
fields: [ 'store_id' ],
|
||||
});
|
||||
},
|
||||
|
||||
// eslint-disable-next-line no-unused-vars
|
||||
async down(queryInterface, Sequelize) {
|
||||
await dropIndexIfExists(queryInterface, TABLE_NAME, INDEX_NAME);
|
||||
},
|
||||
};
|
||||
148
docs/queryorder-wave-index-optimization-plan.md
Normal file
148
docs/queryorder-wave-index-optimization-plan.md
Normal file
@ -0,0 +1,148 @@
|
||||
# queryOrder 波次计数性能优化方案(只读评估 + 方案文件,未执行)
|
||||
|
||||
> 状态:**待用户风险确认**。本方案全程只读评估,未执行任何 DDL / 数据变更。
|
||||
> 编制:wms-db-agent|日期:2026-08-30
|
||||
|
||||
## 1. 背景与瓶颈定位
|
||||
|
||||
- 业务链路:工作台 queryOrder → `app/service/systems/workbench.js`
|
||||
- `_countWaveOrders()`:对 current + dispatch 两族分表执行 `SELECT COUNT(*) WHERE wave_id=? AND warehouse_id=?`
|
||||
- `_getWaveOrderIds()`:同谓词取订单 id 列表
|
||||
- 现状瓶颈(上一轮 DB agent 已定位 + 用户提供生产数据):
|
||||
- 现有索引 `idx_{wh}_current_wave` 为 `(status, wave_id)`,前导列 `status` 不在谓词中;
|
||||
- 生产 dispatch 分表约 **25.38 万行 / 524MB**,单次 COUNT 全表扫描约 **12.69 万行**;生产 MySQL **5.7.44**。
|
||||
- 关联问题:序列表 `wms_order_id_location_{wh}` 缺约 **12.4 万**存量订单 id 记录 → queryOrder 定位回退为分表遍历(见 §5)。
|
||||
|
||||
## 2. 分表索引生成机制
|
||||
|
||||
### 2.1 模型层定义
|
||||
|
||||
- `app/model/order_delivery_table_schema.js`:
|
||||
- `buildIndexOptions(warehouseId, type)` 生成每张分表的索引列表;
|
||||
- current 类型共 8 个索引,其中 `idx_{wh}_current_wave = (status, wave_id)`(瓶颈索引);
|
||||
- dispatch 类型复用 current 的基础索引:`baseIndexes[0..2] + idx_dispatch_{wh}_dispatch_lane (dispatch_lane, status) + baseIndexes.slice(3)`,即 dispatch 分表同样继承 `idx_{wh}_current_wave`;
|
||||
- `buildIndexLines()` 用于建表 DDL;`buildTableOptions()` 供动态模型 define。
|
||||
- 基表模型 `app/model/order_delivery.js` 自带索引列表(`wave_id = (status, wave_id)` 等)——基表 `wms_order_delivery` 非分表,**不在本次范围**(可选加,默认不加)。
|
||||
|
||||
### 2.2 运行时 drift 同步(⚠️ 关键风险)
|
||||
|
||||
- `app/model/order_delivery_factory.js`:`getOrCreateModel` → `ensureManagedTableSchema` → `needsTableSchemaSync`(比对期望索引)→ `alterManagedTableSchema`(**只补缺失索引、不删已有索引**)。
|
||||
- 每次进程首次使用某分表模型时触发(模型有内存缓存)。
|
||||
- 结论:**若先改 schema 文件再部署代码,应用会在首个请求时自动对 524MB 大表执行建索引 DDL(无 ALGORITHM/LOCK 控制、无法择时)**。
|
||||
- 因此正确顺序必须是:**先执行迁移(低峰期)→ 再落盘 schema 代码变更 → 再部署**;这样应用运行时 drift 检查发现索引已存在,不会重复建。
|
||||
|
||||
### 2.3 现有索引核对(开发环境,只读 SHOW INDEX)
|
||||
|
||||
开发环境(config.local.js,客户端 wms)确认 current/dispatch 分表现有索引与模型一致,瓶颈索引为:
|
||||
|
||||
| 表(开发环境示例) | 瓶颈索引 | 列 |
|
||||
|---|---|---|
|
||||
| wms_order_delivery_1000028_dispatch | idx_1000028_current_wave | status, wave_id |
|
||||
| wms_order_delivery_1000028 | idx_1000028_current_wave | status, wave_id |
|
||||
|
||||
开发环境分表规模(只读 information_schema):`wms_order_delivery_100000` 66,976 行 / 41.6MB;`wms_order_delivery_100000_dispatch` 2,488 行。生产分表规模以用户提供数据为准(dispatch 25.38 万行 / 524MB),执行前需实测。
|
||||
|
||||
## 3. 修改点清单
|
||||
|
||||
### 3.1 模型 schema(本次仅书面标注,未改文件)
|
||||
|
||||
> 为避免与 wms-dev-agent 的修复冲突,本 agent **不直接修改 schema 代码**,待用户确认后由 wms-dev-agent 落盘;或在用户授权后由本 agent 改。
|
||||
|
||||
- 文件:`app/model/order_delivery_table_schema.js`
|
||||
- 函数:`buildIndexOptions`,current 分支共享 `indexes` 数组内、`idx_${prefix}_wave` 之前插入:
|
||||
|
||||
```js
|
||||
{
|
||||
name: `idx_${prefix}_wave_id`,
|
||||
fields: [ 'wave_id' ],
|
||||
},
|
||||
```
|
||||
|
||||
- dispatch 分支**无需修改**(通过 `baseIndexes` 自动继承)。
|
||||
- 索引名与迁移草案一致:`idx_{wh}_current_wave_id`(dispatch 表沿用 `_current_` 前缀,与既有继承索引命名习惯一致)。
|
||||
|
||||
### 3.2 迁移文件(已创建,未执行)
|
||||
|
||||
- 路径:`database/migrations/20260830100000-add-wave-id-index-to-order-delivery-shards.js`
|
||||
- 要点:
|
||||
- 动态枚举 `wms_order_delivery_{wh}` 与 `wms_order_delivery_{wh}_dispatch`(information_schema,不写死仓库 id);
|
||||
- 幂等:`SHOW INDEX` 已存在则跳过;
|
||||
- 使用原生 `ALTER TABLE ... ADD INDEX ..., ALGORITHM=INPLACE, LOCK=NONE`(Sequelize `addIndex` 不支持传算法/锁参数,故用原生 SQL);
|
||||
- `down` 为 `DROP INDEX`(同样 INPLACE/LOCK=NONE);
|
||||
- 语法已通过 `node --check`;**未对任何环境执行**。
|
||||
|
||||
## 4. 生产执行风险评估与建议
|
||||
|
||||
### 4.1 MySQL 5.7.44 在线 DDL 支持
|
||||
|
||||
- InnoDB 添加二级索引支持 `ALGORITHM=INPLACE, LOCK=NONE`(MySQL 5.6+,5.7 完整支持):不重建表、不锁写、并发 DML 允许。
|
||||
- 前置检查项:
|
||||
1. `SHOW VARIABLES LIKE 'old_alter_table'` 应为 `OFF`(默认);
|
||||
2. 确认表引擎 InnoDB(本项目分表均为 InnoDB);
|
||||
3. 执行前实测各分表行数与大小。
|
||||
|
||||
### 4.2 预估耗时与索引体积
|
||||
|
||||
- 索引体积:`wave_id BIGINT(20)`(8 字节)+ 主键 8 字节,25.38 万行约 **4–6 MB**,几乎不增加磁盘压力;
|
||||
- 建索引耗时:全表扫描 524MB + 排序 25 万行键值,低负载 SSD 上单个 dispatch 分表约 **数十秒–5 分钟**;current 分表按行数同比。多仓多表总窗口建议预留 **15–30 分钟**。
|
||||
- 副作用:每个分表多一个二级索引,INSERT 时多写约 20 字节/行,可忽略。
|
||||
|
||||
### 4.3 建议执行窗口
|
||||
|
||||
- 低峰期:**凌晨 02:00–05:00** 或周末低峰;避开波次扫描定时任务(`app/schedule/sync_finished_wave_batch.js`)、批量导入与大促。
|
||||
- 逐表执行并监控:`SHOW PROCESSLIST`、`INFORMATION_SCHEMA.INNODB_TRX`(确认无长事务)。
|
||||
|
||||
### 4.4 执行方式(红线)
|
||||
|
||||
- ❌ 禁止对生产库直接执行裸 `ALTER TABLE`;❌ 禁止用 `script/db-query.ps1` 查/改生产(它永远是开发环境)。
|
||||
- ✅ 生产必须走迁移流程:
|
||||
- 全量:`$env:NODE_ENV='production'; npx sequelize-cli db:migrate --migrations-path database/migrations --env production`
|
||||
- 或单条:`node script/run-single-migration.cjs 20260830100000-add-wave-id-index-to-order-delivery-shards.js`(内部连 `database/config.js` 的 production)
|
||||
- ⚠️ **生产当前有 4 条 pending 迁移**(只读 `db:migrate:status --env production` 结果):`20260829120000` / `20260829160000` / `20260829170000` / `20260829180000`(report-delivery 相关)。`run-single-migration.cjs` 会拒绝跨序执行 → **先跑完这 4 条**再跑本条;用 `db:migrate` 则按序自动全部执行。
|
||||
- 开发环境基线:迁移全部 up(最新 `20260829180000`);本条迁移在开发/生产两边均显示 `down`(未执行,符合"草案"状态)。
|
||||
|
||||
### 4.5 回滚
|
||||
|
||||
- `down`:`DROP INDEX`(INPLACE/LOCK=NONE,秒级完成),不重建表、不影响数据。
|
||||
|
||||
## 5. 存量回填评估(script/backfill-order-id-location.cjs)
|
||||
|
||||
### 5.1 适用性
|
||||
|
||||
- 目标:将分表存量 id 补入 `wms_order_id_location_{wh}`(id → location 映射),修复 queryOrder 定位回退(约 12.4 万行缺失)。
|
||||
- 脚本能力:`--dry-run`、`--warehouse-id=`、`--batch-size=`(100–50000,默认 1000)、`--db-client=`、`--config-path=`。
|
||||
- ⚠️ 默认连开发库(config.local.js);**生产必须** `--config-path=script/db-query-prod-config.js --db-client=wms`。
|
||||
- 流程:枚举分表 → 确保序列表存在(缺失时 CREATE TABLE)→ 分批 LEFT JOIN(PK 序)找缺失 id → 多行 `INSERT ... ON DUPLICATE KEY UPDATE` → 每仓结束抬 `AUTO_INCREMENT = MAX(id)+50`。
|
||||
|
||||
### 5.2 数据量与分批建议
|
||||
|
||||
- 约 12.4 万行;默认 batch=1000 约 124 批。每批重新执行 LEFT JOIN(无物化),最大分表 25 万行 × 124 批 ≈ 3 千万次 PK 探测,低峰可接受;建议 `--batch-size=5000` 减少轮次。
|
||||
- 建议顺序:`--dry-run` 全量预演 → 核对输出 → 按仓库逐个 `--warehouse-id=` 执行 → 前后核对 `COUNT(*)`。
|
||||
|
||||
### 5.3 风险点
|
||||
|
||||
1. **id 碰撞(最高风险)**:回填期间若序列表 AUTO_INCREMENT 仍低于缺失 id 区间,新订单可能分配到相同 id,`ON DUPLICATE KEY UPDATE` 会把新订单的 location 覆盖为来源表 location。执行前必须核对:`AUTO_INCREMENT` vs 缺失 id 最大值;务必在**最低写入时段**执行。
|
||||
2. **DDL**:`ensureSequenceTable` 可能 CREATE TABLE;结束会 `ALTER TABLE ... AUTO_INCREMENT`(小表、秒级)——均属 DDL/写操作,需用户确认。
|
||||
3. **location 覆盖**:id 已存在于序列表时会被覆盖(脚本语义如此)。
|
||||
4. **无断点续跑**:中断后重跑安全(幂等 upsert),但需重新扫描。
|
||||
5. **与加索引互补**:索引修波次计数,回填修订单定位,两者独立、可分开执行。
|
||||
|
||||
## 6. 需要用户确认的风险问题清单(交 Dispatcher 转达)
|
||||
|
||||
1. 是否允许在**生产**执行加索引 DDL?(未确认前不执行)
|
||||
2. 执行方式:全量 `db:migrate`(会自动先执行生产 pending 的 4 条 20260829* 迁移)还是单条 `run-single-migration.cjs`(需先补跑那 4 条)?是否同意先执行那 4 条?
|
||||
3. 执行窗口:请指定具体时间(建议凌晨 02:00–05:00);期间可接受轻微 I/O 压力?
|
||||
4. 索引范围:确认 current + dispatch 两族分表、**全部仓库**都加?
|
||||
5. 是否允许对 `wms_order_id_location_{wh}` 回填写数据(约 12.4 万行)?是否先 `--dry-run` 预演?
|
||||
6. 回填窗口与 id 碰撞:是否可安排在最低写入时段?是否同意先核对序列表 AUTO_INCREMENT 区间?
|
||||
7. schema 代码变更(`buildIndexOptions` 新增 `idx_{prefix}_wave_id`):是否由 wms-dev-agent 落盘?确认部署顺序 = **先迁移、后代码**。
|
||||
8. 回滚授权:若上线后异常,是否允许执行 down(DROP INDEX)?
|
||||
|
||||
## 7. 建议执行顺序
|
||||
|
||||
1. 用户完成 §6 风险确认;
|
||||
2. 生产低峰期执行迁移(含前置 4 条 pending);
|
||||
3. 生产 `SHOW INDEX` + `EXPLAIN` 验证新索引生效;
|
||||
4. wms-dev-agent 落盘 `buildIndexOptions` 变更并部署(避免运行时 drift 重复建索引);
|
||||
5. (可选)序列表回填(先 dry-run);
|
||||
6. 观察 queryOrder 链路耗时与错误率。
|
||||
342
docs/report-config-guide.md
Normal file
342
docs/report-config-guide.md
Normal file
@ -0,0 +1,342 @@
|
||||
# 配置驱动通用报表与货主定时投递 — 配置结构说明
|
||||
|
||||
> 本文档与代码实现保持一致(模型:`app/model/report_definition.js`;引擎:`app/service/systems/report.js`;
|
||||
> 渲染翻译层:`app/lib/report/render.js`;内置查询器:`app/service/systems/report/queries/*`;
|
||||
> 投递编排:`app/service/systems/reportDelivery.js`)。
|
||||
> 接口定义见 `methods/system.json` 分组「通用报表模块」(module=report)。
|
||||
|
||||
> 破坏性变更(2026-08-30 模型重构):报表定义由 `code` 编码改为主键 `id` 关联,接口入参 `report_code`
|
||||
> 全部替换为 `report_id`(=报表定义ID,兼容 `reportId` 驼峰);`code/scope/description` 与
|
||||
> `output_config/source_config/sheet_config` 三段 JSON 配置字段已随模型删除,
|
||||
> 列渲染由注册类型硬编码字段规格自动完成(无自定义列配置)。
|
||||
|
||||
## 1. 总览
|
||||
|
||||
报表采用「配置驱动」:`wms_report_definition` 一行配置 = 一个报表(`type` + `fields` 极简配置),
|
||||
大部分新报表场景只需加配置行或新增内置查询器类型,免发版。
|
||||
|
||||
模型 `app/model/report_definition.js` 关键字段:
|
||||
|
||||
| 列 | 类型 | 说明 |
|
||||
|---|---|---|
|
||||
| `id` | BIGINT UNSIGNED | 主键,报表定义ID(接口入参 `report_id`,唯一性由主键承担) |
|
||||
| `name` | STRING(100) | 报表名称 |
|
||||
| `type` | STRING(50) | 报表类型(内置查询器注册 key,如 `stockFlow`) |
|
||||
| `file_name` | STRING(200) | 导出文件名模板(支持 `{date}` 占位,如 `7日出入库_{date}.xlsx`) |
|
||||
| `fields` | JSON | 勾选的字段 key 数组(该类型注册字段的子集;列头/合并/样式/格式化由类型硬编码字段规格决定) |
|
||||
| `is_enabled` | TINYINT(1) | 是否启用:0=停用 1=启用(导出只读 is_enabled=1 的定义) |
|
||||
| `remark` | STRING(500) | 备注 |
|
||||
| `created_at`/`updated_at`/`deleted_at` | DATE | 时间戳与软删标记 |
|
||||
|
||||
生成链路:
|
||||
|
||||
```text
|
||||
report.generate(method 层,异步任务,入参 report_id)
|
||||
-> systems/report.js getDefinition(读定义,is_enabled=1,软删自动排除)
|
||||
-> resolveTypeEntry / resolveQuerier(type 查注册表)
|
||||
-> 内置查询器取数 {windows, rows, meta}
|
||||
-> lib/report/render.js renderSheetByType(按类型硬编码字段规格渲染)
|
||||
-> excel.generateAndUpload(产物 fileKey/url/filename/size)
|
||||
```
|
||||
|
||||
## 2. 注册类型(report.definition.typeList / wms_report_definition.type)
|
||||
|
||||
查询器注册表 `app/service/systems/report/queries/index.js`,`type` 即注册方法 key;
|
||||
查询器签名统一:`async ({ ctx, storeId, warehouseId, params }) => ({ windows, rows, meta })`,
|
||||
每个查询器模块挂载静态字段清单 `fields` 与缺省窗口参数 `defaultWindow`。
|
||||
|
||||
当前注册类型:
|
||||
|
||||
| key | 标题 | 说明 |
|
||||
|---|---|---|
|
||||
| `stockFlow` | 库存变化以及补货报表 | 按日窗口聚合出入库流水与正品库存,输出每 SKU 每日出/入库、可用/总库存、锁定数、待出、日均出/入库、预计可售天数、建议补货量与库存预警 |
|
||||
|
||||
`stockFlow` 缺省窗口参数:`window = { dayCount: 7, cutoverHour: 7 }`。
|
||||
|
||||
`stockFlow` 全量字段清单(16 个顶层字段,`report.definition.typeList` / `report.meta` 直接返回该规格):
|
||||
|
||||
| key | label | type | computed | asText | 说明 |
|
||||
|---|---|---|---|---|---|
|
||||
| `stock_id` | 库存ID | number | - | - | |
|
||||
| `item_code` | 商品编码 | string | - | ✅ | 文本单元格落地,防科学计数法 |
|
||||
| `item_name` | 商品名称 | string | - | - | |
|
||||
| `barcode` | 条码 | string | - | ✅ | 文本单元格落地,防科学计数法 |
|
||||
| `daily` | 每日出入库 | array | - | - | children:`ck`(出库数,number)/ `rk`(入库数,number) |
|
||||
| `ck_total` | 出库合计 | number | - | - | |
|
||||
| `rk_total` | 入库合计 | number | - | - | |
|
||||
| `available` | 可用库存 | number | - | - | |
|
||||
| `total` | 总库存 | number | - | - | |
|
||||
| `pending` | 待出库存 | number | - | - | |
|
||||
| `locked` | 锁定数 | number | - | - | |
|
||||
| `ck_avg` | 出库日均(×10) | number | ✅ | - | 预计算字段 |
|
||||
| `rk_avg` | 入库日均(×10) | number | ✅ | - | 预计算字段 |
|
||||
| `stock_days` | 预计可售天数 | number | ✅ | - | 预计算字段 |
|
||||
| `suggest` | 建议补货量 | number | ✅ | - | 预计算字段 |
|
||||
| `warn` | 库存预警 | boolean | ✅ | - | 预计算字段 |
|
||||
|
||||
### 2.1 stockFlow 口径与假设(8 条,供测试复核)
|
||||
|
||||
1. **窗口**:`dayCount` 个 `[D cutoverHour:00, D+1 cutoverHour:00)` 本地时区半开区间
|
||||
(缺省 7 天、07:00 切点,可由请求 `params.dayCount/cutoverHour` 覆盖)。
|
||||
2. **流水**:`wms_stock_transaction`,`transaction_type IN (INBOUND, OUTBOUND)`,显式排除 LOCK/UNLOCK,
|
||||
按 `created_at` 落入窗口,INBOUND→rk、OUTBOUND→ck。
|
||||
3. **库存口径**:`wms_storage`(库位级正品明细),`inventory_type='ZP'`、`is_enabled=1`、未删除,
|
||||
`SUM(quantity)`=总库存、`SUM(available_quantity)`=可用库存、`SUM(locked_quantity)`=锁定数、
|
||||
待出库存=总库存-可用库存;与 `wms_stock_warehouse` 主表的 `quantity/locked_quantity` 可能存在口径差异。
|
||||
4. **条码**:`wms_stock_barcodes` 多值取字典序第一条(表内无主条码标志,等价旧 PHP `MIN(barcode)` 语义)。
|
||||
5. **行范围**:窗口内有流水或有正品库存的 SKU 均出列,按 `item_code` 升序、`stock_id` 升序。
|
||||
6. **日均口径**:`ck_avg/rk_avg = int(合计/天数×10)`(`formatters.avgDaysPerWeek`)。
|
||||
7. **预计可售天数**:出库日均>0 时 `int(可用库存×10/出库日均×10)`(`available×10/ckAvg` 取整),无出库时为 null。
|
||||
8. **suggest/warn**:由 `formatters` 注册表计算。低库存补偿:`available < 20` 且 `rk_total < 20` 时
|
||||
建议补货量补偿到不低于 30;预警判定由 `warnOf(ck_total, available, rk_total)` 计算。
|
||||
|
||||
## 3. 渲染规则(renderSheetByType,无 sheet_config)
|
||||
|
||||
列定义不再由 `sheet_config.columns` 配置,而由**注册类型字段规格硬编码自动生成**
|
||||
(`app/lib/report/render.js` `renderSheetByType`,按定义勾选字段顺序渲染):
|
||||
|
||||
| 字段类型 | 渲染规则 |
|
||||
|---|---|
|
||||
| `string` | 静态列(表头=label);字段规格 `asText: true` 时整列落地为 Excel 文本单元格 |
|
||||
| `number` | 静态列,统一 `zeroToDash`(`0 / '0' / null / ''` 显示 `-`) |
|
||||
| `boolean` | 静态列,统一 `yesNo`(真→'是'、假→'否',PHP 布尔语义) |
|
||||
| `array` | 窗口展开列:per=窗口数(缺省 7)、pair=children 字段键;表头第 1 行每窗口输出窗口开始日期 `'Y/n/j'`(无前导零,如 `2026/8/23`),pair 数>1 时每窗口表头横向合并(如 D1:E1 … P1:Q1);表头第 2 行按 children label 填充;子字段 number 统一 `zeroToDash` |
|
||||
|
||||
- 存在展开列时启用两行表头,其余列表头纵向合并(如 A1:A2),合并区域**自动生成**,无需配置。
|
||||
- **asText(文本单元格)**:由类型字段规格硬编码(如 `item_code`/`barcode` 声明 `asText: true`),
|
||||
渲染层 `renderSheetByType` 将声明 `asText` 的列收集为 `textColumns`(0 基列索引数组,未声明任何 `asText` 列时不输出该字段),
|
||||
由 `app/service/systems/excel.js` 落地:ExcelJS 路径逐单元格 `numFmt='@'` 并把值转为字符串(原始对象除外),
|
||||
SheetJS 路径逐单元格 `t:'s'`、`z:'@'` 并把值字符串化。适用于条码、商品编码等长数字串
|
||||
(防止被 Excel 按数值展示成科学计数法),**无需**再配合 `textPrefix` 的 `'` 前缀
|
||||
(`textPrefix` 格式化器保留注册仅向后兼容)。
|
||||
- sheet 名称为类型标题(如「库存变化以及补货报表」);`columns` 恒输出空数组
|
||||
(数据以 AOA 二维数组形式输出,表头行内联在 rows 首位)。
|
||||
|
||||
## 4. 导出文件名(file_name)
|
||||
|
||||
- `file_name` 为文件名模板,`{date}` 替换为数据日期(请求 `params.bizDate`,缺省服务器当天,`YYYY-MM-DD`)。
|
||||
- 缺省模板:`<name>_<date>.xlsx`;不以 `.xlsx`/`.xls` 结尾时自动补 `.xlsx`。
|
||||
- 上传目录:`exports/report/<report_id>/`。
|
||||
|
||||
## 5. 货主定时投递(wms_report_delivery_plan / wms_report_delivery_log)
|
||||
|
||||
- **投递计划** `wms_report_delivery_plan`:`store_id + report_definition_id` 唯一(唯一索引 `uk_store_report_definition`,
|
||||
`report_definition_id` 即报表定义ID、接口入参 `report_id`);`schedule_times`(HH:mm 数组,去重升序)、
|
||||
`channel`(**仅支持 `inbox`,默认 `inbox`**;wecom/link 已弃用,保存时传非法渠道报错「投递渠道仅支持 inbox: <channel>」)、
|
||||
`late_grace_minutes`(补投宽限 0-1440,默认 60)、`name`(计划名称,仅展示字段,≤100 字符,可空)、`enabled`。
|
||||
- **计划名称 `name`**(2026-08-30 新增,仅展示字段,不参与 `store_id + report_definition_id` 幂等/关联逻辑):
|
||||
`report.deliveryPlan.save` 可选入参(未传不覆盖既有值;`null`/空串/全空白归一化为 `null` 显式清空;
|
||||
非空 `trim` 后最长 100 字符,超长报错「计划名称 name 长度不能超过 100 字符」);
|
||||
`save` 成功响应与 `report.deliveryPlan.list` 列表项均返回 `name`(未设置时为空字符串)。
|
||||
|
||||
```json
|
||||
// report.deliveryPlan.save(name 可选)
|
||||
{
|
||||
"store_id": 1001,
|
||||
"report_id": 1,
|
||||
"schedule_times": ["09:00", "17:30"],
|
||||
"name": "每日库存报表投递",
|
||||
"late_grace_minutes": 60
|
||||
}
|
||||
```
|
||||
- **渠道收敛兜底**:历史计划残留的 wecom/link 渠道在投递时**按 inbox 兜底执行**(仅记录 warn 日志,不抛错,避免历史计划卡死)。
|
||||
- **迁移归一化**:迁移 `20260829170000` 已把两表 `channel` 列默认值 wecom → inbox、comment 收敛,
|
||||
存量 `channel IN ('wecom','link')` 行统一 UPDATE 为 `inbox`(模型 `defaultValue: 'inbox'` 同步);
|
||||
`report.deliveryPlan.list` / `report.deliveryLog.list` 响应 `channel` 恒为 `inbox`。
|
||||
- **投递记录** `wms_report_delivery_log`:状态机与 `status` 一致:
|
||||
`pending → exporting → delivered / failed / cancelled`;`report_definition_id` 关联报表定义ID,
|
||||
`report_name` 为投递时报表名称快照(审计回放,定义删除后仍可追溯)。
|
||||
- **调度**(`reportDelivery.dispatch`,分钟级):按 HH:mm + 宽限窗口命中后,
|
||||
对每个 `(store_id, report_definition_id, biz_date, time_point)` 幂等生成报表并投递(防重不防漏)。
|
||||
- **失败自动重推**:inbox 推送失败(`success=false` 或消息回写 `push_status=3`)时,立即复用
|
||||
`inbox.message.retry` **重推一次**(`ext_id` 幂等复用同一条消息记录,不重复写);重推仍失败进入
|
||||
`failed` 退避重试:`MAX_RETRY=3`,退避 `retry_count × 60s`;重试扫描条件
|
||||
`status=failed 且 retry_count<3 且 next_retry_at<=now`;卡在 exporting 超过 30 分钟视为陈旧可重扫。
|
||||
- **biz_date 口径**:正常投递为触发日 T-1;跨零点补投(时间点晚于当前时刻)为触发日 T-2,
|
||||
与昨日正常投递口径一致,避免与次日正常投递撞幂等键。
|
||||
|
||||
### 5.1 文本通知模板与定向群/成员(notify_template / notify_group_ids / notify_member_ids)
|
||||
|
||||
投递计划可在投递完成后附带发送一条文本通知(与投递渠道独立,inbox 渠道投递后同样生效;未配置时行为与旧版完全一致)。
|
||||
三个字段均为可选,仅在 `report.deliveryPlan.save` 入参存在时生效(更新时未传保持原值)。
|
||||
|
||||
#### 5.1.1 notify_template(文本通知模板)
|
||||
|
||||
- 最长 **500** 字符,超出报错;空值/未传视为未启用。
|
||||
- 标签白名单(仅以下 4 个标签会被渲染,其余 `{xxx}` 视为未知标签,保存时报错并列出非法标签):
|
||||
|
||||
| 标签 | 渲染内容 |
|
||||
|---|---|
|
||||
| `{time}` | 发送时间,格式 `YYYY-MM-DD HH:mm` |
|
||||
| `{url}` | 报表文件下载链接;链接为空时替换为兜底文案「文件生成中,稍后可在投递记录中查看」 |
|
||||
| `{report_name}` | 报表名称 |
|
||||
| `{biz_date}` | 数据日期 `YYYY-MM-DD` |
|
||||
|
||||
- 示例模板:`【{report_name}】{biz_date} 数据报表已生成,下载:{url}(生成时间 {time})`
|
||||
|
||||
#### 5.1.2 notify_group_ids(通知群,定向内部群)
|
||||
|
||||
- 元素为 `wms_inbox_group.id`(内部群 ID),**正整数**、自动去重并升序,最多 **20** 个。
|
||||
- 保存时校验存在性:软删(已删除)的群报错并**列出缺失 ID**;被屏蔽(`is_blocked=1`)的群仍可选中,
|
||||
屏蔽属于发送时过滤维度。
|
||||
- 发送时逐群推送(群维度协议字段 `group_id`/`group_name` 为单值),并再次过滤
|
||||
`is_blocked=1`、软删、仓库维度不一致的群;此类群不发送且不进入投递记录快照。
|
||||
|
||||
#### 5.1.3 notify_member_ids(通知成员,定向外部成员)
|
||||
|
||||
- 元素为**外部 IM 用户 ID**,**非空字符串**、自动去重,最多 **100** 个。
|
||||
- 推送时 `user_id` **数组整体透传**(目标侧协议支持 user_id 数组),不循环拆发;
|
||||
选择群时成员数组随每个群推送携带,未选择群时单独做一次仅成员推送。
|
||||
|
||||
#### 5.1.4 发送规则与投递记录快照
|
||||
|
||||
- 未配置模板或未选择任何群/成员时**不发送**(投递行为不变)。
|
||||
- 发送时机:报表生成并完成渠道投递后(`delivered` 回写前),失败抛异常走失败退避重试
|
||||
(`MAX_RETRY=3`,退避 `retry_count × 60s`)。
|
||||
- 发送结果快照 `notify_targets` 随投递记录落库并在 `report.deliveryLog.list` 返回:
|
||||
|
||||
```json
|
||||
{
|
||||
"group_ids": [1, 3],
|
||||
"member_ids": ["user-1001", "user-1002"],
|
||||
"notify_text": "【7日出入库数据】2026-08-28 数据报表已生成,下载:https://...(生成时间 2026-08-29 09:00)"
|
||||
}
|
||||
```
|
||||
|
||||
- `group_ids` 为**实际发送**的群内部 ID 列表;`member_ids` 为实际发送的成员 ID 列表;
|
||||
`notify_text` 为标签替换后的最终文本;未发送文本通知时快照为 `null`。
|
||||
|
||||
## 6. 报表定义保存示例(report.definition.save)
|
||||
|
||||
```json
|
||||
{
|
||||
"name": "库存变化以及补货报表",
|
||||
"type": "stockFlow",
|
||||
"fileName": "库存变化_{date}.xlsx",
|
||||
"fields": ["item_code", "item_name", "barcode", "daily", "ck_total", "rk_total", "available", "total", "pending", "locked", "ck_avg", "suggest", "warn"],
|
||||
"is_enabled": 1,
|
||||
"remark": ""
|
||||
}
|
||||
```
|
||||
|
||||
- `type` 必须命中注册表(当前仅 `stockFlow`,未知报「未知的报表类型: <type>」);
|
||||
`fields` 必须为该类型注册字段子集(16 个顶层字段任意勾选,含非法 key 报可读错误并列出可用字段)。
|
||||
- `file_name` 兼容 `fileName` 驼峰写法(驼峰优先);新增必填 `name`/`type`/`file_name`/`fields`;
|
||||
更新按 `id` upsert,未传字段不覆盖;软删记录命中时自动恢复。
|
||||
- 保存成功后响应即报表定义视图:
|
||||
`{ id, name, type, file_name, fields, is_enabled, remark, created_at, updated_at }`。
|
||||
|
||||
## 7. report.definition.typeList / report.meta(前端元数据接口)
|
||||
|
||||
### 7.1 用途
|
||||
|
||||
- `report.definition.typeList`:免权限只读(仅登录),返回注册类型清单
|
||||
`[{ key, title, description, window, fields }]`,供前端报表设计器渲染「报表类型」选择与字段树。
|
||||
- `report.meta`:免权限只读(仅登录,保留审计日志),按 `report_id` 返回
|
||||
`report_id/name/type/file_name/window/fields`(fields 含 `selected` 勾选标记与 `asText` 标记),
|
||||
**不执行真实数据查询**。
|
||||
|
||||
实现:`report.definition.typeList` → `app/service/systemMethods/report/definition.js` → `systems/report.js listRegisteredTypes`;
|
||||
`report.meta` → `app/service/systemMethods/report.js` → `systems/report.js getMeta`。
|
||||
|
||||
> 鉴权/日志口径:`report.definition.typeList` 在 `definition.js` 的 `systemInit` 名单内
|
||||
> (`_noNeedRight/_noNeedAuth/_noNeedLog='typeList'`:免权限 + 免鉴权 + 不写审计日志,仅登录;
|
||||
> 同模块 `save/list/delete` 未声明免权限,仍需授权);`report.meta` 在 `_noNeedRight/_noNeedAuth` 名单内
|
||||
> (免权限 + 免仓库有效期校验,仅登录),未列入 `_noNeedLog` → **保留审计日志**
|
||||
> (`generate`/`generateTaskProgress` 不写审计日志,二者行为不同)。
|
||||
|
||||
### 7.2 请求示例
|
||||
|
||||
```json
|
||||
// report.definition.typeList(无必填参数)
|
||||
{}
|
||||
|
||||
// report.meta
|
||||
{ "report_id": 1 }
|
||||
```
|
||||
|
||||
- `report_id` 与 `reportId` 二选一(均传时优先 `reportId`);为空返回
|
||||
`flag=failure, code=0, message=报表ID report_id 必须为正整数`(HTTP 200)。
|
||||
- 定义不存在或已停用 → HTTP 500,`接口错误: 报表定义不存在或已停用: id=<id>`。
|
||||
|
||||
### 7.3 响应示例
|
||||
|
||||
```json
|
||||
// report.definition.typeList
|
||||
{
|
||||
"flag": "success",
|
||||
"code": 1,
|
||||
"message": "ok",
|
||||
"list": [
|
||||
{
|
||||
"key": "stockFlow",
|
||||
"title": "库存变化以及补货报表",
|
||||
"description": "按日窗口聚合出入库流水与正品库存,……",
|
||||
"window": { "dayCount": 7, "cutoverHour": 7 },
|
||||
"fields": [
|
||||
{ "key": "item_code", "label": "商品编码", "type": "string", "asText": true },
|
||||
{ "key": "daily", "label": "每日出入库", "type": "array", "children": [
|
||||
{ "key": "ck", "label": "出库数", "type": "number" },
|
||||
{ "key": "rk", "label": "入库数", "type": "number" }
|
||||
]},
|
||||
{ "key": "suggest", "label": "建议补货量", "type": "number", "computed": true }
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
// report.meta
|
||||
{
|
||||
"flag": "success",
|
||||
"code": 1,
|
||||
"message": "ok",
|
||||
"report_id": 1,
|
||||
"name": "库存变化以及补货报表",
|
||||
"type": "stockFlow",
|
||||
"file_name": "库存变化_{date}.xlsx",
|
||||
"window": { "dayCount": 7, "cutoverHour": 7 },
|
||||
"fields": [
|
||||
{ "key": "item_code", "label": "商品编码", "type": "string", "asText": true, "selected": true },
|
||||
{ "key": "barcode", "label": "条码", "type": "string", "asText": true, "selected": false }
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
字段元素结构:`{ key, label, type, computed?, asText?, children?, selected? }`:
|
||||
|
||||
- `type`:`string` / `number` / `boolean` / `array`;
|
||||
- `computed: true`:预计算字段(非原始表字段,如 `suggest`/`warn`);
|
||||
- `asText: true`:该列以文本单元格落地(由类型字段规格硬编码,如 `item_code`/`barcode`);
|
||||
- `children`:数组类型字段的子字段(如 `daily` 的 `ck`/`rk`);
|
||||
- `selected`(仅 `report.meta` 返回):该报表定义是否勾选此字段。
|
||||
|
||||
### 7.4 前端如何获取可用字段
|
||||
|
||||
1. 调用 `method=report.definition.typeList`(`POST /system`,header 带 `Authorization: Bearer <token>` 与 `platform`)
|
||||
获取全部注册类型与字段树;
|
||||
2. 保存报表定义时按类型字段树勾选 `fields`(`method=report.definition.save`);
|
||||
3. 渲染/导出前调用 `method=report.meta`(入参 `report_id`)取窗口参数 `window.dayCount/cutoverHour` 与勾选标记 `selected`;
|
||||
4. 导出 sheet 的列由「勾选字段 × 类型硬编码规格」自动生成,前端无需下发任何列配置。
|
||||
|
||||
## 8. 报表定义管理接口(report.definition.save / list / delete)
|
||||
|
||||
管理侧维护 `wms_report_definition` 的 3 个接口,均需登录且需鉴权(`isNeedAuth=true`、`isNeedLogin=true`,
|
||||
`POST /system`,header 带 `Authorization: Bearer <token>` 与 `platform`)。
|
||||
|
||||
- `report.definition.save`:按 `id` upsert(未传 id 新增),入参
|
||||
`{ id?, name, type, file_name/fileName, fields, is_enabled?, remark? }`;
|
||||
`type` 必须命中注册表、`fields` 必须为该类型注册字段子集(非法 key 报可读错误列出);
|
||||
新增必填 `name/type/file_name/fields`;软删记录命中时自动恢复。
|
||||
- `report.definition.list`:`where { name, type, is_enabled }` + `pagination` + `sort`
|
||||
(sort 白名单 `id/name/type/is_enabled/created_at/updated_at`,默认 id DESC);
|
||||
响应每行 `{ id, name, type, file_name, fields, is_enabled, remark, created_at, updated_at }`,软删自动排除。
|
||||
- `report.definition.delete`:入参 `id`;删除前按 `report_definition_id` 统计投递计划引用,
|
||||
仅拦截「启用中」的计划(`enabled=1`,报「存在 N 个启用的投递计划引用该报表,请先停用计划」),
|
||||
停用计划不阻断;重复删除同一 ID 幂等成功(`deleted` 恒为 1)。
|
||||
实现:`app/service/systemMethods/report/definition.js` → `app/service/systems/report.js` 的
|
||||
`saveDefinition` / `listDefinitions` / `deleteDefinition`。
|
||||
|
||||
> 鉴权口径:三个接口 `systemInit` 均未声明免权限(`isNeedAuth=true`),仅通配符角色
|
||||
> (超级管理员/仓库管理员)或已授权角色可用;本次仅文档同步,未扩任何角色授权
|
||||
> (权限缺口可用 `npm run permission:sync:system-api -- --dry-run` 预演)。
|
||||
|
||||
@ -1,4 +1,464 @@
|
||||
[
|
||||
{
|
||||
"version": "2026.08.30-report-delivery-plan-copy",
|
||||
"date": "2026-08-30",
|
||||
"type": "added",
|
||||
"summary": "新增 report.deliveryPlan.copy 批量复制接口:传入源计划ID id 与目标货主ID数组 store_ids(非空正整数数组,自动去重,兼容 storeIds 驼峰),快速复制源计划到其他货主;目标货主已存在同 report_definition_id 计划时跳过不覆盖;notify_group_ids/notify_member_ids 通知配置不复制(新计划置空);enabled 原样复制(保持复制语义),其余字段(report_definition_id/schedule_times/channel/late_grace_minutes/name/remark/notify_template)原样复制;事务批量创建,唯一键冲突单条降级 skipped。",
|
||||
"methods": [
|
||||
"report.deliveryPlan.copy"
|
||||
],
|
||||
"notes": [
|
||||
"app/service/systemMethods/report/deliveryPlan.js copy:解构 id/store_ids(兼容 storeIds 驼峰,优先取驼峰形式,与 save 的 reportId 兼容口径一致),透传 systems.reportDelivery.copyPlan({ id, storeIds }),统一 success 包装 data={ created, skipped };systemInit 未声明免权限(_noNeedLogin/_noNeedRight/_noNeedAuth 均为空),与 save/list 同权限口径(需登录需鉴权,仅通配符角色或已授权角色可用)",
|
||||
"app/service/systems/reportDelivery.js copyPlan:id 必须为正整数(否则抛「计划ID无效」),findByPk 软删排除、不存在抛「计划不存在」;store_ids 经 parseJsonArray 解析为非空数组且元素为正整数并自动去重(空/非数组抛「目标货主 store_ids 必须为非空数组」,非法元素抛「目标货主 store_ids 含非法货主ID(需正整数): <item>」);与源计划 store_id 相同的目标计入 skipped(与源计划货主相同);wms_store 校验存在且 status=1(否则 skipped:货主不存在或状态异常);目标已存在同 report_definition_id 计划(软删排除)跳过(已存在同报表定义计划);新建 payload 中 notify_group_ids/notify_member_ids 置 null(通知配置不复制)、enabled 原样复制,其余字段原样复制;事务批量创建,并发撞 uk_store_report_definition 唯一索引时单条降级 skipped、不中断其余创建",
|
||||
"methods/system.json 通用报表模块(module=report):新增 report.deliveryPlan.copy 条目(description/headers/params id+store_ids+storeIds/response created+skipped(reason 枚举 与源计划货主相同/货主不存在或状态异常/已存在同报表定义计划)/errors);isNeedAuth=true、isNeedLogin=true;版本 0.3.57 -> 0.3.58(docMeta.version),updatedAt 保持 2026-08-30",
|
||||
"AI_METHOD_ROUTING.md 5.1 节路由表新增 report.deliveryPlan.copy 行(service 路径 app/service/systemMethods/report/deliveryPlan.js、函数 copy、需登录、需授权),并新增批量复制特性说明;变更记录列表顶部追加本版本",
|
||||
"权限口径不变:report.deliveryPlan.copy 与 save/list 相同(isNeedAuth=true、isNeedLogin=true),未执行权限变更、未扩大任何角色授权",
|
||||
"本次仅文档同步,业务代码由 wms-dev-agent 完成,未修改 app/ 下任何代码,未执行数据库/Redis 操作,未运行测试"
|
||||
],
|
||||
"module": "report"
|
||||
},
|
||||
{
|
||||
"version": "2026.08.30-inbox-group-members-groupids-array",
|
||||
"date": "2026-08-30",
|
||||
"type": "changed",
|
||||
"summary": "inbox.group.members 入参由单个 groupId 改为数组 groupIds(必填,非空且每个元素为正整数,对应 wms_inbox_group.id),一次查询多个群的成员并在消息层多群聚合去重(多群共享同一 500 条聚合池);破坏性入参变更(移除 groupId),调用方需同步升级。",
|
||||
"methods": [
|
||||
"inbox.group.members"
|
||||
],
|
||||
"notes": [
|
||||
"app/service/systemMethods/inbox.js groupMembers:解构 groupIds 透传给 systems 层;warehouseId 仍从 ctx.user?.store_id 服务端注入(Number 化),不信任前端传值;keyword/limit 透传不变",
|
||||
"app/service/systems/inbox/group.js members:groupIds 校验为非空数组且每个元素为数字或可解析数字字符串的正整数(否则抛「groupIds 无效」);InboxGroup.findAll({ where: { id: { [Op.in]: groupIds }, warehouse_id } }) 批量校验群存在(软删自动排除),无匹配抛「群不存在或无权限操作」;聚合所有群外部 group_id(去重、剔空),全为空返回 { list: [] };消息按 group_id IN + warehouse_id 拉取(id 倒序、limit 500 共享聚合池、user_id 排除 NULL/空串、软删排除);按 user_id 去重取最新 user_name;keyword 对聚合结果做 user_name/user_id 小写包含过滤;截断到 limit(默认20上限100)",
|
||||
"methods/system.json 站内信分组(module=inbox):inbox.group.members 描述改为多群聚合语义;params 删除 groupId、新增 groupIds(array<number|string>,必填,非空数组,元素为正整数,对应 wms_inbox_group.id);errors 400 由「群ID无效 / warehouseId 无效」改为「groupIds 无效 / warehouseId 无效」;headers/响应结构/权限口径不变(warehouseId 仍服务端注入、567 权限);版本 0.3.56 -> 0.3.57(docMeta.version),updatedAt 保持 2026-08-30",
|
||||
"AI_METHOD_ROUTING.md 5.2 节:members 底层实现描述由「groupId 必填」改为「groupIds 必填(数组,多群聚合)」;变更记录列表新增本版本",
|
||||
"权限不变:仍需 567(inbox.group.members,isNeedAuth=true、isNeedLogin=true),未执行权限变更",
|
||||
"本次仅文档同步,业务代码由 wms-dev-agent 完成,未修改 app/ 下任何代码,未执行数据库/Redis 操作,未运行测试"
|
||||
],
|
||||
"module": "inbox"
|
||||
},
|
||||
{
|
||||
"version": "2026.08.30-inbox-group-quicklist-dual-dim-filter",
|
||||
"date": "2026-08-30",
|
||||
"type": "changed",
|
||||
"summary": "inbox.group.quickList 改为双维度可选过滤:store_id(货主维度,对应 wms_inbox_group.store_id 列)与 warehouse_id(仓库维度,对应 wms_inbox_group.warehouse_id 列)均可选,可单独传、可同时传(AND),也可都不传(返回所有仓库/货主的群);本记录修正并取代 2026.08.30-inbox-group-quicklist-store-id(该版将 store_id 错误映射为 warehouse_id 列);新增 store_id 列索引迁移(待发布时执行)。",
|
||||
"methods": [
|
||||
"inbox.group.quickList"
|
||||
],
|
||||
"notes": [
|
||||
"取代关系:本记录修正并取代 2026.08.30-inbox-group-quicklist-store-id 的口径——上一版将入参 store_id 错误映射为 wms_inbox_group.warehouse_id(仓库维度),本版明确 store_id=货主维度(对应 store_id 列)、warehouse_id=仓库维度(对应 warehouse_id 列),两维度均可选可组合,均不传时返回所有仓库/货主的群",
|
||||
"app/service/systemMethods/inbox.js groupQuickList:解构透传 data.store_id(storeId)与 data.warehouse_id(warehouseId)给 systems 层,不再从 ctx.user 注入任何仓库值;其余入参 keyword/groupType/limit 不变",
|
||||
"app/service/systems/inbox/group.js quickList:双列可选过滤——store_id(货主维度,String 化 trim 非空时 Number 化并校验 Number.isInteger 且 >0,否则抛「store_id 无效」)设置 where.store_id;warehouse_id(仓库维度,同样校验否则抛「warehouse_id 无效」)设置 where.warehouse_id;两者可同时传(AND)也可都不传(不加对应过滤条件);keyword 模糊匹配 group_name/group_id、groupType 筛选、limit 默认20上限100、created_at 倒序、软删自动排除均不变",
|
||||
"database/migrations/20260830150000-add-store-id-index-to-wms-inbox-group.js:为 wms_inbox_group.store_id 新增索引 idx_store_id(幂等 up/down,尚未执行,待发布时执行);warehouse_id 维度已由 uk_warehouse_group_id(warehouse_id, group_id) 前导列覆盖,双条件 AND 由两索引组合命中",
|
||||
"methods/system.json 站内信分组(module=inbox):inbox.group.quickList 描述改为双维度可选过滤口径;params 修正 store_id(货主维度,对应 store_id 列)并新增 warehouse_id(可选正整数,对应 warehouse_id 列);errors 400 由「store_id 无效」改为「store_id 无效 / warehouse_id 无效」;headers 保持登录凭证口径(不从中解析仓库上下文);版本 0.3.55 -> 0.3.56(docMeta.version),updatedAt 保持 2026-08-30",
|
||||
"AI_METHOD_ROUTING.md 5.2 节:quickList 底层实现与仓库口径改为双维度口径(store_id=货主维度 / warehouse_id=仓库维度,均可选可组合、不传返回全部、不再从登录上下文注入),变更记录列表新增本版本并标注修正/取代上一版",
|
||||
"权限不变:仍需 566(inbox.group.quickList,isNeedAuth=true、isNeedLogin=true),未执行权限变更",
|
||||
"本次仅文档同步,业务代码由 wms-dev-agent 完成,未修改 app/ 下任何代码,未执行数据库/Redis 操作,未运行测试"
|
||||
],
|
||||
"module": "inbox"
|
||||
},
|
||||
{
|
||||
"version": "2026.08.30-inbox-group-quicklist-store-id",
|
||||
"date": "2026-08-30",
|
||||
"type": "changed",
|
||||
"summary": "inbox.group.quickList 新增可选入参 store_id(对应 wms_inbox_group.warehouse_id):传入时仅返回该仓库的群,不传或为空时返回所有仓库的群;旧口径「warehouseId 由服务端从登录上下文自动注入、不信任前端传值」作废,改为透传前端入参 store_id。",
|
||||
"methods": [
|
||||
"inbox.group.quickList"
|
||||
],
|
||||
"notes": [
|
||||
"app/service/systemMethods/inbox.js groupQuickList:不再从 ctx.user.store_id 自动注入 warehouseId,改为解构透传 data.store_id(storeId)给 systems 层;其余入参 keyword/groupType/limit 不变",
|
||||
"app/service/systems/inbox/group.js quickList:storeId 可选(String(data.storeId ?? '').trim() 非空时 Number 化并校验 Number.isInteger 且 >0,否则抛「store_id 无效」);传入时 where.warehouse_id = storeId 过滤,不传或为空时不加 warehouse_id 过滤、返回所有仓库的群;keyword 模糊匹配 group_name/group_id、groupType 筛选、limit 默认20上限100、created_at 倒序、软删自动排除均不变",
|
||||
"methods/system.json 站内信分组(module=inbox):inbox.group.quickList 描述删除「warehouseId 由服务端从登录上下文自动注入」,补 store_id 口径(可选正整数,对应 warehouse_id,不传返回全部);params 新增 store_id(number|string,可选);errors 400 由「warehouseId 无效」改为「store_id 无效」;headers 描述改为登录凭证口径(不再从中解析 warehouseId 仓库上下文);版本 0.3.54 -> 0.3.55(docMeta.version),updatedAt 保持 2026-08-30",
|
||||
"AI_METHOD_ROUTING.md 5.2 节:quickList 底层实现补 store_id 口径;仓库口径拆分为「quickList 透传前端 store_id(不再服务端注入)/ members 仍从 ctx.user.store_id 服务端注入」",
|
||||
"权限不变:仍需 566(inbox.group.quickList,isNeedAuth=true、isNeedLogin=true),未执行权限变更",
|
||||
"本次仅文档同步,业务代码由 wms-dev-agent 完成,未修改 app/ 下任何代码,未执行数据库/Redis 操作,未运行测试"
|
||||
],
|
||||
"module": "inbox"
|
||||
},
|
||||
{
|
||||
"version": "2026.08.30-report-delivery-plan-name-field",
|
||||
"date": "2026-08-30",
|
||||
"type": "enhanced",
|
||||
"summary": "投递计划新增计划名称 name 字段:report.deliveryPlan.save 新增可选入参 name(string|null;未传不覆盖,null/空串/全空白归一化为 null 显式清空,非空 trim 后 ≤100 超长报错),save 成功响应与 report.deliveryPlan.list 列表项新增 name 字段(缺省空串);name 仅展示字段,不参与幂等/关联逻辑。",
|
||||
"methods": [
|
||||
"report.deliveryPlan.save",
|
||||
"report.deliveryPlan.list"
|
||||
],
|
||||
"notes": [
|
||||
"app/service/systems/reportDelivery.js:新增 normalizePlanName(value)(undefined=未传不覆盖返回 undefined;null/空串/全空白返回 null 显式清空;非空 trim 且 ≤PLAN_NAME_MAX_LENGTH(100),超长抛「计划名称 name 长度不能超过 100 字符」);savePlan 仅在 name !== undefined 时规范化并写入 payload.name,更新时不误清空",
|
||||
"app/service/systems/reportDelivery.js planToView:响应视图新增 name: String(plan.name || '')(缺省空串),save 成功响应与 list 列表项均带该字段",
|
||||
"app/service/systemMethods/report/deliveryPlan.js save:解构透传 name(仅入参存在时附加 saveArgs.name,保持旧调用形状与既有回归断言一致)",
|
||||
"wms_report_delivery_plan 新增 name 列(STRING(100) allowNull,comment「计划名称(前端展示用,缺省时可用报表名称兜底)」;迁移 20260830130000-add-name-to-wms-report-delivery-plan 已完成);name 仅展示字段,不参与 store_id+report_definition_id 幂等/关联逻辑",
|
||||
"methods/system.json 通用报表模块:report.deliveryPlan.save params 新增 name(string|null)、response 新增 name(缺省 '')、errors 新增「计划名称 name 长度不能超过 100 字符」;report.deliveryPlan.list response children 新增 name;版本 0.3.53 -> 0.3.54(docMeta.version),updatedAt 保持 2026-08-30",
|
||||
"docs/report-config-guide.md 第 5 节投递计划补 name 字段口径与保存示例;AI_METHOD_ROUTING.md 5.1 节补 name 变更条目与最新 changes 版本",
|
||||
"权限口径不变:report.deliveryPlan.save/list 仍 isNeedAuth=true(未声明免权限),仅执行 npm run permission:sync:system-api -- --dry-run 预演(不 apply、不扩任何角色授权)",
|
||||
"本次仅文档同步,未修改 app/ 下业务代码,未执行数据库/Redis 操作,未运行测试"
|
||||
],
|
||||
"module": "report"
|
||||
},
|
||||
{
|
||||
"version": "2026.08.30-report-type-list-merge-into-definition",
|
||||
"date": "2026-08-30",
|
||||
"type": "changed",
|
||||
"summary": "枚举接口并入 definition:report.type.list → report.definition.typeList。免权限只读的类型注册清单查询由独立模块 report/type.js 并入 report/definition.js(typeList 方法,systemInit 声明 _noNeedRight/_noNeedAuth/_noNeedLog='typeList',仅要求登录);同模块 save/list/delete 仍需授权。",
|
||||
"methods": [
|
||||
"report.definition.typeList",
|
||||
"report.type.list"
|
||||
],
|
||||
"notes": [
|
||||
"app/service/systemMethods/report/type.js 已删除;app/service/systemMethods/report/definition.js 新增 typeList(data) 方法(无必填入参,忽略请求体),返回 success('ok', { list }),list 由 systems/report.js listRegisteredTypes() 提供(QUERIES.describe() 注册表全量描述,当前仅 stockFlow)",
|
||||
"权限口径:definition.js systemInit 声明 _noNeedRight/_noNeedAuth/_noNeedLog='typeList'(免权限/免鉴权/免审计日志,仅要求登录);同模块 save/list/delete 未声明免权限,仍需授权(isNeedAuth=true),同一模块内权限口径差异已在 method description 中注明",
|
||||
"methods/system.json 通用报表模块:删除 report.type.list,新增 report.definition.typeList(isNeedAuth=false、isNeedLogin=true、无入参;响应 { list: [{key,title,description,window:{dayCount,cutoverHour},fields:[{key,label,type,computed?,asText?,children?}]}] },字段口径与原 report.type.list 一致);版本 0.3.52 -> 0.3.53(docMeta.version),updatedAt 保持 2026-08-30",
|
||||
"docs/report-config-guide.md:report.type.list 全部替换为 report.definition.typeList(第 2/7 节标题、字段口径说明、请求/响应示例与设计器接口链),实现链由 report/type.js 改为 report/definition.js;AI_METHOD_ROUTING.md report 能力清单更新(report.definition.typeList → definition.js typeList)",
|
||||
"权限仅执行 npm run permission:sync:system-api -- --dry-run 预演(不 apply、不扩任何角色授权)",
|
||||
"本次仅文档同步(含文档脚本 update-api-doc.cjs 的 deleteMethods 能力扩展与缩进检测修正),未修改 app/ 下业务代码,未执行数据库/Redis 操作,未运行测试"
|
||||
],
|
||||
"module": "report"
|
||||
},
|
||||
{
|
||||
"version": "2026.08.30-report-definition-model-refactor",
|
||||
"date": "2026-08-30",
|
||||
"type": "changed",
|
||||
"summary": "报表定义模型重构:code→id 关联、type/fields 极简配置、注册表 stockFlow、新增 report.type.list。破坏性变更:report.generate/report.meta/report.deliveryPlan.* 的 report_code 入参全部替换为 report_id(=报表定义ID,兼容 reportId 驼峰),前端需同步改 report_id。",
|
||||
"methods": [
|
||||
"report.generate",
|
||||
"report.meta",
|
||||
"report.type.list",
|
||||
"report.definition.save",
|
||||
"report.definition.list",
|
||||
"report.definition.delete",
|
||||
"report.deliveryPlan.save",
|
||||
"report.deliveryPlan.list",
|
||||
"report.deliveryLog.list"
|
||||
],
|
||||
"notes": [
|
||||
"模型重构(app/model/report_definition.js):移除 code/scope/description 与 output_config/source_config/sheet_config 三段 JSON 配置列,改为 name/type/file_name/fields/is_enabled/remark + 主键 id(唯一性由 id 承担,删除 uk_code);投递计划/记录表外键由 report_code 改为 report_definition_id,投递记录新增 report_name 名称快照",
|
||||
"app/service/systemMethods/report.js:generate/meta 入参 report_code 改为 report_id(reportId 驼峰优先);meta 响应由 report_code/name/scope/query/window/fields 改为 report_id/name/type/file_name/window/fields(fields 新增 selected 勾选标记与 asText 标记);generateTaskProgress 不变",
|
||||
"新增 app/service/systemMethods/report/type.js:report.type.list 免权限只读(systemInit 声明 _noNeedRight/_noNeedAuth/_noNeedLog 含 list,仅要求登录),返回注册类型清单 [{key,title,description,window:{dayCount,cutoverHour},fields:[{key,label,type,computed,asText,children}]}];当前仅注册 stockFlow(标题「库存变化以及补货报表」)",
|
||||
"app/service/systemMethods/report/definition.js:save 入参 {id?,name,type,file_name/fileName,fields,is_enabled,remark}(type 必须命中注册表、fields 必须为该类型注册字段子集,非法 key 报可读错误并列出可用字段;新增必填 type/file_name/fields);list where 改 name/type/is_enabled,sort 白名单 id/name/type/is_enabled/created_at/updated_at;delete 入参 id,引用拦截按 report_definition_id 统计启用中计划",
|
||||
"app/service/systems/report.js:新增 listRegisteredTypes/resolveTypeEntry/validateTypeFields,saveDefinition/listDefinitions/deleteDefinition 按 id 重写;渲染由 app/lib/report/render.js renderSheetByType 按类型硬编码字段规格完成(asText 由类型字段规格硬编码自动应用,string 字段 asText=true 时落地文本单元格),sheet_config 已删除",
|
||||
"app/service/systems/reportDelivery.js:savePlan/listPlans/listLogs 关联键由 report_code 改为 report_definition_id,listLogs 响应新增 report_name 快照;幂等键与唯一索引 uk_store_report_definition 同步改为 report_definition_id",
|
||||
"methods/system.json 通用报表模块:report.generate/report.meta/report.definition.save/report.definition.list/report.definition.delete/report.deliveryPlan.save/report.deliveryPlan.list/report.deliveryLog.list 8 个 method 按新形态重写,新增 report.type.list(report.generateTaskProgress 不受影响保持原样);版本 0.3.51 -> 0.3.52(docMeta.version),updatedAt 保持 2026-08-30",
|
||||
"docs/report-config-guide.md 整体改写(注册类型 stockFlow 标题/描述/16 字段表、report.type.list 用法、definition 保存示例 fileName+type+fields、plan 用 report_id、删除 sheet_config/asText 旧说明并按新渲染规则改写);AI_METHOD_ROUTING.md report 能力清单刷新",
|
||||
"权限口径:report.type.list 免权限(isNeedAuth=false);其余 report.* 沿用既有授权口径(管理类接口 isNeedAuth=true);仅执行 npm run permission:sync:system-api -- --dry-run 预演,未 apply、未扩任何角色授权",
|
||||
"本次仅文档同步,未修改 app/ 下任何代码,未执行数据库/Redis 操作,未运行测试"
|
||||
],
|
||||
"module": "report"
|
||||
},
|
||||
{
|
||||
"version": "2026.08.30-order-export-create-channel-column",
|
||||
"date": "2026-08-30",
|
||||
"type": "enhanced",
|
||||
"summary": "订单导出(order.export)waybill/item 两种导出模式在「平台」列之后新增导出列「来源」(字段 create_channel,中文取值:手工单/接口/奇门/出库转单);该列已自动纳入导出表头白名单 ORDER_EXPORT_ALL_COLUMN_HEADERS(waybill/item 两模式列头并集),export_columns/exportColumns 入参已支持传「来源」,不传或空数组时默认输出全部列。",
|
||||
"methods": [
|
||||
"order.export"
|
||||
],
|
||||
"notes": [
|
||||
"app/service/systems/order_export.js:ORDER_EXPORT_COLUMNS(waybill 模式)与 ORDER_EXPORT_ITEM_COLUMNS(item 模式)均在「平台」(sys_platform_name)之后新增 { header: '来源', key: 'create_channel', width: 12 }",
|
||||
"ORDER_EXPORT_ALL_COLUMN_HEADERS 为 waybill/item 两模式列头并集(Object.freeze(new Set(...))),「来源」在列配置登记后自动可用:export_columns/exportColumns 传「来源」合法(校验不区分导出模式),不传或空数组时输出全部列(含来源)",
|
||||
"取值翻译:app/service/systemMethods/order/base.js CREATE_CHANNEL_LABELS = { MANUAL: '手工单', API: '接口', QM: '奇门', STOCKOUT: '出库转单' },formatCreateChannelLabel 未命中映射时原样返回 create_channel 原文",
|
||||
"methods/system.json:order.export 的 export_columns/exportColumns 参数描述中枚举由 51 个更新为 52 个(在「平台」之后插入「来源」),并补充来源列取值、位置(平台列之后)与两种模式均输出的说明;order.exportTaskProgress 无导出列枚举内容,无需改动",
|
||||
"methods/system.json 版本 0.3.50 -> 0.3.51(docMeta.version),updatedAt 2026-08-29 -> 2026-08-30",
|
||||
"本次仅文档同步,业务代码由 wms-dev-agent 完成,未修改 app/ 下任何代码,未执行数据库/Redis 操作,未运行测试"
|
||||
],
|
||||
"module": "order.index"
|
||||
},
|
||||
{
|
||||
"version": "2026.08.29-waybill-warehouse-waybillCode-array-exact-match",
|
||||
"date": "2026-08-29",
|
||||
"type": "enhanced",
|
||||
"summary": "运单列表与导出接口的 where.waybillCode 支持字符串数组精确匹配:waybill.warehouse.list / waybill.warehouse.export 的 where.waybillCode 由「仅字符串模糊搜索」扩展为「字符串模糊搜索(LIKE '%值%',向后兼容)/ 字符串数组精确匹配(Op.in,元素自动 trim 并过滤空值,空数组或全空值不加该筛选条件)」,修复此前数组入参被逗号拼接后做 LIKE 导致搜索无结果的问题。",
|
||||
"methods": [
|
||||
"waybill.warehouse.list",
|
||||
"waybill.warehouse.export"
|
||||
],
|
||||
"notes": [
|
||||
"app/service/systems/waybill.js list() 第 226-235 行:where.waybillCode 为数组时先逐元素 String 化并 trim、过滤空值,非空则 waybill_code = { [Op.in]: waybillCodeList } 精确匹配;字符串时保持 waybill_code = { [Op.like]: '%trim%', } 模糊匹配(向后兼容)",
|
||||
"export 的筛选条件构建(第 767-776 行)与 list 逻辑一致:数组 Op.in 精确匹配、字符串 Op.like 模糊匹配",
|
||||
"修复前行为:数组入参会被逗号拼接后进入 LIKE 分支,导致搜索无结果;修复后数组元素 trim 并过滤空值,空数组/全空值不加 waybill_code 筛选条件",
|
||||
"methods/system.json:waybill.warehouse.list 与 waybill.warehouse.export 的 where.waybillCode 参数 type 由 string 更新为 string|string[],description 补充字符串模糊搜索与字符串数组精确匹配(元素 trim、过滤空值)规则",
|
||||
"methods/system.json 版本 0.3.49 -> 0.3.50(docMeta.version),updatedAt 保持 2026-08-29",
|
||||
"本次仅文档同步,业务代码已由开发侧修复(app/service/systems/waybill.js),未修改 app/ 下任何代码,未执行数据库/Redis 操作"
|
||||
],
|
||||
"module": "waybill.warehouse"
|
||||
},
|
||||
{
|
||||
"version": "2026.08.29-order-packing-quickWhere-short-kw-guard",
|
||||
"date": "2026-08-29",
|
||||
"type": "enhanced",
|
||||
"summary": "order.packing.list 的 where.quickWhere 运单号降级模糊新增关键词长度校验:精确未命中后仅当 trim 后关键词长度 ≥ 4(QUICK_WHERE_WAYBILL_FUZZY_MIN_LENGTH)才降级 LIKE '%kw%' 模糊查询;长度 < 4 的短词(含单字符)禁止降级、运单号解析直接返回空结果(避免 %短词% 误命中海量历史单号);波次号模糊逻辑不变。",
|
||||
"methods": [
|
||||
"order.packing.list"
|
||||
],
|
||||
"notes": [
|
||||
"app/service/systems/order_packing.js 第 12 行模块常量 QUICK_WHERE_WAYBILL_FUZZY_MIN_LENGTH = 4:注释说明短于该长度的输入(如单字符 \"7\")没有模糊搜索意义且 %短词% 极易误命中海量历史单号(实测 \"7\" 可命中 24149 行),因此禁止短词降级进入 %kw% 模糊分支",
|
||||
"list() 的 where.quickWhere 分支:波次号直接 LIKE '%kw%' 模糊不变;运单号先按「完整单号等值 + 剥离分段后缀主体等值 + 主体前缀 LIKE '主体-%'」精确集合查询 wms_order_express,第 206 行条件 expressRecords.length === 0 && kw.length >= QUICK_WHERE_WAYBILL_FUZZY_MIN_LENGTH 才降级 waybill_code LIKE '%kw%';短词(长度 < 4)不进入模糊分支,运单号解析保持空结果(仅保留波次号模糊条件)",
|
||||
"list() JSDoc 第 64 行 where.quickWhere 描述已同步:精确未命中且关键词长度≥4 时才降级模糊,短词禁止降级避免误命中",
|
||||
"methods/system.json:order.packing.list 的 where.quickWhere 参数描述补充「精确未命中且关键词长度 ≥ 4 才降级 %kw% 模糊;长度 < 4 短词不降级、直接返回空;波次号模糊不变」规则",
|
||||
"methods/system.json 版本 0.3.48 -> 0.3.49(docMeta.version),updatedAt 保持 2026-08-29",
|
||||
"本次仅文档同步,业务代码由 wms-dev-agent 完成,未修改 app/ 下任何代码,未执行数据库/Redis 操作"
|
||||
],
|
||||
"module": "order.packing"
|
||||
},
|
||||
{
|
||||
"version": "2026.08.29-wave-batchCancel-pick-status-guard",
|
||||
"date": "2026-08-29",
|
||||
"type": "enhanced",
|
||||
"summary": "取消波次增加拣货状态校验:order.wave.batchCancel 提交前新增两道业务校验(code 400)——波次内存在拣货中或拣货完成(pick_status 为 padding/fin)的订单、或波次状态已进入拣货及后续环节(wms_wave_batch.wave_status >= 3)时禁止取消波次;runBatchCancelTask 异步兜底命中上述条件跳过该波次并继续处理其余波次;order.wave.batchCancelTaskProgress 任务结果新增 skipped_wave_ids / skipped_wave_count / skipped_waves 字段。",
|
||||
"methods": [
|
||||
"order.wave.batchCancel",
|
||||
"order.wave.batchCancelTaskProgress"
|
||||
],
|
||||
"notes": [
|
||||
"app/service/systemMethods/order/wave.js batchCancel():活动拣货任务校验后新增两道 400 校验——① getOrderModel('pendingOrder', warehouseId) 查询波次内 pick_status IN ('padding','fin') 的订单,命中返回「波次内存在已拣货完成或拣货中的订单,禁止取消波次」(附 wave_ids 与最多前 20 个 order_ids);② 查询 wms_wave_batch 中 wave_status >= 3 的波次,命中返回「波次已进入拣货或后续环节,禁止取消波次」(附 wave_ids)",
|
||||
"runBatchCancelTask():目标波次查询新增 wave_status 列;逐波次处理时先校验 wave_status >= 3(跳过明细 reason=wave_status_blocked,附 wave_status),再在事务内校验波次内 pick_status IN ('padding','fin') 的订单(reason=picked_orders_exist,附 picked_order_count),命中则回滚事务、跳过该波次并继续处理其余波次;无目标波次时 result 返回空 skipped_wave_ids 数组与 skipped_wave_count=0",
|
||||
"任务结果:success 与 failed 终态的 result 均新增 skipped_wave_ids(被跳过波次 ID 列表)、skipped_wave_count(数量)、skipped_waves(明细数组,字段 wave_id/wave_no/reason/wave_status/picked_order_count,其中 wave_status 仅 reason=wave_status_blocked、picked_order_count 仅 reason=picked_orders_exist)",
|
||||
"methods/system.json:order.wave.batchCancel 的 description 补充校验规则说明、errors 新增两条 400 描述;order.wave.batchCancelTaskProgress 的 description 与 response 补充 skipped_wave_ids / skipped_wave_count / skipped_waves 字段说明(含 children 明细),并同步更新 result 字段描述(补充 ids/affected_wave_ids/affected_order_count/skipped_* 等字段枚举)",
|
||||
"methods/system.json 版本 0.3.47 -> 0.3.48(docMeta.version),updatedAt 保持 2026-08-29",
|
||||
"本次仅文档同步,业务代码改动已完成(git diff app/service/systemMethods/order/wave.js),未修改 app/ 下任何代码,未执行数据库/Redis 操作"
|
||||
],
|
||||
"module": "order.wave"
|
||||
},
|
||||
{
|
||||
"version": "2026.08.29-order-packing-waybill-code-match",
|
||||
"date": "2026-08-29",
|
||||
"type": "enhanced",
|
||||
"summary": "打包获取订单与订单快捷搜索的运单号匹配规则收敛:order.packing.list 的 where.waybill_code 由默认「%值%」模糊匹配改为「完整单号等值 + 剥离 -1-1- 分段后缀后主体单号等值 + 主体前缀 LIKE '主体-%'」精确匹配(不再支持部分单号模糊,无匹配返回空);quickWhere 运单号解析先按上述等值集合精确匹配、精确未命中才降级为 %kw% 模糊查询,波次号模糊逻辑不变;order.deliveryOrder.quickSearch 运单号条件同步扩展为「完整等值 + 主体等值 + 主体前缀 LIKE」,运单号不再落入模糊分支,发货单号/原始平台订单号模糊匹配不变(平台交易单号 pay_no 仅回显不参与匹配,修正文档过期描述)。",
|
||||
"methods": [
|
||||
"order.packing.list",
|
||||
"order.deliveryOrder.quickSearch"
|
||||
],
|
||||
"notes": [
|
||||
"新增公共工具 app/lib/waybill_code.js:stripWaybillSegmentSuffix 剥离运单号尾部一单多件包裹序号分段(正则 /(?:-\\d+){2,}-?$/,如 JDX057941864338-1-1- → JDX057941864338,无分段原样返回);escapeLikeWildcards 转义 like 通配符 % _ \\,保证主体前缀匹配的主体部分被等值比较",
|
||||
"app/service/systems/order_packing.js list():where.waybill_code 通过 wms_order_express 解析 order_id(wms_pack_task.waybill_code 通常为空),条件集合为 [waybill_code=完整单号, waybill_code=剥离后缀后主体, waybill_code LIKE '转义主体-%'] 的 OR 组合,命中后按 order_id IN 过滤,无命中强制空结果(queryWhere.id=-1);不再使用 like '%值%' 模糊匹配",
|
||||
"order_packing.js list() 的 where.quickWhere:波次号直接 LIKE '%kw%' 模糊不变;运单号解析先按上述精确集合查询,expressRecords 为空才降级为 waybill_code LIKE '%kw%'(兼容输入部分单号场景);团购按 wave_no、散单按 order_id 查询链路不变",
|
||||
"app/service/systemMethods/order/deliveryOrder.js quickSearch():express 表 OR 条件中运单号扩展为 [完整等值, 主体等值, 主体前缀 LIKE '主体-%'],运单号不再落入 %kw% 模糊分支;delivery_order_code / source_order_codes 仍为 LIKE '%kw%' 模糊匹配;pay_no 不在搜索条件中(仅第三步订单详情输出回显),原文档「平台交易单号 pay_no(模糊)」为过期描述已按实现修正",
|
||||
"methods/system.json:order.packing.list 的 where.waybill_code 描述由「运单号(模糊匹配)」改为完整单号/剥离分段后缀主体/主体前缀三种匹配规则说明,quickWhere 描述补充「先精确后降级模糊」优先级;order.deliveryOrder.quickSearch 的 description 与 keyword 参数描述同步修正(express 表匹配口径、pay_no 仅回显);quickSearch 条目补充空 headers 数组以符合文档校验结构",
|
||||
"methods/system.json 版本 0.3.46 -> 0.3.47(docMeta.version),updatedAt 保持 2026-08-29",
|
||||
"本次仅文档同步,业务代码由 wms-dev-agent 完成,未修改 app/ 下任何代码,未执行数据库/Redis 操作"
|
||||
],
|
||||
"module": "order.packing"
|
||||
},
|
||||
{
|
||||
"version": "2026.08.29-return-unpack-max-record-minutes",
|
||||
"date": "2026-08-29",
|
||||
"type": "enhanced",
|
||||
"summary": "仓库设置新增「拆包最大录制时长」配置 return_unpack_max_record_minutes(分钟,默认 5,min 1):returnUnpack.submit 提交确认时,结束时间超过 开始时间+配置上限 时自动截断为上限时间点",
|
||||
"methods": [
|
||||
"setting.warehouse.getSettings",
|
||||
"setting.warehouse.getFieldMeta",
|
||||
"setting.warehouse.saveSettings",
|
||||
"returnUnpack.submit"
|
||||
],
|
||||
"notes": [
|
||||
"app/service/systems/setting/warehouse.js WAREHOUSE_SETTING_FIELDS 新增 return_unpack_max_record_minutes(名称:拆包最大录制时长(分钟),type integer,非必填,默认 5,min 1,描述:超过上限时提交的结束时间自动截断为开始时间+上限),与 single_order_pack_max_minutes(默认 3)/ group_order_pack_max_minutes(默认 40)并列;getFieldMeta 自动返回该字段元信息",
|
||||
"app/model/store.js DEFAULT_SUBJECT_CONFIG 增加 return_unpack_max_record_minutes: 5;normalizeSubjectConfig 非法值(非正整数)抛「subject_config.return_unpack_max_record_minutes 必须是大于 0 的整数」,空值回退默认 5",
|
||||
"app/service/systems/return_unpack.js submit() 新增私有方法 _resolveSubmitEndTime:候选 end_time 超过 start_time + 配置上限分钟时截断为上限时间点并记录 info 日志;配置读取 ctx.service.systems.deliveryOrder.getStoreSubjectConfig,配置非法/读取失败/start_time 缺失时不约束;其余行为不变(completed 终态、回写 is_back=1、货主群通知等均不变)",
|
||||
"methods/system.json:setting.warehouse.getSettings 响应与 setting.warehouse.saveSettings 入参新增 subject_config.return_unpack_max_record_minutes 字段文档;returnUnpack.submit description 与响应 record 补充「结束时间超过仓库配置的拆包最大录制时长上限时自动截断为开始时间+上限」语义;getFieldMeta 为通用字段元信息结构,无逐字段清单,无需改动",
|
||||
"向后兼容:新增字段可选,不影响既有仓库设置读写;本次仅文档同步,业务代码由 wms-dev-agent 完成",
|
||||
"methods/system.json 版本 0.3.45 -> 0.3.46(docMeta.version),updatedAt 保持 2026-08-29"
|
||||
],
|
||||
"module": "returnUnpack"
|
||||
},
|
||||
{
|
||||
"version": "2026.08.29-returnUnpack.export",
|
||||
"date": "2026-08-29",
|
||||
"type": "enhanced",
|
||||
"summary": "新增退回拆包导出与进度查询接口:returnUnpack.export(提交异步导出任务,入参 where/sort 语义与 returnUnpack.list 一致,warehouse_id 由服务端注入 ctx.user.store_id;后台生成双 Sheet Excel:Sheet1 正常退回运单号列表、Sheet2 明细表并上传)与 returnUnpack.exportTaskProgress(按 task_id 查询任务进度与下载链接,未命中返回 status=not_found)。任务缓存 Redis TTL 30 分钟,状态口径 submitted→running→数据拉取(10~30)→明细拉取(30~50)→Excel(55~90)→上传(92)→success(100),失败 failed+error。两接口免权限免日志口径与 order.export 一致(isNeedAuth=false、isNeedLogin=true)。",
|
||||
"methods": [
|
||||
"returnUnpack.export",
|
||||
"returnUnpack.exportTaskProgress"
|
||||
],
|
||||
"notes": [
|
||||
"app/service/systemMethods/returnUnpack.js 新增 export/exportTaskProgress 与任务缓存辅助方法(generateExportTaskId/normalizeExportTaskId/setExportTaskProgress/getExportTaskProgress):缓存键前缀 return_unpack_export_task_,Redis TTL 1800 秒(30 分钟);export 提交后 setImmediate 异步执行并逐阶段回写进度;exportTaskProgress 入参兼容 task_id/taskId,download_url 从 result.url/cdnUrl/cosUrl/fileKey 兜底取(代码中同时兼容 cndUrl 拼写);task_id 为空或缓存未命中返回 status=not_found(正常响应非报错)",
|
||||
"systemInit 免权限声明:_noNeedRight/_noNeedAuth/_noNeedLog 均含 export,exportTaskProgress(异步任务模式,与 order.export 口径一致,无 wms_permission 记录);_noNeedLogin 不含(两接口均需登录,isNeedAuth=false、isNeedLogin=true)",
|
||||
"app/service/systems/return_unpack.js 新增 exportUnpack:复用 _buildListWhere/_buildListOrder(与 list 语义一致)并强制 warehouse_id=注入值;主表全量分页拉取(每页 500,无行数上限),明细按 unpack_id 分批(每批 100)拉取;货主名批量映射 wms_store.company_name、快递类型映射 wms_order_express.logistics_name(各自独立 try/catch,解析失败降级为空字符串不阻断导出)",
|
||||
"双 Sheet 结构:Sheet1「正常退回运单号列表」列=货主/快递号/商品类数/商品总数/记录人员/记录日期/开始时间/结束时间/是否原单(是/否)/快递类型/自定义店铺/平台单号;Sheet2「明细表」列=货主/快递号/商品名称/商品编码/条码/颜色/规格/数量/是否残次(是/否)/记录人员ID/记录日期/备注/是否原单(是/否)/快递类型/自定义店铺/平台单号;颜色取自明细 product_snapshot.sku_property 中「颜色:xxx」片段(兜底 spec 字段),无颜色信息为空;是否原单按 order_express_id 有值输出是/否;是否残次按 product_status=damaged 输出是/否",
|
||||
"导出上传:ExcelJS 流式写入临时文件后经 systems.upload.uploadFile 上传(key=exports/return_unpack/{warehouseId}/{timestamp}_{token}.xlsx,mimetype xlsx,category=document),结果含 filename/url/fileKey/cdnUrl/cosUrl/current_count/total_count/total_details/sheet_count=2;Sheet1 不加 status 过滤(如需只导特定状态由调用方传 where.status)",
|
||||
"methods/system.json 退回拆包模块(module=returnUnpack)新增 returnUnpack.export 与 returnUnpack.exportTaskProgress 两个 method 条目(追加于 returnUnpack.delete 之后),版本 0.3.44 -> 0.3.45(docMeta.version),updatedAt 保持 2026-08-29",
|
||||
"权限说明:export/exportTaskProgress 免权限(无 wms_permission 记录),仅登录可用;本次仅文档、未扩任何角色授权,不执行权限同步 apply",
|
||||
"仅文档变更,未改任何业务代码、表结构,未执行数据库/Redis 操作"
|
||||
],
|
||||
"module": "returnUnpack"
|
||||
},
|
||||
{
|
||||
"version": "2026.08.29-report-channel-normalize-doc-audit",
|
||||
"date": "2026-08-29",
|
||||
"type": "docs",
|
||||
"summary": "渠道默认值归一化 inbox + 文档一致性校对:全量核对「通用报表模块」全部 report.* method(generate/generateTaskProgress/meta/deliveryPlan.save/list/deliveryLog.list/definition.save/list/delete)与当前实现(app/service/systemMethods/report.js 及 report/ 子目录、app/service/systems/report.js、app/service/systems/reportDelivery.js、模型 report_definition/report_delivery_plan/report_delivery_log、迁移 20260829170000),仅发现 report.deliveryPlan.list / report.deliveryLog.list 响应 channel 字段存在过期描述(wecom/inbox/link),已修正为仅 inbox;其余 method 的 params/response/errors 均与实现一致,无接口行为变化。",
|
||||
"methods": [
|
||||
"report.deliveryPlan.list",
|
||||
"report.deliveryLog.list"
|
||||
],
|
||||
"notes": [
|
||||
"迁移 database/migrations/20260829170000-normalize-report-channel-to-inbox.js:wms_report_delivery_plan / wms_report_delivery_log 的 channel 默认值 wecom → inbox、comment 收敛,存量 channel IN (wecom,link) 统一 UPDATE 为 inbox;模型同步(app/model/report_delivery_plan.js、app/model/report_delivery_log.js defaultValue: inbox)",
|
||||
"代码核对:app/service/systems/reportDelivery.js 的 DELIVERY_CHANNELS 收敛为 [inbox]、DEFAULT_CHANNEL=inbox;deliverByChannel 对非 inbox 渠道记录 warn 日志后按 inbox 兜底投递(不抛错);inbox 推送失败(success=false 或 push_status=3)立即经 ctx.service.inbox.message.retry 重推一次,重推失败进入 failed 退避重试(MAX_RETRY=3,退避 retry_count × 60s)",
|
||||
"修正点:report.deliveryPlan.list / report.deliveryLog.list 响应 channel 字段描述由「投递渠道:wecom/inbox/link」修正为「投递渠道:inbox(渠道已收敛,仅支持 inbox;历史数据已由迁移 20260829170000 归一化)」;仅文档描述修正,params/response 结构、错误码无任何变化",
|
||||
"report.definition.save 的 19 条错误、report.definition.list 排序白名单 id/code/name/scope/is_enabled/created_at/updated_at、notify_template(≤500,标签白名单 {time}/{url}/{report_name}/{biz_date})/notify_group_ids(正整数去重 ≤20,校验存在性排除软删)/notify_member_ids(非空字符串去重 ≤100)参数与校验规则均与代码一致,未改动",
|
||||
"report.generate/report.generateTaskProgress 免权限(_noNeedRight/_noNeedAuth 声明)、report.meta 免权限但保留审计日志(未列入 _noNeedLog)、report.deliveryPlan.*/report.deliveryLog.list/report.definition.* 需授权(isNeedAuth=true,未声明免权限)口径均与 systemInit 声明一致",
|
||||
"methods/system.json 版本 0.3.43 -> 0.3.44(docMeta.version),updatedAt 保持 2026-08-29",
|
||||
"配套文档核对:docs/report-config-guide.md 第 5 节渠道说明已与「仅 inbox + 兜底 + 重推」一致(补充迁移归一化说明);第 8 节 report.definition.save/list/delete 用法与实现一致;AI_METHOD_ROUTING.md 5.1 report 能力速查与路由说明已最新",
|
||||
"权限:仅执行 npm run permission:sync:system-api -- --dry-run 预演缺口,未执行 apply、未扩任何角色授权",
|
||||
"仅文档变更,未改任何业务代码、表结构,未执行数据库/Redis 操作"
|
||||
],
|
||||
"module": "report"
|
||||
},
|
||||
{
|
||||
"version": "2026.08.29-report-definition-management",
|
||||
"date": "2026-08-29",
|
||||
"type": "enhanced",
|
||||
"summary": "通用报表模块新增报表定义管理接口:report.definition.save/list/delete(wms_report_definition 管理侧 CRUD,均需登录且需鉴权 isNeedAuth=true,未扩任何角色授权)。save 按 code upsert(未传字段不覆盖),code 格式 ^[a-z][a-z0-9_]{1,63}$(长度 2-64)、name 必填 ≤100、scope 枚举 warehouse/store/open(默认 warehouse),output_config/source_config/sheet_config 三段 JSON 配置支持对象或 JSON 字符串,source_config.query 须为注册表已有查询器,sheet_config 列结构校验(static/expand/computed,expand pair 与查询器字段清单对齐),response 平铺 report_code;list 支持 where{code,name,scope,is_enabled}(code/name 模糊、scope/is_enabled 精确)/pagination/sort(白名单 id/code/name/scope/is_enabled/created_at/updated_at),response 全量字段含三段 JSON 配置;delete 按 code 软删(幂等),启用中的投递计划引用时拦截「存在 N 个启用的投递计划引用该报表,请先停用计划」。",
|
||||
"methods": [
|
||||
"report.definition.save",
|
||||
"report.definition.list",
|
||||
"report.definition.delete"
|
||||
],
|
||||
"notes": [
|
||||
"app/service/systemMethods/report/definition.js 新增:save/list/delete 仅做出口包装与参数解构(save 仅附加入参中存在的字段,undefined 不进入参数对象,保持「未传不覆盖」语义;list 经 prepareWhereContext 解析 where 后取 code/name/scope/is_enabled),业务逻辑下沉 app/service/systems/report.js saveDefinition/listDefinitions/deleteDefinition",
|
||||
"saveDefinition:code 规范化 trim 后校验(空/格式非法分别报「报表编码 code 不能为空」「报表编码 code 格式非法:须以小写字母开头,仅含小写字母/数字/下划线,长度 2-64」,正则 ^[a-z][a-z0-9_]{1,63}$);name trim 必填 ≤100;scope 枚举校验;JSON 字段仅非 undefined 时经 parseRequiredJson 解析(对象原样返回/JSON 字符串解析/其余报「<field> 解析失败:须为对象或合法 JSON 字符串」);source_config 的 query 必须为注册表已有查询器(resolveQueryKey 缺省 generic,未知报「未知的报表查询器: <key>」);sheet_config 经 validateDefinitionSheetConfig 校验列结构(columns 数组、列类型仅 static/expand/computed、static 列须有 field 或 value、computed 列须有 field 或 formatter、expand pair 须与查询器静态字段清单对齐否则报「sheet_config expand 列 pair 元素 '<key>' 不在查询器 <queryKey> 的字段清单中(可用: <keys>)」);is_enabled 仅 0/1;description/remark ≤500 截断",
|
||||
"upsert 细节:uk_code 唯一索引含 deleted_at,findOne 以 paranoid:false 完整查重;命中软删记录先 restore 再 update(restore 撞唯一索引报「存在多个同名已删除记录,无法自动恢复,请更换报表编码」);并发首次创建撞 SequelizeUniqueConstraintError 降级为重查并更新(查不到报「报表编码已存在,保存冲突,请重试」);保存成功返回 definitionToView 视图(JSON 字段解析为对象)",
|
||||
"listDefinitions:code/name LIKE 模糊(escapeLike 转义 \\%_)、scope 精确(非法报「scope 仅支持 warehouse/store/open,非法: <scope>」)、is_enabled 空值不过滤(Number 化 0/1);pagination page≥1、pageSize 夹取 1-200;sort 白名单 id/code/name/scope/is_enabled/created_at/updated_at(sortField/sortOrder 兼容 sort_field/sort_order 别名,非法字段回退 id DESC);findAll+count 并行,raw 行映射 definitionToView",
|
||||
"deleteDefinition:先按 report_code+enabled=1 统计 wms_report_delivery_plan 启用中引用(>0 报「存在 <N> 个启用的投递计划引用该报表,请先停用计划」),停用计划不阻断;再按 code paranoid:false 查定义(不存在报「报表定义不存在: <code>」,已软删幂等返回 deleted=1),否则 destroy 软删",
|
||||
"method 层统一 catch 后 this.fail(error.message):错误响应 code=0、flag=failure(与 report.meta 惯例一致);save/delete 成功响应将定义 code 平铺为 report_code(避免覆盖统一响应 code=1)",
|
||||
"systemInit 未声明 _noNeedLogin/_noNeedRight/_noNeedAuth 免权限 → 3 个接口均 isNeedAuth=true、isNeedLogin=true,仅通配符角色(超级管理员/仓库管理员)或后续 wms_permission 同步授权角色可用;本次仅文档、未扩任何角色授权,不执行权限同步 apply",
|
||||
"methods/system.json 通用报表模块(module=report)新增 3 个 method 条目(追加于 report.meta 之后),版本 0.3.42 -> 0.3.43",
|
||||
"配套文档:docs/report-config-guide.md 新增第 8 节「报表模板管理接口」;AI_METHOD_ROUTING.md 5.1 report 能力速查表登记 3 个新 method",
|
||||
"仅文档变更,未改任何业务代码,未执行数据库/Redis 操作"
|
||||
],
|
||||
"module": "report"
|
||||
},
|
||||
{
|
||||
"version": "2026.08.29-inbox-group-quick-list-members",
|
||||
"date": "2026-08-29",
|
||||
"type": "enhanced",
|
||||
"summary": "新增站内信群选择下拉接口:inbox.group.quickList(群快速查询,keyword 模糊匹配群名称/外部群ID、groupType 筛选 store/warehouse/express、limit 默认20上限100,warehouseId 服务端注入,无分页,按创建时间倒序)与 inbox.group.members(群成员筛选,groupId 必填,按外部群ID在消息表聚合去重成员取每 user_id 最新 user_name,keyword 过滤后截断,外部群ID为空返回空列表);新增 API 权限 566(quickList)/567(members),授权角色 8/26/28/29,两接口均需登录且需鉴权。",
|
||||
"methods": [
|
||||
"inbox.group.quickList",
|
||||
"inbox.group.members"
|
||||
],
|
||||
"notes": [
|
||||
"app/service/systems/inbox/group.js quickList:where 含 warehouse_id(服务端注入),keyword 对 group_name/group_id 双字段 LIKE 模糊匹配,limit 截断为 1-100(默认20),findAll 仅取 id/group_id/group_name/group_type/sub_type/is_blocked,按 created_at DESC,软删除由 paranoid 自动排除",
|
||||
"app/service/systems/inbox/group.js members:先按 id+warehouse_id 查 wms_inbox_group(不存在抛「群不存在或无权限操作」,id 无效抛「群ID无效」);externalGroupId 为空直接返回 {list:[]};再按外部群ID+仓库查 wms_inbox_message(最近 500 条按 id DESC,user_id 非空),Map 按 user_id 去重取首次(最新)user_name,keyword 在聚合结果上过滤 user_name/user_id,最后 slice(0, limit)",
|
||||
"app/service/systemMethods/inbox.js group.quickList/group.members 子入口:warehouseId 从 ctx.user.store_id 自动注入,不信任前端传值;inbox systemMethods 未声明 systemInit 免权限,两接口走标准 API 权限校验(isNeedAuth=true、isNeedLogin=true)",
|
||||
"权限迁移 database/migrations/20260829180000-add-inbox-group-select-permissions.js:固定权限 ID 566(inbox.group.quickList,API:群快速查询)/567(inbox.group.members,API:群成员列表),type=api,授权角色 26(仓库组-主管)/28(客服组-主管)/29(生产组-主管)/8(经理);超级管理员(7)/仓库管理员(2) 持 * 通配符自动拥有;INSERT IGNORE 幂等,角色权限数组追加后去重排序",
|
||||
"methods/system.json 站内信分组(module=inbox)新增 2 个 method 条目(追加于 inbox.group.messages 之后),版本 0.3.41 -> 0.3.42",
|
||||
"AI_METHOD_ROUTING.md 新增 5.2 inbox.group(站内信群管理)能力速查小节,登记两接口的实现文件/函数/登录/鉴权信息",
|
||||
"仅文档变更,未改任何代码,未执行数据库/Redis 操作"
|
||||
],
|
||||
"module": "inbox"
|
||||
},
|
||||
{
|
||||
"version": "2026.08.29-report-delivery-channel-converge",
|
||||
"date": "2026-08-29",
|
||||
"type": "changed",
|
||||
"summary": "报表投递渠道收敛:report.deliveryPlan.save 的 channel 收敛为仅支持 inbox(默认 inbox,移除 wecom/link,非法渠道报「投递渠道仅支持 inbox: <channel>」);历史 wecom/link 计划投递时按 inbox 兜底执行(warn 日志不抛错);inbox 推送失败立即经 inbox.message.retry 重推一次(ext_id 幂等复用消息记录),重推仍失败进入 failed 退避重试(MAX_RETRY=3,退避 retry_count × 60s)。",
|
||||
"methods": [
|
||||
"report.deliveryPlan.save"
|
||||
],
|
||||
"notes": [
|
||||
"app/service/systems/reportDelivery.js:DELIVERY_CHANNELS 收敛为 ['inbox'],DEFAULT_CHANNEL='inbox';savePlan 对 channel 规范化(trim+lowercase,缺省默认 inbox)后不在白名单则抛「投递渠道仅支持 inbox: <channel>」(原「投递渠道不合法(wecom/inbox/link)」文案已移除)",
|
||||
"deliverByChannel:rawChannel !== 'inbox' 时记录 warn 日志「计划投递渠道 <channel> 已弃用,按 inbox 兜底投递」后按 inbox 执行,不直接抛错(避免历史计划在 failed 退避循环中耗尽重试次数后永久卡死)",
|
||||
"inbox 推送失败判定双保险:pushResult.success=false 或消息记录回写 push_status=3;失败时复用 ctx.service.inbox.message.retry 重推一次(重置 push_status=0 异步重推,ext_id 幂等复用同一条消息记录不重复写);retry 自身抛错则抛「站内信推送失败且重推失败: <原因>」,交由上层 failed 退避循环(MAX_RETRY=3,退避 = retry_count × 60s)",
|
||||
"methods/system.json 通用报表模块:report.deliveryPlan.save 的 channel 参数枚举收敛为仅 inbox(默认 inbox)、响应 channel 字段说明同步收敛、errors 中渠道错误文案更新为「投递渠道仅支持 inbox: <channel>」;版本 0.3.40 -> 0.3.41",
|
||||
"配套文档:docs/report-config-guide.md 投递章节更新渠道说明(移除 wecom/link、历史渠道按 inbox 兜底、inbox 推送失败自动重推);AI_METHOD_ROUTING.md 同步补充渠道收敛说明与变更版本号",
|
||||
"授权说明:本次仅文档、未扩任何角色授权。report.deliveryPlan.save/list、report.deliveryLog.list 仍为需授权接口(isNeedAuth=true),不涉及权限同步操作"
|
||||
],
|
||||
"module": "report"
|
||||
},
|
||||
{
|
||||
"version": "2026.08.29-report-delivery-notify-template-targets",
|
||||
"date": "2026-08-29",
|
||||
"type": "enhanced",
|
||||
"summary": "报表投递新增文本通知与定向群/成员:report.deliveryPlan.save 新增可选参数 notify_template(≤500 字符,标签白名单 {time}/{url}/{report_name}/{biz_date},未知标签报错列出非法标签)、notify_group_ids(wms_inbox_group.id 正整数去重 ≤20,保存时校验存在性且排除软删,缺失报错列出缺失 ID)、notify_member_ids(外部 IM 用户 ID 非空字符串去重 ≤100);report.deliveryPlan.list 响应带出上述 3 个配置字段;report.deliveryLog.list 响应新增 notify_targets 投递目标快照({group_ids, member_ids, notify_text})。",
|
||||
"methods": [
|
||||
"report.deliveryPlan.save",
|
||||
"report.deliveryPlan.list",
|
||||
"report.deliveryLog.list"
|
||||
],
|
||||
"notes": [
|
||||
"app/service/systems/reportDelivery.js savePlan:notify_template/notify_group_ids/notify_member_ids 三个可选参数仅在入参存在(!== undefined)时生效,未传不进入 payload(更新时保持既有字段不动,不传参数行为与旧版完全一致)",
|
||||
"savePlan 校验:notify_template trim 后 ≤500 字符;notify_group_ids 正整数、去重升序、≤20,保存时 validateNotifyGroupExists 校验 wms_inbox_group 存在性(软删自动排除,不校验 is_blocked:被屏蔽群仍可选中,屏蔽属于发送时过滤维度);notify_member_ids 非空字符串、去重、≤100;两者支持数组或 JSON 字符串数组,非数组报「必须为数组」",
|
||||
"标签白名单渲染:app/lib/report/notifyTemplate.js ALLOWED_TAGS={time,url,report_name,biz_date},validateNotifyTemplate 提取 {xxx} 标签并列出非法标签,renderNotifyTemplate 仅替换白名单标签;{url} 为空时替换为兜底文案「文件生成中,稍后可在投递记录中查看」,不阻断投递",
|
||||
"发送链路:reportDelivery.deliverByChannel 投递完成后调用 sendNotifyIfConfigured(与渠道独立,link 渠道同样生效);未配置模板或未选任何群/成员返回 null(不发送);群多选按 wms_inbox_group 逐群推送(群维度协议字段单值),发送时过滤 is_blocked=1/软删/仓库维度不一致;成员 user_id 数组整体透传不循环拆发,选择群时随每个群推送携带,未选择群时单独一次仅成员推送;目标不可达或推送失败抛异常走失败退避重试",
|
||||
"快照:sendNotifyIfConfigured 返回 {group_ids(实际发送的内部群ID), member_ids, notify_text},markDelivered 随 delivered 写入 wms_report_delivery_log.notify_targets;listLogs 以 readJsonObject 读取并输出(未配置时为 null)",
|
||||
"app/service/systems/warehouseNotify.js pushSystemMessage 新增 userIds 参数(仅接受字符串数组,去重过滤空值),推送体 user_id 直接传数组(目标侧协议支持);向后兼容:不传 userIds 且传 group 时校验、幂等 ext_id、落库字段、推送体均与旧版一致;消息表 user_id 列不承载数组(避免超长截断),成员仅随推送体透传并记录在投递日志快照",
|
||||
"method 层 app/service/systemMethods/report/deliveryPlan.js save:仅当 notify_template/notify_group_ids/notify_member_ids 在入参存在时附加到 saveArgs(undefined 不进入参数对象),保持旧调用形状与既有回归断言一致",
|
||||
"授权说明:本次仅文档、未扩任何角色授权。report.deliveryPlan.save/list、report.deliveryLog.list 仍为需授权接口(isNeedAuth=true),不涉及权限同步操作",
|
||||
"methods/system.json 通用报表模块更新 3 个 method 的 params/response/errors(版本 0.3.39 -> 0.3.40);配套文档 docs/report-config-guide.md 投递章节新增「文本通知模板与定向群/成员」小节"
|
||||
],
|
||||
"module": "report"
|
||||
},
|
||||
{
|
||||
"version": "2026.08.29-report-meta",
|
||||
"date": "2026-08-29",
|
||||
"type": "enhanced",
|
||||
"summary": "新增 report.meta(免权限只读列元数据接口,供前端报表设计器拉取可用字段):按报表编码返回 wms_report_definition 的 report_code/name/scope/query 与窗口参数 window{dayCount,cutoverHour},以及查询器静态字段清单 fields(查询器模块挂载的 querier.fields,未挂载返回空数组),不执行真实数据查询。",
|
||||
"methods": [
|
||||
"report.meta"
|
||||
],
|
||||
"notes": [
|
||||
"app/service/systemMethods/report.js meta:入参 report_code/reportCode 双写法(驼峰优先),为空返回 fail「报表编码 report_code 不能为空」(flag=failure、code=0、HTTP 200);调用 systems/report.getMeta 后组装 {report_code, name, scope, query, window, fields}(getMeta 的 code 字段回显为 report_code)",
|
||||
"systemInit 声明:_noNeedRight/_noNeedAuth 含 meta(免权限 + 免仓库有效期鉴权,仅登录),_noNeedLogin 不含 meta(必须登录);_noNeedLog 未含 meta → meta 保留审计日志(generate/generateTaskProgress 不写审计日志,两者行为不同,已在接口文档与配置指南中如实标注)",
|
||||
"app/service/systems/report.js getMeta:读 wms_report_definition(is_enabled=1,不存在/停用抛「报表定义不存在或已停用: <code>」,经 controller 兜底为 HTTP 500 接口错误);window 由 app/lib/report/day_window.resolveWindowConfig 解析(默认 dayCount=7、cutoverHour=7,[D 07:00, D+1 07:00) 半开区间,source_config 可覆盖);fields 由 resolveQuerierFields 读取查询器模块静态字段 querier.fields(未挂载返回空数组)",
|
||||
"静态字段清单挂载方式:查询器模块以 FIELDS 常量挂载到导出函数(queries/sevenDayStockFlow.js 挂载 12 个顶层字段 stock_id/item_code/item_name/barcode/daily/ck_total/rk_total/available/total/pending/suggest/warn;daily 为数组类型含 ck/rk 子字段,suggest/warn 为 computed=true 格式化器预计算字段;queries/generic.js 未挂载,fields 返回空数组)",
|
||||
"授权说明:本次仅文档、未扩任何角色授权。report.meta 免权限(isNeedAuth=false),不涉及权限同步操作",
|
||||
"methods/system.json 通用报表模块分组新增 report.meta 登记(版本 0.3.38 -> 0.3.39);配套文档 docs/report-config-guide.md 新增 report.meta 小节,AI_METHOD_ROUTING.md 刷新 report.meta 条目"
|
||||
],
|
||||
"module": "report"
|
||||
},
|
||||
{
|
||||
"version": "2026.08.29-report-config-driven-generate-delivery",
|
||||
"date": "2026-08-29",
|
||||
"type": "enhanced",
|
||||
"summary": "新增配置驱动通用报表与货主定时投递接口:report.generate(提交报表导出异步任务,仅登录免权限)、report.generateTaskProgress(查询导出任务进度,仅登录免权限)、report.deliveryPlan.save/list(货主报表投递计划新增/更新与分页查询,需授权)、report.deliveryLog.list(投递记录审计分页查询,需授权)。",
|
||||
"methods": [
|
||||
"report.generate",
|
||||
"report.generateTaskProgress",
|
||||
"report.deliveryPlan.save",
|
||||
"report.deliveryPlan.list",
|
||||
"report.deliveryLog.list"
|
||||
],
|
||||
"notes": [
|
||||
"app/service/systemMethods/report.js:systemInit 声明 _noNeedRight/_noNeedAuth = generate,generateTaskProgress(免权限+免仓库有效期鉴权,仅登录);generate 的 warehouse_id 由服务端从登录上下文 ctx.user.store_id 自动注入,禁止前端传递;store_id 支持 store_id/storeId 双写法,<=0 视为不按货主过滤",
|
||||
"app/service/systemMethods/report/deliveryPlan.js 与 report/deliveryLog.js:systemInit 未声明免权限(_noNeedRight/_noNeedAuth 均为空),为需授权管理类接口;methods/system.json 中 isNeedAuth=true 已登记",
|
||||
"权限同步:本次仅写文档、未执行任何授权操作。report.deliveryPlan.save/list、report.deliveryLog.list 为需授权接口,后续请先执行 npm run permission:sync:system-api -- --dry-run 预演,再按标准流程授权;不扩大任何角色授权范围",
|
||||
"实现依赖:app/service/systems/report.js(getDefinition/resolveQuerier/buildWorkbookSheets/generate/generateBuffer)、app/service/systems/reportDelivery.js(savePlan/listPlans/listLogs/dispatch 投递编排)、app/lib/report/*(render/day_window/formatters 纯函数模块)、内置查询器注册表 app/service/systems/report/queries/index.js(sevenDayStockFlow/generic)",
|
||||
"报表配置驱动:wms_report_definition(app/model/report_definition.js)以 code/name/scope + output_config/source_config/sheet_config 三段 JSON 配置驱动,新报表优先加配置行、免发版;sheet_config 支持静态列/窗口展开列/计算列、headerRow1 的 {date} 模板、merges 绝对引用、style、rowFilter",
|
||||
"methods/system.json 新增「通用报表模块」分组(module=report,groupName=通用报表模块),登记 5 个 method 的参数(source=body)、响应与错误码;版本 0.3.37 -> 0.3.38",
|
||||
"配套文档:docs/report-config-guide.md 新增报表配置结构说明(三段 JSON 配置、列定义、{date} 模板、merges、style、rowFilter、查询器注册表与内置查询器口径假设);AI_METHOD_ROUTING.md 同步刷新 report 相关路由说明与服务清单"
|
||||
],
|
||||
"module": "report"
|
||||
},
|
||||
{
|
||||
"version": "2026.08.28-workbench-queryOrder-intercept-pack-flag",
|
||||
"date": "2026-08-28",
|
||||
"type": "enhanced",
|
||||
"summary": "workbench.business(queryOrder/query) 查询订单响应增强:order 对象新增 intercept_status 字段(拦截状态原始值,散单/团购均返回,与既有 pack_status 并列);散单(isSandan=1)时 order 额外返回 intercept_flag/pack_flag 两个 0/1 标志(拦截状态不等于 none 时 intercept_flag=1 否则 0,打包状态不等于 none 时 pack_flag=1 否则 0),团购不返回这两个标志;空值/null 统一归一化为 none。",
|
||||
"methods": [
|
||||
"workbench.business"
|
||||
],
|
||||
"notes": [
|
||||
"app/service/systems/workbench.js _queryOrder 步骤6:intercept_status/pack_status 空值/null 归一化为 none(String(v||'').trim() || 'none'),interceptFlag = 状态 !== none ? 1 : 0,packFlag 同理",
|
||||
"_queryOrder 响应 order 对象新增 intercept_status(原始值,散单/团购均返回),与既有 pack_status 并列,原始状态字段原样保留、不破坏既有调用方",
|
||||
"仅散单(isSandan===1)向 result.order 追加 intercept_flag/pack_flag;团购(isSandan===0)不追加这两个标志字段,pack_status/intercept_status 原始值仍原样返回",
|
||||
"methods/system.json workbench.business 同步补充 queryOrder/query 响应结构:order.intercept_status 字段说明、散单场景 order.intercept_flag/order.pack_flag 字段说明与取值语义(状态不等于 none 返回 1,否则返回 0)"
|
||||
],
|
||||
"module": "workbench"
|
||||
},
|
||||
{
|
||||
"version": "2026.08.28-storage-entry-quickInbound-is-virtual-inbound",
|
||||
"date": "2026-08-28",
|
||||
"type": "enhanced",
|
||||
"summary": "storage.entry.quickInbound 事务内回写 is_virtual_inbound(是否虚拟入库):有绑定收货单 → 0(非虚拟入库),无绑定收货单 → 1(虚拟入库),与 order_status=COMPLETED 同一事务写入;wms_entry_order 新增 is_virtual_inbound 字段(TINYINT(1) NOT NULL DEFAULT 0)",
|
||||
"methods": [
|
||||
"storage.entry.quickInbound"
|
||||
],
|
||||
"notes": [
|
||||
"app/service/systems/storage/entry.js quickInbound:eo.update 事务内新增 is_virtual_inbound 回写,值为 receivingIds.length > 0 ? 0 : 1(有绑定收货单 → 非虚拟入库,无绑定收货单 → 虚拟入库),与 order_status=COMPLETED、sync_status=SUCCESS 同一事务提交",
|
||||
"app/model/entry_order.js:wms_entry_order 新增 is_virtual_inbound 字段(TINYINT(1),allowNull:false,defaultValue:0,comment:是否虚拟入库:0=否 1=是)",
|
||||
"database/migrations/20260828100000-add-is-virtual-inbound-to-wms-entry-order.js:新增迁移(describeTable 已存在时跳过 addColumn),down 删除字段;迁移文件仅创建,本次文档任务未执行",
|
||||
"methods/system.json storage.entry.quickInbound 说明文字补充 is_virtual_inbound 判定规则;入参/出参不变(quickInbound 响应未返回该字段,list/get 查询白名单亦未包含该字段)"
|
||||
],
|
||||
"module": "storage.entry"
|
||||
},
|
||||
{
|
||||
"version": "2026.08.27-order-allocateStorage-allow-storage-location",
|
||||
"date": "2026-08-27",
|
||||
|
||||
@ -286,5 +286,80 @@
|
||||
"item_code 反查不到时回退明细条码,仍无则显示未知编码"
|
||||
],
|
||||
"module": "receiving"
|
||||
},
|
||||
{
|
||||
"version": "2026-08-28-warehouse-01",
|
||||
"date": "2026-08-28",
|
||||
"type": "fixed",
|
||||
"summary": "审核明细 Excel 文件名去中文(审核明细_ → receiving_review_),通知正文修正为「请及时提交入库单入库,入库单务必备注Rxx」,不再额外拼接明细文件行",
|
||||
"methods": [
|
||||
"notify.reply"
|
||||
],
|
||||
"notes": [
|
||||
"storage/receiving.js reviewReceiving:Excel 上传文件名改为 receiving_review_{单号}.xlsx,URL 不再含中文,无需转码",
|
||||
"sendReviewNotice:messageType 固定 text、不再传 url/fileName/mimeType,避免 notice 层追加「明细文件:文件名 链接」行;下载链接直接内嵌正文「审核明细下载:url」",
|
||||
"正文末尾改为「请及时提交入库单入库,入库单务必备注Rxx」,接收方只处理 content 字段,链接以文本形式可见"
|
||||
],
|
||||
"module": "receiving"
|
||||
},
|
||||
{
|
||||
"version": "2026-08-28-warehouse-02",
|
||||
"date": "2026-08-28",
|
||||
"type": "fixed",
|
||||
"summary": "审核明细商品编码反查增加兜底:无对应 wms_stock_store 时回退取 wms_stock_warehouse.item_code,避免部分商品无货主资料时编码缺失",
|
||||
"methods": [
|
||||
"notify.reply"
|
||||
],
|
||||
"notes": [
|
||||
"storage/receiving.js resolveReviewDetailItemCodeMap:先按 stock_id 反查 wms_stock_store.item_code,未命中的 system_product_id 兜底查 wms_stock_warehouse(deleted_at 为空)取 item_code",
|
||||
"两段反查均独立 try/catch,失败仅记日志不阻断审核通知主流程"
|
||||
],
|
||||
"module": "receiving"
|
||||
},
|
||||
{
|
||||
"version": "2026-08-28-warehouse-03",
|
||||
"date": "2026-08-28",
|
||||
"type": "fixed",
|
||||
"summary": "notice 群推送链路补齐 ext_data 透传:查群带回群扩展数据,pushSystemMessage 落库与推送均携带,对齐 pushSystemNotification 已有方式",
|
||||
"methods": [
|
||||
"notify.reply"
|
||||
],
|
||||
"notes": [
|
||||
"systems/notice/index.js findSubscribedGroups 返回群对象新增 ext_data 字段(取 inbox_group.ext_data)",
|
||||
"sendToWarehouseChannel 调 pushSystemMessage 时新增 extData=group.ext_data || null",
|
||||
"systems/warehouseNotify.js pushSystemMessage 新增 extData 入参:wms_inbox_message outbound 行 ext_data 落库,notify.reply 推送体 data.ext_data 透传(与 processor.writeOutboundReply 一致)"
|
||||
],
|
||||
"module": "receiving"
|
||||
},
|
||||
{
|
||||
"version": "2026-08-28-warehouse-04",
|
||||
"date": "2026-08-28",
|
||||
"type": "fixed",
|
||||
"summary": "修复通知消息幂等键吞消息:ext_id 加入事件维度,同一业务单不同事件各落一条 outbound 消息",
|
||||
"methods": [
|
||||
"notify.reply"
|
||||
],
|
||||
"notes": [
|
||||
"systems/notice/index.js sendToWarehouseChannel:extId 改为 businessId:event(同一收货单的创建/完成/审核事件各落一条 outbound 消息,不再被 sys:notice:{businessId}:{groupId} 幂等复用)",
|
||||
"findSubscribedGroups 查询增加 ORDER BY id ASC,保证取群顺序稳定",
|
||||
"systems/warehouseNotify.js:uniqueExtId 超过 VARCHAR(128) 时降级 md5 哈希兜底",
|
||||
"线上案例:R20691023 审核消息因与「正在收货」共用 ext_id 被幂等吞掉,消息表无审核记录"
|
||||
],
|
||||
"module": "receiving"
|
||||
},
|
||||
{
|
||||
"version": "2026-08-28-warehouse-05",
|
||||
"date": "2026-08-28",
|
||||
"type": "added",
|
||||
"summary": "收货单创建/首次绑定货主通知(receiving_store_bound)新增收货人行:优先取 creator_snapshot 创建人姓名,回退当前操作人,无值显示无",
|
||||
"methods": [
|
||||
"notify.reply"
|
||||
],
|
||||
"notes": [
|
||||
"storage/receiving.js 新增 resolveReceivingCreatorName:解析 creator_snapshot(字符串 JSON 或对象)取 name/employees_name/real_name,回退 ctx.user.employees_name",
|
||||
"sendStoreBoundNotice 模板在车牌/快递行后增加「收货人:姓名/无」,修复线上显示「收货人:{}」的空对象问题",
|
||||
"三个触发点(create/bindStore/updateReceivingStats)的 receiving 快照均补充 creator_snapshot 字段"
|
||||
],
|
||||
"module": "receiving"
|
||||
}
|
||||
]
|
||||
|
||||
2299
methods/system.json
2299
methods/system.json
File diff suppressed because it is too large
Load Diff
@ -1,4 +1,9 @@
|
||||
module.exports = {
|
||||
/**
|
||||
* ⚠ 生产数据库连接配置(仅用于 script/db-query.ps1 显式指定 -ConfigPath 时)。
|
||||
* 默认情况下 db-query.ps1 使用 config/config.local.js(开发库),
|
||||
* 只有显式传入本文件才会连接生产库,请确认后再使用。
|
||||
*/
|
||||
module.exports = {
|
||||
mysql: {
|
||||
clients: {
|
||||
wms: {
|
||||
|
||||
@ -63,6 +63,9 @@ const { createRequire } = require("module");
|
||||
const [rows] = await connection.query(query);
|
||||
const payload = JSON.stringify({
|
||||
client: clientName,
|
||||
host: client.host,
|
||||
port: client.port,
|
||||
database: client.database,
|
||||
rowCount: Array.isArray(rows) ? rows.length : 0,
|
||||
rows,
|
||||
});
|
||||
@ -105,6 +108,7 @@ try {
|
||||
Remove-Item -Path $jsonOutFile -ErrorAction SilentlyContinue
|
||||
}
|
||||
Write-Host "Client: $($result.client)"
|
||||
Write-Host "Target: $($result.host):$($result.port)/$($result.database)"
|
||||
Write-Host "Rows: $($result.rowCount)"
|
||||
|
||||
if ($AsTable) {
|
||||
|
||||
@ -2,8 +2,14 @@
|
||||
const fs = require('fs');
|
||||
const SequelizeLib = require('sequelize');
|
||||
|
||||
(async () => {
|
||||
const migrationName = process.argv[2] || process.env.MIGRATION_NAME;
|
||||
/**
|
||||
* 单条迁移执行主流程:加载数据库配置、执行迁移并验证结果,支持 --dry-run 预览。
|
||||
* @return {Promise<void>} 无返回值,通过 process.exitCode 表达执行结果。
|
||||
*/
|
||||
async function main() {
|
||||
const args = process.argv.slice(2);
|
||||
const dryRun = args.includes('--dry-run');
|
||||
const migrationName = args.find(arg => !arg.startsWith('--')) || process.env.MIGRATION_NAME;
|
||||
if (!migrationName) {
|
||||
console.error('ERROR: 必须通过命令行参数或环境变量 MIGRATION_NAME 传入迁移文件名。');
|
||||
console.error('USAGE: node ./script/run-single-migration.cjs 20260523130000-add-cainiao-to-wms-express.js');
|
||||
@ -28,6 +34,18 @@ const SequelizeLib = require('sequelize');
|
||||
}
|
||||
|
||||
const config = dbConfig.production;
|
||||
const targetMeta = dbConfig.dbTarget || { target: 'unknown', source: 'unknown' };
|
||||
console.log(`[RUN-MIGRATION] 连接目标: host=${config.host} port=${config.port} database=${config.database} (判定来源: ${targetMeta.source})`);
|
||||
if (targetMeta.target === 'production') {
|
||||
console.warn('[RUN-MIGRATION] ⚠ 目标为生产库,请确认后再执行;如属误判请设置 WMS_DB_TARGET=local 后重试。');
|
||||
}
|
||||
if (dryRun) {
|
||||
console.log('[RUN-MIGRATION] DRY-RUN 模式:仅展示执行计划,不连接数据库、不执行任何 DDL。');
|
||||
console.log(`[RUN-MIGRATION] 计划执行迁移文件: ${migrationName}`);
|
||||
console.log(`[RUN-MIGRATION] 目标库: ${config.host}:${config.port}/${config.database}`);
|
||||
return;
|
||||
}
|
||||
|
||||
const sequelize = new SequelizeLib(config.database, config.username, config.password, {
|
||||
host: config.host,
|
||||
port: config.port,
|
||||
@ -97,7 +115,7 @@ const SequelizeLib = require('sequelize');
|
||||
|
||||
// record migration in SequelizeMeta
|
||||
try {
|
||||
await sequelize.query('INSERT INTO SequelizeMeta(name) VALUES(?)', { replacements: [migrationName] });
|
||||
await sequelize.query('INSERT INTO SequelizeMeta(name) VALUES(?)', { replacements: [ migrationName ] });
|
||||
} catch (e) {
|
||||
console.error('ERROR: 无法在 SequelizeMeta 中记录迁移:', e && e.message ? e.message : e);
|
||||
process.exitCode = 5;
|
||||
@ -115,7 +133,7 @@ const SequelizeLib = require('sequelize');
|
||||
};
|
||||
|
||||
// migration recorded?
|
||||
const checkRow = await sequelize.query('SELECT name FROM SequelizeMeta WHERE name = ?', { replacements: [migrationName], type: SequelizeLib.QueryTypes.SELECT });
|
||||
const checkRow = await sequelize.query('SELECT name FROM SequelizeMeta WHERE name = ?', { replacements: [ migrationName ], type: SequelizeLib.QueryTypes.SELECT });
|
||||
result.migrationRecorded = (checkRow && checkRow.length > 0);
|
||||
|
||||
// table exists?
|
||||
@ -124,7 +142,7 @@ const SequelizeLib = require('sequelize');
|
||||
|
||||
if (result.tableExists) {
|
||||
const desc = await queryInterface.describeTable('wms_order_wave_strategy_match');
|
||||
const needed = ['id', 'warehouse_id', 'order_id', 'strategy_id', 'create_time'];
|
||||
const needed = [ 'id', 'warehouse_id', 'order_id', 'strategy_id', 'create_time' ];
|
||||
for (const col of needed) {
|
||||
result.columns[col] = !!desc[col];
|
||||
if (desc[col]) {
|
||||
@ -159,4 +177,6 @@ const SequelizeLib = require('sequelize');
|
||||
// close
|
||||
await sequelize.close();
|
||||
process.exitCode = 0;
|
||||
})();
|
||||
}
|
||||
|
||||
main();
|
||||
|
||||
@ -77,7 +77,10 @@ function readJsonFile(filePath) {
|
||||
}
|
||||
|
||||
function detectIndent(raw) {
|
||||
const match = raw.match(/^([ \t]+)"[^"]+":/m);
|
||||
// 取第一个带缩进的值行(对象键、数组元素对象 `{` 或字符串元素)作为单层缩进;
|
||||
// 根为数组的文档(methods/changes/*.json)首行 `[` 后紧跟元素 `{`,
|
||||
// 避免把第二层缩进误判为单层缩进,导致全文件重排
|
||||
const match = raw.match(/^([ \t]+)[\[{"]/m);
|
||||
return match ? match[1] : ' ';
|
||||
}
|
||||
|
||||
@ -212,6 +215,15 @@ function validateSpec(spec, args) {
|
||||
methodNames.add(item.method);
|
||||
});
|
||||
|
||||
let deleteMethods = [];
|
||||
if (Object.prototype.hasOwnProperty.call(spec, 'deleteMethods')) {
|
||||
ensureStringArray(spec.deleteMethods, 'spec.deleteMethods');
|
||||
deleteMethods = spec.deleteMethods;
|
||||
}
|
||||
deleteMethods.forEach(item => {
|
||||
assert(!methodNames.has(item), `Method conflict: ${item} appears in both spec.methods and spec.deleteMethods.`);
|
||||
});
|
||||
|
||||
if (!args.docOnly) {
|
||||
validateChange(spec.change, 'spec.change');
|
||||
} else if (Object.prototype.hasOwnProperty.call(spec, 'change')) {
|
||||
@ -225,6 +237,7 @@ function validateSpec(spec, args) {
|
||||
docMeta: spec.docMeta || {},
|
||||
group: spec.group,
|
||||
methods: spec.methods,
|
||||
deleteMethods,
|
||||
change: spec.change || null,
|
||||
};
|
||||
}
|
||||
@ -251,7 +264,7 @@ function cloneJson(value) {
|
||||
return JSON.parse(JSON.stringify(value));
|
||||
}
|
||||
|
||||
function applyDocUpdate(doc, groupSpec, methods, docMeta) {
|
||||
function applyDocUpdate(doc, groupSpec, methods, docMeta, deleteMethods = []) {
|
||||
const groups = doc.methods.groups;
|
||||
let groupIndex = findGroupIndex(groups, groupSpec);
|
||||
|
||||
@ -275,6 +288,8 @@ function applyDocUpdate(doc, groupSpec, methods, docMeta) {
|
||||
inserted: [],
|
||||
updated: [],
|
||||
moved: [],
|
||||
deleted: [],
|
||||
deleteNotFound: [],
|
||||
};
|
||||
|
||||
for (const methodDoc of methods) {
|
||||
@ -298,6 +313,16 @@ function applyDocUpdate(doc, groupSpec, methods, docMeta) {
|
||||
summary.moved.push(methodDoc.method);
|
||||
}
|
||||
|
||||
for (const methodName of deleteMethods) {
|
||||
const location = findMethodLocation(groups, methodName);
|
||||
if (!location) {
|
||||
summary.deleteNotFound.push(methodName);
|
||||
continue;
|
||||
}
|
||||
groups[location.groupIndex].list.splice(location.methodIndex, 1);
|
||||
summary.deleted.push(methodName);
|
||||
}
|
||||
|
||||
if (docMeta.updatedAt) {
|
||||
doc.updatedAt = docMeta.updatedAt;
|
||||
}
|
||||
@ -339,7 +364,7 @@ function main() {
|
||||
}
|
||||
|
||||
const docNext = cloneJson(docState.json);
|
||||
const summary = applyDocUpdate(docNext, normalized.group, normalized.methods, normalized.docMeta);
|
||||
const summary = applyDocUpdate(docNext, normalized.group, normalized.methods, normalized.docMeta, normalized.deleteMethods);
|
||||
JSON.parse(JSON.stringify(docNext));
|
||||
|
||||
let changeNext = null;
|
||||
@ -354,6 +379,8 @@ function main() {
|
||||
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(', ') : '-'}`);
|
||||
console.log(`deleted: ${summary.deleted.length ? summary.deleted.join(', ') : '-'}`);
|
||||
console.log(`delete-not-found: ${summary.deleteNotFound.length ? summary.deleteNotFound.join(', ') : '-'}`);
|
||||
if (!args.docOnly && normalized.change) {
|
||||
console.log(`change version: ${normalized.change.version}`);
|
||||
}
|
||||
|
||||
@ -1,27 +1,72 @@
|
||||
'use strict';
|
||||
|
||||
const assert = require('node:assert/strict');
|
||||
const { Op } = require('sequelize');
|
||||
|
||||
const WaveService = require('../../../../../app/service/systemMethods/order/wave');
|
||||
|
||||
/** 批量取消任务缓存键前缀(与 wave.js 中的常量保持一致)。 */
|
||||
const BATCH_CANCEL_TASK_CACHE_KEY_PREFIX = 'wave:batch-cancel:';
|
||||
|
||||
/**
|
||||
* 等待若干轮事件循环(用于等待 batchCancel 内 setImmediate 触发的后台任务)。
|
||||
*
|
||||
* @param {number} [ticks=3] 轮次。
|
||||
* @return {Promise<void>} 等待完成。
|
||||
*/
|
||||
function waitImmediate(ticks = 3) {
|
||||
return new Promise(resolve => {
|
||||
let remaining = ticks;
|
||||
const step = () => {
|
||||
remaining -= 1;
|
||||
if (remaining <= 0) {
|
||||
resolve();
|
||||
return;
|
||||
}
|
||||
setImmediate(step);
|
||||
};
|
||||
setImmediate(step);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建 batchCancel 轻量测试上下文。
|
||||
*
|
||||
* @param {Object} [options] 场景配置。
|
||||
* @param {Array<Object>} [options.orders] 订单记录(id/wave_id/wave_no/pick_status)。
|
||||
* @param {Array<Object>} [options.waves] 波次记录(wave_id/wave_no/wave_status)。
|
||||
* @param {Array<Object>} [options.activePickTaskWaves] 活动拣货任务波次行(wave_id)。
|
||||
* @param {number} [options.warehouseId] 仓库ID(默认固定测试仓库 100000)。
|
||||
* @return {{ service: WaveService, state: Object }} 服务实例与状态记录。
|
||||
*/
|
||||
function createHarness() {
|
||||
function createHarness(options = {}) {
|
||||
const warehouseId = Number(options.warehouseId || 100000);
|
||||
const cacheStore = new Map();
|
||||
const state = {
|
||||
sqlCalls: [],
|
||||
orders: [
|
||||
{ id: 101, wave_id: 11, wave_no: 'W11' },
|
||||
{ id: 102, wave_id: 11, wave_no: 'W11' },
|
||||
],
|
||||
cacheKeys: [],
|
||||
orderFindAllCalls: [],
|
||||
orderUpdateCalls: [],
|
||||
canceledWaveIds: [],
|
||||
rollbackCount: 0,
|
||||
backgroundTaskCalls: [],
|
||||
orders: (options.orders || [
|
||||
{ id: 101, wave_id: 11, wave_no: 'W11', pick_status: 'none' },
|
||||
{ id: 102, wave_id: 11, wave_no: 'W11', pick_status: 'none' },
|
||||
]).map(row => ({ ...row })),
|
||||
waves: (options.waves || [
|
||||
{ wave_id: 11, wave_no: 'W11', wave_status: 0 },
|
||||
]).map(row => ({ ...row })),
|
||||
activePickTaskWaves: options.activePickTaskWaves || [],
|
||||
};
|
||||
|
||||
const transaction = {
|
||||
async commit() {},
|
||||
async rollback() {},
|
||||
async commit() {
|
||||
// 轻量测试用空事务:提交不做任何事
|
||||
},
|
||||
async rollback() {
|
||||
state.rollbackCount += 1;
|
||||
},
|
||||
};
|
||||
|
||||
const ctx = {
|
||||
@ -29,13 +74,16 @@ function createHarness() {
|
||||
config: {},
|
||||
async setCacheAsync(key, value) {
|
||||
cacheStore.set(key, value);
|
||||
if (!state.cacheKeys.includes(key)) {
|
||||
state.cacheKeys.push(key);
|
||||
}
|
||||
},
|
||||
async getCacheAsync(key) {
|
||||
return cacheStore.get(key) || null;
|
||||
},
|
||||
},
|
||||
user: {
|
||||
store_id: 100000,
|
||||
store_id: warehouseId,
|
||||
},
|
||||
logger: {
|
||||
info() {},
|
||||
@ -52,10 +100,21 @@ function createHarness() {
|
||||
async query(sql, options = {}) {
|
||||
state.sqlCalls.push({ sql, options });
|
||||
|
||||
if (sql.includes('SELECT wave_id, wave_no') && options.type === 'SELECT') {
|
||||
return [
|
||||
{ wave_id: 11, wave_no: 'W11' },
|
||||
];
|
||||
// 入口校验:活动拣货任务波次查询
|
||||
if (sql.includes('wms_wave_pick_task_wave')) {
|
||||
return state.activePickTaskWaves;
|
||||
}
|
||||
|
||||
// 波次批量表查询(入口 wave_status >= 3 兜底校验 / 后台任务波次加载)
|
||||
if (sql.includes('SELECT wave_id, wave_no, wave_status')) {
|
||||
const replacements = options.replacements || {};
|
||||
const rawIds = replacements.ids || replacements.waveIds || [];
|
||||
const requestedIds = (Array.isArray(rawIds) ? rawIds : [ rawIds ]).map(id => Number(id));
|
||||
const matched = state.waves.filter(item => requestedIds.includes(Number(item.wave_id)));
|
||||
if (sql.includes('wave_status >= 3')) {
|
||||
return matched.filter(item => Number(item.wave_status) >= 3);
|
||||
}
|
||||
return matched;
|
||||
}
|
||||
|
||||
if (sql.includes('DELETE FROM wms_order_wave_index')) {
|
||||
@ -63,6 +122,8 @@ function createHarness() {
|
||||
}
|
||||
|
||||
if (sql.includes('UPDATE wms_wave_batch') && sql.includes('SET wave_status = -1')) {
|
||||
const waveId = Number(options.replacements && options.replacements.waveId || 0);
|
||||
state.canceledWaveIds.push(waveId);
|
||||
return [[], { affectedRows: 1 }];
|
||||
}
|
||||
|
||||
@ -73,15 +134,40 @@ function createHarness() {
|
||||
|
||||
const service = new WaveService(ctx);
|
||||
service.batchCreateOrderOperationLogs = async () => 0;
|
||||
// 快扫副表清理/触发为取消链路外的旁路副作用,stub 掉以保持用例确定性(非取消语义本身)
|
||||
service.enqueueWaveStrategyQuickScanPostOrderChange = () => {};
|
||||
|
||||
const matchWaveId = (row, waveIdCondition) => {
|
||||
if (waveIdCondition && waveIdCondition[Op.in]) {
|
||||
return waveIdCondition[Op.in].map(id => Number(id)).includes(Number(row.wave_id || 0));
|
||||
}
|
||||
return Number(row.wave_id || 0) === Number(waveIdCondition || 0);
|
||||
};
|
||||
const matchPickStatus = (row, pickStatusCondition) => {
|
||||
if (pickStatusCondition === undefined) {
|
||||
return true;
|
||||
}
|
||||
if (pickStatusCondition && pickStatusCondition[Op.in]) {
|
||||
return pickStatusCondition[Op.in].includes(String(row.pick_status || ''));
|
||||
}
|
||||
return String(row.pick_status || '') === String(pickStatusCondition);
|
||||
};
|
||||
|
||||
service.getOrderModel = async () => ({
|
||||
async findAll() {
|
||||
return state.orders.map(item => ({ ...item }));
|
||||
async findAll(options = {}) {
|
||||
const where = (options && options.where) || {};
|
||||
state.orderFindAllCalls.push({ where });
|
||||
return state.orders
|
||||
.filter(item => matchWaveId(item, where.wave_id))
|
||||
.filter(item => matchPickStatus(item, where.pick_status))
|
||||
.map(item => ({ ...item }));
|
||||
},
|
||||
async update(values = {}, options = {}) {
|
||||
const waveId = Number(options.where && options.where.wave_id || 0);
|
||||
const where = (options && options.where) || {};
|
||||
state.orderUpdateCalls.push({ values, where });
|
||||
let affected = 0;
|
||||
for (const row of state.orders) {
|
||||
if (Number(row.wave_id || 0) !== waveId) {
|
||||
if (!matchWaveId(row, where.wave_id)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
@ -117,10 +203,319 @@ describe('test/app/service/systemMethods/order/wave.batchCancel.test.js', () =>
|
||||
|
||||
const deleteCall = state.sqlCalls.find(call => call.sql.includes('DELETE FROM wms_order_wave_index'));
|
||||
assert.ok(deleteCall, '应删除波次索引');
|
||||
assert.deepEqual(deleteCall.options.replacements.orderIds.sort((a, b) => a - b), [ 101, 102 ]);
|
||||
assert.deepEqual(
|
||||
deleteCall.options.replacements.waveIds.map(id => Number(id)),
|
||||
[ 11 ]
|
||||
);
|
||||
|
||||
const progress = await service.getBatchCancelTaskProgress('task_cancel_1');
|
||||
assert.equal(progress.state, 'success');
|
||||
assert.equal(progress.result.canceled_wave_count, 1);
|
||||
assert.equal(progress.result.skipped_wave_count, 0);
|
||||
assert.deepEqual(progress.result.skipped_wave_ids, []);
|
||||
assert.deepEqual(progress.result.skipped_waves, []);
|
||||
assert.equal(state.orders.every(order => order.wave_id === 0), true, '取消后订单应被移出波次');
|
||||
});
|
||||
|
||||
it('batchCancel 波次内存在拣货中订单时应整体拒绝,不删除波次、不移出订单', async () => {
|
||||
const { service, state } = createHarness({
|
||||
waves: [
|
||||
{ wave_id: 11, wave_no: 'W11', wave_status: 0 },
|
||||
{ wave_id: 12, wave_no: 'W12', wave_status: 0 },
|
||||
],
|
||||
orders: [
|
||||
{ id: 101, wave_id: 11, wave_no: 'W11', pick_status: 'padding' },
|
||||
{ id: 102, wave_id: 11, wave_no: 'W11', pick_status: 'none' },
|
||||
{ id: 103, wave_id: 12, wave_no: 'W12', pick_status: 'none' },
|
||||
],
|
||||
});
|
||||
|
||||
const result = await service.batchCancel({
|
||||
warehouse_id: 100000,
|
||||
wave_ids: [ 11, 12 ],
|
||||
});
|
||||
|
||||
assert.equal(result.flag, 'failure');
|
||||
assert.equal(result.code, 400);
|
||||
assert.match(result.message, /禁止取消波次/);
|
||||
assert.deepEqual(result.wave_ids, [ 11 ], '应仅返回存在拣货中订单的波次');
|
||||
assert.deepEqual(result.order_ids, [ 101 ], '应返回命中拣货中订单');
|
||||
|
||||
// 整体拒绝:不得执行任何取消动作
|
||||
assert.equal(
|
||||
state.sqlCalls.some(call => call.sql.includes('DELETE FROM wms_order_wave_index')),
|
||||
false,
|
||||
'整体拒绝时不得删除波次索引'
|
||||
);
|
||||
assert.equal(
|
||||
state.sqlCalls.some(call => call.sql.includes('SET wave_status = -1')),
|
||||
false,
|
||||
'整体拒绝时不得更新波次状态'
|
||||
);
|
||||
assert.equal(state.orderUpdateCalls.length, 0, '整体拒绝时不得移出订单');
|
||||
assert.equal(
|
||||
state.cacheKeys.some(key => key.startsWith(BATCH_CANCEL_TASK_CACHE_KEY_PREFIX)),
|
||||
false,
|
||||
'整体拒绝时不得提交后台取消任务'
|
||||
);
|
||||
assert.equal(state.orders.every(order => order.wave_id !== 0), true, '所有订单应保持原波次');
|
||||
assert.equal(
|
||||
state.orderFindAllCalls.some(call => call.where.pick_status && call.where.pick_status[Op.in]),
|
||||
true,
|
||||
'应执行拣货状态守卫查询'
|
||||
);
|
||||
});
|
||||
|
||||
it('batchCancel 波次内存在拣货完成订单时应整体拒绝', async () => {
|
||||
const { service, state } = createHarness({
|
||||
waves: [
|
||||
{ wave_id: 11, wave_no: 'W11', wave_status: 1 },
|
||||
],
|
||||
orders: [
|
||||
{ id: 101, wave_id: 11, wave_no: 'W11', pick_status: 'fin' },
|
||||
{ id: 102, wave_id: 11, wave_no: 'W11', pick_status: 'none' },
|
||||
],
|
||||
});
|
||||
|
||||
const result = await service.batchCancel({
|
||||
warehouse_id: 100000,
|
||||
wave_ids: [ 11 ],
|
||||
});
|
||||
|
||||
assert.equal(result.flag, 'failure');
|
||||
assert.equal(result.code, 400);
|
||||
assert.match(result.message, /禁止取消波次/);
|
||||
assert.deepEqual(result.wave_ids, [ 11 ]);
|
||||
assert.deepEqual(result.order_ids, [ 101 ]);
|
||||
assert.equal(
|
||||
state.sqlCalls.some(call => call.sql.includes('SET wave_status = -1')),
|
||||
false
|
||||
);
|
||||
assert.equal(state.orderUpdateCalls.length, 0);
|
||||
assert.equal(
|
||||
state.cacheKeys.some(key => key.startsWith(BATCH_CANCEL_TASK_CACHE_KEY_PREFIX)),
|
||||
false
|
||||
);
|
||||
});
|
||||
|
||||
it('batchCancel 波次已进入拣货及后续环节(wave_status >= 3)时应拒绝', async () => {
|
||||
const { service, state } = createHarness({
|
||||
waves: [
|
||||
{ wave_id: 11, wave_no: 'W11', wave_status: 3 },
|
||||
],
|
||||
orders: [
|
||||
{ id: 101, wave_id: 11, wave_no: 'W11', pick_status: 'none' },
|
||||
],
|
||||
});
|
||||
|
||||
const result = await service.batchCancel({
|
||||
warehouse_id: 100000,
|
||||
wave_ids: [ 11 ],
|
||||
});
|
||||
|
||||
assert.equal(result.flag, 'failure');
|
||||
assert.equal(result.code, 400);
|
||||
assert.match(result.message, /禁止取消波次/);
|
||||
assert.deepEqual(result.wave_ids, [ 11 ]);
|
||||
assert.equal(
|
||||
state.sqlCalls.some(call => call.sql.includes('wave_status >= 3')),
|
||||
true,
|
||||
'应执行 wave_status >= 3 兜底校验查询'
|
||||
);
|
||||
assert.equal(
|
||||
state.sqlCalls.some(call => call.sql.includes('SET wave_status = -1')),
|
||||
false
|
||||
);
|
||||
assert.equal(state.orderUpdateCalls.length, 0);
|
||||
assert.equal(
|
||||
state.cacheKeys.some(key => key.startsWith(BATCH_CANCEL_TASK_CACHE_KEY_PREFIX)),
|
||||
false
|
||||
);
|
||||
});
|
||||
|
||||
it('batchCancel 未拣货波次(pick_status=none、wave_status<3)应正常提交取消任务', async () => {
|
||||
const { service, state } = createHarness({
|
||||
waves: [
|
||||
{ wave_id: 11, wave_no: 'W11', wave_status: 1 },
|
||||
],
|
||||
orders: [
|
||||
{ id: 101, wave_id: 11, wave_no: 'W11', pick_status: 'none' },
|
||||
{ id: 102, wave_id: 11, wave_no: 'W11', pick_status: 'none' },
|
||||
],
|
||||
});
|
||||
|
||||
service.runBatchCancelTask = async params => {
|
||||
state.backgroundTaskCalls.push({ ...params });
|
||||
};
|
||||
|
||||
const result = await service.batchCancel({
|
||||
warehouse_id: 100000,
|
||||
wave_ids: [ 11 ],
|
||||
});
|
||||
|
||||
assert.equal(result.flag, 'success');
|
||||
assert.equal(typeof result.task_id, 'string');
|
||||
assert.ok(result.task_id.length > 0);
|
||||
assert.equal(result.message, '批量解除波次任务已提交。');
|
||||
|
||||
await waitImmediate();
|
||||
assert.equal(state.backgroundTaskCalls.length, 1, '应触发后台取消任务');
|
||||
assert.deepEqual(state.backgroundTaskCalls[0], {
|
||||
taskId: result.task_id,
|
||||
warehouseId: 100000,
|
||||
waveIds: [ 11 ],
|
||||
});
|
||||
|
||||
const submitted = await service.getBatchCancelTaskProgress(result.task_id);
|
||||
assert.equal(submitted.state, 'submitted');
|
||||
assert.equal(submitted.warehouse_id, 100000);
|
||||
assert.equal(submitted.wave_ids, '11');
|
||||
});
|
||||
|
||||
it('runBatchCancelTask 波次已进入拣货及后续环节时应跳过并返回 skipped_waves', async () => {
|
||||
const { service, state } = createHarness({
|
||||
waves: [
|
||||
{ wave_id: 11, wave_no: 'W11', wave_status: 3 },
|
||||
],
|
||||
orders: [
|
||||
{ id: 101, wave_id: 11, wave_no: 'W11', pick_status: 'none' },
|
||||
],
|
||||
});
|
||||
|
||||
await service.setBatchCancelTaskProgress('task_skip_status', 'submitted', {
|
||||
warehouse_id: 100000,
|
||||
wave_ids: '11',
|
||||
wave_id_list: [ 11 ],
|
||||
});
|
||||
|
||||
await service.runBatchCancelTask({
|
||||
taskId: 'task_skip_status',
|
||||
warehouseId: 100000,
|
||||
waveIds: [ 11 ],
|
||||
});
|
||||
|
||||
const progress = await service.getBatchCancelTaskProgress('task_skip_status');
|
||||
assert.equal(progress.state, 'success');
|
||||
assert.equal(progress.result.canceled_wave_count, 0);
|
||||
assert.equal(progress.result.skipped_wave_count, 1);
|
||||
assert.deepEqual(progress.result.skipped_wave_ids, [ 11 ]);
|
||||
assert.deepEqual(progress.result.skipped_waves, [
|
||||
{ wave_id: 11, wave_no: 'W11', reason: 'wave_status_blocked', wave_status: 3 },
|
||||
]);
|
||||
|
||||
// 跳过时不得执行任何取消动作
|
||||
assert.equal(
|
||||
state.sqlCalls.some(call => call.sql.includes('SET wave_status = -1')),
|
||||
false
|
||||
);
|
||||
assert.equal(
|
||||
state.sqlCalls.some(call => call.sql.includes('DELETE FROM wms_order_wave_index')),
|
||||
false
|
||||
);
|
||||
assert.equal(state.orderUpdateCalls.length, 0);
|
||||
assert.equal(state.orders[0].wave_id, 11, '订单应保持原波次');
|
||||
});
|
||||
|
||||
it('runBatchCancelTask 波次内存在拣货中/拣货完成订单时应跳过并记录 picked_orders_exist', async () => {
|
||||
const { service, state } = createHarness({
|
||||
waves: [
|
||||
{ wave_id: 11, wave_no: 'W11', wave_status: 0 },
|
||||
],
|
||||
orders: [
|
||||
{ id: 101, wave_id: 11, wave_no: 'W11', pick_status: 'padding' },
|
||||
{ id: 102, wave_id: 11, wave_no: 'W11', pick_status: 'fin' },
|
||||
{ id: 103, wave_id: 11, wave_no: 'W11', pick_status: 'none' },
|
||||
],
|
||||
});
|
||||
|
||||
await service.setBatchCancelTaskProgress('task_skip_picked', 'submitted', {
|
||||
warehouse_id: 100000,
|
||||
wave_ids: '11',
|
||||
wave_id_list: [ 11 ],
|
||||
});
|
||||
|
||||
await service.runBatchCancelTask({
|
||||
taskId: 'task_skip_picked',
|
||||
warehouseId: 100000,
|
||||
waveIds: [ 11 ],
|
||||
});
|
||||
|
||||
const progress = await service.getBatchCancelTaskProgress('task_skip_picked');
|
||||
assert.equal(progress.state, 'success');
|
||||
assert.equal(progress.result.canceled_wave_count, 0);
|
||||
assert.equal(progress.result.skipped_wave_count, 1);
|
||||
assert.deepEqual(progress.result.skipped_wave_ids, [ 11 ]);
|
||||
assert.equal(progress.result.skipped_waves.length, 1);
|
||||
assert.equal(progress.result.skipped_waves[0].wave_id, 11);
|
||||
assert.equal(progress.result.skipped_waves[0].wave_no, 'W11');
|
||||
assert.equal(progress.result.skipped_waves[0].reason, 'picked_orders_exist');
|
||||
assert.equal(progress.result.skipped_waves[0].picked_order_count, 2);
|
||||
|
||||
assert.equal(state.rollbackCount, 1, '命中拣货守卫后应回滚事务');
|
||||
assert.equal(
|
||||
state.sqlCalls.some(call => call.sql.includes('SET wave_status = -1')),
|
||||
false
|
||||
);
|
||||
assert.equal(
|
||||
state.sqlCalls.some(call => call.sql.includes('DELETE FROM wms_order_wave_index')),
|
||||
false
|
||||
);
|
||||
assert.equal(state.orderUpdateCalls.length, 0);
|
||||
assert.equal(state.orders.every(order => order.wave_id === 11), true, '订单应保持原波次');
|
||||
});
|
||||
|
||||
it('runBatchCancelTask 混合波次:正常波次取消、命中条件的波次跳过', async () => {
|
||||
const { service, state } = createHarness({
|
||||
waves: [
|
||||
{ wave_id: 11, wave_no: 'W11', wave_status: 0 },
|
||||
{ wave_id: 12, wave_no: 'W12', wave_status: 3 },
|
||||
{ wave_id: 13, wave_no: 'W13', wave_status: 0 },
|
||||
],
|
||||
orders: [
|
||||
{ id: 101, wave_id: 11, wave_no: 'W11', pick_status: 'none' },
|
||||
{ id: 102, wave_id: 11, wave_no: 'W11', pick_status: 'none' },
|
||||
{ id: 103, wave_id: 12, wave_no: 'W12', pick_status: 'none' },
|
||||
{ id: 104, wave_id: 13, wave_no: 'W13', pick_status: 'padding' },
|
||||
{ id: 105, wave_id: 13, wave_no: 'W13', pick_status: 'none' },
|
||||
],
|
||||
});
|
||||
|
||||
await service.setBatchCancelTaskProgress('task_mixed', 'submitted', {
|
||||
warehouse_id: 100000,
|
||||
wave_ids: '11,12,13',
|
||||
wave_id_list: [ 11, 12, 13 ],
|
||||
});
|
||||
|
||||
await service.runBatchCancelTask({
|
||||
taskId: 'task_mixed',
|
||||
warehouseId: 100000,
|
||||
waveIds: [ 11, 12, 13 ],
|
||||
});
|
||||
|
||||
const progress = await service.getBatchCancelTaskProgress('task_mixed');
|
||||
assert.equal(progress.state, 'success');
|
||||
assert.equal(progress.result.canceled_wave_count, 1);
|
||||
assert.deepEqual(progress.result.affected_wave_ids, [ 11 ]);
|
||||
assert.equal(progress.result.affected_order_count, 2);
|
||||
assert.equal(progress.result.skipped_wave_count, 2);
|
||||
assert.deepEqual(progress.result.skipped_wave_ids, [ 12, 13 ]);
|
||||
assert.deepEqual(
|
||||
progress.result.skipped_waves.map(item => item.reason),
|
||||
[ 'wave_status_blocked', 'picked_orders_exist' ]
|
||||
);
|
||||
|
||||
assert.deepEqual(state.canceledWaveIds, [ 11 ], '仅正常波次执行取消');
|
||||
const deleteCall = state.sqlCalls.find(call => call.sql.includes('DELETE FROM wms_order_wave_index'));
|
||||
assert.deepEqual(
|
||||
deleteCall.options.replacements.waveIds.map(id => Number(id)),
|
||||
[ 11 ]
|
||||
);
|
||||
assert.deepEqual(
|
||||
state.orders.filter(order => [ 101, 102 ].includes(order.id)).map(order => order.wave_id),
|
||||
[ 0, 0 ],
|
||||
'正常波次订单应被移出波次'
|
||||
);
|
||||
assert.equal(state.orders.find(order => order.id === 103).wave_id, 12, '被跳过波次订单保持原波次');
|
||||
assert.equal(state.orders.find(order => order.id === 104).wave_id, 13, '被跳过波次订单保持原波次');
|
||||
});
|
||||
});
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user