Compare commits
No commits in common. "aff7a4fe22cb798a25763d0e718004eb833f76a3" and "95067aeb8a7c126af62eac9d610de6975e433cea" have entirely different histories.
aff7a4fe22
...
95067aeb8a
5
.gitignore
vendored
5
.gitignore
vendored
@ -39,8 +39,3 @@ versioning/*
|
||||
|
||||
app/public/exports/
|
||||
script/debug-*.cjs
|
||||
|
||||
# nginx local wiring (generated server blocks / certs / upstream, not committed)
|
||||
.ssl/
|
||||
nginx_config/
|
||||
nginx-upstream-local.conf
|
||||
|
||||
File diff suppressed because one or more lines are too long
@ -445,14 +445,12 @@ function normalizeGroups(docData) {
|
||||
|
||||
/**
|
||||
* 解析文档对应的统一入口路径,优先使用文档内声明的 http.path。
|
||||
* 只要 http.path 是非空字符串就原样返回,允许 `{ApiApp.callback_url}`
|
||||
* 这类出站回调占位符原样展示;http.path 为 null/空串时回落到模块默认入口。
|
||||
* @param {object} docData 文档 JSON 数据。
|
||||
* @return {string} 统一入口路径。
|
||||
*/
|
||||
function resolveDocEntryPath(docData) {
|
||||
const httpPath = String(docData?.http?.path || '').trim();
|
||||
if (httpPath) {
|
||||
if (httpPath.startsWith('/')) {
|
||||
return httpPath;
|
||||
}
|
||||
|
||||
@ -681,9 +679,8 @@ function renderHtmlPage({
|
||||
entryPath,
|
||||
}) {
|
||||
const isOpenapi = docData.module === 'openapi';
|
||||
const isOpenapiCallback = docData.module === 'openapi_callback';
|
||||
const isWarehouse = docData.module === 'warehouse' || docData.module === 'warehouse_notify';
|
||||
const isExternalApi = isOpenapi || isOpenapiCallback || isWarehouse;
|
||||
const isExternalApi = isOpenapi || isWarehouse;
|
||||
const methodsCount = groups.reduce((sum, group) => sum + toArray(group.list).length, 0);
|
||||
const globalHeaders = toArray(docData.headers);
|
||||
const globalHeadersControls = renderGlobalHeadersControls(globalHeaders);
|
||||
@ -1136,7 +1133,7 @@ function renderHtmlPage({
|
||||
</div>
|
||||
<pre id="docResourcePreview" class="req-result muted">点击上方按钮后,可直接预览当前文档的变更记录或原文 JSON。</pre>
|
||||
</div>`}
|
||||
${isOpenapi || isWarehouse ? (docData.module === 'warehouse_notify' ? `<div class="openapi-guide">
|
||||
${isExternalApi ? (docData.module === 'warehouse_notify' ? `<div class="openapi-guide">
|
||||
<h3>请求方式</h3>
|
||||
<pre class="guide-code">POST {notify_url}?app_key={app_key}&method={方法名}&timestamp={时间戳}&sign={签名}
|
||||
Content-Type: application/json
|
||||
@ -1215,10 +1212,6 @@ Content-Type: application/json
|
||||
${isOpenapi ? `<p style="margin-top:12px;font-size:13px;">
|
||||
<a href="/docs/api/openapi/callback-test" style="color:#1565c0;">→ 回调测试工具</a>
|
||||
<span class="muted">(模拟接收回调通知,验证回调链路)</span>
|
||||
</p>
|
||||
<p style="margin-top:12px;font-size:13px;">
|
||||
<a href="/docs/api/openapi_callback" style="color:#1565c0;">→ 出站回调文档</a>
|
||||
<span class="muted">(WMS → 外部的回调事件定义,共 5 个)</span>
|
||||
</p>` : ''}
|
||||
</div>`) : ''}
|
||||
</section>
|
||||
@ -2164,14 +2157,6 @@ class DocsController extends Controller {
|
||||
await this.renderDoc('openapi');
|
||||
}
|
||||
|
||||
/**
|
||||
* 渲染 OpenAPI 出站回调文档独立页面。
|
||||
* @return {Promise<void>} 无返回值。
|
||||
*/
|
||||
async openapiCallbackEvents() {
|
||||
await this.renderDoc('openapi_callback');
|
||||
}
|
||||
|
||||
/**
|
||||
* 渲染仓库开放 API 文档独立页面。
|
||||
* @return {Promise<void>} 无返回值。
|
||||
|
||||
@ -9,8 +9,7 @@ const { CALLBACK_EVENTS } = require('../service/openapi/callbackRegistry');
|
||||
class OpenapiCallbackController extends Controller {
|
||||
/**
|
||||
* 渲染回调测试页面。
|
||||
* 页面支持选择已注册的回调事件,选中后自动填充与真实回调完全一致的
|
||||
* 完整报文体 { request: {...} }(奇门同层级,可编辑)、填入测试 URL 和密钥,
|
||||
* 页面支持选择已注册的回调事件、填入测试 URL 和密钥,
|
||||
* 前端计算 MD5 签名后 POST 到目标 URL 并展示完整请求/响应。
|
||||
*/
|
||||
async testPage() {
|
||||
@ -46,11 +45,9 @@ class OpenapiCallbackController extends Controller {
|
||||
<div class="container">
|
||||
<div class="card">
|
||||
<h1>OpenAPI 回调测试</h1>
|
||||
<p class="desc">选择已注册的回调事件,自动填充与真实回调完全一致的完整报文体(奇门同层级 { request },可编辑),填入测试 URL 模拟推送。</p>
|
||||
<p class="desc">选择已注册的回调事件,填入测试 URL,模拟真实回调推送。</p>
|
||||
<p style="margin-top:6px;font-size:13px;">
|
||||
<a href="/docs/api/openapi" style="color:#1565c0;">← 返回 API 文档</a>
|
||||
|
|
||||
<a href="/docs/api/openapi_callback" style="color:#1565c0;">→ 出站回调文档</a>
|
||||
</p>
|
||||
</div>
|
||||
|
||||
@ -75,8 +72,8 @@ class OpenapiCallbackController extends Controller {
|
||||
<label>测试回调 URL</label>
|
||||
<input id="callbackUrlInput" type="text" placeholder="https://your-system.com/api/callback" />
|
||||
|
||||
<label>完整报文体(奇门同层级 { request },与真实回调一致,可编辑)</label>
|
||||
<textarea id="dataInput" rows="8" placeholder='{"request":{}}'></textarea>
|
||||
<label>回调数据 Body(自动填充模板,可编辑)</label>
|
||||
<textarea id="dataInput" rows="8" placeholder='{}'></textarea>
|
||||
|
||||
<button id="sendBtn" class="send-btn" onclick="sendTest()">发送测试回调</button>
|
||||
|
||||
@ -105,9 +102,7 @@ class OpenapiCallbackController extends Controller {
|
||||
var found = EVENTS.find(function(e) { return e.name === name; });
|
||||
if (found) {
|
||||
eventDesc.textContent = found.description;
|
||||
dataInput.value = JSON.stringify({
|
||||
request: found.request || {},
|
||||
}, null, 2);
|
||||
dataInput.value = JSON.stringify(found.sampleData, null, 2);
|
||||
} else {
|
||||
eventDesc.textContent = '';
|
||||
dataInput.value = '{}';
|
||||
|
||||
@ -99,7 +99,6 @@ module.exports = {
|
||||
// 库存管理
|
||||
STORAGE_TRANSFER_LOCATION: '库位调拨',
|
||||
STORAGE_TRANSFER_BY_PRODUCT: '商品调拨',
|
||||
STORAGE_UPDATE_EXPIRY: '维护库存效期',
|
||||
STOCK_IN: '商品入库',
|
||||
STOCK_OUT: '商品出库',
|
||||
STOCK_ADJUST: '库存调整',
|
||||
|
||||
@ -1,54 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 站内信 IM 渠道来源工具。
|
||||
*
|
||||
* 群ID 格式与渠道来源一一对应(生产 11 万+ 入站消息 100% 满足该对应关系):
|
||||
* - `xxx@chatroom` 结尾 → wx(个人微信)
|
||||
* - 纯数字(如 10845468709699144)→ qiwe(企业微信)
|
||||
*
|
||||
* ext_data.source 决定回执/通知透传给哪个桥接渠道;一旦与群ID格式不符,
|
||||
* 回执会被投递到错误渠道(典型现象:wx 群用 qiwe 渠道投递 → "qiwe offline" 503)。
|
||||
*/
|
||||
|
||||
/** 个人微信群ID 后缀 */
|
||||
const WX_GROUP_ID_SUFFIX = '@chatroom';
|
||||
|
||||
/**
|
||||
* 按群ID格式推导渠道来源。
|
||||
* @param {string} groupId 外部群ID。
|
||||
* @return {string|null} wx / qiwe;无法判定时返回 null。
|
||||
*/
|
||||
function resolveChannelSource(groupId) {
|
||||
const id = String(groupId || '').trim();
|
||||
if (!id) return null;
|
||||
if (id.endsWith(WX_GROUP_ID_SUFFIX)) return 'wx';
|
||||
if (/^\d+$/.test(id)) return 'qiwe';
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 按群ID格式校正 ext_data.source(不修改入参)。
|
||||
* 仅在 ext_data 已带 source 且与群ID格式不符时返回新对象;
|
||||
* 无 ext_data / 无 source / 群ID无法判定 / 已一致时原样返回。
|
||||
* @param {string} groupId 外部群ID。
|
||||
* @param {Object|null} extData 原始透传数据。
|
||||
* @return {Object|null} 校正后的透传数据。
|
||||
*/
|
||||
function normalizeExtDataSource(groupId, extData) {
|
||||
if (!extData || typeof extData !== 'object' || Array.isArray(extData)) {
|
||||
return extData || null;
|
||||
}
|
||||
const expected = resolveChannelSource(groupId);
|
||||
const current = extData.source;
|
||||
if (!expected || !current || current === expected) {
|
||||
return extData;
|
||||
}
|
||||
return { ...extData, source: expected };
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
WX_GROUP_ID_SUFFIX,
|
||||
resolveChannelSource,
|
||||
normalizeExtDataSource,
|
||||
};
|
||||
@ -95,12 +95,8 @@ async function resolveInterceptRequestGuardInfo(ctx, params = {}) {
|
||||
let weighingWeight = 0;
|
||||
if (ctx && ctx.model && ctx.model.OrderExpress) {
|
||||
try {
|
||||
// 强制同仓校验:读取称重重量必须同时带订单ID与仓库ID,禁止跨仓串读
|
||||
const expressRows = await ctx.model.OrderExpress.findAll({
|
||||
where: {
|
||||
order_id: Number(orderId || 0),
|
||||
warehouse_id: warehouseId,
|
||||
},
|
||||
where: { order_id: Number(orderId || 0) },
|
||||
attributes: [ 'weighing_weight' ],
|
||||
raw: true,
|
||||
transaction,
|
||||
|
||||
@ -1,82 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 通知拦截时间(wms_order_delivery.intercept_time)字段口径工具(纯函数,无 ctx 依赖,可单测)。
|
||||
*
|
||||
* 背景:`intercept_time` 语义原为「进入拦截流程/库内拦截确认时写入」,
|
||||
* 确认拦截会覆盖发起时刻,导致「通知拦截时间」丢失、且无法与「库内确定拦截时刻」区分。
|
||||
*
|
||||
* 自 2026-09-10 起统一为「最近一次发起拦截的通知时刻」:
|
||||
* 1. 发起/通知拦截:**首次写入**(当前时间);重复发起**不覆盖**已有值;
|
||||
* 2. 库内拦截确认(confirmIntercept / 拦截扫描 / 自动确认)、退回入库(returned):**不写该字段**(不覆盖);
|
||||
* 3. 取消/解除拦截(batchUnintercept)与订单克隆重置:**置空 null**;
|
||||
* 4. 因此「库内确定拦截时刻」不再使用本字段,改用配送表 `dispath_time`(订单迁移进配送表的时间,
|
||||
* 库内确定拦截后基本都会走迁移)。
|
||||
*/
|
||||
|
||||
/** 字段名常量 */
|
||||
const INTERCEPT_TIME_FIELD = 'intercept_time';
|
||||
|
||||
/**
|
||||
* 判断通知拦截时间是否为空(null/undefined/空串)。
|
||||
* @param {*} value 字段值
|
||||
* @return {boolean} 是否为空
|
||||
*/
|
||||
function isEmptyInterceptTime(value) {
|
||||
return value === null || value === undefined || value === '';
|
||||
}
|
||||
|
||||
/**
|
||||
* 构造发起拦截时的更新片段:仅当当前值为空时才写入通知拦截时间(首次写入,不覆盖)。
|
||||
*
|
||||
* 用法(实例更新,实例行需能取到 intercept_time):
|
||||
* ```js
|
||||
* await order.update({ intercept_status: 'requested', ...buildNoticeTimePatch(order.intercept_time), updated_at: now });
|
||||
* ```
|
||||
*
|
||||
* @param {*} currentValue 订单当前 intercept_time
|
||||
* @param {Date} [now=new Date()] 本次通知时刻
|
||||
* @return {Object} 需要写入的字段片段;已有值时返回空对象(不覆盖)
|
||||
*/
|
||||
function buildNoticeTimePatch(currentValue, now = new Date()) {
|
||||
return isEmptyInterceptTime(currentValue) ? { [INTERCEPT_TIME_FIELD]: now } : {};
|
||||
}
|
||||
|
||||
/**
|
||||
* 从订单行中筛出「尚未写入通知拦截时间」的订单ID(批量写入用)。
|
||||
*
|
||||
* 用法(批量更新):主更新不写 intercept_time,随后仅对返回的订单ID写一次通知时刻:
|
||||
* ```js
|
||||
* const fillIds = pickNoticeTimeOrderIds(orderRows);
|
||||
* await model.update({ intercept_status: 'requested', updated_at: now }, { where: { id: { [Op.in]: ids } } });
|
||||
* if (fillIds.length > 0) {
|
||||
* await model.update({ intercept_time: now }, { where: { id: { [Op.in]: fillIds } } });
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* @param {Array<Object>} rows 订单行(需含 id 与 intercept_time)
|
||||
* @return {Array<number>} 需要写入通知拦截时间的订单ID(正整数,保序去重)
|
||||
*/
|
||||
function pickNoticeTimeOrderIds(rows = []) {
|
||||
const seen = new Set();
|
||||
const orderIds = [];
|
||||
for (const row of (Array.isArray(rows) ? rows : [])) {
|
||||
if (!row || !isEmptyInterceptTime(row[INTERCEPT_TIME_FIELD])) {
|
||||
continue;
|
||||
}
|
||||
const orderId = Number(row.id || 0);
|
||||
if (!Number.isInteger(orderId) || orderId <= 0 || seen.has(orderId)) {
|
||||
continue;
|
||||
}
|
||||
seen.add(orderId);
|
||||
orderIds.push(orderId);
|
||||
}
|
||||
return orderIds;
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
INTERCEPT_TIME_FIELD,
|
||||
isEmptyInterceptTime,
|
||||
buildNoticeTimePatch,
|
||||
pickNoticeTimeOrderIds,
|
||||
};
|
||||
@ -106,19 +106,6 @@ const WAYBILL_CUSTOM_DISPLAY_TYPES = Object.freeze({
|
||||
PICK_LOCATION_NAME_BARCODE_QTY: '5',
|
||||
});
|
||||
|
||||
/**
|
||||
* 视频号(SPH)自定义区最大行数:超出部分全部舍弃。
|
||||
* 视频号面单自定义区仅可容纳 8 行文本,超过后客户端会出现溢出/错版。
|
||||
* @type {number}
|
||||
*/
|
||||
const SPH_CUSTOM_INFO_MAX_LINES = 8;
|
||||
|
||||
/**
|
||||
* 视频号(SPH)自定义区文本行分隔标记。
|
||||
* @type {string}
|
||||
*/
|
||||
const SPH_CUSTOM_INFO_LINE_BREAK = '<br>';
|
||||
|
||||
const ARRAY_STYLE_KEYS = new Set([
|
||||
'documents',
|
||||
'taskList',
|
||||
@ -650,29 +637,6 @@ function mergeWaybillCustomLines(lines = [], options = {}) {
|
||||
return text;
|
||||
}
|
||||
|
||||
/**
|
||||
* 截断视频号(SPH)自定义区文本行。
|
||||
*
|
||||
* 视频号面单自定义区最多打印 8 行,第 9 行起全部舍弃。
|
||||
* 统计口径为最终文本的全部分行(含首行头部与子单号行),空白行同样计入行数,不做过滤。
|
||||
*
|
||||
* @param {string} text 自定义区文本(以 `<br>` 分隔行)。
|
||||
* @return {string} 截断后的文本。
|
||||
*/
|
||||
function truncateSphCustomInfoLines(text) {
|
||||
const safeText = String(text === undefined || text === null ? '' : text);
|
||||
if (!safeText) {
|
||||
return safeText;
|
||||
}
|
||||
|
||||
const lines = safeText.split(SPH_CUSTOM_INFO_LINE_BREAK);
|
||||
if (lines.length <= SPH_CUSTOM_INFO_MAX_LINES) {
|
||||
return safeText;
|
||||
}
|
||||
|
||||
return lines.slice(0, SPH_CUSTOM_INFO_MAX_LINES).join(SPH_CUSTOM_INFO_LINE_BREAK);
|
||||
}
|
||||
|
||||
/**
|
||||
* 构建数组字段的精简骨架。
|
||||
*
|
||||
@ -2128,7 +2092,6 @@ function applyXhsExpressFieldMapping(
|
||||
* - taskList[0].printInfo 使用 order_express.printinfo(非空时)
|
||||
* - taskList[0].printNum.sumNum 使用 wave_total_orders,curNum 保持模板值,缺失时默认 1
|
||||
* - taskList[0].customInfo.data.description 使用现有商品汇总文本并按 <br> 拼接
|
||||
* - taskList[0].customInfo.data.description 最多保留 8 行(含首行头部与子单号行),第 9 行起全部舍弃
|
||||
* - taskList[0].extendData.sender 使用 policy_config 发件人信息
|
||||
* - taskList[0].taskID 优先沿用 buildPlatformRequestSkeleton 现有 taskId
|
||||
*
|
||||
@ -2203,15 +2166,12 @@ function applySphExpressFieldMapping(
|
||||
boxNo: Number(safeOrderDelivery.box_no || 0),
|
||||
}
|
||||
);
|
||||
// 视频号面单自定义区最多 8 行:子单号行 + 头部行 + 商品明细行合计截断,第 9 行起舍弃
|
||||
const customProductInfo = truncateSphCustomInfoLines(
|
||||
appendExtraCustomLines(
|
||||
mergeWaybillCustomLines(customProductInfoLines, {
|
||||
lineBreak: LINE_BREAK_MAP.LF,
|
||||
}).replace(/\n/g, SPH_CUSTOM_INFO_LINE_BREAK),
|
||||
extraCustomLines,
|
||||
SPH_CUSTOM_INFO_LINE_BREAK
|
||||
)
|
||||
const customProductInfo = appendExtraCustomLines(
|
||||
mergeWaybillCustomLines(customProductInfoLines, {
|
||||
lineBreak: LINE_BREAK_MAP.LF,
|
||||
}).replace(/\n/g, '<br>'),
|
||||
extraCustomLines,
|
||||
'<br>'
|
||||
);
|
||||
|
||||
task.customInfo = isPlainObject(task.customInfo) ? task.customInfo : {};
|
||||
|
||||
@ -1,8 +1,7 @@
|
||||
'use strict';
|
||||
|
||||
const crypto = require('crypto');
|
||||
const http = require('http');
|
||||
const https = require('https');
|
||||
const http = require('http');
|
||||
|
||||
class QimenClient {
|
||||
constructor(app) {
|
||||
@ -16,6 +15,7 @@ class QimenClient {
|
||||
|
||||
return {
|
||||
ctx,
|
||||
qimenLogId: runtime.qimenLogId ?? ctx.qimenLogId ?? null,
|
||||
toXml: runtime.toXml || (signService && typeof signService.toXml === 'function'
|
||||
? signService.toXml.bind(signService)
|
||||
: qimenService && typeof qimenService.formatResponse === 'function'
|
||||
@ -46,15 +46,6 @@ class QimenClient {
|
||||
return { request: data };
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成出站奇门请求的唯一日志 ID。
|
||||
* 不复用入站请求的 ctx.qimenLogId,避免与入站文件队列落库产生唯一索引冲突。
|
||||
* @return {string} 唯一日志 ID。
|
||||
*/
|
||||
generateLogId() {
|
||||
return `QL-${Date.now()}-${crypto.randomBytes(3).toString('hex')}`;
|
||||
}
|
||||
|
||||
replaceXmlTagsWithString(xmlString, oldTag, newTag) {
|
||||
const startTagRegex = new RegExp(`<\\s*${oldTag}(\\s+[^>]*)?>`, 'gi');
|
||||
const endTagRegex = new RegExp(`<\\s*/\\s*${oldTag}\\s*>`, 'gi');
|
||||
@ -191,30 +182,18 @@ class QimenClient {
|
||||
return { queryId: result.queryId, xmlArray };
|
||||
}
|
||||
|
||||
/**
|
||||
* 发送出站奇门 HTTP 请求,并把出站请求日志直接落库。
|
||||
* 出站日志使用独立生成的 log_id,不复用入站请求的 ctx.qimenLogId,
|
||||
* 避免与入站日志的文件队列落库路径产生 log_id 唯一索引冲突。
|
||||
* @param {string} url 请求地址。
|
||||
* @param {Object|string} requestData 请求数据(对象或 XML 字符串)。
|
||||
* @param {Object} [logData={}] 日志附加字段。
|
||||
* @param {Object} [runtime={}] 运行时依赖。
|
||||
* @return {Promise<{queryId: number|undefined, res: string}>} 查询 ID 与响应内容。
|
||||
*/
|
||||
async sendRequest(url, requestData, logData = {}, runtime = {}) {
|
||||
const helpers = this.resolveRuntime(runtime);
|
||||
const startTime = Date.now();
|
||||
// 出站请求不复用入站 ctx.qimenLogId:入站日志统一由文件队列异步落库,
|
||||
// log_id 唯一索引下共用同一 ID 会触发 Duplicate entry 冲突。
|
||||
const requestLogData = Object.assign({
|
||||
body: requestData,
|
||||
result: '',
|
||||
log_id: this.generateLogId(),
|
||||
log_id: helpers.qimenLogId,
|
||||
}, logData);
|
||||
|
||||
requestLogData.body = requestLogData.body || requestData;
|
||||
requestLogData.result = requestLogData.result || '';
|
||||
requestLogData.log_id = requestLogData.log_id || this.generateLogId();
|
||||
requestLogData.log_id = requestLogData.log_id || helpers.qimenLogId || null;
|
||||
|
||||
const httpquery = url.indexOf('https://') > -1 ? https : http;
|
||||
let requestXml;
|
||||
|
||||
@ -1,7 +1,7 @@
|
||||
'use strict';
|
||||
|
||||
module.exports = app => {
|
||||
const { BIGINT, DATE, JSON: JSON_TYPE } = app.Sequelize;
|
||||
const { BIGINT, DATE } = app.Sequelize;
|
||||
|
||||
const EntryOrderReceiving = app.model.define('wms_entry_order_receiving', {
|
||||
id: {
|
||||
@ -20,12 +20,6 @@ module.exports = app => {
|
||||
allowNull: false,
|
||||
comment: '收货单ID,关联 wms_receiving.id',
|
||||
},
|
||||
allocated_quantity: {
|
||||
type: JSON_TYPE,
|
||||
allowNull: true,
|
||||
defaultValue: null,
|
||||
comment: '数量台账:收货明细ID→已分配数量(JSON对象,如 {"123":8});null 表示旧数据未初始化',
|
||||
},
|
||||
created_at: {
|
||||
type: DATE,
|
||||
allowNull: false,
|
||||
|
||||
@ -92,12 +92,6 @@ module.exports = app => {
|
||||
defaultValue: 'MANUAL',
|
||||
comment: '创建来源渠道',
|
||||
},
|
||||
need_oms_waybill: {
|
||||
type: TINYINT(4),
|
||||
allowNull: false,
|
||||
defaultValue: 0,
|
||||
comment: '是否需要回OMS取号:0不需要 1需要(仅openapi创建来源使用,其他默认0)',
|
||||
},
|
||||
source_order_codes: {
|
||||
type: TEXT,
|
||||
allowNull: true,
|
||||
@ -435,7 +429,7 @@ module.exports = app => {
|
||||
type: TINYINT(4),
|
||||
allowNull: false,
|
||||
defaultValue: 0,
|
||||
comment: '波次范围:0未分配波次 1大团购 2散单 3小团购 4单品单件',
|
||||
comment: '波次范围:0未分配波次 1大团购 2散单 3小团购',
|
||||
},
|
||||
grab_operator_id: {
|
||||
type: BIGINT(20),
|
||||
@ -563,12 +557,6 @@ module.exports = app => {
|
||||
defaultValue: 'none',
|
||||
comment: '拦截状态机',
|
||||
},
|
||||
intercept_time: {
|
||||
type: DATE,
|
||||
allowNull: true,
|
||||
defaultValue: null,
|
||||
comment: '拦截时间(进入拦截流程/库内拦截确认时写入)',
|
||||
},
|
||||
};
|
||||
|
||||
// 主表模型
|
||||
|
||||
@ -17,19 +17,6 @@ const MANAGED_TYPES = Object.freeze({
|
||||
*/
|
||||
const AUTO_INCREMENT_SAFE_MARGIN = 50;
|
||||
|
||||
/**
|
||||
* 列表排序索引名称后缀。
|
||||
*
|
||||
* 列表接口固定带 warehouse_id 等值条件且默认按 updated_at / delivery_time 排序,
|
||||
* 对应的索引在 dispatch 分表中需要额外携带 dispatch_lane 才能覆盖 count 统计
|
||||
* (否则统计仍需逐行回表核对 dispatch_lane),因此 dispatch 分支需要识别并
|
||||
* 剔除从 current 继承来的同名后缀索引,改用自身版本,避免同一张表维护两份功能重叠的索引。
|
||||
*/
|
||||
const LIST_SORT_INDEX_SUFFIXES = Object.freeze([
|
||||
'_list_updated_at',
|
||||
'_list_delivery_time',
|
||||
]);
|
||||
|
||||
const TABLE_PATTERNS = Object.freeze([
|
||||
{
|
||||
type: MANAGED_TYPES.DISPATCH,
|
||||
@ -76,17 +63,6 @@ function isHistoryType(type) {
|
||||
return normalizeManagedType(type) === MANAGED_TYPES.HISTORY;
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断索引名是否属于列表排序索引。
|
||||
* @param {string} name 索引名。
|
||||
* @return {boolean} 是否为列表排序索引。
|
||||
*/
|
||||
function isListSortIndexName(name) {
|
||||
const normalizedName = String(name || '');
|
||||
|
||||
return LIST_SORT_INDEX_SUFFIXES.some(suffix => normalizedName.endsWith(suffix));
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断是否为 outsourced 类型。
|
||||
* @param {string} type 模型类型。
|
||||
@ -449,7 +425,7 @@ function buildTableAttributes(app, type) {
|
||||
attributes.id = { ...attributes.id, autoIncrement: false };
|
||||
|
||||
if (isDispatchType(modelType)) {
|
||||
const { ENUM, DATE } = app.Sequelize;
|
||||
const { ENUM } = app.Sequelize;
|
||||
attributes.dispatch_lane = {
|
||||
type: ENUM('m4', 'm5'),
|
||||
field: 'dispatch_lane',
|
||||
@ -457,12 +433,6 @@ function buildTableAttributes(app, type) {
|
||||
defaultValue: 'm4',
|
||||
comment: '配送工作台子域(M4正常/M5异常)',
|
||||
};
|
||||
attributes.dispath_time = {
|
||||
type: DATE,
|
||||
field: 'dispath_time',
|
||||
allowNull: true,
|
||||
comment: '订单迁移进配送表的时间',
|
||||
};
|
||||
}
|
||||
|
||||
if (isHistoryType(modelType)) {
|
||||
@ -546,41 +516,6 @@ function buildTableOptions(app, warehouseId, type) {
|
||||
return options;
|
||||
}
|
||||
|
||||
/**
|
||||
* 构建列表排序索引选项。
|
||||
*
|
||||
* 工作台订单列表(listByModule)的 SQL 形态固定为
|
||||
* `WHERE warehouse_id = ? [AND dispatch_lane = ?] ORDER BY <sortField> DESC, id DESC LIMIT ?`
|
||||
* 且并行执行同条件的 COUNT(*)。若没有与「过滤列前缀 + 排序列」一致的索引:
|
||||
* - 排序需要全表扫描 + filesort;
|
||||
* - COUNT(*) 需要逐行回表核对不在索引中的过滤列。
|
||||
* 生产 wms_order_delivery_1000028_dispatch(59 万行 / 1.1GB)实测单请求因此达到 2 秒,
|
||||
* 故在此显式声明 updated_at(前端请求的实际排序字段)与 delivery_time(deliveryOrder 模块默认排序字段)两份索引。
|
||||
*
|
||||
* @param {number|string} warehouseId 仓库ID。
|
||||
* @param {string} type 模型类型。
|
||||
* @return {Array<Object>} 列表排序索引选项。
|
||||
*/
|
||||
function buildListSortIndexes(warehouseId, type) {
|
||||
const modelType = normalizeManagedType(type);
|
||||
const dispatchType = isDispatchType(modelType);
|
||||
const namePrefix = dispatchType ? `idx_dispatch_${warehouseId}` : `idx_${warehouseId}_${modelType}`;
|
||||
// dispatch 分表的 where 恒定带 dispatch_lane(m4/m5),把该常量列放进索引前缀
|
||||
// 才能让 COUNT(*) 变成纯索引扫描;非 dispatch 分表没有该列。
|
||||
const scopeFields = dispatchType ? [ 'warehouse_id', 'dispatch_lane' ] : [ 'warehouse_id' ];
|
||||
|
||||
return [
|
||||
{
|
||||
name: `${namePrefix}_list_updated_at`,
|
||||
fields: [ ...scopeFields, 'updated_at', 'id' ],
|
||||
},
|
||||
{
|
||||
name: `${namePrefix}_list_delivery_time`,
|
||||
fields: [ ...scopeFields, 'delivery_time', 'id' ],
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 构建索引选项。
|
||||
* @param {number|string} warehouseId 仓库ID。
|
||||
@ -597,19 +532,13 @@ function buildIndexOptions(warehouseId, type) {
|
||||
name: `idx_dispatch_${warehouseId}_dispatch_lane`,
|
||||
fields: [ 'dispatch_lane', 'status' ],
|
||||
};
|
||||
// 继承 current 的索引,但剔除列表排序索引:current 版本的前缀不含 dispatch_lane,
|
||||
// 在 dispatch 分表上无法覆盖 count,须改用带 dispatch_lane 的版本(追加在末尾)
|
||||
const inheritedIndexes = baseIndexes
|
||||
.slice(3)
|
||||
.filter(index => !isListSortIndexName(index.name));
|
||||
|
||||
return [
|
||||
baseIndexes[0],
|
||||
baseIndexes[1],
|
||||
baseIndexes[2],
|
||||
dispatchLaneIndex,
|
||||
...inheritedIndexes,
|
||||
...buildListSortIndexes(warehouseId, modelType),
|
||||
...baseIndexes.slice(3),
|
||||
];
|
||||
}
|
||||
|
||||
@ -673,10 +602,6 @@ function buildIndexOptions(warehouseId, type) {
|
||||
});
|
||||
}
|
||||
|
||||
// 列表排序索引统一追加在末尾:已有索引的下标位置保持不变(dispatch 分支按
|
||||
// 下标继承 current 的前 3 个索引,测试与运行时缓存均依赖该顺序)。
|
||||
indexes.push(...buildListSortIndexes(warehouseId, modelType));
|
||||
|
||||
return indexes;
|
||||
}
|
||||
|
||||
@ -750,8 +675,6 @@ module.exports = {
|
||||
parseNumericConstraint,
|
||||
buildTableAttributes,
|
||||
buildTableName,
|
||||
buildListSortIndexes,
|
||||
isListSortIndexName,
|
||||
buildTableComment,
|
||||
buildTableOptions,
|
||||
buildIndexOptions,
|
||||
|
||||
@ -32,7 +32,7 @@ module.exports = app => {
|
||||
file_name: {
|
||||
type: STRING(200),
|
||||
allowNull: false,
|
||||
comment: '导出文件名模板(支持 {date}/{time}/{datetime}/{timestamp} 占位,如 7日出入库_{date}.xlsx)',
|
||||
comment: '导出文件名模板(支持 {date} 占位,如 7日出入库_{date}.xlsx)',
|
||||
},
|
||||
fields: {
|
||||
type: app.Sequelize.JSON,
|
||||
|
||||
@ -509,11 +509,21 @@ module.exports = app => {
|
||||
defaultValue: app.Sequelize.literal('CURRENT_TIMESTAMP'),
|
||||
comment: '更新时间',
|
||||
},
|
||||
logo_url: {
|
||||
type: STRING(255),
|
||||
allowNull: true,
|
||||
comment: 'logo链接',
|
||||
},
|
||||
project: {
|
||||
type: STRING(20),
|
||||
allowNull: true,
|
||||
comment: '应用',
|
||||
},
|
||||
domain: {
|
||||
type: STRING(100),
|
||||
allowNull: true,
|
||||
comment: '绑定域名',
|
||||
},
|
||||
auth_end: {
|
||||
type: DATE,
|
||||
allowNull: true,
|
||||
|
||||
@ -1,155 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 视频补录请求记录表模型(wms_video_record_request)。
|
||||
*
|
||||
* 站内信查询打包视频 / 退件拆包视频时发现"视频不可用"(无视频记录或全部 failed),
|
||||
* 登记一条补录请求(状态机 pending → requested → recording → completed / failed),
|
||||
* 同时向录制服务推送强制录制;后续查询命中可用视频时由业务层回写 completed + video_url。
|
||||
*
|
||||
* @param {import('egg').Application} app Egg 应用实例。
|
||||
* @return {import('sequelize').ModelCtor<import('sequelize').Model>} Sequelize 模型。
|
||||
*/
|
||||
module.exports = app => {
|
||||
const { BIGINT, INTEGER, STRING, DATE, ENUM, TINYINT } = app.Sequelize;
|
||||
|
||||
const VideoRecordRequest = app.model.define('video_record_request', {
|
||||
id: {
|
||||
type: BIGINT(20).UNSIGNED,
|
||||
primaryKey: true,
|
||||
autoIncrement: true,
|
||||
comment: '主键ID',
|
||||
},
|
||||
warehouse_id: {
|
||||
type: BIGINT(20).UNSIGNED,
|
||||
allowNull: false,
|
||||
comment: '仓库ID',
|
||||
},
|
||||
store_id: {
|
||||
type: BIGINT(20).UNSIGNED,
|
||||
allowNull: false,
|
||||
defaultValue: 0,
|
||||
comment: '货主ID,0=未知',
|
||||
},
|
||||
biz_type: {
|
||||
type: ENUM('pack', 'unpack'),
|
||||
allowNull: false,
|
||||
comment: '业务类型:pack-打包视频 unpack-退件拆包视频',
|
||||
},
|
||||
biz_id: {
|
||||
type: BIGINT(20).UNSIGNED,
|
||||
allowNull: false,
|
||||
comment: '业务ID:pack=wms_pack_task.id,unpack=wms_return_unpack.id',
|
||||
},
|
||||
waybill_code: {
|
||||
type: STRING(64),
|
||||
allowNull: true,
|
||||
comment: '触发查询的运单号',
|
||||
},
|
||||
group_id: {
|
||||
type: STRING(100),
|
||||
allowNull: true,
|
||||
comment: '触发查询的群ID(站内信外部群ID,回信必填)',
|
||||
},
|
||||
group_name: {
|
||||
type: STRING(100),
|
||||
allowNull: true,
|
||||
comment: '触发查询的群名称',
|
||||
},
|
||||
user_id: {
|
||||
type: STRING(100),
|
||||
allowNull: true,
|
||||
comment: '触发查询的用户ID(站内信外部用户ID,回信必填)',
|
||||
},
|
||||
user_name: {
|
||||
type: STRING(100),
|
||||
allowNull: true,
|
||||
comment: '触发查询的用户名称',
|
||||
},
|
||||
source: {
|
||||
type: STRING(20),
|
||||
allowNull: false,
|
||||
defaultValue: 'inbox',
|
||||
comment: '触发来源:inbox-站内信查询',
|
||||
},
|
||||
status: {
|
||||
type: ENUM('pending', 'requested', 'recording', 'completed', 'failed'),
|
||||
allowNull: false,
|
||||
defaultValue: 'pending',
|
||||
comment: '状态机:pending-待推送 requested-已推送 recording-录制中 completed-已完成 failed-失败',
|
||||
},
|
||||
request_count: {
|
||||
type: INTEGER.UNSIGNED,
|
||||
allowNull: false,
|
||||
defaultValue: 0,
|
||||
comment: '推送录制服务次数',
|
||||
},
|
||||
last_request_at: {
|
||||
type: DATE,
|
||||
allowNull: true,
|
||||
comment: '最近一次请求录制服务时间(含推送失败)',
|
||||
},
|
||||
print_computer_id: {
|
||||
type: BIGINT(20).UNSIGNED,
|
||||
allowNull: true,
|
||||
comment: '录制电脑ID,关联 wms_print_computer.id',
|
||||
},
|
||||
request_error: {
|
||||
type: STRING(500),
|
||||
allowNull: true,
|
||||
comment: '推送失败原因(无录制电脑/电脑不在线/打印服务异常)',
|
||||
},
|
||||
video_url: {
|
||||
type: STRING(500),
|
||||
allowNull: true,
|
||||
comment: '录制完成后回写的视频地址',
|
||||
},
|
||||
is_notified: {
|
||||
type: TINYINT(1),
|
||||
allowNull: false,
|
||||
defaultValue: 0,
|
||||
comment: '录制结果是否已通知查询方:0=未通知,1=已通知',
|
||||
},
|
||||
notified_at: {
|
||||
type: DATE,
|
||||
allowNull: true,
|
||||
comment: '录制结果通知时间',
|
||||
},
|
||||
remark: {
|
||||
type: STRING(500),
|
||||
allowNull: true,
|
||||
comment: '备注',
|
||||
},
|
||||
created_at: {
|
||||
type: DATE,
|
||||
allowNull: false,
|
||||
comment: '创建时间',
|
||||
},
|
||||
updated_at: {
|
||||
type: DATE,
|
||||
allowNull: false,
|
||||
comment: '更新时间',
|
||||
},
|
||||
deleted_at: {
|
||||
type: DATE,
|
||||
allowNull: true,
|
||||
comment: '软删除时间',
|
||||
},
|
||||
}, {
|
||||
tableName: 'wms_video_record_request',
|
||||
comment: '视频补录请求记录表',
|
||||
timestamps: true,
|
||||
createdAt: 'created_at',
|
||||
updatedAt: 'updated_at',
|
||||
paranoid: true,
|
||||
deletedAt: 'deleted_at',
|
||||
indexes: [
|
||||
{ name: 'idx_warehouse_biz', fields: [ 'warehouse_id', 'biz_type', 'biz_id' ] },
|
||||
{ name: 'idx_waybill_code', fields: [ 'waybill_code' ] },
|
||||
{ name: 'idx_status_notified_last_request', fields: [ 'status', 'is_notified', 'last_request_at' ] },
|
||||
{ name: 'idx_deleted_at', fields: [ 'deleted_at' ] },
|
||||
],
|
||||
});
|
||||
|
||||
return VideoRecordRequest;
|
||||
};
|
||||
@ -1,165 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 仓库前端个性化配置模型(仓库伪独立部署,单表)。
|
||||
* - 每仓库一行(一仓一域一证书):保存仓库前端 Logo / 标题 / 登录页图 /
|
||||
* 主题等个性化配置,以及证书元信息与证书 PEM 内容(cert_pem / cert_key,由定时
|
||||
* 任务读取后写文件部署,禁止写入日志/接口响应)。
|
||||
* - sync_status 状态机:0-待同步,1-同步成功,2-同步失败;
|
||||
* 管理后台保存后置为待同步,由定时任务同步到 nginx 后回写状态。
|
||||
* - 证书启用/停用由整行删除或 sync_status 表达;证书到期由 cert_expire_at
|
||||
* 判断,不单独保留证书 status 列。
|
||||
* - domain 唯一索引(uk_domain)为 MySQL 可空列唯一索引:允许多个 NULL,
|
||||
* 应用层在写入非空 domain 前必须做唯一性校验,不能依赖数据库约束报错。
|
||||
* - store_id 唯一索引(uk_store_id):每仓一行,由数据库层保证。
|
||||
* - 不启用 paranoid:配置为"每仓库一行"的元数据,删除语义由业务层
|
||||
* (清空/停用配置)表达,表结构不含 deleted_at 列。
|
||||
*
|
||||
* @param {Object} app Egg.js Application 实例。
|
||||
* @return {Object} Sequelize Model 定义。
|
||||
*/
|
||||
module.exports = app => {
|
||||
const { BIGINT, STRING, INTEGER, TINYINT, DATE, TEXT, JSON: JSON_TYPE } = app.Sequelize;
|
||||
|
||||
const WarehouseFrontConfig = app.model.define('warehouse_front_config', {
|
||||
id: {
|
||||
type: BIGINT(20).UNSIGNED,
|
||||
primaryKey: true,
|
||||
autoIncrement: true,
|
||||
allowNull: false,
|
||||
comment: '主键ID',
|
||||
},
|
||||
store_id: {
|
||||
type: BIGINT(20).UNSIGNED,
|
||||
allowNull: false,
|
||||
references: {
|
||||
model: 'store',
|
||||
key: 'id',
|
||||
},
|
||||
comment: '仓库ID,关联 wms_store.id(is_warehouse=1),每仓一行',
|
||||
},
|
||||
domain: {
|
||||
type: STRING(100),
|
||||
allowNull: true,
|
||||
comment: '仓库自持域名;可空列唯一索引允许多个 NULL,非空值唯一性需应用层校验',
|
||||
},
|
||||
title: {
|
||||
type: STRING(100),
|
||||
allowNull: true,
|
||||
comment: '站点标题',
|
||||
},
|
||||
logo_url: {
|
||||
type: STRING(255),
|
||||
allowNull: true,
|
||||
comment: 'Logo地址',
|
||||
},
|
||||
favicon_url: {
|
||||
type: STRING(255),
|
||||
allowNull: true,
|
||||
comment: '站点 favicon 图标地址',
|
||||
},
|
||||
login_bg_url: {
|
||||
type: STRING(255),
|
||||
allowNull: true,
|
||||
comment: '登录页背景图地址',
|
||||
},
|
||||
theme: {
|
||||
type: JSON_TYPE,
|
||||
allowNull: true,
|
||||
defaultValue: null,
|
||||
comment: '主题配置JSON(颜色/布局等)',
|
||||
},
|
||||
cert_path: {
|
||||
type: STRING(500),
|
||||
allowNull: true,
|
||||
comment: '证书文件路径(只存路径不存内容)',
|
||||
},
|
||||
cert_pem: {
|
||||
type: TEXT,
|
||||
allowNull: true,
|
||||
comment: '证书 PEM 内容(私钥不在内);内容仅由定时任务读取,禁止写入日志/接口响应',
|
||||
},
|
||||
key_path: {
|
||||
type: STRING(500),
|
||||
allowNull: true,
|
||||
comment: '私钥文件路径(只存路径不存内容)',
|
||||
},
|
||||
cert_key: {
|
||||
type: TEXT,
|
||||
allowNull: true,
|
||||
comment: '私钥 PEM 内容;内容仅由定时任务读取,禁止写入日志/接口响应',
|
||||
},
|
||||
cert_expire_at: {
|
||||
type: DATE,
|
||||
allowNull: true,
|
||||
comment: '证书到期时间',
|
||||
},
|
||||
sync_status: {
|
||||
type: TINYINT,
|
||||
allowNull: false,
|
||||
defaultValue: 0,
|
||||
validate: {
|
||||
isIn: {
|
||||
args: [[ 0, 1, 2 ]],
|
||||
msg: '同步状态不合法:0-待同步,1-同步成功,2-同步失败',
|
||||
},
|
||||
},
|
||||
comment: '同步状态:0-待同步,1-同步成功,2-同步失败',
|
||||
},
|
||||
sync_attempts: {
|
||||
type: INTEGER(11),
|
||||
allowNull: false,
|
||||
defaultValue: 0,
|
||||
comment: '同步尝试次数',
|
||||
},
|
||||
last_sync_error: {
|
||||
type: STRING(500),
|
||||
allowNull: true,
|
||||
comment: '最近一次同步失败原因',
|
||||
},
|
||||
last_synced_at: {
|
||||
type: DATE,
|
||||
allowNull: true,
|
||||
comment: '最近一次同步成功时间',
|
||||
},
|
||||
created_at: {
|
||||
type: DATE,
|
||||
allowNull: false,
|
||||
defaultValue: app.Sequelize.literal('CURRENT_TIMESTAMP'),
|
||||
comment: '创建时间',
|
||||
},
|
||||
updated_at: {
|
||||
type: DATE,
|
||||
allowNull: false,
|
||||
defaultValue: app.Sequelize.literal('CURRENT_TIMESTAMP'),
|
||||
comment: '更新时间',
|
||||
},
|
||||
}, {
|
||||
tableName: 'wms_warehouse_front_config',
|
||||
freezeTableName: true,
|
||||
underscored: true,
|
||||
timestamps: true,
|
||||
createdAt: 'created_at',
|
||||
updatedAt: 'updated_at',
|
||||
paranoid: false,
|
||||
comment: '仓库前端个性化配置表(含证书内容与元信息)',
|
||||
indexes: [
|
||||
{
|
||||
name: 'uk_store_id',
|
||||
unique: true,
|
||||
fields: [ 'store_id' ],
|
||||
},
|
||||
{
|
||||
name: 'uk_domain',
|
||||
unique: true,
|
||||
fields: [ 'domain' ],
|
||||
},
|
||||
{
|
||||
name: 'idx_sync_status',
|
||||
fields: [ 'sync_status' ],
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
return WarehouseFrontConfig;
|
||||
};
|
||||
@ -97,11 +97,6 @@ module.exports = app => {
|
||||
allowNull: true,
|
||||
comment: '校验结果',
|
||||
},
|
||||
recheck_start_time: {
|
||||
type: DATE,
|
||||
allowNull: true,
|
||||
comment: '复核开始时间',
|
||||
},
|
||||
priority: {
|
||||
type: TINYINT,
|
||||
allowNull: true,
|
||||
|
||||
@ -47,7 +47,7 @@ module.exports = app => {
|
||||
type: STRING(20),
|
||||
allowNull: false,
|
||||
defaultValue: 'pending',
|
||||
comment: '状态:pending/processing/done/failed/waiting_oms(waiting_oms=需要回 OMS 取号,等待外部接入,终态不重试)',
|
||||
comment: '状态:pending/processing/done/failed',
|
||||
},
|
||||
retry_count: {
|
||||
type: INTEGER(3),
|
||||
|
||||
@ -52,11 +52,6 @@ module.exports = app => {
|
||||
allowNull: true,
|
||||
comment: '工作台令牌(随机64位,绑定后生成)',
|
||||
},
|
||||
token_updated_at: {
|
||||
type: DATE,
|
||||
allowNull: true,
|
||||
comment: '工作台 token 最后更新时间(无 token 时为 NULL)',
|
||||
},
|
||||
created_at: {
|
||||
type: DATE,
|
||||
allowNull: false,
|
||||
|
||||
@ -39,9 +39,6 @@ module.exports = app => {
|
||||
// OpenAPI 回调测试 — 所有环境均可访问的独立调试页面
|
||||
router.get('/docs/api/openapi/callback-test', controller.openapiCallback.testPage);
|
||||
|
||||
// OpenAPI 出站回调文档 — 所有环境均可访问
|
||||
router.get('/docs/api/openapi_callback', controller.docs.openapiCallbackEvents);
|
||||
|
||||
// 仅开发环境可访问的 docs 通配路由(静态文件),必须在 /docs/api/openapi 之后注册
|
||||
if (app.config.env === 'local') {
|
||||
router.get('/docs/:relPath(.*)', controller.docs.docsFile);
|
||||
|
||||
@ -7,8 +7,7 @@
|
||||
* - 按仓库拉取 subject_config 中配置的打包最大时长
|
||||
* (散单 single_order_pack_max_minutes / 团购 group_order_pack_max_minutes,单位分钟);
|
||||
* - 当 当前时间 - 开始时间 > 配置时长 时自动结束,
|
||||
* 将 end_time 置为 开始时间 + 上限时长,状态置为已完成(2);
|
||||
* - 任务结束后同步将该工作台关联摄像头的 OSD 叠加复位为「无任务」。
|
||||
* 将 end_time 置为 开始时间 + 上限时长,状态置为已完成(2)。
|
||||
*/
|
||||
module.exports = {
|
||||
schedule: {
|
||||
|
||||
@ -3,11 +3,10 @@
|
||||
const path = require('path');
|
||||
|
||||
/**
|
||||
* 定时消费奇门日志文件队列,逐条幂等插入数据库。
|
||||
* 定时消费奇门日志文件队列,逐条插入数据库。
|
||||
* 间隔 30 秒执行,type: worker(仅一个 worker 执行)。
|
||||
* 使用 fileWriter.consumeFiles 内置的逐条进度追踪,
|
||||
* 任一记录插入失败即停止,下次从失败位置重试。
|
||||
* 同一 log_id 已落库时视为幂等命中直接跳过,避免唯一索引冲突卡死队列。
|
||||
*/
|
||||
module.exports = {
|
||||
schedule: {
|
||||
@ -17,11 +16,6 @@ module.exports = {
|
||||
disable: false,
|
||||
},
|
||||
|
||||
/**
|
||||
* 消费奇门日志队列任务入口。
|
||||
* @param {Egg.Context} ctx Egg 上下文。
|
||||
* @return {Promise<void>} 无返回值。
|
||||
*/
|
||||
async task(ctx) {
|
||||
// 防止重入
|
||||
if (ctx.app._consumeQimenLogsRunning) return;
|
||||
@ -38,7 +32,7 @@ module.exports = {
|
||||
maxConsumeRecordsPerWindow: 500,
|
||||
parseJson: true,
|
||||
onRecord: async record => {
|
||||
const row = {
|
||||
await mysql.insert('wms_qimen_log', {
|
||||
log_id: record.log_id || null,
|
||||
from_key: record.from_key || '',
|
||||
to_key: record.to_key || '',
|
||||
@ -51,17 +45,7 @@ module.exports = {
|
||||
body: record.body || '',
|
||||
result: record.result || '',
|
||||
use_time: record.use_time || 0,
|
||||
};
|
||||
try {
|
||||
await mysql.insert('wms_qimen_log', row);
|
||||
} catch (err) {
|
||||
const isDuplicate = !!err && (err.code === 'ER_DUP_ENTRY' || err.errno === 1062);
|
||||
if (!isDuplicate) {
|
||||
throw err;
|
||||
}
|
||||
// 同一 log_id 已落库时视为幂等命中,跳过并继续推进消费进度
|
||||
ctx.logger.warn(`[consume-qimen-logs] 跳过重复日志 log_id=${row.log_id}`);
|
||||
}
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
|
||||
@ -215,28 +215,12 @@ async function consumePendingRows(ctx) {
|
||||
}
|
||||
|
||||
try {
|
||||
const pipelineResult = await expressService.createWaybillCodePipeline(orders, {
|
||||
await expressService.createWaybillCodePipeline(orders, {
|
||||
awaitTasks: true,
|
||||
warehouseId: group.warehouseId,
|
||||
});
|
||||
|
||||
// 需要回 OMS 取号的订单已由流水线分流:对应队列行置等待终态,不参与本地重试,
|
||||
// 等外部 OMS 取号能力开发完成后再统一处理。
|
||||
const needOmsWaybillOrderIdSet = new Set(
|
||||
(pipelineResult && Array.isArray(pipelineResult.skipped_need_oms_waybill_order_ids)
|
||||
? pipelineResult.skipped_need_oms_waybill_order_ids
|
||||
: [])
|
||||
.map(orderId => Number(orderId))
|
||||
.filter(orderId => Number.isInteger(orderId) && orderId > 0)
|
||||
);
|
||||
const waitingRows = group.rows.filter(row => needOmsWaybillOrderIdSet.has(Number(row.order_id)));
|
||||
const allocatableRows = group.rows.filter(row => !needOmsWaybillOrderIdSet.has(Number(row.order_id)));
|
||||
if (waitingRows.length > 0) {
|
||||
await updateQueueRowsStatus(ctx, waitingRows, 'waiting_oms', '等待外部OMS取号');
|
||||
ctx.logger.info(`[consume-waybill-allocate-queue] 组内订单需要回 OMS 取号,已置等待态 warehouse_id=${group.warehouseId} store_id=${group.storeId} waiting=${waitingRows.length}`);
|
||||
}
|
||||
|
||||
// 5) 判定结果:取到单号(status=1)的订单视为完成(仅统计参与本地取号的队列行)
|
||||
// 5) 判定结果:取到单号(status=1)的订单视为完成
|
||||
const doneKeySet = new Set();
|
||||
if (orderExpressModel && typeof orderExpressModel.findAll === 'function') {
|
||||
const doneRows = await orderExpressModel.findAll({
|
||||
@ -256,13 +240,13 @@ async function consumePendingRows(ctx) {
|
||||
}
|
||||
}
|
||||
|
||||
const doneRows = allocatableRows.filter(row => doneKeySet.has(`${Number(row.order_id)}:${Number(row.business_key) || 1}`));
|
||||
const restRows = allocatableRows.filter(row => !doneKeySet.has(`${Number(row.order_id)}:${Number(row.business_key) || 1}`));
|
||||
const doneRows = group.rows.filter(row => doneKeySet.has(`${Number(row.order_id)}:${Number(row.business_key) || 1}`));
|
||||
const restRows = group.rows.filter(row => !doneKeySet.has(`${Number(row.order_id)}:${Number(row.business_key) || 1}`));
|
||||
|
||||
await updateQueueRowsStatus(ctx, doneRows, 'done', null);
|
||||
await markGroupRetryOrFailed(ctx, restRows, '运单分配未完成', false);
|
||||
|
||||
ctx.logger.info(`[consume-waybill-allocate-queue] 组消费完成 warehouse_id=${group.warehouseId} store_id=${group.storeId} total=${group.rows.length} done=${doneRows.length} rest=${restRows.length} waiting_oms=${waitingRows.length}`);
|
||||
ctx.logger.info(`[consume-waybill-allocate-queue] 组消费完成 warehouse_id=${group.warehouseId} store_id=${group.storeId} total=${group.rows.length} done=${doneRows.length} rest=${restRows.length}`);
|
||||
} catch (error) {
|
||||
ctx.logger.error(`[consume-waybill-allocate-queue] 组消费失败 warehouse_id=${group.warehouseId} store_id=${group.storeId}: ${error.message}`);
|
||||
await markGroupRetryOrFailed(ctx, group.rows, error && error.message ? error.message : String(error), false);
|
||||
|
||||
@ -1,116 +0,0 @@
|
||||
// app/schedule/intercept_auto_confirm.js
|
||||
'use strict';
|
||||
|
||||
const EXECUTION_LOG_CACHE_KEY = 'schedule:intercept_auto_confirm:last_execution';
|
||||
const EXECUTION_LOG_CACHE_TTL = 900; // 15 分钟
|
||||
const EXECUTION_LOG_HISTORY_CACHE_KEY = 'schedule:intercept_auto_confirm:history';
|
||||
const EXECUTION_LOG_HISTORY_MAX = 20; // 保留最近 20 次执行记录
|
||||
const EXECUTION_LOG_HISTORY_TTL = 86400; // 1 天
|
||||
|
||||
/**
|
||||
* 将本次执行日志写入缓存。
|
||||
*
|
||||
* @param {Object} ctx Egg 上下文。
|
||||
* @param {Object} logEntry 日志条目。
|
||||
* @return {Promise<void>} 无返回值。
|
||||
*/
|
||||
async function writeExecutionLogToCache(ctx, logEntry) {
|
||||
try {
|
||||
if (ctx.app && typeof ctx.app.setCacheAsync === 'function') {
|
||||
await ctx.app.setCacheAsync(EXECUTION_LOG_CACHE_KEY, logEntry, EXECUTION_LOG_CACHE_TTL);
|
||||
}
|
||||
} catch (err) {
|
||||
ctx.logger.warn(`[intercept-auto-confirm] 写入执行日志缓存失败: ${err.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 将本次执行日志追加到历史记录缓存(保留最近 N 次)。
|
||||
*
|
||||
* @param {Object} ctx Egg 上下文。
|
||||
* @param {Object} logEntry 日志条目。
|
||||
* @return {Promise<void>} 无返回值。
|
||||
*/
|
||||
async function appendExecutionHistory(ctx, logEntry) {
|
||||
try {
|
||||
if (typeof ctx.app.getCacheAsync !== 'function' || typeof ctx.app.setCacheAsync !== 'function') {
|
||||
return;
|
||||
}
|
||||
|
||||
const rawHistory = await ctx.app.getCacheAsync(EXECUTION_LOG_HISTORY_CACHE_KEY);
|
||||
const history = Array.isArray(rawHistory) ? rawHistory : [];
|
||||
history.unshift(logEntry);
|
||||
await ctx.app.setCacheAsync(
|
||||
EXECUTION_LOG_HISTORY_CACHE_KEY,
|
||||
history.slice(0, EXECUTION_LOG_HISTORY_MAX),
|
||||
EXECUTION_LOG_HISTORY_TTL
|
||||
);
|
||||
} catch (err) {
|
||||
ctx.logger.warn(`[intercept-auto-confirm] 写入执行历史缓存失败: ${err.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 每 1 小时在单 worker 中执行一次自动库内拦截确定。
|
||||
*
|
||||
* 扫描待处理表(current 分表)中「拦截状态为请求拦截(intercept_status='requested')
|
||||
* 且面单未打印(print_status='none')」的订单,满足拦截时间超 12 小时或
|
||||
* 创建时间超 36 小时任一条件时,自动执行库内拦截确定。
|
||||
*/
|
||||
module.exports = {
|
||||
schedule: {
|
||||
interval: '1h',
|
||||
type: 'worker',
|
||||
immediate: false,
|
||||
disable: false,
|
||||
},
|
||||
|
||||
/**
|
||||
* 执行自动库内拦截确定任务。
|
||||
*
|
||||
* @param {Object} ctx Egg 上下文。
|
||||
* @return {Promise<void>} 无返回值。
|
||||
*/
|
||||
async task(ctx) {
|
||||
if (ctx.app._interceptAutoConfirmRunning) {
|
||||
return;
|
||||
}
|
||||
|
||||
ctx.app._interceptAutoConfirmRunning = true;
|
||||
|
||||
const startedAt = Date.now();
|
||||
let status = 'success';
|
||||
let errorMessage = '';
|
||||
let result = null;
|
||||
|
||||
try {
|
||||
result = await ctx.service.systems.interceptAutoConfirm.runAutoConfirm();
|
||||
} catch (error) {
|
||||
status = 'error';
|
||||
errorMessage = error.message;
|
||||
ctx.logger.error(`[intercept-auto-confirm] 执行失败: ${error.message}`);
|
||||
} finally {
|
||||
ctx.app._interceptAutoConfirmRunning = false;
|
||||
}
|
||||
|
||||
const logEntry = {
|
||||
executed_at: new Date().toISOString(),
|
||||
duration_ms: Date.now() - startedAt,
|
||||
status,
|
||||
error_message: errorMessage,
|
||||
warehouse_count: result ? result.warehouse_count : 0,
|
||||
candidate_count: result ? result.candidate_count : 0,
|
||||
confirmed_count: result ? result.confirmed_count : 0,
|
||||
failed_count: result ? result.failed_count : 0,
|
||||
warehouse_ids: result ? result.warehouse_ids : [],
|
||||
};
|
||||
await writeExecutionLogToCache(ctx, logEntry);
|
||||
await appendExecutionHistory(ctx, logEntry);
|
||||
|
||||
ctx.logger.info(
|
||||
`[intercept-auto-confirm] 本轮完成 warehouses=${logEntry.warehouse_count}`
|
||||
+ ` candidate=${logEntry.candidate_count} confirmed=${logEntry.confirmed_count}`
|
||||
+ ` failed=${logEntry.failed_count} duration=${logEntry.duration_ms}ms`
|
||||
);
|
||||
},
|
||||
};
|
||||
@ -1,60 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 视频补录状态收敛 + 结果通知定时任务。
|
||||
*
|
||||
* 每分钟在单 worker 中串行执行两段:
|
||||
* 1) settleStatuses:把「在途且未通知」的补录请求收敛为终态
|
||||
* (视频已产出 → completed;录制服务失败 / 超过超时阈值 → failed),只改状态不通知;
|
||||
* 2) notifyResults:扫「终态且未通知」的记录回信到触发查询的群
|
||||
* (有用户信息时定向回原用户),成功后标记 is_notified=1;失败记录额外转仓库客服群人工处理。
|
||||
*
|
||||
* 单轮处理条数由 config.inbox.videoRecordNotifyLimit 控制(默认 10),
|
||||
* 超时阈值由 config.inbox.videoRecordNotifyTimeoutMs 控制(默认 1 小时)。
|
||||
*/
|
||||
module.exports = {
|
||||
schedule: {
|
||||
interval: '1m',
|
||||
type: 'worker',
|
||||
immediate: false,
|
||||
disable: false,
|
||||
},
|
||||
|
||||
/**
|
||||
* 执行视频补录状态收敛与结果通知。
|
||||
*
|
||||
* 两段串行,顺序不可颠倒:
|
||||
* 1) settleStatuses:只把在途记录收敛为终态(completed / failed),不通知;
|
||||
* 2) notifyResults:扫「终态且未通知」的记录回信(成功复用原查询链路文案,失败转人工)。
|
||||
*
|
||||
* @param {Object} ctx Egg 上下文。
|
||||
* @return {Promise<void>} 无返回值。
|
||||
*/
|
||||
async task(ctx) {
|
||||
if (ctx.app._videoRecordNotifyRunning) {
|
||||
return;
|
||||
}
|
||||
|
||||
ctx.app._videoRecordNotifyRunning = true;
|
||||
|
||||
try {
|
||||
const settle = await ctx.service.systems.videoRecordRequest.settleStatuses();
|
||||
const result = await ctx.service.systems.videoRecordRequest.notifyResults();
|
||||
const settleChanged = settle
|
||||
&& (settle.completed > 0 || settle.failed > 0 || settle.timeout > 0 || settle.invalid > 0);
|
||||
if (settleChanged || (result && (result.notified > 0 || result.skipped > 0))) {
|
||||
ctx.logger.info(
|
||||
`[notify-video-record] 本轮完成 settle(scanned=${settle && settle.scanned} completed=${settle && settle.completed} ` +
|
||||
`failed=${settle && settle.failed} timeout=${settle && settle.timeout} invalid=${settle && settle.invalid}) ` +
|
||||
`notify(scanned=${result && result.scanned} notified=${result && result.notified} ` +
|
||||
`completed=${result && result.completed} failed=${result && result.failed} ` +
|
||||
`timeout=${result && result.timeout} skipped=${result && result.skipped})`
|
||||
);
|
||||
}
|
||||
} catch (error) {
|
||||
ctx.logger.error(`[notify-video-record] 任务执行失败: ${error.message}`);
|
||||
} finally {
|
||||
ctx.app._videoRecordNotifyRunning = false;
|
||||
}
|
||||
},
|
||||
};
|
||||
@ -104,9 +104,7 @@ module.exports = {
|
||||
status,
|
||||
error_message: errorMessage,
|
||||
candidate_count: result ? result.candidate_count : 0,
|
||||
empty_count: result ? result.empty_count : 0,
|
||||
closed_count: result ? result.closed_count : 0,
|
||||
pending_confirm_count: result ? result.pending_confirm_count : 0,
|
||||
warehouse_ids: result ? result.warehouse_ids : [],
|
||||
closed_waves: result ? result.closed_waves : [],
|
||||
};
|
||||
@ -114,8 +112,7 @@ module.exports = {
|
||||
await appendExecutionHistory(ctx, logEntry);
|
||||
|
||||
ctx.logger.info(
|
||||
`[sync-finished-wave-batch] 本轮完成 closed=${result ? result.closed_count : 0} candidate=${result ? result.candidate_count : 0}`
|
||||
+ ` pendingConfirm=${result ? result.pending_confirm_count : 0} warehouses=${result ? result.warehouse_ids.length : 0}`
|
||||
`[sync-finished-wave-batch] 本轮完成 closed=${result ? result.closed_count : 0} candidate=${result ? result.candidate_count : 0} warehouses=${result ? result.warehouse_ids.length : 0}`
|
||||
);
|
||||
},
|
||||
};
|
||||
|
||||
@ -1,88 +0,0 @@
|
||||
// app/schedule/system_log_cleanup.js
|
||||
'use strict';
|
||||
|
||||
/** @type {number} 默认单批硬删除行数 */
|
||||
const DEFAULT_BATCH_SIZE = 2000;
|
||||
/** @type {number} 默认批间休眠最小毫秒数 */
|
||||
const DEFAULT_SLEEP_MIN_MS = 100;
|
||||
/** @type {number} 默认批间休眠最大毫秒数 */
|
||||
const DEFAULT_SLEEP_MAX_MS = 500;
|
||||
|
||||
/**
|
||||
* 系统日志超期清理定时任务。
|
||||
*
|
||||
* 默认每日凌晨 03:00:00(cron:秒 分 时 日 月 周)在单 worker 中执行一次,
|
||||
* 硬删除 wms_system_log 超过保留天数(默认 60 天)的日志以释放磁盘空间,避开 08:00–23:00 业务高峰。
|
||||
* cron 从 config.systemLogCleanup.cron 读取(config.default.js 提供默认值),
|
||||
* 本地环境可在 config.local.js 覆盖为短间隔以便快速验证,不影响生产 03:00 触发时间。
|
||||
* 保留天数由 service.systems.systemLog 读取 config.systemLogCleanup.retainDays(默认 60,非法值回退 60);
|
||||
* 由 config.systemLogCleanup 控制:enable=false 时不注册本任务;
|
||||
* 实际清理逻辑收敛在 service.systems.systemLog.cleanupExpiredSystemLogs。
|
||||
*
|
||||
* @param {Object} app Egg 应用实例。
|
||||
* @return {Object} 定时任务定义(含 schedule 与 task)。
|
||||
*/
|
||||
module.exports = app => {
|
||||
const cleanupConfig = (app.config && app.config.systemLogCleanup) || {};
|
||||
// cron 从配置读取,缺省时回退为每日凌晨 03:00(cron 格式:秒 分 时 日 月 周)
|
||||
const cleanupCron = typeof cleanupConfig.cron === 'string' && cleanupConfig.cron
|
||||
? cleanupConfig.cron
|
||||
: '0 0 3 * * *';
|
||||
|
||||
return {
|
||||
schedule: {
|
||||
cron: cleanupCron,
|
||||
type: 'worker',
|
||||
immediate: false,
|
||||
disable: cleanupConfig.enable === false,
|
||||
},
|
||||
|
||||
/**
|
||||
* 执行系统日志超期清理。
|
||||
*
|
||||
* 采用单 worker 防重入:上一轮未结束时跳过本轮;
|
||||
* 任务失败只记录错误日志,不向上抛出,避免导致 schedule 崩溃。
|
||||
*
|
||||
* @param {Object} ctx Egg 上下文。
|
||||
* @return {Promise<void>} 无返回值。
|
||||
*/
|
||||
async task(ctx) {
|
||||
const scheduleName = 'system_log_cleanup';
|
||||
|
||||
if (ctx.app._systemLogCleanupRunning) {
|
||||
ctx.logger.info(`[${scheduleName}] 本轮任务跳过,上一轮尚未结束`);
|
||||
return;
|
||||
}
|
||||
|
||||
ctx.app._systemLogCleanupRunning = true;
|
||||
const startedAt = Date.now();
|
||||
try {
|
||||
const config = ctx.app.config.systemLogCleanup || {};
|
||||
// 保留天数(retainDays)由 service 读取 config.systemLogCleanup.retainDays 自行解析,此处不再透传
|
||||
const options = {
|
||||
batchSize: Number(config.batchSize) > 0
|
||||
? Math.floor(Number(config.batchSize))
|
||||
: DEFAULT_BATCH_SIZE,
|
||||
sleepMinMs: Number(config.sleepMinMs) >= 0
|
||||
? Math.floor(Number(config.sleepMinMs))
|
||||
: DEFAULT_SLEEP_MIN_MS,
|
||||
sleepMaxMs: Number(config.sleepMaxMs) >= 0
|
||||
? Math.floor(Number(config.sleepMaxMs))
|
||||
: DEFAULT_SLEEP_MAX_MS,
|
||||
};
|
||||
|
||||
const summary = await ctx.service.systems.systemLog.cleanupExpiredSystemLogs(options);
|
||||
|
||||
ctx.logger.info(
|
||||
`[${scheduleName}] 本轮完成 skipped=${summary.skipped} boundary_id=${summary.boundary_id}`
|
||||
+ ` batches=${summary.batch_count} deleted=${summary.deleted_rows}`
|
||||
+ ` duration=${Date.now() - startedAt}ms`
|
||||
);
|
||||
} catch (error) {
|
||||
ctx.logger.error(`[${scheduleName}] 执行失败: ${error.message}`);
|
||||
} finally {
|
||||
ctx.app._systemLogCleanupRunning = false;
|
||||
}
|
||||
},
|
||||
};
|
||||
};
|
||||
@ -1,69 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
/** @type {number} 扫描间隔兜底默认值(毫秒):1 小时,配置缺失时使用 */
|
||||
const DEFAULT_SCAN_INTERVAL_MS = 60 * 60 * 1000;
|
||||
/** @type {number} token 有效期兜底默认值(毫秒):3 个月(按 30 天/月折算),配置缺失时使用 */
|
||||
const DEFAULT_MAX_AGE_MS = 3 * 30 * 24 * 60 * 60 * 1000;
|
||||
/** @type {number} 批处理兜底默认值(条) */
|
||||
const DEFAULT_BATCH_SIZE = 50;
|
||||
|
||||
/**
|
||||
* 工作台 token 超期强制下线定时任务。
|
||||
* 由 config.workbenchTokenExpire 控制:
|
||||
* - enable=false 时不注册本任务;
|
||||
* - scanIntervalMs 控制扫描间隔(毫秒),开发环境可覆盖为短循环便于测试;
|
||||
* - maxAgeMs 控制 token 有效期阈值,token_updated_at 距今超过该时长即强制下线;
|
||||
* - batchSize 控制单批处理条数。
|
||||
* 实际清理逻辑收敛在 service.systems.workbench.clearExpiredWorkbenchTokens。
|
||||
* @param {Object} app Egg 应用实例
|
||||
* @return {Object} 定时任务定义(含 schedule 与 task)
|
||||
*/
|
||||
module.exports = app => {
|
||||
const workbenchTokenExpire = (app.config && app.config.workbenchTokenExpire) || {};
|
||||
const scanIntervalMs = Number(workbenchTokenExpire.scanIntervalMs) > 0
|
||||
? Number(workbenchTokenExpire.scanIntervalMs)
|
||||
: DEFAULT_SCAN_INTERVAL_MS;
|
||||
|
||||
return {
|
||||
schedule: {
|
||||
interval: scanIntervalMs,
|
||||
type: 'worker',
|
||||
immediate: false,
|
||||
disable: workbenchTokenExpire.enable === false,
|
||||
},
|
||||
|
||||
/**
|
||||
* 扫描并清理 token 超期未更新的工作台,使其强制下线。
|
||||
* 采用单 worker 防重入:上一轮未结束时跳过本轮。
|
||||
* @param {Object} ctx Egg 上下文
|
||||
* @return {Promise<void>} 无返回值
|
||||
*/
|
||||
async task(ctx) {
|
||||
const scheduleName = 'workbench_token_expire';
|
||||
const config = ctx.app.config.workbenchTokenExpire || {};
|
||||
|
||||
if (ctx.app._workbenchTokenExpireRunning) {
|
||||
ctx.logger.info(`[${scheduleName}] 本轮任务跳过,上一轮尚未结束`);
|
||||
return;
|
||||
}
|
||||
|
||||
ctx.app._workbenchTokenExpireRunning = true;
|
||||
try {
|
||||
const maxAgeMs = Number(config.maxAgeMs) > 0 ? Number(config.maxAgeMs) : DEFAULT_MAX_AGE_MS;
|
||||
const batchSize = Number(config.batchSize) > 0 ? Math.floor(Number(config.batchSize)) : DEFAULT_BATCH_SIZE;
|
||||
const expiredBefore = new Date(Date.now() - maxAgeMs);
|
||||
|
||||
const summary = await ctx.service.systems.workbench.clearExpiredWorkbenchTokens({
|
||||
expiredBefore,
|
||||
batchSize,
|
||||
});
|
||||
|
||||
ctx.logger.info(`[${scheduleName}] 本轮扫描完成:maxAgeMs=${maxAgeMs} expiredBefore=${expiredBefore.toISOString()} scanned=${summary.total_scanned} cleared=${summary.total_cleared} failed=${summary.total_failed}`);
|
||||
} catch (error) {
|
||||
ctx.logger.error(`[${scheduleName}] 执行失败: ${error.message}`);
|
||||
} finally {
|
||||
ctx.app._workbenchTokenExpireRunning = false;
|
||||
}
|
||||
},
|
||||
};
|
||||
};
|
||||
@ -266,7 +266,7 @@ ${historyContext}
|
||||
- 需要上下文但记忆不足时,主动调用 recallHistory 回顾对话历史
|
||||
- 【防误判规则 - interceptWaybill】讨论已有售后工单(AS开头编号)、询问物流进度、问"快递到哪了"、转发售后截图等均不是拦截请求,严禁调用 interceptWaybill。只有用户明确说"拦截/退回/召回/追回/取消"运单时才可调用
|
||||
- 【规则 - requestPickup】货主售后群/仓库客服群中客户要求上门揽收/取件(如"揽收""上门取件""退货取件""寄回""让快递来拿"等)且提供了运单号时,调用 requestPickup(keyword=运单号,多个用逗号分隔)。函数会创建揽收售后工单,并优先转发到对应快递的揽收群(未配置揽收群时回退到售后群);返回的 data.message 是模板消息必须原样回复;若消息中无运单号,先向客户确认运单号再调用
|
||||
- 【措辞规则 - interceptWaybill】拦截结果回复严禁使用"已拦截""拦截成功"等确定口吻,必须使用"拦截信息已登记""已提交拦截申请"等措辞。因为快递拦截可能失败,实际结果以快递公司反馈为准。回复时必须给出运单号与处理结果,严禁把售后单号(AS 开头编号)回复给用户
|
||||
- 【措辞规则 - interceptWaybill】拦截结果回复严禁使用"已拦截""拦截成功"等确定口吻,必须使用"拦截信息已登记""已提交拦截申请"等措辞。因为快递拦截可能失败,实际结果以快递公司反馈为准。回复时需列出工单号供用户跟进
|
||||
- 【规则 - handleStoreFeedback】货主售后群中客户反馈"错发/发错""破损/坏了""多发/发多""少发/漏发"且提供了运单号时,调用 handleStoreFeedback 创建售后工单(初始状态未开始处理,不通知快递群);若消息中无运单号,先向客户确认运单号再调用
|
||||
- 【规则 - handleExpressFeedback】快递售后群中,快递客服反馈处理进度/结果(如"已通知网点""网点正在处理""已拦截""已联系收件人""改地址失败/无法改""已签收""加急处理"等)且消息含运单号时,必须调用 handleExpressFeedback(keyword=运单号,多个用逗号分隔)。该函数会自动查找已有售后工单追加反馈并回信到相关群,无工单则自动创建。严禁把快递客服的进度/结果反馈判定为无需处理而 silent;若消息无运单号,先用 recallHistory 或询问确认运单号,严禁跳过
|
||||
- 【规则 - handleExpressFeedback 证据核实】快递售后群中快递方发消息要求"提供交易记录截图/未收到依据/核实签收/带日期单号"等证据类诉求且消息含运单号时,同样必须调用 handleExpressFeedback(as_sub_type=verify_delivery),由函数创建售后工单并回信到货主售后群;严禁仅回复"收到/已记录"等确认话术而不调用函数
|
||||
@ -278,7 +278,7 @@ ${historyContext}
|
||||
- 【规则 - createPostnum】货主售后群中客户要求"出单/打单/打印单/催发货/分配快递号"且提供了订单号时,调用 createPostnum(keyword=订单号,多个用逗号分隔);仅待处理表已审核且未分配快递号的订单可分配,函数会走分配流程并按结果返回"已分配+已回传"或"分配失败,等待客服人工处理"模板;返回的 data.message 是模板消息必须原样回复;若消息中无订单号,先向客户确认订单号再调用
|
||||
- 【模板消息 - queryReturn】queryReturn 返回的 data.message 是已排版好的模板消息,必须原样作为最终回复输出,禁止改写、删减、增补内容,禁止添加 Markdown 或额外说明
|
||||
- 【规则 - queryWarehouseAddress】用户询问"仓库地址/收货地址/退货地址/退件地址/寄回地址"时,调用 queryWarehouseAddress 查询仓库配置中的 receiver_address;返回的 data.message 是模板消息必须原样回复
|
||||
- 【模板消息 - handleStoreFeedback】handleStoreFeedback 返回的 data.message 是已排版好的模板消息(运单号+问题类型+"稍后客服将人工核实跟进"),必须原样作为最终回复输出,禁止改写、删减或增补内容,严禁补充售后单号
|
||||
- 【模板消息 - handleStoreFeedback】handleStoreFeedback 返回的 data.message 是已排版好的模板消息(运单号+问题类型+工单号+"稍后客服将人工核实跟进"),必须原样作为最终回复输出,禁止改写、删减或增补内容
|
||||
- 用户发送"查退回+运单号"时,调用 queryReturn 查询退回明细,不要误调 queryOrder 或 interceptWaybill
|
||||
- 【查询类请求强制调函数】查订单/查退回/查库存等查询类请求必须实际调用对应函数获取结果后再回复,严禁仅凭历史对话或猜测臆测"服务不可用/无法处理"而跳过函数调用
|
||||
- 【历史失败回复免疫】群历史中 AI 的历史回复(尤其含"失败""异常""无法处理"等字样的兜底回复)只是历史记录,不代表当前功能不可用;严禁模仿、引用这类历史回复,也严禁据此判断函数不可用而拒绝调用;登记/操作/查询类请求必须实际调用对应函数获取最新结果`;
|
||||
|
||||
@ -4,7 +4,6 @@ const Service = require('egg').Service;
|
||||
|
||||
// 群类型常量定义统一收口到 inbox/groups.js
|
||||
const { GROUP } = require('./groups');
|
||||
const { pickNoticeTimeOrderIds } = require('../../lib/intercept_time');
|
||||
|
||||
/**
|
||||
* 站内信函数注册表。
|
||||
@ -164,10 +163,10 @@ class InboxFunctionsService extends Service {
|
||||
};
|
||||
}
|
||||
|
||||
// 查已有快递单号(强制同仓校验:同时匹配订单ID与仓库ID)
|
||||
// 查已有快递单号
|
||||
const existingExpress = await ctx.model.OrderExpress.findOne({
|
||||
attributes: [ 'waybill_code', 'logistics_name', 'status' ],
|
||||
where: { order_id: orderDelivery.id, business_key: 1, warehouse_id: warehouseId },
|
||||
where: { order_id: orderDelivery.id, business_key: 1 },
|
||||
raw: true,
|
||||
});
|
||||
|
||||
@ -835,12 +834,6 @@ class InboxFunctionsService extends Service {
|
||||
reason: { type: 'string', required: false, description: '拦截原因' },
|
||||
},
|
||||
groups: [ GROUP.BOUND_WAREHOUSE_CUSTOMER_SERVICE, GROUP.BOUND_STORE_AFTER_SALES ],
|
||||
/**
|
||||
* 拦截运单处理器:批量创建售后工单,并按波次规则写入订单拦截状态
|
||||
* intercept_status='requested' 与拦截时间 intercept_time。
|
||||
* @param {Object} params 入参,包含 keyword(运单号)与 reason(拦截原因)。
|
||||
* @return {Promise<Object>} 处理结果,包含 success 与 data/error。
|
||||
*/
|
||||
handler: async (params = {}) => {
|
||||
const { ctx } = this;
|
||||
const raw = String(params.keyword || '').trim();
|
||||
@ -922,20 +915,13 @@ class InboxFunctionsService extends Service {
|
||||
// 过滤掉已存在工单的
|
||||
const toCreate = validList.filter(e => !existingWaybillIds.has(e.id));
|
||||
const alreadyExist = existingASList.map(r => r.after_sale_no);
|
||||
// 已存在工单对应的运单号(去重):客户回信只给运单号,不暴露售后单号
|
||||
const alreadyExistWbs = [ ...new Set(existingASList.map(r => {
|
||||
const hit = validList.find(v => Number(v.id) === Number(r.waybill_id));
|
||||
return hit ? hit.waybill_code : '';
|
||||
}).filter(Boolean)) ];
|
||||
|
||||
if (toCreate.length === 0) {
|
||||
return {
|
||||
success: true,
|
||||
data: {
|
||||
existed: true,
|
||||
message: alreadyExistWbs.length > 0
|
||||
? `运单${alreadyExistWbs.join('、')} 已有处理中的拦截申请`
|
||||
: '拦截信息已登记过,无需重复提交',
|
||||
message: `运单已存在处理中的拦截工单: ${alreadyExist.join('、')}`,
|
||||
after_sale_nos: alreadyExist,
|
||||
},
|
||||
};
|
||||
@ -998,7 +984,7 @@ class InboxFunctionsService extends Service {
|
||||
const orderModel = await ctx.model.OrderDeliveryFactory.getCurrentModel(warehouseId);
|
||||
if (orderModel) {
|
||||
const orders = await orderModel.findAll({
|
||||
attributes: [ 'id', 'step', 'wave_id', 'inspection_status', 'intercept_time' ],
|
||||
attributes: [ 'id', 'step', 'wave_id', 'inspection_status' ],
|
||||
where: {
|
||||
id: { [ctx.app.Sequelize.Op.in]: orderIds },
|
||||
step: { [ctx.app.Sequelize.Op.in]: [ 1, 2, 3 ] },
|
||||
@ -1074,23 +1060,12 @@ class InboxFunctionsService extends Service {
|
||||
}
|
||||
}
|
||||
|
||||
// 执行拦截状态设置(订单表 + 运单表;通知拦截时间只在首次发起时写入,不覆盖已有值)
|
||||
// 执行拦截状态设置(订单表 + 运单表)
|
||||
if (interceptOrderIds.length > 0) {
|
||||
const noticeNow = new Date();
|
||||
const interceptIdSet = new Set(interceptOrderIds.map(id => Number(id)));
|
||||
const fillNoticeOrderIds = pickNoticeTimeOrderIds(
|
||||
orders.filter(order => interceptIdSet.has(Number(order.id)))
|
||||
);
|
||||
await orderModel.update(
|
||||
{ intercept_status: 'requested' },
|
||||
{ where: { id: { [ctx.app.Sequelize.Op.in]: interceptOrderIds } } }
|
||||
);
|
||||
if (fillNoticeOrderIds.length > 0) {
|
||||
await orderModel.update(
|
||||
{ intercept_time: noticeNow },
|
||||
{ where: { id: { [ctx.app.Sequelize.Op.in]: fillNoticeOrderIds } } }
|
||||
);
|
||||
}
|
||||
// 同步更新运单表拦截标记
|
||||
await ctx.model.OrderExpress.update(
|
||||
{ is_intercept: 'Y' },
|
||||
@ -1180,19 +1155,14 @@ class InboxFunctionsService extends Service {
|
||||
}
|
||||
|
||||
// 第六步:有通知的工单升级为 pending_feedback
|
||||
// 同时收集运单号:客户回信只给运单号 + 处理内容,不再暴露售后单号
|
||||
const notifiedAsNos = [];
|
||||
const notNotifiedAsNos = [];
|
||||
const notifiedWbs = [];
|
||||
const notNotifiedWbs = [];
|
||||
for (const e of toCreate) {
|
||||
const asNo = waybillToAsNo[e.id];
|
||||
if (notifiedWaybillIds.has(e.id)) {
|
||||
notifiedAsNos.push(asNo);
|
||||
notifiedWbs.push(e.waybill_code);
|
||||
} else {
|
||||
notNotifiedAsNos.push(asNo);
|
||||
notNotifiedWbs.push(e.waybill_code);
|
||||
}
|
||||
}
|
||||
|
||||
@ -1215,16 +1185,16 @@ class InboxFunctionsService extends Service {
|
||||
);
|
||||
}
|
||||
|
||||
// 构造返回消息(运单号 + 处理内容,不含售后单号)
|
||||
// 构造返回消息
|
||||
const parts = [];
|
||||
if (notifiedWbs.length > 0) {
|
||||
parts.push(`运单${notifiedWbs.join('、')} 拦截信息已登记,已通知快递群`);
|
||||
if (notifiedAsNos.length > 0) {
|
||||
parts.push(`拦截信息已登记并通知快递群,工单: ${notifiedAsNos.join('、')}`);
|
||||
}
|
||||
if (notNotifiedWbs.length > 0) {
|
||||
parts.push(`运单${notNotifiedWbs.join('、')} 拦截信息已登记(未配置快递群,需人工跟进)`);
|
||||
if (notNotifiedAsNos.length > 0) {
|
||||
parts.push(`拦截信息已登记(未配置快递群,需人工跟进),工单: ${notNotifiedAsNos.join('、')}`);
|
||||
}
|
||||
if (alreadyExistWbs.length > 0) {
|
||||
parts.push(`运单${alreadyExistWbs.join('、')} 拦截信息已登记过`);
|
||||
if (alreadyExist.length > 0) {
|
||||
parts.push(`已登记过,工单: ${alreadyExist.join('、')}`);
|
||||
}
|
||||
if (skipped.length > 0) {
|
||||
parts.push(`无权操作: ${skipped.join('、')}`);
|
||||
@ -1612,49 +1582,14 @@ class InboxFunctionsService extends Service {
|
||||
}
|
||||
lines.push('');
|
||||
lines.push('退件录像地址为:');
|
||||
const unpackId = Number(unpack.id || 0);
|
||||
if (videos.length > 0) {
|
||||
for (const video of videos) {
|
||||
if (video.video_url) lines.push(String(video.video_url));
|
||||
}
|
||||
lines.push('拆包视频保存会有延迟,可以在稍后发送:查退回+运单号,查询');
|
||||
// 视频已可用:推进补录请求状态为 completed(回写视频地址)
|
||||
if (unpackId > 0) {
|
||||
try {
|
||||
await ctx.service.systems.videoRecordRequest.syncByVideos({
|
||||
biz_type: 'unpack',
|
||||
biz_id: unpackId,
|
||||
videos,
|
||||
});
|
||||
} catch (err) {
|
||||
ctx.logger.warn(`[inbox functions] 拆包视频补录状态同步失败 unpack=${unpackId}: ${err.message}`);
|
||||
}
|
||||
}
|
||||
} else if (unpackId > 0) {
|
||||
// 视频不可用:登记补录请求并推送录制服务重新录制(录制服务不可用时仅登记,不阻断查询)
|
||||
let inFlight = false;
|
||||
try {
|
||||
const req = await ctx.service.systems.videoRecordRequest.requestUnpackVideo({
|
||||
warehouse_id: warehouseId,
|
||||
unpack_id: unpackId,
|
||||
waybill_code: waybill,
|
||||
store_id: Number(unpack.store_id || 0),
|
||||
group_id: String(ctx.inboxContext?.group_id || '').trim(),
|
||||
group_name: String(ctx.inboxContext?.group_name || '').trim(),
|
||||
user_id: String(ctx.inboxContext?.user_id || '').trim(),
|
||||
user_name: String(ctx.inboxContext?.user_name || '').trim(),
|
||||
source: 'inbox',
|
||||
});
|
||||
inFlight = Boolean(req && (req.pushed || (req.reused && req.status !== 'failed')));
|
||||
} catch (err) {
|
||||
ctx.logger.warn(`[inbox functions] 拆包视频补录推送失败 unpack=${unpackId}: ${err.message}`);
|
||||
}
|
||||
lines.push(inFlight
|
||||
? '视频暂不可用,已推送重新录制,请稍等通知录制结果'
|
||||
: '视频暂不可用,已登记补录,请稍后重试');
|
||||
} else {
|
||||
lines.push('暂无');
|
||||
}
|
||||
lines.push('拆包视频保存会有延迟,可以在稍后发送:查退回+运单号,查询');
|
||||
message = lines.join('\n');
|
||||
} else if (result.status === 'received') {
|
||||
message = `包裹${waybill}已收到未拆包,拆包登记后,将自动发送通知拆包信息`;
|
||||
@ -1700,12 +1635,6 @@ class InboxFunctionsService extends Service {
|
||||
reason: { type: 'string', required: false, description: '取消拦截原因' },
|
||||
},
|
||||
groups: [ GROUP.BOUND_WAREHOUSE_CUSTOMER_SERVICE, GROUP.BOUND_STORE_AFTER_SALES ],
|
||||
/**
|
||||
* 取消拦截处理器:为运单创建/追加取消拦截工单,并按波次规则重新写入
|
||||
* 订单拦截状态 intercept_status='requested' 与拦截时间 intercept_time。
|
||||
* @param {Object} params 入参,包含 keyword(运单号)与 reason(取消拦截原因)。
|
||||
* @return {Promise<Object>} 处理结果,包含 success 与 data/error。
|
||||
*/
|
||||
handler: async (params = {}) => {
|
||||
const { ctx } = this;
|
||||
const raw = String(params.keyword || '').trim();
|
||||
@ -1778,7 +1707,6 @@ class InboxFunctionsService extends Service {
|
||||
} catch (e) { /* ignore */ }
|
||||
|
||||
let feedbackCount = 0;
|
||||
const feedbackWbs = [];
|
||||
const cancelGroup = ctx.inboxContext?.group_name || '未知群';
|
||||
const cancelUser = ctx.inboxContext?.user_name || '未知用户';
|
||||
const cancelTime = new Date().toISOString().slice(0, 19)
|
||||
@ -1798,19 +1726,13 @@ class InboxFunctionsService extends Service {
|
||||
remark: remarkLines.join('\n'),
|
||||
});
|
||||
feedbackCount += 1;
|
||||
if (as.waybill_no) feedbackWbs.push(as.waybill_no);
|
||||
} catch (e) {
|
||||
ctx.logger.warn(`[inbox functions] 取消拦截反馈失败 as_no=${as.after_sale_no}: ${e.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
const parts = [];
|
||||
if (feedbackCount > 0) {
|
||||
const wbs = [ ...new Set(feedbackWbs) ];
|
||||
parts.push(wbs.length > 0
|
||||
? `运单${wbs.join('、')} 取消拦截信息已登记(已追加到处理中的工单)`
|
||||
: `取消拦截信息已登记 ${feedbackCount} 个`);
|
||||
}
|
||||
if (feedbackCount > 0) parts.push(`已有工单追加取消拦截: ${feedbackCount}个`);
|
||||
|
||||
// 第四步:无工单的按拦截规则创建
|
||||
const createdNos = [];
|
||||
@ -1839,12 +1761,7 @@ class InboxFunctionsService extends Service {
|
||||
createdNos.push(afterSaleNo);
|
||||
}
|
||||
}
|
||||
if (createdNos.length > 0) {
|
||||
const wbs = toCreate.map(e => e.waybill_code).filter(Boolean);
|
||||
parts.push(wbs.length > 0
|
||||
? `运单${wbs.join('、')} 取消拦截信息已登记(已创建处理工单)`
|
||||
: `取消拦截信息已登记 ${createdNos.length} 个`);
|
||||
}
|
||||
if (createdNos.length > 0) parts.push(`已创建取消拦截工单: ${createdNos.length}个`);
|
||||
|
||||
ctx.logger.info(
|
||||
`[inbox functions] 取消拦截: total=${keywords.length} ` +
|
||||
@ -1858,7 +1775,7 @@ class InboxFunctionsService extends Service {
|
||||
const orderModel = await ctx.model.OrderDeliveryFactory.getCurrentModel(warehouseId);
|
||||
if (orderModel) {
|
||||
const orders = await orderModel.findAll({
|
||||
attributes: [ 'id', 'step', 'wave_id', 'inspection_status', 'intercept_time' ],
|
||||
attributes: [ 'id', 'step', 'wave_id', 'inspection_status' ],
|
||||
where: { id: { [ctx.app.Sequelize.Op.in]: orderIds }, step: { [ctx.app.Sequelize.Op.in]: [ 1, 2, 3 ] } },
|
||||
raw: true,
|
||||
});
|
||||
@ -1903,21 +1820,10 @@ class InboxFunctionsService extends Service {
|
||||
if (needIntercept) interceptOrderIds.push(order.id);
|
||||
}
|
||||
if (interceptOrderIds.length > 0) {
|
||||
const noticeNow = new Date();
|
||||
const interceptIdSet = new Set(interceptOrderIds.map(id => Number(id)));
|
||||
const fillNoticeOrderIds = pickNoticeTimeOrderIds(
|
||||
orders.filter(order => interceptIdSet.has(Number(order.id)))
|
||||
);
|
||||
await orderModel.update(
|
||||
{ intercept_status: 'requested' },
|
||||
{ where: { id: { [ctx.app.Sequelize.Op.in]: interceptOrderIds } } }
|
||||
);
|
||||
if (fillNoticeOrderIds.length > 0) {
|
||||
await orderModel.update(
|
||||
{ intercept_time: noticeNow },
|
||||
{ where: { id: { [ctx.app.Sequelize.Op.in]: fillNoticeOrderIds } } }
|
||||
);
|
||||
}
|
||||
await ctx.model.OrderExpress.update(
|
||||
{ is_intercept: 'Y' },
|
||||
{ where: { order_id: { [ctx.app.Sequelize.Op.in]: interceptOrderIds }, warehouse_id: warehouseId } }
|
||||
@ -2081,12 +1987,12 @@ class InboxFunctionsService extends Service {
|
||||
const alreadyExist = existingASList.map(r => r.after_sale_no);
|
||||
|
||||
/**
|
||||
* 组装客户回信模板:运单号 + 问题信息(不暴露售后单号)。
|
||||
* @param {Array<{waybill: string, as_no: string}>} pairs 运单号→工单号列表(as_no 仅内部使用)。
|
||||
* 组装客户回信模板:单号 + 问题信息 + 工单号。
|
||||
* @param {Array<{waybill: string, as_no: string}>} pairs 运单号→工单号列表。
|
||||
* @return {string} 模板消息。
|
||||
*/
|
||||
const buildReply = pairs => {
|
||||
const lines = pairs.map(p => `运单${p.waybill} ${issue.label}问题已登记`);
|
||||
const lines = pairs.map(p => `运单${p.waybill} ${issue.label}问题已登记,工单:${p.as_no}`);
|
||||
if (notFound.length > 0) {
|
||||
lines.push(`未找到运单:${notFound.join('、')},请核实单号`);
|
||||
}
|
||||
@ -2621,12 +2527,12 @@ class InboxFunctionsService extends Service {
|
||||
}
|
||||
}
|
||||
|
||||
// 第六步:客户回信模板(运单号 + 诉求,不暴露售后单号)
|
||||
// 第六步:客户回信模板(单号+诉求+工单)
|
||||
const createdPairs = toCreate.map(e => ({
|
||||
waybill: e.waybill_code,
|
||||
as_no: waybillToAsNo[e.id] || '',
|
||||
}));
|
||||
const lines = [ ...createdPairs, ...existedPairs ].map(p => `运单${p.waybill} ${issue.label}问题已登记`);
|
||||
const lines = [ ...createdPairs, ...existedPairs ].map(p => `运单${p.waybill} ${issue.label}问题已登记,工单:${p.as_no}`);
|
||||
if (notFound.length > 0) {
|
||||
lines.push(`未找到运单:${notFound.join('、')},请核实单号`);
|
||||
}
|
||||
@ -3139,7 +3045,7 @@ class InboxFunctionsService extends Service {
|
||||
});
|
||||
|
||||
this.register('queryPackVideo', {
|
||||
description: '打包视频查询。传入运单号,查询该运单对应的打包视频:散单按订单查打包记录,团购单按波次查打包记录。有视频返回视频地址;视频不可用时自动登记补录请求并向录制服务推送强制录制(回复“视频暂不可用,已推送重新录制,请稍等通知录制结果”,推送失败则“视频暂不可用,已登记补录,请稍后重试”);无打包记录提示无打包记录。仅查询,不创建工单',
|
||||
description: '打包视频查询。传入运单号,查询该运单对应的打包视频:散单按订单查打包记录,团购单按波次查打包记录。有视频返回视频地址;有打包记录无视频提示稍后再试;无打包记录提示无打包记录。仅查询,不创建工单',
|
||||
weight: 86,
|
||||
keywords: [ '打包视频', '打包录像', '装箱视频', '打包监控', '录像' ],
|
||||
params: {
|
||||
@ -3152,11 +3058,6 @@ class InboxFunctionsService extends Service {
|
||||
const storeId = Number(ctx.inboxContext?.store_id || 0);
|
||||
const warehouseId = Number(ctx.inboxContext?.warehouse_id || 0);
|
||||
const groupType = String(ctx.inboxContext?.group_type || '').trim();
|
||||
// 触发查询的群/人员:写入补录请求,供后续录制结果回发原群、@原用户
|
||||
const inboxGroupId = String(ctx.inboxContext?.group_id || '').trim();
|
||||
const inboxGroupName = String(ctx.inboxContext?.group_name || '').trim();
|
||||
const inboxUserId = String(ctx.inboxContext?.user_id || '').trim();
|
||||
const inboxUserName = String(ctx.inboxContext?.user_name || '').trim();
|
||||
|
||||
if (!raw) return { success: false, error: '请提供运单号' };
|
||||
if (!warehouseId) return { success: false, error: '无法获取仓库信息' };
|
||||
@ -3210,11 +3111,9 @@ class InboxFunctionsService extends Service {
|
||||
}
|
||||
|
||||
const videoLines = [];
|
||||
const noVideoWbs = [];
|
||||
const noRecordWbs = [];
|
||||
const orderMissingWbs = [];
|
||||
// 视频不可用已推送重新录制 / 仅登记补录(推送失败)
|
||||
const reRecordWbs = [];
|
||||
const reRecordFailedWbs = [];
|
||||
|
||||
for (const e of validList) {
|
||||
// 第二步:查订单行(优先序列表定位,未命中回退 当前→历史→配送 遍历)
|
||||
@ -3305,45 +3204,9 @@ class InboxFunctionsService extends Service {
|
||||
.filter(Boolean);
|
||||
|
||||
if (urls.length === 0) {
|
||||
// 视频不可用:登记补录请求并推送录制服务重新录制(录制服务不可用时仅登记,不阻断查询)
|
||||
let inFlight = 0;
|
||||
for (const task of packTasks) {
|
||||
try {
|
||||
const req = await ctx.service.systems.videoRecordRequest.requestPackVideo({
|
||||
warehouse_id: warehouseId,
|
||||
pack_task_id: task.id,
|
||||
waybill_code: e.waybill_code,
|
||||
store_id: Number(e.store_id || 0),
|
||||
group_id: inboxGroupId,
|
||||
group_name: inboxGroupName,
|
||||
user_id: inboxUserId,
|
||||
user_name: inboxUserName,
|
||||
source: 'inbox',
|
||||
});
|
||||
if (req && (req.pushed || (req.reused && req.status !== 'failed'))) inFlight += 1;
|
||||
} catch (err) {
|
||||
ctx.logger.warn(`[inbox functions] 打包视频补录推送失败 task=${task.id}: ${err.message}`);
|
||||
}
|
||||
}
|
||||
if (inFlight > 0) {
|
||||
reRecordWbs.push(e.waybill_code);
|
||||
} else {
|
||||
reRecordFailedWbs.push(e.waybill_code);
|
||||
}
|
||||
noVideoWbs.push(e.waybill_code);
|
||||
} else {
|
||||
videoLines.push(`${e.waybill_code}\n${urls.join('\n')}`);
|
||||
// 视频已可用:推进补录请求状态为 completed(回写视频地址)
|
||||
for (const task of packTasks) {
|
||||
try {
|
||||
await ctx.service.systems.videoRecordRequest.syncByVideos({
|
||||
biz_type: 'pack',
|
||||
biz_id: task.id,
|
||||
videos,
|
||||
});
|
||||
} catch (err) {
|
||||
ctx.logger.warn(`[inbox functions] 打包视频补录状态同步失败 task=${task.id}: ${err.message}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ -3352,13 +3215,9 @@ class InboxFunctionsService extends Service {
|
||||
if (videoLines.length > 0) {
|
||||
lines.push(videoLines.join('\n'));
|
||||
}
|
||||
if (reRecordWbs.length > 0) {
|
||||
lines.push(reRecordWbs.join('\n'));
|
||||
lines.push('视频暂不可用,已推送重新录制,请稍等通知录制结果');
|
||||
}
|
||||
if (reRecordFailedWbs.length > 0) {
|
||||
lines.push(reRecordFailedWbs.join('\n'));
|
||||
lines.push('视频暂不可用,已登记补录,请稍后重试');
|
||||
if (noVideoWbs.length > 0) {
|
||||
lines.push(noVideoWbs.join('\n'));
|
||||
lines.push('打包视频可能还未保存,请稍后再试');
|
||||
}
|
||||
if (noRecordWbs.length > 0) {
|
||||
lines.push(noRecordWbs.join('\n'));
|
||||
@ -3376,17 +3235,14 @@ class InboxFunctionsService extends Service {
|
||||
|
||||
ctx.logger.info(
|
||||
`[inbox functions] 打包视频查询: total=${keywords.length} found=${validList.length} ` +
|
||||
`video=${videoLines.length} reRecord=${reRecordWbs.length} reRecordFailed=${reRecordFailedWbs.length} ` +
|
||||
`noRecord=${noRecordWbs.length}`
|
||||
`video=${videoLines.length} noVideo=${noVideoWbs.length} noRecord=${noRecordWbs.length}`
|
||||
);
|
||||
|
||||
return {
|
||||
success: true,
|
||||
data: {
|
||||
has_video: videoLines.length,
|
||||
no_video: reRecordWbs.length + reRecordFailedWbs.length,
|
||||
re_record: reRecordWbs.length,
|
||||
re_record_failed: reRecordFailedWbs.length,
|
||||
no_video: noVideoWbs.length,
|
||||
no_record: noRecordWbs.length,
|
||||
message: lines.join('\n'),
|
||||
direct_reply: true,
|
||||
|
||||
@ -1,7 +1,6 @@
|
||||
'use strict';
|
||||
|
||||
const Service = require('egg').Service;
|
||||
const { normalizeExtDataSource } = require('../../lib/inbox_channel');
|
||||
|
||||
const WAREHOUSE_INTERFACE_TYPE_ID = 3;
|
||||
|
||||
@ -47,15 +46,13 @@ class InboxProcessorService extends Service {
|
||||
};
|
||||
|
||||
// 群存在但 ext_data 为空,且入站消息带有 ext_data → 写回群配置
|
||||
// 写回前按群ID格式校正渠道来源,避免把错误渠道固化进群配置
|
||||
if (group && !info.ext_data && msgExtData && typeof msgExtData === 'object' && Object.keys(msgExtData).length > 0) {
|
||||
try {
|
||||
const normalizedExt = normalizeExtDataSource(groupId, msgExtData);
|
||||
await ctx.model.InboxGroup.update(
|
||||
{ ext_data: normalizedExt },
|
||||
{ ext_data: msgExtData },
|
||||
{ where: { group_id: groupId, warehouse_id: warehouseId } }
|
||||
);
|
||||
info.ext_data = normalizedExt;
|
||||
info.ext_data = msgExtData;
|
||||
ctx.logger.info(`[inbox processor] 群 ext_data 写回成功: ${groupId}`);
|
||||
} catch (e) {
|
||||
ctx.logger.warn(`[inbox processor] 群 ext_data 写回失败: ${e.message}`);
|
||||
@ -492,18 +489,6 @@ class InboxProcessorService extends Service {
|
||||
throw new Error(`回执缺少必填字段: user_id=${userId || '?'}, user_name=${userName || '?'}`);
|
||||
}
|
||||
|
||||
// 按群ID格式校正渠道来源(@chatroom→wx / 纯数字→qiwe):
|
||||
// 群配置 ext_data 渠道错配时,回执会被桥接投递到错误渠道而丢失
|
||||
const rawExtData = data.ext_data || null;
|
||||
const outboundExtData = normalizeExtDataSource(groupId, rawExtData);
|
||||
if (rawExtData && outboundExtData && rawExtData.source
|
||||
&& rawExtData.source !== outboundExtData.source) {
|
||||
ctx.logger.warn(
|
||||
`[inbox processor] 回执 ext_data 渠道已校正 group_id=${groupId} ` +
|
||||
`${rawExtData.source} → ${outboundExtData.source}`
|
||||
);
|
||||
}
|
||||
|
||||
const ackExtId = `sys:ack:${extId}`;
|
||||
const callbackConfig = await this.getApiAppCallbackConfig(warehouseId);
|
||||
try {
|
||||
@ -525,7 +510,7 @@ class InboxProcessorService extends Service {
|
||||
group_name: groupName,
|
||||
user_name: isSystem ? null : userName,
|
||||
content: replyContent,
|
||||
ext_data: outboundExtData, flags: {},
|
||||
ext_data: data.ext_data || null, flags: {},
|
||||
});
|
||||
outboundId = created.id;
|
||||
}
|
||||
@ -539,7 +524,7 @@ class InboxProcessorService extends Service {
|
||||
data: {
|
||||
type: isSystem ? 'system' : source === 'ai_reply' ? 'ai' : source === 'bind_confirm' ? 'bind' : source === 'balance' ? 'balance' : 'error',
|
||||
content: replyContent,
|
||||
ext_data: outboundExtData,
|
||||
ext_data: data.ext_data || null,
|
||||
ext_id: String(outboundId),
|
||||
group_id: groupId,
|
||||
...(isSystem ? {} : { user_id: userId, user_name: userName }),
|
||||
|
||||
@ -248,9 +248,7 @@ function extractWaybills(text) {
|
||||
if (/^\d{3,4}-\d{7,8}$/.test(t)) return false; // 座机带横线(020-12345678)
|
||||
if (/^0\d{9,11}$/.test(t)) return false; // 0开头座机/服务号(02012345678)
|
||||
if (/^400\d{7}$/.test(t)) return false; // 400 服务电话
|
||||
// 日期时间戳(如 20260914201201):年份限定 19xx/20xx,
|
||||
// 否则 14 位运单号(如中通 79140215263762 → 被误读成 7914-02-15)会被当日期戳剔除
|
||||
if (/^(19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{4,}$/.test(t)) return false;
|
||||
if (/^\d{4}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{4,}$/.test(t)) return false; // 日期时间戳
|
||||
if (/^[A-Za-z_-]+$/.test(t)) return false; // 纯字母
|
||||
return true;
|
||||
});
|
||||
@ -338,25 +336,13 @@ const SILENT_RE = /^(好|好的|好的呢|好嘞|嗯|嗯嗯|哦|哦哦|ok|okay|
|
||||
|
||||
// ============================ 规则表(顺序即优先级) ============================
|
||||
|
||||
/**
|
||||
* 运单号标签:"物流单号 / 物流单 号 / 物 流单号 / 快递单号 / 运单号" 等
|
||||
* 只是单号前缀说明,不代表"要查物流"。判定查询意图前先剔除标签词,
|
||||
* 避免机器人格式"物流单号:SF123 拦截"因含"物流"被误判为物流查询而整条静默(不回信)。
|
||||
* 兼容 IM 转写时在标签字符间断插空格的情况(实测生产存在"物 流单号")。
|
||||
* 仅剔除标签本身,聊天正文里的"物流显示签收"等仍保留,查询类消息继续被守卫拦住。
|
||||
*/
|
||||
const WAYBILL_LABEL_RE = /(物\s*流|快\s*递|运\s*单|包\s*裹|邮\s*件)\s*单\s*号?/g;
|
||||
|
||||
/** 物流查询意图关键词:命中即认为不是拦截请求 */
|
||||
const TRACKING_QUERY_RE = /(到哪|在哪|哪里|快递到|物流|轨迹|查单|查快递|查物流|到哪里|取消拦截|撤销拦截|解除拦截|不拦截|不用拦截)/;
|
||||
|
||||
/**
|
||||
* 拦截类规则的防误判守卫:询问物流进度/查快递等不是拦截请求,
|
||||
* 取消/撤销类语义属于 cancelIntercept(双保险,长词优先已能保证)
|
||||
* @param {string} t 消息正文
|
||||
* @return {boolean} 是否允许命中拦截规则
|
||||
*/
|
||||
const INTERCEPT_GUARD = t => !TRACKING_QUERY_RE.test(String(t || '').replace(WAYBILL_LABEL_RE, ' '));
|
||||
const INTERCEPT_GUARD = t => !/(到哪|在哪|哪里|快递到|物流|轨迹|查单|查快递|查物流|到哪里|取消拦截|撤销拦截|解除拦截|不拦截|不用拦截)/.test(t);
|
||||
|
||||
/** 货主群(store) */
|
||||
const STORE_RULES = [
|
||||
|
||||
@ -18,13 +18,12 @@ class OpenapiCallbackService extends Service {
|
||||
|
||||
/**
|
||||
* 计算回调签名(与 OpenAPI 入口签名算法完全一致)。
|
||||
* 算法:md5(canonicalQuery + selfAppSecret + md5(stableStringify(body)))。
|
||||
* @param {Object} options 签名参数。
|
||||
* @param {string} options.event 回调 method(模块.动作,如 deliveryorder.confirm),仅用于 query 的 method。
|
||||
* @param {string} options.event 事件名,如 order_completed。
|
||||
* @param {string} options.appKey 应用 app_key。
|
||||
* @param {string} options.selfAppSecret 应用密钥。
|
||||
* @param {Object} options.body 完整回调报文体(奇门同层级 { request: {...} })。
|
||||
* @param {string} options.timestamp 秒级时间戳(10 位字符串,与 /openapi 入站时效校验一致)。
|
||||
* @param {Object} options.body 回调请求体数据。
|
||||
* @param {string} options.timestamp 毫秒时间戳。
|
||||
* @return {{ canonicalQuery: string, bodySign: string, sign: string }} 签名计算结果。
|
||||
*/
|
||||
signCallback({ event, appKey, selfAppSecret, body, timestamp }) {
|
||||
@ -40,23 +39,21 @@ class OpenapiCallbackService extends Service {
|
||||
|
||||
/**
|
||||
* 发送回调请求(带自动重试)。
|
||||
* 报文体固定为奇门同层级结构 { request: {...} },event 仅拼入 query 的 method;
|
||||
* 非 2xx 响应或网络错误触发重试,最多重试 MAX_RETRY 次,
|
||||
* 每次重试间隔递增(2s → 5s → 15s),请求超时 30 秒。
|
||||
* 每次重试间隔递增(2s → 5s → 15s)。
|
||||
* @param {Object} options 回调选项。
|
||||
* @param {string} options.callbackUrl 回调目标 URL。
|
||||
* @param {string} options.appKey 应用 app_key。
|
||||
* @param {string} options.selfAppSecret 应用密钥。
|
||||
* @param {string} options.event 回调 method(模块.动作,如 deliveryorder.confirm),仅用于 query 的 method。
|
||||
* @param {Object} options.request 奇门同层级业务报文内容(不含外层 request 包装,由发送端包装)。
|
||||
* @param {string} options.event 事件名,如 order_completed。
|
||||
* @param {Object} options.data 回调数据。
|
||||
* @param {Object} [options.metadata] 额外元数据。
|
||||
* @return {Promise<Object>} 回调结果 { success, retryCount, response, error }。
|
||||
*/
|
||||
async sendWithRetry({ callbackUrl, appKey, selfAppSecret, event, request }) {
|
||||
async sendWithRetry({ callbackUrl, appKey, selfAppSecret, event, data, metadata }) {
|
||||
const { ctx } = this;
|
||||
// 秒级时间戳(10 位):与 /openapi 入站时效校验(±600 秒窗口)及回调调试页保持一致
|
||||
const timestamp = String(Math.floor(Date.now() / 1000));
|
||||
// 报文体固定为奇门同层级 { request }:event 只出现在 query 的 method 中
|
||||
const body = { request: request || {} };
|
||||
const timestamp = String(Date.now());
|
||||
const body = { event, data, metadata: metadata || {} };
|
||||
const { sign } = this.signCallback({ event, appKey, selfAppSecret, body, timestamp });
|
||||
|
||||
const queryString = [
|
||||
@ -88,8 +85,6 @@ class OpenapiCallbackService extends Service {
|
||||
lastResponse = result;
|
||||
|
||||
if (result.status >= 200 && result.status < 300) {
|
||||
console.log(`[OpenapiCallback] event=${event} appKey=${appKey} retry=${attempt} url=${url} status=${result.status} success=true response=${this._formatResponsePayload(result.data)}`);
|
||||
|
||||
await this.logCallback({
|
||||
appKey,
|
||||
event,
|
||||
@ -109,8 +104,6 @@ class OpenapiCallbackService extends Service {
|
||||
|
||||
lastError = new Error(`回调返回非 2xx 状态码: ${result.status}`);
|
||||
|
||||
console.log(`[OpenapiCallback] event=${event} appKey=${appKey} retry=${attempt} url=${url} status=${result.status} success=false response=${this._formatResponsePayload(result.data)}`);
|
||||
|
||||
await this.logCallback({
|
||||
appKey,
|
||||
event,
|
||||
@ -122,9 +115,6 @@ class OpenapiCallbackService extends Service {
|
||||
});
|
||||
} catch (error) {
|
||||
lastError = error;
|
||||
const availableResponse = lastResponse ? lastResponse.data : null;
|
||||
|
||||
console.log(`[OpenapiCallback] event=${event} appKey=${appKey} retry=${attempt} url=${url} success=false error=${error.message} response=${this._formatResponsePayload(availableResponse)}`);
|
||||
|
||||
await this.logCallback({
|
||||
appKey,
|
||||
@ -132,7 +122,7 @@ class OpenapiCallbackService extends Service {
|
||||
callbackUrl,
|
||||
success: false,
|
||||
retryCount: attempt,
|
||||
response: availableResponse,
|
||||
response: null,
|
||||
error: error.message,
|
||||
});
|
||||
}
|
||||
@ -153,14 +143,14 @@ class OpenapiCallbackService extends Service {
|
||||
|
||||
/**
|
||||
* 根据 app_key 查询 api_app 获取 callback_url 与密钥,发送回调通知。
|
||||
* 报文体由 sendWithRetry 统一包装为奇门同层级 { request: {...} }。
|
||||
* @param {Object} options 回调选项。
|
||||
* @param {string} options.appKey 应用 app_key。
|
||||
* @param {string} options.event 回调 method(模块.动作,如 deliveryorder.confirm),仅用于 query 的 method。
|
||||
* @param {Object} options.request 奇门同层级业务报文内容(不含外层 request 包装,由发送端包装)。
|
||||
* @param {string} options.event 事件名,如 order_completed。
|
||||
* @param {Object} options.data 回调数据。
|
||||
* @param {Object} [options.metadata] 额外元数据。
|
||||
* @return {Promise<Object>} 回调结果 { success, retryCount, response, error }。
|
||||
*/
|
||||
async sendByAppKey({ appKey, event, request }) {
|
||||
async sendByAppKey({ appKey, event, data, metadata }) {
|
||||
const { ctx } = this;
|
||||
const normalizedAppKey = String(appKey || '').trim();
|
||||
|
||||
@ -200,65 +190,26 @@ class OpenapiCallbackService extends Service {
|
||||
appKey: normalizedAppKey,
|
||||
selfAppSecret: appConfig.self_app_secret || '',
|
||||
event,
|
||||
request,
|
||||
data,
|
||||
metadata,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 将回调响应报文格式化为日志可输出的字符串。
|
||||
* 兼容对象、字符串、Buffer / ArrayBuffer / TypedArray 与 null / undefined,
|
||||
* 超出最大长度时做截断处理,避免日志刷屏。
|
||||
* @param {*} response 回调响应报文,类型不限。
|
||||
* @return {string} 格式化后的报文字符串。
|
||||
*/
|
||||
_formatResponsePayload(response) {
|
||||
const MAX_PAYLOAD_LENGTH = 500;
|
||||
let payload;
|
||||
|
||||
if (response === null || response === undefined) {
|
||||
payload = 'null';
|
||||
} else if (typeof response === 'string') {
|
||||
payload = response;
|
||||
} else if (Buffer.isBuffer(response)) {
|
||||
payload = response.toString('utf8');
|
||||
} else if (response instanceof ArrayBuffer) {
|
||||
payload = Buffer.from(response).toString('utf8');
|
||||
} else if (ArrayBuffer.isView(response)) {
|
||||
// TypedArray 与 DataView:仅取视图对应的内存区间
|
||||
payload = Buffer.from(response.buffer, response.byteOffset, response.byteLength).toString('utf8');
|
||||
} else {
|
||||
try {
|
||||
payload = JSON.stringify(response);
|
||||
} catch (error) {
|
||||
// 循环引用等序列化异常时降级处理
|
||||
payload = String(response);
|
||||
}
|
||||
}
|
||||
|
||||
if (payload.length > MAX_PAYLOAD_LENGTH) {
|
||||
return `${payload.slice(0, MAX_PAYLOAD_LENGTH)}...(truncated)`;
|
||||
}
|
||||
|
||||
return payload;
|
||||
}
|
||||
|
||||
/**
|
||||
* 记录回调日志。
|
||||
* 格式:[OpenapiCallback] event=xxx appKey=xxx url=xxx retry=N success=xxx response=xxx
|
||||
* 格式:[OpenapiCallback] event=xxx appKey=xxx url=xxx retry=N success=xxx
|
||||
* @param {Object} options 日志选项。
|
||||
* @param {string} options.appKey 应用 app_key。
|
||||
* @param {string} options.event 事件名。
|
||||
* @param {string} options.callbackUrl 回调目标 URL。
|
||||
* @param {boolean} options.success 是否成功。
|
||||
* @param {number} options.retryCount 重试次数。
|
||||
* @param {*} [options.response] 回调响应报文。
|
||||
* @param {string} [options.error] 错误信息。
|
||||
* @return {void} 无返回值。
|
||||
*/
|
||||
async logCallback({ appKey, event, callbackUrl, success, retryCount, response, error }) {
|
||||
async logCallback({ appKey, event, callbackUrl, success, retryCount, error }) {
|
||||
const { ctx } = this;
|
||||
const payload = this._formatResponsePayload(response);
|
||||
const logMessage = `[OpenapiCallback] event=${event} appKey=${appKey} url=${callbackUrl} retry=${retryCount} success=${success} response=${payload}`;
|
||||
const logMessage = `[OpenapiCallback] event=${event} appKey=${appKey} url=${callbackUrl} retry=${retryCount} success=${success}`;
|
||||
|
||||
if (success) {
|
||||
ctx.logger.info(logMessage);
|
||||
|
||||
@ -3,192 +3,27 @@
|
||||
/**
|
||||
* OpenAPI 回调事件注册表。
|
||||
* 每个事件包含 name(事件名)、label(展示名)、description(说明)、
|
||||
* request(奇门同层级报文模板,即 request 节点的内容,不含外层 request 包装;
|
||||
* 真实回调报文结构统一为 { request: {...} },字段名与嵌套层级和真实调用点完全一致)。
|
||||
* 回调调试页 GET /docs/api/openapi/callback-test 直接消费本注册表。
|
||||
* sampleData(示例数据,与真实回调数据格式一致)。
|
||||
*/
|
||||
const CALLBACK_EVENTS = [
|
||||
{
|
||||
name: 'entryorder.confirm',
|
||||
label: '入库单确认完成(直入)',
|
||||
description: '直入入库(API 来源)完成后回传,对应奇门 taobao.qimen.entryorder.confirm',
|
||||
request: {
|
||||
entryOrder: {
|
||||
entryOrderCode: 'RK20260912001',
|
||||
ownerCode: 'OWNER-001',
|
||||
warehouseCode: 'WH-100',
|
||||
entryOrderId: 543,
|
||||
entryOrderType: 'SCRK',
|
||||
outBizCode: 'DIRECT_INBOUND_1726131400000',
|
||||
confirmType: 0,
|
||||
status: 'FULFILLED',
|
||||
freight: 0,
|
||||
operateTime: '2026-09-12 10:30:00',
|
||||
remark: '导入/PDA直接入库提交',
|
||||
},
|
||||
orderLines: [
|
||||
{
|
||||
orderLineNo: 1,
|
||||
ownerCode: 'OWNER-001',
|
||||
itemCode: 'SKU-1',
|
||||
itemId: '1001',
|
||||
inventoryType: 'ZP',
|
||||
planQty: 2,
|
||||
actualQty: 2,
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'entryorder.match',
|
||||
label: '入库单匹配收货完成',
|
||||
description: '入库单匹配收货单完成后回传(API 来源),对应奇门 taobao.qimen.entryorder.confirm',
|
||||
request: {
|
||||
entryOrder: {
|
||||
entryOrderCode: 'RK20260912002',
|
||||
ownerCode: 'OWNER-001',
|
||||
warehouseCode: 'WH-100',
|
||||
entryOrderId: 543,
|
||||
entryOrderType: 'SCRK',
|
||||
outBizCode: 'RECEIVING_MATCH_1726131400000',
|
||||
confirmType: 0,
|
||||
status: 'FULFILLED',
|
||||
freight: 0,
|
||||
operateTime: '2026-09-12 10:30:00',
|
||||
remark: '匹配收货单RCV20260912001自动回传',
|
||||
},
|
||||
orderLines: [
|
||||
{
|
||||
orderLineNo: 1,
|
||||
ownerCode: 'OWNER-001',
|
||||
itemCode: 'SKU-1',
|
||||
itemId: '1001',
|
||||
inventoryType: 'ZP',
|
||||
planQty: 2,
|
||||
actualQty: 2,
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'deliveryorder.confirm',
|
||||
name: 'order_completed',
|
||||
label: '订单发货完成',
|
||||
description: '订单同步(出库)完成后触发,对应奇门 taobao.qimen.deliveryorder.confirm',
|
||||
request: {
|
||||
deliveryOrder: {
|
||||
totalOrderLines: 1,
|
||||
deliveryOrderCode: 'DO20260912001',
|
||||
deliveryOrderId: 123,
|
||||
warehouseCode: 'WH-100',
|
||||
orderType: 'JYCK',
|
||||
status: 'DELIVERED',
|
||||
outBizCode: 'DO20260912001',
|
||||
confirmType: 0,
|
||||
orderConfirmTime: '2026-09-12 10:30:00',
|
||||
operatorCode: '',
|
||||
operatorName: '',
|
||||
storageFee: '0',
|
||||
operateTime: '2026-09-12 10:30:00',
|
||||
},
|
||||
packages: {
|
||||
package: [
|
||||
{
|
||||
logisticsCode: 'YTO',
|
||||
logisticsName: '圆通速递',
|
||||
expressCode: 'YT1234567890',
|
||||
packageCode: 'DO20260912001',
|
||||
invoiceNo: 'INV20260912001',
|
||||
items: [
|
||||
{
|
||||
itemCode: 'SKU-1',
|
||||
itemId: 1001,
|
||||
quantity: 2,
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
orderLines: [
|
||||
{
|
||||
orderLineNo: '1',
|
||||
orderSourceCode: 'SO20260912001',
|
||||
subSourceCode: '',
|
||||
ownerCode: 'OWNER-001',
|
||||
itemCode: 'SKU-1',
|
||||
itemId: 1001,
|
||||
itemName: '测试商品1',
|
||||
extCode: '',
|
||||
planQty: 2,
|
||||
actualQty: 2,
|
||||
retailPrice: 0,
|
||||
actualPrice: 0,
|
||||
discountAmount: '0',
|
||||
inventoryType: 'ZP',
|
||||
snList: [],
|
||||
qrCode: '',
|
||||
},
|
||||
],
|
||||
description: '订单同步(出库)完成后触发',
|
||||
sampleData: {
|
||||
orderIds: [ 1001, 1002 ],
|
||||
status: 'completed',
|
||||
successCount: 2,
|
||||
failedCount: 0,
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'stockout.confirm',
|
||||
label: '出库单确认完成',
|
||||
description: '出库单确认回传(API 来源),对应奇门 taobao.qimen.stockout.confirm',
|
||||
request: {
|
||||
deliveryOrder: {
|
||||
totalOrderLines: 1,
|
||||
deliveryOrderCode: 'SO20260912001',
|
||||
deliveryOrderId: 5001,
|
||||
warehouseCode: 'WH-100',
|
||||
orderType: 'PTCK',
|
||||
status: 'DELIVERED',
|
||||
outBizCode: 'SO20260912001',
|
||||
confirmType: 0,
|
||||
orderConfirmTime: '2026-09-12 10:30:00',
|
||||
operatorCode: '',
|
||||
operatorName: '',
|
||||
},
|
||||
packages: {
|
||||
package: [
|
||||
{
|
||||
logisticsCode: 'YTO',
|
||||
logisticsName: '圆通速递',
|
||||
expressCode: 'YT1234567890',
|
||||
packageCode: 'SO20260912001',
|
||||
items: [
|
||||
{
|
||||
itemCode: 'SKU-1',
|
||||
itemId: 1001,
|
||||
quantity: 2,
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
orderLines: [
|
||||
{
|
||||
orderLineNo: '1',
|
||||
ownerCode: 'OWNER-001',
|
||||
itemCode: 'SKU-1',
|
||||
itemId: 1001,
|
||||
itemName: '测试商品1',
|
||||
planQty: 2,
|
||||
actualQty: 2,
|
||||
inventoryType: 'ZP',
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'deliveryorder.cancel',
|
||||
name: 'order_cancelled',
|
||||
label: '订单已取消',
|
||||
description: '订单取消成功后触发(出站回调事件名 deliveryorder.cancel,与入站方法 order.cancel 区分,避免回调误路由到取消单据接口;无奇门对应接口,按 deliveryOrder 节点约定自定义)',
|
||||
request: {
|
||||
deliveryOrder: {
|
||||
deliveryOrderCode: 'TEST-ORDER-001',
|
||||
orderType: 'JYCK',
|
||||
status: 'CANCELED',
|
||||
},
|
||||
description: '订单取消成功后触发',
|
||||
sampleData: {
|
||||
orderCode: 'TEST-ORDER-001',
|
||||
status: 'cancelled',
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
@ -44,20 +44,21 @@ class OpenapiCallbackMethodService extends MainService {
|
||||
* 模拟发送回调通知(测试用)。
|
||||
* 通过 app_key 查找回调配置并发送一次回调请求。
|
||||
* @param {Object} [payload={}] 调用参数。
|
||||
* @param {Object} [payload.body={}] 请求体数据,可指定 event 与 request(奇门同层级业务报文,不含外层 request 包装)。
|
||||
* @param {Object} [payload.body={}] 请求体数据,可指定 event 与 data。
|
||||
* @param {Object} [payload.query={}] 请求 query 数据,需包含 app_key。
|
||||
* @return {Promise<Object>} 回调测试结果。
|
||||
*/
|
||||
async test(payload = {}) {
|
||||
const { body = {}, query = {} } = payload;
|
||||
const { event = 'deliveryorder.confirm', request = {} } = body;
|
||||
const { event = 'order_completed', data = {} } = body;
|
||||
|
||||
try {
|
||||
const info = await this.resolveAppInfo(query.app_key);
|
||||
const result = await this.ctx.service.openapi.callback.sendByAppKey({
|
||||
appKey: info.appKey,
|
||||
event,
|
||||
request,
|
||||
data,
|
||||
metadata: { test: true },
|
||||
});
|
||||
|
||||
if (result.success) {
|
||||
|
||||
@ -66,12 +66,7 @@ class OpenapiDeliveryorderService extends MainService {
|
||||
*/
|
||||
async create(payload = {}) {
|
||||
const { body = {} } = payload;
|
||||
const {
|
||||
deliveryOrder,
|
||||
orderLines,
|
||||
need_oms_waybill: needOmsWaybillSnake,
|
||||
needOmsWaybill,
|
||||
} = body;
|
||||
const { deliveryOrder, orderLines } = body;
|
||||
|
||||
if (!deliveryOrder || !deliveryOrder.deliveryOrderCode) {
|
||||
return this.fail('deliveryOrder 参数缺失或不完整');
|
||||
@ -81,13 +76,10 @@ class OpenapiDeliveryorderService extends MainService {
|
||||
}
|
||||
|
||||
try {
|
||||
// need_oms_waybill 在请求根节点传入(不在 deliveryOrder 内),
|
||||
// 兼容 snake_case / camelCase 两种写法,仅 openapi(API) 来源会落库生效。
|
||||
const data = {
|
||||
request: {
|
||||
deliveryOrder,
|
||||
orderLines,
|
||||
need_oms_waybill: needOmsWaybillSnake ?? needOmsWaybill,
|
||||
},
|
||||
};
|
||||
|
||||
|
||||
@ -30,10 +30,6 @@ class OpenapiEntryorderService extends MainService {
|
||||
}
|
||||
|
||||
// 字段映射:OpenAPI 风格字段名 → 底层 tryCreateEntryOrder 期望的字段名
|
||||
// 注意(2026-09-14):以下字段当前未被底层消费,保留仅为兼容调用方,勿据此判断生效:
|
||||
// - warehouseCode:仓库上下文一律以 app_key 合约解析结果为准,报文值被忽略
|
||||
// - operateTime / operatorName:底层既不落库也不参与任何逻辑
|
||||
// 另:ownerCode 不通过本映射生效,由下方显式作为 customerId 传入(落 qimen_owner_code)
|
||||
const mappedEntryOrder = {
|
||||
entryOrderCode: entryOrder.entryOrderCode,
|
||||
orderType: entryOrder.entryOrderType || entryOrder.orderType || 'SCRK',
|
||||
@ -62,16 +58,9 @@ class OpenapiEntryorderService extends MainService {
|
||||
},
|
||||
};
|
||||
|
||||
// 货主编码对齐奇门口径:奇门侧 qimen_owner_code 取自请求上下文 customerId
|
||||
// (出站回传 entryorder.confirm 的 ownerCode 即取该列,见 buildEntryOrderConfirmRequest)。
|
||||
// OpenAPI 合约上下文的 customerId 恒为 null,会导致 API 来源入库单 qimen_owner_code 为空、
|
||||
// 回传 ownerCode 为空,故此处用报文 entryOrder.ownerCode 补齐(与奇门落库口径一致)。
|
||||
const info = this.getInfo();
|
||||
const ownerCode = String(entryOrder.ownerCode || '').trim();
|
||||
|
||||
const res = await this.ctx.service.systems.entryOrder.addOrder(
|
||||
data,
|
||||
{ ...info, customerId: ownerCode || info.customerId || '' },
|
||||
this.getInfo(),
|
||||
'API'
|
||||
);
|
||||
|
||||
|
||||
@ -3,20 +3,12 @@
|
||||
const MainService = require('../main');
|
||||
|
||||
const { getInterceptRequestBlockReason, resolveInterceptRequestGuardInfo } = require('../../lib/intercept_guard');
|
||||
const { buildNoticeTimePatch } = require('../../lib/intercept_time');
|
||||
|
||||
class OpenapiOrderService extends MainService {
|
||||
/**
|
||||
* 取消发货单。
|
||||
* 上下文(storeId/warehouseId/appKey)已由 dispatchOpenapiMethod 统一注入。
|
||||
* 支持类型:
|
||||
* - 出库单类型(JYCK/HHCK/BFCK → ORDER):操作 wms_order_delivery 主表,
|
||||
* 触发拦截时同步写入订单拦截时间 intercept_time(当前时间);
|
||||
* - CK 组出库单(PTCK/DBCK/B2BCK/QTCK/CGTH):走独立出库单表 wms_order_stockout 取消,
|
||||
* 取消成功后不需要向开放平台回传任何事件;
|
||||
* - RK 组入库单(B2BRK/SCRK/LYRK/CCRK/CGRK/DBRK/QTRK):走入库单作废流程(状态守卫、
|
||||
* 回退收货单占用),取消成功后不需要向开放平台回传任何事件。
|
||||
* 其余类型返回不支持。
|
||||
* 当前仅支持出库单类型(JYCK/HHCK/BFCK → ORDER),非出库单类型返回不支持。
|
||||
* @param {Object} payload 调用参数。
|
||||
* @param {Object} payload.body 请求体数据,包含 orderCode、orderType。
|
||||
* @param {Object} payload.query 请求 query 数据。
|
||||
@ -28,13 +20,9 @@ class OpenapiOrderService extends MainService {
|
||||
const { orderCode } = body;
|
||||
const orderType = String(body.orderType || 'JYCK').trim().toUpperCase();
|
||||
|
||||
// 出库单类型映射:JYCK / HHCK / BFCK → ORDER(wms_order_delivery 取消流程)
|
||||
// 出库单类型映射:JYCK / HHCK / BFCK → ORDER
|
||||
const ORDER_TYPES = [ 'JYCK', 'HHCK', 'BFCK' ];
|
||||
// CK 组出库单:走独立出库单表 wms_order_stockout 取消流程
|
||||
const CK_TYPES = [ 'PTCK', 'DBCK', 'B2BCK', 'QTCK', 'CGTH' ];
|
||||
// RK 组入库单:走入库单作废流程(与奇门 orderType 枚举 method=RK 完全一致)
|
||||
const RK_TYPES = [ 'B2BRK', 'SCRK', 'LYRK', 'CCRK', 'CGRK', 'DBRK', 'QTRK' ];
|
||||
if (!ORDER_TYPES.includes(orderType) && !CK_TYPES.includes(orderType) && !RK_TYPES.includes(orderType)) {
|
||||
if (!ORDER_TYPES.includes(orderType)) {
|
||||
return this.fail('暂不支持该订单类型的取消操作');
|
||||
}
|
||||
|
||||
@ -43,45 +31,6 @@ class OpenapiOrderService extends MainService {
|
||||
return this.fail('orderCode 参数缺失');
|
||||
}
|
||||
|
||||
// CK 组:委托共享出库单取消实现,取消成功后不回传任何开放平台事件
|
||||
if (CK_TYPES.includes(orderType)) {
|
||||
const info = this.getInfo();
|
||||
return ctx.service.systems.stockoutOrder.cancel(
|
||||
{ stockoutOrderCode: normalizedOrderCode },
|
||||
{
|
||||
storeId: info.storeId,
|
||||
warehouseId: info.warehouseId,
|
||||
operatorLabel: String(info.appKey || '').trim()
|
||||
? `openapi:${String(info.appKey).trim()}`
|
||||
: 'openapi',
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
// RK 组:委托共享入库单作废实现(守卫 + 回退收货单占用 + 操作日志),
|
||||
// 取消成功后不回传任何开放平台事件;已作废按幂等成功处理
|
||||
if (RK_TYPES.includes(orderType)) {
|
||||
const info = this.getInfo();
|
||||
const result = await ctx.service.systems.storage.entry.cancel(
|
||||
{ entryOrderCode: normalizedOrderCode },
|
||||
{
|
||||
storeId: info.storeId,
|
||||
warehouseId: info.warehouseId,
|
||||
operatorLabel: String(info.appKey || '').trim()
|
||||
? `openapi:${String(info.appKey).trim()}`
|
||||
: 'openapi',
|
||||
skipExternalSync: true,
|
||||
idempotent: true,
|
||||
notFoundMessage: '未找到对应的入库单',
|
||||
}
|
||||
);
|
||||
|
||||
if (result.code === 200) {
|
||||
return this.success('取消入库单成功');
|
||||
}
|
||||
return this.fail(result.message || '取消入库单失败');
|
||||
}
|
||||
|
||||
try {
|
||||
const { storeId, warehouseId, appKey: ctxAppKey } = this.getInfo();
|
||||
|
||||
@ -121,12 +70,9 @@ class OpenapiOrderService extends MainService {
|
||||
});
|
||||
|
||||
if (!blockReason) {
|
||||
// 通知拦截时间只在首次发起时写入(重复发起不覆盖已有值)
|
||||
const noticeNow = new Date();
|
||||
await existingOrder.update({
|
||||
intercept_status: 'intercepting',
|
||||
...buildNoticeTimePatch(existingOrder.intercept_time, noticeNow),
|
||||
updated_at: noticeNow,
|
||||
updated_at: new Date(),
|
||||
}, {
|
||||
transaction,
|
||||
});
|
||||
@ -289,19 +235,12 @@ class OpenapiOrderService extends MainService {
|
||||
if (callbackService && typeof callbackService.sendByAppKey === 'function') {
|
||||
const appKey = String(query.app_key || ctxAppKey || '').trim();
|
||||
if (appKey) {
|
||||
// 出站回调事件名 deliveryorder.cancel:与入站方法 order.cancel 区分,
|
||||
// 避免 callback_url 误指向 /openapi 时被路由到取消单据接口
|
||||
// 报文对齐奇门 request 层级:deliveryOrder 节点约定(无奇门对应接口,
|
||||
// status 使用 CANCELED 与奇门 deliveryOrder.status 家族枚举风格一致)
|
||||
callbackService.sendByAppKey({
|
||||
appKey,
|
||||
event: 'deliveryorder.cancel',
|
||||
request: {
|
||||
deliveryOrder: {
|
||||
deliveryOrderCode: normalizedOrderCode,
|
||||
orderType,
|
||||
status: 'CANCELED',
|
||||
},
|
||||
event: 'order_cancelled',
|
||||
data: {
|
||||
orderCode,
|
||||
status: 'cancelled',
|
||||
},
|
||||
}).catch(err => {
|
||||
this.ctx.logger.warn('[OpenapiOrderCancel] 回调忽略失败: %s', err.message);
|
||||
|
||||
@ -1,89 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
const MainService = require('../main');
|
||||
|
||||
/**
|
||||
* 开放 API 出库单适配层。
|
||||
*
|
||||
* 处理 openapi stockout.create / stockout.query,业务逻辑统一委托到
|
||||
* `app/service/systems/stockout_order.js`(ctx.service.systems.stockoutOrder),
|
||||
* 与 qimenMethods/stockout.js 共用同一份实现。
|
||||
*
|
||||
* 与奇门的差异:
|
||||
* - 入参为开放 API 扁平结构(body.deliveryOrder / body.orderLines / body.deliveryOrderCode),
|
||||
* 不像奇门那样包一层 request 节点;
|
||||
* - 落库 source_type=API,出库单回传走 OpenAPI 回调(event=stockout.confirm);
|
||||
* - 上下文(storeId/warehouseId/warehouseCode)由 openapiEntry 合约解析后注入。
|
||||
*/
|
||||
class OpenapiStockoutService extends MainService {
|
||||
|
||||
/**
|
||||
* 创建出库单。
|
||||
*
|
||||
* @param {Object} payload 调用参数。
|
||||
* @param {Object} payload.body 请求体数据,需包含 deliveryOrder 与 orderLines。
|
||||
* @param {Object} payload.query 请求 query 数据。
|
||||
* @return {Promise<Object>} 创建结果,成功时返回 stockoutOrderId/stockoutOrderCode,失败返回错误信息。
|
||||
*/
|
||||
async create(payload = {}) {
|
||||
const { body = {} } = payload;
|
||||
const { deliveryOrder, orderLines } = body;
|
||||
|
||||
if (!deliveryOrder || !deliveryOrder.deliveryOrderCode) {
|
||||
return this.fail('deliveryOrder 参数缺失或不完整');
|
||||
}
|
||||
if (!orderLines) {
|
||||
return this.fail('orderLines 参数缺失');
|
||||
}
|
||||
|
||||
const info = this.getInfo();
|
||||
|
||||
return this.ctx.service.systems.stockoutOrder.create(
|
||||
{
|
||||
request: {
|
||||
deliveryOrder,
|
||||
orderLines,
|
||||
},
|
||||
},
|
||||
{
|
||||
storeId: info.storeId,
|
||||
warehouseId: info.warehouseId,
|
||||
warehouseCode: info.warehouseCode,
|
||||
appKey: info.appKey,
|
||||
sourceType: 'API',
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询出库单。
|
||||
*
|
||||
* @param {Object} payload 调用参数。
|
||||
* @param {Object} payload.body 请求体数据,需包含 deliveryOrderCode(兼容 deliveryOrder.deliveryOrderCode)。
|
||||
* @param {Object} payload.query 请求 query 数据。
|
||||
* @return {Promise<Object>} 查询结果,成功返回出库单详情,失败返回错误信息。
|
||||
*/
|
||||
async query(payload = {}) {
|
||||
const { body = {} } = payload;
|
||||
const deliveryOrderCode = String(
|
||||
body.deliveryOrderCode
|
||||
|| (body.deliveryOrder && body.deliveryOrder.deliveryOrderCode)
|
||||
|| ''
|
||||
).trim();
|
||||
|
||||
if (!deliveryOrderCode) {
|
||||
return this.fail('deliveryOrderCode 参数缺失');
|
||||
}
|
||||
|
||||
return this.ctx.service.systems.stockoutOrder.query({
|
||||
request: {
|
||||
deliveryOrder: {
|
||||
deliveryOrderCode,
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
module.exports = OpenapiStockoutService;
|
||||
@ -230,12 +230,10 @@ class QimenService extends Service {
|
||||
});
|
||||
}
|
||||
/**
|
||||
* 保存出站奇门请求日志(直接落库)。
|
||||
* 仅用于出站请求(qimenClient.sendRequest)的日志落库;
|
||||
* 入站请求日志统一走文件队列异步消费落库,避免同一 log_id 双写入冲突。
|
||||
* @param {Object} logData 日志数据,需包含 log_id 等字段。
|
||||
* 保存奇门请求日志。
|
||||
* @param {Object} logData 日志数据。
|
||||
* @param {number} startTime 请求开始时间戳。
|
||||
* @return {Promise<number|undefined>} 新增日志主键 ID,失败时返回 undefined。
|
||||
* @return {Promise<number|undefined>} 新增日志ID。
|
||||
*/
|
||||
async saveQimenLog(logData, startTime) {
|
||||
const {
|
||||
@ -254,10 +252,9 @@ class QimenService extends Service {
|
||||
|
||||
logData.use_time = Date.now() - startTime;
|
||||
|
||||
// 不再回退使用 ctx.qimenLogId:入站 log_id 已由文件队列消费落库,
|
||||
// 出站复用会触发唯一索引冲突,出站日志必须使用自身生成的 log_id。
|
||||
// 使用 egg-mysql 保存日志到数据库
|
||||
const result = await ctx.app.mysql.get('wms').insert('wms_qimen_log', {
|
||||
log_id: logData.log_id || null,
|
||||
log_id: logData.log_id || ctx.qimenLogId || null,
|
||||
from_key: logData.from_key || '',
|
||||
to_key: logData.to_key || '',
|
||||
method: logData.method || '',
|
||||
@ -277,27 +274,11 @@ class QimenService extends Service {
|
||||
ctx.logger.info('奇门接口日志数据: ', JSON.stringify(logData));
|
||||
}
|
||||
}
|
||||
/**
|
||||
* 按 log_id 更新奇门请求日志的响应内容。
|
||||
* @param {string} result 响应内容。
|
||||
* @return {Promise<Object>} 数据库更新结果。
|
||||
*/
|
||||
async saveQimenLogResult(result) {
|
||||
const { ctx } = this;
|
||||
await ctx.app.mysql.get('wms').update('wms_qimen_log', { result }, {
|
||||
where: { log_id: ctx.qimenLogId },
|
||||
});
|
||||
await this.ctx.app.mysql.get('wms').update('wms_qimen_log', { result, id: this.ctx.qimenLogId });
|
||||
}
|
||||
/**
|
||||
* 按 log_id 更新奇门请求日志的请求体内容。
|
||||
* @param {string} body 请求体内容。
|
||||
* @return {Promise<Object>} 数据库更新结果。
|
||||
*/
|
||||
async saveQimenLogBody(body) {
|
||||
const { ctx } = this;
|
||||
await ctx.app.mysql.get('wms').update('wms_qimen_log', { body }, {
|
||||
where: { log_id: ctx.qimenLogId },
|
||||
});
|
||||
await this.ctx.app.mysql.get('wms').update('wms_qimen_log', { body, id: this.ctx.qimenLogId });
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@ -3,7 +3,6 @@
|
||||
const MainService = require('../main');
|
||||
|
||||
const { getInterceptRequestBlockReason, resolveInterceptRequestGuardInfo } = require('../../lib/intercept_guard');
|
||||
const { buildNoticeTimePatch } = require('../../lib/intercept_time');
|
||||
|
||||
class orderServer extends MainService {
|
||||
|
||||
@ -90,31 +89,14 @@ class orderServer extends MainService {
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询订单关联的拦截运单信息。
|
||||
*
|
||||
* 强制同仓校验:读取 wms_order_express 必须同时带订单ID与仓库ID,
|
||||
* 禁止仅凭订单ID跨仓串读运单号;仓库ID缺失时拒绝读取。
|
||||
*
|
||||
* @param {number|string} orderId 订单ID。
|
||||
* @param {number|string|null|undefined} warehouseId 仓库ID,必须为订单所属仓库。
|
||||
* @return {Promise<Array<Object>>} 运单信息列表。
|
||||
*/
|
||||
async getInterceptExpressInfo(orderId, warehouseId) {
|
||||
async getInterceptExpressInfo(orderId) {
|
||||
const { ctx } = this;
|
||||
const normalizedOrderId = Number(orderId || 0);
|
||||
const normalizedWarehouseId = warehouseId !== null && warehouseId !== undefined && warehouseId !== ''
|
||||
? Number(warehouseId)
|
||||
: 0;
|
||||
|
||||
if (!Number.isFinite(normalizedOrderId) || normalizedOrderId <= 0) {
|
||||
return [];
|
||||
}
|
||||
|
||||
if (!Number.isFinite(normalizedWarehouseId) || normalizedWarehouseId <= 0) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const orderExpressModel = ctx.model && ctx.model.OrderExpress;
|
||||
if (!orderExpressModel || typeof orderExpressModel.findAll !== 'function') {
|
||||
return [];
|
||||
@ -123,7 +105,6 @@ class orderServer extends MainService {
|
||||
const rows = await orderExpressModel.findAll({
|
||||
where: {
|
||||
order_id: normalizedOrderId,
|
||||
warehouse_id: normalizedWarehouseId,
|
||||
},
|
||||
attributes: [ 'waybill_code', 'logistics_code', 'logistics_name', 'logistics_interface_id' ],
|
||||
order: [[ 'id', 'DESC' ]],
|
||||
@ -141,7 +122,7 @@ class orderServer extends MainService {
|
||||
async sendCancelInterceptNotice({ orderCode, existingOrder, info }) {
|
||||
const { ctx } = this;
|
||||
try {
|
||||
const express = await this.getInterceptExpressInfo(existingOrder && existingOrder.id, info.warehouseId);
|
||||
const express = await this.getInterceptExpressInfo(existingOrder && existingOrder.id);
|
||||
|
||||
await ctx.service.systems.notice.send({
|
||||
event: 'order_cancel_intercepted',
|
||||
@ -174,20 +155,6 @@ class orderServer extends MainService {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 取消奇门订单。
|
||||
* 按 orderType 分发:
|
||||
* - ORDER(JYCK/HHCK/BFCK):订单未同步且未开始拣货/打印时直接取消;已同步或已开始
|
||||
* 拣货/打印时转入拦截处理:写入订单拦截状态 intercept_status(intercepting/requested)
|
||||
* 并同步写入拦截时间 intercept_time。
|
||||
* - RK(B2BRK/SCRK/LYRK/CCRK/CGRK/DBRK/QTRK):走入库单作废流程(状态守卫、
|
||||
* 回退收货单占用、写操作日志),取消成功后不需要向奇门回传任何事件。
|
||||
* - CK(PTCK/DBCK/B2BCK/QTCK/CGTH):走独立出库单表 wms_order_stockout 取消,
|
||||
* 取消成功后不需要向奇门回传任何事件。
|
||||
* @param {Object} data 奇门请求数据。
|
||||
* @param {Object} data.request 请求体,包含 orderCode、orderType 等字段。
|
||||
* @return {Promise<Object>} 取消结果,成功时返回成功消息,失败时返回错误信息。
|
||||
*/
|
||||
async cancel(data) {
|
||||
const { ctx } = this;
|
||||
const info = this.getInfo();
|
||||
@ -261,12 +228,9 @@ class orderServer extends MainService {
|
||||
});
|
||||
|
||||
if (!blockReason) {
|
||||
// 通知拦截时间只在首次发起时写入(重复发起不覆盖已有值)
|
||||
const noticeNow = new Date();
|
||||
await existingOrder.update({
|
||||
intercept_status: 'intercepting',
|
||||
...buildNoticeTimePatch(existingOrder.intercept_time, noticeNow),
|
||||
updated_at: noticeNow,
|
||||
updated_at: new Date(),
|
||||
}, {
|
||||
transaction,
|
||||
});
|
||||
@ -314,7 +278,7 @@ class orderServer extends MainService {
|
||||
|
||||
// 创建售后工单 + 通知快递群(仅限有运单的订单,与正常货主发起拦截一致;失败不影响主流程)
|
||||
try {
|
||||
const interceptExpress = await this.getInterceptExpressInfo(existingOrder.id, info.warehouseId);
|
||||
const interceptExpress = await this.getInterceptExpressInfo(existingOrder.id);
|
||||
if (Array.isArray(interceptExpress) && interceptExpress.length > 0) {
|
||||
await ctx.service.systems.afterSale.createInterceptWorkOrdersAndNotify({
|
||||
orderIds: [ existingOrder.id ],
|
||||
@ -357,12 +321,9 @@ class orderServer extends MainService {
|
||||
});
|
||||
|
||||
if (!syncBlockReason) {
|
||||
// 通知拦截时间只在首次发起时写入(重复发起不覆盖已有值)
|
||||
const noticeNow = new Date();
|
||||
await existingOrder.update({
|
||||
intercept_status: 'requested',
|
||||
...buildNoticeTimePatch(existingOrder.intercept_time, noticeNow),
|
||||
updated_at: noticeNow,
|
||||
updated_at: new Date(),
|
||||
}, {
|
||||
transaction,
|
||||
});
|
||||
@ -410,7 +371,7 @@ class orderServer extends MainService {
|
||||
|
||||
// 创建售后工单 + 通知快递群(仅限有运单的订单,与正常货主发起拦截一致;失败不影响主流程)
|
||||
try {
|
||||
const interceptExpress = await this.getInterceptExpressInfo(existingOrder.id, info.warehouseId);
|
||||
const interceptExpress = await this.getInterceptExpressInfo(existingOrder.id);
|
||||
if (Array.isArray(interceptExpress) && interceptExpress.length > 0) {
|
||||
await ctx.service.systems.afterSale.createInterceptWorkOrdersAndNotify({
|
||||
orderIds: [ existingOrder.id ],
|
||||
@ -556,56 +517,24 @@ class orderServer extends MainService {
|
||||
}
|
||||
case 'RK':
|
||||
{
|
||||
// RK 组入库单(B2BRK/SCRK/LYRK/CCRK/CGRK/DBRK/QTRK):委托共享入库单作废实现
|
||||
// (守卫 sync_status/COMPLETED、回退收货单占用、写操作日志),
|
||||
// 取消成功后不需要向奇门回传任何事件;已作废按幂等成功处理。
|
||||
const orderCode = String(data?.request?.orderCode || '').trim();
|
||||
if (!orderCode) {
|
||||
return this.fail('入库单号不能为空');
|
||||
}
|
||||
|
||||
const rkInfo = this.getInfo();
|
||||
const result = await ctx.service.systems.storage.entry.cancel(
|
||||
{ entryOrderCode: orderCode },
|
||||
{
|
||||
storeId: rkInfo.storeId,
|
||||
warehouseId: rkInfo.warehouseId,
|
||||
operatorLabel: String(rkInfo.customerId || '').trim()
|
||||
? `qimen:${String(rkInfo.customerId).trim()}`
|
||||
: 'qimen',
|
||||
skipExternalSync: true,
|
||||
idempotent: true,
|
||||
notFoundMessage: '未找到对应的入库单',
|
||||
}
|
||||
);
|
||||
|
||||
if (result.code === 200) {
|
||||
const existingOrder = await ctx.model.EntryOrder.findOne({
|
||||
where: {
|
||||
entry_order_code: data.request.orderCode,
|
||||
warehouse_id: info.warehouseId,
|
||||
store_id: info.storeId,
|
||||
},
|
||||
});
|
||||
if (existingOrder) {
|
||||
await existingOrder.update({
|
||||
order_status: 'CANCELLED',
|
||||
updated_at: new Date(),
|
||||
});
|
||||
return this.success('取消入库单成功');
|
||||
}
|
||||
return this.fail(result.message || '取消入库单失败');
|
||||
return this.fail('未找到对应的入库单');
|
||||
}
|
||||
case 'CK':
|
||||
{
|
||||
// CK 组出库单(PTCK/DBCK/B2BCK/QTCK/CGTH):走独立出库单表 wms_order_stockout 取消,
|
||||
// 共享实现 systems/stockout_order.js#cancel(事务 + 行锁,释放 QM_STOCKOUT 锁定)。
|
||||
// 取消成功后不需要向奇门回传任何事件。
|
||||
const orderCode = String(data?.request?.orderCode || '').trim();
|
||||
if (!orderCode) {
|
||||
return this.fail('出库单号不能为空');
|
||||
}
|
||||
|
||||
const ckInfo = this.getInfo();
|
||||
return ctx.service.systems.stockoutOrder.cancel(
|
||||
{ stockoutOrderCode: orderCode },
|
||||
{
|
||||
storeId: ckInfo.storeId,
|
||||
warehouseId: ckInfo.warehouseId,
|
||||
operatorLabel: String(ckInfo.customerId || '').trim()
|
||||
? `qimen:${String(ckInfo.customerId).trim()}`
|
||||
: 'qimen',
|
||||
}
|
||||
);
|
||||
}
|
||||
return this.fail('取消出库单未开发完成');
|
||||
case 'JG':
|
||||
return this.fail('取消加工单未开发完成');
|
||||
case 'BACKORDER':
|
||||
|
||||
@ -3,38 +3,275 @@
|
||||
const MainService = require('../main');
|
||||
|
||||
/**
|
||||
* 奇门出库单适配层。
|
||||
* 奇门出库单服务。
|
||||
*
|
||||
* 处理奇门 stockout.create / stockout.query 接口,业务逻辑统一委托到
|
||||
* `app/service/systems/stockout_order.js`(ctx.service.systems.stockoutOrder),
|
||||
* 与 openapiMethods/stockout.js 共用同一份实现。
|
||||
* 落库表:`wms_order_stockout` + `wms_order_stockout_items`。
|
||||
* 处理 stockout.create / stockout.query 接口,
|
||||
* 使用专用表 `wms_order_stockout` + `wms_order_stockout_items`。
|
||||
*/
|
||||
class stockoutServer extends MainService {
|
||||
|
||||
/**
|
||||
* 创建出库单(奇门渠道,source_type=QM)。
|
||||
* 创建出库单。
|
||||
*
|
||||
* 将奇门 stockout.create 请求的 deliveryOrder / orderLines 写入
|
||||
* `wms_order_stockout` 主表和 `wms_order_stockout_items` 明细表,
|
||||
* 整个过程在一个数据库事务内完成,失败自动回滚。
|
||||
*
|
||||
* @param {object} data - 奇门 stockout.create 请求体
|
||||
* @param {object} data.request - 请求数据
|
||||
* @param {object} data.request.deliveryOrder - 出库单头信息
|
||||
* @param {object} data.request.orderLines - 出库单明细
|
||||
* @param {object|object[]} data.request.orderLines.orderLine - 明细行(单条为对象,多条为数组)
|
||||
* @return {Promise<object>} 返回 success / fail 结果
|
||||
*/
|
||||
async create(data) {
|
||||
const info = this.getInfo();
|
||||
return this.ctx.service.systems.stockoutOrder.create(data, {
|
||||
storeId: info.storeId,
|
||||
warehouseId: info.warehouseId,
|
||||
warehouseCode: info.warehouseCode,
|
||||
appKey: info.appKey,
|
||||
sourceType: 'QM',
|
||||
});
|
||||
const { app, ctx, storeId, warehouseId, warehouseCode } = this;
|
||||
const { deliveryOrder, orderLines } = data.request;
|
||||
|
||||
// 单条 orderLine 转为数组
|
||||
let orderLine = orderLines && orderLines.orderLine;
|
||||
if (orderLine && orderLine.orderLineNo) {
|
||||
orderLine = [ orderLine ];
|
||||
}
|
||||
|
||||
if (!orderLine || !Array.isArray(orderLine) || orderLine.length === 0) {
|
||||
return this.fail('创建出库单失败,失败原因:\n没有有效的订单明细数据');
|
||||
}
|
||||
|
||||
const totalOrderLines = deliveryOrder.totalOrderLines || orderLine.length;
|
||||
|
||||
// 快递编码解析(简化口径,独立于订单兜底链):
|
||||
// 1. 货主开启 enable_external_express_code 且传了 logisticsCode 时,按
|
||||
// wms_express_setting 映射 → 系统快递列表 匹配;
|
||||
// 2. 未传 / 未开启 / 匹配不到 → 使用出库单兜底快递编码(stockout_default_express_code,
|
||||
// 默认 ZT 自提),不再回退订单默认快递;不走订单的快递策略漏斗(matchPolicy)。
|
||||
let expressCode = null;
|
||||
let expressName = null;
|
||||
try {
|
||||
const deliveryOrderService = ctx.service.systems.deliveryOrder;
|
||||
const policyConfig = await deliveryOrderService.getStoreWarehousePolicyConfig(storeId, warehouseId);
|
||||
const expressList = await ctx.service.systems.express.getExpressList();
|
||||
const findExpress = code => {
|
||||
const upperCode = String(code || '').trim().toUpperCase();
|
||||
if (!upperCode || !Array.isArray(expressList)) {
|
||||
return null;
|
||||
}
|
||||
return expressList.find(item => item
|
||||
&& String(item.code || item.value || '').trim().toUpperCase() === upperCode) || null;
|
||||
};
|
||||
const externalCode = String(deliveryOrder.logisticsCode || '').trim();
|
||||
const enableExternal = deliveryOrderService.normalizePolicyFlag(
|
||||
policyConfig && policyConfig.enable_external_express_code
|
||||
);
|
||||
|
||||
if (enableExternal && externalCode) {
|
||||
// 1) wms_express_setting 外部编码映射 → 系统快递编码
|
||||
const settingSnapshot = await deliveryOrderService.resolveExpressSettingSnapshot(externalCode, warehouseId);
|
||||
if (settingSnapshot && settingSnapshot.expressCode) {
|
||||
const sysCode = String(settingSnapshot.expressCode).trim();
|
||||
const sysItem = findExpress(sysCode);
|
||||
expressCode = sysCode;
|
||||
expressName = sysItem
|
||||
? String(sysItem.name || sysItem.label || sysCode).trim()
|
||||
: String(settingSnapshot.name || sysCode).trim();
|
||||
} else {
|
||||
// 2) 系统快递列表直接匹配
|
||||
const matched = findExpress(externalCode);
|
||||
if (matched) {
|
||||
expressCode = String(matched.code || matched.value || externalCode).trim();
|
||||
expressName = String(matched.name || matched.label || expressCode).trim();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!expressCode) {
|
||||
// 兜底:出库单兜底快递编码(货主配置,默认 ZT 自提),不回退订单默认快递
|
||||
const fallbackCode = String(policyConfig && policyConfig.stockout_default_express_code || '').trim() || 'ZT';
|
||||
const fallbackItem = findExpress(fallbackCode);
|
||||
expressCode = fallbackItem
|
||||
? String(fallbackItem.code || fallbackItem.value || fallbackCode).trim()
|
||||
: fallbackCode;
|
||||
expressName = fallbackItem
|
||||
? String(fallbackItem.name || fallbackItem.label || fallbackCode).trim()
|
||||
: fallbackCode;
|
||||
}
|
||||
} catch (err) {
|
||||
ctx.logger.warn(`[stockout.create] 快递编码解析失败,保持为空: ${err.message}`);
|
||||
}
|
||||
|
||||
// 收件人信息解析(receiverInfo 13 个标准字段落库,供转订单与确认回传使用)
|
||||
const receiver = deliveryOrder.receiverInfo && typeof deliveryOrder.receiverInfo === 'object'
|
||||
? deliveryOrder.receiverInfo
|
||||
: {};
|
||||
const receiverFields = {
|
||||
receiver_company: receiver.company,
|
||||
receiver_name: receiver.name,
|
||||
receiver_zip_code: receiver.zipCode,
|
||||
receiver_tel: receiver.tel,
|
||||
receiver_mobile: receiver.mobile,
|
||||
receiver_email: receiver.email,
|
||||
receiver_country_code: receiver.countryCode,
|
||||
receiver_province: receiver.province,
|
||||
receiver_city: receiver.city,
|
||||
receiver_area: receiver.area,
|
||||
receiver_town: receiver.town,
|
||||
receiver_detail_address: receiver.detailAddress,
|
||||
receiver_id: receiver.id,
|
||||
};
|
||||
for (const key of Object.keys(receiverFields)) {
|
||||
const rawValue = receiverFields[key];
|
||||
receiverFields[key] = rawValue === undefined || rawValue === null
|
||||
? null
|
||||
: String(rawValue).trim() || null;
|
||||
}
|
||||
|
||||
// 第一步:校验所有商品是否在 StockStore 中存在,并收集有效明细
|
||||
const errors = [];
|
||||
const items = [];
|
||||
for (let i = 0; i < orderLine.length; i++) {
|
||||
const line = orderLine[i];
|
||||
let wmsStock = await app.model.StockStore.findByPk(line.itemId);
|
||||
// 校验 StockStore 记录的 store_id 与当前上下文一致,防止跨货主越权
|
||||
if (wmsStock && Number(wmsStock.store_id) !== Number(this.storeId)) {
|
||||
wmsStock = null;
|
||||
}
|
||||
// 外部渠道(奇门)itemId 可能是平台商品标识或条码而非 WMS 主键,
|
||||
// 主键查不到或跨货主时降级按 item_code + 仓库货主维度查找
|
||||
if (!wmsStock && line.itemCode) {
|
||||
const stockWhere = {
|
||||
item_code: line.itemCode,
|
||||
warehouse_id: warehouseId,
|
||||
store_id: storeId,
|
||||
};
|
||||
if (this.appKey) {
|
||||
stockWhere.app_key = this.appKey;
|
||||
}
|
||||
wmsStock = await app.model.StockStore.findOne({ where: stockWhere });
|
||||
}
|
||||
if (!wmsStock) {
|
||||
errors.push(
|
||||
`SKU${line.itemId}商品《${line.itemName}》编码《${line.itemCode}》\n未同步推送到仓库`
|
||||
);
|
||||
continue;
|
||||
}
|
||||
if (!wmsStock.stock_id) {
|
||||
errors.push(
|
||||
`SKU${line.itemId}商品《${line.itemName}》编码《${line.itemCode}》wms无对应关系\n请联系仓库关联创建商品`
|
||||
);
|
||||
continue;
|
||||
}
|
||||
const planQty = parseInt(line.planQty) || 0;
|
||||
if (planQty <= 0) {
|
||||
errors.push(
|
||||
`SKU${line.itemId}商品《${line.itemName}》编码《${line.itemCode}》\n计划数量必须大于0`
|
||||
);
|
||||
continue;
|
||||
}
|
||||
items.push({
|
||||
orderLineNo: line.orderLineNo,
|
||||
ownerCode: line.ownerCode,
|
||||
itemCode: line.itemCode,
|
||||
itemId: line.itemId,
|
||||
itemName: line.itemName,
|
||||
planQty,
|
||||
inventoryType: line.inventoryType,
|
||||
stockId: wmsStock.stock_id,
|
||||
});
|
||||
}
|
||||
|
||||
if (errors.length > 0) {
|
||||
return this.fail(`创建出库单失败,失败原因:\n${errors.join('\n')}`);
|
||||
}
|
||||
|
||||
// 预取超卖配置,避免每次 lockItemStorages 在锁内回退查 DB
|
||||
const oversellConfig = await ctx.service.systems.stockStore
|
||||
.getStoreWarehousePolicyByStoreAndWarehouse(storeId, warehouseId);
|
||||
|
||||
// 第二步:在事务中写入主表 + 库存锁定 + 明细表
|
||||
const transaction = await ctx.model.transaction();
|
||||
try {
|
||||
const order = await ctx.model.OrderStockout.create(
|
||||
{
|
||||
stockout_order_code: deliveryOrder.deliveryOrderCode,
|
||||
order_type: deliveryOrder.orderType,
|
||||
total_order_lines: totalOrderLines,
|
||||
order_create_time: deliveryOrder.createTime
|
||||
? new Date(deliveryOrder.createTime)
|
||||
: null,
|
||||
remark: deliveryOrder.remark || null,
|
||||
express_code: expressCode,
|
||||
express_name: expressName,
|
||||
...receiverFields,
|
||||
warehouse_id: warehouseId,
|
||||
store_id: storeId,
|
||||
qimen_owner_code: items[0].ownerCode,
|
||||
qimen_warehouse_code: warehouseCode,
|
||||
source_type: 'QM',
|
||||
created_at: new Date(),
|
||||
updated_at: new Date(),
|
||||
},
|
||||
{ transaction }
|
||||
);
|
||||
|
||||
const orderId = order.id;
|
||||
|
||||
// 库存锁定:按 stockId 升序排序后逐个加锁,避免死锁
|
||||
const sortedItems = [ ...items ].sort((a, b) => a.stockId - b.stockId);
|
||||
for (const item of sortedItems) {
|
||||
const lockResult = await ctx.service.systems.stockStore.lockItemStorages(
|
||||
item.stockId,
|
||||
item.planQty,
|
||||
transaction,
|
||||
oversellConfig,
|
||||
{ orderType: 'QM_STOCKOUT', orderNo: deliveryOrder.deliveryOrderCode, orderId }
|
||||
);
|
||||
if (!lockResult.success) {
|
||||
throw new Error(
|
||||
`SKU${item.itemId}商品《${item.itemName}》编码《${item.itemCode}》\n库存锁定失败: ${lockResult.error}`
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// 批量创建明细
|
||||
const now = new Date();
|
||||
const itemRecords = items.map(item => ({
|
||||
order_id: orderId,
|
||||
order_line_no: item.orderLineNo,
|
||||
owner_code: item.ownerCode,
|
||||
item_code: item.itemCode,
|
||||
item_id: item.itemId,
|
||||
item_name: item.itemName,
|
||||
plan_qty: item.planQty,
|
||||
inventory_type: item.inventoryType,
|
||||
stock_id: item.stockId,
|
||||
created_at: now,
|
||||
updated_at: now,
|
||||
}));
|
||||
|
||||
await ctx.model.OrderStockoutItems.bulkCreate(itemRecords, {
|
||||
transaction,
|
||||
validate: true,
|
||||
});
|
||||
|
||||
await transaction.commit();
|
||||
|
||||
return this.success('出库单创建成功', {
|
||||
stockoutOrderId: order.id,
|
||||
stockoutOrderCode: order.stockout_order_code,
|
||||
});
|
||||
} catch (err) {
|
||||
await transaction.rollback();
|
||||
ctx.logger.error('[stockout.create] 事务写入失败:', err);
|
||||
return this.fail(`创建出库单失败,失败原因:\n${err.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询出库单。
|
||||
*
|
||||
* 根据 deliveryOrderCode 查 `wms_order_stockout` 主表,
|
||||
* 然后关联查 `wms_order_stockout_items` 明细,按奇门标准响应格式返回。
|
||||
*
|
||||
* @param {object} data - 奇门 stockout.query 请求体
|
||||
* @param {object} data.request - 请求数据
|
||||
* @param {object} data.request.deliveryOrder - 出库单查询条件
|
||||
@ -42,9 +279,47 @@ class stockoutServer extends MainService {
|
||||
* @return {Promise<object>} 返回 success / fail 结果
|
||||
*/
|
||||
async query(data) {
|
||||
return this.ctx.service.systems.stockoutOrder.query(data);
|
||||
const { app, ctx } = this;
|
||||
const { deliveryOrderCode } = data.request.deliveryOrder;
|
||||
|
||||
// 查主表
|
||||
const order = await ctx.model.OrderStockout.findOne({
|
||||
where: { stockout_order_code: deliveryOrderCode },
|
||||
});
|
||||
if (!order) {
|
||||
return this.fail('未找到出库单');
|
||||
}
|
||||
|
||||
// 查明细
|
||||
const items = await ctx.model.OrderStockoutItems.findAll({
|
||||
where: { order_id: order.id },
|
||||
order: [[ 'order_line_no', 'ASC' ]],
|
||||
});
|
||||
|
||||
return this.success('成功', {
|
||||
totalLines: items.length,
|
||||
deliveryOrder: {
|
||||
deliveryOrderCode: order.stockout_order_code,
|
||||
deliveryOrderId: order.id,
|
||||
warehouseCode: order.qimen_warehouse_code,
|
||||
orderType: order.order_type,
|
||||
status: order.order_status,
|
||||
createTime: order.order_create_time ? app.formatDate(order.order_create_time) : null,
|
||||
remark: order.remark || '',
|
||||
},
|
||||
orderLines: {
|
||||
orderLine: items.map(item => ({
|
||||
orderLineNo: item.order_line_no,
|
||||
ownerCode: item.owner_code,
|
||||
itemCode: item.item_code,
|
||||
itemId: item.item_id,
|
||||
itemName: item.item_name,
|
||||
planQty: item.plan_qty,
|
||||
inventoryType: item.inventory_type,
|
||||
})),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
module.exports = stockoutServer;
|
||||
|
||||
@ -1,46 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
const MainService = require('../main');
|
||||
|
||||
class FrontConfigMethodsService extends MainService {
|
||||
constructor(ctx) {
|
||||
super(ctx);
|
||||
// 公共按域名拉取前端配置:免登录、免权限、免鉴权(保留系统日志,与 workbench 公共接口口径一致)
|
||||
const _noNeedLogin = 'getByDomain';
|
||||
const _noNeedRight = 'getByDomain';
|
||||
const _noNeedLog = '';
|
||||
const _noNeedAuth = 'getByDomain';
|
||||
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
|
||||
}
|
||||
|
||||
/**
|
||||
* 按域名拉取仓库前端公开配置(公共无鉴权接口)。
|
||||
*
|
||||
* 安全红线:响应仅含公开字段(domain/title/logo_url/login_bg_url/favicon_url/theme),
|
||||
* 不含 cert_path、key_path、sync_status、sync_attempts、last_sync_error 等内部字段。
|
||||
*
|
||||
* @param {Object} [data={}] 请求参数。
|
||||
* @param {string} data.domain 待查询域名(必填,非空)。
|
||||
* @return {Promise<Object>} 统一响应结构;命中返回公开字段配置(code=200),
|
||||
* 未登记域名返回 code=404「域名未配置」。
|
||||
*/
|
||||
async getByDomain(data = {}) {
|
||||
const { domain } = data || {};
|
||||
|
||||
const targetService = this.service && this.service.systems && this.service.systems.setting && this.service.systems.setting.warehouse;
|
||||
if (!targetService || typeof targetService.getFrontConfigByDomain !== 'function') {
|
||||
return this.fail('获取前端配置失败', { code: 500 });
|
||||
}
|
||||
|
||||
try {
|
||||
const result = await targetService.getFrontConfigByDomain(domain);
|
||||
return this.success('获取成功', { ...result, code: 200 });
|
||||
} catch (error) {
|
||||
return this.fail(error.message || '获取前端配置失败', {
|
||||
code: Number(error.code) || 500,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = FrontConfigMethodsService;
|
||||
@ -1052,10 +1052,10 @@ class indexService extends MainService {
|
||||
*/
|
||||
constructor(ctx) {
|
||||
super(ctx);
|
||||
const _noNeedLogin = 'getI18nMessage,putI18nCollect,test,getCainiaoStfTemplates,polyapiAuthorizeUrl,getWorkbenchBindCode,LoginWorkbenchByCode,queryUserByToken';
|
||||
const _noNeedRight = 'loginToIm,getI18nMessage,putI18nCollect,fastWhereTree,loadStores,loadWarehouses,loadExpressInterfaces,getImages,getCOSUploadConfig,uploadSuccessNotify,getMessageDetail,searchSpace,searchSpaces,listInterfaceTypes,getLocationTypeList,getQimenAppList,getExpressList,getExpressProductTypeList,getPlatformList,getPrintPlatformList,getPlatformOauthLink,listenPlatformOauthBind,recognizeLicensePlate,getCainiaoStfTemplates,getPrintPlatformTemplateList,polyapiAuthorizeUrl,toOrder,getWorkbenchBindCode,LoginWorkbenchByCode,queryUserByToken';
|
||||
const _noNeedLogin = 'getI18nMessage,putI18nCollect,test,getCainiaoStfTemplates,polyapiAuthorizeUrl,getWorkbenchBindCode,LoginWorkbenchByCode';
|
||||
const _noNeedRight = 'loginToIm,getI18nMessage,putI18nCollect,fastWhereTree,loadStores,loadWarehouses,loadExpressInterfaces,getImages,getCOSUploadConfig,uploadSuccessNotify,getMessageDetail,searchSpace,searchSpaces,listInterfaceTypes,getLocationTypeList,getQimenAppList,getExpressList,getExpressProductTypeList,getPlatformList,getPrintPlatformList,getPlatformOauthLink,listenPlatformOauthBind,recognizeLicensePlate,getCainiaoStfTemplates,getPrintPlatformTemplateList,polyapiAuthorizeUrl,toOrder,getWorkbenchBindCode,LoginWorkbenchByCode';
|
||||
const _noNeedLog = '*';
|
||||
const _noNeedAuth = 'loginToIm,getI18nMessage,putI18nCollect,fastWhereTree,loadStores,loadWarehouses,loadExpressInterfaces,getImages,getMessageDetail,searchSpace,searchSpaces,listInterfaceTypes,getLocationTypeList,getQimenAppList,getExpressList,getExpressProductTypeList,getPlatformList,getPrintPlatformList,getPlatformOauthLink,listenPlatformOauthBind,recognizeLicensePlate,test,getCainiaoStfTemplates,getPrintPlatformTemplateList,polyapiAuthorizeUrl,toOrder,getWorkbenchBindCode,LoginWorkbenchByCode,queryUserByToken';
|
||||
const _noNeedAuth = 'loginToIm,getI18nMessage,putI18nCollect,fastWhereTree,loadStores,loadWarehouses,loadExpressInterfaces,getImages,getMessageDetail,searchSpace,searchSpaces,listInterfaceTypes,getLocationTypeList,getQimenAppList,getExpressList,getExpressProductTypeList,getPlatformList,getPrintPlatformList,getPlatformOauthLink,listenPlatformOauthBind,recognizeLicensePlate,test,getCainiaoStfTemplates,getPrintPlatformTemplateList,polyapiAuthorizeUrl,toOrder,getWorkbenchBindCode,LoginWorkbenchByCode';
|
||||
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
|
||||
}
|
||||
async fastWhereTree(data) {
|
||||
@ -3397,46 +3397,5 @@ class indexService extends MainService {
|
||||
return this.fail(error.message);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据 token(ye4s 登录临时码 tmp_code)查询用户信息。
|
||||
*
|
||||
* @param {Object} data 请求参数
|
||||
* @param {string} data.token ye4s 登录临时码(对应 ye4s_user.tmp_code)
|
||||
* @return {Promise<Object>} 统一响应结构;命中时返回 real_name 与 wms_account_id,未命中时返回失败响应(code=404)
|
||||
*/
|
||||
async queryUserByToken(data = {}) {
|
||||
const { ctx } = this;
|
||||
const { token } = data || {};
|
||||
|
||||
if (!token || !String(token).trim()) {
|
||||
return this.fail('token 不能为空', { code: 400 });
|
||||
}
|
||||
|
||||
try {
|
||||
const ye4sClient = ctx.app.mysql.get('ye4s');
|
||||
const rows = await ye4sClient.select('ye4s_user', {
|
||||
where: {
|
||||
tmp_code: String(token).trim(),
|
||||
},
|
||||
columns: [ 'real_name', 'wms_account_id' ],
|
||||
limit: 1,
|
||||
});
|
||||
|
||||
if (!rows || rows.length === 0) {
|
||||
return this.fail('用户不存在', { code: 404 });
|
||||
}
|
||||
|
||||
const userRecord = rows[0];
|
||||
return this.success('查询成功', {
|
||||
real_name: userRecord.real_name ?? '',
|
||||
wms_account_id: userRecord.wms_account_id ?? null,
|
||||
code: 200,
|
||||
});
|
||||
} catch (error) {
|
||||
ctx.logger.error('查询用户失败:', error);
|
||||
return this.fail(error.message || '查询用户失败', { code: 500 });
|
||||
}
|
||||
}
|
||||
}
|
||||
module.exports = indexService;
|
||||
|
||||
@ -801,13 +801,8 @@ class OrderBaseService extends MainService {
|
||||
|
||||
/**
|
||||
* 查询订单关联运单信息。
|
||||
*
|
||||
* 强制同仓校验:查询条件必须同时包含订单ID与仓库ID,
|
||||
* 禁止仅凭订单ID读取 wms_order_express,避免跨仓串读运单号。
|
||||
* 仓库ID优先取订单详情行(order.warehouse_id),缺省时回退当前用户上下文仓库。
|
||||
*
|
||||
* @param {number|string} orderId 订单ID。
|
||||
* @param {Object} [order] 订单详情行,用于补充 sys_logistics_code / sys_logistics_name 与仓库ID。
|
||||
* @param {Object} [order] 订单详情行,用于补充 sys_logistics_code / sys_logistics_name。
|
||||
* @return {Promise<Object[]>} 运单信息列表。
|
||||
*/
|
||||
async getOrderExpressesByOrderId(orderId, order) {
|
||||
@ -822,23 +817,9 @@ class OrderBaseService extends MainService {
|
||||
return [];
|
||||
}
|
||||
|
||||
// 强制同仓校验:仓库ID优先取订单行,缺省回退当前上下文仓库;均缺失时拒绝读取
|
||||
const contextWarehouseId = this.getWarehouseId();
|
||||
const orderWarehouseId = Number(order && order.warehouse_id);
|
||||
const warehouseId = Number.isFinite(orderWarehouseId) && orderWarehouseId > 0
|
||||
? orderWarehouseId
|
||||
: (contextWarehouseId !== null && contextWarehouseId !== undefined && contextWarehouseId !== ''
|
||||
? Number(contextWarehouseId)
|
||||
: 0);
|
||||
|
||||
if (!Number.isFinite(warehouseId) || warehouseId <= 0) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const rows = await orderExpressModel.findAll({
|
||||
where: {
|
||||
order_id: normalizedOrderId,
|
||||
warehouse_id: warehouseId,
|
||||
},
|
||||
attributes: [ 'waybill_code', 'logistics_code', 'logistics_name', 'logistics_interface_id', 'logistics_interface_name', 'weighing_weight', 'business_key', 'create_at', 'package_material_id', 'package_material_name_snapshot' ],
|
||||
order: [[ 'id', 'ASC' ]],
|
||||
@ -899,10 +880,6 @@ class OrderBaseService extends MainService {
|
||||
|
||||
/**
|
||||
* 批量补齐订单列表的快递号信息。
|
||||
*
|
||||
* 强制同仓校验:运单查询按「订单ID + 仓库ID」分组执行,
|
||||
* 禁止仅凭订单ID读取 wms_order_express,避免跨仓串读运单号。
|
||||
*
|
||||
* @param {Object[]} list 订单列表。
|
||||
* @return {Promise<Object[]>} 补齐后的列表。
|
||||
*/
|
||||
@ -925,53 +902,16 @@ class OrderBaseService extends MainService {
|
||||
}
|
||||
|
||||
const { Op } = this.app.Sequelize;
|
||||
|
||||
// 强制同仓校验:逐订单解析仓库归属(行内 warehouse_id 优先,缺省回退当前上下文仓库),
|
||||
// 无法确定仓库归属的订单不参与运单查询,避免仅凭订单ID跨仓串读
|
||||
const contextWarehouseId = this.getWarehouseId();
|
||||
const warehouseIdByOrder = new Map();
|
||||
for (const item of list) {
|
||||
const orderId = Number(item && item.id);
|
||||
if (!Number.isFinite(orderId) || orderId <= 0) {
|
||||
continue;
|
||||
}
|
||||
const rowWarehouseId = Number(item && item.warehouse_id);
|
||||
if (Number.isFinite(rowWarehouseId) && rowWarehouseId > 0) {
|
||||
warehouseIdByOrder.set(orderId, rowWarehouseId);
|
||||
} else if (contextWarehouseId !== null && contextWarehouseId !== undefined && contextWarehouseId !== '') {
|
||||
warehouseIdByOrder.set(orderId, Number(contextWarehouseId));
|
||||
}
|
||||
}
|
||||
|
||||
const scopedOrderIds = orderIds.filter(orderId => warehouseIdByOrder.has(orderId));
|
||||
const expressRows = [];
|
||||
if (scopedOrderIds.length > 0) {
|
||||
const orderIdsByWarehouse = new Map();
|
||||
for (const orderId of scopedOrderIds) {
|
||||
const orderWarehouseId = warehouseIdByOrder.get(orderId);
|
||||
if (!orderIdsByWarehouse.has(orderWarehouseId)) {
|
||||
orderIdsByWarehouse.set(orderWarehouseId, []);
|
||||
}
|
||||
orderIdsByWarehouse.get(orderWarehouseId).push(orderId);
|
||||
}
|
||||
|
||||
for (const [ orderWarehouseId, warehouseOrderIds ] of orderIdsByWarehouse.entries()) {
|
||||
const rows = await orderExpressModel.findAll({
|
||||
where: {
|
||||
order_id: {
|
||||
[Op.in]: warehouseOrderIds,
|
||||
},
|
||||
warehouse_id: orderWarehouseId,
|
||||
},
|
||||
attributes: [ 'id', 'order_id', 'waybill_code', 'logistics_code', 'logistics_name', 'logistics_interface_id', 'platform_code' ],
|
||||
order: [[ 'id', 'ASC' ]],
|
||||
raw: true,
|
||||
});
|
||||
if (Array.isArray(rows)) {
|
||||
expressRows.push(...rows);
|
||||
}
|
||||
}
|
||||
}
|
||||
const expressRows = await orderExpressModel.findAll({
|
||||
where: {
|
||||
order_id: {
|
||||
[Op.in]: orderIds,
|
||||
},
|
||||
},
|
||||
attributes: [ 'id', 'order_id', 'waybill_code', 'logistics_code', 'logistics_name', 'logistics_interface_id', 'platform_code' ],
|
||||
order: [[ 'id', 'ASC' ]],
|
||||
raw: true,
|
||||
});
|
||||
|
||||
const expressMap = new Map();
|
||||
if (Array.isArray(expressRows)) {
|
||||
@ -1191,7 +1131,7 @@ class OrderBaseService extends MainService {
|
||||
/**
|
||||
* 提取 wave_scope(波次范围)虚拟筛选条件。
|
||||
* 将其从 where 中移除并解析为波次范围值集合,后续直接生成订单表 wave_scope 字段过滤。
|
||||
* 取值约定:0=未分配波次,1=大团购,2=散单,3=小团购,4=单品单件;value 支持单个值或数组(多选)。
|
||||
* 取值约定:0=未分配波次,1=大团购,2=散单,3=小团购;value 支持单个值或数组(多选)。
|
||||
* @param {Object} whereInput 标准化后的 where 条件。
|
||||
* @return {{ where: Object, waveScope: number[]|null }} 清洗后的 where 与波次范围值集合。
|
||||
*/
|
||||
@ -1223,8 +1163,8 @@ class OrderBaseService extends MainService {
|
||||
));
|
||||
|
||||
for (const scope of normalizedScopes) {
|
||||
if (!Number.isInteger(scope) || scope < 0 || scope > 4) {
|
||||
throw new Error('wave_scope 参数不合法,仅支持 0(未分配波次)/1(大团购)/2(散单)/3(小团购)/4(单品单件)');
|
||||
if (!Number.isInteger(scope) || scope < 0 || scope > 3) {
|
||||
throw new Error('wave_scope 参数不合法,仅支持 0(未分配波次)/1(大团购)/2(散单)/3(小团购)');
|
||||
}
|
||||
}
|
||||
|
||||
@ -1303,7 +1243,7 @@ class OrderBaseService extends MainService {
|
||||
* 根据波次范围(wave_scope)构建订单表 wave_scope 字段过滤条件。
|
||||
* 订单表已冗余 wave_scope 字段(写入波次时维护),直接按字段过滤,
|
||||
* 无需再反查 wms_wave_batch。
|
||||
* @param {Array<number>} waveScopes 波次范围值集合(0/1/2/3/4)。
|
||||
* @param {Array<number>} waveScopes 波次范围值集合(0/1/2/3)。
|
||||
* @return {Object|null} Sequelize 条件,无有效范围时返回 null。
|
||||
*/
|
||||
buildWaveScopeFilterCondition(waveScopes = []) {
|
||||
@ -1312,7 +1252,7 @@ class OrderBaseService extends MainService {
|
||||
(Array.isArray(waveScopes) ? waveScopes : [ waveScopes ])
|
||||
.filter(scope => scope !== undefined && scope !== null && scope !== '')
|
||||
.map(scope => Number(scope))
|
||||
)).filter(scope => Number.isInteger(scope) && scope >= 0 && scope <= 4);
|
||||
)).filter(scope => Number.isInteger(scope) && scope >= 0 && scope <= 3);
|
||||
|
||||
if (normalizedScopes.length === 0) {
|
||||
return null;
|
||||
|
||||
@ -34,9 +34,6 @@ class OrderPackingMethodService extends MainService {
|
||||
* order_id(订单ID)、workbench_id(工作台ID)、quickWhere(快捷搜索:波次号直接匹配 + 运单号通过express→order→wave链路解析)、
|
||||
* start_time(开始打包时间范围,{operator:'between', value:[start,end]})、end_time(结束打包时间范围)、create_time(创建时间范围);
|
||||
* start_time_start / start_time_end 为开始时间范围的兼容旧写法。
|
||||
* 运单号与波次号字段支持 {operator, value} 标准结构且 value 支持数组:
|
||||
* operator=contains/like 时按 LIKE '%值%' 模糊匹配(waybill_code 可命中 '主体-1-1-' 等分段单号),wave_no 另支持 eq/in 精确、ne 不等;
|
||||
* waybill_code 缺省/eq 时为「完整单号等值 + 剥离分段后缀主体等值 + 主体前缀」精确匹配。
|
||||
* @param {Object} [data.sort] 排序参数 { sortField, sortOrder }
|
||||
* @return {Promise<Object>} 统一成功包装响应
|
||||
*/
|
||||
|
||||
@ -3,7 +3,6 @@
|
||||
const OrderBaseService = require('./base');
|
||||
|
||||
const { getInterceptRequestBlockReason, resolveInterceptRequestGuardInfoMap } = require('../../../lib/intercept_guard');
|
||||
const { pickNoticeTimeOrderIds } = require('../../../lib/intercept_time');
|
||||
|
||||
const PENDING_OUTBOUND_STATUS = 'padding';
|
||||
const PENDING_CANCEL_STATUS = 'cancel';
|
||||
@ -874,7 +873,7 @@ class PendingOrderService extends OrderBaseService {
|
||||
.map(order => Number(order && order.id || 0))
|
||||
.filter(id => Number.isInteger(id) && id > 0);
|
||||
|
||||
await this.assertOrdersWithoutWaybill(targetOrderIds, warehouseId, transaction);
|
||||
await this.assertOrdersWithoutWaybill(targetOrderIds, transaction);
|
||||
|
||||
const affectedWaveIds = [ ...new Set(targetOrders
|
||||
.map(order => Number(order && order.wave_id || 0))
|
||||
@ -959,16 +958,13 @@ class PendingOrderService extends OrderBaseService {
|
||||
/**
|
||||
* 校验订单是否已分配运单号。
|
||||
*
|
||||
* 强制同仓校验:读取 wms_order_express 必须同时带上订单ID与仓库ID,
|
||||
* 禁止仅凭订单ID跨仓串读运单号。
|
||||
* 若任一订单存在非空运单号,直接抛出业务异常,阻止反审。
|
||||
*
|
||||
* @param {Array<number>} orderIds 订单ID集合。
|
||||
* @param {number|string|null|undefined} warehouseId 仓库ID,必须为当前订单所属仓库。
|
||||
* @param {Object} transaction Sequelize 事务对象。
|
||||
* @return {Promise<void>} 无返回值。
|
||||
*/
|
||||
async assertOrdersWithoutWaybill(orderIds = [], warehouseId = null, transaction) {
|
||||
async assertOrdersWithoutWaybill(orderIds = [], transaction) {
|
||||
const normalizedOrderIds = Array.isArray(orderIds)
|
||||
? orderIds
|
||||
.map(orderId => Number(orderId || 0))
|
||||
@ -984,19 +980,10 @@ class PendingOrderService extends OrderBaseService {
|
||||
return;
|
||||
}
|
||||
|
||||
// 强制同仓校验:缺少仓库上下文时直接跳过校验读取(按无可读记录处理)
|
||||
const normalizedWarehouseId = warehouseId !== null && warehouseId !== undefined && warehouseId !== ''
|
||||
? Number(warehouseId)
|
||||
: 0;
|
||||
if (!Number.isInteger(normalizedWarehouseId) || normalizedWarehouseId <= 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
const expressRows = await orderExpressModel.findAll({
|
||||
attributes: [ 'order_id', 'waybill_code' ],
|
||||
where: {
|
||||
order_id: normalizedOrderIds,
|
||||
warehouse_id: normalizedWarehouseId,
|
||||
},
|
||||
raw: true,
|
||||
transaction,
|
||||
@ -2418,7 +2405,6 @@ class PendingOrderService extends OrderBaseService {
|
||||
/**
|
||||
* 将待处理订单取消,并关闭到已取消状态。
|
||||
* 仅允许取消当前仓库内处于待审核、待处理、待处理异常语义的订单。
|
||||
* 已同步订单取消时转为拦截处理:写入 intercept_status='requested' 并同步写入拦截时间 intercept_time。
|
||||
*
|
||||
* 取消、波次清理、储位释放与创建锁释放在同一事务内完成:
|
||||
* 任一环节失败整体回滚,避免"已取消但库存锁定未释放"的中间态。
|
||||
@ -2503,8 +2489,6 @@ class PendingOrderService extends OrderBaseService {
|
||||
);
|
||||
if (syncedOrderIds.length > 0) {
|
||||
const syncNow = new Date();
|
||||
// 通知拦截时间只在首次发起时写入(重复发起不覆盖已有值)
|
||||
const fillNoticeOrderIds = pickNoticeTimeOrderIds(syncedOrders);
|
||||
await model.update(
|
||||
{
|
||||
intercept_status: 'requested',
|
||||
@ -2517,12 +2501,6 @@ class PendingOrderService extends OrderBaseService {
|
||||
transaction,
|
||||
}
|
||||
);
|
||||
if (fillNoticeOrderIds.length > 0) {
|
||||
await model.update(
|
||||
{ intercept_time: syncNow },
|
||||
{ where: { id: fillNoticeOrderIds }, transaction }
|
||||
);
|
||||
}
|
||||
// 同步更新运单表拦截标记
|
||||
try {
|
||||
const { Op: cancelOp } = this.app.Sequelize;
|
||||
@ -2895,8 +2873,6 @@ class PendingOrderService extends OrderBaseService {
|
||||
* 用 code 查找 wms_platform 表中对应的平台记录,若存在则将订单的
|
||||
* sys_platform_code 和 sys_platform_name 更新为该平台的 code 和 name;
|
||||
* 若不存在则返回错误。只操作当前仓库的当前订单表,不处理其他订单表。
|
||||
* 正在分配快递(wms_order_express 存在 status=0 的取号中占位记录)的订单跳过处理,
|
||||
* 不影响其余订单,跳过明细通过 skipped_order_ids 透出。
|
||||
*
|
||||
* @param {Object} data 请求体。
|
||||
* @param {number[]} data.order_ids 订单ID 数组。
|
||||
@ -2936,46 +2912,14 @@ class PendingOrderService extends OrderBaseService {
|
||||
throw new Error(`平台编码 ${code} 不存在`);
|
||||
}
|
||||
|
||||
// 正在分配快递的订单(order_express 存在 status=0 占位记录)跳过处理,不影响其余订单
|
||||
const orderExpressModel = this.ctx.model && this.ctx.model.OrderExpress;
|
||||
const allocatingIdSet = new Set();
|
||||
if (orderExpressModel && typeof orderExpressModel.findAll === 'function') {
|
||||
const allocatingRows = await orderExpressModel.findAll({
|
||||
attributes: [ 'order_id' ],
|
||||
where: {
|
||||
order_id: orderIds,
|
||||
warehouse_id: warehouseId,
|
||||
status: 0,
|
||||
},
|
||||
raw: true,
|
||||
});
|
||||
for (const row of Array.isArray(allocatingRows) ? allocatingRows : []) {
|
||||
const orderId = Number(row && row.order_id);
|
||||
if (Number.isFinite(orderId) && orderId > 0) {
|
||||
allocatingIdSet.add(orderId);
|
||||
}
|
||||
}
|
||||
}
|
||||
const skippedOrderIds = orderIds.filter(orderId => allocatingIdSet.has(orderId));
|
||||
const updatableOrderIds = orderIds.filter(orderId => !allocatingIdSet.has(orderId));
|
||||
|
||||
const model = await this.getOrderModel('order', warehouseId);
|
||||
const where = {
|
||||
...this.buildOrderWhere(updatableOrderIds, warehouseId),
|
||||
...this.buildOrderWhere(orderIds, warehouseId),
|
||||
post_status: 'none',
|
||||
};
|
||||
|
||||
const platformName = String(platform.name || '').trim();
|
||||
|
||||
if (updatableOrderIds.length === 0) {
|
||||
return this.success('ok', {
|
||||
updated_count: 0,
|
||||
skipped_order_ids: skippedOrderIds,
|
||||
sys_platform_code: platform.code,
|
||||
sys_platform_name: platformName,
|
||||
});
|
||||
}
|
||||
|
||||
// 更新前查询候选订单,筛出平台实际发生变化的订单,用于逐单写入订单日志
|
||||
const candidateOrders = await model.findAll({
|
||||
where,
|
||||
@ -3008,7 +2952,7 @@ class PendingOrderService extends OrderBaseService {
|
||||
sys_platform_code: platform.code,
|
||||
sys_platform_name: platformName,
|
||||
updated_count: count,
|
||||
message: `批量修改订单平台:订单ID [${orderIds.join(', ')}],平台 ${platform.code}(${platformName}),共更新 ${count} 条${skippedOrderIds.length > 0 ? `,跳过取号中 ${skippedOrderIds.length} 条` : ''}`,
|
||||
message: `批量修改订单平台:订单ID [${orderIds.join(', ')}],平台 ${platform.code}(${platformName}),共更新 ${count} 条`,
|
||||
},
|
||||
beforeChanges: null,
|
||||
});
|
||||
@ -3051,7 +2995,6 @@ class PendingOrderService extends OrderBaseService {
|
||||
|
||||
return this.success('ok', {
|
||||
updated_count: count,
|
||||
skipped_order_ids: skippedOrderIds,
|
||||
sys_platform_code: platform.code,
|
||||
sys_platform_name: String(platform.name || '').trim(),
|
||||
});
|
||||
@ -3067,10 +3010,6 @@ class PendingOrderService extends OrderBaseService {
|
||||
* logistics_code/logistics_name 均写系统快递的 code/name;
|
||||
* - 未找到则报错。
|
||||
* 只操作当前仓库的当前订单表,不处理其他订单表。
|
||||
* 操作日志逐单写入(business_id 为订单 ID),确保订单详情页可查询;
|
||||
* 未满足更新条件(post_status 不为 none)的订单写入"未生效"日志。
|
||||
* 正在分配快递(wms_order_express 存在 status=0 的取号中占位记录)的订单跳过处理,
|
||||
* 不影响其余订单,跳过明细通过 skipped_order_ids 透出。
|
||||
*
|
||||
* @param {Object} data 请求体。
|
||||
* @param {number[]} data.order_ids 订单ID 数组。
|
||||
@ -3132,58 +3071,12 @@ class PendingOrderService extends OrderBaseService {
|
||||
logisticsName = sysLogisticsName;
|
||||
}
|
||||
|
||||
// 正在分配快递的订单(order_express 存在 status=0 占位记录)跳过处理,不影响其余订单
|
||||
const orderExpressModel = this.ctx.model && this.ctx.model.OrderExpress;
|
||||
const allocatingIdSet = new Set();
|
||||
if (orderExpressModel && typeof orderExpressModel.findAll === 'function') {
|
||||
const allocatingRows = await orderExpressModel.findAll({
|
||||
attributes: [ 'order_id' ],
|
||||
where: {
|
||||
order_id: orderIds,
|
||||
warehouse_id: warehouseId,
|
||||
status: 0,
|
||||
},
|
||||
raw: true,
|
||||
});
|
||||
for (const row of Array.isArray(allocatingRows) ? allocatingRows : []) {
|
||||
const orderId = Number(row && row.order_id);
|
||||
if (Number.isFinite(orderId) && orderId > 0) {
|
||||
allocatingIdSet.add(orderId);
|
||||
}
|
||||
}
|
||||
}
|
||||
const skippedOrderIds = orderIds.filter(orderId => allocatingIdSet.has(orderId));
|
||||
const updatableOrderIds = orderIds.filter(orderId => !allocatingIdSet.has(orderId));
|
||||
|
||||
const model = await this.getOrderModel('order', warehouseId);
|
||||
const where = {
|
||||
...this.buildOrderWhere(updatableOrderIds, warehouseId),
|
||||
...this.buildOrderWhere(orderIds, warehouseId),
|
||||
post_status: 'none',
|
||||
};
|
||||
|
||||
if (updatableOrderIds.length === 0) {
|
||||
return this.success('ok', {
|
||||
updated_count: 0,
|
||||
skipped_order_ids: skippedOrderIds,
|
||||
sys_logistics_code: sysLogisticsCode,
|
||||
sys_logistics_name: sysLogisticsName,
|
||||
logistics_code: logisticsCode,
|
||||
logistics_name: logisticsName,
|
||||
});
|
||||
}
|
||||
|
||||
// 更新前先确定实际可修改的订单集合,用于逐单写订单维度日志
|
||||
const updatableRows = await model.findAll({
|
||||
attributes: [ 'id' ],
|
||||
where,
|
||||
raw: true,
|
||||
});
|
||||
const updatableIdSet = new Set(
|
||||
(Array.isArray(updatableRows) ? updatableRows : [])
|
||||
.map(row => Number(row && row.id))
|
||||
.filter(v => Number.isFinite(v) && v > 0)
|
||||
);
|
||||
|
||||
const [ affectedRows ] = await model.update({
|
||||
sys_logistics_code: sysLogisticsCode,
|
||||
sys_logistics_name: sysLogisticsName,
|
||||
@ -3194,44 +3087,32 @@ class PendingOrderService extends OrderBaseService {
|
||||
|
||||
const count = Number(affectedRows || 0);
|
||||
|
||||
// 记录操作日志:逐单写入(business_id 为订单 ID),订单详情页可查询
|
||||
const logPayloads = updatableOrderIds.map(orderId => {
|
||||
const isUpdated = updatableIdSet.has(orderId);
|
||||
return {
|
||||
// 记录操作日志
|
||||
try {
|
||||
await this.ctx.service.systems.operationLog.createOperationLog({
|
||||
businessType: 'order',
|
||||
businessId: String(orderId),
|
||||
businessId: logWarehouseId,
|
||||
operationCode: 'ORDER_UPDATE_EXPRESS',
|
||||
operator,
|
||||
extras: {
|
||||
warehouseId: logWarehouseId,
|
||||
orderIds: [ orderId ],
|
||||
orderIds,
|
||||
express_code: expressCode,
|
||||
sys_logistics_code: sysLogisticsCode,
|
||||
sys_logistics_name: sysLogisticsName,
|
||||
logistics_code: logisticsCode,
|
||||
logistics_name: logisticsName,
|
||||
updated_count: isUpdated ? 1 : 0,
|
||||
message: isUpdated
|
||||
? `修改订单快递:快递 ${logisticsCode}(${logisticsName}),系统快递 ${sysLogisticsCode}(${sysLogisticsName})`
|
||||
: `修改订单快递未生效(订单已分配快递或状态不允许):快递 ${logisticsCode}(${logisticsName})`,
|
||||
updated_count: count,
|
||||
message: `批量修改订单快递:订单ID [${orderIds.join(', ')}],快递 ${logisticsCode}(${logisticsName}),系统快递 ${sysLogisticsCode}(${sysLogisticsName}),共更新 ${count} 条`,
|
||||
},
|
||||
beforeChanges: null,
|
||||
};
|
||||
});
|
||||
|
||||
try {
|
||||
if (logPayloads.length === 1) {
|
||||
await this.ctx.service.systems.operationLog.createOperationLog(logPayloads[0]);
|
||||
} else {
|
||||
await this.ctx.service.systems.operationLog.createOperationLogs(logPayloads);
|
||||
}
|
||||
});
|
||||
} catch (logErr) {
|
||||
this.ctx.logger.warn('[PendingOrderService.updateOrderExpress] 写入操作日志失败,不影响业务', logErr);
|
||||
}
|
||||
|
||||
return this.success('ok', {
|
||||
updated_count: count,
|
||||
skipped_order_ids: skippedOrderIds,
|
||||
sys_logistics_code: sysLogisticsCode,
|
||||
sys_logistics_name: sysLogisticsName,
|
||||
logistics_code: logisticsCode,
|
||||
@ -3532,8 +3413,6 @@ class PendingOrderService extends OrderBaseService {
|
||||
outbound_status: 'none',
|
||||
lock_status: 'none',
|
||||
intercept_status: 'none',
|
||||
// 克隆重置拦截字段:通知拦截时间必须清空,避免新单继承原单发起拦截时刻
|
||||
intercept_time: null,
|
||||
sync_status: 'padding',
|
||||
order_flag: '',
|
||||
wave_id: 0,
|
||||
@ -3564,7 +3443,7 @@ class PendingOrderService extends OrderBaseService {
|
||||
'delivery_type', 'weight_type', 'is_urgency', 'invoice_flag',
|
||||
'name', 'zip_code', 'tel', 'mobile', 'email',
|
||||
'country_code', 'province', 'city', 'area', 'town', 'detail_address',
|
||||
'id_type', 'id_number', 'oaid', 'extend_props',
|
||||
'id_type', 'id_number', 'oaid',
|
||||
'items', 'items_count', 'items_total', 'items_weight', 'items_hash', 'items_crc',
|
||||
];
|
||||
|
||||
@ -4638,8 +4517,8 @@ ${numbered}`;
|
||||
/**
|
||||
* 执行批量拦截后台任务。
|
||||
*
|
||||
* 直接对给定订单ID数组,将 intercept_status 更新为 'requested' 并同步写入拦截时间 intercept_time,
|
||||
* 同时写入操作日志。仅处理当前仓库上下文内的订单。
|
||||
* 直接对给定订单ID数组,将 intercept_status 更新为 'requested',并写入操作日志。
|
||||
* 仅处理当前仓库上下文内的订单。
|
||||
*
|
||||
* @param {Object} params 任务参数。
|
||||
* @param {string} params.taskId 任务ID。
|
||||
@ -4717,7 +4596,7 @@ ${numbered}`;
|
||||
}
|
||||
|
||||
const orderRows = await orderModel.findAll({
|
||||
attributes: [ 'id', 'delivery_order_code', 'pre_delivery_order_code', 'wave_id', 'inspection_status', 'intercept_time' ],
|
||||
attributes: [ 'id', 'delivery_order_code', 'pre_delivery_order_code', 'wave_id', 'inspection_status' ],
|
||||
where: {
|
||||
warehouse_id: warehouseId,
|
||||
id: {
|
||||
@ -4807,30 +4686,18 @@ ${numbered}`;
|
||||
}
|
||||
|
||||
const now = new Date();
|
||||
// 通知拦截时间只在首次发起时写入(重复发起不覆盖已有值)
|
||||
const fillNoticeOrderIds = pickNoticeTimeOrderIds(chunkRows);
|
||||
await orderModel.update(
|
||||
{ intercept_status: 'requested', updated_at: now },
|
||||
{
|
||||
where: {
|
||||
id: {
|
||||
[Op.in]: chunkOrderIds,
|
||||
},
|
||||
const updateValues = {
|
||||
intercept_status: 'requested',
|
||||
updated_at: now,
|
||||
};
|
||||
|
||||
await orderModel.update(updateValues, {
|
||||
where: {
|
||||
id: {
|
||||
[Op.in]: chunkOrderIds,
|
||||
},
|
||||
}
|
||||
);
|
||||
if (fillNoticeOrderIds.length > 0) {
|
||||
await orderModel.update(
|
||||
{ intercept_time: now },
|
||||
{
|
||||
where: {
|
||||
id: {
|
||||
[Op.in]: fillNoticeOrderIds,
|
||||
},
|
||||
},
|
||||
}
|
||||
);
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
// 同步更新运单表拦截标记
|
||||
try {
|
||||
@ -6236,8 +6103,7 @@ ${numbered}`;
|
||||
/**
|
||||
* 执行批量解除拦截后台任务。
|
||||
*
|
||||
* 直接对给定订单ID数组,将 intercept_status 更新为 'none' 并同步清空拦截时间 intercept_time(置为 null),
|
||||
* 同时写入操作日志 ORDER_INTERCEPT_CANCEL。
|
||||
* 直接对给定订单ID数组,将 intercept_status 更新为 'none',并写入操作日志 ORDER_INTERCEPT_CANCEL。
|
||||
* 同时释放订单对应的拦截锁定库存(intercept_locked_quantity 回落到可用数量,失败不阻断主流程)。
|
||||
* 仅处理当前仓库上下文内的订单。
|
||||
*
|
||||
@ -6383,7 +6249,6 @@ ${numbered}`;
|
||||
const now = new Date();
|
||||
const updateValues = {
|
||||
intercept_status: 'none',
|
||||
intercept_time: null,
|
||||
updated_at: now,
|
||||
};
|
||||
|
||||
|
||||
@ -2,6 +2,14 @@
|
||||
|
||||
const OrderBaseService = require('./base');
|
||||
|
||||
/**
|
||||
* 允许确认拦截(更新为 intercepted_at_warehouse)的前置拦截状态:
|
||||
* 拦截发起中(requested/requesting/intercepting)与历史遗留值 intercepted。
|
||||
* 其余状态(none/空、intercepted_at_warehouse、intercepted_in_transit、returning、returned、
|
||||
* delivered_by_mistake、timeout、cancelled、failed、exception)一律不允许确认拦截。
|
||||
*/
|
||||
const CONFIRMABLE_INTERCEPT_STATUSES = [ 'requested', 'requesting', 'intercepting', 'intercepted' ];
|
||||
|
||||
class RecheckOrderService extends OrderBaseService {
|
||||
/**
|
||||
* 初始化复核订单系统方法免登录、免权限、免日志与免鉴权配置。
|
||||
@ -30,8 +38,6 @@ class RecheckOrderService extends OrderBaseService {
|
||||
* - 运单号命中但订单无波次信息时,退回单订单详情模式(list 每项含 detail/items/expresses/logs、
|
||||
* items_weight、suggested_package_material)
|
||||
* - 所有模式的 list[] 每项均附带 items_weight(订单商品总重量)与 suggested_package_material(推荐包材信息,无推荐时为 null)
|
||||
* - 任一模式首次成功加载波次复核视图时,回写该波次的复核开始时间(recheck_start_time),
|
||||
* 仅首次写入(按 IS NULL 条件更新),回写失败仅告警、不影响扫描主流程
|
||||
* @param {Object} data 请求体。
|
||||
* @param {string} [data.keyword] 通用扫描关键词。
|
||||
* @param {string} [data.value] 通用扫描关键词别名。
|
||||
@ -77,10 +83,6 @@ class RecheckOrderService extends OrderBaseService {
|
||||
this.buildGroupWaveList(groupTaskId, warehouseId),
|
||||
this.getPickerInfoByTaskId(groupTaskId, warehouseId),
|
||||
]);
|
||||
await this.markWaveRecheckStart(
|
||||
groupWaveList.map(item => Number(item.wave_id || 0)),
|
||||
warehouseId
|
||||
);
|
||||
return {
|
||||
match_type: matchType,
|
||||
list_type: 'group',
|
||||
@ -119,7 +121,6 @@ class RecheckOrderService extends OrderBaseService {
|
||||
|
||||
const scanView = await this.buildSingleWaveScanView(orderWaveId, orderWaveNo, warehouseId);
|
||||
if (scanView) {
|
||||
await this.markWaveRecheckStart([ orderWaveId ], warehouseId);
|
||||
return {
|
||||
match_type: matchType,
|
||||
list_type: 'single',
|
||||
@ -175,10 +176,6 @@ class RecheckOrderService extends OrderBaseService {
|
||||
this.buildGroupWaveList(groupTaskId, warehouseId),
|
||||
this.getPickerInfoByTaskId(groupTaskId, warehouseId),
|
||||
]);
|
||||
await this.markWaveRecheckStart(
|
||||
groupWaveList.map(item => Number(item.wave_id || 0)),
|
||||
warehouseId
|
||||
);
|
||||
return {
|
||||
match_type: matchType,
|
||||
list_type: 'group',
|
||||
@ -193,7 +190,6 @@ class RecheckOrderService extends OrderBaseService {
|
||||
|
||||
const scanView = await this.buildSingleWaveScanView(waveId, waveNo, warehouseId);
|
||||
if (scanView) {
|
||||
await this.markWaveRecheckStart([ waveId ], warehouseId);
|
||||
return {
|
||||
match_type: matchType,
|
||||
list_type: 'single',
|
||||
@ -224,10 +220,6 @@ class RecheckOrderService extends OrderBaseService {
|
||||
this.buildGroupWaveList(taskId, warehouseId),
|
||||
this.getPickerInfoByTaskId(taskId, warehouseId),
|
||||
]);
|
||||
await this.markWaveRecheckStart(
|
||||
groupWaveList.map(item => Number(item.wave_id || 0)),
|
||||
warehouseId
|
||||
);
|
||||
return {
|
||||
match_type: 'cart',
|
||||
list_type: 'group',
|
||||
@ -255,7 +247,6 @@ class RecheckOrderService extends OrderBaseService {
|
||||
|
||||
const taskWaves = Array.isArray(taskWaveRows) ? taskWaveRows : [];
|
||||
const scanViews = [];
|
||||
const scannedWaveIds = [];
|
||||
|
||||
for (const tw of taskWaves) {
|
||||
const waveId = Number(tw.wave_id || 0);
|
||||
@ -266,14 +257,10 @@ class RecheckOrderService extends OrderBaseService {
|
||||
|
||||
if (scanView) {
|
||||
scanViews.push(scanView);
|
||||
scannedWaveIds.push(waveId);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 扫描视图构建成功后回写波次复核开始时间(仅首次写入,失败不影响主流程)
|
||||
await this.markWaveRecheckStart(scannedWaveIds, warehouseId);
|
||||
|
||||
if (scanViews.length === 0) {
|
||||
return {
|
||||
match_type: 'cart',
|
||||
@ -345,49 +332,6 @@ class RecheckOrderService extends OrderBaseService {
|
||||
throw new Error('未找到对应订单');
|
||||
}
|
||||
|
||||
/**
|
||||
* 回写波次复核开始时间(仅首次扫描写入)。
|
||||
* 对每个有效波次执行条件更新:仅当 recheck_start_time 为空时写入 NOW(),并同步刷新 update_time,
|
||||
* 与拣货任务开始时间补写惯例(app/service/systems/pick.js)保持一致;
|
||||
* 多波次场景每个波次各自按 IS NULL 条件判断,已写过复核开始时间的波次不会被覆盖。
|
||||
* 回写失败仅记录告警日志,不阻断扫描主流程(如迁移未执行导致字段缺失等场景)。
|
||||
* @param {number|Array<number>} waveIds 波次ID或波次ID数组。
|
||||
* @param {number} warehouseId 仓库ID。
|
||||
* @return {Promise<void>} 无返回值。
|
||||
*/
|
||||
async markWaveRecheckStart(waveIds, warehouseId) {
|
||||
const { ctx } = this;
|
||||
const normalizedWarehouseId = Number(warehouseId || 0);
|
||||
const sourceWaveIds = Array.isArray(waveIds) ? waveIds : [ waveIds ];
|
||||
const normalizedWaveIds = [ ...new Set(sourceWaveIds
|
||||
.map(id => Number(id || 0))
|
||||
.filter(id => Number.isInteger(id) && id > 0)) ];
|
||||
|
||||
if (normalizedWarehouseId <= 0 || normalizedWaveIds.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
await ctx.model.query(
|
||||
`
|
||||
UPDATE wms_wave_batch
|
||||
SET recheck_start_time = NOW(),
|
||||
update_time = NOW()
|
||||
WHERE wave_id IN (:waveIds)
|
||||
AND warehouse_id = :warehouseId
|
||||
AND recheck_start_time IS NULL
|
||||
`,
|
||||
{
|
||||
replacements: { waveIds: normalizedWaveIds, warehouseId: normalizedWarehouseId },
|
||||
}
|
||||
);
|
||||
} catch (error) {
|
||||
ctx.logger.warn(
|
||||
`[recheckOrder.markWaveRecheckStart] 回写波次复核开始时间失败,不影响扫描主流程, waveIds=${normalizedWaveIds.join(',')}, error=${error.message}`
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 通过拣货任务ID刷新复核扫描视图。
|
||||
* 根据任务的 pick_mode 区分散单/团单模式,返回与 scanOrder 一致的数据结构,用于前端刷新数据。
|
||||
@ -1690,7 +1634,7 @@ class RecheckOrderService extends OrderBaseService {
|
||||
|
||||
this.assertOrderCanRecheck(order);
|
||||
|
||||
const expresses = await this.getOrderExpressesByOrderId(orderId, order);
|
||||
const expresses = await this.getOrderExpressesByOrderId(orderId);
|
||||
const waybillNo = String(expresses?.[0]?.waybill_code || '').trim();
|
||||
|
||||
const now = new Date();
|
||||
@ -2206,7 +2150,6 @@ class RecheckOrderService extends OrderBaseService {
|
||||
|
||||
/**
|
||||
* 更新波次拣货任务订单的复核状态,若任务下所有订单均已复核完成则自动解绑车任务。
|
||||
* 复核状态更新后,会先清理波次内「已拦截且未打印」的订单(回池),避免其卡住任务完成判定。
|
||||
* @param {number} orderId 订单ID。
|
||||
* @param {number} warehouseId 仓库ID。
|
||||
* @param {{ id: string|null, name: string }} operator 操作人信息。
|
||||
@ -2251,26 +2194,6 @@ class RecheckOrderService extends OrderBaseService {
|
||||
}
|
||||
);
|
||||
|
||||
// 复核时同步清理波次内「已拦截且未打印」的订单(回池),避免拦截订单卡住任务/波次完成判定
|
||||
try {
|
||||
const currentOrderModel = await this.getOrderModelByTableType('current', warehouseId);
|
||||
const currentOrder = await currentOrderModel.findOne({
|
||||
where: { id: orderId, warehouse_id: warehouseId },
|
||||
attributes: [ 'id', 'wave_id' ],
|
||||
raw: true,
|
||||
});
|
||||
const currentWaveId = Number(currentOrder && currentOrder.wave_id || 0);
|
||||
if (currentWaveId > 0) {
|
||||
await this.removeUnprintedInterceptedOrdersFromWave({
|
||||
waveId: currentWaveId,
|
||||
warehouseId,
|
||||
operator,
|
||||
});
|
||||
}
|
||||
} catch (removeErr) {
|
||||
ctx.logger.warn(`[confirmRecheck] 清理波次未打印拦截订单失败,不影响复核主流程, orderId=${orderId}, error=${removeErr.message}`);
|
||||
}
|
||||
|
||||
// 查询当前订单所属的波次拣货任务ID
|
||||
const taskRows = await ctx.model.query(
|
||||
`SELECT DISTINCT task_id
|
||||
@ -2475,8 +2398,6 @@ class RecheckOrderService extends OrderBaseService {
|
||||
* 批量更新波次拣货任务订单的复核状态,并按任务维度检查是否需要解绑车任务。
|
||||
* 与单订单版本不同,本方法一次性更新所有相关任务订单的 review_status,
|
||||
* 再按去重后的 task_id 逐任务判断是否所有订单均已复核完成。
|
||||
* 复核状态更新后,会先清理受影响波次内「已拦截且未打印」的订单(回池),
|
||||
* 避免其卡住任务完成判定。
|
||||
* @param {number[]} orderIds 订单ID列表。
|
||||
* @param {number} warehouseId 仓库ID。
|
||||
* @param {{ id: string|null, name: string }} operator 操作人信息。
|
||||
@ -2520,31 +2441,6 @@ class RecheckOrderService extends OrderBaseService {
|
||||
}
|
||||
);
|
||||
|
||||
// 复核时同步清理受影响波次内「已拦截且未打印」的订单(回池),避免拦截订单卡住任务完成判定
|
||||
try {
|
||||
const cleanupOrderModel = await this.getOrderModelByTableType('current', warehouseId);
|
||||
const cleanupWaveRows = await cleanupOrderModel.findAll({
|
||||
where: {
|
||||
id: { [this.app.Sequelize.Op.in]: orderIds },
|
||||
warehouse_id: warehouseId,
|
||||
},
|
||||
attributes: [ 'wave_id' ],
|
||||
raw: true,
|
||||
});
|
||||
const cleanupWaveIds = [ ...new Set((Array.isArray(cleanupWaveRows) ? cleanupWaveRows : [])
|
||||
.map(r => Number(r && r.wave_id || 0))
|
||||
.filter(id => Number.isInteger(id) && id > 0)) ];
|
||||
for (const cleanupWaveId of cleanupWaveIds) {
|
||||
await this.removeUnprintedInterceptedOrdersFromWave({
|
||||
waveId: cleanupWaveId,
|
||||
warehouseId,
|
||||
operator,
|
||||
});
|
||||
}
|
||||
} catch (removeErr) {
|
||||
ctx.logger.warn(`[confirmRecheck] 批量复核-清理波次未打印拦截订单失败,不影响主流程, error=${removeErr.message}`);
|
||||
}
|
||||
|
||||
// 查询受影响的去重 task_id
|
||||
const taskRows = await ctx.model.query(
|
||||
`SELECT DISTINCT task_id
|
||||
@ -3452,9 +3348,8 @@ class RecheckOrderService extends OrderBaseService {
|
||||
o.delivery_order_code LIKE :keyword
|
||||
OR o.pre_delivery_order_code LIKE :keyword
|
||||
OR EXISTS (
|
||||
SELECT 1 FROM wms_order_express oe
|
||||
SELECT 1 FROM order_express oe
|
||||
WHERE oe.order_id = o.id
|
||||
AND oe.warehouse_id = o.warehouse_id
|
||||
AND oe.waybill_code LIKE :keyword
|
||||
AND oe.delete_at IS NULL
|
||||
)
|
||||
@ -3594,7 +3489,7 @@ class RecheckOrderService extends OrderBaseService {
|
||||
o.create_at,
|
||||
o.recheck_time,
|
||||
wi.wave_index,
|
||||
(SELECT oe.waybill_code FROM wms_order_express oe WHERE oe.order_id = o.id AND oe.warehouse_id = o.warehouse_id AND oe.delete_at IS NULL LIMIT 1) AS waybill_code
|
||||
(SELECT oe.waybill_code FROM order_express oe WHERE oe.order_id = o.id AND oe.delete_at IS NULL LIMIT 1) AS waybill_code
|
||||
FROM ${orderTableName} o${waveIndexJoin}
|
||||
${whereClause}
|
||||
ORDER BY o.id ASC
|
||||
@ -3855,18 +3750,13 @@ class RecheckOrderService extends OrderBaseService {
|
||||
* 仅拦截当前指定订单(不波及波次内其他订单),支持部分失败:未找到的订单与处理失败的
|
||||
* 订单记录在 failed 列表并返回失败原因,其余订单继续处理。
|
||||
*
|
||||
* 本方法为 method 出口包装层:解析仓库上下文与订单ID后,复用 systems 层
|
||||
* interceptAutoConfirm.confirmInterceptForOrderIds 完成实际拦截确认动作,
|
||||
* 与定时任务「自动库内拦截确定」共用同一内部实现,保证两条链路行为一致。
|
||||
*
|
||||
* 前置条件:订单必须处于拦截发起中状态(requested/requesting/intercepting,历史值 intercepted 兼容)。
|
||||
* 未发起拦截(none/空)的订单直接静默跳过不参与处理;已确认拦截(intercepted_at_warehouse)及其它
|
||||
* 非可确认状态(intercepted_in_transit/returning/returned/delivered_by_mistake/timeout/cancelled/failed/
|
||||
* exception)的订单一律跳过并记录失败原因;更新 SQL 的 where 同时限定拦截状态,防止并发修改导致误更新。
|
||||
*
|
||||
* 每个订单的拦截处理:
|
||||
* 1. 更新 wms_order_delivery:intercept_status = intercepted_at_warehouse、step=4、outbound_status=fin,
|
||||
* 并同步写入拦截时间 intercept_time(当前时间)
|
||||
* 1. 更新 wms_order_delivery:intercept_status = intercepted_at_warehouse、step=4、outbound_status=fin
|
||||
* 2. 同步更新运单表:is_intercept='Y'、is_back='Y'(库内拦截确认,货物在库内需退回)
|
||||
* 3. 释放储位分配(cancelAllocateStorage 拦截模式:库存不归还可用,移入拦截锁定字段 intercept_locked_quantity)
|
||||
* 4. 释放订单锁(lock_status='none')
|
||||
@ -3879,6 +3769,7 @@ class RecheckOrderService extends OrderBaseService {
|
||||
* @return {Promise<Object>} 批量拦截结果,包含 success/failed 列表与 success_count/failed_count 计数。
|
||||
*/
|
||||
async confirmIntercept(data = {}) {
|
||||
const { ctx } = this;
|
||||
const warehouseId = this.getWarehouseId();
|
||||
const orderIds = this.normalizeOrderIds(data);
|
||||
|
||||
@ -3886,13 +3777,183 @@ class RecheckOrderService extends OrderBaseService {
|
||||
this.ctx.throw(400, '订单ID列表不能为空');
|
||||
}
|
||||
|
||||
// method 出口仅做入参解构与包装,拦截确认动作统一由 systems 层内部方法执行
|
||||
const operator = this.getOrderLogOperator();
|
||||
return await this.ctx.service.systems.interceptAutoConfirm.confirmInterceptForOrderIds({
|
||||
orderIds,
|
||||
warehouseId,
|
||||
operator,
|
||||
const orderModel = await this.getOrderModelByTableType('current', warehouseId);
|
||||
const orderRows = await orderModel.findAll({
|
||||
where: this.buildOrderWhere(orderIds, warehouseId),
|
||||
attributes: [ 'id', 'delivery_order_code', 'pre_delivery_order_code', 'intercept_status', 'wave_no' ],
|
||||
raw: true,
|
||||
});
|
||||
|
||||
const orderMap = new Map();
|
||||
for (const row of orderRows) {
|
||||
orderMap.set(Number(row.id), row);
|
||||
}
|
||||
|
||||
const successOrders = [];
|
||||
const failedOrders = [];
|
||||
const successOrderIds = [];
|
||||
|
||||
for (const orderId of orderIds) {
|
||||
const order = orderMap.get(orderId);
|
||||
|
||||
if (!order) {
|
||||
failedOrders.push({ order_id: orderId, reason: '未找到对应订单' });
|
||||
continue;
|
||||
}
|
||||
|
||||
const orderWhere = this.buildOrderWhere([ orderId ], warehouseId);
|
||||
const orderNo = String(order.delivery_order_code || order.pre_delivery_order_code || '').trim();
|
||||
const interceptStatus = String(order.intercept_status || '').trim();
|
||||
|
||||
// 未发起拦截(none/空)的订单直接跳过,不参与确认拦截处理
|
||||
if (interceptStatus === '' || interceptStatus === 'none') {
|
||||
continue;
|
||||
}
|
||||
|
||||
// 已确认拦截的订单跳过,避免重复执行副作用(释放储位/工单/日志等)
|
||||
if (interceptStatus === 'intercepted_at_warehouse') {
|
||||
failedOrders.push({
|
||||
order_id: orderId,
|
||||
delivery_order_code: orderNo,
|
||||
reason: '订单已确认拦截',
|
||||
});
|
||||
continue;
|
||||
}
|
||||
|
||||
// 仅拦截发起中(requested/requesting/intercepting)与历史值 intercepted 允许确认,
|
||||
// 其余状态(intercepted_in_transit/returning/returned/delivered_by_mistake/timeout/
|
||||
// cancelled/failed/exception)不允许确认拦截
|
||||
if (!CONFIRMABLE_INTERCEPT_STATUSES.includes(interceptStatus)) {
|
||||
failedOrders.push({
|
||||
order_id: orderId,
|
||||
delivery_order_code: orderNo,
|
||||
reason: `订单拦截状态不允许确认拦截: ${interceptStatus}`,
|
||||
});
|
||||
continue;
|
||||
}
|
||||
|
||||
try {
|
||||
const now = new Date();
|
||||
const updateValues = {
|
||||
intercept_status: 'intercepted_at_warehouse',
|
||||
step: 4,
|
||||
outbound_status: 'fin',
|
||||
updated_at: now,
|
||||
};
|
||||
const updateResult = await orderModel.update(updateValues, {
|
||||
where: {
|
||||
...orderWhere,
|
||||
// 数据库层再次限定拦截状态,防止查询后状态被并发修改导致误更新
|
||||
intercept_status: { [ctx.app.Sequelize.Op.in]: CONFIRMABLE_INTERCEPT_STATUSES },
|
||||
},
|
||||
});
|
||||
const affectedRows = Array.isArray(updateResult) ? Number(updateResult[0] || 0) : Number(updateResult || 0);
|
||||
|
||||
if (affectedRows <= 0) {
|
||||
throw new Error('拦截状态更新失败,请稍后重试');
|
||||
}
|
||||
|
||||
// 同步更新运单表:标记拦截 + 退回(库内拦截确认,货物在库内需退回)
|
||||
try {
|
||||
await ctx.model.OrderExpress.update(
|
||||
{ is_intercept: 'Y', is_back: 'Y' },
|
||||
{ where: { order_id: orderId, warehouse_id: warehouseId } }
|
||||
);
|
||||
} catch (expressErr) {
|
||||
ctx.logger.warn(
|
||||
`[recheckOrder.confirmIntercept] 更新运单拦截/退回标记失败, orderId=${orderId}, error=${expressErr.message}`
|
||||
);
|
||||
}
|
||||
|
||||
// 拦截成功后释放储位分配(拦截模式:库存移入拦截锁定,不归还可用)
|
||||
try {
|
||||
await this.service.systems.orderStorageAllocation.cancelAllocateStorage({
|
||||
order_ids: [ orderId ],
|
||||
interceptMode: true,
|
||||
});
|
||||
} catch (allocErr) {
|
||||
ctx.logger.warn(
|
||||
`[recheckOrder.confirmIntercept] 释放储位分配失败,不影响拦截, orderId=${orderId}, error=${allocErr.message}`
|
||||
);
|
||||
}
|
||||
|
||||
// 拦截成功后释放订单锁
|
||||
try {
|
||||
await orderModel.update(
|
||||
{ lock_status: 'none', updated_at: now },
|
||||
{ where: orderWhere }
|
||||
);
|
||||
} catch (lockErr) {
|
||||
ctx.logger.warn(
|
||||
`[recheckOrder.confirmIntercept] 释放锁失败,不影响拦截, orderId=${orderId}, error=${lockErr.message}`
|
||||
);
|
||||
}
|
||||
|
||||
// 写入操作日志(失败不影响主流程)
|
||||
try {
|
||||
const operator = this.getOrderLogOperator();
|
||||
const logWarehouseId = this.getOrderLogWarehouseId(warehouseId);
|
||||
await ctx.service.systems.operationLog.createOperationLog({
|
||||
businessType: 'order',
|
||||
businessId: orderId,
|
||||
operationCode: 'ORDER_INTERCEPT_CONFIRM',
|
||||
operator,
|
||||
extras: {
|
||||
warehouseId: logWarehouseId,
|
||||
orderId,
|
||||
orderNo,
|
||||
previousInterceptStatus: String(order.intercept_status || '').trim(),
|
||||
newInterceptStatus: 'intercepted_at_warehouse',
|
||||
},
|
||||
beforeChanges: null,
|
||||
});
|
||||
} catch (logErr) {
|
||||
ctx.logger.warn(
|
||||
`[recheckOrder.confirmIntercept] 写入操作日志失败,不影响业务, orderId=${orderId}, error=${logErr.message}`
|
||||
);
|
||||
}
|
||||
|
||||
successOrders.push({
|
||||
order_id: orderId,
|
||||
order_no: orderNo,
|
||||
intercept_status: 'intercepted_at_warehouse',
|
||||
updated_at: now,
|
||||
});
|
||||
successOrderIds.push(orderId);
|
||||
} catch (error) {
|
||||
ctx.logger.warn(
|
||||
`[recheckOrder.confirmIntercept] 确认拦截失败, orderId=${orderId}, error=${error.message}`
|
||||
);
|
||||
failedOrders.push({
|
||||
order_id: orderId,
|
||||
delivery_order_code: orderNo,
|
||||
reason: `确认拦截失败: ${error.message}`,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// 创建售后工单 + 通知快递群(成功订单 ID 汇总统一调用,失败不影响主流程)
|
||||
if (successOrderIds.length > 0) {
|
||||
try {
|
||||
const operator = this.getOrderLogOperator();
|
||||
await this.service.systems.afterSale.createInterceptWorkOrdersAndNotify({
|
||||
orderIds: successOrderIds,
|
||||
warehouseId,
|
||||
creatorLabel: operator.name || '系统',
|
||||
});
|
||||
} catch (workOrderErr) {
|
||||
ctx.logger.warn(
|
||||
`[recheckOrder.confirmIntercept] 创建工单/通知失败, orderIds=${successOrderIds.join(',')}, error=${workOrderErr.message}`
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
success: successOrders,
|
||||
failed: failedOrders,
|
||||
success_count: successOrders.length,
|
||||
failed_count: failedOrders.length,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
@ -3904,9 +3965,7 @@ class RecheckOrderService extends OrderBaseService {
|
||||
* 2. 校验通过后将运单 is_back、is_intercept 设为 'Y'
|
||||
* 3. 检查是否存在关联的未完结售后工单(wms_after_sale),若有则调用 handleWorkOrder 写入
|
||||
* "库内拦截成功"步骤并将工单置为 completed
|
||||
* 4. 同步更新 wms_order_delivery 的 intercept_status 为 intercepted_at_warehouse(**不写 intercept_time**:
|
||||
* 该字段恒为「最近一次发起拦截的通知时刻」,库内确定拦截不覆盖,见 app/lib/intercept_time.js;
|
||||
* 库内确定拦截时刻以配送表 dispath_time 为准),
|
||||
* 4. 同步更新 wms_order_delivery 的 intercept_status 为 intercepted_at_warehouse,
|
||||
* 并释放储位分配(拦截模式:库存移入拦截锁定,不归还可用)与订单锁(仅订单级状态更新,不标记订单下其他面单)
|
||||
*
|
||||
* 注:库内拦截确认需标记退回 is_back='Y';发起拦截链路仅写 is_intercept,不写 is_back。
|
||||
@ -4020,7 +4079,6 @@ class RecheckOrderService extends OrderBaseService {
|
||||
});
|
||||
|
||||
if (order) {
|
||||
// 库内确定拦截不写 intercept_time(不覆盖通知拦截时刻),库内确定时刻以配送表 dispath_time 为准
|
||||
await orderModel.update(
|
||||
{
|
||||
intercept_status: 'intercepted_at_warehouse',
|
||||
@ -4975,170 +5033,8 @@ class RecheckOrderService extends OrderBaseService {
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 将波次内「已拦截且未打印」的订单移除出波次(回池)。
|
||||
*
|
||||
* 背景:拦截订单无法打印、无法复核,会卡住波次复核完成判定与波次终结;
|
||||
* 解除拦截后因 wave_id 仍大于 0 而无法被波次策略重新抓取,导致无法继续发货。
|
||||
* 复核链路在更新复核状态后调用本方法,把未打印的拦截订单从波次中释放回候选池,
|
||||
* 拦截解除后即可重新抓取发货;已打印(print_status != 'none')的拦截订单保持不动,
|
||||
* 避免已贴面单实物与波次记录分离。
|
||||
*
|
||||
* @param {Object} params 移除参数。
|
||||
* @param {number} params.waveId 波次ID。
|
||||
* @param {number} params.warehouseId 仓库ID。
|
||||
* @param {{ id: string|null, name: string }} params.operator 操作人信息。
|
||||
* @param {Object} [params.transaction] Sequelize 事务对象(事务内调用时传入)。
|
||||
* @return {Promise<{removed_order_ids: number[], removed_count: number}>} 移除结果。
|
||||
*/
|
||||
async removeUnprintedInterceptedOrdersFromWave({ waveId, warehouseId, operator, transaction = null } = {}) {
|
||||
const { ctx } = this;
|
||||
const normalizedWaveId = Number(waveId || 0);
|
||||
const normalizedWarehouseId = Number(warehouseId || 0);
|
||||
if (!Number.isInteger(normalizedWaveId) || normalizedWaveId <= 0
|
||||
|| !Number.isInteger(normalizedWarehouseId) || normalizedWarehouseId <= 0) {
|
||||
return { removed_order_ids: [], removed_count: 0 };
|
||||
}
|
||||
|
||||
// 查询波次内「已拦截且未打印」的订单(intercept_status 空值按 none 处理,Op.ne 对 NULL 不命中)
|
||||
const orderModel = await this.getOrderModelByTableType('current', normalizedWarehouseId);
|
||||
const removableRows = await orderModel.findAll({
|
||||
where: {
|
||||
warehouse_id: normalizedWarehouseId,
|
||||
wave_id: normalizedWaveId,
|
||||
print_status: 'none',
|
||||
intercept_status: { [this.app.Sequelize.Op.ne]: 'none' },
|
||||
},
|
||||
attributes: [ 'id', 'wave_id', 'wave_no' ],
|
||||
raw: true,
|
||||
transaction,
|
||||
});
|
||||
const normalizedRemovableRows = Array.isArray(removableRows) ? removableRows : [];
|
||||
const removedOrderIds = [ ...new Set(normalizedRemovableRows
|
||||
.map(row => Number(row && row.id || 0))
|
||||
.filter(id => Number.isInteger(id) && id > 0)) ];
|
||||
if (removedOrderIds.length === 0) {
|
||||
return { removed_order_ids: [], removed_count: 0 };
|
||||
}
|
||||
|
||||
// 1. 订单 wave_id 清零(回池),清空波次编号与策略扫描标记
|
||||
await orderModel.update({
|
||||
wave_id: 0,
|
||||
wave_no: '',
|
||||
wave_strategy_version: 0,
|
||||
wave_scan_result: 0,
|
||||
}, {
|
||||
where: {
|
||||
warehouse_id: normalizedWarehouseId,
|
||||
id: { [this.app.Sequelize.Op.in]: removedOrderIds },
|
||||
},
|
||||
transaction,
|
||||
validate: false,
|
||||
hooks: false,
|
||||
});
|
||||
|
||||
// 2. 删除波次索引行(其余订单 wave_index 保持不变仅跳号,避免与已放货篮子编号错位)
|
||||
const waveService = ctx.service && ctx.service.systemMethods && ctx.service.systemMethods.order
|
||||
&& ctx.service.systemMethods.order.wave;
|
||||
if (waveService && typeof waveService.deleteOrderWaveIndexByOrderIds === 'function') {
|
||||
await waveService.deleteOrderWaveIndexByOrderIds({
|
||||
warehouseId: normalizedWarehouseId,
|
||||
orderIds: removedOrderIds,
|
||||
transaction,
|
||||
});
|
||||
}
|
||||
|
||||
// 3. 移除任务订单关联(散单模式),任务复核完成判定与进度统计不再包含拦截订单
|
||||
await ctx.model.query(
|
||||
`DELETE FROM wms_wave_pick_task_order
|
||||
WHERE warehouse_id = :warehouseId
|
||||
AND order_id IN (:orderIds)`,
|
||||
{
|
||||
replacements: {
|
||||
warehouseId: normalizedWarehouseId,
|
||||
orderIds: removedOrderIds,
|
||||
},
|
||||
transaction,
|
||||
}
|
||||
);
|
||||
|
||||
// 4. 回写波次统计:total_orders 扣除被移除订单数,processed_orders 收敛不超过剩余订单数
|
||||
const remainingRows = await orderModel.findAll({
|
||||
where: {
|
||||
warehouse_id: normalizedWarehouseId,
|
||||
wave_id: normalizedWaveId,
|
||||
},
|
||||
attributes: [ 'id' ],
|
||||
raw: true,
|
||||
transaction,
|
||||
});
|
||||
const remainingCount = Array.isArray(remainingRows) ? remainingRows.length : 0;
|
||||
await ctx.model.query(
|
||||
`UPDATE wms_wave_batch
|
||||
SET total_orders = :remainingCount,
|
||||
processed_orders = LEAST(processed_orders, :remainingCount),
|
||||
update_time = NOW()
|
||||
WHERE warehouse_id = :warehouseId
|
||||
AND wave_id = :waveId`,
|
||||
{
|
||||
replacements: {
|
||||
warehouseId: normalizedWarehouseId,
|
||||
waveId: normalizedWaveId,
|
||||
remainingCount,
|
||||
},
|
||||
type: ctx.model.QueryTypes.UPDATE,
|
||||
transaction,
|
||||
}
|
||||
);
|
||||
|
||||
// 5. 写订单操作日志 ORDER_WAVE_REMOVE(不影响主流程)
|
||||
try {
|
||||
const operationLogService = ctx.service && ctx.service.systems && ctx.service.systems.operationLog;
|
||||
if (operationLogService && typeof operationLogService.createOperationLogs === 'function') {
|
||||
const logPayloads = normalizedRemovableRows.map(row => ({
|
||||
businessType: 'order',
|
||||
businessId: `${row.id}`,
|
||||
operationCode: 'ORDER_WAVE_REMOVE',
|
||||
operator: {
|
||||
id: operator && operator.id ? String(operator.id) : null,
|
||||
name: operator && operator.name ? String(operator.name).trim() : 'system',
|
||||
},
|
||||
extras: {
|
||||
message: `订单从波次 ${String(row && row.wave_no || '').trim() || '未知波次'} 中移除`,
|
||||
warehouseId: normalizedWarehouseId,
|
||||
externalLogType: 'API',
|
||||
},
|
||||
}));
|
||||
await operationLogService.createOperationLogs(logPayloads);
|
||||
}
|
||||
} catch (logErr) {
|
||||
ctx.logger.warn(`[recheckOrder.removeUnprintedIntercepted] 写订单操作日志失败,不影响主流程, waveId=${normalizedWaveId}, error=${logErr.message}`);
|
||||
}
|
||||
|
||||
// 6. 触发波次策略快扫,让回池订单重新进入候选池(拦截未解除时策略仍会排除)
|
||||
try {
|
||||
if (waveService && typeof waveService.enqueueWaveStrategyQuickScanPostOrderChange === 'function') {
|
||||
waveService.enqueueWaveStrategyQuickScanPostOrderChange(
|
||||
normalizedWarehouseId,
|
||||
removedOrderIds,
|
||||
{ triggerScan: true, source: 'recheckRemoveUnprintedIntercepted' }
|
||||
);
|
||||
}
|
||||
} catch (scanErr) {
|
||||
ctx.logger.warn(`[recheckOrder.removeUnprintedIntercepted] 触发策略快扫失败,不影响主流程, waveId=${normalizedWaveId}, error=${scanErr.message}`);
|
||||
}
|
||||
|
||||
ctx.logger.info(
|
||||
`[recheckOrder.removeUnprintedIntercepted] 波次未打印拦截订单已移除回池, waveId=${normalizedWaveId}, removedCount=${removedOrderIds.length}, orderIds=${removedOrderIds.join(',')}`
|
||||
);
|
||||
|
||||
return { removed_order_ids: removedOrderIds, removed_count: removedOrderIds.length };
|
||||
}
|
||||
|
||||
/**
|
||||
* 在事务中更新波次拣货任务订单的复核状态,并判断是否需要解绑车任务。
|
||||
* 复核状态更新后,会先在事务内清理波次内「已拦截且未打印」的订单(回池),
|
||||
* 避免其卡住任务完成判定。
|
||||
*
|
||||
* @param {number} orderId 订单ID。
|
||||
* @param {number} warehouseId 仓库ID。
|
||||
@ -5185,28 +5081,6 @@ class RecheckOrderService extends OrderBaseService {
|
||||
}
|
||||
);
|
||||
|
||||
// 复核时在事务内清理波次内「已拦截且未打印」的订单(回池),避免拦截订单卡住任务完成判定
|
||||
try {
|
||||
const cleanupOrderModel = await this.getOrderModelByTableType('current', warehouseId);
|
||||
const cleanupOrder = await cleanupOrderModel.findOne({
|
||||
where: { id: orderId, warehouse_id: warehouseId },
|
||||
attributes: [ 'id', 'wave_id' ],
|
||||
raw: true,
|
||||
transaction,
|
||||
});
|
||||
const cleanupWaveId = Number(cleanupOrder && cleanupOrder.wave_id || 0);
|
||||
if (cleanupWaveId > 0) {
|
||||
await this.removeUnprintedInterceptedOrdersFromWave({
|
||||
waveId: cleanupWaveId,
|
||||
warehouseId,
|
||||
operator,
|
||||
transaction,
|
||||
});
|
||||
}
|
||||
} catch (removeErr) {
|
||||
ctx.logger.warn(`[batchQuickRecheck] 清理波次未打印拦截订单失败,不影响复核主流程, orderId=${orderId}, error=${removeErr.message}`);
|
||||
}
|
||||
|
||||
// 查询当前订单所属的波次拣货任务ID
|
||||
const taskRows = await ctx.model.query(
|
||||
`SELECT DISTINCT task_id
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@ -7,7 +7,6 @@ const {
|
||||
ExpressPrintPayloadBuilder,
|
||||
RequestScopedPrintIdGenerator,
|
||||
} = require('../../lib/express_print_payload_builder');
|
||||
const { INTERCEPT_STATUS_NONE } = require('../../lib/intercept_guard');
|
||||
|
||||
/**
|
||||
* 打印 Service
|
||||
@ -2881,40 +2880,21 @@ class PrintService extends MainService {
|
||||
}
|
||||
const orderDeliveryModel = await orderDeliveryFactory.getCurrentModel(resolvedWarehouseId);
|
||||
|
||||
// 查询任务主表:团购模式校验、任务结束状态兜底解绑均需要
|
||||
const taskRows = await ctx.model.query(
|
||||
'SELECT pick_mode, status FROM wms_wave_pick_task WHERE id = :taskId LIMIT 1',
|
||||
{ replacements: { taskId }, type: ctx.model.QueryTypes.SELECT }
|
||||
);
|
||||
const task = Array.isArray(taskRows) && taskRows.length > 0 ? taskRows[0] : null;
|
||||
if (!task) return;
|
||||
const pickMode = Number(task.pick_mode || 0);
|
||||
const taskStatus = Number(task.status || 0);
|
||||
|
||||
// 拦截订单不可打印(打印清单剔除 + 打印回执更新排除拦截订单),print_status 永远停留在 none。
|
||||
// 解绑判定的「未打印」统计必须排除拦截订单,与打印剔除、复核打印统计口径保持一致,
|
||||
// 避免波次内存在拦截订单时车永远无法解绑。
|
||||
const nonInterceptedWhere = { [ctx.model.Sequelize.Op.in]: [ INTERCEPT_STATUS_NONE, null ] };
|
||||
|
||||
const unbindCart = async reason => {
|
||||
const operator = this.getPrintOrderOperationOperator();
|
||||
const unbindUserId = operator.id || null;
|
||||
await ctx.model.query(
|
||||
'UPDATE wms_pick_task_cart_binding SET is_active = 0, unbind_user_id = :unbindUserId, unbind_time = NOW(), update_time = NOW() WHERE task_id = :taskId AND is_active = 1',
|
||||
{ replacements: { taskId, unbindUserId } }
|
||||
);
|
||||
this.ctx.logger.info('[print.unbindCart] 车标解绑成功', { waveId, warehouseId: resolvedWarehouseId, taskId, waveType, waveTypeLabel: waveType === 1 ? '团购' : '散单', reason, unbindUserId });
|
||||
};
|
||||
|
||||
let totalOrderCount = 0;
|
||||
let unprintedCount = 0;
|
||||
|
||||
if (waveType === 1) {
|
||||
// 团购波次:仅团购拣货模式(pick_mode=1 小团购 / pick_mode=5 大团购)参与解绑判断
|
||||
const taskRows = await ctx.model.query(
|
||||
'SELECT pick_mode FROM wms_wave_pick_task WHERE id = :taskId LIMIT 1',
|
||||
{ replacements: { taskId }, type: ctx.model.QueryTypes.SELECT }
|
||||
);
|
||||
const task = Array.isArray(taskRows) && taskRows.length > 0 ? taskRows[0] : null;
|
||||
const pickMode = task ? Number(task.pick_mode) : 0;
|
||||
if (![ 1, 5 ].includes(pickMode)) return;
|
||||
|
||||
// 团购任务订单不写入 wms_wave_pick_task_order,改为按任务关联的全部波次统计:
|
||||
// 任务下所有波次的非拦截订单均已打印时才解绑
|
||||
// 任务下所有波次的订单均已打印时才解绑
|
||||
const taskWaveIdRows = await ctx.model.query(
|
||||
'SELECT DISTINCT wave_id FROM wms_wave_pick_task_wave WHERE task_id = :taskId AND warehouse_id = :warehouseId',
|
||||
{ replacements: { taskId, warehouseId: resolvedWarehouseId }, type: ctx.model.QueryTypes.SELECT }
|
||||
@ -2922,51 +2902,32 @@ class PrintService extends MainService {
|
||||
const waveIds = (Array.isArray(taskWaveIdRows) ? taskWaveIdRows : [])
|
||||
.map(r => Number(r && r.wave_id))
|
||||
.filter(id => id > 0);
|
||||
if (waveIds.length === 0) {
|
||||
// 任务无波次关联:仅任务已结束(待复核/完成/取消)时兜底解绑,避免车残留
|
||||
if ([ 2, 3, 9 ].includes(taskStatus)) await unbindCart('task_no_wave_ended');
|
||||
return;
|
||||
}
|
||||
if (waveIds.length === 0) return;
|
||||
unprintedCount = await orderDeliveryModel.count({
|
||||
where: {
|
||||
warehouse_id: resolvedWarehouseId,
|
||||
wave_id: { [ctx.model.Sequelize.Op.in]: waveIds },
|
||||
print_status: 'none',
|
||||
intercept_status: nonInterceptedWhere,
|
||||
},
|
||||
});
|
||||
totalOrderCount = await orderDeliveryModel.count({
|
||||
where: {
|
||||
warehouse_id: resolvedWarehouseId,
|
||||
wave_id: { [ctx.model.Sequelize.Op.in]: waveIds },
|
||||
intercept_status: nonInterceptedWhere,
|
||||
},
|
||||
});
|
||||
} else {
|
||||
// 散单波次:按任务订单维度检查,任务下所有非拦截订单均已打印时才解绑
|
||||
// 散单波次:按任务订单维度检查,任务下所有订单均已打印时才解绑
|
||||
const taskOrders = await ctx.model.query(
|
||||
'SELECT DISTINCT order_id FROM wms_wave_pick_task_order WHERE task_id = :taskId',
|
||||
{ replacements: { taskId }, type: ctx.model.QueryTypes.SELECT }
|
||||
);
|
||||
const orderIds = (Array.isArray(taskOrders) ? taskOrders : []).map(r => Number(r && r.order_id)).filter(id => id > 0);
|
||||
if (orderIds.length === 0) {
|
||||
// 任务订单关联为空(如拦截订单被提交拣货移除):任务已结束时兜底解绑,避免车残留
|
||||
if ([ 2, 3, 9 ].includes(taskStatus)) await unbindCart('task_no_orders_ended');
|
||||
return;
|
||||
}
|
||||
if (orderIds.length === 0) return;
|
||||
unprintedCount = await orderDeliveryModel.count({
|
||||
where: {
|
||||
id: { [ctx.model.Sequelize.Op.in]: orderIds },
|
||||
print_status: 'none',
|
||||
intercept_status: nonInterceptedWhere,
|
||||
},
|
||||
});
|
||||
totalOrderCount = await orderDeliveryModel.count({
|
||||
where: {
|
||||
id: { [ctx.model.Sequelize.Op.in]: orderIds },
|
||||
intercept_status: nonInterceptedWhere,
|
||||
},
|
||||
where: { id: { [ctx.model.Sequelize.Op.in]: orderIds }, print_status: 'none' },
|
||||
});
|
||||
totalOrderCount = orderIds.length;
|
||||
}
|
||||
|
||||
if (unprintedCount > 0) {
|
||||
@ -2974,7 +2935,13 @@ class PrintService extends MainService {
|
||||
return;
|
||||
}
|
||||
|
||||
await unbindCart('all_printed');
|
||||
const operator = this.getPrintOrderOperationOperator();
|
||||
const unbindUserId = operator.id || null;
|
||||
await ctx.model.query(
|
||||
'UPDATE wms_pick_task_cart_binding SET is_active = 0, unbind_user_id = :unbindUserId, unbind_time = NOW(), update_time = NOW() WHERE task_id = :taskId AND is_active = 1',
|
||||
{ replacements: { taskId, unbindUserId } }
|
||||
);
|
||||
this.ctx.logger.info('[print.unbindCart] 车标解绑成功', { waveId, warehouseId: resolvedWarehouseId, taskId, waveType, waveTypeLabel: waveType === 1 ? '团购' : '散单', unbindUserId });
|
||||
} catch (error) {
|
||||
this.ctx.logger.error('[print.unbindCart] 解绑车标检查异常', { waveId, warehouseId: resolvedWarehouseId, taskId, waveType, error: error && error.message ? error.message : String(error) });
|
||||
}
|
||||
|
||||
@ -40,7 +40,7 @@ class ReportDefinitionMethodService extends MainService {
|
||||
* @param {number} [data.id] 报表定义ID(正整数;不传视为新增)
|
||||
* @param {string} data.name 报表名称(必填,≤100)
|
||||
* @param {string} data.type 报表类型(注册方法 key,如 stockFlow;新增必填)
|
||||
* @param {string} data.file_name 导出文件名模板(支持 {date}/{time}/{datetime}/{timestamp};新增必填,≤200,兼容 fileName)
|
||||
* @param {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)
|
||||
|
||||
@ -64,22 +64,6 @@ class ReturnUnpackMethodService extends MainService {
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 运单批量转入退件登记(退回拆包,批量)。
|
||||
* 新方法需鉴权 + 需登录 + 记录日志,不在任何免检清单内。
|
||||
*
|
||||
* @param {Object} data 请求体。
|
||||
* @param {number|Array<number>} data.ids 运单表主键ID(wms_order_express.id,单个数值或数组,去重后上限 200)。
|
||||
* @return {Promise<Object>} 统一 success 包装,data 含 total/success_count/failed_count/success/failed。
|
||||
*/
|
||||
async transferByWaybills(data = {}) {
|
||||
const { ids } = data;
|
||||
return this._call(
|
||||
() => this.service.systems.returnUnpack.transferByWaybills({ ids }),
|
||||
'运单批量转入退件登记失败'
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 录明细(增)。
|
||||
*
|
||||
|
||||
@ -6,9 +6,9 @@ class SettingWarehouseMethodsService extends MainService {
|
||||
constructor(ctx) {
|
||||
super(ctx);
|
||||
const _noNeedLogin = '';
|
||||
const _noNeedRight = 'getSettings,getFieldMeta,saveSettings,getFrontConfig,saveFrontConfig,saveFrontCert';
|
||||
const _noNeedRight = 'getSettings,getFieldMeta,saveSettings';
|
||||
const _noNeedLog = '*';
|
||||
const _noNeedAuth = 'getSettings,getFieldMeta,saveSettings,getFrontConfig,saveFrontConfig,saveFrontCert';
|
||||
const _noNeedAuth = 'getSettings,getFieldMeta,saveSettings';
|
||||
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
|
||||
}
|
||||
|
||||
@ -79,110 +79,6 @@ class SettingWarehouseMethodsService extends MainService {
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询当前仓库前端独立部署配置(settings 页回显)。
|
||||
*
|
||||
* 响应含证书原文(cert_pem)与私钥原文(key_pem)回显,
|
||||
* 仅限登录用户查询其仓库上下文绑定的配置,供仓库主体 settings 页回显;
|
||||
* 公共无鉴权接口 frontConfig.getByDomain 不经过本出口,仍只返回公开字段白名单。
|
||||
*
|
||||
* @return {Promise<Object>} 统一响应结果。
|
||||
*/
|
||||
async getFrontConfig() {
|
||||
const targetService = this.service && this.service.systems && this.service.systems.setting && this.service.systems.setting.warehouse;
|
||||
|
||||
if (!targetService || typeof targetService.getFrontConfig !== 'function') {
|
||||
return this.fail('获取仓库前端配置失败', { code: 500 });
|
||||
}
|
||||
|
||||
try {
|
||||
const result = await targetService.getFrontConfig();
|
||||
return this.success('ok', result);
|
||||
} catch (error) {
|
||||
return this.fail(error.message || '获取仓库前端配置失败', {
|
||||
code: Number(error.code) || 500,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 保存当前仓库前端独立部署品牌配置(upsert,一仓一行,仅品牌字段部分更新)。
|
||||
*
|
||||
* domain 与证书字段不再受理:domain 变更必须走 saveFrontCert 重新校验证书;
|
||||
* cert_pem/key_pem/cert_path/key_path/cert_expire_at 一律被白名单过滤忽略。
|
||||
*
|
||||
* @param {Object} data 请求参数。
|
||||
* @param {string} [data.title] 站点标题(≤100 字符,空值清空)。
|
||||
* @param {string} [data.logo_url] Logo 地址(≤255 字符,空值清空)。
|
||||
* @param {string} [data.favicon_url] 站点 favicon 图标地址(≤255 字符,空值清空)。
|
||||
* @param {string} [data.login_bg_url] 登录页背景图地址(≤255 字符,空值清空)。
|
||||
* @param {Object|string} [data.theme] 主题配置(合法 JSON 对象或 JSON 字符串,空值清空)。
|
||||
* @return {Promise<Object>} 统一响应结果。
|
||||
*/
|
||||
async saveFrontConfig(data = {}) {
|
||||
const targetService = this.service && this.service.systems && this.service.systems.setting && this.service.systems.setting.warehouse;
|
||||
|
||||
if (!targetService || typeof targetService.saveFrontConfig !== 'function') {
|
||||
return this.fail('保存仓库前端配置失败', { code: 500 });
|
||||
}
|
||||
|
||||
try {
|
||||
const source = data || {};
|
||||
const params = {};
|
||||
|
||||
// domain/cert_path/key_path/cert_pem/key_pem/cert_expire_at 均不受理:
|
||||
// domain 变更走 saveFrontCert,证书与有效期字段由后端权威维护,前端传值直接忽略
|
||||
for (const key of [ 'title', 'logo_url', 'favicon_url', 'login_bg_url', 'theme' ]) {
|
||||
if (Object.prototype.hasOwnProperty.call(source, key)) {
|
||||
params[key] = source[key];
|
||||
}
|
||||
}
|
||||
|
||||
const result = await targetService.saveFrontConfig(params);
|
||||
return this.success('ok', result);
|
||||
} catch (error) {
|
||||
return this.fail(error.message || '保存仓库前端配置失败', {
|
||||
code: Number(error.code) || 500,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 上传当前仓库前端独立部署证书(domain + 证书/私钥成对,需登录、仅仓库主体)。
|
||||
*
|
||||
* 后端自动写入 cert_expire_at(证书 validTo 权威值),证书/私钥内容直接入库(不落盘),
|
||||
* 保存后清理新旧 domain 的公共拉取缓存并返回完整配置输出
|
||||
* (响应含证书/私钥原文回显,口径与 getFrontConfig 一致)。
|
||||
*
|
||||
* @param {Object} data 请求参数。
|
||||
* @param {string} data.domain 仓库自持域名(必填,非空,≤100 字符,全局唯一)。
|
||||
* @param {string} data.pem 证书 PEM 文本(必填)。
|
||||
* @param {string} data.key 私钥 PEM 文本(必填,与证书成对)。
|
||||
* @return {Promise<Object>} 统一响应结果。
|
||||
*/
|
||||
async saveFrontCert(data = {}) {
|
||||
const targetService = this.service && this.service.systems && this.service.systems.setting && this.service.systems.setting.warehouse;
|
||||
|
||||
if (!targetService || typeof targetService.saveFrontCert !== 'function') {
|
||||
return this.fail('上传前端证书失败', { code: 500 });
|
||||
}
|
||||
|
||||
try {
|
||||
const source = data || {};
|
||||
const { domain, pem, key } = source;
|
||||
const result = await targetService.saveFrontCert({
|
||||
domain,
|
||||
pem,
|
||||
key,
|
||||
});
|
||||
return this.success('ok', result);
|
||||
} catch (error) {
|
||||
return this.fail(error.message || '上传前端证书失败', {
|
||||
code: Number(error.code) || 500,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = SettingWarehouseMethodsService;
|
||||
|
||||
@ -13,9 +13,9 @@ class InventoryMethodService extends MainService {
|
||||
constructor(ctx) {
|
||||
super(ctx);
|
||||
const _noNeedLogin = '';
|
||||
const _noNeedRight = 'list,export,exportTaskProgress,listByStockId,listBySpaceId';
|
||||
const _noNeedLog = 'list,export,exportTaskProgress,listByStockId,listBySpaceId';
|
||||
const _noNeedAuth = 'list,quickPutaway,directPutaway,export,exportTaskProgress,listByStockId,listBySpaceId';
|
||||
const _noNeedRight = 'list,export,exportTaskProgress,listByStockId';
|
||||
const _noNeedLog = 'list,export,exportTaskProgress,listByStockId';
|
||||
const _noNeedAuth = 'list,quickPutaway,directPutaway,export,exportTaskProgress,listByStockId';
|
||||
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
|
||||
}
|
||||
|
||||
@ -48,25 +48,6 @@ class InventoryMethodService extends MainService {
|
||||
return this.success('ok', result);
|
||||
}
|
||||
|
||||
/**
|
||||
* 维护库存效期:传入库存记录ID与生产日期/到期日期,更新当前库存批次的两个日期字段。
|
||||
*
|
||||
* 仓库上下文来自当前登录用户(ctx.user.store_id),跨仓库的 storage_id 按不存在处理。
|
||||
* production_date / expiry_date 至少传一个,未传字段保持库内原值,传 null 或空串表示清空;
|
||||
* 合并后生产日期不能晚于到期日期。
|
||||
*
|
||||
* @param {Object} data 请求体
|
||||
* @param {number} data.storage_id 库存记录ID(wms_storage.id,必填)
|
||||
* @param {string|null} [data.production_date] 生产日期(YYYY-MM-DD,null/空串清空)
|
||||
* @param {string|null} [data.expiry_date] 到期日期(YYYY-MM-DD,null/空串清空)
|
||||
* @return {Promise<Object>} 统一 success 包装(内层为 code/message/data 结构)
|
||||
*/
|
||||
async updateExpiry(data = {}) {
|
||||
const { service } = this;
|
||||
const result = await service.systems.storage.inventory.updateExpiry(data);
|
||||
return this.success('ok', result);
|
||||
}
|
||||
|
||||
/**
|
||||
* 提取 stock_query 虚拟筛选条件(与订单查询一致)。
|
||||
* 将其从 where 中移除并返回清洗后的 where 与 stock_query 关键字。
|
||||
@ -141,20 +122,6 @@ class InventoryMethodService extends MainService {
|
||||
return this.success('ok', result);
|
||||
}
|
||||
|
||||
/**
|
||||
* 按库位查询库存商品列表:传入 space_id,判断该库位是否为当前仓库的库位,
|
||||
* 是则返回该库位下有量库存(quantity > 0)的商品列表(按 stock_id 汇总为一条)。
|
||||
* 商品信息统一走 stock_warehouse 通用链路(getStockDetails),返回 stock_warehouse 通用属性。
|
||||
* @param {Object} data 请求体
|
||||
* @param {number} data.space_id 库位ID(必填)
|
||||
* @return {Promise<Object>} 统一 success 包装
|
||||
*/
|
||||
async listBySpaceId(data = {}) {
|
||||
const { service } = this;
|
||||
const result = await service.systems.storage.inventory.getStorageListBySpaceId(data.space_id);
|
||||
return this.success('ok', result);
|
||||
}
|
||||
|
||||
/**
|
||||
* 收货单快捷入库:将收货单的明细直接转为入库单,相同商品自动合并数量。
|
||||
* 要求货主配置中允许收货单快捷入库,否则直接返回失败。
|
||||
|
||||
@ -390,11 +390,6 @@ class StorageStockoutService extends MainService {
|
||||
|
||||
/**
|
||||
* 写 wms_operation_log 操作日志(businessType=stockout),失败仅告警不影响主流程。
|
||||
*
|
||||
* 委托到共享实现 `systems/stockout_order.js#_writeStockoutOperationLog`,
|
||||
* 保持本入口的历史口径:操作人取自 ctx.user,仓库取自 ctx.user.store_id(缺失时
|
||||
* 回退出库单自身 warehouse_id)。
|
||||
*
|
||||
* @param {Object} order 出库单实例或行
|
||||
* @param {string} operationCode 操作编码
|
||||
* @param {string} message 日志内容
|
||||
@ -403,20 +398,32 @@ class StorageStockoutService extends MainService {
|
||||
*/
|
||||
async _writeStockoutOperationLog(order, operationCode, message, options = {}) {
|
||||
const { ctx } = this;
|
||||
const stockoutOrderService = ctx.service && ctx.service.systems && ctx.service.systems.stockoutOrder;
|
||||
if (!stockoutOrderService || typeof stockoutOrderService._writeStockoutOperationLog !== 'function') {
|
||||
ctx.logger.warn('[stockout] 出库单领域服务不可用,跳过记录');
|
||||
const opLogService = ctx.service && ctx.service.systems && ctx.service.systems.operationLog;
|
||||
if (!opLogService || typeof opLogService.createOperationLogs !== 'function') {
|
||||
ctx.logger.warn('[stockout] 操作日志服务不可用,跳过记录');
|
||||
return;
|
||||
}
|
||||
const user = ctx.user || {};
|
||||
await stockoutOrderService._writeStockoutOperationLog(order, operationCode, message, {
|
||||
transaction: options.transaction,
|
||||
warehouseId: Number(ctx.user && ctx.user.store_id) || order.warehouse_id || null,
|
||||
operator: {
|
||||
id: user.employees_id ?? user.id ?? null,
|
||||
name: String(user.employees_name || user.real_name || user.name || 'system'),
|
||||
},
|
||||
});
|
||||
try {
|
||||
await opLogService.createOperationLogs([
|
||||
{
|
||||
businessType: 'stockout',
|
||||
businessId: order.id,
|
||||
operationCode,
|
||||
operator: {
|
||||
id: user.employees_id ?? user.id ?? null,
|
||||
name: String(user.employees_name || user.real_name || user.name || 'system'),
|
||||
},
|
||||
extras: {
|
||||
warehouseId: Number(ctx.user && ctx.user.store_id) || order.warehouse_id || null,
|
||||
message,
|
||||
externalLogType: 'NONE',
|
||||
},
|
||||
},
|
||||
], { transaction: options.transaction });
|
||||
} catch (err) {
|
||||
ctx.logger.warn(`[stockout] 写操作日志失败: ${err.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@ -559,10 +566,9 @@ class StorageStockoutService extends MainService {
|
||||
/**
|
||||
* 出库单确认(直出)。
|
||||
* 不改变内部库存,直接按出库单明细的计划数量确认。
|
||||
* 出站回传按 source_type 分流(QM→奇门 taobao.qimen.stockout.confirm,
|
||||
* API→OpenAPI 回调 stockout.confirm,其他内部来源直接视为成功),
|
||||
* 回传成功后释放创建时占用的库存锁定(QM_STOCKOUT,写 UNLOCK 流水),状态才推进到 COMPLETED。
|
||||
* 要求运单号已填写(以复数 waybill_codes 为准,存量单回退单数 waybill_code),否则拒绝确认。
|
||||
* 出站同步 taobao.qimen.stockout.confirm 成功后,释放创建时占用的库存锁定(QM_STOCKOUT,写 UNLOCK 流水),
|
||||
* 状态才推进到 COMPLETED。
|
||||
* 要求 express_code 已填写,否则拒绝确认。
|
||||
* @param {Object} data 请求体
|
||||
* @param {number} data.id 出库单ID(必填)
|
||||
* @return {Promise<Object>} 统一成功/失败包装响应
|
||||
@ -584,15 +590,9 @@ class StorageStockoutService extends MainService {
|
||||
return this.fail(`出库单当前状态(${order.order_status})不允许确认`);
|
||||
}
|
||||
|
||||
// 校验运单号是否已填写:回传以复数 waybill_codes 为准(一单多运单 → 奇门 packages.package[]),
|
||||
// 单数 waybill_code 已弃用,仅在复数缺失时对存量单做兼容回退。
|
||||
const confirmWaybillCodes = (Array.isArray(order.waybill_codes) && order.waybill_codes.length > 0
|
||||
? order.waybill_codes
|
||||
: [ order.waybill_code ])
|
||||
.map(code => String(code || '').trim())
|
||||
.filter(code => !!code);
|
||||
if (confirmWaybillCodes.length === 0) {
|
||||
return this.fail('出库单未填写运单号(waybill_codes),请先更新运单号后再确认');
|
||||
// 校验运单号是否已填写
|
||||
if (!order.waybill_code) {
|
||||
return this.fail('出库单未填写运单号(waybill_code),请先更新运单号后再确认');
|
||||
}
|
||||
|
||||
// 第一步:事务内写入明细 actual_qty(暂不改变 order_status)
|
||||
@ -618,39 +618,76 @@ class StorageStockoutService extends MainService {
|
||||
return this.fail(`确认失败:${err.message}`);
|
||||
}
|
||||
|
||||
// 第二步:按出库单来源通知外部
|
||||
// QM → 奇门 taobao.qimen.stockout.confirm;API → OpenAPI 回调 stockout.confirm;
|
||||
// WMS 等内部来源 → 无需通知外部,直接视为成功。
|
||||
// 与出库单转订单回传(orderAsync.syncStockoutOrders)共用同一分流实现,避免两处逻辑漂移。
|
||||
const orderAsyncService = ctx.service.systems && ctx.service.systems.orderAsync;
|
||||
// 第二步:出站通知 ERP(taobao.qimen.stockout.confirm)
|
||||
const { app } = this;
|
||||
let qimenSuccess = false;
|
||||
let qimenMessage = '';
|
||||
|
||||
if (!orderAsyncService || typeof orderAsyncService.notifyStockoutExternal !== 'function') {
|
||||
qimenMessage = '出库单回传服务不可用';
|
||||
ctx.logger.error('[stockout.confirm] 出库单回传服务不可用(ctx.service.systems.orderAsync 缺失)');
|
||||
} else {
|
||||
if (app.qimenClient && order.qimen_owner_code && order.qimen_warehouse_code) {
|
||||
try {
|
||||
// 直出确认没有发货单上下文,orderRow 传空对象:报文内快递信息回退出库单 express_code/express_name
|
||||
// 运单号统一走复数(packages.package[].expressCode),不传 deliveryOrder.expressCode
|
||||
const outboundData = orderAsyncService.buildStockoutConfirmRequest(order, {}, items, confirmWaybillCodes);
|
||||
const now = app.formatDate(new Date());
|
||||
const waybillCodes = Array.isArray(order.waybill_codes) && order.waybill_codes.length > 0
|
||||
? order.waybill_codes
|
||||
: [ order.waybill_code ].filter(Boolean);
|
||||
|
||||
// API 来源需按货主合约反查回调 appKey;QM 来源由奇门 client 按货主编码发送,无需 appKey
|
||||
let appKey = '';
|
||||
if (String(order.source_type || 'QM').trim().toUpperCase() === 'API') {
|
||||
const resolvedApp = await orderAsyncService.resolveOpenApiAppByStore(order.store_id, order.warehouse_id);
|
||||
appKey = String((resolvedApp && resolvedApp.appKey) || '').trim();
|
||||
}
|
||||
const outboundData = {
|
||||
deliveryOrder: {
|
||||
totalOrderLines: order.total_order_lines,
|
||||
deliveryOrderCode: order.stockout_order_code,
|
||||
deliveryOrderId: order.id,
|
||||
warehouseCode: order.qimen_warehouse_code,
|
||||
orderType: order.order_type,
|
||||
status: 'DELIVERED',
|
||||
outBizCode: order.stockout_order_code,
|
||||
confirmType: 0,
|
||||
orderConfirmTime: now,
|
||||
operatorCode: '',
|
||||
operatorName: '',
|
||||
},
|
||||
packages: {
|
||||
package: waybillCodes.map(code => ({
|
||||
logisticsCode: order.express_code || 'OTHER',
|
||||
logisticsName: order.express_name || 'OTHER',
|
||||
expressCode: code,
|
||||
packageCode: order.stockout_order_code,
|
||||
items: items.map(item => ({
|
||||
itemCode: item.item_code || '',
|
||||
itemId: item.item_id || '',
|
||||
quantity: item.plan_qty || 0,
|
||||
})),
|
||||
})),
|
||||
},
|
||||
orderLines: items.map(item => ({
|
||||
orderLineNo: item.order_line_no || '',
|
||||
ownerCode: item.owner_code || order.qimen_owner_code,
|
||||
itemCode: item.item_code || '',
|
||||
itemId: item.item_id || '',
|
||||
itemName: item.item_name || '',
|
||||
planQty: item.plan_qty || 0,
|
||||
actualQty: item.plan_qty || 0,
|
||||
inventoryType: item.inventory_type || 'ZP',
|
||||
})),
|
||||
};
|
||||
|
||||
const notifyResult = await orderAsyncService.notifyStockoutExternal(order, outboundData, { appKey });
|
||||
qimenSuccess = !!(notifyResult && notifyResult.success === true);
|
||||
qimenMessage = qimenSuccess
|
||||
? ''
|
||||
: String((notifyResult && notifyResult.message) || '通知外部失败').trim();
|
||||
const sendResult = await app.qimenClient.send(
|
||||
'taobao.qimen.stockout.confirm',
|
||||
order.qimen_owner_code,
|
||||
outboundData,
|
||||
{ ctx }
|
||||
);
|
||||
|
||||
// 解析奇门响应
|
||||
const response = (sendResult && sendResult.xmlArray && sendResult.xmlArray.response)
|
||||
? (Array.isArray(sendResult.xmlArray.response) ? sendResult.xmlArray.response[0] : sendResult.xmlArray.response)
|
||||
: {};
|
||||
qimenSuccess = String(response.flag || '').trim() === 'success';
|
||||
qimenMessage = qimenSuccess ? '' : `${response.code || ''} ${response.message || '未知错误'}`.trim();
|
||||
} catch (outboundErr) {
|
||||
qimenMessage = outboundErr.message || '出站通知异常';
|
||||
ctx.logger.error(`[stockout.confirm] 出站通知异常: ${qimenMessage}`);
|
||||
}
|
||||
} else {
|
||||
ctx.logger.warn(`[stockout.confirm] 跳过出站通知: qimenClient=${!!app.qimenClient}, ownerCode=${order.qimen_owner_code}, warehouseCode=${order.qimen_warehouse_code}`);
|
||||
}
|
||||
|
||||
// 第三步:根据出站结果更新状态
|
||||
@ -731,9 +768,9 @@ class StorageStockoutService extends MainService {
|
||||
/**
|
||||
* 出库单取消。
|
||||
*
|
||||
* 委托到共享实现 `systems/stockout_order.js#cancel`(奇门 / openapi 同口径:
|
||||
* 事务 + 行锁,释放 QM_STOCKOUT 库存锁定,状态置 CANCELLED 并写操作日志),
|
||||
* 本入口负责入参校验与对外契约映射。
|
||||
* 仅 CREATED / PENDING 状态允许取消;事务内释放创建时占用的库存锁定(QM_STOCKOUT,
|
||||
* 写 UNLOCK 流水),状态置为 CANCELLED,并写 wms_operation_log 操作日志。
|
||||
* 已转订单(TRANSFERRED)与已完成(COMPLETED)状态禁止取消。
|
||||
*
|
||||
* @param {Object} data 请求体
|
||||
* @param {number} data.id 出库单ID(必填)
|
||||
@ -752,47 +789,89 @@ class StorageStockoutService extends MainService {
|
||||
return this.fail('缺少仓库上下文');
|
||||
}
|
||||
|
||||
const stockoutOrderService = ctx.service && ctx.service.systems && ctx.service.systems.stockoutOrder;
|
||||
if (!stockoutOrderService || typeof stockoutOrderService.cancel !== 'function') {
|
||||
return this.fail('出库单取消服务不可用');
|
||||
const order = await ctx.model.OrderStockout.findOne({
|
||||
where: { id, warehouse_id: warehouseId, deleted_at: null },
|
||||
});
|
||||
if (!order) {
|
||||
return this.fail('出库单不存在');
|
||||
}
|
||||
|
||||
const result = await stockoutOrderService.cancel(
|
||||
{ id },
|
||||
{
|
||||
storeId: null,
|
||||
warehouseId,
|
||||
operatorLabel: String(
|
||||
(ctx.user && (ctx.user.employees_name || ctx.user.real_name || ctx.user.name)) || 'system'
|
||||
),
|
||||
if (!order.canCancel || !order.canCancel()) {
|
||||
return this.fail(`出库单当前状态(${order.order_status})不允许取消`);
|
||||
}
|
||||
|
||||
const items = await ctx.model.OrderStockoutItems.findAll({
|
||||
where: { order_id: order.id },
|
||||
raw: true,
|
||||
});
|
||||
|
||||
// 释放创建时占用的库存锁定 + 状态置 CANCELLED + 操作日志,同一事务
|
||||
const cancelTransaction = await ctx.model.transaction();
|
||||
try {
|
||||
let releasedQty = 0;
|
||||
for (const item of items) {
|
||||
const qty = Number(item.plan_qty) || 0;
|
||||
if (qty <= 0) continue;
|
||||
const releaseResult = await ctx.service.systems.stockStore.lockItemStorages(
|
||||
item.stock_id,
|
||||
-qty,
|
||||
cancelTransaction,
|
||||
null,
|
||||
{
|
||||
orderType: 'QM_STOCKOUT',
|
||||
orderNo: order.stockout_order_code,
|
||||
orderId: order.id,
|
||||
remark: '出库单取消释放锁定',
|
||||
}
|
||||
);
|
||||
if (!releaseResult.success) {
|
||||
// 已释放过(锁定不足)视为幂等成功,避免阻断
|
||||
const alreadyReleased = String(releaseResult.error || '').includes('释放数量超过已锁定库存');
|
||||
if (alreadyReleased) {
|
||||
ctx.logger.warn(`[stockout.cancel] 库存${item.stock_id}锁定已释放,跳过: ${releaseResult.error}`);
|
||||
continue;
|
||||
}
|
||||
throw new Error(`库存${item.stock_id}释放锁定失败: ${releaseResult.error}`);
|
||||
}
|
||||
releasedQty += qty;
|
||||
}
|
||||
);
|
||||
|
||||
if (result.flag !== 'success') {
|
||||
// 契约文案映射:共享层「未找到对应的出库单」→ 本入口「出库单不存在」,其余文案原样透出
|
||||
return this.fail(
|
||||
result.message === '未找到对应的出库单' ? '出库单不存在' : result.message
|
||||
await ctx.model.OrderStockout.update(
|
||||
{ order_status: 'CANCELLED', sync_message: '已取消', updated_at: new Date() },
|
||||
{ where: { id: order.id }, transaction: cancelTransaction }
|
||||
);
|
||||
|
||||
await this._writeStockoutOperationLog(
|
||||
order,
|
||||
'STOCKOUT_CANCEL',
|
||||
`出库单已取消,释放锁定库存 ${releasedQty}`,
|
||||
{ transaction: cancelTransaction }
|
||||
);
|
||||
|
||||
await cancelTransaction.commit();
|
||||
} catch (err) {
|
||||
await cancelTransaction.rollback().catch(() => {});
|
||||
ctx.logger.error(`[stockout.cancel] 取消失败: ${order.stockout_order_code} - ${err.message}`);
|
||||
return this.fail(`取消失败:${err.message}`);
|
||||
}
|
||||
|
||||
ctx.logger.info(`[stockout.cancel] 取消完成: ${order.stockout_order_code}`);
|
||||
return this.success('取消成功', {
|
||||
id: result.id,
|
||||
stockout_order_code: result.stockout_order_code,
|
||||
order_status: result.order_status,
|
||||
id: order.id,
|
||||
stockout_order_code: order.stockout_order_code,
|
||||
order_status: 'CANCELLED',
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新出库单快递和运单号。
|
||||
* 用于在确认前填写 express_code / waybill_codes。
|
||||
* 运单号以复数 waybill_codes 为准(一单多运单);单数 waybill_code 已弃用,
|
||||
* 传入 waybill_codes 时会自动镜像为首个单号写回单数列。
|
||||
* 用于在确认前填写 express_code / waybill_code / waybill_codes。
|
||||
* express_code 传入后自动从系统快递表解析 express_name。
|
||||
* @param {Object} data 请求体
|
||||
* @param {number} data.id 出库单ID(必填)
|
||||
* @param {string} [data.express_code] 快递公司编码(如 SF、STO),传入后自动解析 express_name
|
||||
* @param {string} [data.waybill_code] 运单号(单数,已弃用;仅作为 waybill_codes 首个的镜像,勿单独使用)
|
||||
* @param {string[]} [data.waybill_codes] 运单号列表(复数,回传以此为准,支持一单多运单)
|
||||
* @param {string} [data.waybill_code] 运单号
|
||||
* @param {string[]} [data.waybill_codes] 运单号列表
|
||||
* @return {Promise<Object>} 统一成功/失败包装响应
|
||||
*/
|
||||
async updateExpress(data = {}) {
|
||||
@ -827,9 +906,6 @@ class StorageStockoutService extends MainService {
|
||||
}
|
||||
}
|
||||
|
||||
// waybill_code(单数)已弃用:回传以 waybill_codes(复数)为准(一单多运单),
|
||||
// 单数列仅作为复数首个的镜像保留,便于历史查询与展示;
|
||||
// 传入 waybill_codes 时以复数首个覆盖单数,避免两列不一致。
|
||||
if (data.waybill_code !== undefined) {
|
||||
updateData.waybill_code = data.waybill_code || null;
|
||||
}
|
||||
@ -839,9 +915,6 @@ class StorageStockoutService extends MainService {
|
||||
return this.fail('waybill_codes 必须是数组或 null');
|
||||
}
|
||||
updateData.waybill_codes = codes;
|
||||
updateData.waybill_code = Array.isArray(codes) && codes.length > 0
|
||||
? String(codes[0] || '').trim() || null
|
||||
: null;
|
||||
}
|
||||
|
||||
if (Object.keys(updateData).length <= 1) {
|
||||
|
||||
@ -5,10 +5,10 @@ const MainService = require('../main');
|
||||
class WorkbenchService extends MainService {
|
||||
constructor(ctx) {
|
||||
super(ctx);
|
||||
const _noNeedLogin = 'business,getWorkbenchInfo,removeMember,bindMember,packOrder,finishPack,sendWeight,queryOrder';
|
||||
const _noNeedRight = 'list,detail,business,getWorkbenchInfo,removeMember,bindMember,packOrder,finishPack,sendWeight,queryOrder';
|
||||
const _noNeedLogin = 'business,getWorkbenchInfo,removeMember,bindMember';
|
||||
const _noNeedRight = 'list,detail,business,getWorkbenchInfo,removeMember,bindMember';
|
||||
const _noNeedLog = 'list,detail,getWorkbenchInfo,removeMember,bindMember';
|
||||
const _noNeedAuth = 'list,detail,business,getWorkbenchInfo,removeMember,bindMember,packOrder,finishPack,sendWeight,queryOrder';
|
||||
const _noNeedAuth = 'list,detail,business,getWorkbenchInfo,removeMember,bindMember';
|
||||
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
|
||||
}
|
||||
|
||||
@ -143,15 +143,13 @@ class WorkbenchService extends MainService {
|
||||
}
|
||||
|
||||
/**
|
||||
* 使用 token 获取工作台信息(免登录、免鉴权)。
|
||||
* 返回主表信息、成员列表 members,以及当前正在打包的波次(current_wave)与订单列表(current_orders)。
|
||||
* @param {Object} data - { token }
|
||||
* 使用 token 获取工作台信息(免登录、免鉴权)
|
||||
* @param data - { token }
|
||||
*/
|
||||
async getWorkbenchInfo(data) {
|
||||
const { service } = this;
|
||||
try {
|
||||
const { token } = data || {};
|
||||
const result = await service.systems.workbench.getWorkbenchInfoByToken({ token });
|
||||
const result = await service.systems.workbench.getWorkbenchInfoByToken(data || {});
|
||||
if (result && result.success) {
|
||||
return this.success('获取成功', result);
|
||||
}
|
||||
@ -222,117 +220,6 @@ class WorkbenchService extends MainService {
|
||||
return this.fail(error.message);
|
||||
}
|
||||
}
|
||||
/**
|
||||
* 工作台打包上报(免登录、免鉴权,以工作台 token 鉴权,仓库与工作台由服务端注入)
|
||||
* @param {Object} data - {
|
||||
* token, delivery_order_code, wave_no, status, pack_time,
|
||||
* wave_total_orders, items_count, items_total, users
|
||||
* }
|
||||
*/
|
||||
async packOrder(data) {
|
||||
const { service } = this;
|
||||
try {
|
||||
const {
|
||||
token,
|
||||
delivery_order_code: deliveryOrderCode,
|
||||
wave_no: waveNo,
|
||||
status,
|
||||
pack_time: packTime,
|
||||
wave_total_orders: waveTotalOrders,
|
||||
items_count: itemsCount,
|
||||
items_total: itemsTotal,
|
||||
users,
|
||||
} = data || {};
|
||||
const result = await service.systems.workbench.packOrderByToken({
|
||||
token,
|
||||
delivery_order_code: deliveryOrderCode,
|
||||
wave_no: waveNo,
|
||||
status,
|
||||
pack_time: packTime,
|
||||
wave_total_orders: waveTotalOrders,
|
||||
items_count: itemsCount,
|
||||
items_total: itemsTotal,
|
||||
users,
|
||||
});
|
||||
if (result && result.success) {
|
||||
return this.success('ok', result);
|
||||
}
|
||||
const statusCode = result && result.statusCode;
|
||||
return this.fail(
|
||||
result && result.message ? result.message : '打包上报失败',
|
||||
statusCode ? { code: statusCode } : undefined
|
||||
);
|
||||
} catch (error) {
|
||||
return this.fail(error.message);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 工作台打包完成(免登录、免鉴权,以工作台 token 鉴权,仓库与工作台由服务端注入)
|
||||
* @param {Object} data - { token }
|
||||
*/
|
||||
async finishPack(data) {
|
||||
const { service } = this;
|
||||
try {
|
||||
const { token } = data || {};
|
||||
const result = await service.systems.workbench.finishPackByToken({ token });
|
||||
if (result && result.success) {
|
||||
return this.success('ok', result);
|
||||
}
|
||||
const statusCode = result && result.statusCode;
|
||||
return this.fail(
|
||||
result && result.message ? result.message : '打包完成失败',
|
||||
statusCode ? { code: statusCode } : undefined
|
||||
);
|
||||
} catch (error) {
|
||||
return this.fail(error.message);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 工作台称重上报(免登录、免鉴权,以工作台 token 鉴权,仓库由服务端注入)
|
||||
* @param {Object} data - { token, barcode, weight }
|
||||
*/
|
||||
async sendWeight(data) {
|
||||
const { service } = this;
|
||||
try {
|
||||
const { token, barcode, weight } = data || {};
|
||||
const result = await service.systems.workbench.sendWeightByToken({ token, barcode, weight });
|
||||
if (result && result.success) {
|
||||
return this.success('ok', result);
|
||||
}
|
||||
const statusCode = result && result.statusCode;
|
||||
return this.fail(
|
||||
result && result.message ? result.message : '称重上报失败',
|
||||
statusCode ? { code: statusCode } : undefined
|
||||
);
|
||||
} catch (error) {
|
||||
return this.fail(error.message);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 条码查询订单(免登录、免鉴权,以工作台 token 鉴权,仓库由服务端注入)
|
||||
* body 传入的 warehouse_id/workbench_id 一律忽略,仅以 token 解析出的工作台仓库为准。
|
||||
* @param {Object} data - { token, barcode }
|
||||
*/
|
||||
async queryOrder(data) {
|
||||
const { service } = this;
|
||||
try {
|
||||
const { token, barcode } = data || {};
|
||||
const result = await service.systems.workbench.queryOrderByToken({ token, barcode });
|
||||
if (result && result.success) {
|
||||
return this.success('ok', result);
|
||||
}
|
||||
const statusCode = result && result.statusCode;
|
||||
return this.fail(
|
||||
result && result.message ? result.message : '查询订单失败',
|
||||
statusCode ? { code: statusCode } : undefined
|
||||
);
|
||||
} catch (error) {
|
||||
return this.fail(error.message);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = WorkbenchService;
|
||||
|
||||
@ -1267,11 +1267,7 @@ class AfterSaleService extends Service {
|
||||
storeIds: [ notifyStoreId ],
|
||||
warehouseId,
|
||||
});
|
||||
// 通知文案只给运单号 + 处理内容(售后单号对客户无意义)
|
||||
const waybillNo = String(asRow.waybill_no || '').trim();
|
||||
const content = waybillNo
|
||||
? `运单${waybillNo} 处理备注:\n${remarkText}`
|
||||
: `处理备注:\n${remarkText}`;
|
||||
const content = `【工单 ${asRow.after_sale_no}】处理备注:\n${remarkText}`;
|
||||
for (const g of storeGroups) {
|
||||
if (!g.group_id) continue;
|
||||
ctx.service.inbox.processor.pushSystemNotification({
|
||||
|
||||
@ -25,7 +25,6 @@ const ORDER_OPERATION_CODES = Object.freeze({
|
||||
EXPRESS_FALLBACK: 'ORDER_EXPRESS_FALLBACK',
|
||||
EXPRESS_POLICY_MATCH: 'ORDER_EXPRESS_POLICY_MATCH',
|
||||
AUTO_EXPRESS_SKIP: 'ORDER_AUTO_EXPRESS_SKIP',
|
||||
NEED_OMS_WAYBILL_WAIT: 'ORDER_NEED_OMS_WAYBILL_WAIT',
|
||||
});
|
||||
|
||||
const STORE_SUBJECT_CONFIG_CACHE_TTL_SECONDS = 600;
|
||||
@ -670,26 +669,6 @@ class DeliveryOrderService extends Service {
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 归一化“是否需要回 OMS 取号”入参为 0/1。
|
||||
* 兼容 1/0、'1'/'0'、true/false、'true'/'false'、'Y'/'N'、'YES'/'NO',
|
||||
* 其余非法值一律按 0 处理。
|
||||
*
|
||||
* @param {*} value 原始入参。
|
||||
* @return {number} 1=需要回 OMS 取号,0=不需要。
|
||||
*/
|
||||
normalizeNeedOmsWaybill(value) {
|
||||
if (value === true) {
|
||||
return 1;
|
||||
}
|
||||
if (value === false || value === null || value === undefined) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
const text = String(value).trim().toUpperCase();
|
||||
return [ '1', 'TRUE', 'Y', 'YES' ].includes(text) ? 1 : 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建发货单。
|
||||
*
|
||||
@ -726,18 +705,6 @@ class DeliveryOrderService extends Service {
|
||||
|| 'MANUAL'
|
||||
).trim().toUpperCase() || 'MANUAL';
|
||||
|
||||
// 是否需要回 OMS 取号:仅 openapi(API)创建来源使用,
|
||||
// 支持请求根节点(data.request.need_oms_waybill)与 deliveryOrder 内两种传参位置,
|
||||
// 其他渠道(QM/MANUAL/STOCKOUT)一律强制 0,避免被非法入参污染。
|
||||
const needOmsWaybill = normalizedCreateChannel === 'API'
|
||||
? this.normalizeNeedOmsWaybill(
|
||||
data.request.need_oms_waybill
|
||||
?? data.request.needOmsWaybill
|
||||
?? deliveryOrder.need_oms_waybill
|
||||
?? deliveryOrder.needOmsWaybill
|
||||
)
|
||||
: 0;
|
||||
|
||||
// 订单 id 序列表初始化可能执行 DDL(隐式提交),必须在事务外先完成
|
||||
try {
|
||||
await ctx.model.OrderDeliveryFactory.ensureLocationSequenceTable(warehouseIdStr);
|
||||
@ -786,20 +753,26 @@ class DeliveryOrderService extends Service {
|
||||
normalizedCreateChannel,
|
||||
step,
|
||||
operationLogs,
|
||||
requestExtendProps,
|
||||
needOmsWaybill
|
||||
requestExtendProps
|
||||
);
|
||||
|
||||
// 创建订单:订单 id 统一由仓库序列表分配,显式写入 current 分表。
|
||||
// 不再回退分表自增:分表自增序列与序列表发号区间重叠会产生冲突 id,
|
||||
// 发号失败时直接抛错,由事务回滚,杜绝脏 id 落库。
|
||||
const orderId = await ctx.model.OrderDeliveryFactory.allocateOrderId(warehouseIdStr, transaction, 'current');
|
||||
await DeliveryModel.create({ ...orderData, id: orderId }, { transaction });
|
||||
this.appendOrderOperationLog(
|
||||
operationLogs,
|
||||
ORDER_OPERATION_CODES.CREATE,
|
||||
`订单创建成功,orderId:${orderId}`,
|
||||
{ prepend: true }
|
||||
);
|
||||
|
||||
// 将建单渠道注入 info,供 addOrderLines 区分 MANUAL 降级逻辑
|
||||
info.createChannel = normalizedCreateChannel;
|
||||
|
||||
let itemsInfo = null;
|
||||
// 添加订单明细(先写明细、后写主表:库存预占失败直接回滚,不留悬挂主表行)
|
||||
// 添加订单明细
|
||||
if (orderLines && (orderLines.orderLine)) {
|
||||
itemsInfo = await this.addOrderLines(
|
||||
orderLines.orderLine,
|
||||
@ -811,22 +784,19 @@ class DeliveryOrderService extends Service {
|
||||
throw new Error('[订单无明细]');
|
||||
}
|
||||
|
||||
// 统计列(items / items_hash / items_crc)在 wms_order_delivery_* 上均为二级索引列,
|
||||
// 必须与主表 INSERT 同一条语句写入:先插占位值(''/0/NULL)再 UPDATE 回写,
|
||||
// 会让并发建单在同一索引区间反复“删标记旧条目 + 插入新条目”,
|
||||
// 批量推单高并发下必然死锁(生产 2026-09-10 单批 354 个事务因此失败)。
|
||||
const stats = this.buildOrderStats(itemsInfo, deliveryOrder);
|
||||
await DeliveryModel.create({ ...orderData, ...stats, id: orderId }, { transaction });
|
||||
this.appendOrderOperationLog(
|
||||
operationLogs,
|
||||
ORDER_OPERATION_CODES.CREATE,
|
||||
`订单创建成功,orderId:${orderId}`,
|
||||
{ prepend: true }
|
||||
);
|
||||
|
||||
// 快递策略命中时只覆盖非索引的快递字段(不动 items/items_hash/items_crc)
|
||||
const expressOverride = {};
|
||||
// 更新订单统计信息 - 直接使用itemsInfo中的计算结果
|
||||
if (itemsInfo) {
|
||||
const stats = {
|
||||
items: itemsInfo.items_str || '', // 原始结构字符串
|
||||
items_count: itemsInfo.stock_count || 0, // 商品种类数
|
||||
items_total: itemsInfo.item_total_count || 0, // 商品总数(直接使用计算结果)
|
||||
items_weight: itemsInfo.total_weight || 0, // 总重量
|
||||
items_hash: this.generateItemsHash(itemsInfo), // 哈希值
|
||||
items_crc: this.calculateCRC32(itemsInfo.items_str || ''), // CRC校验
|
||||
source_order_codes: ((itemsInfo.stats && itemsInfo.stats.source_order_codes) || []).filter(code => code).join(',') || deliveryOrder.deliveryOrderCode,
|
||||
updated_at: new Date(),
|
||||
};
|
||||
|
||||
// ===== 快递绑定策略漏斗匹配(items 处理后 weight 可用) =====
|
||||
// enable_external_express_code 开启时仅"纯货主维度"策略参与漏斗,命中后覆盖外部快递匹配结果;
|
||||
// 关闭时全维度策略参与,沿用原有逻辑
|
||||
@ -904,11 +874,12 @@ class DeliveryOrderService extends Service {
|
||||
sysLogisticsName = logisticsCode;
|
||||
}
|
||||
|
||||
expressOverride.logistics_code = logisticsCode;
|
||||
expressOverride.logistics_name = logisticsName;
|
||||
expressOverride.sys_logistics_code = sysLogisticsCode;
|
||||
expressOverride.sys_logistics_name = sysLogisticsName;
|
||||
expressOverride.weight_type = matchResult.weightType;
|
||||
stats.logistics_code = logisticsCode;
|
||||
stats.logistics_name = logisticsName;
|
||||
stats.sys_logistics_code = sysLogisticsCode;
|
||||
stats.sys_logistics_name = sysLogisticsName;
|
||||
stats.weight_type = matchResult.weightType;
|
||||
stats.updated_at = new Date();
|
||||
|
||||
// 写入操作日志:命中了哪条策略
|
||||
this.appendOrderOperationLog(
|
||||
@ -947,15 +918,13 @@ class DeliveryOrderService extends Service {
|
||||
});
|
||||
}
|
||||
|
||||
if (Object.keys(expressOverride).length > 0) {
|
||||
await DeliveryModel.update(
|
||||
expressOverride,
|
||||
{
|
||||
where: { id: orderId },
|
||||
transaction,
|
||||
}
|
||||
);
|
||||
}
|
||||
await DeliveryModel.update(
|
||||
stats,
|
||||
{
|
||||
where: { id: orderId },
|
||||
transaction,
|
||||
}
|
||||
);
|
||||
|
||||
// 记录详细日志
|
||||
ctx.logger.info('[订单统计信息已更新]', {
|
||||
@ -1012,11 +981,8 @@ class DeliveryOrderService extends Service {
|
||||
}
|
||||
};
|
||||
|
||||
// 重试约定:
|
||||
// 1. 主键冲突(分表自增水位与已有数据重叠)修复水位后重试一次;
|
||||
// 2. 死锁 / 锁等待超时:批量推单高并发下的瞬时竞争,事务已整体回滚,退避后重放。
|
||||
const MAX_CREATE_ATTEMPTS = 3;
|
||||
for (let attempt = 1; attempt <= MAX_CREATE_ATTEMPTS; attempt++) {
|
||||
// 主键冲突(分表自增水位与已有数据重叠)允许修复水位后重试一次
|
||||
for (let attempt = 1; attempt <= 2; attempt++) {
|
||||
const operationLogs = [];
|
||||
try {
|
||||
return await createOnce(operationLogs);
|
||||
@ -1040,20 +1006,6 @@ class DeliveryOrderService extends Service {
|
||||
continue;
|
||||
}
|
||||
|
||||
// 死锁/锁等待:退避后重试(带抖动,避免同一批请求再次同时竞争)
|
||||
if (this.isRetryableLockError(error) && attempt < MAX_CREATE_ATTEMPTS) {
|
||||
ctx.logger.warn('[DeliveryOrderService.addOrder] 数据库锁冲突,退避后重试建单', {
|
||||
deliveryOrderCode: deliveryOrder && deliveryOrder.deliveryOrderCode,
|
||||
warehouseId: warehouseIdStr,
|
||||
storeId: info.storeId,
|
||||
attempt,
|
||||
maxAttempts: MAX_CREATE_ATTEMPTS,
|
||||
error: error.message,
|
||||
});
|
||||
await new Promise(resolve => setTimeout(resolve, 30 * attempt + Math.floor(Math.random() * 50)));
|
||||
continue;
|
||||
}
|
||||
|
||||
return {
|
||||
success: false,
|
||||
message: `订单创建失败: ${this.formatOrderCreateError(error, deliveryOrder)}`,
|
||||
@ -1064,61 +1016,11 @@ class DeliveryOrderService extends Service {
|
||||
|
||||
return {
|
||||
success: false,
|
||||
message: '订单创建失败: 重试后仍未成功,请稍后重试',
|
||||
message: '订单创建失败: 主键冲突重试后仍未成功',
|
||||
data: null,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 构建订单主表统计列(随 INSERT 一次写入)。
|
||||
*
|
||||
* wms_order_delivery_* 的 items / items_hash / items_crc 都是二级索引列,
|
||||
* 只能在 INSERT 时写入:若先插占位值再 UPDATE 回写,高并发建单时
|
||||
* 几十行占位值(''/0/NULL)落在同一索引区间,会反复触发“删标记 + 插入”
|
||||
* 而互相死锁。
|
||||
*
|
||||
* @param {Object} itemsInfo addOrderLines 返回的明细统计信息。
|
||||
* @param {Object} deliveryOrder 订单主信息。
|
||||
* @return {Object} 可直接并入 INSERT 的统计字段。
|
||||
*/
|
||||
buildOrderStats(itemsInfo, deliveryOrder) {
|
||||
return {
|
||||
items: itemsInfo.items_str || '', // 原始结构字符串
|
||||
items_count: itemsInfo.stock_count || 0, // 商品种类数
|
||||
items_total: itemsInfo.item_total_count || 0, // 商品总数(直接使用计算结果)
|
||||
items_weight: itemsInfo.total_weight || 0, // 总重量
|
||||
items_hash: this.generateItemsHash(itemsInfo), // 哈希值
|
||||
items_crc: this.calculateCRC32(itemsInfo.items_str || ''), // CRC校验
|
||||
source_order_codes: ((itemsInfo.stats && itemsInfo.stats.source_order_codes) || []).filter(code => code).join(',') || deliveryOrder.deliveryOrderCode,
|
||||
// 主表 timestamps:false,updated_at 需显式写入(原先由统计列 UPDATE 顺带更新)
|
||||
updated_at: new Date(),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断是否为可重试的数据库锁冲突(死锁 / 锁等待超时)。
|
||||
*
|
||||
* 建单事务整体回滚后重放是安全的(订单 id 由序列表重新发号),
|
||||
* 批量推单场景下瞬时竞争可自愈。
|
||||
*
|
||||
* @param {Error} error 原始异常。
|
||||
* @return {boolean} 是否可重试。
|
||||
*/
|
||||
isRetryableLockError(error) {
|
||||
if (!error) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const original = error.original || error.parent || error;
|
||||
const code = (original && (original.code || original.errno)) || error.code;
|
||||
if (code === 1213 || code === 1205 || code === 'ER_LOCK_DEADLOCK' || code === 'ER_LOCK_WAIT_TIMEOUT') {
|
||||
return true;
|
||||
}
|
||||
|
||||
const message = String((original && original.sqlMessage) || error.message || '').toLowerCase();
|
||||
return message.includes('deadlock found') || message.includes('lock wait timeout');
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断是否为分表主键自增冲突。
|
||||
*
|
||||
@ -1168,10 +1070,6 @@ class DeliveryOrderService extends Service {
|
||||
return String(firstItem.message || error.message || '唯一约束冲突').trim();
|
||||
}
|
||||
|
||||
if (this.isRetryableLockError(error)) {
|
||||
return '数据库锁冲突(死锁/锁等待超时),系统已自动重试,请稍后再试';
|
||||
}
|
||||
|
||||
const parentSqlMessage = error && error.parent && error.parent.sqlMessage;
|
||||
if (parentSqlMessage) {
|
||||
return `${error.message} (${parentSqlMessage})`;
|
||||
@ -1392,7 +1290,6 @@ class DeliveryOrderService extends Service {
|
||||
* @param {number} step 订单步骤。
|
||||
* @param {Array<Object>} [operationLogs=[]] 待写入的操作日志数组。
|
||||
* @param {Object} [requestExtendProps] 请求级扩展属性,携带 ewaybill_order_code 等关键字段。
|
||||
* @param {number} [needOmsWaybill=0] 是否需要回 OMS 取号(0/1),仅 openapi 来源可能为 1。
|
||||
* @return {Promise<Object>} 可入库的订单数据。
|
||||
*/
|
||||
async prepareOrderData(
|
||||
@ -1401,8 +1298,7 @@ class DeliveryOrderService extends Service {
|
||||
createChannel = 'MANUAL',
|
||||
step = DELIVERY_ORDER_STEP.PENDING_REVIEW,
|
||||
operationLogs = [],
|
||||
requestExtendProps,
|
||||
needOmsWaybill = 0
|
||||
requestExtendProps
|
||||
) {
|
||||
const {
|
||||
deliveryOrderCode,
|
||||
@ -1467,7 +1363,6 @@ class DeliveryOrderService extends Service {
|
||||
source_platform_name: sourcePlatformName || '',
|
||||
oaid_order_source_code: oaidOrderSourceCode || '',
|
||||
create_channel: String(createChannel || 'MANUAL').trim().toUpperCase() || 'MANUAL',
|
||||
need_oms_waybill: this.normalizeNeedOmsWaybill(needOmsWaybill),
|
||||
sys_platform_code: platformSnapshot.sysPlatformCode,
|
||||
sys_platform_name: platformSnapshot.sysPlatformName,
|
||||
// 创建时间统一取服务器当前时间,不采用报文 createTime,避免被平台上报时间覆盖
|
||||
@ -2777,51 +2672,6 @@ class DeliveryOrderService extends Service {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 补写「等待外部 OMS 取号」的订单操作日志。
|
||||
*
|
||||
* need_oms_waybill=1 的订单(仅 openapi 创建来源可能为 1)不参与本地自动分配快递:
|
||||
* 分流时不入本地取号队列,写一条操作记录说明原因与当前等待态;
|
||||
* 外部 OMS 取号能力上线后再接入实际取号与运单回写。
|
||||
* 写入失败仅记录告警,不影响订单创建主流程。
|
||||
*
|
||||
* @param {Object} context 异步处理上下文。
|
||||
* @return {Promise<void>} 无返回值。
|
||||
*/
|
||||
async appendNeedOmsWaybillWaitLog(context) {
|
||||
const orderId = Number(context && context.orderId || 0);
|
||||
const warehouseId = Number(context && context.warehouseId || 0);
|
||||
const operationLogService = this.ctx
|
||||
&& this.ctx.service
|
||||
&& this.ctx.service.systems
|
||||
&& this.ctx.service.systems.operationLog;
|
||||
if (!operationLogService || typeof operationLogService.createOperationLogs !== 'function' || orderId <= 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
await operationLogService.createOperationLogs([{
|
||||
businessType: 'order',
|
||||
businessId: `${orderId}`,
|
||||
operationCode: ORDER_OPERATION_CODES.NEED_OMS_WAYBILL_WAIT,
|
||||
operator: {
|
||||
id: null,
|
||||
name: 'system',
|
||||
},
|
||||
extras: {
|
||||
warehouseId,
|
||||
message: '订单需要回 OMS 取号,已跳过本地分配快递,等待外部 OMS 取号',
|
||||
},
|
||||
}]);
|
||||
} catch (error) {
|
||||
this.ctx.logger.warn('[DeliveryOrderService.appendNeedOmsWaybillWaitLog] 写入操作日志失败,不影响主流程', {
|
||||
orderId,
|
||||
warehouseId,
|
||||
error: error && error.message,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// 订单异步流程
|
||||
/**
|
||||
* 订单创建后的异步流程。
|
||||
@ -2902,20 +2752,7 @@ class DeliveryOrderService extends Service {
|
||||
});
|
||||
}
|
||||
|
||||
// 需要回 OMS 取号的订单(仅 openapi 创建来源可能为 1)先做分流:
|
||||
// 不进入本地自动分配快递队列,写「等待外部 OMS 取号」日志;
|
||||
// 等外部 OMS 取号能力开发完成后,再在此处接入实际取号/运单回写。
|
||||
const needOmsWaybill = this.normalizeNeedOmsWaybill(context.order && context.order.need_oms_waybill) === 1;
|
||||
if (needOmsWaybill) {
|
||||
this.ctx.logger.info('[DeliveryOrderService.asyncProcessOrderCreated] 订单需要回 OMS 取号,跳过本地自动分配快递', {
|
||||
orderId: context.orderId,
|
||||
warehouseId: context.warehouseId,
|
||||
storeId: context.storeId,
|
||||
});
|
||||
await this.runAsyncProcessStep('appendNeedOmsWaybillWaitLog', async () => {
|
||||
await this.appendNeedOmsWaybillWaitLog(context);
|
||||
});
|
||||
} else if (isAutoAllocateExpressEnabled) {
|
||||
if (isAutoAllocateExpressEnabled) {
|
||||
await this.runAsyncProcessStep('allocateExpress', async () => {
|
||||
// 不再逐单直接取号:改为写入消费队列,由定时任务按仓库+货主串行批量消费,
|
||||
// 避免大批量订单创建时 N 条并发取号事务的 AB-BA 死锁。截单/未审核订单在此处不会入队。
|
||||
|
||||
@ -2518,7 +2518,7 @@ class ExpressService extends Service {
|
||||
[Op.ne]: 'cancel',
|
||||
},
|
||||
},
|
||||
attributes: [ 'id', 'sys_platform_code', 'logistics_code', 'sys_platform_name', 'logistics_name', 'store_id', 'pay_no', 'from_key', 'intercept_status', 'lock_status', 'need_oms_waybill' ],
|
||||
attributes: [ 'id', 'sys_platform_code', 'logistics_code', 'sys_platform_name', 'logistics_name', 'store_id', 'pay_no', 'from_key', 'intercept_status', 'lock_status' ],
|
||||
raw: true,
|
||||
});
|
||||
|
||||
@ -2542,7 +2542,7 @@ class ExpressService extends Service {
|
||||
[Op.ne]: 'cancel',
|
||||
},
|
||||
},
|
||||
attributes: [ 'id', 'sys_platform_code', 'logistics_code', 'sys_platform_name', 'logistics_name', 'store_id', 'pay_no', 'from_key', 'intercept_status', 'lock_status', 'need_oms_waybill' ],
|
||||
attributes: [ 'id', 'sys_platform_code', 'logistics_code', 'sys_platform_name', 'logistics_name', 'store_id', 'pay_no', 'from_key', 'intercept_status', 'lock_status' ],
|
||||
raw: true,
|
||||
});
|
||||
}
|
||||
@ -2578,41 +2578,22 @@ class ExpressService extends Service {
|
||||
skippedLockedOrderIds,
|
||||
});
|
||||
}
|
||||
|
||||
// 需要回 OMS 取号的订单分流:不参与本地分配快递,等外部 OMS 取号能力接入后单独处理。
|
||||
// need_oms_waybill 为订单级标记(仅 openapi 创建来源可能为 1),同一订单的所有 business_key 一并跳过。
|
||||
const needOmsWaybillOrderIdSet = new Set(activeOrders
|
||||
.filter(order => Number(order && order.need_oms_waybill) === 1)
|
||||
.map(order => Number(order && order.id || 0))
|
||||
.filter(orderId => Number.isInteger(orderId) && orderId > 0));
|
||||
const skippedNeedOmsWaybillOrderIds = Array.from(needOmsWaybillOrderIdSet);
|
||||
const allocatableOrders = activeOrders
|
||||
.filter(order => !needOmsWaybillOrderIdSet.has(Number(order && order.id || 0)));
|
||||
if (skippedNeedOmsWaybillOrderIds.length > 0) {
|
||||
this.ctx.logger.info('[ExpressService.createWaybillCodePipeline] 跳过需要回 OMS 取号的订单', {
|
||||
traceId,
|
||||
warehouseId,
|
||||
skippedNeedOmsWaybillOrderIds,
|
||||
});
|
||||
}
|
||||
|
||||
this.ctx.logger.info('[ExpressService.createWaybillCodePipeline] 订单筛选结果', {
|
||||
traceId,
|
||||
warehouseId,
|
||||
inputOrderCount: orderList.length,
|
||||
currentCount: (Array.isArray(currentOrders) ? currentOrders : []).length,
|
||||
dispatchCount: dispatchOrders.length,
|
||||
matchedOrderCount: allocatableOrders.length,
|
||||
matchedOrderCount: activeOrders.length,
|
||||
skippedInterceptedOrderIds,
|
||||
skippedLockedOrderIds,
|
||||
skippedNeedOmsWaybillOrderIds,
|
||||
});
|
||||
|
||||
// 【step1.5】过滤已分配运单号(status=1)且传入 business_key=1 的订单,避免重复分配。
|
||||
const orderExpressModel = this.ctx.model && this.ctx.model.OrderExpress;
|
||||
let filteredOrdersArr = allocatableOrders;
|
||||
if (orderExpressModel && allocatableOrders.length > 0) {
|
||||
const orderIds = allocatableOrders.map(o => Number(o.id)).filter(id => id > 0);
|
||||
let filteredOrdersArr = activeOrders;
|
||||
if (orderExpressModel && activeOrders.length > 0) {
|
||||
const orderIds = activeOrders.map(o => Number(o.id)).filter(id => id > 0);
|
||||
const completedRows = await orderExpressModel.findAll({
|
||||
where: {
|
||||
order_id: { [Op.in]: orderIds },
|
||||
@ -2627,8 +2608,8 @@ class ExpressService extends Service {
|
||||
skipSet.add(`${Number(row.order_id)}:${Number(row.business_key)}`);
|
||||
}
|
||||
if (skipSet.size > 0) {
|
||||
const beforeCount = allocatableOrders.length;
|
||||
filteredOrdersArr = allocatableOrders.filter(order => {
|
||||
const beforeCount = activeOrders.length;
|
||||
filteredOrdersArr = activeOrders.filter(order => {
|
||||
const matchedExpress = orderList.find(express => Number(order.id) === Number(express.order_id));
|
||||
const businessKey = matchedExpress ? Number(matchedExpress.business_key) : 1;
|
||||
if (businessKey === 1 && skipSet.has(`${Number(order.id)}:1`)) {
|
||||
@ -2640,7 +2621,7 @@ class ExpressService extends Service {
|
||||
this.ctx.logger.info('[ExpressService.createWaybillCodePipeline] 跳过已分配运单号(business_key=1)的订单', {
|
||||
traceId,
|
||||
skippedCount: beforeCount - filteredOrdersArr.length,
|
||||
skippedOrderIds: allocatableOrders
|
||||
skippedOrderIds: activeOrders
|
||||
.filter(order => {
|
||||
const matchedExpress = orderList.find(express => Number(order.id) === Number(express.order_id));
|
||||
const businessKey = matchedExpress ? Number(matchedExpress.business_key) : 1;
|
||||
@ -2653,20 +2634,11 @@ class ExpressService extends Service {
|
||||
}
|
||||
|
||||
if (filteredOrdersArr.length === 0) {
|
||||
const noAllocatableByNeedOms = allocatableOrders.length === 0 && skippedNeedOmsWaybillOrderIds.length > 0;
|
||||
const emptyMessage = noAllocatableByNeedOms
|
||||
? '订单需要回 OMS 取号,已跳过本地分配快递,等待外部 OMS 取号'
|
||||
: '所有订单均已分配运单号,无需处理';
|
||||
this.ctx.logger.info('[ExpressService.createWaybillCodePipeline] 无可处理订单', {
|
||||
traceId,
|
||||
needOmsWaybillOnly: noAllocatableByNeedOms,
|
||||
skippedNeedOmsWaybillOrderIds,
|
||||
});
|
||||
this.ctx.logger.info('[ExpressService.createWaybillCodePipeline] 所有订单均已分配运单号,无需处理', { traceId });
|
||||
return {
|
||||
message: emptyMessage,
|
||||
message: '所有订单均已分配运单号,无需处理',
|
||||
skipped_intercepted_order_ids: skippedInterceptedOrderIds,
|
||||
skipped_locked_order_ids: skippedLockedOrderIds,
|
||||
skipped_need_oms_waybill_order_ids: skippedNeedOmsWaybillOrderIds,
|
||||
};
|
||||
}
|
||||
|
||||
@ -2773,7 +2745,6 @@ class ExpressService extends Service {
|
||||
message: '分配快递任务已提交',
|
||||
skipped_intercepted_order_ids: skippedInterceptedOrderIds,
|
||||
skipped_locked_order_ids: skippedLockedOrderIds,
|
||||
skipped_need_oms_waybill_order_ids: skippedNeedOmsWaybillOrderIds,
|
||||
};
|
||||
}
|
||||
/**
|
||||
@ -2845,14 +2816,10 @@ class ExpressService extends Service {
|
||||
const orderExpressModel = this.ctx.model && this.ctx.model.OrderExpress;
|
||||
if (orderExpressModel && allOrderIds.length > 0) {
|
||||
try {
|
||||
// 强制同仓校验:读取运单状态必须同时限定订单ID与仓库ID,禁止跨仓串读
|
||||
const statusCheckWarehouseId = Number(options && options.warehouse_id)
|
||||
|| this.getCurrentWarehouseId();
|
||||
const successRows = await orderExpressModel.findAll({
|
||||
where: {
|
||||
order_id: { [this.app.Sequelize.Op.in]: allOrderIds },
|
||||
status: 1,
|
||||
warehouse_id: statusCheckWarehouseId,
|
||||
},
|
||||
attributes: [ 'order_id' ],
|
||||
raw: true,
|
||||
|
||||
@ -601,76 +601,6 @@ class ExpressPlatformService extends MainService {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 取号回写前兜底校验:比对订单主表当前快递编码与本次取号请求的快递编码。
|
||||
*
|
||||
* 取号请求为外部 HTTP 调用且耗时较长,期间订单快递可能被并发修改;
|
||||
* 此处只做告警记录,不阻断回写,用于事后定位编码错位问题。
|
||||
*
|
||||
* @param {Object} params 校验入参。
|
||||
* @param {string} params.traceId 本次取号链路标识。
|
||||
* @param {Array<Object>} params.successUpdates 即将回写的成功取号项列表。
|
||||
* @param {string} [params.requestExpressCode] 本次取号请求使用的快递编码。
|
||||
* @param {Object} [params.transaction] 回写事务对象。
|
||||
* @return {Promise<void>} 无返回值。
|
||||
*/
|
||||
async warnExpressCodeMismatch(params = {}) {
|
||||
const {
|
||||
traceId,
|
||||
successUpdates,
|
||||
requestExpressCode,
|
||||
transaction,
|
||||
} = params;
|
||||
const updates = Array.isArray(successUpdates) ? successUpdates : [];
|
||||
const requestCode = String(requestExpressCode || '').trim();
|
||||
if (!requestCode || updates.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
const firstWarehouseId = Number(updates[0] && updates[0].warehouse_id) || 0;
|
||||
if (!firstWarehouseId) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const orderModel = await this.service.systems.express.getWaybillAsyncOrderDeliveryModel(firstWarehouseId);
|
||||
const orderIds = updates
|
||||
.map(item => Number(item && item.order_id))
|
||||
.filter(v => Number.isFinite(v) && v > 0);
|
||||
if (orderIds.length === 0) {
|
||||
return;
|
||||
}
|
||||
const rows = await orderModel.findAll({
|
||||
attributes: [ 'id', 'logistics_code' ],
|
||||
where: { id: orderIds },
|
||||
transaction,
|
||||
raw: true,
|
||||
});
|
||||
const currentCodeMap = new Map(
|
||||
(Array.isArray(rows) ? rows : [])
|
||||
.map(row => [ Number(row && row.id) || 0, String(row && row.logistics_code || '').trim() ])
|
||||
);
|
||||
for (const item of updates) {
|
||||
const orderId = Number(item && item.order_id) || 0;
|
||||
const currentCode = currentCodeMap.get(orderId) || '';
|
||||
if (currentCode && currentCode !== requestCode) {
|
||||
this.ctx.logger.error('[expressPlatform.polyapi] 回写前快递编码不一致告警', {
|
||||
traceId,
|
||||
order_id: orderId,
|
||||
request_express_code: requestCode,
|
||||
current_logistics_code: currentCode,
|
||||
});
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
// 兜底校验失败不影响回写主流程
|
||||
this.ctx.logger.warn('[expressPlatform.polyapi] 回写前快递编码校验异常,跳过', {
|
||||
traceId,
|
||||
error: error && error.message ? error.message : `${error}`,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 从 orders 数据中提取失败订单清理所需的基本字段。
|
||||
*
|
||||
@ -700,18 +630,11 @@ class ExpressPlatformService extends MainService {
|
||||
}
|
||||
|
||||
/**
|
||||
* 菠萝派(PolyAPI)平台取号接口。
|
||||
*
|
||||
* 流程:查询已分配运单号 → 调用平台字典接口 → 按平台编码构造订单载荷并调用
|
||||
* Differ.JH.Logistics.PostOrder 取号 → 逐条校验结果 → 事务回写运单号与快递编码。
|
||||
* 回写前会兜底校验主表当前快递编码与本次取号接口编码是否一致,不一致仅告警。
|
||||
*
|
||||
* @param {Object} [data={}] 平台业务入参。
|
||||
* @param {Object} [data.matchedPlatform] 匹配到的快递平台配置。
|
||||
* @param {Object} [data.listByWarehousePlatformCode] 当前仓库平台快递接口配置。
|
||||
* @param {Array} [data.orders] 待取号订单列表(含 order_delivery 与 business_key)。
|
||||
* @return {Promise<void>} 无返回值;内部完成回写与日志,失败时抛出异常。
|
||||
*/
|
||||
* 菠萝派数据处理接口。
|
||||
*
|
||||
* @param {Object} [data={}] 平台业务入参。
|
||||
* @return {Promise<never>} 当前暂未实现,直接抛出异常。
|
||||
*/
|
||||
async polyapi(data = {}) {
|
||||
const { matchedPlatform, listByWarehousePlatformCode, orders } = data;
|
||||
const traceId = this.buildExpressPlatformTraceId(data);
|
||||
@ -762,23 +685,16 @@ class ExpressPlatformService extends MainService {
|
||||
orderCount: orderIdList.length,
|
||||
orderIds: orderIdList.slice(0, 50),
|
||||
});
|
||||
// 强制同仓校验:读取已分配运单必须同时限定订单ID与仓库ID,禁止跨仓串读
|
||||
const allocatedWarehouseId = Number(listByWarehousePlatformCode && listByWarehousePlatformCode.warehouse_id)
|
||||
|| Number(this.ctx && this.ctx.user && this.ctx.user.store_id)
|
||||
|| 0;
|
||||
const allocatedWaybillRows = allocatedWarehouseId > 0
|
||||
? await orderExpressModel.findAll({
|
||||
attributes: [ 'order_id', 'business_key', 'waybill_code' ],
|
||||
where: {
|
||||
order_id: {
|
||||
[Op.in]: orderIdList,
|
||||
},
|
||||
warehouse_id: allocatedWarehouseId,
|
||||
const allocatedWaybillRows = await orderExpressModel.findAll({
|
||||
attributes: [ 'order_id', 'business_key', 'waybill_code' ],
|
||||
where: {
|
||||
order_id: {
|
||||
[Op.in]: orderIdList,
|
||||
},
|
||||
order: [[ 'id', 'ASC' ]],
|
||||
raw: true,
|
||||
})
|
||||
: [];
|
||||
},
|
||||
order: [[ 'id', 'ASC' ]],
|
||||
raw: true,
|
||||
});
|
||||
|
||||
this.ctx.logger.info('[expressPlatform.polyapi] 查询已分配快递号后', {
|
||||
traceId,
|
||||
@ -1648,15 +1564,6 @@ class ExpressPlatformService extends MainService {
|
||||
// 与 createWaybillCode 回写事务一致,避免 AB-BA 死锁
|
||||
await this.lockAndDeductWaybillSettlement(settlementRelationMap, storeWarehouseModel, transaction);
|
||||
|
||||
// 回写前兜底校验:主表当前快递编码与本次取号接口编码不一致时告警,
|
||||
// 防止取号期间订单快递被并发修改导致回写编码错位
|
||||
await this.warnExpressCodeMismatch({
|
||||
traceId,
|
||||
successUpdates,
|
||||
requestExpressCode: listByWarehousePlatformCode && listByWarehousePlatformCode.sys_express_code,
|
||||
transaction,
|
||||
});
|
||||
|
||||
for (const item of successUpdates) {
|
||||
const warehouseId = Number(item.warehouse_id) || 0;
|
||||
const orderId = Number(item.order_id) || 0;
|
||||
@ -1854,13 +1761,6 @@ class ExpressPlatformService extends MainService {
|
||||
.map(item => String(item || '').trim())
|
||||
.filter(Boolean)
|
||||
: [];
|
||||
// tid 优先取订单表 oaid_order_source_code,为空/空字符串时兜底到原逻辑
|
||||
const oaidOrderSourceCodes = orderDelivery && orderDelivery.oaid_order_source_code
|
||||
? String(orderDelivery.oaid_order_source_code)
|
||||
.split(',')
|
||||
.map(item => String(item || '').trim())
|
||||
.filter(Boolean)
|
||||
: [];
|
||||
const recipientMobile = orderDelivery && (orderDelivery.mobile || orderDelivery.tel) || '';
|
||||
const orderDeliveryOaid = orderDelivery && orderDelivery.oaid ? String(orderDelivery.oaid).trim() : '';
|
||||
const oaidTooLong = orderDeliveryOaid.indexOf('-') !== -1 || orderDeliveryOaid.length > 128;
|
||||
@ -1906,11 +1806,9 @@ class ExpressPlatformService extends MainService {
|
||||
phone: recipientMobile,
|
||||
oaid: oaidTooLong ? '' : orderDeliveryOaid,
|
||||
caid: oaidTooLong ? orderDeliveryOaid : '',
|
||||
tid: oaidOrderSourceCodes.length > 0
|
||||
? oaidOrderSourceCodes[0]
|
||||
: sourceOrderCodes.length > 0
|
||||
? sourceOrderCodes[0]
|
||||
: orderDelivery && orderDelivery.delivery_order_code || '',
|
||||
tid: sourceOrderCodes.length > 0
|
||||
? sourceOrderCodes[0]
|
||||
: orderDelivery && orderDelivery.delivery_order_code || '',
|
||||
},
|
||||
user_id: listByWarehousePlatformCode.shop && listByWarehousePlatformCode.shop.owner_id || 0,
|
||||
notify_extend_info: normalizedExtData,
|
||||
|
||||
@ -1177,7 +1177,7 @@ class InboundDirectLogService extends Service {
|
||||
}
|
||||
|
||||
// 回写收货单和收货明细的入库状态(绑定模式:按 receiving_detail_id 优先扣减)
|
||||
await this._syncReceivingStorageStatus({ entryItemIds, transaction, entryOrderId: eo.id });
|
||||
await this._syncReceivingStorageStatus({ entryItemIds, transaction });
|
||||
|
||||
// 非绑定模式剩余导入量:按 stock_id 匹配绑定收货单明细占用(绑定模式优先,剩余兜底)
|
||||
await this._applyReceivingStockOccupancy({ entryOrder: eo, directLogs, transaction });
|
||||
@ -1392,53 +1392,16 @@ class InboundDirectLogService extends Service {
|
||||
return lines;
|
||||
}
|
||||
|
||||
/**
|
||||
* 组装 entryorder.confirm 业务报文(与奇门 taobao.qimen.entryorder.confirm 同层级)。
|
||||
* 返回 { entryOrder, orderLines },不包含外层 request 包装,
|
||||
* 字段与取值逻辑以奇门分支为唯一基准,奇门与 OpenAPI 回传共用。
|
||||
* @param {Object} entryOrder 入库单对象
|
||||
* @param {Array<Object>} orderLines 入库明细行数组
|
||||
* @param {Object} [options] 可选配置
|
||||
* @param {string} [options.outBizCode] 外部业务编码,缺省时自动生成 DIRECT_INBOUND_时间戳
|
||||
* @param {boolean} [options.isFin=true] 是否最终确认(confirmType 0=最终 / 1=部分,status FULFILLED / PARTFULFILLED)
|
||||
* @param {string} [options.remark] 备注
|
||||
* @return {{ entryOrder: Object, orderLines: Array<Object> }} 组装后的业务报文
|
||||
*/
|
||||
buildEntryOrderConfirmRequest(entryOrder, orderLines, options = {}) {
|
||||
const { app } = this;
|
||||
const { outBizCode, isFin = true, remark } = options;
|
||||
|
||||
return {
|
||||
entryOrder: {
|
||||
entryOrderCode: entryOrder.entry_order_code,
|
||||
ownerCode: entryOrder.qimen_owner_code || '',
|
||||
warehouseCode: entryOrder.qimen_warehouse_code || '',
|
||||
entryOrderId: entryOrder.id,
|
||||
entryOrderType: entryOrder.order_type,
|
||||
outBizCode: outBizCode || `DIRECT_INBOUND_${Date.now()}`,
|
||||
confirmType: isFin ? 0 : 1,
|
||||
status: isFin ? 'FULFILLED' : 'PARTFULFILLED',
|
||||
freight: 0,
|
||||
operateTime: app.formatDate(new Date()),
|
||||
remark: remark || '',
|
||||
},
|
||||
orderLines,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* OpenAPI 回传:查询 ApiApp 回调地址并 POST 回传。
|
||||
* 报文体与奇门同层级({ request: { entryOrder, orderLines } },外层 request 由发送端自动包裹),
|
||||
* 与奇门分支共用 buildEntryOrderConfirmRequest 组装。
|
||||
* @param {Object} entryOrder 入库单
|
||||
* @param {Object} [options] 可选配置
|
||||
* @param {Object} options.request 奇门同层级业务报文 { entryOrder, orderLines }(由 buildEntryOrderConfirmRequest 组装)
|
||||
* @param {boolean} [options.throwOnError=false] 失败时是否向外抛出异常
|
||||
* @return {Promise<Object|null>} 返回回传结果 { success, error?, statusCode?, body? },异常时返回 null
|
||||
*/
|
||||
async _sendOpenApiCallback(entryOrder, options = {}) {
|
||||
const { ctx, app } = this;
|
||||
const { request, throwOnError = false } = options;
|
||||
const { throwOnError = false } = options;
|
||||
|
||||
try {
|
||||
const storeWarehouse = await ctx.model.StoreWarehouse.findOne({
|
||||
@ -1486,19 +1449,30 @@ class InboundDirectLogService extends Service {
|
||||
return null;
|
||||
}
|
||||
|
||||
const callbackData = {
|
||||
entryOrderId: entryOrder.id,
|
||||
entryOrderCode: entryOrder.entry_order_code,
|
||||
completedAt: new Date().toISOString(),
|
||||
inboundType: 'direct',
|
||||
};
|
||||
|
||||
console.log('[quickInbound] _sendOpenApiCallback 发送前:', {
|
||||
entryOrderId: entryOrder.id,
|
||||
callbackUrl: apiApp.callback_url,
|
||||
appKey: apiApp.self_app_key,
|
||||
request,
|
||||
callbackData,
|
||||
});
|
||||
|
||||
const result = await ctx.service.openapi.callback.sendWithRetry({
|
||||
callbackUrl: apiApp.callback_url,
|
||||
appKey: apiApp.self_app_key,
|
||||
selfAppSecret: apiApp.self_app_secret || '',
|
||||
event: 'entryorder.confirm',
|
||||
request,
|
||||
event: 'entry_order_direct_inbound_completed',
|
||||
data: callbackData,
|
||||
metadata: {
|
||||
source: 'inbound_direct_log',
|
||||
entryOrderId: entryOrder.id,
|
||||
},
|
||||
});
|
||||
|
||||
console.log('[quickInbound] _sendOpenApiCallback 响应:', {
|
||||
@ -1592,11 +1566,22 @@ class InboundDirectLogService extends Service {
|
||||
// 3. 构造 queryData 并发请求(事务外)
|
||||
if (sourceType === 'QM') {
|
||||
const queryData = {
|
||||
request: this.buildEntryOrderConfirmRequest(entryOrder, orderLines, {
|
||||
outBizCode,
|
||||
remark,
|
||||
isFin,
|
||||
}),
|
||||
request: {
|
||||
entryOrder: {
|
||||
entryOrderCode: entryOrder.entry_order_code,
|
||||
ownerCode: entryOrder.qimen_owner_code || '',
|
||||
warehouseCode: entryOrder.qimen_warehouse_code || '',
|
||||
entryOrderId: entryOrder.id,
|
||||
entryOrderType: entryOrder.order_type,
|
||||
outBizCode: outBizCode || `DIRECT_INBOUND_${Date.now()}`,
|
||||
confirmType: isFin ? 0 : 1,
|
||||
status: isFin ? 'FULFILLED' : 'PARTFULFILLED',
|
||||
freight: 0,
|
||||
operateTime: app.formatDate(new Date()),
|
||||
remark: remark || '',
|
||||
},
|
||||
orderLines,
|
||||
},
|
||||
};
|
||||
|
||||
console.log('[qimenEntrySync] 奇门请求发送前:', {
|
||||
@ -1682,14 +1667,7 @@ class InboundDirectLogService extends Service {
|
||||
|
||||
let apiResult;
|
||||
try {
|
||||
apiResult = await this._sendOpenApiCallback(entryOrder, {
|
||||
throwOnError: true,
|
||||
request: this.buildEntryOrderConfirmRequest(entryOrder, orderLines, {
|
||||
outBizCode,
|
||||
remark,
|
||||
isFin,
|
||||
}),
|
||||
});
|
||||
apiResult = await this._sendOpenApiCallback(entryOrder, { throwOnError: true });
|
||||
} catch (err) {
|
||||
apiResult = { success: false, error: err.message };
|
||||
}
|
||||
@ -1751,10 +1729,9 @@ class InboundDirectLogService extends Service {
|
||||
* @param {Object} params 参数
|
||||
* @param {number[]} params.entryItemIds 当前入库单的所有明细 ID 列表
|
||||
* @param {Object} params.transaction Sequelize 事务对象
|
||||
* @param {number} [params.entryOrderId] 入库单 ID(用于同步数量台账)
|
||||
* @return {Promise<void>}
|
||||
*/
|
||||
async _syncReceivingStorageStatus({ entryItemIds, transaction, entryOrderId = null }) {
|
||||
async _syncReceivingStorageStatus({ entryItemIds, transaction }) {
|
||||
const { ctx, app } = this;
|
||||
|
||||
// 查询所有 committed 状态的绑定记录(从 InboundDirectLog 中筛选有 receiving_detail_id 的记录)
|
||||
@ -1798,7 +1775,6 @@ class InboundDirectLogService extends Service {
|
||||
|
||||
// 逐条计算并更新收货明细
|
||||
const receivingIdSet = new Set();
|
||||
const ledgerQuantityMap = new Map();
|
||||
for (const detail of details) {
|
||||
const storedQuantity = detailQuantityMap.get(detail.id) || 0;
|
||||
const actualQuantity = Number(detail.actual_quantity) || 0;
|
||||
@ -1819,12 +1795,6 @@ class InboundDirectLogService extends Service {
|
||||
transaction,
|
||||
}
|
||||
);
|
||||
|
||||
// 台账覆盖条目:绑定模式对收货明细为直接覆写语义
|
||||
ledgerQuantityMap.set(detail.id, {
|
||||
receivingId: Number(detail.receiving_id),
|
||||
quantity: storedQuantity,
|
||||
});
|
||||
}
|
||||
|
||||
// 按收货单汇总,更新 wms_receiving.storage_status
|
||||
@ -1877,15 +1847,6 @@ class InboundDirectLogService extends Service {
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
// 同步数量台账:绑定模式按 committed 汇总量覆写对应明细条目(保持台账与 stored_quantity 一致)
|
||||
if (entryOrderId && ledgerQuantityMap.size > 0) {
|
||||
await ctx.service.systems.receivingEntryMatch.setLedgerAllocation({
|
||||
entryOrderId,
|
||||
detailQuantityMap: ledgerQuantityMap,
|
||||
transaction,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@ -1946,7 +1907,6 @@ class InboundDirectLogService extends Service {
|
||||
receivingDetailRows: boundDetails,
|
||||
stockInboundQtyMap,
|
||||
transaction,
|
||||
entryOrderId: entryOrder.id,
|
||||
});
|
||||
|
||||
ctx.logger.info(
|
||||
|
||||
@ -1,578 +0,0 @@
|
||||
// app/service/systems/intercept_auto_confirm.js
|
||||
'use strict';
|
||||
|
||||
const MainService = require('../main');
|
||||
|
||||
// 允许确认拦截(更新为 intercepted_at_warehouse)的前置拦截状态白名单:
|
||||
// 拦截发起中(requested/requesting/intercepting)与历史遗留值 intercepted。
|
||||
// 其余状态一律不允许确认拦截,防止并发修改导致误更新。
|
||||
const CONFIRMABLE_INTERCEPT_STATUSES = Object.freeze([ 'requested', 'requesting', 'intercepting', 'intercepted' ]);
|
||||
|
||||
// 自动确认扫描命中的拦截状态:仅请求拦截(requested)
|
||||
const AUTO_CONFIRM_INTERCEPT_STATUS = 'requested';
|
||||
// 自动确认扫描要求的面单打印状态:未打印
|
||||
const AUTO_CONFIRM_PRINT_STATUS = 'none';
|
||||
// 拦截时间超时阈值(小时):intercept_time 超过 12 小时自动确认
|
||||
const INTERCEPT_TIME_TIMEOUT_HOURS = 12;
|
||||
// 创建时间超时阈值(小时):create_at 超过 36 小时自动确认
|
||||
const CREATE_AT_TIMEOUT_HOURS = 36;
|
||||
// 拦截时间超时阈值(毫秒),供口径镜像函数使用
|
||||
const INTERCEPT_TIME_TIMEOUT_MS = INTERCEPT_TIME_TIMEOUT_HOURS * 60 * 60 * 1000;
|
||||
// 创建时间超时阈值(毫秒),供口径镜像函数使用
|
||||
const CREATE_AT_TIMEOUT_MS = CREATE_AT_TIMEOUT_HOURS * 60 * 60 * 1000;
|
||||
// 单批扫描数量上限(分页扫描,避免单批过大)
|
||||
const SCAN_BATCH_SIZE = 100;
|
||||
// 单批确认数量上限(批量确认,避免单批过大)
|
||||
const CONFIRM_BATCH_SIZE = 100;
|
||||
// 仓库当前表分表名匹配模式:wms_order_delivery_{warehouseId}(不含 history/dispatch/outsourced)
|
||||
const CURRENT_SHARD_TABLE_PATTERN = /^wms_order_delivery_(\d+)$/;
|
||||
// 定时任务自动确认的操作人(无用户上下文)
|
||||
const AUTO_CONFIRM_OPERATOR = Object.freeze({ id: null, name: '系统' });
|
||||
|
||||
/**
|
||||
* 将任意时间值转换为毫秒时间戳,无法解析时返回 null。
|
||||
*
|
||||
* @param {*} value 时间值(Date / 日期字符串 / 数字)。
|
||||
* @return {number|null} 毫秒时间戳或 null。
|
||||
*/
|
||||
function toTimestamp(value) {
|
||||
if (value === null || value === undefined || value === '') {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (value instanceof Date) {
|
||||
const time = value.getTime();
|
||||
return Number.isFinite(time) ? time : null;
|
||||
}
|
||||
|
||||
if (typeof value === 'number') {
|
||||
return Number.isFinite(value) ? value : null;
|
||||
}
|
||||
|
||||
const parsed = Date.parse(String(value));
|
||||
return Number.isFinite(parsed) ? parsed : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 自动库内拦截确定服务。
|
||||
*
|
||||
* 背景:订单发起拦截(intercept_status='requested')后若人工迟迟未做「库内拦截确定」,
|
||||
* 订单会长期停留在拦截发起中。本服务定时扫描待处理表(current 分表),对
|
||||
* 「intercept_status='requested' 且 print_status='none'(面单未打印)」的订单,
|
||||
* 满足以下任一条件时自动执行库内拦截确定:
|
||||
* - intercept_time 超过 12 小时(NULL 自然不命中,无需特判);
|
||||
* - create_at 超过 36 小时。
|
||||
*
|
||||
* 本服务同时提供 confirmInterceptForOrderIds 作为库内拦截确定的内部实现,
|
||||
* systemMethods/order/recheckOrder.js 的 confirmIntercept 出口复用该方法,
|
||||
* 定时任务同样复用,保证两条链路行为一致。
|
||||
*/
|
||||
class InterceptAutoConfirmService extends MainService {
|
||||
/**
|
||||
* 在当前调用内临时注入 ctx.user 上下文,并在结束后恢复。
|
||||
*
|
||||
* 用于复用依赖登录上下文的既有 service 能力(如储位取消分配读取 ctx.user.store_id),
|
||||
* 避免扩大影响范围。
|
||||
*
|
||||
* @param {Object} patchUser 需要覆盖的用户上下文字段。
|
||||
* @param {Function} callback 业务回调。
|
||||
* @return {Promise<any>} 回调执行结果。
|
||||
*/
|
||||
async withPatchedCtxUser(patchUser, callback) {
|
||||
const { ctx } = this;
|
||||
const originUser = ctx.user;
|
||||
const safeOriginUser = originUser && typeof originUser === 'object' ? originUser : {};
|
||||
const safePatchUser = patchUser && typeof patchUser === 'object' ? patchUser : {};
|
||||
ctx.user = {
|
||||
...safeOriginUser,
|
||||
...safePatchUser,
|
||||
};
|
||||
|
||||
try {
|
||||
return await callback();
|
||||
} finally {
|
||||
ctx.user = originUser;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 枚举库内全部仓库的当前订单分表(wms_order_delivery_{warehouseId})对应的仓库ID。
|
||||
*
|
||||
* 通过 INFORMATION_SCHEMA 枚举真实存在的物理分表,比查询 wms_warehouse 更可靠:
|
||||
* 避免仓库配置表与物理分表不一致(如已建表未配置、已停用仓库残留分表)导致的漏扫;
|
||||
* history/dispatch/outsourced 等表位通过表名正则过滤,仅保留 current 表位。
|
||||
*
|
||||
* @return {Promise<number[]>} 仓库ID列表。
|
||||
*/
|
||||
async listCurrentWarehouseIds() {
|
||||
const { ctx } = this;
|
||||
const rows = await ctx.model.query(
|
||||
'SELECT TABLE_NAME AS tableName'
|
||||
+ ' FROM INFORMATION_SCHEMA.TABLES'
|
||||
+ ' WHERE TABLE_SCHEMA = DATABASE()'
|
||||
+ ' AND TABLE_NAME LIKE \'wms_order_delivery\\_%\''
|
||||
+ ' ORDER BY TABLE_NAME',
|
||||
{ type: ctx.model.QueryTypes.SELECT }
|
||||
);
|
||||
|
||||
const warehouseIds = [];
|
||||
for (const row of (Array.isArray(rows) ? rows : [])) {
|
||||
const tableName = String(row.tableName || row.TABLE_NAME || '').trim();
|
||||
const matched = CURRENT_SHARD_TABLE_PATTERN.exec(tableName);
|
||||
if (!matched) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const warehouseId = Number(matched[1]);
|
||||
if (Number.isInteger(warehouseId) && warehouseId > 0) {
|
||||
warehouseIds.push(warehouseId);
|
||||
}
|
||||
}
|
||||
|
||||
return Array.from(new Set(warehouseIds));
|
||||
}
|
||||
|
||||
/**
|
||||
* 构造自动确认候选订单的 SQL 过滤条件(不含 warehouse_id 与 id 分页条件)。
|
||||
*
|
||||
* 口径:
|
||||
* - intercept_status = 'requested'(请求拦截);
|
||||
* - print_status = 'none'(面单未打印);
|
||||
* - 满足任一超时条件:intercept_time 超过 12 小时,或 create_at 超过 36 小时;
|
||||
* 时间比较使用数据库侧 NOW()/DATE_SUB,避免应用与数据库时钟偏差;
|
||||
* intercept_time 为 NULL 时小于比较自然不命中,无需特判。
|
||||
*
|
||||
* @return {string} SQL 过滤条件片段。
|
||||
*/
|
||||
buildCandidateWhereSql() {
|
||||
return `intercept_status = '${AUTO_CONFIRM_INTERCEPT_STATUS}'`
|
||||
+ ` AND print_status = '${AUTO_CONFIRM_PRINT_STATUS}'`
|
||||
+ ' AND ('
|
||||
+ ` intercept_time < DATE_SUB(NOW(), INTERVAL ${INTERCEPT_TIME_TIMEOUT_HOURS} HOUR)`
|
||||
+ ` OR create_at < DATE_SUB(NOW(), INTERVAL ${CREATE_AT_TIMEOUT_HOURS} HOUR)`
|
||||
+ ' )';
|
||||
}
|
||||
|
||||
/**
|
||||
* 候选订单口径镜像函数:判断单行是否命中自动确认条件(12h/36h 口径)。
|
||||
*
|
||||
* 与 buildCandidateWhereSql 的 SQL 口径保持一致,供单元测试验证边界语义;
|
||||
* 生产扫描以 SQL 为准。
|
||||
*
|
||||
* @param {Object} fields 订单行字段。
|
||||
* @param {string} [fields.interceptStatus] 拦截状态。
|
||||
* @param {string} [fields.printStatus] 面单打印状态。
|
||||
* @param {Date|string|number|null} [fields.interceptTime] 拦截时间(可空)。
|
||||
* @param {Date|string|number|null} [fields.createAt] 创建时间。
|
||||
* @param {Date} [now=new Date()] 当前时间基准。
|
||||
* @return {boolean} 是否命中自动确认条件。
|
||||
*/
|
||||
matchesAutoConfirmCriteria(fields = {}, now = new Date()) {
|
||||
const row = fields && typeof fields === 'object' ? fields : {};
|
||||
const interceptStatus = String(row.interceptStatus ?? '').trim();
|
||||
const printStatus = String(row.printStatus ?? '').trim();
|
||||
const nowMs = now instanceof Date ? now.getTime() : toTimestamp(now);
|
||||
|
||||
if (interceptStatus !== AUTO_CONFIRM_INTERCEPT_STATUS || printStatus !== AUTO_CONFIRM_PRINT_STATUS) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const interceptMs = toTimestamp(row.interceptTime);
|
||||
if (interceptMs !== null && interceptMs < nowMs - INTERCEPT_TIME_TIMEOUT_MS) {
|
||||
return true;
|
||||
}
|
||||
|
||||
const createMs = toTimestamp(row.createAt);
|
||||
if (createMs !== null && createMs < nowMs - CREATE_AT_TIMEOUT_MS) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析并校验仓库当前订单分表名。
|
||||
*
|
||||
* @param {number|string} warehouseId 仓库ID。
|
||||
* @return {string} 可直接拼接到 SQL 的表名(仅含字母数字下划线)。
|
||||
*/
|
||||
resolveCurrentTableName(warehouseId) {
|
||||
const normalizedWarehouseId = Number(warehouseId);
|
||||
if (!Number.isInteger(normalizedWarehouseId) || normalizedWarehouseId <= 0) {
|
||||
throw new Error(`非法仓库ID: ${warehouseId}`);
|
||||
}
|
||||
|
||||
const factory = this.ctx.model && this.ctx.model.OrderDeliveryFactory;
|
||||
if (!factory || typeof factory.generateTableName !== 'function') {
|
||||
throw new Error('订单工厂不可用');
|
||||
}
|
||||
|
||||
const tableName = String(factory.generateTableName(normalizedWarehouseId, 'current') || '').trim();
|
||||
if (!/^[a-zA-Z0-9_]+$/.test(tableName)) {
|
||||
throw new Error(`订单表名不合法: ${tableName}`);
|
||||
}
|
||||
|
||||
return tableName;
|
||||
}
|
||||
|
||||
/**
|
||||
* 分页扫描指定仓库的自动确认候选订单ID(id 游标翻页,避免 OFFSET 深翻页)。
|
||||
*
|
||||
* @param {number|string} warehouseId 仓库ID。
|
||||
* @param {number} [batchSize=SCAN_BATCH_SIZE] 单批扫描数量。
|
||||
* @return {Promise<number[]>} 命中条件的订单ID列表。
|
||||
*/
|
||||
async scanCandidateOrderIds(warehouseId, batchSize = SCAN_BATCH_SIZE) {
|
||||
const { ctx } = this;
|
||||
const tableName = this.resolveCurrentTableName(warehouseId);
|
||||
const candidateWhereSql = this.buildCandidateWhereSql();
|
||||
const normalizedBatchSize = Math.max(Number.parseInt(batchSize, 10) || SCAN_BATCH_SIZE, 1);
|
||||
const orderIds = [];
|
||||
let lastId = 0;
|
||||
|
||||
for (;;) {
|
||||
const rows = await ctx.model.query(
|
||||
'SELECT id'
|
||||
+ ` FROM ${tableName}`
|
||||
+ ' WHERE warehouse_id = :warehouseId'
|
||||
+ ` AND ${candidateWhereSql}`
|
||||
+ ' AND id > :lastId'
|
||||
+ ' ORDER BY id ASC'
|
||||
+ ' LIMIT :limit',
|
||||
{
|
||||
replacements: {
|
||||
warehouseId: Number(warehouseId),
|
||||
lastId,
|
||||
limit: normalizedBatchSize,
|
||||
},
|
||||
type: ctx.model.QueryTypes.SELECT,
|
||||
}
|
||||
);
|
||||
|
||||
const pageRows = Array.isArray(rows) ? rows : [];
|
||||
if (pageRows.length === 0) {
|
||||
break;
|
||||
}
|
||||
|
||||
let pageMaxId = lastId;
|
||||
for (const row of pageRows) {
|
||||
const orderId = Number(row && row.id || 0);
|
||||
if (Number.isFinite(orderId) && orderId > 0) {
|
||||
orderIds.push(orderId);
|
||||
pageMaxId = orderId;
|
||||
}
|
||||
}
|
||||
|
||||
// 防死循环:本页没有解析出任何有效订单ID,或已不足一页,结束翻页
|
||||
if (pageMaxId <= lastId || pageRows.length < normalizedBatchSize) {
|
||||
break;
|
||||
}
|
||||
|
||||
lastId = pageMaxId;
|
||||
}
|
||||
|
||||
return orderIds;
|
||||
}
|
||||
|
||||
/**
|
||||
* 库内拦截确定内部实现:按订单ID列表批量确认仓库拦截(不依赖用户上下文)。
|
||||
*
|
||||
* systemMethods 出口 confirmIntercept 与定时任务统一复用本方法,保证行为一致。
|
||||
* 支持部分失败:未找到的订单与处理失败的订单记录在 failed 列表并返回失败原因,
|
||||
* 其余订单继续处理;每单失败不影响其他订单。
|
||||
*
|
||||
* 每个订单的拦截处理:
|
||||
* 1. 更新订单:intercept_status=intercepted_at_warehouse、step=4、outbound_status=fin,
|
||||
* where 同时限定拦截状态白名单防并发误更新;
|
||||
* **不写 intercept_time**(该字段恒为「最近一次发起拦截的通知时刻」,库内确定拦截不覆盖,
|
||||
* 见 app/lib/intercept_time.js;库内确定拦截时刻以配送表 dispath_time 为准)
|
||||
* 2. 同步更新运单表:is_intercept='Y'、is_back='Y'
|
||||
* 3. 释放储位分配(cancelAllocateStorage 拦截模式,临时注入仓库上下文)
|
||||
* 4. 释放订单锁(lock_status='none')
|
||||
* 5. 写入操作日志(ORDER_INTERCEPT_CONFIRM)
|
||||
* 全部订单处理完后,按成功订单ID汇总批量创建售后工单 + 通知快递群。
|
||||
* 运单标记、储位释放、锁释放、工单创建、日志写入失败均不影响主流程。
|
||||
*
|
||||
* @param {Object} params 参数。
|
||||
* @param {number[]} params.orderIds 订单ID列表。
|
||||
* @param {number|string} params.warehouseId 仓库ID。
|
||||
* @param {Object} [params.operator] 操作人信息({ id, name })。
|
||||
* @return {Promise<Object>} 批量拦截结果,包含 success/failed 列表与 success_count/failed_count 计数。
|
||||
*/
|
||||
async confirmInterceptForOrderIds(params = {}) {
|
||||
const { ctx } = this;
|
||||
const requestParams = params && typeof params === 'object' ? params : {};
|
||||
const orderIds = Array.isArray(requestParams.orderIds)
|
||||
? Array.from(new Set(
|
||||
requestParams.orderIds.map(value => Number(value)).filter(value => Number.isFinite(value) && value > 0)
|
||||
))
|
||||
: [];
|
||||
const warehouseId = requestParams.warehouseId ?? null;
|
||||
const operator = requestParams.operator && typeof requestParams.operator === 'object'
|
||||
? requestParams.operator
|
||||
: { ...AUTO_CONFIRM_OPERATOR };
|
||||
|
||||
if (orderIds.length === 0) {
|
||||
throw new Error('订单ID不能为空');
|
||||
}
|
||||
|
||||
if (warehouseId === null || warehouseId === undefined || warehouseId === '') {
|
||||
throw new Error('缺少仓库上下文 store_id');
|
||||
}
|
||||
|
||||
const { Op } = ctx.app.Sequelize;
|
||||
const orderModel = await ctx.model.OrderDeliveryFactory.getCurrentModel(warehouseId);
|
||||
const orderRows = await orderModel.findAll({
|
||||
where: {
|
||||
id: { [Op.in]: orderIds },
|
||||
warehouse_id: warehouseId,
|
||||
},
|
||||
attributes: [ 'id', 'delivery_order_code', 'pre_delivery_order_code', 'intercept_status', 'wave_no' ],
|
||||
raw: true,
|
||||
});
|
||||
|
||||
const orderMap = new Map();
|
||||
for (const row of orderRows) {
|
||||
orderMap.set(Number(row.id), row);
|
||||
}
|
||||
|
||||
const successOrders = [];
|
||||
const failedOrders = [];
|
||||
const successOrderIds = [];
|
||||
|
||||
for (const orderId of orderIds) {
|
||||
const order = orderMap.get(orderId);
|
||||
|
||||
if (!order) {
|
||||
failedOrders.push({ order_id: orderId, reason: '未找到对应订单' });
|
||||
continue;
|
||||
}
|
||||
|
||||
const orderNo = String(order.delivery_order_code || order.pre_delivery_order_code || '').trim();
|
||||
const interceptStatus = String(order.intercept_status || '').trim();
|
||||
|
||||
// 未发起拦截(none/空)的订单直接跳过,不参与确认拦截处理
|
||||
if (interceptStatus === '' || interceptStatus === 'none') {
|
||||
continue;
|
||||
}
|
||||
|
||||
// 已确认拦截的订单跳过,避免重复执行副作用(释放储位/工单/日志等)
|
||||
if (interceptStatus === 'intercepted_at_warehouse') {
|
||||
failedOrders.push({
|
||||
order_id: orderId,
|
||||
delivery_order_code: orderNo,
|
||||
reason: '订单已确认拦截',
|
||||
});
|
||||
continue;
|
||||
}
|
||||
|
||||
// 仅拦截发起中与历史值 intercepted 允许确认,其余状态不允许确认拦截
|
||||
if (!CONFIRMABLE_INTERCEPT_STATUSES.includes(interceptStatus)) {
|
||||
failedOrders.push({
|
||||
order_id: orderId,
|
||||
delivery_order_code: orderNo,
|
||||
reason: `订单拦截状态不允许确认拦截: ${interceptStatus}`,
|
||||
});
|
||||
continue;
|
||||
}
|
||||
|
||||
try {
|
||||
const now = new Date();
|
||||
// 库内确定拦截不写 intercept_time(不覆盖通知拦截时刻),库内确定时刻以配送表 dispath_time 为准
|
||||
const updateValues = {
|
||||
intercept_status: 'intercepted_at_warehouse',
|
||||
step: 4,
|
||||
outbound_status: 'fin',
|
||||
updated_at: now,
|
||||
};
|
||||
const updateResult = await orderModel.update(updateValues, {
|
||||
where: {
|
||||
id: orderId,
|
||||
warehouse_id: warehouseId,
|
||||
// 数据库层再次限定拦截状态,防止查询后状态被并发修改导致误更新
|
||||
intercept_status: { [Op.in]: CONFIRMABLE_INTERCEPT_STATUSES },
|
||||
},
|
||||
});
|
||||
const affectedRows = Array.isArray(updateResult) ? Number(updateResult[0] || 0) : Number(updateResult || 0);
|
||||
|
||||
if (affectedRows <= 0) {
|
||||
throw new Error('拦截状态更新失败,请稍后重试');
|
||||
}
|
||||
|
||||
// 同步更新运单表:标记拦截 + 退回(库内拦截确认,货物在库内需退回)
|
||||
try {
|
||||
await ctx.model.OrderExpress.update(
|
||||
{ is_intercept: 'Y', is_back: 'Y' },
|
||||
{ where: { order_id: orderId, warehouse_id: warehouseId } }
|
||||
);
|
||||
} catch (expressErr) {
|
||||
ctx.logger.warn(
|
||||
`[interceptAutoConfirm.confirmInterceptForOrderIds] 更新运单拦截/退回标记失败, orderId=${orderId}, error=${expressErr.message}`
|
||||
);
|
||||
}
|
||||
|
||||
// 拦截成功后释放储位分配(拦截模式:库存移入拦截锁定,不归还可用)
|
||||
try {
|
||||
await this.withPatchedCtxUser({ store_id: warehouseId }, () => (
|
||||
ctx.service.systems.orderStorageAllocation.cancelAllocateStorage({
|
||||
order_ids: [ orderId ],
|
||||
interceptMode: true,
|
||||
})
|
||||
));
|
||||
} catch (allocErr) {
|
||||
ctx.logger.warn(
|
||||
`[interceptAutoConfirm.confirmInterceptForOrderIds] 释放储位分配失败,不影响拦截, orderId=${orderId}, error=${allocErr.message}`
|
||||
);
|
||||
}
|
||||
|
||||
// 拦截成功后释放订单锁
|
||||
try {
|
||||
await orderModel.update(
|
||||
{ lock_status: 'none', updated_at: now },
|
||||
{ where: { id: orderId, warehouse_id: warehouseId } }
|
||||
);
|
||||
} catch (lockErr) {
|
||||
ctx.logger.warn(
|
||||
`[interceptAutoConfirm.confirmInterceptForOrderIds] 释放锁失败,不影响拦截, orderId=${orderId}, error=${lockErr.message}`
|
||||
);
|
||||
}
|
||||
|
||||
// 写入操作日志(失败不影响主流程)
|
||||
try {
|
||||
await ctx.service.systems.operationLog.createOperationLog({
|
||||
businessType: 'order',
|
||||
businessId: orderId,
|
||||
operationCode: 'ORDER_INTERCEPT_CONFIRM',
|
||||
operator,
|
||||
extras: {
|
||||
warehouseId,
|
||||
orderId,
|
||||
orderNo,
|
||||
previousInterceptStatus: String(order.intercept_status || '').trim(),
|
||||
newInterceptStatus: 'intercepted_at_warehouse',
|
||||
},
|
||||
beforeChanges: null,
|
||||
});
|
||||
} catch (logErr) {
|
||||
ctx.logger.warn(
|
||||
`[interceptAutoConfirm.confirmInterceptForOrderIds] 写入操作日志失败,不影响业务, orderId=${orderId}, error=${logErr.message}`
|
||||
);
|
||||
}
|
||||
|
||||
successOrders.push({
|
||||
order_id: orderId,
|
||||
order_no: orderNo,
|
||||
intercept_status: 'intercepted_at_warehouse',
|
||||
updated_at: now,
|
||||
});
|
||||
successOrderIds.push(orderId);
|
||||
} catch (error) {
|
||||
ctx.logger.warn(
|
||||
`[interceptAutoConfirm.confirmInterceptForOrderIds] 确认拦截失败, orderId=${orderId}, error=${error.message}`
|
||||
);
|
||||
failedOrders.push({
|
||||
order_id: orderId,
|
||||
delivery_order_code: orderNo,
|
||||
reason: `确认拦截失败: ${error.message}`,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// 创建售后工单 + 通知快递群(成功订单 ID 汇总统一调用,失败不影响主流程)
|
||||
if (successOrderIds.length > 0) {
|
||||
try {
|
||||
await ctx.service.systems.afterSale.createInterceptWorkOrdersAndNotify({
|
||||
orderIds: successOrderIds,
|
||||
warehouseId,
|
||||
creatorLabel: operator.name || '系统',
|
||||
});
|
||||
} catch (workOrderErr) {
|
||||
ctx.logger.warn(
|
||||
`[interceptAutoConfirm.confirmInterceptForOrderIds] 创建工单/通知失败, orderIds=${successOrderIds.join(',')}, error=${workOrderErr.message}`
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
success: successOrders,
|
||||
failed: failedOrders,
|
||||
success_count: successOrders.length,
|
||||
failed_count: failedOrders.length,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 自动库内拦截确定主入口:枚举仓库 → 分页扫描候选订单 → 分批确认拦截。
|
||||
*
|
||||
* 单个仓库扫描/确认失败仅记录日志与 detail.error,不影响其他仓库;
|
||||
* 全部动作失败不阻断下轮执行(异常上抛由定时任务捕获记录)。
|
||||
*
|
||||
* @param {Object} [options={}] 执行选项。
|
||||
* @param {number} [options.scanBatchSize=SCAN_BATCH_SIZE] 单批扫描数量。
|
||||
* @param {number} [options.confirmBatchSize=CONFIRM_BATCH_SIZE] 单批确认数量。
|
||||
* @return {Promise<Object>} 执行结果汇总,包含 warehouse_count/candidate_count/confirmed_count/
|
||||
* failed_count/warehouse_ids/duration_ms/details。
|
||||
*/
|
||||
async runAutoConfirm(options = {}) {
|
||||
const { ctx } = this;
|
||||
const startedAt = Date.now();
|
||||
const requestOptions = options && typeof options === 'object' ? options : {};
|
||||
const scanBatchSize = Math.max(Number.parseInt(requestOptions.scanBatchSize, 10) || SCAN_BATCH_SIZE, 1);
|
||||
const confirmBatchSize = Math.max(Number.parseInt(requestOptions.confirmBatchSize, 10) || CONFIRM_BATCH_SIZE, 1);
|
||||
const warehouseIds = await this.listCurrentWarehouseIds();
|
||||
|
||||
const details = [];
|
||||
let candidateCount = 0;
|
||||
let confirmedCount = 0;
|
||||
let failedCount = 0;
|
||||
|
||||
for (const warehouseId of warehouseIds) {
|
||||
const detail = {
|
||||
warehouse_id: warehouseId,
|
||||
candidate_count: 0,
|
||||
confirmed_count: 0,
|
||||
failed_count: 0,
|
||||
error: null,
|
||||
};
|
||||
|
||||
try {
|
||||
const candidateIds = await this.scanCandidateOrderIds(warehouseId, scanBatchSize);
|
||||
detail.candidate_count = candidateIds.length;
|
||||
|
||||
for (let offset = 0; offset < candidateIds.length; offset += confirmBatchSize) {
|
||||
const batchIds = candidateIds.slice(offset, offset + confirmBatchSize);
|
||||
const batchResult = await this.confirmInterceptForOrderIds({
|
||||
orderIds: batchIds,
|
||||
warehouseId,
|
||||
operator: AUTO_CONFIRM_OPERATOR,
|
||||
});
|
||||
|
||||
detail.confirmed_count += batchResult.success_count;
|
||||
detail.failed_count += batchResult.failed_count;
|
||||
}
|
||||
} catch (error) {
|
||||
detail.error = String(error && error.message ? error.message : error);
|
||||
ctx.logger.warn(
|
||||
`[interceptAutoConfirm.runAutoConfirm] 仓库 ${warehouseId} 处理失败,跳过: ${detail.error}`
|
||||
);
|
||||
}
|
||||
|
||||
candidateCount += detail.candidate_count;
|
||||
confirmedCount += detail.confirmed_count;
|
||||
failedCount += detail.failed_count;
|
||||
details.push(detail);
|
||||
}
|
||||
|
||||
return {
|
||||
warehouse_count: warehouseIds.length,
|
||||
candidate_count: candidateCount,
|
||||
confirmed_count: confirmedCount,
|
||||
failed_count: failedCount,
|
||||
warehouse_ids: warehouseIds,
|
||||
duration_ms: Date.now() - startedAt,
|
||||
details,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = InterceptAutoConfirmService;
|
||||
@ -135,18 +135,7 @@ function resolveOrderWaybillCodesInternal(orderRow = {}, waybillCodes = []) {
|
||||
return fallbackCode ? [ fallbackCode ] : [];
|
||||
}
|
||||
|
||||
/**
|
||||
* 按订单ID批量构建运单号映射。
|
||||
*
|
||||
* 强制同仓校验:读取 wms_order_express 必须同时带订单ID与仓库ID,
|
||||
* 禁止仅凭订单ID跨仓串读运单号;仓库ID缺失时返回空映射。
|
||||
*
|
||||
* @param {Object} service 订单异步服务实例。
|
||||
* @param {Array<number>} orderIds 订单ID列表。
|
||||
* @param {number|string|null|undefined} warehouseId 仓库ID,必须为订单所属仓库。
|
||||
* @return {Promise<Map<number, string[]>>} order_id 到运单号数组的映射。
|
||||
*/
|
||||
async function buildOrderWaybillCodeMapInternal(service, orderIds = [], warehouseId = null) {
|
||||
async function buildOrderWaybillCodeMapInternal(service, orderIds = []) {
|
||||
const normalizedOrderIds = Array.isArray(orderIds)
|
||||
? orderIds.map(orderId => Number(orderId)).filter(orderId => Number.isFinite(orderId) && orderId > 0)
|
||||
: [];
|
||||
@ -157,20 +146,12 @@ async function buildOrderWaybillCodeMapInternal(service, orderIds = [], warehous
|
||||
return waybillCodeMap;
|
||||
}
|
||||
|
||||
const normalizedWarehouseId = warehouseId !== null && warehouseId !== undefined && warehouseId !== ''
|
||||
? Number(warehouseId)
|
||||
: 0;
|
||||
if (!Number.isFinite(normalizedWarehouseId) || normalizedWarehouseId <= 0) {
|
||||
return waybillCodeMap;
|
||||
}
|
||||
|
||||
const { Op } = service.app.Sequelize;
|
||||
const expressRows = await orderExpressModel.findAll({
|
||||
where: {
|
||||
order_id: {
|
||||
[Op.in]: normalizedOrderIds,
|
||||
},
|
||||
warehouse_id: normalizedWarehouseId,
|
||||
},
|
||||
attributes: [ 'order_id', 'business_key', 'waybill_code' ],
|
||||
order: [[ 'id', 'ASC' ]],
|
||||
@ -481,7 +462,7 @@ async function syncManualOrdersInternal(service, groupedOrder = {}, context = {}
|
||||
}
|
||||
}
|
||||
|
||||
const waybillCodeMap = await buildOrderWaybillCodeMapInternal(service, orderIds, warehouseId);
|
||||
const waybillCodeMap = await buildOrderWaybillCodeMapInternal(service, orderIds);
|
||||
|
||||
// dispatch前最终去重,防止同一orderId在列表中重复导致并发双扣
|
||||
const uniqueOrderIds = [ ...new Set(orderIds) ];
|
||||
@ -857,307 +838,6 @@ async function processManualOrderInternal(service, orderModel, orderItemsModel,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 按订单货主合约反查可用的 OpenAPI 应用配置(ApiApp)。
|
||||
*
|
||||
* 口径与入库单回调 _sendOpenApiCallback 对齐:
|
||||
* 先按 store_id + warehouse_id + auth_status=2 查 StoreWarehouse 授权关系,
|
||||
* 再按 contract_id 查启用(is_enabled=1)且配置了 callback_url 的 ApiApp。
|
||||
* 未找到授权关系 / 无可用 ApiApp 配置时返回 null 并记录 warn 日志。
|
||||
*
|
||||
* @param {Object} service 订单异步服务实例。
|
||||
* @param {number|string} storeId 货主 ID。
|
||||
* @param {number|string} warehouseId 仓库 ID。
|
||||
* @return {Promise<Object|null>} { appKey, selfAppSecret, callbackUrl },未找到可用配置时返回 null。
|
||||
*/
|
||||
async function resolveOpenApiAppByStoreInternal(service, storeId, warehouseId) {
|
||||
const normalizedStoreId = Number(storeId || 0);
|
||||
const normalizedWarehouseId = Number(warehouseId || 0);
|
||||
const storeWarehouseModel = service.ctx.model && service.ctx.model.StoreWarehouse;
|
||||
const apiAppModel = service.ctx.model && service.ctx.model.ApiApp;
|
||||
|
||||
if (!Number.isFinite(normalizedStoreId) || normalizedStoreId <= 0
|
||||
|| !Number.isFinite(normalizedWarehouseId) || normalizedWarehouseId <= 0
|
||||
|| !storeWarehouseModel || typeof storeWarehouseModel.findOne !== 'function'
|
||||
|| !apiAppModel || typeof apiAppModel.findOne !== 'function') {
|
||||
service.ctx.logger.warn('[OrderAsyncService.resolveOpenApiAppByStore] 缺少货主/仓库上下文或数据模型不可用,无法反查 ApiApp', {
|
||||
storeId: normalizedStoreId,
|
||||
warehouseId: normalizedWarehouseId,
|
||||
});
|
||||
return null;
|
||||
}
|
||||
|
||||
const { Op } = service.app.Sequelize;
|
||||
|
||||
const storeWarehouse = await storeWarehouseModel.findOne({
|
||||
where: {
|
||||
store_id: normalizedStoreId,
|
||||
warehouse_id: normalizedWarehouseId,
|
||||
auth_status: 2,
|
||||
},
|
||||
attributes: [ 'id' ],
|
||||
raw: true,
|
||||
});
|
||||
|
||||
if (!storeWarehouse) {
|
||||
service.ctx.logger.warn(`[OrderAsyncService] OpenAPI回调:未找到授权关系 storeId=${normalizedStoreId} warehouseId=${normalizedWarehouseId}`);
|
||||
return null;
|
||||
}
|
||||
|
||||
const apiApp = await apiAppModel.findOne({
|
||||
where: {
|
||||
contract_id: storeWarehouse.id,
|
||||
is_enabled: 1,
|
||||
callback_url: {
|
||||
[Op.and]: [
|
||||
{ [Op.ne]: null },
|
||||
{ [Op.ne]: '' },
|
||||
],
|
||||
},
|
||||
},
|
||||
attributes: [ 'self_app_key', 'self_app_secret', 'callback_url' ],
|
||||
raw: true,
|
||||
});
|
||||
|
||||
if (!apiApp || !apiApp.callback_url) {
|
||||
service.ctx.logger.warn(`[OrderAsyncService] OpenAPI回调:未找到有效ApiApp配置 storeId=${normalizedStoreId} warehouseId=${normalizedWarehouseId} contractId=${storeWarehouse.id}`);
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
appKey: String(apiApp.self_app_key || '').trim(),
|
||||
selfAppSecret: String(apiApp.self_app_secret || '').trim(),
|
||||
callbackUrl: String(apiApp.callback_url || '').trim(),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 将 API 渠道订单标记为同步失败(sync_status='error' + 待处理异常)。
|
||||
*
|
||||
* 与奇门渠道回传失败口径一致:失败不扣减库存、不置 'fin',
|
||||
* 订单可被重新派发重试(分发前过滤仅跳过 'fin')。
|
||||
*
|
||||
* @param {Object} service 订单异步服务实例。
|
||||
* @param {Object} orderModel 订单主模型。
|
||||
* @param {number} orderId 订单 ID。
|
||||
* @param {number} warehouseId 仓库 ID。
|
||||
* @param {string} message 失败原因。
|
||||
* @return {Promise<void>} 无返回值,写库失败仅记录 error 日志。
|
||||
*/
|
||||
async function markApiSyncFailedInternal(service, orderModel, orderId, warehouseId, message) {
|
||||
try {
|
||||
await orderModel.update({
|
||||
sync_status: 'error',
|
||||
}, {
|
||||
where: {
|
||||
id: orderId,
|
||||
warehouse_id: warehouseId,
|
||||
},
|
||||
});
|
||||
} catch (error) {
|
||||
service.ctx.logger.error(`[OrderAsyncService.markApiSyncFailed] 更新 sync_status=error 失败 orderId=${orderId}`, {
|
||||
message: String((error && error.message) || error || '').trim(),
|
||||
});
|
||||
}
|
||||
|
||||
try {
|
||||
await markPendingExceptionInternal(service, orderModel, orderId, warehouseId, message);
|
||||
} catch (error) {
|
||||
service.ctx.logger.error(`[OrderAsyncService.markApiSyncFailed] 标记待处理异常失败 orderId=${orderId}`, {
|
||||
message: String((error && error.message) || error || '').trim(),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* API 渠道单订单同步:先回传 deliveryorder.confirm,回调成功后才本地扣减库存并置已同步。
|
||||
*
|
||||
* 与奇门渠道(processQmOrderInternal)口径对齐:
|
||||
* ① 组装与奇门 taobao.qimen.deliveryorder.confirm 完全一致的 request 报文
|
||||
* (缺奇门货主编码等组装数据时直接失败);
|
||||
* ② 解析发送用 appKey:context.appKey 非空优先,缺失时按订单货主合约反查 ApiApp
|
||||
* (同一批次按货主缓存,N 单 / M 货主 → 2M 次查询,无 N+1);
|
||||
* ③ 发送回调(sendByAppKey,内部最多 4 次尝试),成功才算平台已确认;
|
||||
* ④ 回调成功 → 扣减库存 + sync_status='fin';失败/异常 → sync_status='error'
|
||||
* + 待处理异常,不扣减库存,可重新派发;
|
||||
* 订单/回调配置缺失(无 store_id、无「启用且 callback_url 非空」的 ApiApp)按失败处理,
|
||||
* 不再静默跳过,避免订单在平台未确认时被置为已同步。
|
||||
*
|
||||
* @param {Object} service 订单异步服务实例。
|
||||
* @param {Object} orderModel 订单主模型。
|
||||
* @param {Object} orderItemsModel 订单明细模型。
|
||||
* @param {number} orderId 订单 ID。
|
||||
* @param {number} warehouseId 仓库 ID。
|
||||
* @param {Object} orderRow 订单主表记录。
|
||||
* @param {Array<Object>} orderItems 订单明细记录。
|
||||
* @param {Object} [context] 同步上下文(appKey 可选)。
|
||||
* @param {Array<string>} [waybillCodes] 运单号列表。
|
||||
* @param {Map<number, Object>} [appByStoreCache] 货主 → ApiApp 反查结果缓存(批内共享)。
|
||||
* @return {Promise<Object>} 单订单同步结果(status / message / error 等)。
|
||||
*/
|
||||
async function processApiOrderInternal(service, orderModel, orderItemsModel, orderId, warehouseId, orderRow, orderItems, context = {}, waybillCodes = [], appByStoreCache = new Map()) {
|
||||
if (!orderRow) {
|
||||
return {
|
||||
order_id: orderId,
|
||||
status: 'failed',
|
||||
message: '发货单不存在',
|
||||
};
|
||||
}
|
||||
|
||||
const deliveryOrderCode = String(orderRow.delivery_order_code || '').trim();
|
||||
|
||||
/**
|
||||
* 统一失败出口:写 sync_status='error' + 待处理异常后返回失败结果。
|
||||
* @param {string} message 失败原因。
|
||||
* @param {Object} [extra] 附加返回字段。
|
||||
* @return {Promise<Object>} 单订单失败结果。
|
||||
*/
|
||||
const failSync = async (message, extra = {}) => {
|
||||
await markApiSyncFailedInternal(service, orderModel, orderId, warehouseId, message);
|
||||
|
||||
return {
|
||||
order_id: orderId,
|
||||
delivery_order_code: deliveryOrderCode,
|
||||
status: 'failed',
|
||||
message,
|
||||
error: message,
|
||||
...extra,
|
||||
};
|
||||
};
|
||||
|
||||
try {
|
||||
// ① 组装回调报文
|
||||
const requestData = await buildQimenDeliveryOrderConfirmDataInternal(service, orderRow, orderItems, {
|
||||
...context,
|
||||
packageExpressCode: Array.isArray(waybillCodes) ? waybillCodes[0] : '',
|
||||
packageExpressCodes: waybillCodes,
|
||||
});
|
||||
|
||||
if (!requestData || !requestData.ownerCode || !requestData.request) {
|
||||
service.ctx.logger.warn(`[OrderAsyncService.processApiOrder] 回调报文组装数据缺失 orderId=${orderId}`, {
|
||||
deliveryOrderCode,
|
||||
ownerCode: requestData && requestData.ownerCode,
|
||||
});
|
||||
|
||||
return await failSync('发货单缺少奇门货主编码');
|
||||
}
|
||||
|
||||
// ② 解析发送用 appKey
|
||||
const callbackService = service.ctx.service.openapi && service.ctx.service.openapi.callback;
|
||||
if (!callbackService || typeof callbackService.sendByAppKey !== 'function') {
|
||||
return await failSync('OpenAPI 回调服务未初始化');
|
||||
}
|
||||
|
||||
let resolvedAppKey = String(context.appKey || '').trim();
|
||||
if (!resolvedAppKey) {
|
||||
const storeId = Number(orderRow.store_id) || 0;
|
||||
if (storeId <= 0) {
|
||||
service.ctx.logger.warn(`[OrderAsyncService.processApiOrder] 订单缺少货主 store_id orderId=${orderId}`, {
|
||||
deliveryOrderCode,
|
||||
});
|
||||
|
||||
return await failSync('发货单缺少货主 store_id,无法解析回传用 appKey');
|
||||
}
|
||||
|
||||
if (!appByStoreCache.has(storeId)) {
|
||||
appByStoreCache.set(storeId, await resolveOpenApiAppByStoreInternal(service, storeId, warehouseId));
|
||||
}
|
||||
|
||||
const resolvedApp = appByStoreCache.get(storeId);
|
||||
resolvedAppKey = String(resolvedApp && resolvedApp.appKey || '').trim();
|
||||
|
||||
if (!resolvedAppKey) {
|
||||
service.ctx.logger.warn(`[OrderAsyncService.processApiOrder] 货主无可用 ApiApp 配置 orderId=${orderId} storeId=${storeId}`, {
|
||||
deliveryOrderCode,
|
||||
});
|
||||
|
||||
return await failSync('货主未配置可用的 OpenAPI 回调(wms_api_app 启用且 callback_url 非空)');
|
||||
}
|
||||
}
|
||||
|
||||
// ③ 发送回调:回调成功才继续本地出库扣减
|
||||
let callbackResult = null;
|
||||
try {
|
||||
callbackResult = await callbackService.sendByAppKey({
|
||||
appKey: resolvedAppKey,
|
||||
event: 'deliveryorder.confirm',
|
||||
request: requestData.request,
|
||||
});
|
||||
} catch (error) {
|
||||
const message = `OpenAPI 回调确认异常: ${String((error && error.message) || error || '').trim() || '未知错误'}`;
|
||||
|
||||
service.ctx.logger.error(`[OrderAsyncService.processApiOrder] deliveryorder.confirm 回调异常 orderId=${orderId}`, {
|
||||
appKey: resolvedAppKey,
|
||||
deliveryOrderCode,
|
||||
message,
|
||||
});
|
||||
|
||||
return await failSync(message);
|
||||
}
|
||||
|
||||
if (!callbackResult || callbackResult.success !== true) {
|
||||
const callbackRetryCount = Number(callbackResult && callbackResult.retryCount) || 0;
|
||||
const message = `OpenAPI 回调确认失败: ${String((callbackResult && callbackResult.error) || '回调失败').trim()}`;
|
||||
|
||||
service.ctx.logger.error(`[OrderAsyncService.processApiOrder] deliveryorder.confirm 回调失败 orderId=${orderId}`, {
|
||||
appKey: resolvedAppKey,
|
||||
deliveryOrderCode,
|
||||
retryCount: callbackRetryCount,
|
||||
error: callbackResult && callbackResult.error,
|
||||
});
|
||||
|
||||
return await failSync(message, {
|
||||
callback_retry_count: callbackRetryCount,
|
||||
});
|
||||
}
|
||||
|
||||
service.ctx.logger.info(`[OrderAsyncService.processApiOrder] deliveryorder.confirm 回调成功,开始本地出库扣减 orderId=${orderId}`, {
|
||||
appKey: resolvedAppKey,
|
||||
deliveryOrderCode,
|
||||
retryCount: Number(callbackResult.retryCount) || 0,
|
||||
});
|
||||
|
||||
// ④ 回调成功 → 扣减库存 + 置 sync_status='fin'
|
||||
const localSyncResult = await processLocalChannelOrderInternal(
|
||||
service,
|
||||
CREATE_CHANNEL_API,
|
||||
orderModel,
|
||||
orderItemsModel,
|
||||
orderId,
|
||||
warehouseId,
|
||||
orderRow
|
||||
);
|
||||
|
||||
return {
|
||||
...localSyncResult,
|
||||
callback_retry_count: Number(callbackResult.retryCount) || 0,
|
||||
};
|
||||
} catch (error) {
|
||||
const message = `API 渠道同步异常: ${String((error && error.message) || error || '').trim() || '未知错误'}`;
|
||||
|
||||
service.ctx.logger.error(`[OrderAsyncService.processApiOrder] 同步异常 orderId=${orderId}`, {
|
||||
deliveryOrderCode,
|
||||
message,
|
||||
});
|
||||
|
||||
return await failSync(message);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 本地渠道(MANUAL / API)订单同步收尾:
|
||||
* MANUAL:逐单锁定扣减库存并置 sync_status='fin';
|
||||
* API:逐单先回传 deliveryorder.confirm,回调成功后才扣减库存并置 'fin',
|
||||
* 回调失败/无可用回调配置则 sync_status='error' + 待处理异常(与奇门渠道口径一致),
|
||||
* 最后统计成功/失败数量返回。
|
||||
*
|
||||
* @param {Object} service 订单异步服务实例。
|
||||
* @param {string} createChannel 创建渠道(MANUAL / API)。
|
||||
* @param {Object} [groupedOrder] 分组后的订单(含 order_ids / order_count / orders)。
|
||||
* @param {Object} [context] 同步上下文(含 warehouseId / request_id;appKey 可选,缺失时按订单货主合约反查)。
|
||||
* @param {string} [syncTarget] 同步目标(internal / api)。
|
||||
* @return {Promise<Object>} 同步结果(含 success_count / failed_count / sync_results 等)。
|
||||
*/
|
||||
async function finalizeLocalChannelOrdersInternal(service, createChannel, groupedOrder = {}, context = {}, syncTarget = 'internal') {
|
||||
const orderIds = Array.isArray(groupedOrder.order_ids)
|
||||
? groupedOrder.order_ids.map(orderId => Number(orderId)).filter(orderId => Number.isFinite(orderId) && orderId > 0)
|
||||
@ -1235,28 +915,7 @@ async function finalizeLocalChannelOrdersInternal(service, createChannel, groupe
|
||||
}
|
||||
}
|
||||
|
||||
// 订单明细按 order_id 建索引,供逐单回调组装奇门报文复用(与 syncQmOrdersInternal 一致)
|
||||
const itemsByOrderId = new Map();
|
||||
for (const orderItem of Array.isArray(orderItemRows) ? orderItemRows : []) {
|
||||
const itemOrderId = Number(orderItem && orderItem.order_id);
|
||||
if (!Number.isFinite(itemOrderId) || itemOrderId <= 0) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!itemsByOrderId.has(itemOrderId)) {
|
||||
itemsByOrderId.set(itemOrderId, []);
|
||||
}
|
||||
|
||||
itemsByOrderId.get(itemOrderId).push(orderItem);
|
||||
}
|
||||
|
||||
// API 渠道:一次性批量取运单号 + 批内共享货主 appKey 反查缓存,
|
||||
// 供逐单「先回传 deliveryorder.confirm → 成功才扣减库存」复用(无逐单 N+1 查询)
|
||||
const isApiChannel = createChannel === CREATE_CHANNEL_API;
|
||||
const waybillCodeMap = isApiChannel
|
||||
? await buildOrderWaybillCodeMapInternal(service, orderIds, warehouseId)
|
||||
: new Map();
|
||||
const appByStoreCache = new Map();
|
||||
void orderItemRows;
|
||||
|
||||
// dispatch前最终去重,防止同一orderId在列表中重复导致并发双扣
|
||||
const uniqueOrderIds = [ ...new Set(orderIds) ];
|
||||
@ -1269,20 +928,6 @@ async function finalizeLocalChannelOrdersInternal(service, createChannel, groupe
|
||||
if (!dispathedOrderRow) {
|
||||
return { order_id: orderId, status: 'skipped', message: '订单已完成同步,跳过' };
|
||||
}
|
||||
if (isApiChannel) {
|
||||
return processApiOrderInternal(
|
||||
service,
|
||||
orderModel,
|
||||
orderItemsModel,
|
||||
orderId,
|
||||
warehouseId,
|
||||
dispathedOrderRow,
|
||||
itemsByOrderId.get(orderId) || [],
|
||||
context,
|
||||
waybillCodeMap.get(orderId) || [],
|
||||
appByStoreCache
|
||||
);
|
||||
}
|
||||
return processLocalChannelOrderInternal(
|
||||
service,
|
||||
createChannel,
|
||||
@ -1301,6 +946,39 @@ async function finalizeLocalChannelOrdersInternal(service, createChannel, groupe
|
||||
const failedCount = syncResults.filter(item => item.status === 'failed').length;
|
||||
const overallSuccess = failedCount === 0 && successCount === syncResults.length;
|
||||
|
||||
// 同步成功后触发 OpenAPI 回调通知(fire-and-forget,不阻塞主流程)
|
||||
if (createChannel === CREATE_CHANNEL_API && successCount > 0) {
|
||||
try {
|
||||
const callbackService = service.ctx.service.openapi && service.ctx.service.openapi.callback;
|
||||
|
||||
if (callbackService && typeof callbackService.sendByAppKey === 'function') {
|
||||
const appKey = String(context.appKey || '').trim();
|
||||
|
||||
if (appKey) {
|
||||
callbackService.sendByAppKey({
|
||||
appKey,
|
||||
event: 'order_completed',
|
||||
data: {
|
||||
orderIds,
|
||||
status: 'completed',
|
||||
successCount,
|
||||
failedCount,
|
||||
},
|
||||
metadata: {
|
||||
warehouseId,
|
||||
createChannel,
|
||||
syncTarget,
|
||||
},
|
||||
}).catch(err => {
|
||||
service.ctx.logger.warn(`[OrderAsyncService] OpenAPI 回调忽略失败: ${err.message}`);
|
||||
});
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
service.ctx.logger.warn(`[OrderAsyncService] 触发回调异常,不影响主流程: ${err.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
create_channel: createChannel,
|
||||
order_ids: orderIds,
|
||||
@ -1403,7 +1081,7 @@ function buildStockoutConfirmDataInternal(service, stockoutOrder, orderRow, stoc
|
||||
* 通知外部出库单确认结果(按出库单 source_type 分流)。
|
||||
*
|
||||
* - QM:奇门 taobao.qimen.stockout.confirm,flag=success 视为成功;
|
||||
* - API:OpenAPI 签名回调(event=stockout.confirm,报文为与奇门同层级的 request 节点);
|
||||
* - API:OpenAPI 签名回调(event=stockout_completed);
|
||||
* - 其他(WMS 等内部来源):无需通知外部,直接视为成功。
|
||||
*
|
||||
* @param {Object} service 服务实例
|
||||
@ -1462,11 +1140,19 @@ async function notifyStockoutExternalInternal(service, stockoutOrder, requestDat
|
||||
}
|
||||
|
||||
try {
|
||||
// requestData 即奇门 request 节点内容,OpenAPI 回调按同层级 request 发送
|
||||
const callbackResult = await callbackService.sendByAppKey({
|
||||
appKey,
|
||||
event: 'stockout.confirm',
|
||||
request: requestData,
|
||||
event: 'stockout_completed',
|
||||
data: {
|
||||
stockoutOrderCode: stockoutOrder.stockout_order_code,
|
||||
status: 'completed',
|
||||
...requestData,
|
||||
},
|
||||
metadata: {
|
||||
warehouseId: Number(stockoutOrder.warehouse_id) || 0,
|
||||
storeId: Number(stockoutOrder.store_id) || 0,
|
||||
sourceType,
|
||||
},
|
||||
});
|
||||
|
||||
if (callbackResult && callbackResult.success === true) {
|
||||
@ -1710,7 +1396,7 @@ async function processStockoutOrderInternal(service, orderModel, orderItemsModel
|
||||
raw: true,
|
||||
});
|
||||
|
||||
// 快递信息写回字段(回传成功落库):物流编码/名称 + 运单号列表(复数为准,单数为镜像)
|
||||
// 快递信息写回字段(回传成功落库):物流编码/名称 + 运单号列表
|
||||
const expressWriteback = {
|
||||
waybill_code: normalizedWaybillCodes[0] || '',
|
||||
waybill_codes: normalizedWaybillCodes,
|
||||
@ -1877,7 +1563,7 @@ async function syncStockoutOrdersInternal(service, groupedOrder = {}, context =
|
||||
}
|
||||
}
|
||||
|
||||
const waybillCodeMap = await buildOrderWaybillCodeMapInternal(service, orderIds, warehouseId);
|
||||
const waybillCodeMap = await buildOrderWaybillCodeMapInternal(service, orderIds);
|
||||
|
||||
const itemsByOrderId = new Map();
|
||||
for (const orderItem of Array.isArray(orderItemRows) ? orderItemRows : []) {
|
||||
@ -2713,7 +2399,7 @@ async function syncQmOrdersInternal(service, groupedOrder = {}, context = {}) {
|
||||
}
|
||||
}
|
||||
|
||||
const waybillCodeMap = await buildOrderWaybillCodeMapInternal(service, orderIds, warehouseId);
|
||||
const waybillCodeMap = await buildOrderWaybillCodeMapInternal(service, orderIds);
|
||||
|
||||
const itemsByOrderId = new Map();
|
||||
for (const orderItem of Array.isArray(orderItemRows) ? orderItemRows : []) {
|
||||
@ -2846,45 +2532,6 @@ class OrderAsyncService extends MainService {
|
||||
async syncStockoutOrders(groupedOrder = {}, context = {}) {
|
||||
return await syncStockoutOrdersInternal(this, groupedOrder, context);
|
||||
}
|
||||
|
||||
/**
|
||||
* 组装出库单确认回传报文(与奇门 request 节点同层级,OpenAPI 回调复用)。
|
||||
*
|
||||
* 供出库单转订单回传与出库单直出确认(storage.stockout.confirm)共用,
|
||||
* 避免两处各写一份报文结构导致漂移。
|
||||
*
|
||||
* @param {Object} stockoutOrder 出库单记录(模型实例或 raw 对象)。
|
||||
* @param {Object} orderRow 发货单记录(raw);直出确认无订单上下文时传空对象即可。
|
||||
* @param {Array} stockoutItems 出库单明细数组。
|
||||
* @param {Array<string>} [waybillCodes] 运单号列表。
|
||||
* @return {Object} 出库单确认回传请求体。
|
||||
*/
|
||||
buildStockoutConfirmRequest(stockoutOrder, orderRow, stockoutItems, waybillCodes = []) {
|
||||
return buildStockoutConfirmDataInternal(this, stockoutOrder, orderRow, stockoutItems, waybillCodes);
|
||||
}
|
||||
|
||||
/**
|
||||
* 按出库单 source_type 通知外部(QM→奇门,API→OpenAPI 回调,其他→无需通知直接成功)。
|
||||
*
|
||||
* @param {Object} stockoutOrder 出库单记录。
|
||||
* @param {Object} requestData 出库单确认回传请求体。
|
||||
* @param {Object} [context] 上下文(API 来源需传 appKey)。
|
||||
* @return {Promise<{success: boolean, message: string}>} 通知结果。
|
||||
*/
|
||||
async notifyStockoutExternal(stockoutOrder, requestData, context = {}) {
|
||||
return await notifyStockoutExternalInternal(this, stockoutOrder, requestData, context);
|
||||
}
|
||||
|
||||
/**
|
||||
* 按货主合约反查可用的 OpenAPI 应用配置(ApiApp),用于 API 来源出站回调。
|
||||
*
|
||||
* @param {number|string} storeId 货主 ID。
|
||||
* @param {number|string} warehouseId 仓库 ID。
|
||||
* @return {Promise<Object|null>} { appKey, selfAppSecret, callbackUrl },未找到时返回 null。
|
||||
*/
|
||||
async resolveOpenApiAppByStore(storeId, warehouseId) {
|
||||
return await resolveOpenApiAppByStoreInternal(this, storeId, warehouseId);
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = OrderAsyncService;
|
||||
|
||||
@ -305,21 +305,13 @@ class OrderDeliveryMigrationService extends MainService {
|
||||
/**
|
||||
* 构造配送表插入行。
|
||||
*
|
||||
* 写入配送表时追加 dispath_time(当前时间),用于记录订单迁移进配送表的时间;
|
||||
* 仅配送表写入该字段,源表数据不受影响。
|
||||
*
|
||||
* @param {Object} row 当前订单工作台数据。
|
||||
* @return {Object} 可写入配送表的数据。
|
||||
*/
|
||||
buildDispatchRow(row) {
|
||||
const payload = { ...(row || {}) };
|
||||
delete payload.dispatch_lane;
|
||||
|
||||
return {
|
||||
...payload,
|
||||
dispatch_lane: DISPATCH_LANE,
|
||||
dispath_time: new Date(),
|
||||
};
|
||||
return { ...payload, dispatch_lane: DISPATCH_LANE };
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@ -275,12 +275,8 @@ class OrderExpressService extends Service {
|
||||
|
||||
/**
|
||||
* 读取订单下有效快递记录。
|
||||
*
|
||||
* 强制同仓校验:读取 wms_order_express 必须同时带订单ID与仓库ID,
|
||||
* 禁止仅凭订单ID跨仓串读运单号;仓库ID缺失时直接抛业务错误拒绝读取。
|
||||
*
|
||||
* @param {number} orderId 订单ID。
|
||||
* @param {number|string|null|undefined} warehouseId 仓库ID,必须为订单所属仓库。
|
||||
* @param {number|string|null|undefined} warehouseId 仓库ID。
|
||||
* @return {Promise<Array<Object>>} 快递记录列表。
|
||||
*/
|
||||
async findValidOrderExpressRows(orderId, warehouseId) {
|
||||
@ -289,16 +285,15 @@ class OrderExpressService extends Service {
|
||||
throw this.createBusinessError('订单快递模型未初始化', 500);
|
||||
}
|
||||
|
||||
if (warehouseId === null || warehouseId === undefined || warehouseId === '') {
|
||||
throw this.createBusinessError('缺少仓库上下文,禁止读取订单运单记录', 400);
|
||||
}
|
||||
|
||||
const where = {
|
||||
order_id: orderId,
|
||||
delete_at: null,
|
||||
warehouse_id: warehouseId,
|
||||
};
|
||||
|
||||
if (warehouseId !== null && warehouseId !== undefined && warehouseId !== '') {
|
||||
where.warehouse_id = warehouseId;
|
||||
}
|
||||
|
||||
const rows = await orderExpressModel.findAll({
|
||||
where,
|
||||
attributes: [ 'id', 'order_id', 'waybill_code', 'weighing_weight' ],
|
||||
@ -343,7 +338,7 @@ class OrderExpressService extends Service {
|
||||
);
|
||||
}
|
||||
|
||||
// 先查运单表校验运单是否存在(强制同仓校验:订单ID + 仓库ID)
|
||||
// 先查运单表校验运单是否存在
|
||||
const orderExpressModel = this.ctx.model && this.ctx.model.OrderExpress;
|
||||
if (!orderExpressModel || typeof orderExpressModel.findOne !== 'function') {
|
||||
throw this.createBusinessError('运单模型未初始化', 500);
|
||||
@ -353,7 +348,6 @@ class OrderExpressService extends Service {
|
||||
where: {
|
||||
order_id: normalizedOrderId,
|
||||
delete_at: null,
|
||||
warehouse_id: warehouseId,
|
||||
},
|
||||
attributes: [ 'id', 'order_id', 'waybill_code', 'business_key' ],
|
||||
raw: true,
|
||||
@ -637,11 +631,9 @@ class OrderExpressService extends Service {
|
||||
}
|
||||
|
||||
const { Op } = this.app.Sequelize;
|
||||
// 强制同仓校验:批量更新称重重量必须同时限定订单ID与仓库ID
|
||||
const updateWhere = {
|
||||
order_id: { [Op.in]: orderIds },
|
||||
delete_at: null,
|
||||
warehouse_id: warehouseId,
|
||||
};
|
||||
|
||||
// 先验证匹配记录是否存在,避免 MySQL 因值未变返回 affected_rows=0 导致误判
|
||||
@ -717,12 +709,11 @@ class OrderExpressService extends Service {
|
||||
};
|
||||
}
|
||||
|
||||
// 查询指定订单下所有有效运单记录(强制同仓校验:订单ID + 仓库ID)
|
||||
// 查询指定订单下所有有效运单记录
|
||||
const expressRows = await orderExpressModel.findAll({
|
||||
where: {
|
||||
order_id: orderId,
|
||||
delete_at: null,
|
||||
warehouse_id: warehouseId,
|
||||
},
|
||||
attributes: [ 'business_key', 'weighing_weight', 'waybill_code' ],
|
||||
raw: true,
|
||||
@ -986,11 +977,9 @@ class OrderExpressService extends Service {
|
||||
}
|
||||
|
||||
const { Op } = this.app.Sequelize;
|
||||
// 强制同仓校验:批量更新称重重量必须同时限定订单ID与仓库ID
|
||||
const updateWhere = {
|
||||
order_id: { [Op.in]: orderIds },
|
||||
delete_at: null,
|
||||
warehouse_id: warehouseId,
|
||||
};
|
||||
|
||||
// 先验证匹配记录是否存在,避免 MySQL 因值未变返回 affected_rows=0 导致误判
|
||||
@ -1724,13 +1713,11 @@ class OrderExpressService extends Service {
|
||||
? { [Op.is]: null }
|
||||
: businessKey;
|
||||
|
||||
// 强制同仓校验:按订单ID批量查询运单必须同时限定仓库ID
|
||||
const expressRows = await orderExpressModel.findAll({
|
||||
where: {
|
||||
order_id: { [Op.in]: orderIds },
|
||||
business_key: businessKeyWhere,
|
||||
delete_at: null,
|
||||
warehouse_id: warehouseId,
|
||||
},
|
||||
attributes: [ 'id', 'order_id', 'waybill_code', 'business_key', 'package_material_id' ],
|
||||
raw: true,
|
||||
|
||||
@ -104,49 +104,28 @@ class OrderPackingService extends Service {
|
||||
}
|
||||
}
|
||||
|
||||
// 运单号筛选:通过 wms_order_express 表解析 order_id,再按 order_id 过滤(wms_pack_task.waybill_code 通常为空)。
|
||||
// 支持 {operator,value} 标准结构,value 支持字符串或字符串数组(多单号取并集):
|
||||
// - operator=contains/like:按下发单号模糊匹配 LIKE '%单号%'(通配符已转义),可命中 '主体-1-1-' 等分段单号;
|
||||
// - 其他(缺省/eq):完整单号等值 + 剥离 -1-1- 分段后缀主体等值 + 主体前缀 LIKE '主体-%',
|
||||
// 不落入 %短串% 模糊分支(保持「不完整短串不得命中订单」的业务约束)。
|
||||
// 运单号筛选:通过 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 = String(where.waybill_code?.operator || '').trim().toLowerCase();
|
||||
const waybillList = (Array.isArray(waybillValue) ? waybillValue : [ waybillValue ])
|
||||
.map(item => (item === undefined || item === null ? '' : String(item).trim()))
|
||||
.filter(Boolean);
|
||||
|
||||
if (waybillList.length > 0) {
|
||||
const isContainsWaybill = waybillOperator === 'contains' || waybillOperator === 'like';
|
||||
const waybillConditions = [];
|
||||
|
||||
for (const waybillCode of waybillList) {
|
||||
if (isContainsWaybill) {
|
||||
waybillConditions.push({
|
||||
waybill_code: { [Op.like]: `%${escapeLikeWildcards(waybillCode)}%` },
|
||||
});
|
||||
continue;
|
||||
}
|
||||
|
||||
// 剥离分段后缀得到主体运单号(JDX057941864338-1-1- → JDX057941864338)
|
||||
const baseWaybill = stripWaybillSegmentSuffix(waybillCode);
|
||||
const escapedBase = escapeLikeWildcards(baseWaybill);
|
||||
// 等值匹配集合:完整单号等值 + 主体单号等值 + 主体单号前缀段(主体相同、分段序号不同)
|
||||
waybillConditions.push({ waybill_code: waybillCode });
|
||||
if (baseWaybill !== waybillCode) {
|
||||
waybillConditions.push({ waybill_code: baseWaybill });
|
||||
}
|
||||
if (escapedBase) {
|
||||
waybillConditions.push({ waybill_code: { [Op.like]: `${escapedBase}-%` } });
|
||||
}
|
||||
}
|
||||
|
||||
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,
|
||||
};
|
||||
const expressRecords = await ctx.model.OrderExpress.findAll({
|
||||
where: {
|
||||
warehouse_id: warehouseId,
|
||||
delete_at: null,
|
||||
[Op.or]: waybillConditions,
|
||||
},
|
||||
where: expressWhere,
|
||||
attributes: [ 'order_id' ],
|
||||
raw: true,
|
||||
});
|
||||
@ -160,32 +139,11 @@ class OrderPackingService extends Service {
|
||||
}
|
||||
}
|
||||
|
||||
// 波次号筛选:支持 {operator,value} 标准结构,value 支持字符串或字符串数组(多值取并集)。
|
||||
// - operator=eq / in:精确匹配(单值等值,多值 Op.in);
|
||||
// - operator=ne:不等于;
|
||||
// - operator=contains / like 与缺省:模糊匹配 LIKE '%值%'(通配符已转义,缺省保持历史模糊行为)。
|
||||
// 波次号模糊匹配
|
||||
if (where.wave_no) {
|
||||
const waveNoValue = where.wave_no?.value ?? where.wave_no;
|
||||
const waveNoOperator = String(where.wave_no?.operator || '').trim().toLowerCase();
|
||||
const waveNoList = (Array.isArray(waveNoValue) ? waveNoValue : [ waveNoValue ])
|
||||
.map(item => (item === undefined || item === null ? '' : String(item).trim()))
|
||||
.filter(Boolean);
|
||||
|
||||
if (waveNoList.length > 0) {
|
||||
if (waveNoOperator === 'eq' || waveNoOperator === 'in') {
|
||||
queryWhere.wave_no = waveNoList.length === 1 ? waveNoList[0] : { [Op.in]: waveNoList };
|
||||
} else if (waveNoOperator === 'ne') {
|
||||
queryWhere.wave_no = { [Op.ne]: waveNoList[0] };
|
||||
} else if (waveNoList.length === 1) {
|
||||
queryWhere.wave_no = { [Op.like]: `%${escapeLikeWildcards(waveNoList[0])}%` };
|
||||
} else {
|
||||
const likeConditions = waveNoList.map(
|
||||
item => ({ wave_no: { [Op.like]: `%${escapeLikeWildcards(item)}%` } })
|
||||
);
|
||||
queryWhere[Op.and] = [ ...(queryWhere[Op.and] || []),
|
||||
{ [Op.or]: likeConditions },
|
||||
];
|
||||
}
|
||||
if (waveNoValue && String(waveNoValue).trim()) {
|
||||
queryWhere.wave_no = { [Op.like]: `%${String(waveNoValue).trim()}%` };
|
||||
}
|
||||
}
|
||||
|
||||
@ -439,9 +397,8 @@ 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 后过滤)。支持 {operator,value} 标准结构,value 支持字符串或数组:
|
||||
* operator=contains/like 时按 LIKE '%单号%' 模糊匹配(可命中分段单号);缺省/eq 时先剥离一单多件分段后缀、主体单号等值匹配 + 主体前缀匹配
|
||||
* @param {Object} [where.wave_no] 波次号。支持 {operator,value} 标准结构,value 支持字符串或数组:eq/in 精确、ne 不等、contains/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查;运单号先剥离分段后缀等值匹配,精确未命中且关键词长度≥4 时才降级模糊,短词禁止降级避免误命中)
|
||||
|
||||
@ -11,8 +11,7 @@ const MINUTE_MS = 60 * 1000;
|
||||
* 打包任务自动结束服务。
|
||||
* 扫描 wms_pack_task 未结束任务,按仓库配置的打包最大时长
|
||||
* (散单 single_order_pack_max_minutes / 团购 group_order_pack_max_minutes,单位分钟)
|
||||
* 判断是否超时,超时则将结束时间置为开始时间 + 上限时长并标记已完成,
|
||||
* 同时将该工作台关联摄像头的 OSD 叠加复位为「无任务」。
|
||||
* 判断是否超时,超时则将结束时间置为开始时间 + 上限时长并标记已完成。
|
||||
*/
|
||||
class PackTaskAutoFinishService extends MainService {
|
||||
/**
|
||||
@ -36,7 +35,7 @@ class PackTaskAutoFinishService extends MainService {
|
||||
status: { [Op.lt]: PACK_TASK_FINISHED_STATUS },
|
||||
start_time: { [Op.ne]: null },
|
||||
},
|
||||
attributes: [ 'id', 'warehouse_id', 'pack_mode', 'start_time', 'order_id', 'wave_id', 'workbench_id' ],
|
||||
attributes: [ 'id', 'warehouse_id', 'pack_mode', 'start_time', 'order_id', 'wave_id' ],
|
||||
});
|
||||
|
||||
if (tasks.length === 0) {
|
||||
@ -110,14 +109,6 @@ class PackTaskAutoFinishService extends MainService {
|
||||
});
|
||||
}
|
||||
|
||||
// 同步工作台 OSD:任务结束后复位为「无任务」(与 workbench._finishPack 语义一致,避免屏幕残留上一个任务文字)
|
||||
if (workbenchService && typeof workbenchService._resetPackOsd === 'function') {
|
||||
await workbenchService._resetPackOsd({
|
||||
warehouseId,
|
||||
workbenchId: Number(task.workbench_id || 0),
|
||||
});
|
||||
}
|
||||
|
||||
autoFinished += 1;
|
||||
|
||||
ctx.logger.info(
|
||||
|
||||
@ -1985,7 +1985,6 @@ class PickSystemService extends Service {
|
||||
// 订单 wave_id 清零、重建波次索引、回写波次统计,并移除任务订单关联
|
||||
const removedFromWaveOrderLogItems = [];
|
||||
const removedFromWaveOrderIds = [];
|
||||
const affectedWaveIdsForUnbind = [];
|
||||
if (skippedInterceptedOrders.length > 0 && taskSource !== 0) {
|
||||
const skippedOrderIds = skippedInterceptedOrders.map(item => item.order_id);
|
||||
const interceptOrderModel = await this.getOrderModel(warehouseId);
|
||||
@ -2008,7 +2007,6 @@ class PickSystemService extends Service {
|
||||
const affectedWaveIds = [ ...new Set(normalizedRemovableRows
|
||||
.map(row => Number(row && row.wave_id || 0))
|
||||
.filter(waveId => Number.isInteger(waveId) && waveId > 0)) ];
|
||||
affectedWaveIdsForUnbind.push(...affectedWaveIds);
|
||||
|
||||
if (normalizedRemovableRows.length > 0) {
|
||||
await interceptOrderModel.update({
|
||||
@ -2170,7 +2168,7 @@ class PickSystemService extends Service {
|
||||
await this.ctx.model.query(`
|
||||
UPDATE wms_wave_pick_task
|
||||
SET status = 2,
|
||||
finish_time = CASE WHEN finish_time IS NULL THEN NOW() ELSE finish_time END,
|
||||
finish_time = NOW(),
|
||||
start_time = CASE WHEN start_time IS NULL THEN NOW() ELSE start_time END,
|
||||
update_time = NOW()
|
||||
WHERE id = :taskId
|
||||
@ -2236,7 +2234,6 @@ class PickSystemService extends Service {
|
||||
operatorName,
|
||||
removedFromWaveOrderLogItems,
|
||||
removedFromWaveOrderIds,
|
||||
affectedWaveIds: affectedWaveIdsForUnbind,
|
||||
});
|
||||
return {
|
||||
task_id: taskId,
|
||||
@ -2453,7 +2450,7 @@ class PickSystemService extends Service {
|
||||
await ctx.model.query(`
|
||||
UPDATE wms_wave_pick_task
|
||||
SET status = 2,
|
||||
finish_time = CASE WHEN finish_time IS NULL THEN NOW() ELSE finish_time END,
|
||||
finish_time = NOW(),
|
||||
start_time = CASE WHEN start_time IS NULL THEN NOW() ELSE start_time END,
|
||||
update_time = NOW()
|
||||
WHERE id = :taskId
|
||||
@ -2522,7 +2519,6 @@ class PickSystemService extends Service {
|
||||
operatorName,
|
||||
removedFromWaveOrderLogItems,
|
||||
removedFromWaveOrderIds,
|
||||
affectedWaveIds: affectedWaveIdsForUnbind,
|
||||
});
|
||||
|
||||
// 写入 order_operation_log 拣货完成日志
|
||||
@ -2599,9 +2595,6 @@ class PickSystemService extends Service {
|
||||
const removedFromWaveOrderIds = Array.isArray(params && params.removedFromWaveOrderIds)
|
||||
? params.removedFromWaveOrderIds
|
||||
: [];
|
||||
const affectedWaveIds = Array.isArray(params && params.affectedWaveIds)
|
||||
? params.affectedWaveIds
|
||||
: [];
|
||||
|
||||
if (removedFromWaveOrderLogItems.length > 0) {
|
||||
try {
|
||||
@ -2652,28 +2645,6 @@ class PickSystemService extends Service {
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// 拦截订单被移出波次后,补触发打印完成解绑车核实:
|
||||
// 打印链路对含拦截订单的波次无法解绑(拦截订单不可打印),提交拣货移除拦截订单后重查一次,
|
||||
// 保证任务结束时车能被释放(不影响主流程)
|
||||
if (affectedWaveIds.length > 0) {
|
||||
try {
|
||||
const printService = this.ctx
|
||||
&& this.ctx.service
|
||||
&& this.ctx.service.systemMethods
|
||||
&& this.ctx.service.systemMethods.print;
|
||||
if (printService && typeof printService.tryUnbindCartAfterPrintComplete === 'function') {
|
||||
for (const waveId of [ ...new Set(affectedWaveIds) ]) {
|
||||
await printService.tryUnbindCartAfterPrintComplete(waveId, warehouseId);
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
this.ctx.logger.warn('[pick.wavePickTaskComplete] 移除拦截订单后补触发解绑车失败,不影响主流程', {
|
||||
error: e && e.message,
|
||||
affectedWaveIds,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@ -181,35 +181,18 @@ class ReportService extends Service {
|
||||
}
|
||||
|
||||
/**
|
||||
* 构建导出文件名(支持 file_name 模板占位符)。
|
||||
*
|
||||
* 占位符(2026-09-10 扩充,均为本地时区):
|
||||
* - `{date}`:数据日期(请求 params.bizDate,缺省服务器当天,`YYYY-MM-DD`)——语义不变;
|
||||
* - `{time}`:生成时刻 `HHmmss`(如 `200745`);
|
||||
* - `{datetime}`:`{date}_{time}`(如 `2026-09-09_200745`);
|
||||
* - `{timestamp}`:生成时刻毫秒时间戳(如 `1789136465123`)。
|
||||
*
|
||||
* 用途:同一天多次投递/手动导出同一报表时,文件名带生成时刻可避免 COS 同名覆盖
|
||||
*(同名文件会被后一次写覆盖,且 CDN 可能继续回源旧内容)。
|
||||
*
|
||||
* 构建导出文件名(支持 file_name 模板的 {date} 占位)。
|
||||
* @param {Object} definition 报表定义视图
|
||||
* @param {string} [bizDate=''] 数据日期(YYYY-MM-DD,缺省用今天)
|
||||
* @param {Date} [now=new Date()] 生成时刻(渲染 {time}/{datetime}/{timestamp} 用,可注入供测试)
|
||||
* @return {string} 文件名
|
||||
*/
|
||||
buildFilename(definition, bizDate = '', now = new Date()) {
|
||||
const nowDate = now instanceof Date && !Number.isNaN(now.getTime()) ? now : new Date();
|
||||
const dateText = String(bizDate || '').trim() || scheduleDateOf(nowDate);
|
||||
const timeText = `${String(nowDate.getHours()).padStart(2, '0')}`
|
||||
+ `${String(nowDate.getMinutes()).padStart(2, '0')}`
|
||||
+ `${String(nowDate.getSeconds()).padStart(2, '0')}`;
|
||||
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
|
||||
.replace(/\{datetime\}/g, `${dateText}_${timeText}`)
|
||||
.replace(/\{date\}/g, dateText)
|
||||
.replace(/\{time\}/g, timeText)
|
||||
.replace(/\{timestamp\}/g, String(nowDate.getTime()));
|
||||
const filename = template.includes('{date}')
|
||||
? template.replace(/\{date\}/g, dateText)
|
||||
: template;
|
||||
return filename.endsWith('.xlsx') || filename.endsWith('.xls') ? filename : `${filename}.xlsx`;
|
||||
}
|
||||
|
||||
|
||||
@ -1,7 +1,6 @@
|
||||
'use strict';
|
||||
|
||||
const sevenDayStockFlow = require('./sevenDayStockFlow');
|
||||
const interceptOrder = require('./interceptOrder');
|
||||
|
||||
/**
|
||||
* 报表内置查询器注册表。
|
||||
@ -17,7 +16,6 @@ const interceptOrder = require('./interceptOrder');
|
||||
*/
|
||||
const QUERIES = {
|
||||
stockFlow: sevenDayStockFlow,
|
||||
interceptOrder,
|
||||
};
|
||||
|
||||
/**
|
||||
@ -35,17 +33,6 @@ const DESCRIPTIONS = [
|
||||
},
|
||||
fields: (Array.isArray(sevenDayStockFlow.fields) ? sevenDayStockFlow.fields : []).map(field => ({ ...field })),
|
||||
},
|
||||
{
|
||||
key: 'interceptOrder',
|
||||
title: '库内确定拦截订单明细',
|
||||
description: '按配送表 dispath_time(订单迁移进配送表的时间)统计昨日库内确定拦截订单'
|
||||
+ '(intercept_status=intercepted_at_warehouse),按商品明细展开(一个商品一行),'
|
||||
+ '列与订单导出含明细模式(export_mode=item)一致,仅不含「商品图片」列',
|
||||
window: {
|
||||
...(interceptOrder.defaultWindow || { dayCount: 1, cutoverHour: 0 }),
|
||||
},
|
||||
fields: (Array.isArray(interceptOrder.fields) ? interceptOrder.fields : []).map(field => ({ ...field })),
|
||||
},
|
||||
];
|
||||
|
||||
/**
|
||||
|
||||
@ -1,477 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
const { scheduleDateOf } = require('../../../../lib/report/day_window');
|
||||
|
||||
/**
|
||||
* 库内确定拦截订单明细查询器(静态字段清单)。
|
||||
*
|
||||
* 前 46 列与 order.export(export_mode=item,按商品明细展开)的列对齐,
|
||||
* 仅去掉「商品图片」列(报表渲染不支持内嵌图片,订单导出该列本身也不落地 URL);
|
||||
* 另附加 3 列(订单导出无):
|
||||
* `source_order_codes`(平台交易单号,取订单表源单号字段,位置紧跟「外部单号」)、
|
||||
* `intercept_notice_time`(通知拦截时间,取配送表 intercept_time,为空时回落 ORDER_INTERCEPT_REQUEST 日志最早时间)、
|
||||
* `intercept_confirm_time`(库内确定拦截时间,取配送表 dispath_time)。
|
||||
* key 与查询器返回的行字段一一对应,type 统一为 string:
|
||||
* 渲染层对 string 字段原样输出,不做 zeroToDash/yesNo 转换,
|
||||
* 从而保证单元格取值与订单导出逐格一致(见 render.js renderCell 口径);
|
||||
* 两个时间列由查询器格式化为 'YYYY-MM-DD HH:mm:ss' 字符串(与订单导出的时间列同格式)。
|
||||
* @type {Array<Object>}
|
||||
*/
|
||||
const FIELDS = Object.freeze([
|
||||
{ key: 'id', label: '订单ID', type: 'string' },
|
||||
{ key: 'delivery_order_code', label: '订单号', type: 'string' },
|
||||
{ key: 'external_order_code', label: '外部单号', type: 'string' },
|
||||
{ key: 'source_order_codes', label: '平台交易单号', type: 'string' },
|
||||
{ key: 'status', label: '订单状态', type: 'string' },
|
||||
{ key: 'wave_no', label: '波次号', type: 'string' },
|
||||
{ key: 'wave_index', label: '波次序号', type: 'string' },
|
||||
{ key: 'store_id', label: '货主', type: 'string' },
|
||||
{ key: 'sys_platform_name', label: '平台', type: 'string' },
|
||||
{ key: 'create_channel', label: '来源', type: 'string' },
|
||||
{ key: 'shop_nick', label: '店铺昵称', type: 'string' },
|
||||
{ key: 'receiver_name', label: '收件人', type: 'string' },
|
||||
{ key: 'receiver_mobile', label: '收件人电话', type: 'string' },
|
||||
{ key: 'receiver_province', label: '省', type: 'string' },
|
||||
{ key: 'receiver_city', label: '市', type: 'string' },
|
||||
{ key: 'receiver_district', label: '区', type: 'string' },
|
||||
{ key: 'receiver_town', label: '镇', type: 'string' },
|
||||
{ key: 'receiver_detail', label: '详细地址', type: 'string' },
|
||||
{ key: 'item_name', label: '仓库商品名称', type: 'string' },
|
||||
{ key: 'item_barcode', label: '商品条码', type: 'string' },
|
||||
{ key: 'item_quantity', label: '数量', type: 'string' },
|
||||
{ key: 'logistics_name', label: '物流公司', type: 'string' },
|
||||
{ key: 'waybill_code', label: '运单号', type: 'string' },
|
||||
{ key: 'business_type', label: '业务类型', type: 'string' },
|
||||
{ key: 'logistics_interface_name', label: '运单接口', type: 'string' },
|
||||
{ key: 'package_material_id', label: '包材ID', type: 'string' },
|
||||
{ key: 'package_material_code', label: '包材编码', type: 'string' },
|
||||
{ key: 'package_material_name', label: '包材名称', type: 'string' },
|
||||
{ key: 'waybill_allocated_at', label: '分配时间', type: 'string' },
|
||||
{ key: 'items_count', label: '商品种数', type: 'string' },
|
||||
{ key: 'items_total', label: '商品件数', type: 'string' },
|
||||
{ key: 'items_weight', label: '商品重量', type: 'string' },
|
||||
{ key: 'weighing_weight', label: '称重重量(g)', type: 'string' },
|
||||
{ key: 'total_amount', label: '订单金额', type: 'string' },
|
||||
{ key: 'got_amount', label: '实收金额', type: 'string' },
|
||||
{ key: 'create_at', label: '创建时间', type: 'string' },
|
||||
{ key: 'pay_time', label: '支付时间', type: 'string' },
|
||||
{ key: 'delivery_time', label: '发货时间', type: 'string' },
|
||||
{ key: 'outbound_status', label: '出库状态', type: 'string' },
|
||||
{ key: 'inspection_status', label: '复核状态', type: 'string' },
|
||||
{ key: 'recheck_status', label: '复核完成状态', type: 'string' },
|
||||
{ key: 'post_status', label: '配货状态', type: 'string' },
|
||||
{ key: 'pack_status', label: '打包状态', type: 'string' },
|
||||
{ key: 'remark', label: '备注', type: 'string' },
|
||||
{ key: 'buyer_message', label: '买家留言', type: 'string' },
|
||||
{ key: 'seller_message', label: '卖家留言', type: 'string' },
|
||||
{ key: 'archive_time', label: '归档时间', type: 'string' },
|
||||
{ key: 'intercept_notice_time', label: '通知拦截时间', type: 'string' },
|
||||
{ key: 'intercept_confirm_time', label: '库内确定拦截时间', type: 'string' },
|
||||
]);
|
||||
|
||||
/**
|
||||
* 查询器缺省窗口元数据(供 report.definition.typeList 展示)。
|
||||
* 本查询器为「单个自然日」粒度:dayCount=1、cutoverHour=0(00:00 切日,非 stockFlow 的 07:00)。
|
||||
* @type {{dayCount: number, cutoverHour: number}}
|
||||
*/
|
||||
const DEFAULT_WINDOW = Object.freeze({ dayCount: 1, cutoverHour: 0 });
|
||||
|
||||
/** 查询表位:配送表(订单出库迁移后的表位,dispath_time 为该表独有字段) */
|
||||
const DISPATCH_TABLE_TYPE = 'dispatch';
|
||||
/** 库内确定拦截状态(order.recheckOrder.confirmIntercept / intercept_auto_confirm 写入值) */
|
||||
const INTERCEPTED_AT_WAREHOUSE_STATUS = 'intercepted_at_warehouse';
|
||||
/** 明细展开模式(与 order.export export_mode=item 一致:一个商品一行) */
|
||||
const EXPORT_MODE_ITEM = 'item';
|
||||
/** 单页拉取订单数(复用订单导出分页大小) */
|
||||
const DEFAULT_PAGE_SIZE = 1000;
|
||||
/** 单次报表生成的最大明细行数保护(防御性上限,正常日拦截单量远低于该值) */
|
||||
const MAX_EXPORT_ROWS = 200000;
|
||||
/** 通知拦截(发起拦截请求)操作日志编码:wms_operation_log.operation_code */
|
||||
const ORDER_INTERCEPT_REQUEST_CODE = 'ORDER_INTERCEPT_REQUEST';
|
||||
/** 拦截时间富化(回查配送表 + 操作日志)单批订单ID数 */
|
||||
const ENRICH_CHUNK_SIZE = 500;
|
||||
|
||||
/**
|
||||
* 两位补零。
|
||||
* @param {number} value 数值
|
||||
* @return {string} 补零字符串
|
||||
*/
|
||||
function pad2(value) {
|
||||
return String(value).padStart(2, '0');
|
||||
}
|
||||
|
||||
/**
|
||||
* 本地时区格式化为 'YYYY-MM-DD HH:mm:ss'。
|
||||
* @param {Date} date 时间对象
|
||||
* @return {string} 格式化结果
|
||||
*/
|
||||
function formatDateTime(date) {
|
||||
return `${date.getFullYear()}-${pad2(date.getMonth() + 1)}-${pad2(date.getDate())}`
|
||||
+ ` ${pad2(date.getHours())}:${pad2(date.getMinutes())}:${pad2(date.getSeconds())}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析统计日与查询区间。
|
||||
*
|
||||
* 规则:
|
||||
* 1. `params.bizDate`(或 `biz_date`)为合法 `YYYY-MM-DD` 时,按该日自然日整天统计;
|
||||
* 2. 未传/非法时回落「昨日自然日」,即 [昨日 00:00:00.000, 今日 00:00:00.000);
|
||||
* 3. **硬约束:统计日不得晚于昨天**——传入今天/未来日期一律回落昨日,
|
||||
* 保证「今天生成/投递的报表不含今天的数据」(当天新迁入的拦截单只会在次日报表里出现);
|
||||
* 4. 区间为本地时区半开区间(start 含、end 不含),通过 `new Date(y, m, d)` 构造,
|
||||
* 规避夏令时导致的步进偏差。
|
||||
*
|
||||
* @param {Object} [params={}] 查询器业务参数
|
||||
* @return {{bizDate: string, start: Date, end: Date}} 统计日与区间
|
||||
*/
|
||||
function resolveBizDayWindow(params = {}) {
|
||||
const safeParams = params && typeof params === 'object' ? params : {};
|
||||
const rawBizDate = String(safeParams.bizDate || safeParams.biz_date || '').trim();
|
||||
|
||||
const now = new Date();
|
||||
const todayStart = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 0, 0, 0, 0);
|
||||
const yesterdayStart = new Date(now.getFullYear(), now.getMonth(), now.getDate() - 1, 0, 0, 0, 0);
|
||||
|
||||
let baseDate = null;
|
||||
|
||||
const matched = /^(\d{4})-(\d{2})-(\d{2})$/.exec(rawBizDate);
|
||||
if (matched) {
|
||||
const year = Number(matched[1]);
|
||||
const month = Number(matched[2]);
|
||||
const day = Number(matched[3]);
|
||||
const candidate = new Date(year, month - 1, day, 0, 0, 0, 0);
|
||||
if (
|
||||
candidate.getFullYear() === year
|
||||
&& candidate.getMonth() === month - 1
|
||||
&& candidate.getDate() === day
|
||||
) {
|
||||
baseDate = candidate;
|
||||
}
|
||||
}
|
||||
|
||||
if (!baseDate) {
|
||||
baseDate = yesterdayStart;
|
||||
}
|
||||
|
||||
// 今天及以后一律回落昨日:今天生成/投递的报表只含昨天(及更早显式指定日)的数据
|
||||
if (baseDate.getTime() >= todayStart.getTime()) {
|
||||
baseDate = yesterdayStart;
|
||||
}
|
||||
|
||||
const start = new Date(baseDate.getFullYear(), baseDate.getMonth(), baseDate.getDate(), 0, 0, 0, 0);
|
||||
const end = new Date(baseDate.getFullYear(), baseDate.getMonth(), baseDate.getDate() + 1, 0, 0, 0, 0);
|
||||
|
||||
return { bizDate: scheduleDateOf(start), start, end };
|
||||
}
|
||||
|
||||
/**
|
||||
* 按字段清单裁剪订单导出行,保证报表列与订单导出 item 模式对齐并丢弃多余键(如 item_image)。
|
||||
* @param {Object} row 订单导出行
|
||||
* @return {Object} 仅含注册字段的报表行
|
||||
*/
|
||||
function pickReportRow(row = {}) {
|
||||
const safeRow = row && typeof row === 'object' ? row : {};
|
||||
const result = {};
|
||||
for (const field of FIELDS) {
|
||||
const value = safeRow[field.key];
|
||||
result[field.key] = value === undefined ? '' : value;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 安全格式化时间列(与订单导出 formatDateSafe 口径一致:空值/无效值返回空字符串)。
|
||||
* @param {*} value 时间原始值
|
||||
* @param {Object} app Egg app 实例(取 app.formatDate)
|
||||
* @return {string} 'YYYY-MM-DD HH:mm:ss' 或空字符串
|
||||
*/
|
||||
function formatTimeValue(value, app) {
|
||||
if (value === null || value === undefined || value === '' || value === 0) {
|
||||
return '';
|
||||
}
|
||||
const date = value instanceof Date ? value : new Date(value);
|
||||
if (Number.isNaN(date.getTime()) || date.getTime() <= 0) {
|
||||
return '';
|
||||
}
|
||||
return app && typeof app.formatDate === 'function' ? app.formatDate(date) : formatDateTime(date);
|
||||
}
|
||||
|
||||
/**
|
||||
* 富化报表附加列(按订单ID回查,分片避免大 IN 列表)。
|
||||
*
|
||||
* - `source_order_codes`(平台交易单号):直接取配送表同名字段(`mapOrderExportRow(item)` 不输出该列);
|
||||
* - `intercept_notice_time`(通知拦截时间):主取配送表 `intercept_time`
|
||||
* (自 2026-09-10 起该字段为「最近一次发起拦截的通知时刻」,确认拦截不再覆盖,
|
||||
* 见 `app/lib/intercept_time.js`);该列为空时回落 `wms_operation_log` 中
|
||||
* `operation_code = 'ORDER_INTERCEPT_REQUEST'` 的**最早**记录时间(历史数据兼容)。
|
||||
* 回查日志按 `business_type='order' + business_id=订单ID + warehouse_id=当前仓库` 三重过滤:
|
||||
* 订单 ID 按仓库发号,必须同仓隔离,禁止仅凭订单ID跨仓串读。
|
||||
* - `intercept_confirm_time`(库内确定拦截时间):取配送表 `dispath_time`
|
||||
* (订单迁移进配送表的时间;库内确定拦截后订单会走 outbound_status=fin 的自动迁移,故等价于库内确定拦截时刻)。
|
||||
*
|
||||
* 时间列均格式化为 'YYYY-MM-DD HH:mm:ss';查不到值时留空字符串。
|
||||
*
|
||||
* @param {Object} args 入参
|
||||
* @param {Object} args.ctx Egg 上下文
|
||||
* @param {Object} args.app Egg app 实例(时间格式化)
|
||||
* @param {Object} args.orderModel 配送表模型(读取 source_order_codes/intercept_time/dispath_time)
|
||||
* @param {number} args.warehouseId 仓库ID
|
||||
* @param {Array<Object>} args.rows 报表行(原地写入附加列,行内需含订单ID `id`)
|
||||
* @return {Promise<Array<Object>>} 富化后的行数组(同一引用)
|
||||
*/
|
||||
async function enrichInterceptFields({ ctx, app, orderModel, warehouseId, rows = [] }) {
|
||||
const list = Array.isArray(rows) ? rows : [];
|
||||
if (list.length === 0) {
|
||||
return list;
|
||||
}
|
||||
|
||||
const orderIds = [ ...new Set(
|
||||
list
|
||||
.map(row => Number(row && row.id) || 0)
|
||||
.filter(orderId => orderId > 0)
|
||||
) ];
|
||||
if (orderIds.length === 0) {
|
||||
return list;
|
||||
}
|
||||
|
||||
const { Op, fn, col } = app.Sequelize;
|
||||
const noticeTimeMap = new Map();
|
||||
const confirmTimeMap = new Map();
|
||||
const sourceOrderCodeMap = new Map();
|
||||
const logModel = ctx.model && ctx.model.OperationLog;
|
||||
|
||||
for (let offset = 0; offset < orderIds.length; offset += ENRICH_CHUNK_SIZE) {
|
||||
const chunk = orderIds.slice(offset, offset + ENRICH_CHUNK_SIZE);
|
||||
|
||||
// 平台交易单号(source_order_codes)+ 通知拦截时间(intercept_time)+ 库内确定拦截时间(dispath_time)
|
||||
try {
|
||||
const orderRows = await orderModel.findAll({
|
||||
where: { id: { [Op.in]: chunk } },
|
||||
attributes: [ 'id', 'source_order_codes', 'intercept_time', 'dispath_time' ],
|
||||
raw: true,
|
||||
});
|
||||
for (const orderRow of (Array.isArray(orderRows) ? orderRows : [])) {
|
||||
const orderId = Number(orderRow && orderRow.id) || 0;
|
||||
if (orderId > 0) {
|
||||
sourceOrderCodeMap.set(orderId, orderRow.source_order_codes);
|
||||
noticeTimeMap.set(orderId, orderRow.intercept_time);
|
||||
confirmTimeMap.set(orderId, orderRow.dispath_time);
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
ctx.logger.warn(
|
||||
'[report.interceptOrder] 回查配送表附加列失败,平台交易单号/拦截时间列留空: %s',
|
||||
error && error.message ? error.message : `${error}`
|
||||
);
|
||||
}
|
||||
|
||||
// 通知拦截时间(兜底,仅补齐主取为空的订单):操作日志最早一条 ORDER_INTERCEPT_REQUEST
|
||||
if (logModel && typeof logModel.findAll === 'function') {
|
||||
const pendingIds = chunk.filter(
|
||||
orderId => orderId > 0 && (noticeTimeMap.get(orderId) === null || noticeTimeMap.get(orderId) === undefined)
|
||||
);
|
||||
if (pendingIds.length === 0) {
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
const logRows = await logModel.findAll({
|
||||
attributes: [ 'business_id', [ fn('MIN', col('created_at')), 'notice_time' ]],
|
||||
where: {
|
||||
business_type: 'order',
|
||||
operation_code: ORDER_INTERCEPT_REQUEST_CODE,
|
||||
warehouse_id: warehouseId,
|
||||
business_id: { [Op.in]: pendingIds.map(orderId => String(orderId)) },
|
||||
},
|
||||
group: [ 'business_id' ],
|
||||
raw: true,
|
||||
});
|
||||
for (const logRow of (Array.isArray(logRows) ? logRows : [])) {
|
||||
const orderId = Number(logRow && logRow.business_id) || 0;
|
||||
if (orderId > 0) {
|
||||
noticeTimeMap.set(orderId, logRow.notice_time);
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
ctx.logger.warn(
|
||||
'[report.interceptOrder] 回查通知拦截操作日志失败,通知拦截时间列留空: %s',
|
||||
error && error.message ? error.message : `${error}`
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (const row of list) {
|
||||
const orderId = Number(row && row.id) || 0;
|
||||
const sourceOrderCodes = sourceOrderCodeMap.get(orderId);
|
||||
row.source_order_codes = sourceOrderCodes === null || sourceOrderCodes === undefined
|
||||
? ''
|
||||
: String(sourceOrderCodes);
|
||||
row.intercept_notice_time = formatTimeValue(noticeTimeMap.get(orderId), app);
|
||||
row.intercept_confirm_time = formatTimeValue(confirmTimeMap.get(orderId), app);
|
||||
}
|
||||
|
||||
return list;
|
||||
}
|
||||
|
||||
/**
|
||||
* 内置查询器:库内确定拦截订单明细(昨日迁入配送表的库内拦截订单,按商品明细展开)。
|
||||
*
|
||||
* 口径与假设(供测试复核):
|
||||
* 1. 数据源:配送表 `wms_order_delivery_{warehouseId}_dispatch`,仅取
|
||||
* `intercept_status = 'intercepted_at_warehouse'`(库内确定拦截;由
|
||||
* `order.recheckOrder.confirmIntercept` 与 `intercept_auto_confirm` 写入,同时 step=4、outbound_status=fin);
|
||||
* 2. 时间基准:`dispath_time`(订单迁移进配送表的时刻,配送表独有字段,由
|
||||
* `orderDeliveryMigration.buildDispatchRow` 写入 `new Date()`);
|
||||
* 3. 时间范围:默认「昨日自然日」[昨日 00:00:00.000, 今日 00:00:00.000) 本地时区半开区间,
|
||||
* 可通过 `params.bizDate`(YYYY-MM-DD)指定更早的统计日;非法值回落昨日,
|
||||
* **今天及以后的日期一律回落昨日**(今天生成/投递的报表永不含今天数据,
|
||||
* 当天新迁入配送表的拦截单只会在次日报表中出现);
|
||||
* 4. 明细粒度与列:复用 `orderExport.buildOrderExportPage` → `mapOrderExportRow(row, ctx, 'item')`,
|
||||
* 因此状态中文翻译、货主备注、条码/商品名回落、运单汇总、包材等取值与订单导出 item 模式逐格一致;
|
||||
* 列清单 = 订单导出 item 模式 47 列去掉「商品图片」列(46 列)+ 3 列附加列
|
||||
* (平台交易单号 source_order_codes、通知拦截时间、库内确定拦截时间,共 49 列);
|
||||
* 5. 无商品明细的订单输出一行订单级数据(运单字段汇总),与订单导出 item 模式一致;
|
||||
* 6. 主维度:warehouseId 必填(配送表按仓库分表);storeId > 0 时追加 `store_id` 过滤
|
||||
* (货主维度报表与投递),否则为仓库维度全量;
|
||||
* 7. 排序:按订单 ID 升序分页拉取(单页 1000 单,循环至不足一页);
|
||||
* 8. 附加列(订单导出 item 模式无此 3 列):
|
||||
* - `source_order_codes`(平台交易单号)= 配送表 `source_order_codes` 原值
|
||||
* (`mapOrderExportRow(item)` 不输出该列,由本查询器回查补充,位置紧跟「外部单号」);
|
||||
* - `intercept_notice_time`(通知拦截时间)= 配送表 `intercept_time`
|
||||
* (自 2026-09-10 起为「最近一次发起拦截的通知时刻」,确认拦截不再覆盖;
|
||||
* 为空时回落 `wms_operation_log` 的 ORDER_INTERCEPT_REQUEST 最早记录,按同仓隔离查询);
|
||||
* - `intercept_confirm_time`(库内确定拦截时间)= 配送表 `dispath_time`
|
||||
* (订单迁移进配送表的时间,库内确定拦截后基本都会走出库迁移);
|
||||
* 两个时间列格式化为 'YYYY-MM-DD HH:mm:ss';
|
||||
* 8. 波次序号(wave_index):复用订单导出同款 `attachOrderWaveIndex`,该实现按登录上下文仓库
|
||||
* 取值,定时投递(无 ctx.user)场景降级为 0,手工导出(仓库主体)为真实序号。
|
||||
*
|
||||
* @param {Object} args 查询器入参
|
||||
* @param {Object} args.ctx Egg 上下文
|
||||
* @param {number|null} args.storeId 货主ID(可选,<=0 时不按货主过滤)
|
||||
* @param {number|null} args.warehouseId 仓库ID(必填)
|
||||
* @param {Object} [args.params={}] 业务参数(bizDate 统计日覆盖)
|
||||
* @return {Promise<{windows: Array<Object>, rows: Array<Object>, meta: Object}>} 查询结果
|
||||
*/
|
||||
async function interceptOrder({ ctx, storeId = null, warehouseId = null, params = {} }) {
|
||||
const { app } = ctx;
|
||||
const { Op } = app.Sequelize;
|
||||
|
||||
const normalizedWarehouseId = Number(warehouseId) || 0;
|
||||
if (normalizedWarehouseId <= 0) {
|
||||
throw new Error('interceptOrder 查询器缺少仓库维度 warehouseId');
|
||||
}
|
||||
|
||||
const { bizDate, start, end } = resolveBizDayWindow(params);
|
||||
const normalizedStoreId = Number(storeId) || 0;
|
||||
|
||||
const orderExport = ctx.service && ctx.service.systems ? ctx.service.systems.orderExport : null;
|
||||
if (!orderExport || typeof orderExport.buildOrderExportPage !== 'function') {
|
||||
throw new Error('订单导出服务不可用,无法复用订单明细口径(orderExport.buildOrderExportPage)');
|
||||
}
|
||||
|
||||
const target = orderExport.resolveExportTarget({ tableType: DISPATCH_TABLE_TYPE });
|
||||
const orderModel = await orderExport.getOrderModelByTableType(DISPATCH_TABLE_TYPE, normalizedWarehouseId);
|
||||
|
||||
const queryWhere = {
|
||||
intercept_status: INTERCEPTED_AT_WAREHOUSE_STATUS,
|
||||
dispath_time: {
|
||||
[Op.gte]: start,
|
||||
[Op.lt]: end,
|
||||
},
|
||||
};
|
||||
if (normalizedStoreId > 0) {
|
||||
queryWhere.store_id = normalizedStoreId;
|
||||
}
|
||||
|
||||
const pageSize = Number(typeof orderExport.getExportPageSize === 'function'
|
||||
? orderExport.getExportPageSize()
|
||||
: 0) || DEFAULT_PAGE_SIZE;
|
||||
|
||||
const rows = [];
|
||||
let orderCount = 0;
|
||||
let page = 1;
|
||||
let truncated = false;
|
||||
|
||||
for (;;) {
|
||||
const pageResult = await orderExport.buildOrderExportPage({
|
||||
page,
|
||||
pageSize,
|
||||
queryWhere,
|
||||
order: [[ 'id', 'ASC' ]],
|
||||
orderModel,
|
||||
target,
|
||||
warehouseId: normalizedWarehouseId,
|
||||
mode: EXPORT_MODE_ITEM,
|
||||
});
|
||||
|
||||
const pageOrderCount = Number(pageResult && pageResult.orderCount) || 0;
|
||||
if (pageOrderCount <= 0) {
|
||||
break;
|
||||
}
|
||||
|
||||
const pageRows = Array.isArray(pageResult && pageResult.exportRows) ? pageResult.exportRows : [];
|
||||
for (const pageRow of pageRows) {
|
||||
rows.push(pickReportRow(pageRow));
|
||||
if (rows.length >= MAX_EXPORT_ROWS) {
|
||||
truncated = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
orderCount += pageOrderCount;
|
||||
if (truncated || pageOrderCount < pageSize) {
|
||||
break;
|
||||
}
|
||||
page += 1;
|
||||
}
|
||||
|
||||
if (truncated) {
|
||||
ctx.logger.warn(
|
||||
'[report.interceptOrder] 明细行数达到上限 %s,已截断(bizDate=%s warehouseId=%s)',
|
||||
MAX_EXPORT_ROWS,
|
||||
bizDate,
|
||||
normalizedWarehouseId
|
||||
);
|
||||
}
|
||||
|
||||
// 附加列:平台交易单号(source_order_codes)+ 通知拦截时间(配送表 intercept_time,日志兜底)
|
||||
// + 库内确定拦截时间(配送表 dispath_time)
|
||||
await enrichInterceptFields({
|
||||
ctx,
|
||||
app,
|
||||
orderModel,
|
||||
warehouseId: normalizedWarehouseId,
|
||||
rows,
|
||||
});
|
||||
|
||||
const noticeTimeFilledCount = rows.filter(row => String(row.intercept_notice_time || '').trim()).length;
|
||||
const confirmTimeFilledCount = rows.filter(row => String(row.intercept_confirm_time || '').trim()).length;
|
||||
|
||||
return {
|
||||
windows: [],
|
||||
rows,
|
||||
meta: {
|
||||
bizDate,
|
||||
startTime: formatDateTime(start),
|
||||
endTime: formatDateTime(end),
|
||||
warehouseId: normalizedWarehouseId,
|
||||
storeId: normalizedStoreId,
|
||||
interceptStatus: INTERCEPTED_AT_WAREHOUSE_STATUS,
|
||||
timeField: 'dispath_time',
|
||||
orderCount,
|
||||
rowCount: rows.length,
|
||||
noticeTimeFilledCount,
|
||||
confirmTimeFilledCount,
|
||||
truncated,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
module.exports = interceptOrder;
|
||||
module.exports.fields = FIELDS;
|
||||
module.exports.defaultWindow = DEFAULT_WINDOW;
|
||||
// 纯函数导出(供单测/校验脚本复核口径,不作为查询器调用入口)
|
||||
module.exports.resolveBizDayWindow = resolveBizDayWindow;
|
||||
module.exports.pickReportRow = pickReportRow;
|
||||
module.exports.enrichInterceptFields = enrichInterceptFields;
|
||||
@ -358,8 +358,6 @@ class ReturnReceivedService extends Service {
|
||||
* 更新退回运单关联订单的退回状态并写入操作记录(不处理库存信息)。
|
||||
* - current 表(待处理):设置 intercept_status='returned'、step=4、outbound_status='fin' 触发自动转配送表;
|
||||
* - dispatch 表(配送中):仅更新 intercept_status='returned';
|
||||
* - 两条链路均**不写** intercept_time(该字段恒为「最近一次发起拦截的通知时刻」,
|
||||
* 退回入库不覆盖,见 app/lib/intercept_time.js);
|
||||
* - 不释放储位分配、不释放订单锁。
|
||||
* 兼容 current/dispatch 分表:先查 current 表,不存在再查 dispatch 表。
|
||||
*
|
||||
|
||||
@ -245,7 +245,32 @@ class ReturnUnpackService extends Service {
|
||||
remark: remark ? String(remark).slice(0, 500) : null,
|
||||
};
|
||||
|
||||
const createdRow = await this._insertMainWithRetry(baseFields, warehouseId, 'create');
|
||||
let created = null;
|
||||
const maxAttempts = 5;
|
||||
for (let attempt = 1; attempt <= maxAttempts && !created; attempt += 1) {
|
||||
const unpackNo = await this._generateUnpackNo(warehouseId);
|
||||
try {
|
||||
created = await ctx.model.ReturnUnpack.create({
|
||||
...baseFields,
|
||||
unpack_no: unpackNo,
|
||||
});
|
||||
} catch (err) {
|
||||
const isUniqueConflict = err && (
|
||||
err.name === 'SequelizeUniqueConstraintError'
|
||||
|| (err.parent && err.parent.code === 'ER_DUP_ENTRY')
|
||||
);
|
||||
if (isUniqueConflict && attempt < maxAttempts) {
|
||||
// 并发撞号:指数退避 + 随机抖动后重新取号重试,降低同一序号再次碰撞概率
|
||||
const backoffMs = Math.min(500, attempt * 40) + Math.floor(Math.random() * 60);
|
||||
ctx.logger.warn(`[returnUnpack.create] 拆包单号唯一冲突,第 ${attempt} 次重试(退避 ${backoffMs}ms): ${err.message}`);
|
||||
await new Promise(resolve => setTimeout(resolve, backoffMs));
|
||||
continue;
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
const createdRow = created && typeof created.toJSON === 'function' ? created.toJSON() : created;
|
||||
|
||||
// 7. 原订单详情(仅原单退回时拉取,参考 afterSale.detail._resolveOrderDetail)
|
||||
let order = null;
|
||||
@ -267,104 +292,6 @@ class ReturnUnpackService extends Service {
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 运单批量转入退件登记(退回拆包,批量)。
|
||||
* 批量入参运单表主键 ID(wms_order_express.id):过滤非正整数 + 去重,单次上限 200;
|
||||
* 逐单处理,单条失败不阻断主流程。
|
||||
* 命中的运单统一标记 wms_order_express.is_back='Y'(不做其他前置条件限制);
|
||||
* 幂等:同仓库 + 同运单号已存在有效(status != 'cancelled')拆包单时直接复用,
|
||||
* 复用单明细为空时按订单明细补写(优先 items JSON,为空回退明细分表)。
|
||||
*
|
||||
* @param {Object} params 批量转入参数。
|
||||
* @param {Array<number>|number} params.ids 运单表主键ID(wms_order_express.id,单个数值或数组)。
|
||||
* @return {Promise<Object>} { total, success_count, failed_count, success[], failed[] },
|
||||
* 成功项含 waybill_id/waybill_code/unpack_id/unpack_no/reused/detail_count/total_quantity,
|
||||
* 失败项含 waybill_id/waybill_code(运单命中时)/reason。
|
||||
*/
|
||||
async transferByWaybills({ ids }) {
|
||||
const { ctx, app } = this;
|
||||
const { Op } = app.Sequelize;
|
||||
|
||||
// 入参归一化:单个数值转数组,过滤非正整数 + 去重
|
||||
const rawIds = Array.isArray(ids) ? ids : [ ids ];
|
||||
const waybillIds = [ ...new Set(
|
||||
rawIds.map(id => Number(id)).filter(id => Number.isInteger(id) && id > 0)
|
||||
) ];
|
||||
|
||||
if (waybillIds.length === 0) {
|
||||
throw this.createBusinessError('ids 不能为空', 400);
|
||||
}
|
||||
if (waybillIds.length > 200) {
|
||||
throw this.createBusinessError('单次最多批量转入 200 个运单', 400);
|
||||
}
|
||||
|
||||
// 仓库隔离:由服务端从当前上下文自动注入,禁止前端传入
|
||||
const warehouseId = Number(ctx.user && ctx.user.store_id || 0);
|
||||
if (!Number.isFinite(warehouseId) || warehouseId <= 0) {
|
||||
throw this.createBusinessError('缺少仓库上下文', 400);
|
||||
}
|
||||
|
||||
// 操作人上下文(与 create 完全一致)
|
||||
const unpackerId = Number(ctx.user && ctx.user.employees_id || 0);
|
||||
const unpackerName = String(
|
||||
(ctx.user && ctx.user.employees_name) || (ctx.user && ctx.user.real_name) || ''
|
||||
).trim();
|
||||
if (!Number.isFinite(unpackerId) || unpackerId <= 0) {
|
||||
throw this.createBusinessError('缺少拆包人员工号上下文', 400);
|
||||
}
|
||||
|
||||
// 批量反查运单:一次查询完成 运单ID + 仓库 命中判定(未命中的 ID 记为失败)
|
||||
const expressMap = new Map();
|
||||
try {
|
||||
const expressRows = await ctx.model.OrderExpress.findAll({
|
||||
where: { id: { [Op.in]: waybillIds }, warehouse_id: warehouseId },
|
||||
attributes: [ 'id', 'waybill_code', 'order_id', 'store_id', 'source_order_codes', 'business_key' ],
|
||||
raw: true,
|
||||
});
|
||||
for (const row of expressRows) {
|
||||
expressMap.set(Number(row.id), row);
|
||||
}
|
||||
} catch (err) {
|
||||
ctx.logger.warn(`[returnUnpack.transferByWaybills] 批量反查运单失败: ${err.message}`);
|
||||
throw this.createBusinessError('反查运单失败,请稍后重试', 500);
|
||||
}
|
||||
|
||||
/** @type {Array<Object>} 成功项列表 */
|
||||
const success = [];
|
||||
/** @type {Array<Object>} 失败项列表 */
|
||||
const failed = [];
|
||||
|
||||
for (const waybillId of waybillIds) {
|
||||
const orderExpress = expressMap.get(waybillId) || null;
|
||||
try {
|
||||
const item = await this._transferOneWaybill({
|
||||
orderExpress,
|
||||
waybillId,
|
||||
warehouseId,
|
||||
unpackerId,
|
||||
unpackerName,
|
||||
});
|
||||
success.push(item);
|
||||
} catch (err) {
|
||||
const reason = (err && err.message) || '转入失败';
|
||||
ctx.logger.warn(`[returnUnpack.transferByWaybills] 运单ID ${waybillId} 转入失败: ${reason}`);
|
||||
failed.push({
|
||||
waybill_id: waybillId,
|
||||
waybill_code: orderExpress ? String(orderExpress.waybill_code || '') : null,
|
||||
reason,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
total: waybillIds.length,
|
||||
success_count: success.length,
|
||||
failed_count: failed.length,
|
||||
success,
|
||||
failed,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 录明细:以拆包单ID为依据录入一条明细(识别到系统商品时回填快照)。
|
||||
* 仅以 stock_id 识别商品;不指定 stock_id 时一律标注未知商品,
|
||||
@ -1991,368 +1918,6 @@ class ReturnUnpackService extends Service {
|
||||
// 辅助方法
|
||||
// ===========================
|
||||
|
||||
/**
|
||||
* 生成拆包单号并插入主表(并发撞 uk_unpack_no 唯一索引时重新取号重试)。
|
||||
* 最多重试 5 次,指数退避 + 随机抖动;create 与 transferByWaybills 共用。
|
||||
*
|
||||
* @param {Object} baseFields 主表插入字段(不含 unpack_no)。
|
||||
* @param {number} warehouseId 仓库ID(用于取号)。
|
||||
* @param {string} scene 调用场景标识(用于日志)。
|
||||
* @return {Promise<Object>} 创建后的主表记录(JSON 对象)。
|
||||
*/
|
||||
async _insertMainWithRetry(baseFields, warehouseId, scene) {
|
||||
const { ctx } = this;
|
||||
const maxAttempts = 5;
|
||||
for (let attempt = 1; attempt <= maxAttempts; attempt += 1) {
|
||||
const unpackNo = await this._generateUnpackNo(warehouseId);
|
||||
try {
|
||||
const created = await ctx.model.ReturnUnpack.create({
|
||||
...baseFields,
|
||||
unpack_no: unpackNo,
|
||||
});
|
||||
return created && typeof created.toJSON === 'function' ? created.toJSON() : created;
|
||||
} catch (err) {
|
||||
const isUniqueConflict = err && (
|
||||
err.name === 'SequelizeUniqueConstraintError'
|
||||
|| (err.parent && err.parent.code === 'ER_DUP_ENTRY')
|
||||
);
|
||||
if (isUniqueConflict && attempt < maxAttempts) {
|
||||
// 并发撞号:指数退避 + 随机抖动后重新取号重试,降低同一序号再次碰撞概率
|
||||
const backoffMs = Math.min(500, attempt * 40) + Math.floor(Math.random() * 60);
|
||||
ctx.logger.warn(
|
||||
`[returnUnpack.${scene}] 拆包单号唯一冲突,第 ${attempt} 次重试(退避 ${backoffMs}ms): ${err.message}`
|
||||
);
|
||||
await new Promise(resolve => setTimeout(resolve, backoffMs));
|
||||
continue;
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
throw this.createBusinessError('拆包单号生成失败,请重试', 500);
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理单个运单的批量转入:校验运单 → 标记退回 → 幂等复用/新建拆包单 → 复制订单明细。
|
||||
* 子单(business_key > 1)跳过;一个运单只允许一条有效拆包单。
|
||||
*
|
||||
* @param {Object} params 单运单处理参数。
|
||||
* @param {Object|null} params.orderExpress 调用方批量反查得到的运单行;null=不存在或不属于当前仓库。
|
||||
* @param {number} params.waybillId 运单表主键ID。
|
||||
* @param {number} params.warehouseId 仓库ID。
|
||||
* @param {number} params.unpackerId 拆包人员工号ID。
|
||||
* @param {string} params.unpackerName 拆包人员工号名称。
|
||||
* @return {Promise<Object>} 成功项:{ waybill_id, waybill_code, unpack_id, unpack_no, reused, detail_count, total_quantity }。
|
||||
*/
|
||||
async _transferOneWaybill({ orderExpress, waybillId, warehouseId, unpackerId, unpackerName }) {
|
||||
const { ctx, app } = this;
|
||||
const { Op } = app.Sequelize;
|
||||
|
||||
// 1. 校验运单(调用方已按 运单ID + 仓库 批量反查,避免跨仓运单被转入本仓拆包单)
|
||||
if (!orderExpress) {
|
||||
throw this.createBusinessError('运单不存在', 404);
|
||||
}
|
||||
|
||||
// 子单不处理:business_key 为空或 1 视为主单,>1 跳过
|
||||
if (Number(orderExpress.business_key || 0) > 1) {
|
||||
throw this.createBusinessError('运单为子单(business_key>1),跳过', 400);
|
||||
}
|
||||
|
||||
// 运单号是拆包单的必填业务键:未取号的运单无可登记的运单号
|
||||
const waybillCode = String(orderExpress.waybill_code || '').trim();
|
||||
if (!waybillCode) {
|
||||
throw this.createBusinessError('运单号为空,无法转入退件登记', 400);
|
||||
}
|
||||
|
||||
// 2. 命中的运单统一标记退回(不做其他前置条件限制)
|
||||
try {
|
||||
await ctx.model.OrderExpress.update(
|
||||
{ is_back: 'Y' },
|
||||
{ where: { id: orderExpress.id } }
|
||||
);
|
||||
} catch (err) {
|
||||
ctx.logger.warn(`[returnUnpack.transferByWaybills] 标记运单退回失败 id=${orderExpress.id}: ${err.message}`);
|
||||
}
|
||||
|
||||
// 3. 幂等复用:同仓库 + 同运单号已存在有效(status != 'cancelled')拆包单时直接复用
|
||||
let existing = null;
|
||||
try {
|
||||
const existingList = await ctx.model.ReturnUnpack.findAll({
|
||||
where: {
|
||||
warehouse_id: warehouseId,
|
||||
waybill_code: waybillCode,
|
||||
status: { [Op.ne]: 'cancelled' },
|
||||
},
|
||||
attributes: [ 'id', 'unpack_no', 'return_received_id', 'order_express_id', 'order_id' ],
|
||||
order: [[ 'created_at', 'DESC' ], [ 'id', 'DESC' ]],
|
||||
raw: true,
|
||||
});
|
||||
if (existingList.length > 0) {
|
||||
existing = existingList[0];
|
||||
// 同运单号可能有多张拆包单:优先复用已录明细的最新单(与 create 口径一致)
|
||||
const countRows = await ctx.model.ReturnUnpackDetail.findAll({
|
||||
where: { unpack_id: { [Op.in]: existingList.map(row => row.id) } },
|
||||
attributes: [
|
||||
'unpack_id',
|
||||
[ ctx.model.fn('COUNT', ctx.model.col('id')), 'detail_count' ],
|
||||
],
|
||||
group: [ 'unpack_id' ],
|
||||
raw: true,
|
||||
});
|
||||
const detailCountMap = new Map(
|
||||
countRows.map(row => [ Number(row.unpack_id), Number(row.detail_count) || 0 ])
|
||||
);
|
||||
const withDetails = existingList.find(row => (detailCountMap.get(Number(row.id)) || 0) > 0);
|
||||
if (withDetails) {
|
||||
existing = withDetails;
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
ctx.logger.warn(`[returnUnpack.transferByWaybills] 查重已有拆包单失败 ${waybillCode}: ${err.message}`);
|
||||
}
|
||||
|
||||
// 可选:命中退回收到登记(同仓库 + 同运单号)时回填 return_received_id
|
||||
const returnReceivedId = await this._resolveReturnReceivedId(warehouseId, waybillCode);
|
||||
|
||||
if (existing) {
|
||||
const unpackId = Number(existing.id);
|
||||
|
||||
// 复用单明细为空时按规则 4 补写订单明细
|
||||
let summary = await this._countDetails(unpackId);
|
||||
if (summary.detail_count === 0) {
|
||||
try {
|
||||
const backfillOrderId = Number(existing.order_id || 0) || Number(orderExpress.order_id || 0);
|
||||
await this._backfillDetailsFromOrder(unpackId, warehouseId, backfillOrderId);
|
||||
summary = await this._countDetails(unpackId);
|
||||
} catch (err) {
|
||||
ctx.logger.warn(`[returnUnpack.transferByWaybills] 复用单补写明细失败 unpack_id=${unpackId}: ${err.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
// 主表退回收到单ID为空时回填
|
||||
if (returnReceivedId && !existing.return_received_id) {
|
||||
try {
|
||||
await ctx.model.ReturnUnpack.update(
|
||||
{ return_received_id: returnReceivedId },
|
||||
{ where: { id: unpackId } }
|
||||
);
|
||||
} catch (err) {
|
||||
ctx.logger.warn(`[returnUnpack.transferByWaybills] 回填退回收到单失败 unpack_id=${unpackId}: ${err.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
waybill_id: waybillId,
|
||||
waybill_code: waybillCode,
|
||||
unpack_id: unpackId,
|
||||
unpack_no: existing.unpack_no || '',
|
||||
reused: true,
|
||||
detail_count: summary.detail_count,
|
||||
total_quantity: summary.total_quantity,
|
||||
};
|
||||
}
|
||||
|
||||
// 4. 新建拆包单:解析关联订单明细(优先 items JSON,为空回退明细分表,复用 afterSale 现成实现)
|
||||
const orderId = Number(orderExpress.order_id || 0);
|
||||
let order = null;
|
||||
if (orderId > 0) {
|
||||
try {
|
||||
order = await ctx.service.systems.afterSale._resolveOrderDetail(orderId, warehouseId);
|
||||
} catch (err) {
|
||||
ctx.logger.warn(`[returnUnpack.transferByWaybills] 拉取订单详情失败 orderId=${orderId}: ${err.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
const orderItems = order && Array.isArray(order.items) ? order.items : [];
|
||||
if (orderItems.length === 0) {
|
||||
throw this.createBusinessError('运单关联订单无明细可复制', 400);
|
||||
}
|
||||
|
||||
const storeId = Number(orderExpress.store_id || 0) || Number(order && order.store_id || 0) || null;
|
||||
const storeRemark = await this._resolveStoreRemark(storeId, warehouseId);
|
||||
|
||||
const now = new Date();
|
||||
const unpackDate = app.formatDate(now, 'YYYY-MM-DD');
|
||||
|
||||
const createdRow = await this._insertMainWithRetry({
|
||||
warehouse_id: warehouseId,
|
||||
return_received_id: returnReceivedId,
|
||||
waybill_code: waybillCode,
|
||||
unpack_date: unpackDate,
|
||||
start_time: now,
|
||||
end_time: null,
|
||||
unpacker_id: unpackerId,
|
||||
unpacker_name: unpackerName || '未命名',
|
||||
status: 'unpacking',
|
||||
detail_status: 'none_recognized',
|
||||
total_items: 0,
|
||||
total_quantity: 0,
|
||||
order_express_id: orderExpress.id,
|
||||
order_id: orderId > 0 ? orderId : null,
|
||||
store_id: storeId,
|
||||
source_order_codes: orderExpress.source_order_codes || null,
|
||||
shop_name: storeRemark || null,
|
||||
camera_ids: null,
|
||||
remark: null,
|
||||
}, warehouseId, 'transferByWaybills');
|
||||
|
||||
const unpackId = Number(createdRow.id);
|
||||
|
||||
// 5. 复制订单明细(逐行 1:1 复制,不做合并/换算),插入后回填主表汇总
|
||||
const detailRows = await this._buildTransferDetailRows(orderItems);
|
||||
await ctx.model.ReturnUnpackDetail.bulkCreate(
|
||||
detailRows.map(row => ({ ...row, unpack_id: unpackId, warehouse_id: warehouseId }))
|
||||
);
|
||||
const summary = await this._recalcMain(unpackId, warehouseId);
|
||||
|
||||
return {
|
||||
waybill_id: waybillId,
|
||||
waybill_code: waybillCode,
|
||||
unpack_id: unpackId,
|
||||
unpack_no: createdRow.unpack_no || '',
|
||||
reused: false,
|
||||
detail_count: summary.total_items,
|
||||
total_quantity: summary.total_quantity,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 按规则补写拆包单明细:解析关联订单明细(优先 items JSON,为空回退明细分表)并逐行复制写入。
|
||||
*
|
||||
* @param {number} unpackId 拆包单ID。
|
||||
* @param {number} warehouseId 仓库ID。
|
||||
* @param {number} orderId 订单ID。
|
||||
* @return {Promise<number>} 写入的明细行数。
|
||||
*/
|
||||
async _backfillDetailsFromOrder(unpackId, warehouseId, orderId) {
|
||||
const { ctx } = this;
|
||||
if (!orderId || !Number.isFinite(orderId) || orderId <= 0) {
|
||||
throw this.createBusinessError('未找到关联订单', 404);
|
||||
}
|
||||
|
||||
let order = null;
|
||||
try {
|
||||
order = await ctx.service.systems.afterSale._resolveOrderDetail(orderId, warehouseId);
|
||||
} catch (err) {
|
||||
ctx.logger.warn(`[returnUnpack._backfillDetailsFromOrder] 拉取订单详情失败 orderId=${orderId}: ${err.message}`);
|
||||
}
|
||||
|
||||
const orderItems = order && Array.isArray(order.items) ? order.items : [];
|
||||
if (orderItems.length === 0) {
|
||||
throw this.createBusinessError('订单无明细可复制', 400);
|
||||
}
|
||||
|
||||
const detailRows = await this._buildTransferDetailRows(orderItems);
|
||||
await ctx.model.ReturnUnpackDetail.bulkCreate(
|
||||
detailRows.map(row => ({ ...row, unpack_id: unpackId, warehouse_id: warehouseId }))
|
||||
);
|
||||
await this._recalcMain(unpackId, warehouseId);
|
||||
return detailRows.length;
|
||||
}
|
||||
|
||||
/**
|
||||
* 统计拆包单明细行数与总数量(不更新主表)。
|
||||
*
|
||||
* @param {number} unpackId 拆包单ID。
|
||||
* @return {Promise<Object>} { detail_count, total_quantity }。
|
||||
*/
|
||||
async _countDetails(unpackId) {
|
||||
const { ctx } = this;
|
||||
const details = await ctx.model.ReturnUnpackDetail.findAll({
|
||||
where: { unpack_id: unpackId },
|
||||
attributes: [ 'quantity' ],
|
||||
raw: true,
|
||||
});
|
||||
return {
|
||||
detail_count: details.length,
|
||||
total_quantity: details.reduce((sum, row) => sum + (Number(row.quantity) || 0), 0),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 反查退回收到登记单ID(同仓库 + 同运单号,取最新一条),用于主表回填。
|
||||
*
|
||||
* @param {number} warehouseId 仓库ID。
|
||||
* @param {string} waybillCode 运单号。
|
||||
* @return {Promise<number|null>} 退回收到单ID,未命中返回 null。
|
||||
*/
|
||||
async _resolveReturnReceivedId(warehouseId, waybillCode) {
|
||||
const { ctx } = this;
|
||||
try {
|
||||
const received = await ctx.model.ReturnReceived.findOne({
|
||||
where: { warehouse_id: warehouseId, waybill_code: waybillCode },
|
||||
attributes: [ 'id' ],
|
||||
order: [[ 'id', 'DESC' ]],
|
||||
raw: true,
|
||||
});
|
||||
return received ? Number(received.id) || null : null;
|
||||
} catch (err) {
|
||||
ctx.logger.warn(`[returnUnpack._resolveReturnReceivedId] 反查退回收到单失败: ${err.message}`);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 将订单明细逐行映射为拆包明细行(1:1 复制,不做合并/换算)。
|
||||
* 口径参考 addDetail:有 stock_id 记 is_recognized=1;spec 仅在取到库存 sku_property 时填;
|
||||
* quantity 取订单行 plan_qty(最小 1);product_status 固定 normal;
|
||||
* product_snapshot 仅在取到库存详情时写入。
|
||||
*
|
||||
* @param {Array<Object>} orderItems 订单明细行(来自 afterSale._resolveOrderDetail 的 items)。
|
||||
* @return {Promise<Array<Object>>} 拆包明细行数组(不含 unpack_id / warehouse_id)。
|
||||
*/
|
||||
async _buildTransferDetailRows(orderItems) {
|
||||
const { ctx } = this;
|
||||
const stockIds = [ ...new Set(
|
||||
orderItems
|
||||
.map(item => Number(item && item.stock_id))
|
||||
.filter(id => Number.isInteger(id) && id > 0)
|
||||
) ];
|
||||
|
||||
/** @type {Map<number, Object>} 库存详情快照映射 */
|
||||
const stockMap = new Map();
|
||||
if (stockIds.length > 0) {
|
||||
try {
|
||||
const stockRows = await ctx.model.StockWarehouse.findAll({
|
||||
where: { id: { [this.app.Sequelize.Op.in]: stockIds } },
|
||||
attributes: [
|
||||
'id', 'item_code', 'goods_code', 'item_name',
|
||||
'sku_property', 'stock_unit', 'item_type',
|
||||
],
|
||||
raw: true,
|
||||
});
|
||||
for (const row of stockRows) {
|
||||
stockMap.set(Number(row.id), row);
|
||||
}
|
||||
} catch (err) {
|
||||
ctx.logger.warn(`[returnUnpack._buildTransferDetailRows] 批量查询库存详情失败: ${err.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
return orderItems.map(item => {
|
||||
const stockId = Number(item && item.stock_id);
|
||||
const stock = stockId > 0 ? (stockMap.get(stockId) || null) : null;
|
||||
const isRecognized = stockId > 0 ? 1 : 0;
|
||||
return {
|
||||
stock_id: isRecognized ? stockId : null,
|
||||
is_recognized: isRecognized,
|
||||
item_code: String((item && item.item_code) || (stock && stock.item_code) || '').slice(0, 50) || null,
|
||||
item_name: String((item && item.item_name) || (stock && stock.item_name) || '未知商品').slice(0, 255),
|
||||
spec: stock && stock.sku_property ? String(stock.sku_property).slice(0, 100) : null,
|
||||
quantity: Math.max(1, parseInt(item && item.plan_qty) || 1),
|
||||
product_status: 'normal',
|
||||
product_snapshot: stock ? JSON.stringify({
|
||||
item_code: stock.item_code || '',
|
||||
goods_code: stock.goods_code || '',
|
||||
item_name: stock.item_name || '',
|
||||
sku_property: stock.sku_property || '',
|
||||
stock_unit: stock.stock_unit || '',
|
||||
item_type: stock.item_type || '',
|
||||
}) : null,
|
||||
remark: null,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 按主键查询拆包单,并校验仓库隔离。
|
||||
*
|
||||
|
||||
@ -1,7 +1,5 @@
|
||||
'use strict';
|
||||
|
||||
const crypto = require('node:crypto');
|
||||
|
||||
const { Service } = require('egg');
|
||||
|
||||
const INTERNAL_WAVE_STRATEGY_VERSION_KEY = 'wave_strategy_version';
|
||||
@ -335,33 +333,6 @@ const WAREHOUSE_SETTING_FIELDS = Object.freeze([
|
||||
}),
|
||||
]);
|
||||
|
||||
// 仓库前端配置品牌文本字段元信息(对应 wms_warehouse_front_config,一仓一行)。
|
||||
// 域名与证书字段不在此列:domain/cert_pem/cert_key/cert_path/key_path 只能通过证书上传接口(saveFrontCert)变更。
|
||||
const FRONT_CONFIG_TEXT_FIELDS = Object.freeze([
|
||||
Object.freeze({ key: 'title', name: 'title', maxLength: 100 }),
|
||||
Object.freeze({ key: 'logo_url', name: 'logo_url', maxLength: 255 }),
|
||||
Object.freeze({ key: 'favicon_url', name: 'favicon_url', maxLength: 255 }),
|
||||
Object.freeze({ key: 'login_bg_url', name: 'login_bg_url', maxLength: 255 }),
|
||||
]);
|
||||
|
||||
// 公共按域名拉取接口对外输出的字段白名单(安全红线:严禁输出证书/私钥内容与证书路径、同步状态等内部字段)
|
||||
const FRONT_CONFIG_PUBLIC_FIELDS = Object.freeze([
|
||||
'domain',
|
||||
'title',
|
||||
'logo_url',
|
||||
'login_bg_url',
|
||||
'favicon_url',
|
||||
'theme',
|
||||
]);
|
||||
|
||||
// 公共按域名拉取接口缓存 TTL(秒)
|
||||
const FRONT_CONFIG_PUBLIC_CACHE_TTL_SECONDS = 600;
|
||||
// 未登记域名空缓存 TTL(秒):短缓存兜底防穿透,域名登记后由保存流程主动失效
|
||||
const FRONT_CONFIG_PUBLIC_MISS_CACHE_TTL_SECONDS = 60;
|
||||
|
||||
// 证书/私钥 PEM 文本最大长度(正常 RSA/ECC 证书远小于该值,防止异常大报文)
|
||||
const FRONT_CONFIG_PEM_MAX_LENGTH = 64 * 1024;
|
||||
|
||||
class SettingWarehouseService extends Service {
|
||||
/**
|
||||
* 读取默认快递与平台编码选项,查询失败时自动降级为空列表。
|
||||
@ -727,658 +698,6 @@ class SettingWarehouseService extends Service {
|
||||
cache_cleared_warehouse_id: cacheWarehouseId,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 校验并规范化仓库前端配置的字符串字段。
|
||||
*
|
||||
* @param {*} value 原始值。
|
||||
* @param {string} fieldName 字段名。
|
||||
* @param {number} maxLength 字段最大长度。
|
||||
* @return {string|null} 规范化后的字符串;空值返回 null(表示清空)。
|
||||
* @throws {Error} 超长时抛出,状态码 400。
|
||||
*/
|
||||
normalizeFrontConfigText(value, fieldName, maxLength) {
|
||||
if (value === undefined || value === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const normalized = String(value).trim();
|
||||
if (!normalized) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (normalized.length > maxLength) {
|
||||
throw this.createError(`${fieldName} 长度不能超过 ${maxLength} 字符`, 400);
|
||||
}
|
||||
|
||||
return normalized;
|
||||
}
|
||||
|
||||
/**
|
||||
* 校验并规范化仓库前端配置的 theme 字段。
|
||||
*
|
||||
* @param {*} value 原始值(对象或 JSON 字符串)。
|
||||
* @return {Object|null} 规范化后的主题对象;空值返回 null(表示清空)。
|
||||
* @throws {Error} 非合法 JSON 对象时抛出,状态码 400。
|
||||
*/
|
||||
normalizeFrontConfigTheme(value) {
|
||||
if (value === undefined || value === null || value === '') {
|
||||
return null;
|
||||
}
|
||||
|
||||
let parsed = value;
|
||||
if (typeof value === 'string') {
|
||||
try {
|
||||
parsed = JSON.parse(value.trim());
|
||||
} catch (error) {
|
||||
throw this.createError('theme 必须是合法的 JSON 对象', 400);
|
||||
}
|
||||
}
|
||||
|
||||
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
|
||||
throw this.createError('theme 必须是合法的 JSON 对象', 400);
|
||||
}
|
||||
|
||||
return parsed;
|
||||
}
|
||||
|
||||
/**
|
||||
* 校验非空 domain 的全局唯一性(可空列唯一索引允许多 NULL,数据库不兜底)。
|
||||
*
|
||||
* @param {string} domain 待校验域名(非空)。
|
||||
* @param {number} excludeWarehouseId 排除的仓库 ID(当前仓库自身)。
|
||||
* @return {Promise<void>} 无返回值。
|
||||
* @throws {Error} domain 已被其他仓库使用时抛出,状态码 409。
|
||||
*/
|
||||
async assertFrontConfigDomainUnique(domain, excludeWarehouseId) {
|
||||
const configModel = this.ctx.model && this.ctx.model.WarehouseFrontConfig;
|
||||
if (!configModel || typeof configModel.findOne !== 'function') {
|
||||
throw this.createError('WarehouseFrontConfig model 不可用', 500);
|
||||
}
|
||||
|
||||
const { Op } = this.app.Sequelize;
|
||||
const existing = await configModel.findOne({
|
||||
where: {
|
||||
domain,
|
||||
store_id: { [Op.ne]: excludeWarehouseId },
|
||||
},
|
||||
attributes: [ 'store_id', 'domain' ],
|
||||
});
|
||||
|
||||
if (existing) {
|
||||
throw this.createError(`域名 ${domain} 已被其他仓库使用`, 409);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 构建仓库前端配置的输出对象(无记录时返回默认空配置)。
|
||||
*
|
||||
* 证书回显:输出证书原文(cert_pem)与私钥原文(key_pem,取自 cert_key 列),
|
||||
* 不再输出 cert_path/key_path 路径字段(保存时已置空,尚无真实路径)。
|
||||
* 安全说明:私钥原文回显仅限仓库主体登录后的 settings 页
|
||||
* (getFrontConfig/saveFrontConfig/saveFrontCert 三个需登录接口复用本输出);
|
||||
* 公共无鉴权接口 getFrontConfigByDomain 走 buildFrontConfigPublicOutput 白名单,
|
||||
* 不经过本方法,仍不暴露证书/私钥内容与同步状态等内部字段。
|
||||
*
|
||||
* @param {Object|null} record 配置记录实例(可为 null)。
|
||||
* @param {number} warehouseId 当前仓库 ID。
|
||||
* @return {Object} 规范化输出对象。
|
||||
*/
|
||||
buildFrontConfigOutput(record, warehouseId) {
|
||||
const hasRecord = !!(record && typeof record.get === 'function');
|
||||
const getValue = key => (hasRecord ? record.get(key) : null);
|
||||
|
||||
return {
|
||||
warehouse_id: Number(warehouseId || 0),
|
||||
domain: hasRecord ? (getValue('domain') || '') : '',
|
||||
title: hasRecord ? (getValue('title') || '') : '',
|
||||
logo_url: hasRecord ? (getValue('logo_url') || '') : '',
|
||||
favicon_url: hasRecord ? (getValue('favicon_url') || '') : '',
|
||||
login_bg_url: hasRecord ? (getValue('login_bg_url') || '') : '',
|
||||
theme: hasRecord ? (getValue('theme') || null) : null,
|
||||
cert_pem: hasRecord ? (getValue('cert_pem') || '') : '',
|
||||
key_pem: hasRecord ? (getValue('cert_key') || '') : '',
|
||||
cert_expire_at: hasRecord ? (getValue('cert_expire_at') || null) : null,
|
||||
sync_status: hasRecord ? Number(getValue('sync_status') || 0) : 0,
|
||||
sync_attempts: hasRecord ? Number(getValue('sync_attempts') || 0) : 0,
|
||||
last_sync_error: hasRecord ? (getValue('last_sync_error') || '') : '',
|
||||
last_synced_at: hasRecord ? (getValue('last_synced_at') || null) : null,
|
||||
updated_at: hasRecord ? (getValue('updated_at') || null) : null,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询当前仓库的前端独立部署配置(settings 页回显)。
|
||||
*
|
||||
* 需登录(token 绑定仓库上下文,只能查到自己仓库的配置),
|
||||
* 响应含证书原文(cert_pem)与私钥原文(key_pem),供仓库主体 settings 页回显;
|
||||
* 公共无鉴权接口 getFrontConfigByDomain 仍只返回公开字段白名单。
|
||||
*
|
||||
* @return {Promise<Object>} 配置输出对象;无记录时返回默认空配置。
|
||||
* @throws {Error} 未识别到当前仓库时抛出,状态码 400。
|
||||
*/
|
||||
async getFrontConfig() {
|
||||
const warehouseId = this.getCurrentWarehouseId();
|
||||
|
||||
const configModel = this.ctx.model && this.ctx.model.WarehouseFrontConfig;
|
||||
if (!configModel || typeof configModel.findOne !== 'function') {
|
||||
throw this.createError('WarehouseFrontConfig model 不可用', 500);
|
||||
}
|
||||
|
||||
const record = await configModel.findOne({
|
||||
where: {
|
||||
store_id: warehouseId,
|
||||
},
|
||||
});
|
||||
|
||||
return this.buildFrontConfigOutput(record, warehouseId);
|
||||
}
|
||||
|
||||
/**
|
||||
* 构建前端配置公共拉取接口的缓存键(按域名)。
|
||||
*
|
||||
* @param {string} domain 域名(内部会 trim 规范化)。
|
||||
* @return {string} Redis 缓存键。
|
||||
*/
|
||||
getFrontConfigDomainCacheKey(domain) {
|
||||
return `front:config:domain:${String(domain || '').trim()}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 构建前端配置公共拉取接口的输出对象(仅公开字段白名单)。
|
||||
*
|
||||
* 安全红线:只输出 FRONT_CONFIG_PUBLIC_FIELDS 白名单字段,
|
||||
* 严禁输出 cert_pem/cert_key 证书与私钥内容,以及 cert_path、key_path、
|
||||
* sync_status、sync_attempts、last_sync_error 等内部字段。
|
||||
*
|
||||
* @param {Object} record 配置记录实例。
|
||||
* @return {Object} 仅含公开字段的输出对象。
|
||||
*/
|
||||
buildFrontConfigPublicOutput(record) {
|
||||
const hasRecord = !!(record && typeof record.get === 'function');
|
||||
const getValue = key => (hasRecord ? record.get(key) : null);
|
||||
|
||||
const output = {};
|
||||
for (const key of FRONT_CONFIG_PUBLIC_FIELDS) {
|
||||
const value = hasRecord ? getValue(key) : null;
|
||||
output[key] = key === 'theme' ? (value || null) : (value || '');
|
||||
}
|
||||
return output;
|
||||
}
|
||||
|
||||
/**
|
||||
* 清理指定域名的前端配置公共拉取缓存(空域名跳过)。
|
||||
*
|
||||
* @param {string} domain 待清理的域名。
|
||||
* @return {Promise<void>} 无返回值。
|
||||
*/
|
||||
async clearFrontConfigDomainCache(domain) {
|
||||
const normalizedDomain = String(domain || '').trim();
|
||||
if (!normalizedDomain) {
|
||||
return;
|
||||
}
|
||||
|
||||
await this.deleteCacheByKey(this.getFrontConfigDomainCacheKey(normalizedDomain));
|
||||
}
|
||||
|
||||
/**
|
||||
* 按域名查询前端配置(公共无鉴权接口业务实现,Redis 缓存 + 查库兜底)。
|
||||
*
|
||||
* 安全红线:只返回公开字段(domain/title/logo_url/login_bg_url/favicon_url/theme),
|
||||
* 严禁返回 cert_pem/cert_key 证书与私钥内容,以及 cert_path/key_path/
|
||||
* sync_status/sync_attempts/last_sync_error 等内部字段。
|
||||
*
|
||||
* @param {string} domain 待查询域名。
|
||||
* @return {Promise<Object>} 仅含公开字段的配置对象。
|
||||
* @throws {Error} domain 为空时抛出 400;未登记域名抛出 404;数据库异常抛出 500。
|
||||
*/
|
||||
async getFrontConfigByDomain(domain) {
|
||||
const normalizedDomain = String(domain || '').trim();
|
||||
|
||||
if (!normalizedDomain) {
|
||||
throw this.createError('domain 不能为空', 400);
|
||||
}
|
||||
|
||||
if (normalizedDomain.length > 100) {
|
||||
throw this.createError('domain 长度不能超过 100 字符', 400);
|
||||
}
|
||||
|
||||
const cacheKey = this.getFrontConfigDomainCacheKey(normalizedDomain);
|
||||
|
||||
// 优先读缓存;Redis 异常时降级查库(getCacheAsync 内部已做 Redis 降级处理)
|
||||
if (this.app && typeof this.app.getCacheAsync === 'function') {
|
||||
try {
|
||||
const cached = await this.app.getCacheAsync(cacheKey);
|
||||
|
||||
// 未登记域名空缓存标记:直接按未配置返回,防穿透
|
||||
if (cached && typeof cached === 'object' && cached.configured === false) {
|
||||
throw this.createError('域名未配置', 404);
|
||||
}
|
||||
|
||||
if (cached && typeof cached === 'object' && typeof cached.domain === 'string' && cached.domain) {
|
||||
return cached;
|
||||
}
|
||||
} catch (error) {
|
||||
if (Number(error.code) === 404) {
|
||||
throw error;
|
||||
}
|
||||
this.ctx.logger.warn('[SettingWarehouseService.getFrontConfigByDomain] 读取缓存失败,降级查库: %s', error.message);
|
||||
}
|
||||
}
|
||||
|
||||
const configModel = this.ctx.model && this.ctx.model.WarehouseFrontConfig;
|
||||
if (!configModel || typeof configModel.findOne !== 'function') {
|
||||
throw this.createError('WarehouseFrontConfig model 不可用', 500);
|
||||
}
|
||||
|
||||
const record = await configModel.findOne({
|
||||
where: {
|
||||
domain: normalizedDomain,
|
||||
},
|
||||
});
|
||||
|
||||
if (!record) {
|
||||
// 缓存穿透兜底:未登记域名写短 TTL 空缓存,防止高频探测打穿数据库
|
||||
if (this.app && typeof this.app.setCacheAsync === 'function') {
|
||||
try {
|
||||
await this.app.setCacheAsync(cacheKey, { configured: false }, FRONT_CONFIG_PUBLIC_MISS_CACHE_TTL_SECONDS);
|
||||
} catch (error) {
|
||||
this.ctx.logger.warn('[SettingWarehouseService.getFrontConfigByDomain] 写入未命中空缓存失败: %s', error.message);
|
||||
}
|
||||
}
|
||||
throw this.createError('域名未配置', 404);
|
||||
}
|
||||
|
||||
const output = this.buildFrontConfigPublicOutput(record);
|
||||
|
||||
if (this.app && typeof this.app.setCacheAsync === 'function') {
|
||||
try {
|
||||
await this.app.setCacheAsync(cacheKey, output, FRONT_CONFIG_PUBLIC_CACHE_TTL_SECONDS);
|
||||
} catch (error) {
|
||||
this.ctx.logger.warn('[SettingWarehouseService.getFrontConfigByDomain] 写入缓存失败: %s', error.message);
|
||||
}
|
||||
}
|
||||
|
||||
return output;
|
||||
}
|
||||
|
||||
/**
|
||||
* 规范化证书/私钥 PEM 文本:去首尾空白,空值返回 null(表示未提供)。
|
||||
*
|
||||
* @param {*} value 原始值(PEM 文本)。
|
||||
* @param {string} fieldName 字段名(用于错误提示)。
|
||||
* @return {string|null} 规范化后的 PEM 文本;空值返回 null。
|
||||
* @throws {Error} 内容超过长度上限时抛出,状态码 400。
|
||||
*/
|
||||
normalizeFrontConfigPem(value, fieldName) {
|
||||
if (value === undefined || value === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const normalized = String(value).trim();
|
||||
if (!normalized) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (normalized.length > FRONT_CONFIG_PEM_MAX_LENGTH) {
|
||||
throw this.createError(`${fieldName} 内容长度不能超过 ${FRONT_CONFIG_PEM_MAX_LENGTH} 字符`, 400);
|
||||
}
|
||||
|
||||
return normalized;
|
||||
}
|
||||
|
||||
/**
|
||||
* 用 Node 内置 crypto.X509Certificate 解析证书 PEM 文本。
|
||||
*
|
||||
* @param {string} certPem 证书 PEM 文本。
|
||||
* @return {Object} 解析成功后的 X509Certificate 实例。
|
||||
* @throws {Error} 证书无法解析时抛出,状态码 400,统一文案“证书不合法”。
|
||||
*/
|
||||
parseFrontConfigCertPem(certPem) {
|
||||
try {
|
||||
return new crypto.X509Certificate(certPem);
|
||||
} catch (error) {
|
||||
throw this.createError('证书不合法', 400);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 校验证书有效期:未生效或已过期的证书禁止提交。
|
||||
*
|
||||
* @param {Object} cert 已解析的 X509Certificate 实例。
|
||||
* @return {void} 无返回值。
|
||||
* @throws {Error} 证书未生效或已过期时抛出,状态码 400,统一文案“证书不合法”。
|
||||
*/
|
||||
assertFrontConfigCertValid(cert) {
|
||||
const now = Date.now();
|
||||
const validFrom = new Date(cert.validFrom);
|
||||
const validTo = new Date(cert.validTo);
|
||||
|
||||
if (Number.isNaN(validFrom.getTime())) {
|
||||
throw this.createError('证书不合法', 400);
|
||||
}
|
||||
|
||||
if (validFrom.getTime() > now) {
|
||||
throw this.createError('证书不合法', 400);
|
||||
}
|
||||
|
||||
if (Number.isNaN(validTo.getTime())) {
|
||||
throw this.createError('证书不合法', 400);
|
||||
}
|
||||
|
||||
if (validTo.getTime() <= now) {
|
||||
throw this.createError('证书不合法', 400);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 收集证书可覆盖的域名列表:SAN 中的 DNS 项与 CN,统一转小写。
|
||||
*
|
||||
* @param {Object} cert 已解析的 X509Certificate 实例。
|
||||
* @return {string[]} 小写域名列表。
|
||||
*/
|
||||
collectFrontConfigCertNames(cert) {
|
||||
const names = [];
|
||||
|
||||
const sanText = cert.subjectAltName || '';
|
||||
for (const part of String(sanText).split(',')) {
|
||||
const entry = String(part).trim();
|
||||
if (entry.startsWith('DNS:')) {
|
||||
const dnsName = entry.slice(4).trim();
|
||||
if (dnsName) {
|
||||
names.push(dnsName.toLowerCase());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const subjectText = cert.subject || '';
|
||||
const cnMatch = /CN\s*=\s*([^,\n]+)/i.exec(String(subjectText));
|
||||
if (cnMatch && cnMatch[1]) {
|
||||
names.push(cnMatch[1].trim().toLowerCase());
|
||||
}
|
||||
|
||||
return names;
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断证书域名列表是否覆盖目标域名(支持精确匹配与通配符 *.example.com)。
|
||||
*
|
||||
* @param {string[]} names 证书 SAN/CN 域名列表(小写)。
|
||||
* @param {string} domain 待校验域名。
|
||||
* @return {boolean} 是否覆盖。
|
||||
*/
|
||||
frontConfigCertCoversDomain(names, domain) {
|
||||
const target = String(domain).toLowerCase();
|
||||
if (!target) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return names.some(name => {
|
||||
const normalized = String(name).toLowerCase();
|
||||
if (normalized === target) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (normalized.startsWith('*.')) {
|
||||
const suffix = normalized.slice(1);
|
||||
return target.endsWith(suffix) && target.length > suffix.length;
|
||||
}
|
||||
|
||||
return false;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 校验私钥与证书是否成对:对比两者的 SPKI DER 公钥指纹。
|
||||
*
|
||||
* @param {string} keyPem 私钥 PEM 文本。
|
||||
* @param {Object} cert 已解析的 X509Certificate 实例。
|
||||
* @return {void} 无返回值。
|
||||
* @throws {Error} 私钥无法解析或与证书不匹配时抛出,状态码 400,统一文案“证书不合法”。
|
||||
*/
|
||||
validateFrontConfigKeyPem(keyPem, cert) {
|
||||
let publicKey;
|
||||
try {
|
||||
publicKey = crypto.createPublicKey(keyPem);
|
||||
} catch (error) {
|
||||
throw this.createError('证书不合法', 400);
|
||||
}
|
||||
|
||||
const keySpki = publicKey.export({ type: 'spki', format: 'der' });
|
||||
const certSpki = cert.publicKey.export({ type: 'spki', format: 'der' });
|
||||
if (Buffer.compare(keySpki, certSpki) !== 0) {
|
||||
throw this.createError('证书不合法', 400);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 校验当前主体为仓库主体(前端独立部署配置仅仓库主体可操作)。
|
||||
*
|
||||
* @return {Promise<Object>} 当前主体对象(含 id/company_name/project/isWarehouse/status)。
|
||||
* @throws {Error} 签约关系服务不可用时抛出 500;非仓库主体时抛出 403。
|
||||
*/
|
||||
async assertFrontConfigWarehouseSubject() {
|
||||
const storeWarehouseService = this.ctx.service && this.ctx.service.systems && this.ctx.service.systems.storeWarehouse;
|
||||
if (!storeWarehouseService || typeof storeWarehouseService.getCurrentSubject !== 'function') {
|
||||
throw this.createError('签约关系服务不可用', 500);
|
||||
}
|
||||
|
||||
const currentSubject = await storeWarehouseService.getCurrentSubject();
|
||||
if (!currentSubject || !currentSubject.isWarehouse) {
|
||||
throw this.createError('仅仓库主体可配置前端独立部署', 403);
|
||||
}
|
||||
|
||||
return currentSubject;
|
||||
}
|
||||
|
||||
/**
|
||||
* 保存当前仓库前端独立部署品牌配置(upsert,一仓一行,仅品牌字段部分更新)。
|
||||
*
|
||||
* 域名与证书不在本接口受理范围:domain 变更必须走 saveFrontCert 重新校验证书;
|
||||
* cert_pem/key_pem/cert_path/key_path/cert_expire_at 一律不受理(方法层白名单过滤)。
|
||||
* 保存仍视为一次配置变更:同步状态重置为待同步,写库成功后清理当前 domain 的公共拉取缓存。
|
||||
*
|
||||
* @param {Object} [data={}] 请求参数。
|
||||
* @param {string} [data.title] 站点标题(≤100 字符,空值清空)。
|
||||
* @param {string} [data.logo_url] Logo 地址(≤255 字符,空值清空)。
|
||||
* @param {string} [data.favicon_url] 站点 favicon 图标地址(≤255 字符,空值清空)。
|
||||
* @param {string} [data.login_bg_url] 登录页背景图地址(≤255 字符,空值清空)。
|
||||
* @param {Object|string} [data.theme] 主题配置(合法 JSON 对象或 JSON 字符串,空值清空)。
|
||||
* @return {Promise<Object>} 保存后的配置输出对象(同步状态已重置为待同步;证书回显口径与 getFrontConfig 一致)。
|
||||
* @throws {Error} 非仓库主体时抛出 403;参数非法时抛出 400。
|
||||
*/
|
||||
async saveFrontConfig(data = {}) {
|
||||
const warehouseId = this.getCurrentWarehouseId();
|
||||
|
||||
// 仅仓库主体管理员可配置前端独立部署(isWarehouse 判定)
|
||||
await this.assertFrontConfigWarehouseSubject();
|
||||
|
||||
const configModel = this.ctx.model && this.ctx.model.WarehouseFrontConfig;
|
||||
if (!configModel || typeof configModel.findOne !== 'function') {
|
||||
throw this.createError('WarehouseFrontConfig model 不可用', 500);
|
||||
}
|
||||
|
||||
const patch = {};
|
||||
|
||||
for (const field of FRONT_CONFIG_TEXT_FIELDS) {
|
||||
if (Object.prototype.hasOwnProperty.call(data, field.key)) {
|
||||
patch[field.key] = this.normalizeFrontConfigText(data[field.key], field.name, field.maxLength);
|
||||
}
|
||||
}
|
||||
|
||||
if (Object.prototype.hasOwnProperty.call(data, 'theme')) {
|
||||
patch.theme = this.normalizeFrontConfigTheme(data.theme);
|
||||
}
|
||||
|
||||
// 保存即重置同步状态:本次保存待同步
|
||||
patch.sync_status = 0;
|
||||
patch.sync_attempts = 0;
|
||||
patch.last_sync_error = null;
|
||||
patch.last_synced_at = null;
|
||||
|
||||
let record = await configModel.findOne({
|
||||
where: {
|
||||
store_id: warehouseId,
|
||||
},
|
||||
});
|
||||
|
||||
// 品牌字段不改变 domain:写库成功后清理当前 domain 的公共拉取缓存即可
|
||||
const previousDomain = record ? String(record.get('domain') || '').trim() : '';
|
||||
|
||||
try {
|
||||
if (record) {
|
||||
await record.update(patch);
|
||||
} else {
|
||||
record = await configModel.create({
|
||||
store_id: warehouseId,
|
||||
...patch,
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
// 并发写入兜底:唯一索引冲突统一转为业务错误
|
||||
if (error && error.name === 'SequelizeUniqueConstraintError') {
|
||||
const conflictFields = error.fields || {};
|
||||
if (Object.prototype.hasOwnProperty.call(conflictFields, 'domain')) {
|
||||
throw this.createError(`域名 ${patch.domain || ''} 已被其他仓库使用`, 409);
|
||||
}
|
||||
throw this.createError('仓库前端配置保存冲突,请稍后重试', 409);
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
|
||||
// 回查一次再输出,避免实例上残留 CURRENT_TIMESTAMP 等字面量
|
||||
const savedRecord = await configModel.findByPk(record.id);
|
||||
|
||||
// 写库成功后清理公共拉取缓存(先写库后清缓存);清缓存失败仅记日志,不影响保存结果
|
||||
if (previousDomain) {
|
||||
await this.clearFrontConfigDomainCache(previousDomain)
|
||||
.catch(error => {
|
||||
this.ctx.logger.warn('[SettingWarehouseService.saveFrontConfig] 清理前端配置缓存失败: %s', error.message);
|
||||
});
|
||||
}
|
||||
|
||||
return this.buildFrontConfigOutput(savedRecord, warehouseId);
|
||||
}
|
||||
|
||||
/**
|
||||
* 上传当前仓库前端独立部署证书(domain + 证书/私钥成对,upsert 该仓库行的证书与域名信息)。
|
||||
*
|
||||
* 校验链:证书可解析 → 未生效拒绝 → 已过期拒绝 → 私钥与证书成对 →
|
||||
* 证书 SAN/CN 覆盖 domain(支持 *.example.com 通配,不覆盖返回 400)→
|
||||
* domain 全局唯一(非空,409)。
|
||||
* 证书校验链任一失败均返回统一文案“证书不合法”(400),不返回细节。
|
||||
* 通过后自动写入 cert_expire_at(证书 validTo 权威值,不接受前端传值),
|
||||
* 证书/私钥 PEM 内容直接写入 cert_pem/cert_key 列(内容仅定时任务读取,
|
||||
* 不写暂存文件);cert_path/key_path 保存时置空,避免内容已换而路径陈旧,
|
||||
* 等待未来定时任务部署后回填真实路径;同时更新该仓库行的 domain/cert_expire_at
|
||||
* 并重置同步状态;写库成功后清理旧域名与新域名的公共拉取缓存(先写库后清缓存)。
|
||||
*
|
||||
* @param {Object} [data={}] 请求参数。
|
||||
* @param {string} data.domain 仓库自持域名(必填,非空,≤100 字符,全局唯一)。
|
||||
* @param {string} data.pem 证书 PEM 文本(必填)。
|
||||
* @param {string} data.key 私钥 PEM 文本(必填,与证书成对)。
|
||||
* @return {Promise<Object>} 保存后的完整配置输出对象(含证书/私钥原文回显,口径与 getFrontConfig 一致)。
|
||||
* @throws {Error} 非仓库主体时抛出 403;参数非法/证书不合法时抛出 400(证书校验失败统一文案“证书不合法”);域名重复时抛出 409。
|
||||
*/
|
||||
async saveFrontCert(data = {}) {
|
||||
const warehouseId = this.getCurrentWarehouseId();
|
||||
|
||||
// 仅仓库主体管理员可上传前端独立部署证书(isWarehouse 判定)
|
||||
await this.assertFrontConfigWarehouseSubject();
|
||||
|
||||
const configModel = this.ctx.model && this.ctx.model.WarehouseFrontConfig;
|
||||
if (!configModel || typeof configModel.findOne !== 'function') {
|
||||
throw this.createError('WarehouseFrontConfig model 不可用', 500);
|
||||
}
|
||||
|
||||
// 入参必填校验:domain 非空且 ≤100;pem/key 必填(nginx 起 HTTPS 需要成对)
|
||||
const domain = this.normalizeFrontConfigText(data.domain, 'domain', 100);
|
||||
if (!domain) {
|
||||
throw this.createError('domain 不能为空', 400);
|
||||
}
|
||||
|
||||
const certPem = this.normalizeFrontConfigPem(data.pem, 'pem');
|
||||
if (!certPem) {
|
||||
throw this.createError('pem 不能为空', 400);
|
||||
}
|
||||
|
||||
const keyPem = this.normalizeFrontConfigPem(data.key, 'key');
|
||||
if (!keyPem) {
|
||||
throw this.createError('key 不能为空', 400);
|
||||
}
|
||||
|
||||
// 校验链:证书可解析 → 未生效/已过期拒绝 → 私钥匹配 → SAN/CN 覆盖 domain → domain 全局唯一
|
||||
const cert = this.parseFrontConfigCertPem(certPem);
|
||||
this.assertFrontConfigCertValid(cert);
|
||||
this.validateFrontConfigKeyPem(keyPem, cert);
|
||||
|
||||
const certNames = this.collectFrontConfigCertNames(cert);
|
||||
if (!this.frontConfigCertCoversDomain(certNames, domain)) {
|
||||
throw this.createError('证书不合法', 400);
|
||||
}
|
||||
|
||||
await this.assertFrontConfigDomainUnique(domain, warehouseId);
|
||||
|
||||
// 证书/私钥内容直接入库(不再写暂存文件),有效期以证书 validTo 权威写入。
|
||||
// cert_path/key_path 保存时置空:内容已换而路径陈旧,避免 nginx 误读;
|
||||
// 等待未来定时任务(Egg schedule/外部 crontab)部署后回填真实路径。
|
||||
const patch = {
|
||||
domain,
|
||||
cert_pem: certPem,
|
||||
cert_key: keyPem,
|
||||
cert_path: null,
|
||||
key_path: null,
|
||||
cert_expire_at: new Date(cert.validTo),
|
||||
// 保存即重置同步状态:本次上传待同步
|
||||
sync_status: 0,
|
||||
sync_attempts: 0,
|
||||
last_sync_error: null,
|
||||
last_synced_at: null,
|
||||
};
|
||||
|
||||
let record = await configModel.findOne({
|
||||
where: {
|
||||
store_id: warehouseId,
|
||||
},
|
||||
});
|
||||
|
||||
// 记录更新前的域名,写库成功后用于清理旧域名公共拉取缓存
|
||||
const previousDomain = record ? String(record.get('domain') || '').trim() : '';
|
||||
|
||||
try {
|
||||
if (record) {
|
||||
await record.update(patch);
|
||||
} else {
|
||||
record = await configModel.create({
|
||||
store_id: warehouseId,
|
||||
...patch,
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
// 并发写入兜底:唯一索引冲突统一转为业务错误
|
||||
if (error && error.name === 'SequelizeUniqueConstraintError') {
|
||||
const conflictFields = error.fields || {};
|
||||
if (Object.prototype.hasOwnProperty.call(conflictFields, 'domain')) {
|
||||
throw this.createError(`域名 ${domain} 已被其他仓库使用`, 409);
|
||||
}
|
||||
throw this.createError('仓库前端配置保存冲突,请稍后重试', 409);
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
|
||||
// 回查一次再输出,避免实例上残留 CURRENT_TIMESTAMP 等字面量
|
||||
const savedRecord = await configModel.findByPk(record.id);
|
||||
|
||||
// 写库成功后清理公共拉取缓存(先写库后清缓存:避免先清后写时并发读把旧值重新写回缓存)。
|
||||
// 需同时清理旧域名(更新前记录)与新域名(本次上传)两个 key;清缓存失败仅记日志,不影响保存结果。
|
||||
const affectedDomains = [ ...new Set([ previousDomain, domain ].filter(item => item)) ];
|
||||
await Promise.all(affectedDomains.map(affectedDomain => this.clearFrontConfigDomainCache(affectedDomain)
|
||||
.catch(error => {
|
||||
this.ctx.logger.warn('[SettingWarehouseService.saveFrontCert] 清理前端配置缓存失败: %s', error.message);
|
||||
})));
|
||||
|
||||
return this.buildFrontConfigOutput(savedRecord, warehouseId);
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = SettingWarehouseService;
|
||||
|
||||
@ -1,557 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
const MainService = require('../main');
|
||||
|
||||
/**
|
||||
* 非订单出库单(stockout)领域服务。
|
||||
*
|
||||
* 抽离原 `qimenMethods/stockout.js` 的核心实现,供奇门(stockout.create/query)
|
||||
* 与开放 API(openapi stockout.create/query)薄适配层共用:
|
||||
* - 落库 `wms_order_stockout` 主表 + `wms_order_stockout_items` 明细表;
|
||||
* - 创建时按明细计划数量锁定库存(库存锁标记 `QM_STOCKOUT`,与取消/确认/转单释放口径一致)。
|
||||
*
|
||||
* 入参沿用奇门报文结构 `data.request.deliveryOrder` / `data.request.orderLines`,
|
||||
* 上下文(storeId/warehouseId/warehouseCode/appKey/sourceType)由调用方通过
|
||||
* `options` 显式传入,避免领域服务实例依赖 setInfo 状态。
|
||||
*/
|
||||
class StockoutOrderService extends MainService {
|
||||
|
||||
/**
|
||||
* 解析出库单快递编码(独立于订单兜底链)。
|
||||
*
|
||||
* 口径:
|
||||
* 1. 货主开启 enable_external_express_code 且传了 logisticsCode 时,按
|
||||
* wms_express_setting 映射 → 系统快递列表匹配;
|
||||
* 2. 未传 / 未开启 / 匹配不到 → 使用出库单兜底快递编码
|
||||
* (stockout_default_express_code,默认 ZT 自提),不回退订单默认快递;
|
||||
* 不走订单的快递策略漏斗(matchPolicy)。
|
||||
* 解析失败仅告警不阻断建单(快递为空,可在确认前手工补填)。
|
||||
*
|
||||
* @param {Object} deliveryOrder 出库单头信息(奇门 deliveryOrder 节点)。
|
||||
* @param {Object} context 上下文,需包含 storeId / warehouseId。
|
||||
* @return {Promise<{ expressCode: string|null, expressName: string|null }>} 解析结果。
|
||||
*/
|
||||
async resolveStockoutExpress(deliveryOrder = {}, context = {}) {
|
||||
const { ctx } = this;
|
||||
const { storeId, warehouseId } = context;
|
||||
|
||||
let expressCode = null;
|
||||
let expressName = null;
|
||||
|
||||
try {
|
||||
const deliveryOrderService = ctx.service.systems.deliveryOrder;
|
||||
const policyConfig = await deliveryOrderService.getStoreWarehousePolicyConfig(storeId, warehouseId);
|
||||
const expressList = await ctx.service.systems.express.getExpressList();
|
||||
const findExpress = code => {
|
||||
const upperCode = String(code || '').trim().toUpperCase();
|
||||
if (!upperCode || !Array.isArray(expressList)) {
|
||||
return null;
|
||||
}
|
||||
return expressList.find(item => item
|
||||
&& String(item.code || item.value || '').trim().toUpperCase() === upperCode) || null;
|
||||
};
|
||||
const externalCode = String(deliveryOrder.logisticsCode || '').trim();
|
||||
const enableExternal = deliveryOrderService.normalizePolicyFlag(
|
||||
policyConfig && policyConfig.enable_external_express_code
|
||||
);
|
||||
|
||||
if (enableExternal && externalCode) {
|
||||
// 1) wms_express_setting 外部编码映射 → 系统快递编码
|
||||
const settingSnapshot = await deliveryOrderService.resolveExpressSettingSnapshot(externalCode, warehouseId);
|
||||
if (settingSnapshot && settingSnapshot.expressCode) {
|
||||
const sysCode = String(settingSnapshot.expressCode).trim();
|
||||
const sysItem = findExpress(sysCode);
|
||||
expressCode = sysCode;
|
||||
expressName = sysItem
|
||||
? String(sysItem.name || sysItem.label || sysCode).trim()
|
||||
: String(settingSnapshot.name || sysCode).trim();
|
||||
} else {
|
||||
// 2) 系统快递列表直接匹配
|
||||
const matched = findExpress(externalCode);
|
||||
if (matched) {
|
||||
expressCode = String(matched.code || matched.value || externalCode).trim();
|
||||
expressName = String(matched.name || matched.label || expressCode).trim();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!expressCode) {
|
||||
// 兜底:出库单兜底快递编码(货主配置,默认 ZT 自提),不回退订单默认快递
|
||||
const fallbackCode = String(policyConfig && policyConfig.stockout_default_express_code || '').trim() || 'ZT';
|
||||
const fallbackItem = findExpress(fallbackCode);
|
||||
expressCode = fallbackItem
|
||||
? String(fallbackItem.code || fallbackItem.value || fallbackCode).trim()
|
||||
: fallbackCode;
|
||||
expressName = fallbackItem
|
||||
? String(fallbackItem.name || fallbackItem.label || fallbackCode).trim()
|
||||
: fallbackCode;
|
||||
}
|
||||
} catch (err) {
|
||||
ctx.logger.warn(`[stockout.create] 快递编码解析失败,保持为空: ${err.message}`);
|
||||
}
|
||||
|
||||
return { expressCode, expressName };
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建出库单。
|
||||
*
|
||||
* 将请求的 deliveryOrder / orderLines 写入 `wms_order_stockout` 主表和
|
||||
* `wms_order_stockout_items` 明细表,并库存锁定,整个过程在一个数据库事务内完成,
|
||||
* 失败自动回滚。
|
||||
*
|
||||
* @param {Object} data 请求体,遵循奇门报文结构。
|
||||
* @param {Object} data.request 请求数据。
|
||||
* @param {Object} data.request.deliveryOrder 出库单头信息。
|
||||
* @param {Object} data.request.orderLines 出库单明细。
|
||||
* @param {Object|Object[]} data.request.orderLines.orderLine 明细行(单条为对象,多条为数组)。
|
||||
* @param {Object} options 上下文与来源。
|
||||
* @param {number} options.storeId 货主ID。
|
||||
* @param {number} options.warehouseId 仓库ID。
|
||||
* @param {string} [options.warehouseCode] 仓库编码。
|
||||
* @param {string} [options.appKey] 开放接口 app_key(用于 StockStore 降级匹配)。
|
||||
* @param {string} [options.sourceType='QM'] 来源类型(QM / API / WMS)。
|
||||
* @return {Promise<Object>} 返回 success / fail 结果。
|
||||
*/
|
||||
async create(data, options = {}) {
|
||||
const { app, ctx } = this;
|
||||
const { storeId, warehouseId, warehouseCode, appKey } = options;
|
||||
const sourceType = options.sourceType || 'QM';
|
||||
const { deliveryOrder, orderLines } = data.request;
|
||||
|
||||
// 单条 orderLine 转为数组
|
||||
let orderLine = orderLines && orderLines.orderLine;
|
||||
if (orderLine && orderLine.orderLineNo) {
|
||||
orderLine = [ orderLine ];
|
||||
}
|
||||
|
||||
if (!orderLine || !Array.isArray(orderLine) || orderLine.length === 0) {
|
||||
return this.fail('创建出库单失败,失败原因:\n没有有效的订单明细数据');
|
||||
}
|
||||
|
||||
const totalOrderLines = deliveryOrder.totalOrderLines || orderLine.length;
|
||||
|
||||
// 快递编码解析
|
||||
const { expressCode, expressName } = await this.resolveStockoutExpress(deliveryOrder, {
|
||||
storeId,
|
||||
warehouseId,
|
||||
});
|
||||
|
||||
// 收件人信息解析(receiverInfo 13 个标准字段落库,供转订单与确认回传使用)
|
||||
const receiver = deliveryOrder.receiverInfo && typeof deliveryOrder.receiverInfo === 'object'
|
||||
? deliveryOrder.receiverInfo
|
||||
: {};
|
||||
const receiverFields = {
|
||||
receiver_company: receiver.company,
|
||||
receiver_name: receiver.name,
|
||||
receiver_zip_code: receiver.zipCode,
|
||||
receiver_tel: receiver.tel,
|
||||
receiver_mobile: receiver.mobile,
|
||||
receiver_email: receiver.email,
|
||||
receiver_country_code: receiver.countryCode,
|
||||
receiver_province: receiver.province,
|
||||
receiver_city: receiver.city,
|
||||
receiver_area: receiver.area,
|
||||
receiver_town: receiver.town,
|
||||
receiver_detail_address: receiver.detailAddress,
|
||||
receiver_id: receiver.id,
|
||||
};
|
||||
for (const key of Object.keys(receiverFields)) {
|
||||
const rawValue = receiverFields[key];
|
||||
receiverFields[key] = rawValue === undefined || rawValue === null
|
||||
? null
|
||||
: String(rawValue).trim() || null;
|
||||
}
|
||||
|
||||
// 第一步:校验所有商品是否在 StockStore 中存在,并收集有效明细
|
||||
const errors = [];
|
||||
const items = [];
|
||||
for (let i = 0; i < orderLine.length; i++) {
|
||||
const line = orderLine[i];
|
||||
let wmsStock = await app.model.StockStore.findByPk(line.itemId);
|
||||
// 校验 StockStore 记录的 store_id 与当前上下文一致,防止跨货主越权
|
||||
if (wmsStock && Number(wmsStock.store_id) !== Number(storeId)) {
|
||||
wmsStock = null;
|
||||
}
|
||||
// 外部渠道 itemId 可能是平台商品标识或条码而非 WMS 主键,
|
||||
// 主键查不到或跨货主时降级按 item_code + 仓库货主维度查找
|
||||
if (!wmsStock && line.itemCode) {
|
||||
const stockWhere = {
|
||||
item_code: line.itemCode,
|
||||
warehouse_id: warehouseId,
|
||||
store_id: storeId,
|
||||
};
|
||||
if (appKey) {
|
||||
stockWhere.app_key = appKey;
|
||||
}
|
||||
wmsStock = await app.model.StockStore.findOne({ where: stockWhere });
|
||||
}
|
||||
if (!wmsStock) {
|
||||
errors.push(
|
||||
`SKU${line.itemId}商品《${line.itemName}》编码《${line.itemCode}》\n未同步推送到仓库`
|
||||
);
|
||||
continue;
|
||||
}
|
||||
if (!wmsStock.stock_id) {
|
||||
errors.push(
|
||||
`SKU${line.itemId}商品《${line.itemName}》编码《${line.itemCode}》wms无对应关系\n请联系仓库关联创建商品`
|
||||
);
|
||||
continue;
|
||||
}
|
||||
const planQty = parseInt(line.planQty) || 0;
|
||||
if (planQty <= 0) {
|
||||
errors.push(
|
||||
`SKU${line.itemId}商品《${line.itemName}》编码《${line.itemCode}》\n计划数量必须大于0`
|
||||
);
|
||||
continue;
|
||||
}
|
||||
items.push({
|
||||
orderLineNo: line.orderLineNo,
|
||||
ownerCode: line.ownerCode,
|
||||
itemCode: line.itemCode,
|
||||
itemId: line.itemId,
|
||||
itemName: line.itemName,
|
||||
planQty,
|
||||
inventoryType: line.inventoryType,
|
||||
stockId: wmsStock.stock_id,
|
||||
});
|
||||
}
|
||||
|
||||
if (errors.length > 0) {
|
||||
return this.fail(`创建出库单失败,失败原因:\n${errors.join('\n')}`);
|
||||
}
|
||||
|
||||
// 预取超卖配置,避免每次 lockItemStorages 在锁内回退查 DB
|
||||
const oversellConfig = await ctx.service.systems.stockStore
|
||||
.getStoreWarehousePolicyByStoreAndWarehouse(storeId, warehouseId);
|
||||
|
||||
// 第二步:在事务中写入主表 + 库存锁定 + 明细表
|
||||
const transaction = await ctx.model.transaction();
|
||||
try {
|
||||
const order = await ctx.model.OrderStockout.create(
|
||||
{
|
||||
stockout_order_code: deliveryOrder.deliveryOrderCode,
|
||||
order_type: deliveryOrder.orderType,
|
||||
total_order_lines: totalOrderLines,
|
||||
order_create_time: deliveryOrder.createTime
|
||||
? new Date(deliveryOrder.createTime)
|
||||
: null,
|
||||
remark: deliveryOrder.remark || null,
|
||||
express_code: expressCode,
|
||||
express_name: expressName,
|
||||
...receiverFields,
|
||||
warehouse_id: warehouseId,
|
||||
store_id: storeId,
|
||||
qimen_owner_code: items[0].ownerCode,
|
||||
qimen_warehouse_code: warehouseCode,
|
||||
source_type: sourceType,
|
||||
created_at: new Date(),
|
||||
updated_at: new Date(),
|
||||
},
|
||||
{ transaction }
|
||||
);
|
||||
|
||||
const orderId = order.id;
|
||||
|
||||
// 库存锁定:按 stockId 升序排序后逐个加锁,避免死锁
|
||||
const sortedItems = [ ...items ].sort((a, b) => a.stockId - b.stockId);
|
||||
for (const item of sortedItems) {
|
||||
const lockResult = await ctx.service.systems.stockStore.lockItemStorages(
|
||||
item.stockId,
|
||||
item.planQty,
|
||||
transaction,
|
||||
oversellConfig,
|
||||
{ orderType: 'QM_STOCKOUT', orderNo: deliveryOrder.deliveryOrderCode, orderId }
|
||||
);
|
||||
if (!lockResult.success) {
|
||||
throw new Error(
|
||||
`SKU${item.itemId}商品《${item.itemName}》编码《${item.itemCode}》\n库存锁定失败: ${lockResult.error}`
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// 批量创建明细
|
||||
const now = new Date();
|
||||
const itemRecords = items.map(item => ({
|
||||
order_id: orderId,
|
||||
order_line_no: item.orderLineNo,
|
||||
owner_code: item.ownerCode,
|
||||
item_code: item.itemCode,
|
||||
item_id: item.itemId,
|
||||
item_name: item.itemName,
|
||||
plan_qty: item.planQty,
|
||||
inventory_type: item.inventoryType,
|
||||
stock_id: item.stockId,
|
||||
created_at: now,
|
||||
updated_at: now,
|
||||
}));
|
||||
|
||||
await ctx.model.OrderStockoutItems.bulkCreate(itemRecords, {
|
||||
transaction,
|
||||
validate: true,
|
||||
});
|
||||
|
||||
await transaction.commit();
|
||||
|
||||
return this.success('出库单创建成功', {
|
||||
stockoutOrderId: order.id,
|
||||
stockoutOrderCode: order.stockout_order_code,
|
||||
});
|
||||
} catch (err) {
|
||||
await transaction.rollback();
|
||||
ctx.logger.error('[stockout.create] 事务写入失败:', err);
|
||||
return this.fail(`创建出库单失败,失败原因:\n${err.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询出库单。
|
||||
*
|
||||
* 根据 deliveryOrderCode 查 `wms_order_stockout` 主表,
|
||||
* 然后关联查 `wms_order_stockout_items` 明细,返回标准结构。
|
||||
*
|
||||
* @param {Object} data 请求体,遵循奇门报文结构。
|
||||
* @param {Object} data.request 请求数据。
|
||||
* @param {Object} data.request.deliveryOrder 出库单查询条件。
|
||||
* @param {string} data.request.deliveryOrder.deliveryOrderCode 出库单号。
|
||||
* @return {Promise<Object>} 返回 success / fail 结果。
|
||||
*/
|
||||
async query(data) {
|
||||
const { app, ctx } = this;
|
||||
const { deliveryOrderCode } = data.request.deliveryOrder;
|
||||
|
||||
// 查主表
|
||||
const order = await ctx.model.OrderStockout.findOne({
|
||||
where: { stockout_order_code: deliveryOrderCode },
|
||||
});
|
||||
if (!order) {
|
||||
return this.fail('未找到出库单');
|
||||
}
|
||||
|
||||
// 查明细
|
||||
const items = await ctx.model.OrderStockoutItems.findAll({
|
||||
where: { order_id: order.id },
|
||||
order: [[ 'order_line_no', 'ASC' ]],
|
||||
});
|
||||
|
||||
return this.success('成功', {
|
||||
totalLines: items.length,
|
||||
deliveryOrder: {
|
||||
deliveryOrderCode: order.stockout_order_code,
|
||||
deliveryOrderId: order.id,
|
||||
warehouseCode: order.qimen_warehouse_code,
|
||||
orderType: order.order_type,
|
||||
status: order.order_status,
|
||||
createTime: order.order_create_time ? app.formatDate(order.order_create_time) : null,
|
||||
remark: order.remark || '',
|
||||
},
|
||||
orderLines: {
|
||||
orderLine: items.map(item => ({
|
||||
orderLineNo: item.order_line_no,
|
||||
ownerCode: item.owner_code,
|
||||
itemCode: item.item_code,
|
||||
itemId: item.item_id,
|
||||
itemName: item.item_name,
|
||||
planQty: item.plan_qty,
|
||||
inventoryType: item.inventory_type,
|
||||
})),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 取消出库单(奇门 / openapi / systemMethods 共用)。
|
||||
*
|
||||
* 定位方式:优先按 stockoutOrderCode,其次按 id;上下文(storeId / warehouseId /
|
||||
* operatorLabel)一律由 options 显式传入,不读取 ctx.user。仅 CREATED / PENDING
|
||||
* 状态允许取消:事务内(行锁)释放创建时占用的库存锁定(QM_STOCKOUT,写 UNLOCK
|
||||
* 流水),状态置 CANCELLED 并写操作日志;已 CANCELLED 幂等返回成功;
|
||||
* COMPLETED / TRANSFERRED 等其他状态拒绝取消。
|
||||
* 取消成功后不需要向奇门 / 开放平台回传任何事件。
|
||||
*
|
||||
* @param {Object} data 请求体。
|
||||
* @param {string} [data.stockoutOrderCode] 出库单号(优先)。
|
||||
* @param {number} [data.id] 出库单ID。
|
||||
* @param {Object} options 上下文。
|
||||
* @param {number|null} [options.storeId] 货主ID(有值时参与定位条件)。
|
||||
* @param {number} options.warehouseId 仓库ID。
|
||||
* @param {string} [options.operatorLabel] 操作人标识(写入操作日志,如 qimen:xxx / openapi:xxx)。
|
||||
* @return {Promise<Object>} 统一成功/失败包装响应,成功时返回 id / stockout_order_code / order_status。
|
||||
*/
|
||||
async cancel(data = {}, options = {}) {
|
||||
const { ctx } = this;
|
||||
const { storeId, warehouseId, operatorLabel } = options;
|
||||
const stockoutOrderCode = String(data.stockoutOrderCode || '').trim();
|
||||
const id = Number(data.id || 0);
|
||||
const normalizedWarehouseId = Number(warehouseId) || 0;
|
||||
|
||||
if (normalizedWarehouseId <= 0) {
|
||||
return this.fail('缺少仓库上下文');
|
||||
}
|
||||
|
||||
if (!stockoutOrderCode && !(id > 0)) {
|
||||
return this.fail('出库单号不能为空');
|
||||
}
|
||||
|
||||
// 定位条件:仓库 + 货主(有值时)+ 软删除过滤;单号优先,否则按 ID
|
||||
const where = {
|
||||
warehouse_id: normalizedWarehouseId,
|
||||
deleted_at: null,
|
||||
};
|
||||
if (storeId !== undefined && storeId !== null && storeId !== '') {
|
||||
where.store_id = Number(storeId);
|
||||
}
|
||||
if (stockoutOrderCode) {
|
||||
where.stockout_order_code = stockoutOrderCode;
|
||||
} else {
|
||||
where.id = id;
|
||||
}
|
||||
|
||||
const transaction = await ctx.model.transaction();
|
||||
let order;
|
||||
try {
|
||||
// 行锁防并发取消 / 确认 / 转单
|
||||
order = await ctx.model.OrderStockout.findOne({
|
||||
where,
|
||||
transaction,
|
||||
lock: transaction.LOCK.UPDATE,
|
||||
});
|
||||
if (!order) {
|
||||
await transaction.rollback();
|
||||
return this.fail('未找到对应的出库单');
|
||||
}
|
||||
|
||||
// 幂等:已取消直接返回成功,不重复释放库存
|
||||
if (String(order.order_status || '').trim() === 'CANCELLED') {
|
||||
await transaction.rollback();
|
||||
return this.success('取消出库单成功', {
|
||||
id: order.id,
|
||||
stockout_order_code: order.stockout_order_code,
|
||||
order_status: 'CANCELLED',
|
||||
});
|
||||
}
|
||||
|
||||
// 状态守卫:仅 CREATED / PENDING 允许取消(与 storage.stockout.cancel 同口径)
|
||||
if (!order.canCancel || !order.canCancel()) {
|
||||
await transaction.rollback();
|
||||
return this.fail(`出库单当前状态(${order.order_status})不允许取消`);
|
||||
}
|
||||
|
||||
const items = await ctx.model.OrderStockoutItems.findAll({
|
||||
where: { order_id: order.id },
|
||||
raw: true,
|
||||
transaction,
|
||||
});
|
||||
|
||||
// 释放创建时占用的库存锁定(口径与 storage.stockout.cancel 完全一致)
|
||||
let releasedQty = 0;
|
||||
for (const item of items) {
|
||||
const qty = Number(item.plan_qty) || 0;
|
||||
if (qty <= 0) continue;
|
||||
const releaseResult = await ctx.service.systems.stockStore.lockItemStorages(
|
||||
item.stock_id,
|
||||
-qty,
|
||||
transaction,
|
||||
null,
|
||||
{
|
||||
orderType: 'QM_STOCKOUT',
|
||||
orderNo: order.stockout_order_code,
|
||||
orderId: order.id,
|
||||
remark: '出库单取消释放锁定',
|
||||
}
|
||||
);
|
||||
if (!releaseResult.success) {
|
||||
// 已释放过(锁定不足)视为幂等成功,避免阻断重试
|
||||
const alreadyReleased = String(releaseResult.error || '').includes('释放数量超过已锁定库存');
|
||||
if (alreadyReleased) {
|
||||
ctx.logger.warn(`[stockout.cancel] 库存${item.stock_id}锁定已释放,跳过: ${releaseResult.error}`);
|
||||
continue;
|
||||
}
|
||||
throw new Error(`库存${item.stock_id}释放锁定失败: ${releaseResult.error}`);
|
||||
}
|
||||
releasedQty += qty;
|
||||
}
|
||||
|
||||
await ctx.model.OrderStockout.update(
|
||||
{ order_status: 'CANCELLED', sync_message: '已取消', updated_at: new Date() },
|
||||
{ where: { id: order.id }, transaction }
|
||||
);
|
||||
|
||||
await this._writeStockoutOperationLog(
|
||||
order,
|
||||
'STOCKOUT_CANCEL',
|
||||
`出库单已取消,释放锁定库存 ${releasedQty}`,
|
||||
{
|
||||
transaction,
|
||||
warehouseId: normalizedWarehouseId,
|
||||
operator: { id: null, name: operatorLabel || 'system' },
|
||||
}
|
||||
);
|
||||
|
||||
await transaction.commit();
|
||||
} catch (err) {
|
||||
try {
|
||||
await transaction.rollback();
|
||||
} catch (rollbackErr) {
|
||||
ctx.logger.error('[stockout.cancel] 事务回滚失败:', rollbackErr);
|
||||
}
|
||||
ctx.logger.error(`[stockout.cancel] 取消失败: ${err.message}`);
|
||||
return this.fail(`取消失败:${err.message}`);
|
||||
}
|
||||
|
||||
ctx.logger.info(`[stockout.cancel] 取消完成: ${order.stockout_order_code}`);
|
||||
return this.success('取消出库单成功', {
|
||||
id: order.id,
|
||||
stockout_order_code: order.stockout_order_code,
|
||||
order_status: 'CANCELLED',
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 写 wms_operation_log 操作日志(businessType=stockout),失败仅告警不影响主流程。
|
||||
*
|
||||
* 与 systemMethods/storage/stockout 历史日志口径一致;操作人 / 仓库信息由
|
||||
* options 显式传入,不读取 ctx.user(供奇门 / openapi 等无登录用户上下文渠道复用)。
|
||||
*
|
||||
* @param {Object} order 出库单实例或行。
|
||||
* @param {string} operationCode 操作编码(如 STOCKOUT_CANCEL)。
|
||||
* @param {string} message 日志内容。
|
||||
* @param {Object} [options={}] 选项。
|
||||
* @param {Object} [options.transaction] 数据库事务对象。
|
||||
* @param {number|null} [options.warehouseId] 仓库ID,缺省回退出库单自身 warehouse_id。
|
||||
* @param {Object} [options.operator={}] 操作人信息,含 id / name。
|
||||
* @return {Promise<void>} 无返回值。
|
||||
*/
|
||||
async _writeStockoutOperationLog(order, operationCode, message, options = {}) {
|
||||
const { ctx } = this;
|
||||
const opLogService = ctx.service && ctx.service.systems && ctx.service.systems.operationLog;
|
||||
if (!opLogService || typeof opLogService.createOperationLogs !== 'function') {
|
||||
ctx.logger.warn('[stockout] 操作日志服务不可用,跳过记录');
|
||||
return;
|
||||
}
|
||||
const operator = options.operator || {};
|
||||
try {
|
||||
await opLogService.createOperationLogs([
|
||||
{
|
||||
businessType: 'stockout',
|
||||
businessId: order.id,
|
||||
operationCode,
|
||||
operator: {
|
||||
id: operator.id ?? null,
|
||||
name: String(operator.name || 'system'),
|
||||
},
|
||||
extras: {
|
||||
warehouseId: options.warehouseId ?? order.warehouse_id ?? null,
|
||||
message,
|
||||
externalLogType: 'NONE',
|
||||
},
|
||||
},
|
||||
], { transaction: options.transaction });
|
||||
} catch (err) {
|
||||
ctx.logger.warn(`[stockout] 写操作日志失败: ${err.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
module.exports = StockoutOrderService;
|
||||
@ -978,18 +978,15 @@ class EntryService extends Service {
|
||||
|
||||
/**
|
||||
* 查询当前仓库可访问的入库单。
|
||||
* 默认仓库取 ctx.user.store_id,外部渠道可通过 warehouseId 显式覆盖。
|
||||
* @param {number} id 入库单ID
|
||||
* @param {number} [warehouseId] 仓库ID,缺省取 ctx.user.store_id
|
||||
* @return {Promise<Object|null>} 入库单实例
|
||||
*/
|
||||
async getOwnedEntryOrderById(id, warehouseId = null) {
|
||||
async getOwnedEntryOrderById(id) {
|
||||
const { ctx } = this;
|
||||
const normalizedWarehouseId = Number(warehouseId) || Number(ctx.user?.store_id) || 0;
|
||||
return await ctx.model.EntryOrder.findOne({
|
||||
where: {
|
||||
id,
|
||||
warehouse_id: normalizedWarehouseId,
|
||||
warehouse_id: ctx.user.store_id,
|
||||
is_enabled: 1,
|
||||
deleted_at: null,
|
||||
},
|
||||
@ -997,88 +994,14 @@ class EntryService extends Service {
|
||||
}
|
||||
|
||||
/**
|
||||
* 作废入库单(系统方法入口与奇门 / openapi 外部渠道共用)。
|
||||
*
|
||||
* 定位方式:
|
||||
* - 传 data.entryOrderCode(或 data.entry_order_code)时按单号定位,定位条件带
|
||||
* is_enabled / deleted_at / warehouse_id,有 storeId 时追加货主条件;
|
||||
* - 否则回退 data.id / data.ids(系统方法入口口径不变)。
|
||||
*
|
||||
* options 为外部渠道扩展,系统方法入口不传时行为与文案与历史版本完全一致:
|
||||
* - warehouseId:覆盖仓库上下文(默认 ctx.user.store_id);
|
||||
* - storeId:有值时参与定位;
|
||||
* - operatorLabel:覆盖操作人(写入回传与操作日志);
|
||||
* - skipExternalSync:true 时跳过 QM 来源的 qimenEntrySync 取消回传;
|
||||
* - idempotent:true 时已作废(CANCELLED)按幂等成功处理;
|
||||
* - notFoundMessage:未找到时的错误文案(默认「入库单不存在或无权访问」)。
|
||||
*
|
||||
* 作废入库单。
|
||||
* @param {Object} data 请求体
|
||||
* @param {number} [data.id] 单个入库单ID
|
||||
* @param {number[]} [data.ids] 批量入库单ID数组
|
||||
* @param {string} [data.entryOrderCode] 入库单号(外部渠道按单号定位,优先)
|
||||
* @param {Object} [options] 可选上下文(外部渠道扩展,系统方法入口不传)
|
||||
* @return {Promise<Object>} { code, message, data } 结构
|
||||
* @return {Promise<Object>} code/data/message 结构
|
||||
*/
|
||||
async cancel(data = {}, options = {}) {
|
||||
async cancel(data = {}) {
|
||||
const { ctx } = this;
|
||||
const {
|
||||
warehouseId: optWarehouseId,
|
||||
storeId: optStoreId,
|
||||
operatorLabel,
|
||||
skipExternalSync = false,
|
||||
idempotent = false,
|
||||
notFoundMessage,
|
||||
} = options;
|
||||
|
||||
// 仓库上下文:外部渠道通过 options.warehouseId 覆盖,系统方法入口取 ctx.user.store_id
|
||||
const warehouseId = Number(optWarehouseId) || Number(ctx.user?.store_id) || 0;
|
||||
|
||||
// 操作人:外部渠道通过 options.operatorLabel 覆盖,系统方法入口取 ctx.user
|
||||
const operator = String(operatorLabel || '').trim()
|
||||
? { id: null, name: String(operatorLabel).trim() }
|
||||
: {
|
||||
id: ctx.user?.employees_id || ctx.user?.id || '',
|
||||
name: ctx.user?.employees_name || '',
|
||||
};
|
||||
|
||||
const notFoundText = String(notFoundMessage || '').trim() || '入库单不存在或无权访问';
|
||||
|
||||
// 按单号定位(外部渠道),优先于 id / ids
|
||||
const entryOrderCode = String(data.entryOrderCode || data.entry_order_code || '').trim();
|
||||
if (entryOrderCode) {
|
||||
const where = {
|
||||
entry_order_code: entryOrderCode,
|
||||
warehouse_id: warehouseId,
|
||||
is_enabled: 1,
|
||||
deleted_at: null,
|
||||
};
|
||||
if (optStoreId !== undefined && optStoreId !== null && optStoreId !== '') {
|
||||
where.store_id = Number(optStoreId);
|
||||
}
|
||||
|
||||
const entryOrder = await ctx.model.EntryOrder.findOne({ where });
|
||||
if (!entryOrder) {
|
||||
return {
|
||||
code: 404,
|
||||
message: notFoundText,
|
||||
data: null,
|
||||
};
|
||||
}
|
||||
|
||||
const guard = this._guardCancelEntryOrder(entryOrder, idempotent);
|
||||
if (guard) {
|
||||
return {
|
||||
code: guard.code,
|
||||
message: guard.message,
|
||||
data: guard.code === 200 ? { ids: [ entryOrder.id ] } : null,
|
||||
};
|
||||
}
|
||||
|
||||
return await this._doCancelEntryOrder(entryOrder, { operator, skipExternalSync });
|
||||
}
|
||||
|
||||
// 按 id / ids 定位(系统方法入口,行为与文案保持不变)
|
||||
const normalizedResult = this.normalizeCancelEntryOrderIds(data);
|
||||
|
||||
if (!normalizedResult.ok) {
|
||||
return {
|
||||
code: normalizedResult.code || 400,
|
||||
@ -1090,29 +1013,101 @@ class EntryService extends Service {
|
||||
const orderIds = normalizedResult.ids || [];
|
||||
|
||||
for (const orderId of orderIds) {
|
||||
const entryOrder = await this.getOwnedEntryOrderById(orderId, warehouseId);
|
||||
const entryOrder = await this.getOwnedEntryOrderById(orderId);
|
||||
if (!entryOrder) {
|
||||
return {
|
||||
code: 404,
|
||||
message: notFoundText,
|
||||
message: '入库单不存在或无权访问',
|
||||
data: null,
|
||||
};
|
||||
}
|
||||
|
||||
const guard = this._guardCancelEntryOrder(entryOrder, idempotent);
|
||||
if (guard) {
|
||||
if (guard.code === 200) continue; // 幂等:已作废跳过,继续处理剩余单据
|
||||
// 6b: sync_status=SUCCESS 不可取消
|
||||
if (entryOrder.sync_status === 'SUCCESS') {
|
||||
return {
|
||||
code: guard.code,
|
||||
message: guard.message,
|
||||
code: 400,
|
||||
message: '入库单已完成回传,不可取消',
|
||||
data: null,
|
||||
};
|
||||
}
|
||||
|
||||
const cancelResult = await this._doCancelEntryOrder(entryOrder, { operator, skipExternalSync });
|
||||
if (cancelResult.code !== 200) {
|
||||
return cancelResult;
|
||||
if (entryOrder.order_status === 'COMPLETED') {
|
||||
return {
|
||||
code: 400,
|
||||
message: '已完成入库单不允许作废',
|
||||
data: null,
|
||||
};
|
||||
}
|
||||
|
||||
if (entryOrder.order_status === 'CANCELLED') {
|
||||
return {
|
||||
code: 400,
|
||||
message: '入库单已作废',
|
||||
data: null,
|
||||
};
|
||||
}
|
||||
|
||||
// 6a: QM 来源需发送取消同步
|
||||
if (String(entryOrder.source_type) === 'QM') {
|
||||
const entryItems = await ctx.model.EntryItems.findAll({
|
||||
where: { order_id: entryOrder.id },
|
||||
attributes: [ 'item_code', 'item_id', 'count', 'inventory_type', 'owner_code' ],
|
||||
raw: true,
|
||||
});
|
||||
|
||||
const orderLines = (entryItems || []).map((item, idx) => ({
|
||||
orderLineNo: idx + 1,
|
||||
ownerCode: item.owner_code || '',
|
||||
itemCode: item.item_code || '',
|
||||
itemId: item.item_id || '',
|
||||
inventoryType: item.inventory_type || 'ZP',
|
||||
planQty: item.count || 0,
|
||||
actualQty: 0, // 全部为 0,通知 ERP 关闭
|
||||
}));
|
||||
|
||||
const syncResult = await ctx.service.systems.inboundDirectLog.qimenEntrySync({
|
||||
entryOrder,
|
||||
orderLines,
|
||||
outBizCode: `CANCEL_${Date.now()}`,
|
||||
remark: '入库单取消',
|
||||
operator: {
|
||||
id: ctx.user?.employees_id || ctx.user?.id || '',
|
||||
name: ctx.user?.employees_name || '',
|
||||
},
|
||||
});
|
||||
|
||||
if (!syncResult.success) {
|
||||
return {
|
||||
code: 500,
|
||||
message: `取消失败: ${syncResult.message}`,
|
||||
data: null,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
// 更新状态
|
||||
await entryOrder.update({
|
||||
order_status: 'CANCELLED',
|
||||
updated_at: new Date(),
|
||||
});
|
||||
|
||||
// 回退关联收货单的入库状态,避免死锁
|
||||
await this._rollbackReceivingStorageStatus(entryOrder.id);
|
||||
|
||||
// 写操作日志
|
||||
await ctx.service.systems.operationLog.createOperationLog({
|
||||
businessType: 'entry_order',
|
||||
businessId: entryOrder.id,
|
||||
operationCode: 'ENTRY_ORDER_CANCEL',
|
||||
operator: {
|
||||
id: ctx.user?.employees_id || ctx.user?.id || '',
|
||||
name: ctx.user?.employees_name || '',
|
||||
},
|
||||
extras: {
|
||||
warehouseId: entryOrder.warehouse_id,
|
||||
message: '入库单已取消',
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
@ -1122,144 +1117,41 @@ class EntryService extends Service {
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 作废入库单的状态守卫校验。
|
||||
* 返回 null 表示允许继续作废;返回 { code, message } 表示拦截;
|
||||
* 幂等模式下已作废返回 { code: 200 }(由调用方决定跳过或直接成功),
|
||||
* 且幂等判定优先于回传状态判定(已作废单据的回传状态不影响重试幂等)。
|
||||
* @param {Object} entryOrder 入库单实例
|
||||
* @param {boolean} idempotent 是否幂等模式(已作废视为成功)
|
||||
* @return {{ code: number, message: string }|null} 守卫结果
|
||||
*/
|
||||
_guardCancelEntryOrder(entryOrder, idempotent = false) {
|
||||
// 幂等模式:已作废优先按成功处理(外部渠道重试口径)
|
||||
if (idempotent && entryOrder.order_status === 'CANCELLED') {
|
||||
return {
|
||||
code: 200,
|
||||
message: '作废成功',
|
||||
};
|
||||
}
|
||||
|
||||
// sync_status=SUCCESS 不可取消
|
||||
if (entryOrder.sync_status === 'SUCCESS') {
|
||||
return {
|
||||
code: 400,
|
||||
message: '入库单已完成回传,不可取消',
|
||||
};
|
||||
}
|
||||
|
||||
if (entryOrder.order_status === 'COMPLETED') {
|
||||
return {
|
||||
code: 400,
|
||||
message: '已完成入库单不允许作废',
|
||||
};
|
||||
}
|
||||
|
||||
if (entryOrder.order_status === 'CANCELLED') {
|
||||
return {
|
||||
code: 400,
|
||||
message: '入库单已作废',
|
||||
};
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 执行单个入库单的作废动作:QM 来源发送取消同步(actualQty 全 0)、
|
||||
* 状态置 CANCELLED、回退收货单占用、写 ENTRY_ORDER_CANCEL 操作日志。
|
||||
* @param {Object} entryOrder 入库单实例
|
||||
* @param {Object} [context] 上下文
|
||||
* @param {Object} [context.operator] 操作人信息 { id, name }
|
||||
* @param {boolean} [context.skipExternalSync] 是否跳过 QM 取消同步回传
|
||||
* @return {Promise<Object>} { code, message, data } 结构
|
||||
*/
|
||||
async _doCancelEntryOrder(entryOrder, context = {}) {
|
||||
const { ctx } = this;
|
||||
const { operator = {}, skipExternalSync = false } = context;
|
||||
|
||||
// QM 来源需发送取消同步(外部渠道不回传时跳过)
|
||||
if (String(entryOrder.source_type) === 'QM' && !skipExternalSync) {
|
||||
const entryItems = await ctx.model.EntryItems.findAll({
|
||||
where: { order_id: entryOrder.id },
|
||||
attributes: [ 'item_code', 'item_id', 'count', 'inventory_type', 'owner_code' ],
|
||||
raw: true,
|
||||
});
|
||||
|
||||
const orderLines = (entryItems || []).map((item, idx) => ({
|
||||
orderLineNo: idx + 1,
|
||||
ownerCode: item.owner_code || '',
|
||||
itemCode: item.item_code || '',
|
||||
itemId: item.item_id || '',
|
||||
inventoryType: item.inventory_type || 'ZP',
|
||||
planQty: item.count || 0,
|
||||
actualQty: 0, // 全部为 0,通知 ERP 关闭
|
||||
}));
|
||||
|
||||
const syncResult = await ctx.service.systems.inboundDirectLog.qimenEntrySync({
|
||||
entryOrder,
|
||||
orderLines,
|
||||
outBizCode: `CANCEL_${Date.now()}`,
|
||||
remark: '入库单取消',
|
||||
operator,
|
||||
});
|
||||
|
||||
if (!syncResult.success) {
|
||||
return {
|
||||
code: 500,
|
||||
message: `取消失败: ${syncResult.message}`,
|
||||
data: null,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
// 更新状态
|
||||
await entryOrder.update({
|
||||
order_status: 'CANCELLED',
|
||||
updated_at: new Date(),
|
||||
});
|
||||
|
||||
// 回退关联收货单的入库状态,避免死锁
|
||||
await this._rollbackReceivingStorageStatus(entryOrder.id);
|
||||
|
||||
// 写操作日志
|
||||
await ctx.service.systems.operationLog.createOperationLog({
|
||||
businessType: 'entry_order',
|
||||
businessId: entryOrder.id,
|
||||
operationCode: 'ENTRY_ORDER_CANCEL',
|
||||
operator,
|
||||
extras: {
|
||||
warehouseId: entryOrder.warehouse_id,
|
||||
message: '入库单已取消',
|
||||
},
|
||||
});
|
||||
|
||||
return {
|
||||
code: 200,
|
||||
message: '作废成功',
|
||||
data: { ids: [ entryOrder.id ] },
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 回退入库单关联收货单的入库状态(入库单作废时调用)。
|
||||
* 按绑定行数量台账逐单回收本入库单在收货单上的占用(不影响其他入库单的占用),
|
||||
* 并清空台账;失败不阻塞主流程,仅打印日志。
|
||||
* 失败不阻塞主流程,仅打印日志。
|
||||
* @param {number} entryOrderId 入库单ID
|
||||
* @return {Promise<void>}
|
||||
*/
|
||||
async _rollbackReceivingStorageStatus(entryOrderId) {
|
||||
const { ctx } = this;
|
||||
try {
|
||||
const result = await ctx.service.systems.receivingEntryMatch.rollbackEntryOrderBindings({
|
||||
entryOrderId,
|
||||
receivingId: null,
|
||||
softDeleteBinding: false,
|
||||
// 1. 查询关联的收货单ID列表
|
||||
const bindings = await ctx.model.EntryOrderReceiving.findAll({
|
||||
where: { entry_order_id: entryOrderId, deleted_at: null },
|
||||
attributes: [ 'receiving_id' ],
|
||||
raw: true,
|
||||
});
|
||||
|
||||
const receivingIds = (bindings || [ ]).map(b => b.receiving_id).filter(Boolean);
|
||||
if (receivingIds.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
// 2. 回退收货单主表 storage_status → 'none'
|
||||
await ctx.model.Receiving.update(
|
||||
{ storage_status: 'none', updated_at: new Date() },
|
||||
{ where: { id: { [ctx.app.Sequelize.Op.in]: receivingIds } } }
|
||||
);
|
||||
|
||||
// 3. 回退收货单明细 storage_status → 'none', stored_quantity → 0
|
||||
await ctx.model.ReceivingDetail.update(
|
||||
{ storage_status: 'none', stored_quantity: 0, updated_at: new Date() },
|
||||
{ where: { receiving_id: { [ctx.app.Sequelize.Op.in]: receivingIds } } }
|
||||
);
|
||||
|
||||
ctx.logger.info(
|
||||
`[storage.entry.cancel] 入库单 ${entryOrderId} 作废,已按台账回退收货单入库状态,` +
|
||||
`rolledBack=${JSON.stringify((result && result.rolled_back) || [])}`
|
||||
`[storage.entry.cancel] 入库单 ${entryOrderId} 作废,已回退收货单入库状态,receivingIds=[${receivingIds.join(',')}]`
|
||||
);
|
||||
} catch (err) {
|
||||
ctx.logger.error(
|
||||
@ -1534,10 +1426,9 @@ class EntryService extends Service {
|
||||
* @param {Array<Object>} params.receivingDetailRows 收货明细快照 [{ id, receiving_id, system_product_id, actual_quantity, stored_quantity }]
|
||||
* @param {Map<number, {inboundQty: number}>} params.stockInboundQtyMap stock_id -> 本次入库量
|
||||
* @param {Object} params.transaction Sequelize 事务对象
|
||||
* @param {number} [params.entryOrderId] 入库单 ID(传入时同步累加数量台账)
|
||||
* @return {Promise<void>}
|
||||
*/
|
||||
async _applyReceivingInboundUsage({ receivingDetailRows, stockInboundQtyMap, transaction, entryOrderId = null }) {
|
||||
async _applyReceivingInboundUsage({ receivingDetailRows, stockInboundQtyMap, transaction }) {
|
||||
const { ctx, app } = this;
|
||||
|
||||
if (!receivingDetailRows || receivingDetailRows.length === 0) return;
|
||||
@ -1562,7 +1453,6 @@ class EntryService extends Service {
|
||||
}
|
||||
|
||||
const touchedReceivingIds = new Set();
|
||||
const detailDeltaMap = new Map();
|
||||
|
||||
// 3. 逐商品分配本次入库量:使用了多少就写多少
|
||||
for (const [ stockId, plan ] of stockInboundQtyMap) {
|
||||
@ -1586,10 +1476,6 @@ class EntryService extends Service {
|
||||
transaction,
|
||||
});
|
||||
touchedReceivingIds.add(Number(detail.receiving_id));
|
||||
detailDeltaMap.set(Number(detail.id), {
|
||||
receivingId: Number(detail.receiving_id),
|
||||
quantity: delta,
|
||||
});
|
||||
left -= delta;
|
||||
}
|
||||
}
|
||||
@ -1625,15 +1511,6 @@ class EntryService extends Service {
|
||||
ctx.logger.info(
|
||||
`[storage.entry] 已回写收货单入库状态,receivingIds=[${[ ...touchedReceivingIds ].join(',')}]`
|
||||
);
|
||||
|
||||
// 5. 同步数量台账:本次落到各收货明细的分配量累加到对应绑定行
|
||||
if (entryOrderId && detailDeltaMap.size > 0) {
|
||||
await ctx.service.systems.receivingEntryMatch.recordLedgerAllocation({
|
||||
entryOrderId,
|
||||
detailDeltaMap,
|
||||
transaction,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@ -1982,7 +1859,6 @@ class EntryService extends Service {
|
||||
receivingDetailRows: receivingDetailsSnapshot,
|
||||
stockInboundQtyMap: stockPlanMap,
|
||||
transaction,
|
||||
entryOrderId: eo.id,
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@ -244,65 +244,6 @@ async function enrichInventoryStockAttachments(ctx, list = []) {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析并规范化库存效期维护入参中的日期值(统一输出 'YYYY-MM-DD')。
|
||||
*
|
||||
* 规则:
|
||||
* - `undefined`:未传该字段(不更新,返回 provided=false);
|
||||
* - `null` / 空串:清空该字段(provided=true 且 value=null);
|
||||
* - `'YYYY-MM-DD'` / `'YYYY/MM/DD'` / `'YYYY-MM-DD HH:mm:ss'` / ISO 字符串 / Date:
|
||||
* 仅取日期部分并校验为真实存在的日期,规范化为 'YYYY-MM-DD';
|
||||
* - 其它:视为非法(invalid=true),由调用方返回参数错误。
|
||||
*
|
||||
* @param {unknown} value 待解析的日期值
|
||||
* @return {{provided: boolean, value: (string|null), invalid: boolean}} 解析结果
|
||||
*/
|
||||
function parseStorageDateInput(value) {
|
||||
if (value === undefined) {
|
||||
return { provided: false, value: null, invalid: false };
|
||||
}
|
||||
|
||||
if (value === null || (typeof value === 'string' && value.trim() === '')) {
|
||||
return { provided: true, value: null, invalid: false };
|
||||
}
|
||||
|
||||
let year;
|
||||
let month;
|
||||
let day;
|
||||
|
||||
if (value instanceof Date) {
|
||||
if (Number.isNaN(value.getTime())) {
|
||||
return { provided: true, value: null, invalid: true };
|
||||
}
|
||||
year = value.getFullYear();
|
||||
month = value.getMonth() + 1;
|
||||
day = value.getDate();
|
||||
} else {
|
||||
const matched = /^(\d{4})[-/.](\d{1,2})[-/.](\d{1,2})([T\s].*)?$/.exec(String(value).trim());
|
||||
if (!matched) {
|
||||
return { provided: true, value: null, invalid: true };
|
||||
}
|
||||
year = Number(matched[1]);
|
||||
month = Number(matched[2]);
|
||||
day = Number(matched[3]);
|
||||
}
|
||||
|
||||
const parsed = new Date(year, month - 1, day);
|
||||
const isValidDate = parsed.getFullYear() === year
|
||||
&& parsed.getMonth() === month - 1
|
||||
&& parsed.getDate() === day;
|
||||
|
||||
if (!isValidDate || year < 1900 || year > 2999) {
|
||||
return { provided: true, value: null, invalid: true };
|
||||
}
|
||||
|
||||
return {
|
||||
provided: true,
|
||||
value: `${year}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')}`,
|
||||
invalid: false,
|
||||
};
|
||||
}
|
||||
|
||||
class InventoryService extends Service {
|
||||
|
||||
/**
|
||||
@ -1217,195 +1158,6 @@ class InventoryService extends Service {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 维护当前库存的生产日期与到期日期(wms_storage.production_date / expiry_date)。
|
||||
*
|
||||
* 口径说明:
|
||||
* 1) 按库存记录维度维护(单条 storage_id),仓库上下文来自当前登录用户(ctx.user.store_id),
|
||||
* 跨仓库的 storage_id 一律按「不存在」处理;
|
||||
* 2) 两个日期字段至少传一个;未传的字段保持库内原值;传 null 或空串表示清空该字段;
|
||||
* 3) 日期支持 'YYYY-MM-DD' / 'YYYY/MM/DD' / 'YYYY-MM-DD HH:mm:ss' / ISO 字符串,
|
||||
* 内部统一按 'YYYY-MM-DD' 落库;
|
||||
* 4) 校验合并后的生产日期不得晚于到期日期(未传字段取库内现值参与比较);
|
||||
* 5) 更新前后完全一致时直接返回 changed=false,不写库、不记日志。
|
||||
*
|
||||
* @param {Object} data 请求体
|
||||
* @param {number} data.storage_id 库存记录ID(wms_storage.id,必填)
|
||||
* @param {string|Date|null} [data.production_date] 生产日期(传 null/空串表示清空)
|
||||
* @param {string|Date|null} [data.expiry_date] 到期日期(传 null/空串表示清空)
|
||||
* @return {Promise<{code: number, message: string, data: (Object|null)}>} 统一 code/message/data 结构
|
||||
*/
|
||||
async updateExpiry(data = {}) {
|
||||
const { ctx } = this;
|
||||
const requestData = data && typeof data === 'object' ? data : {};
|
||||
|
||||
// ────────── 1. 参数校验 ──────────
|
||||
const storageId = Number(requestData.storage_id || 0);
|
||||
if (!Number.isInteger(storageId) || storageId <= 0) {
|
||||
return { code: 400, message: 'storage_id 必填且必须为正整数', data: null };
|
||||
}
|
||||
|
||||
const productionDateInput = parseStorageDateInput(requestData.production_date);
|
||||
const expiryDateInput = parseStorageDateInput(requestData.expiry_date);
|
||||
|
||||
if (productionDateInput.invalid) {
|
||||
return { code: 400, message: 'production_date 格式非法,须为 YYYY-MM-DD', data: null };
|
||||
}
|
||||
|
||||
if (expiryDateInput.invalid) {
|
||||
return { code: 400, message: 'expiry_date 格式非法,须为 YYYY-MM-DD', data: null };
|
||||
}
|
||||
|
||||
if (!productionDateInput.provided && !expiryDateInput.provided) {
|
||||
return { code: 400, message: 'production_date 与 expiry_date 至少传入一个', data: null };
|
||||
}
|
||||
|
||||
const warehouseId = Number(ctx.user && (ctx.user.store_id ?? ctx.user.warehouse_id)) || 0;
|
||||
if (warehouseId <= 0) {
|
||||
return { code: 400, message: '无法获取当前仓库信息', data: null };
|
||||
}
|
||||
|
||||
// ────────── 2. 事务内加锁维护 ──────────
|
||||
const transaction = await ctx.model.transaction();
|
||||
|
||||
try {
|
||||
const storageRecord = await ctx.model.Storage.findOne({
|
||||
where: {
|
||||
id: storageId,
|
||||
warehouse_id: warehouseId,
|
||||
is_enabled: 1,
|
||||
delete_at: null,
|
||||
},
|
||||
lock: transaction.LOCK.UPDATE,
|
||||
transaction,
|
||||
});
|
||||
|
||||
if (!storageRecord) {
|
||||
await transaction.rollback();
|
||||
return { code: 404, message: `库存记录不存在或无权访问: storage_id=${storageId}`, data: null };
|
||||
}
|
||||
|
||||
const beforeProductionDate = parseStorageDateInput(storageRecord.production_date).value;
|
||||
const beforeExpiryDate = parseStorageDateInput(storageRecord.expiry_date).value;
|
||||
|
||||
const nextProductionDate = productionDateInput.provided
|
||||
? productionDateInput.value
|
||||
: beforeProductionDate;
|
||||
const nextExpiryDate = expiryDateInput.provided
|
||||
? expiryDateInput.value
|
||||
: beforeExpiryDate;
|
||||
|
||||
// 合并后校验:生产日期不能晚于到期日期
|
||||
if (nextProductionDate && nextExpiryDate && nextProductionDate > nextExpiryDate) {
|
||||
await transaction.rollback();
|
||||
return {
|
||||
code: 400,
|
||||
message: `生产日期(${nextProductionDate})不能晚于到期日期(${nextExpiryDate})`,
|
||||
data: null,
|
||||
};
|
||||
}
|
||||
|
||||
const baseData = {
|
||||
storage_id: storageId,
|
||||
warehouse_id: warehouseId,
|
||||
store_id: storageRecord.store_id,
|
||||
space_id: storageRecord.space_id,
|
||||
stock_id: storageRecord.stock_id,
|
||||
batch_no: storageRecord.batch_no,
|
||||
};
|
||||
|
||||
if (nextProductionDate === beforeProductionDate && nextExpiryDate === beforeExpiryDate) {
|
||||
await transaction.rollback();
|
||||
return {
|
||||
code: 200,
|
||||
message: '生产日期与到期日期均无变化,未做修改',
|
||||
data: {
|
||||
...baseData,
|
||||
production_date: beforeProductionDate,
|
||||
expiry_date: beforeExpiryDate,
|
||||
changed: false,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
await ctx.model.Storage.update({
|
||||
production_date: nextProductionDate,
|
||||
expiry_date: nextExpiryDate,
|
||||
updated_at: new Date(),
|
||||
}, {
|
||||
where: { id: storageId },
|
||||
transaction,
|
||||
});
|
||||
|
||||
const changeSummary = [];
|
||||
if (nextProductionDate !== beforeProductionDate) {
|
||||
changeSummary.push(`生产日期 ${beforeProductionDate || '空'} → ${nextProductionDate || '空'}`);
|
||||
}
|
||||
if (nextExpiryDate !== beforeExpiryDate) {
|
||||
changeSummary.push(`到期日期 ${beforeExpiryDate || '空'} → ${nextExpiryDate || '空'}`);
|
||||
}
|
||||
|
||||
// ────────── 3. 记录操作日志(失败仅告警,不影响主流程) ──────────
|
||||
try {
|
||||
await ctx.service.systems.operationLog.createOperationLog({
|
||||
businessType: 'storage',
|
||||
businessId: storageId,
|
||||
operationCode: 'STORAGE_UPDATE_EXPIRY',
|
||||
operator: {
|
||||
id: ctx.user?.employees_id || ctx.user?.id,
|
||||
name: ctx.user?.employees_name || '',
|
||||
},
|
||||
extras: {
|
||||
warehouseId,
|
||||
message: changeSummary.join(';'),
|
||||
},
|
||||
beforeChanges: {
|
||||
...baseData,
|
||||
production_date: beforeProductionDate,
|
||||
expiry_date: beforeExpiryDate,
|
||||
},
|
||||
});
|
||||
} catch (logErr) {
|
||||
ctx.logger.warn('[inventory.updateExpiry] 写入操作日志失败,不影响业务', logErr);
|
||||
}
|
||||
|
||||
await transaction.commit();
|
||||
|
||||
ctx.logger.info('[inventory.updateExpiry] 库存效期维护完成', {
|
||||
warehouse_id: warehouseId,
|
||||
storage_id: storageId,
|
||||
production_date: nextProductionDate,
|
||||
expiry_date: nextExpiryDate,
|
||||
});
|
||||
|
||||
return {
|
||||
code: 200,
|
||||
message: '更新成功',
|
||||
data: {
|
||||
...baseData,
|
||||
production_date: nextProductionDate,
|
||||
expiry_date: nextExpiryDate,
|
||||
before_production_date: beforeProductionDate,
|
||||
before_expiry_date: beforeExpiryDate,
|
||||
changed: true,
|
||||
},
|
||||
};
|
||||
} catch (error) {
|
||||
await transaction.rollback();
|
||||
ctx.logger.error('[inventory.updateExpiry] 库存效期维护异常', {
|
||||
storage_id: storageId,
|
||||
error: error.message,
|
||||
stack: error.stack,
|
||||
});
|
||||
|
||||
if (error.name === 'SequelizeDatabaseError' && error.message.includes('Lock wait timeout')) {
|
||||
return { code: 409, message: '库存记录被锁定,请稍后重试', data: null };
|
||||
}
|
||||
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据商品快捷搜索关键字解析匹配的 stock_id 列表(仓库维度)。
|
||||
* 支持按商品编码(item_code)、商品名称(item_name)、货物编码(goods_code)、
|
||||
@ -1779,202 +1531,6 @@ class InventoryService extends Service {
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 按库位查询库存商品列表:传入 space_id,先判断该库位是否为当前仓库的库位,
|
||||
* 是则返回该库位下有量库存(quantity > 0)的商品列表,按商品(stock_id)汇总为一条。
|
||||
* 商品信息统一走 stock_warehouse 通用链路(getStockDetails),返回 stock_warehouse 通用属性
|
||||
* (item_code/item_name/sku_property/stock_unit/is_batch_mgmt/is_shelf_life_mgmt/
|
||||
* packing_requirements/need_recheck/barcodes/image_url 等)。
|
||||
*
|
||||
* @param {number} spaceId 库位ID(wms_location_space.id,必填)
|
||||
* @return {Promise<Object>} code/message/data 结构,data 为 { space, list }
|
||||
*/
|
||||
async getStorageListBySpaceId(spaceId) {
|
||||
const { ctx, app } = this;
|
||||
const { Op } = app.Sequelize;
|
||||
|
||||
// ────────── 1. 参数校验 ──────────
|
||||
const normalizedSpaceId = Number(spaceId);
|
||||
if (!Number.isInteger(normalizedSpaceId) || normalizedSpaceId <= 0) {
|
||||
return { code: 400, message: 'space_id 必填且必须为正整数', data: null };
|
||||
}
|
||||
|
||||
const warehouseId = ctx.user && ctx.user.store_id;
|
||||
if (!warehouseId) {
|
||||
return { code: 400, message: '无法获取当前仓库信息', data: null };
|
||||
}
|
||||
|
||||
// ────────── 2. 判断该库位是否属于当前仓库 ──────────
|
||||
const space = await ctx.model.LocationSpace.findOne({
|
||||
where: {
|
||||
id: normalizedSpaceId,
|
||||
warehouse_id: warehouseId,
|
||||
deleted_at: null,
|
||||
},
|
||||
attributes: [ 'id', 'warehouse_id', 'space_code', 'custom_name', 'space_status' ],
|
||||
raw: true,
|
||||
});
|
||||
|
||||
if (!space) {
|
||||
// 区分「库位不存在」与「库位存在但不属于当前仓库」
|
||||
const spaceInOtherWarehouse = await ctx.model.LocationSpace.findOne({
|
||||
where: { id: normalizedSpaceId, deleted_at: null },
|
||||
attributes: [ 'id', 'warehouse_id' ],
|
||||
raw: true,
|
||||
});
|
||||
if (spaceInOtherWarehouse) {
|
||||
return { code: 400, message: `库位 ${normalizedSpaceId} 不属于当前仓库`, data: null };
|
||||
}
|
||||
return { code: 404, message: `库位不存在: space_id=${normalizedSpaceId}`, data: null };
|
||||
}
|
||||
|
||||
const spaceInfo = {
|
||||
id: Number(space.id),
|
||||
warehouse_id: Number(space.warehouse_id),
|
||||
space_code: space.space_code || '',
|
||||
custom_name: space.custom_name || '',
|
||||
space_status: space.space_status || '',
|
||||
};
|
||||
|
||||
// ────────── 3. 查询该库位下有量库存明细(quantity > 0) ──────────
|
||||
const rows = await ctx.model.Storage.findAll({
|
||||
where: {
|
||||
warehouse_id: warehouseId,
|
||||
space_id: normalizedSpaceId,
|
||||
quantity: { [Op.gt]: 0 },
|
||||
is_enabled: 1,
|
||||
delete_at: null,
|
||||
},
|
||||
attributes: [
|
||||
'id', 'warehouse_id', 'store_id', 'space_id', 'stock_id',
|
||||
'batch_no', 'inventory_type', 'quantity', 'locked_quantity',
|
||||
'intercept_locked_quantity', 'available_quantity',
|
||||
'production_date', 'expiry_date', 'inbound_time',
|
||||
],
|
||||
order: [[ 'id', 'DESC' ]],
|
||||
raw: true,
|
||||
});
|
||||
|
||||
if (!rows.length) {
|
||||
return { code: 200, message: 'ok', data: { space: spaceInfo, list: [] } };
|
||||
}
|
||||
|
||||
// ────────── 4. 商品通用属性:统一走 stock_warehouse 通用链路(getStockDetails) ──────────
|
||||
const stockIds = [ ...new Set(rows.map(row => Number(row.stock_id)).filter(Boolean)) ];
|
||||
const stockDetailMap = new Map();
|
||||
try {
|
||||
const stockDetails = await ctx.service.systems.stockWarehouse.getStockDetails(stockIds, { warehouseId });
|
||||
for (const detail of (Array.isArray(stockDetails) ? stockDetails : [])) {
|
||||
stockDetailMap.set(Number(detail && detail.id || 0), detail);
|
||||
}
|
||||
} catch (error) {
|
||||
ctx.logger?.warn?.('[storage.inventory] getStorageListBySpaceId 查询商品通用属性失败,stock 降级为 null', {
|
||||
error: error.message,
|
||||
});
|
||||
}
|
||||
|
||||
// ────────── 5. 货主名称:按当前仓库收敛的签约表 store_remask ──────────
|
||||
const storeRemarkMap = new Map();
|
||||
const storeIds = [ ...new Set(rows.map(row => Number(row.store_id || 0)).filter(Boolean)) ];
|
||||
if (storeIds.length > 0) {
|
||||
try {
|
||||
const storeRows = await ctx.model.StoreWarehouse.findAll({
|
||||
where: { warehouse_id: warehouseId, store_id: { [Op.in]: storeIds } },
|
||||
attributes: [ 'store_id', 'store_remask' ],
|
||||
raw: true,
|
||||
});
|
||||
for (const row of storeRows) {
|
||||
storeRemarkMap.set(Number(row.store_id), row.store_remask || '');
|
||||
}
|
||||
} catch (error) {
|
||||
ctx.logger?.warn?.('[storage.inventory] getStorageListBySpaceId 查询货主名称失败,store_name 降级为 null', {
|
||||
error: error.message,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// ────────── 6. 按商品(stock_id)汇总为一条 ──────────
|
||||
const list = this._aggregateStorageRowsByStock(rows, spaceInfo, stockDetailMap, storeRemarkMap);
|
||||
|
||||
return {
|
||||
code: 200,
|
||||
message: 'ok',
|
||||
data: { space: spaceInfo, list },
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 将同一库位下的库存明细行按商品(stock_id)汇总:汇总数量并统计批次数与最早/最晚入库时间。
|
||||
* 商品字段取自 stock_warehouse 通用属性(getStockDetails 返回值,未命中时为 null)。
|
||||
*
|
||||
* @param {Array<Object>} rows wms_storage 明细行(Sequelize 实例或 plain 对象)
|
||||
* @param {Object} [spaceInfo] 库位信息(space_code/custom_name 平铺到每行)
|
||||
* @param {Map<number, Object>} [stockDetailMap] stock_id → stock_warehouse 通用属性
|
||||
* @param {Map<number, string>} [storeRemarkMap] store_id → 货主名称(store_remask)
|
||||
* @return {Array<Object>} 按商品汇总后的列表
|
||||
*/
|
||||
_aggregateStorageRowsByStock(rows = [], spaceInfo = null, stockDetailMap = null, storeRemarkMap = null) {
|
||||
const { app } = this;
|
||||
const location = spaceInfo || {};
|
||||
const stockMap = stockDetailMap || new Map();
|
||||
const storeMap = storeRemarkMap || new Map();
|
||||
const groupedMap = new Map();
|
||||
|
||||
for (const item of rows) {
|
||||
const row = item && typeof item.get === 'function' ? item.get({ plain: true }) : item;
|
||||
const stockId = Number(row.stock_id || 0);
|
||||
if (!stockId) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const quantity = Number(row.quantity || 0);
|
||||
const lockedQuantity = Number(row.locked_quantity || 0);
|
||||
const interceptLockedQuantity = Number(row.intercept_locked_quantity || 0);
|
||||
const availableQuantity = Number(row.available_quantity || 0);
|
||||
const inboundTimeMs = row.inbound_time ? new Date(row.inbound_time).getTime() : null;
|
||||
|
||||
const existing = groupedMap.get(stockId);
|
||||
if (!existing) {
|
||||
groupedMap.set(stockId, {
|
||||
warehouse_id: row.warehouse_id,
|
||||
store_id: row.store_id,
|
||||
space_id: Number(row.space_id || 0),
|
||||
stock_id: stockId,
|
||||
quantity,
|
||||
locked_quantity: lockedQuantity,
|
||||
intercept_locked_quantity: interceptLockedQuantity,
|
||||
available_quantity: availableQuantity,
|
||||
batch_count: 1,
|
||||
first_inbound_time: inboundTimeMs,
|
||||
last_inbound_time: inboundTimeMs,
|
||||
});
|
||||
continue;
|
||||
}
|
||||
|
||||
existing.quantity += quantity;
|
||||
existing.locked_quantity += lockedQuantity;
|
||||
existing.intercept_locked_quantity += interceptLockedQuantity;
|
||||
existing.available_quantity += availableQuantity;
|
||||
existing.batch_count += 1;
|
||||
if (inboundTimeMs !== null && (existing.first_inbound_time === null || inboundTimeMs < existing.first_inbound_time)) {
|
||||
existing.first_inbound_time = inboundTimeMs;
|
||||
}
|
||||
if (inboundTimeMs !== null && (existing.last_inbound_time === null || inboundTimeMs > existing.last_inbound_time)) {
|
||||
existing.last_inbound_time = inboundTimeMs;
|
||||
}
|
||||
}
|
||||
|
||||
return [ ...groupedMap.values() ].map(row => ({
|
||||
...row,
|
||||
space_code: location.space_code || '',
|
||||
space_name: location.custom_name || location.space_code || '',
|
||||
store_name: storeMap.get(Number(row.store_id || 0)) || null,
|
||||
stock: stockMap.get(row.stock_id) || null,
|
||||
first_inbound_time: row.first_inbound_time ? app.formatDate(row.first_inbound_time) : '',
|
||||
last_inbound_time: row.last_inbound_time ? app.formatDate(row.last_inbound_time) : '',
|
||||
}));
|
||||
}
|
||||
|
||||
/**
|
||||
* 将库存明细行按库位(space_id)汇总:汇总 quantity/locked_quantity/available_quantity,
|
||||
* 统计批次数并取最早/最晚入库时间。汇总行不含批次与效期字段,保留商品/库位关联信息。
|
||||
|
||||
@ -388,10 +388,9 @@ class StorageReportService extends Service {
|
||||
* @param {number[]} [options.storeIds=[]] 货主ID列表
|
||||
* @param {number[]} [options.spaceIds=[]] 库位ID列表
|
||||
* @param {boolean} [options.includeBarcode=false] 是否加载条码映射
|
||||
* @param {number[]} [options.entryOrderIds=[]] 入库单ID列表
|
||||
* @param {number[]} [options.orderIds=[]] 出库单ID列表
|
||||
* @param {number|null} [options.warehouseId=null] 仓库ID
|
||||
* @param {Map<number, number>} [options.orderWarehouseMap] 订单ID到仓库ID映射(货主模式跨仓库场景下用于运单同仓校验)
|
||||
* @param options.entryOrderIds
|
||||
* @param options.orderIds
|
||||
* @param options.warehouseId
|
||||
* @return {Promise<Object>} 映射对象
|
||||
*/
|
||||
async loadReportReferenceMaps({
|
||||
@ -402,7 +401,6 @@ class StorageReportService extends Service {
|
||||
entryOrderIds = [],
|
||||
orderIds = [],
|
||||
warehouseId = null,
|
||||
orderWarehouseMap = null,
|
||||
} = {}) {
|
||||
const { ctx, app } = this;
|
||||
const normalizedStockIds = [ ...new Set((stockIds || []).map(item => Number(item)).filter(item => Number.isInteger(item) && item > 0)) ];
|
||||
@ -479,44 +477,13 @@ class StorageReportService extends Service {
|
||||
)
|
||||
: [],
|
||||
normalizedOrderIds.length > 0
|
||||
? (async () => {
|
||||
// 强制同仓校验:读取 wms_order_express 必须同时带订单ID与仓库ID,
|
||||
// 禁止仅凭订单ID跨仓串读运单号。
|
||||
// 仓库模式:直接用当前仓库ID过滤;货主模式:按订单所属仓库分组查询。
|
||||
const resultRows = [];
|
||||
const querySql = 'SELECT order_id, waybill_code FROM wms_order_express WHERE order_id IN (:ids) AND warehouse_id = :warehouseId';
|
||||
if (Number.isInteger(normalizedWarehouseId) && normalizedWarehouseId > 0) {
|
||||
resultRows.push(...await ctx.model.query(
|
||||
querySql,
|
||||
{
|
||||
replacements: { ids: normalizedOrderIds, warehouseId: normalizedWarehouseId },
|
||||
type: app.Sequelize.QueryTypes.SELECT,
|
||||
}
|
||||
));
|
||||
} else if (orderWarehouseMap instanceof Map && orderWarehouseMap.size > 0) {
|
||||
const idsByWarehouse = new Map();
|
||||
for (const orderId of normalizedOrderIds) {
|
||||
const orderWarehouseId = Number(orderWarehouseMap.get(orderId));
|
||||
if (!Number.isInteger(orderWarehouseId) || orderWarehouseId <= 0) {
|
||||
continue;
|
||||
}
|
||||
if (!idsByWarehouse.has(orderWarehouseId)) {
|
||||
idsByWarehouse.set(orderWarehouseId, []);
|
||||
}
|
||||
idsByWarehouse.get(orderWarehouseId).push(orderId);
|
||||
}
|
||||
for (const [ orderWarehouseId, warehouseOrderIds ] of idsByWarehouse.entries()) {
|
||||
resultRows.push(...await ctx.model.query(
|
||||
querySql,
|
||||
{
|
||||
replacements: { ids: warehouseOrderIds, warehouseId: orderWarehouseId },
|
||||
type: app.Sequelize.QueryTypes.SELECT,
|
||||
}
|
||||
));
|
||||
}
|
||||
? ctx.model.query(
|
||||
'SELECT order_id, waybill_code FROM wms_order_express WHERE order_id IN (:ids)',
|
||||
{
|
||||
replacements: { ids: normalizedOrderIds },
|
||||
type: app.Sequelize.QueryTypes.SELECT,
|
||||
}
|
||||
return resultRows;
|
||||
})()
|
||||
)
|
||||
: [],
|
||||
normalizedStoreIds.length > 0 && Number.isInteger(normalizedWarehouseId) && normalizedWarehouseId > 0
|
||||
? ctx.model.StoreWarehouse.findAll({
|
||||
@ -610,7 +577,7 @@ class StorageReportService extends Service {
|
||||
* @param {Object} [sort] 排序参数
|
||||
* @param {string} [sort.sortField] 排序字段
|
||||
* @param {string} [sort.sortOrder] 排序顺序
|
||||
* @param {string} [exportMode] 导出模式(仅仓库侧生效):'item' 导出全部(含锁定),不传/其他值则排除锁定类型记录;货主侧固定只导出出入库流水
|
||||
* @param {string} [exportMode] 导出模式:'item' 导出全部(含锁定),不传/其他值则排除锁定类型记录
|
||||
* @param {string} [searchMode='warehouse'] 查询维度:'warehouse' 按仓库维度(默认),'store' 按货主维度
|
||||
* @param {number[]} [stockIds=null] 商品库存ID列表(精确过滤)
|
||||
* @param {string} [keyword=''] 商品关键字(模糊匹配)
|
||||
@ -666,11 +633,7 @@ class StorageReportService extends Service {
|
||||
}
|
||||
|
||||
const normalizedExportMode = String(exportMode || '').trim();
|
||||
if (isStoreMode) {
|
||||
// 货主侧口径:变更记录只包含出入库流水,锁定/解锁(LOCK/UNLOCK)一律不导出,无视 exportMode
|
||||
whereClauses.push('t.transaction_type NOT IN (:excludeStoreTypes)');
|
||||
replacements.excludeStoreTypes = [ 'LOCK', 'UNLOCK' ];
|
||||
} else if (normalizedExportMode !== 'item') {
|
||||
if (normalizedExportMode !== 'item') {
|
||||
whereClauses.push('t.transaction_type != :excludeLockType');
|
||||
replacements.excludeLockType = 'LOCK';
|
||||
}
|
||||
@ -698,7 +661,6 @@ class StorageReportService extends Service {
|
||||
t.created_at,
|
||||
t.transaction_type,
|
||||
t.store_id,
|
||||
t.warehouse_id,
|
||||
t.stock_id,
|
||||
${detailSpaceSelectSql},
|
||||
t.quantity,
|
||||
@ -735,16 +697,6 @@ class StorageReportService extends Service {
|
||||
? [ ...new Set(summaryList.map(item => Number(item.space_id)).filter(item => Number.isInteger(item) && item > 0)) ]
|
||||
: [];
|
||||
|
||||
// 货主模式:从流水明细按订单ID收集所属仓库,用于运单查询强制同仓校验
|
||||
const detailOrderWarehouseMap = new Map();
|
||||
for (const item of safeDetailRows) {
|
||||
const orderId = Number(item.order_id);
|
||||
const rowWarehouseId = Number(item.warehouse_id);
|
||||
if (Number.isInteger(orderId) && orderId > 0 && Number.isInteger(rowWarehouseId) && rowWarehouseId > 0) {
|
||||
detailOrderWarehouseMap.set(orderId, rowWarehouseId);
|
||||
}
|
||||
}
|
||||
|
||||
const maps = await this.loadReportReferenceMaps({
|
||||
stockIds: [ ...new Set([ ...summaryStockIds, ...detailStockIds ]) ],
|
||||
storeIds: [ ...new Set([ ...summaryStoreIds, ...detailStoreIds ]) ],
|
||||
@ -753,7 +705,6 @@ class StorageReportService extends Service {
|
||||
entryOrderIds: detailEntryOrderIds,
|
||||
orderIds: detailOrderIds,
|
||||
warehouseId,
|
||||
orderWarehouseMap: detailOrderWarehouseMap,
|
||||
});
|
||||
|
||||
const summaryColumns = [
|
||||
@ -1234,14 +1185,14 @@ class StorageReportService extends Service {
|
||||
ON ft.id = (
|
||||
SELECT MIN(t2.id)
|
||||
FROM ${transactionSource.tableName} t2
|
||||
WHERE ${rebindTableAlias(rangeWhereClauses, 't2').join(' AND ')}${isBySpace ? ' AND COALESCE(t2.space_id, 0) = g.space_id' : ''} AND t2.stock_id = g.stock_id AND t2.store_id = g.store_id
|
||||
WHERE ${rebindTableAlias(rangeWhereClauses, 't2').join(' AND ')}${isBySpace ? ' AND COALESCE(t2.space_id, 0) = g.space_id' : ''}
|
||||
AND t2.created_at = g._min_ct
|
||||
)
|
||||
LEFT JOIN ${transactionSource.tableName} lt
|
||||
ON lt.id = (
|
||||
SELECT MAX(t3.id)
|
||||
FROM ${transactionSource.tableName} t3
|
||||
WHERE ${rebindTableAlias(rangeWhereClauses, 't3').join(' AND ')}${isBySpace ? ' AND COALESCE(t3.space_id, 0) = g.space_id' : ''} AND t3.stock_id = g.stock_id AND t3.store_id = g.store_id
|
||||
WHERE ${rebindTableAlias(rangeWhereClauses, 't3').join(' AND ')}${isBySpace ? ' AND COALESCE(t3.space_id, 0) = g.space_id' : ''}
|
||||
AND t3.created_at = g._max_ct
|
||||
)
|
||||
ORDER BY g.stock_id ASC, g.space_id ASC, g.store_id ASC, g._min_ct ASC, g._max_ct ASC
|
||||
@ -1294,7 +1245,7 @@ class StorageReportService extends Service {
|
||||
ON lt.id = (
|
||||
SELECT MAX(t3.id)
|
||||
FROM ${transactionSource.tableName} t3
|
||||
WHERE ${rebindTableAlias(preStartWhereClauses, 't3').join(' AND ')}${isBySpace ? ' AND COALESCE(t3.space_id, 0) = g.space_id' : ''} AND t3.stock_id = g.stock_id AND t3.store_id = g.store_id
|
||||
WHERE ${rebindTableAlias(preStartWhereClauses, 't3').join(' AND ')}${isBySpace ? ' AND COALESCE(t3.space_id, 0) = g.space_id' : ''}
|
||||
AND t3.created_at = g._max_ct
|
||||
)
|
||||
ORDER BY g.stock_id ASC, g.space_id ASC, g.store_id ASC, g._max_ct DESC
|
||||
|
||||
@ -237,6 +237,8 @@ class StoreService extends Service {
|
||||
status: 1, // 直接启用
|
||||
created_by: userId,
|
||||
is_warehouse: 0, // 默认不是仓库
|
||||
logo_url: data.logo_url,
|
||||
domain: data.domain,
|
||||
auth_start: data.auth_start,
|
||||
auth_end: data.auth_end,
|
||||
subject_config: subjectConfig,
|
||||
@ -372,6 +374,8 @@ class StoreService extends Service {
|
||||
status: 1, // 直接通过
|
||||
created_by: userId,
|
||||
is_warehouse: 1, // 标记为仓库
|
||||
logo_url: data.logo_url,
|
||||
domain: data.domain,
|
||||
auth_start: new Date(), // 设置当前时间为授权开始时间
|
||||
auth_end: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000), // 默认授权7天试用
|
||||
subject_config: subjectConfig,
|
||||
|
||||
@ -3279,6 +3279,8 @@ class SettingStoreWarehouseService extends Service {
|
||||
* @param {string} [data.contact_email] 可选,联系邮箱。
|
||||
* @param {string} [data.address] 可选,公司地址。
|
||||
* @param {string} [data.industry] 可选,所属行业。
|
||||
* @param {string} [data.logo_url] 可选,Logo链接。
|
||||
* @param {string} [data.domain] 可选,绑定域名。
|
||||
* @param {string} [data.auth_start] 可选,授权开始日期,默认当天。
|
||||
* @param {string} [data.auth_end] 可选,授权结束日期。
|
||||
* @param {number} [data.print_quantity=0] 可选,初始面单余额。
|
||||
@ -3372,6 +3374,8 @@ class SettingStoreWarehouseService extends Service {
|
||||
status: 1,
|
||||
created_by: accountId,
|
||||
is_warehouse: 0,
|
||||
logo_url: data.logo_url || null,
|
||||
domain: data.domain || null,
|
||||
auth_end: authEnd,
|
||||
};
|
||||
|
||||
|
||||
@ -1,180 +0,0 @@
|
||||
// app/service/systems/system_log.js
|
||||
'use strict';
|
||||
|
||||
const MainService = require('../main');
|
||||
|
||||
/** @type {string} 系统日志表名 */
|
||||
const SYSTEM_LOG_TABLE = 'wms_system_log';
|
||||
/** @type {number} 默认日志保留天数:删除创建时间早于该天数的日志 */
|
||||
const DEFAULT_RETAIN_DAYS = 60;
|
||||
/** @type {number} 默认单批硬删除行数 */
|
||||
const DEFAULT_BATCH_SIZE = 2000;
|
||||
/** @type {number} 默认批间休眠最小毫秒数 */
|
||||
const DEFAULT_SLEEP_MIN_MS = 100;
|
||||
/** @type {number} 默认批间休眠最大毫秒数 */
|
||||
const DEFAULT_SLEEP_MAX_MS = 500;
|
||||
|
||||
/**
|
||||
* 休眠指定毫秒数。
|
||||
*
|
||||
* @param {number} ms 休眠毫秒数。
|
||||
* @return {Promise<void>} 无返回值。
|
||||
*/
|
||||
function sleep(ms) {
|
||||
return new Promise(resolve => setTimeout(resolve, ms));
|
||||
}
|
||||
|
||||
/**
|
||||
* 将保留天数归一化为正整数。
|
||||
*
|
||||
* 仅接受正整数(含数字字符串),其余非法值(负数、0、小数、非数字)一律回退默认保留天数;
|
||||
* 归一化后的值直接拼入 SQL 模板的 INTERVAL 表达式,保证无 SQL 注入风险。
|
||||
*
|
||||
* @param {*} value 待归一化的保留天数。
|
||||
* @return {number} 归一化后的正整数保留天数。
|
||||
*/
|
||||
function normalizeRetainDays(value) {
|
||||
const normalized = Number(value);
|
||||
return Number.isInteger(normalized) && normalized > 0 ? normalized : DEFAULT_RETAIN_DAYS;
|
||||
}
|
||||
|
||||
/**
|
||||
* 系统日志清理服务。
|
||||
*
|
||||
* 背景:wms_system_log 单表无分表无分区,日志长期增长会占用大量磁盘空间。
|
||||
* created_at 由应用写入 new Date(),与自增主键 id 严格单调递增,且 created_at 无索引,
|
||||
* 因此按时间条件过滤会全表扫描,必须按 id 边界走主键索引删除;
|
||||
* 同时必须使用原生 SQL 硬删除,禁止 SystemLog.destroy(全局 paranoid 软删除会增大行体积且语义不符)。
|
||||
*/
|
||||
class SystemLogService extends MainService {
|
||||
/**
|
||||
* 定位删除边界 id:创建时间早于保留天数截止时间的最大 id。
|
||||
*
|
||||
* 由于 created_at 与 id 严格单调递增,id 不大于该边界的行即全部过期行,
|
||||
* 等价于按 created_at 时间边界删除且走主键索引;查不到时返回 null 表示无过期日志。
|
||||
*
|
||||
* @param {number} retainDays 日志保留天数(正整数;非法值回退默认 60)。
|
||||
* @return {Promise<number|null>} 边界 id;无过期日志时返回 null。
|
||||
*/
|
||||
async findCleanupBoundaryId(retainDays) {
|
||||
const { ctx } = this;
|
||||
const safeRetainDays = normalizeRetainDays(retainDays);
|
||||
|
||||
const rows = await ctx.model.query(
|
||||
`SELECT id FROM ${SYSTEM_LOG_TABLE}`
|
||||
+ ` WHERE created_at < DATE_SUB(NOW(), INTERVAL ${safeRetainDays} DAY)`
|
||||
+ ' ORDER BY id DESC LIMIT 1',
|
||||
{ type: ctx.model.QueryTypes.SELECT }
|
||||
);
|
||||
|
||||
const firstRow = Array.isArray(rows) ? rows[0] : null;
|
||||
const boundaryId = firstRow ? Number(firstRow.id) : null;
|
||||
return Number.isInteger(boundaryId) && boundaryId > 0 ? boundaryId : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 单批硬删除 id 不大于边界值的系统日志(每批最多 batchSize 行)。
|
||||
*
|
||||
* @param {number} boundaryId 删除边界 id(含边界行本身)。
|
||||
* @param {number} batchSize 单批最大删除行数。
|
||||
* @return {Promise<number>} 本批实际删除行数。
|
||||
*/
|
||||
async deleteSystemLogsBatch(boundaryId, batchSize) {
|
||||
const { ctx } = this;
|
||||
const safeBoundaryId = Number(boundaryId) > 0 ? Math.floor(Number(boundaryId)) : 0;
|
||||
const safeBatchSize = Number(batchSize) > 0 ? Math.floor(Number(batchSize)) : DEFAULT_BATCH_SIZE;
|
||||
if (safeBoundaryId <= 0) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
// 不传 type:默认走 RAW 查询,mysql2 对 DELETE 返回 ResultSetHeader,
|
||||
// 取 [result, data] 结构中第一项的 affectedRows 作为本批删除行数
|
||||
const rawResult = await ctx.model.query(
|
||||
`DELETE FROM ${SYSTEM_LOG_TABLE}`
|
||||
+ ` WHERE id <= ${safeBoundaryId}`
|
||||
+ ' ORDER BY id'
|
||||
+ ` LIMIT ${safeBatchSize}`
|
||||
);
|
||||
const header = Array.isArray(rawResult) ? rawResult[0] : rawResult;
|
||||
const affectedRows = Number(header && header.affectedRows);
|
||||
return Number.isFinite(affectedRows) && affectedRows > 0 ? affectedRows : 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* 清理超过保留天数的系统日志(定时任务入口)。
|
||||
*
|
||||
* 流程:先定位边界 id,再按 id 升序分批硬删除,循环到单批受影响行数为 0 为止,
|
||||
* 批间随机休眠 100~500ms 降低数据库压力;不执行 OPTIMIZE TABLE,
|
||||
* 由 InnoDB 自行复用已删除数据页,避免重建大表占满磁盘。
|
||||
*
|
||||
* @param {Object} [options={}] 清理参数。
|
||||
* @param {number} [options.retainDays] 日志保留天数(正整数);缺省时读取
|
||||
* config.systemLogCleanup.retainDays,仍非法或未配置时回退 60。
|
||||
* @param {number} [options.batchSize=2000] 单批硬删除行数。
|
||||
* @param {number} [options.sleepMinMs=100] 批间休眠最小毫秒数。
|
||||
* @param {number} [options.sleepMaxMs=500] 批间休眠最大毫秒数。
|
||||
* @return {Promise<Object>} 清理结果摘要。
|
||||
*/
|
||||
async cleanupExpiredSystemLogs(options = {}) {
|
||||
const { ctx } = this;
|
||||
const startedAt = Date.now();
|
||||
const safeOptions = options && typeof options === 'object' ? options : {};
|
||||
|
||||
const cleanupConfig = (ctx.app.config && ctx.app.config.systemLogCleanup) || {};
|
||||
const rawRetainDays = safeOptions.retainDays !== undefined && safeOptions.retainDays !== null
|
||||
? safeOptions.retainDays
|
||||
: cleanupConfig.retainDays;
|
||||
const retainDays = normalizeRetainDays(rawRetainDays);
|
||||
const batchSize = Number(safeOptions.batchSize) > 0
|
||||
? Math.floor(Number(safeOptions.batchSize))
|
||||
: DEFAULT_BATCH_SIZE;
|
||||
const sleepMinMs = Number(safeOptions.sleepMinMs) >= 0
|
||||
? Math.floor(Number(safeOptions.sleepMinMs))
|
||||
: DEFAULT_SLEEP_MIN_MS;
|
||||
let sleepMaxMs = Number(safeOptions.sleepMaxMs) >= 0
|
||||
? Math.floor(Number(safeOptions.sleepMaxMs))
|
||||
: DEFAULT_SLEEP_MAX_MS;
|
||||
if (sleepMaxMs < sleepMinMs) {
|
||||
sleepMaxMs = sleepMinMs;
|
||||
}
|
||||
|
||||
const boundaryId = await this.findCleanupBoundaryId(retainDays);
|
||||
if (boundaryId === null) {
|
||||
ctx.logger.info(`[system-log-cleanup] 无超过 ${retainDays} 天的系统日志,跳过本次清理`);
|
||||
return {
|
||||
skipped: true,
|
||||
boundary_id: null,
|
||||
batch_count: 0,
|
||||
deleted_rows: 0,
|
||||
duration_ms: Date.now() - startedAt,
|
||||
};
|
||||
}
|
||||
|
||||
let batchCount = 0;
|
||||
let totalDeleted = 0;
|
||||
let affectedRows = 1;
|
||||
|
||||
while (affectedRows > 0) {
|
||||
if (batchCount > 0) {
|
||||
const sleepMs = Math.floor(sleepMinMs + Math.random() * (sleepMaxMs - sleepMinMs + 1));
|
||||
await sleep(sleepMs);
|
||||
}
|
||||
|
||||
affectedRows = await this.deleteSystemLogsBatch(boundaryId, batchSize);
|
||||
if (affectedRows > 0) {
|
||||
batchCount += 1;
|
||||
totalDeleted += affectedRows;
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
skipped: false,
|
||||
boundary_id: boundaryId,
|
||||
batch_count: batchCount,
|
||||
deleted_rows: totalDeleted,
|
||||
duration_ms: Date.now() - startedAt,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = SystemLogService;
|
||||
@ -1,826 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
const Service = require('egg').Service;
|
||||
|
||||
/** 业务类型:打包视频 */
|
||||
const BIZ_TYPE_PACK = 'pack';
|
||||
/** 业务类型:退件拆包视频 */
|
||||
const BIZ_TYPE_UNPACK = 'unpack';
|
||||
|
||||
/**
|
||||
* 补录请求状态机。
|
||||
* pending(待推送) → requested(已推送) → recording(录制中) → completed(已完成) / failed(失败)
|
||||
*/
|
||||
const STATUS = Object.freeze({
|
||||
PENDING: 'pending',
|
||||
REQUESTED: 'requested',
|
||||
RECORDING: 'recording',
|
||||
COMPLETED: 'completed',
|
||||
FAILED: 'failed',
|
||||
});
|
||||
|
||||
/** 在途状态(此状态内的请求不重复推送) */
|
||||
const ACTIVE_STATUSES = Object.freeze([ STATUS.PENDING, STATUS.REQUESTED, STATUS.RECORDING ]);
|
||||
|
||||
/** 终态状态(已由 settleStatuses 收敛,等待 notifyResults 回信) */
|
||||
const TERMINAL_STATUSES = Object.freeze([ STATUS.COMPLETED, STATUS.FAILED ]);
|
||||
|
||||
/** 超时失败原因前缀:settleStatuses 写入,notifyResults 据此区分回信文案 */
|
||||
const TIMEOUT_ERROR_PREFIX = '重新录制超时';
|
||||
|
||||
/** 幂等复用窗口:窗口内同一业务对象重复查询只复用已有请求,不重复推送(默认 10 分钟) */
|
||||
const REUSE_WINDOW_MS = 10 * 60 * 1000;
|
||||
|
||||
/** 推送失败原因字段最大长度 */
|
||||
const ERROR_MAX_LENGTH = 500;
|
||||
|
||||
/**
|
||||
* 转人工通知的目标群:仓库群的客服群(warehouse/customer_service)。
|
||||
* 取值需与 app/service/inbox/groups.js 中 warehouse 的 subTypes 一致。
|
||||
*/
|
||||
const MANUAL_HANDLING_SUB_TYPE = 'customer_service';
|
||||
|
||||
/**
|
||||
* 视频补录请求服务层。
|
||||
*
|
||||
* 场景:站内信查询"打包视频 / 退件拆包视频"时若视频不可用(无视频记录或全部 failed),
|
||||
* 由本服务登记补录请求(状态机落库 wms_video_record_request)并向录制服务推送强制录制,
|
||||
* 推送口径与 order.packing.forceRecord / returnUnpack.forceRecord 完全一致:
|
||||
* 查录制电脑(wms_print_computer is_recording=true)→ 校验 Redis 在线键 →
|
||||
* 重置视频记录为 created → POST {printService.url}/record/force。
|
||||
*/
|
||||
class VideoRecordRequestService extends Service {
|
||||
|
||||
/**
|
||||
* 查询仓库的录制电脑(wms_print_computer is_recording=true)。
|
||||
*
|
||||
* @param {number} warehouseId 仓库ID。
|
||||
* @return {Promise<Object|null>} 录制电脑行,找不到返回 null。
|
||||
*/
|
||||
async _getRecordingComputer(warehouseId) {
|
||||
const { ctx } = this;
|
||||
const row = await ctx.model.PrintComputer.findOne({
|
||||
where: { warehouse_id: warehouseId, is_recording: true, deleted_at: null },
|
||||
attributes: [ 'id', 'name', 'warehouse_id' ],
|
||||
raw: true,
|
||||
});
|
||||
return row || null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 校验录制电脑是否在线(与 forceRecord 相同的 Redis 在线键)。
|
||||
*
|
||||
* @param {number} warehouseId 仓库ID。
|
||||
* @param {number} computerId 录制电脑ID。
|
||||
* @return {Promise<boolean>} 是否在线。
|
||||
*/
|
||||
async _isComputerOnline(warehouseId, computerId) {
|
||||
const { ctx } = this;
|
||||
try {
|
||||
const redisPrinter = ctx.app.redis.get('printer');
|
||||
const onlineInfo = await redisPrinter.get(`warehouse:${warehouseId}:printer:${computerId}`);
|
||||
return Boolean(onlineInfo);
|
||||
} catch (err) {
|
||||
ctx.logger.warn(`[videoRecordRequest] 录制电脑在线校验失败 wh=${warehouseId} cid=${computerId}: ${err.message}`);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 重置视频记录为 created 并清空 video_url(与 forceRecord 同口径,触发重新录制)。
|
||||
*
|
||||
* @param {string} bizType 业务类型 pack/unpack。
|
||||
* @param {number} bizId 业务ID(pack_task_id / unpack_id)。
|
||||
* @return {Promise<void>}
|
||||
*/
|
||||
async _resetVideoRecords(bizType, bizId) {
|
||||
const { ctx } = this;
|
||||
if (bizType === BIZ_TYPE_UNPACK) {
|
||||
await ctx.model.ReturnUnpackVideo.update(
|
||||
{ status: 'created', video_url: '' },
|
||||
{ where: { unpack_id: bizId, deleted_at: null } }
|
||||
);
|
||||
return;
|
||||
}
|
||||
await ctx.model.PackTaskVideo.update(
|
||||
{ status: 'created', video_url: '' },
|
||||
{ where: { pack_task_id: bizId, deleted_at: null } }
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断已有请求是否处于幂等复用窗口内。
|
||||
*
|
||||
* @param {Object} row 请求记录行。
|
||||
* @return {boolean} true=窗口内(不重复推送)。
|
||||
*/
|
||||
_withinReuseWindow(row) {
|
||||
const base = row.last_request_at || row.updated_at;
|
||||
if (!base) return false;
|
||||
return Date.now() - new Date(base).getTime() < REUSE_WINDOW_MS;
|
||||
}
|
||||
|
||||
/**
|
||||
* 标记请求推送失败(无录制电脑 / 电脑不在线 / 打印服务异常)。
|
||||
*
|
||||
* @param {Object} params 参数。
|
||||
* @param {number} params.requestId 请求记录ID。
|
||||
* @param {string} params.error 失败原因。
|
||||
* @param {number|null} [params.computerId] 录制电脑ID。
|
||||
* @return {Promise<Object>} 统一的请求结果对象。
|
||||
*/
|
||||
async _markFailed({ requestId, error, computerId = null }) {
|
||||
const { ctx } = this;
|
||||
const message = String(error || '推送强制录制失败').slice(0, ERROR_MAX_LENGTH);
|
||||
await ctx.model.VideoRecordRequest.update(
|
||||
{
|
||||
status: STATUS.FAILED,
|
||||
request_error: message,
|
||||
print_computer_id: computerId,
|
||||
last_request_at: new Date(),
|
||||
remark: '视频不可用,推送强制录制失败',
|
||||
},
|
||||
{ where: { id: requestId } }
|
||||
);
|
||||
return { request_id: requestId, status: STATUS.FAILED, pushed: false, reused: false, error: message };
|
||||
}
|
||||
|
||||
/**
|
||||
* 打包任务视频补录请求。
|
||||
*
|
||||
* @param {Object} params 参数。
|
||||
* @param {number} params.warehouse_id 仓库ID。
|
||||
* @param {number} params.pack_task_id 打包任务ID(wms_pack_task.id)。
|
||||
* @param {string} [params.waybill_code] 触发查询的运单号。
|
||||
* @param {number} [params.store_id] 货主ID。
|
||||
* @param {string} [params.group_id] 触发查询的群ID。
|
||||
* @param {string} [params.group_name] 触发查询的群名称。
|
||||
* @param {string} [params.user_id] 触发查询的用户ID。
|
||||
* @param {string} [params.user_name] 触发查询的用户名称。
|
||||
* @param {string} [params.source] 触发来源。
|
||||
* @return {Promise<Object>} { request_id, status, pushed, reused, error }。
|
||||
*/
|
||||
async requestPackVideo({ warehouse_id, pack_task_id, waybill_code = '', store_id = 0, group_id = '', group_name = '', user_id = '', user_name = '', source = 'inbox' } = {}) {
|
||||
return this.requestFor({
|
||||
biz_type: BIZ_TYPE_PACK,
|
||||
biz_id: pack_task_id,
|
||||
warehouse_id,
|
||||
waybill_code,
|
||||
store_id,
|
||||
group_id,
|
||||
group_name,
|
||||
user_id,
|
||||
user_name,
|
||||
source,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 退件拆包视频补录请求。
|
||||
*
|
||||
* @param {Object} params 参数。
|
||||
* @param {number} params.warehouse_id 仓库ID。
|
||||
* @param {number} params.unpack_id 拆包单ID(wms_return_unpack.id)。
|
||||
* @param {string} [params.waybill_code] 触发查询的运单号。
|
||||
* @param {number} [params.store_id] 货主ID。
|
||||
* @param {string} [params.group_id] 触发查询的群ID。
|
||||
* @param {string} [params.group_name] 触发查询的群名称。
|
||||
* @param {string} [params.user_id] 触发查询的用户ID。
|
||||
* @param {string} [params.user_name] 触发查询的用户名称。
|
||||
* @param {string} [params.source] 触发来源。
|
||||
* @return {Promise<Object>} { request_id, status, pushed, reused, error }。
|
||||
*/
|
||||
async requestUnpackVideo({ warehouse_id, unpack_id, waybill_code = '', store_id = 0, group_id = '', group_name = '', user_id = '', user_name = '', source = 'inbox' } = {}) {
|
||||
return this.requestFor({
|
||||
biz_type: BIZ_TYPE_UNPACK,
|
||||
biz_id: unpack_id,
|
||||
warehouse_id,
|
||||
waybill_code,
|
||||
store_id,
|
||||
group_id,
|
||||
group_name,
|
||||
user_id,
|
||||
user_name,
|
||||
source,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 通用补录请求:登记请求记录(状态机起点 pending)→ 推送录制服务 → 推进状态。
|
||||
*
|
||||
* 幂等:同一仓库 + 业务对象在复用窗口内已有在途(pending/requested/recording)请求时直接复用,
|
||||
* 不重复推送;超窗口或上次 failed 时复活同一条记录重新推送(避免同一业务对象堆积多条记录)。
|
||||
*
|
||||
* @param {Object} params 参数。
|
||||
* @param {string} params.biz_type 业务类型 pack/unpack。
|
||||
* @param {number} params.biz_id 业务ID。
|
||||
* @param {number} params.warehouse_id 仓库ID。
|
||||
* @param {string} [params.waybill_code] 触发查询的运单号。
|
||||
* @param {number} [params.store_id] 货主ID。
|
||||
* @param {string} [params.group_id] 触发查询的群ID。
|
||||
* @param {string} [params.group_name] 触发查询的群名称。
|
||||
* @param {string} [params.user_id] 触发查询的用户ID。
|
||||
* @param {string} [params.user_name] 触发查询的用户名称。
|
||||
* @param {string} [params.source] 触发来源。
|
||||
* @return {Promise<Object>} { request_id, status, pushed, reused, error }。
|
||||
*/
|
||||
async requestFor({ biz_type, biz_id, warehouse_id, waybill_code = '', store_id = 0, group_id = '', group_name = '', user_id = '', user_name = '', source = 'inbox' } = {}) {
|
||||
const { ctx } = this;
|
||||
|
||||
const bizType = biz_type === BIZ_TYPE_UNPACK ? BIZ_TYPE_UNPACK : BIZ_TYPE_PACK;
|
||||
const bizId = Number(biz_id || 0);
|
||||
const warehouseId = Number(warehouse_id || 0);
|
||||
if (!bizId || !warehouseId) {
|
||||
return { request_id: null, status: null, pushed: false, reused: false, error: '缺少业务ID或仓库上下文' };
|
||||
}
|
||||
|
||||
// 触发查询的群/人员(供后续录制结果回发原群、@原用户)
|
||||
const groupId = String(group_id || '').slice(0, 100);
|
||||
const groupName = String(group_name || '').slice(0, 100);
|
||||
const userId = String(user_id || '').slice(0, 100);
|
||||
const userName = String(user_name || '').slice(0, 100);
|
||||
|
||||
// 1. 幂等:查该业务对象最近一条请求记录
|
||||
const latest = await ctx.model.VideoRecordRequest.findOne({
|
||||
where: { warehouse_id: warehouseId, biz_type: bizType, biz_id: bizId, deleted_at: null },
|
||||
order: [[ 'id', 'DESC' ]],
|
||||
raw: true,
|
||||
});
|
||||
|
||||
if (latest && latest.status !== STATUS.COMPLETED && this._withinReuseWindow(latest)) {
|
||||
return {
|
||||
request_id: latest.id,
|
||||
status: latest.status,
|
||||
pushed: false,
|
||||
reused: true,
|
||||
error: latest.request_error || null,
|
||||
};
|
||||
}
|
||||
|
||||
// 2. 写入请求记录(状态机起点 pending);已有未完成记录则复活复用
|
||||
let requestId = latest && latest.status !== STATUS.COMPLETED ? latest.id : null;
|
||||
if (requestId) {
|
||||
await ctx.model.VideoRecordRequest.update(
|
||||
{
|
||||
status: STATUS.PENDING,
|
||||
store_id: Number(store_id || 0) || Number(latest.store_id || 0),
|
||||
waybill_code: String(waybill_code || '') || latest.waybill_code,
|
||||
group_id: groupId || latest.group_id,
|
||||
group_name: groupName || latest.group_name,
|
||||
user_id: userId || latest.user_id,
|
||||
user_name: userName || latest.user_name,
|
||||
source: source || latest.source,
|
||||
print_computer_id: null,
|
||||
request_error: null,
|
||||
remark: '视频不可用,重新发起补录',
|
||||
},
|
||||
{ where: { id: requestId } }
|
||||
);
|
||||
} else {
|
||||
const created = await ctx.model.VideoRecordRequest.create({
|
||||
warehouse_id: warehouseId,
|
||||
store_id: Number(store_id || 0),
|
||||
biz_type: bizType,
|
||||
biz_id: bizId,
|
||||
waybill_code: String(waybill_code || ''),
|
||||
group_id: groupId || null,
|
||||
group_name: groupName || null,
|
||||
user_id: userId || null,
|
||||
user_name: userName || null,
|
||||
source: source || 'inbox',
|
||||
status: STATUS.PENDING,
|
||||
request_count: 0,
|
||||
remark: '视频不可用,自动发起补录',
|
||||
});
|
||||
requestId = created && created.id;
|
||||
}
|
||||
|
||||
// 3. 录制电脑存在性 + 在线校验(不满足写入 failed,不阻断业务查询)
|
||||
const computer = await this._getRecordingComputer(warehouseId);
|
||||
if (!computer) {
|
||||
return { ...(await this._markFailed({ requestId, error: '该仓库无录制电脑,无法推送重新录制' })), biz_type: bizType, biz_id: bizId };
|
||||
}
|
||||
const online = await this._isComputerOnline(warehouseId, computer.id);
|
||||
if (!online) {
|
||||
return {
|
||||
...(await this._markFailed({ requestId, error: '录制电脑不在线,无法推送重新录制', computerId: computer.id })),
|
||||
biz_type: bizType,
|
||||
biz_id: bizId,
|
||||
};
|
||||
}
|
||||
|
||||
// 4. 重置视频记录为 created(与 forceRecord 一致)
|
||||
try {
|
||||
await this._resetVideoRecords(bizType, bizId);
|
||||
} catch (err) {
|
||||
ctx.logger.warn(`[videoRecordRequest] 重置视频记录失败 biz=${bizType}:${bizId}: ${err.message}`);
|
||||
}
|
||||
|
||||
// 5. 推送录制服务(打印服务 /record/force)
|
||||
const printServiceUrl = ctx.app.config.printService.url;
|
||||
const requestData = bizType === BIZ_TYPE_UNPACK ? { unpack_id: bizId } : { pack_task_id: bizId };
|
||||
try {
|
||||
const res = await ctx.curl(`${printServiceUrl}/record/force`, {
|
||||
method: 'POST',
|
||||
contentType: 'json',
|
||||
data: requestData,
|
||||
dataType: 'json',
|
||||
timeout: 10000,
|
||||
});
|
||||
if (res.status >= 400) {
|
||||
return {
|
||||
...(await this._markFailed({ requestId, error: `录制服务返回 ${res.status}`, computerId: computer.id })),
|
||||
biz_type: bizType,
|
||||
biz_id: bizId,
|
||||
};
|
||||
}
|
||||
} catch (err) {
|
||||
ctx.logger.warn(`[videoRecordRequest] 推送强制录制失败 biz=${bizType}:${bizId}: ${err.message}`);
|
||||
return {
|
||||
...(await this._markFailed({ requestId, error: `通知录制服务失败: ${err.message}`, computerId: computer.id })),
|
||||
biz_type: bizType,
|
||||
biz_id: bizId,
|
||||
};
|
||||
}
|
||||
|
||||
// 6. 推送成功 → 状态推进为 requested(request_count 自增)
|
||||
await ctx.model.VideoRecordRequest.update(
|
||||
{
|
||||
status: STATUS.REQUESTED,
|
||||
request_count: ctx.app.Sequelize.literal('request_count + 1'),
|
||||
last_request_at: new Date(),
|
||||
print_computer_id: computer.id,
|
||||
request_error: null,
|
||||
remark: '视频不可用,已推送重新录制',
|
||||
},
|
||||
{ where: { id: requestId } }
|
||||
);
|
||||
|
||||
ctx.logger.info(`[videoRecordRequest] 已推送重新录制 biz=${bizType}:${bizId} wh=${warehouseId} cid=${computer.id}`);
|
||||
|
||||
return { request_id: requestId, status: STATUS.REQUESTED, pushed: true, reused: false, error: null, biz_type: bizType, biz_id: bizId };
|
||||
}
|
||||
|
||||
/**
|
||||
* 依据视频记录推进请求状态(查询命中视频时调用)。
|
||||
*
|
||||
* 规则:有可用视频(video_url 非空且非 failed)→ completed;
|
||||
* 有录制中记录 → recording;全部 failed → failed;其余保持不变。
|
||||
*
|
||||
* 结果以视频原表为准,不回写 video_url(同一业务对象可能存在多路视频)。
|
||||
*
|
||||
* @param {Object} params 参数。
|
||||
* @param {string} params.biz_type 业务类型 pack/unpack。
|
||||
* @param {number} params.biz_id 业务ID。
|
||||
* @param {Array<Object>} params.videos 视频记录数组(含 video_url/status)。
|
||||
* @return {Promise<Object|null>} { status, changed },无在途请求时返回 null。
|
||||
*/
|
||||
async syncByVideos({ biz_type, biz_id, videos } = {}) {
|
||||
const { ctx } = this;
|
||||
const bizType = biz_type === BIZ_TYPE_UNPACK ? BIZ_TYPE_UNPACK : BIZ_TYPE_PACK;
|
||||
const bizId = Number(biz_id || 0);
|
||||
if (!bizId) return null;
|
||||
|
||||
const list = Array.isArray(videos) ? videos.filter(Boolean) : [];
|
||||
const { Op } = ctx.app.Sequelize;
|
||||
|
||||
const row = await ctx.model.VideoRecordRequest.findOne({
|
||||
where: {
|
||||
biz_type: bizType,
|
||||
biz_id: bizId,
|
||||
status: { [Op.in]: ACTIVE_STATUSES },
|
||||
deleted_at: null,
|
||||
},
|
||||
order: [[ 'id', 'DESC' ]],
|
||||
raw: true,
|
||||
});
|
||||
if (!row) return null;
|
||||
|
||||
const available = list.find(v => v.video_url && v.status !== 'failed');
|
||||
let target = null;
|
||||
if (available) target = STATUS.COMPLETED;
|
||||
else if (list.some(v => v.status === 'recording')) target = STATUS.RECORDING;
|
||||
else if (list.length > 0 && list.every(v => v.status === 'failed')) target = STATUS.FAILED;
|
||||
|
||||
if (!target || target === row.status) return { status: row.status, changed: false };
|
||||
|
||||
const updates = { status: target };
|
||||
await ctx.model.VideoRecordRequest.update(updates, { where: { id: row.id } });
|
||||
|
||||
return { status: target, changed: true };
|
||||
}
|
||||
|
||||
/**
|
||||
* 状态收敛:把「在途」的补录请求推进为终态(completed / failed),不做任何通知。
|
||||
*
|
||||
* 定时任务的第一步(先收敛状态、再统一通知),与通知步骤解耦:
|
||||
* - 有可用视频且无仍在录制(或已超时)→ completed(超时窗口内仍缺摄像头时先交付已有的);
|
||||
* - 视频记录全部 failed → failed(录制服务返回失败);
|
||||
* - 超过 timeoutMs 仍无可用视频 → failed(超时);
|
||||
* - 其余(仍在录制中且未超时)→ 本轮不动,等下一轮;
|
||||
* - 记录缺少 warehouse_id / biz_id(永远无法处理)→ failed,避免每分钟占用扫描窗口。
|
||||
*
|
||||
* 说明:一个打包任务 / 拆包单可能对应多路摄像头视频(多条 wms_*_video 记录),
|
||||
* 因此以视频原表为准:有可用视频即算成功,权威视频列表由查询链路输出(见 notifyResults)。
|
||||
*
|
||||
* @param {Object} [options] 参数。
|
||||
* @param {number} [options.limit] 单轮处理条数上限,默认取 config.inbox.videoRecordNotifyLimit(10)。
|
||||
* @param {number} [options.timeoutMs] 超时阈值(毫秒),默认取 config.inbox.videoRecordNotifyTimeoutMs(1 小时)。
|
||||
* @return {Promise<Object>} { scanned, completed, failed, timeout, invalid, skipped }。
|
||||
*/
|
||||
async settleStatuses(options = {}) {
|
||||
const { ctx } = this;
|
||||
const inboxConfig = (ctx.app.config && ctx.app.config.inbox) || {};
|
||||
const limit = Math.max(1, Number(options.limit) || Number(inboxConfig.videoRecordNotifyLimit) || 10);
|
||||
const timeoutMs = Math.max(
|
||||
0,
|
||||
Number(options.timeoutMs) || Number(inboxConfig.videoRecordNotifyTimeoutMs) || 60 * 60 * 1000
|
||||
);
|
||||
const { Op } = ctx.app.Sequelize;
|
||||
|
||||
const rows = await ctx.model.VideoRecordRequest.findAll({
|
||||
where: {
|
||||
status: { [Op.in]: ACTIVE_STATUSES },
|
||||
is_notified: 0,
|
||||
deleted_at: null,
|
||||
},
|
||||
// last_request_at 是组合索引 idx_status_notified_last_request 的第三列,按它排序可避免 filesort
|
||||
order: [[ 'last_request_at', 'ASC' ], [ 'id', 'ASC' ]],
|
||||
limit,
|
||||
raw: true,
|
||||
});
|
||||
|
||||
const stat = { scanned: rows.length, completed: 0, failed: 0, timeout: 0, invalid: 0, skipped: 0 };
|
||||
|
||||
for (const row of rows) {
|
||||
try {
|
||||
const warehouseId = Number(row.warehouse_id || 0);
|
||||
const bizId = Number(row.biz_id || 0);
|
||||
if (!warehouseId || !bizId) {
|
||||
// 关键字段缺失 → 永远无法处理,直接收敛为失败,避免每分钟占用扫描窗口
|
||||
await ctx.model.VideoRecordRequest.update(
|
||||
{ status: STATUS.FAILED, request_error: '记录缺少仓库/业务对象,无法处理' },
|
||||
{ where: { id: row.id } }
|
||||
);
|
||||
stat.invalid += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
// 1. 读视频记录(打包/拆包分表)
|
||||
const videos = row.biz_type === BIZ_TYPE_UNPACK
|
||||
? await ctx.model.ReturnUnpackVideo.findAll({
|
||||
attributes: [ 'id', 'video_url', 'status' ],
|
||||
where: { unpack_id: bizId, deleted_at: null },
|
||||
raw: true,
|
||||
})
|
||||
: await ctx.model.PackTaskVideo.findAll({
|
||||
attributes: [ 'id', 'video_url', 'status' ],
|
||||
where: { pack_task_id: bizId, deleted_at: null },
|
||||
raw: true,
|
||||
});
|
||||
const list = Array.isArray(videos) ? videos : [];
|
||||
const statusOf = v => String(v.status || '');
|
||||
// 多路视频:需"有可用视频 且 无仍在录制",避免只出一路就误判完成
|
||||
const hasAvailable = list.some(v => v.video_url && statusOf(v) !== 'failed');
|
||||
const hasRecording = list.some(v => statusOf(v) === 'recording');
|
||||
const allFailed = list.length > 0 && list.every(v => statusOf(v) === 'failed');
|
||||
|
||||
// 2. 超时判定(以最近一次请求时间为准)
|
||||
const base = row.last_request_at || row.updated_at || row.created_at;
|
||||
const ageMs = base ? Date.now() - new Date(base).getTime() : 0;
|
||||
const timedOut = timeoutMs > 0 && ageMs >= timeoutMs;
|
||||
|
||||
let updates = null;
|
||||
if (hasAvailable && (!hasRecording || timedOut)) {
|
||||
updates = {
|
||||
status: STATUS.COMPLETED,
|
||||
request_error: hasRecording ? '部分摄像头仍在录制,已先交付可用视频' : null,
|
||||
};
|
||||
stat.completed += 1;
|
||||
} else if (allFailed) {
|
||||
updates = { status: STATUS.FAILED, request_error: '录制服务返回失败' };
|
||||
stat.failed += 1;
|
||||
} else if (timedOut) {
|
||||
updates = {
|
||||
status: STATUS.FAILED,
|
||||
request_error: `${TIMEOUT_ERROR_PREFIX}(${Math.round(timeoutMs / 60000)} 分钟)未产出视频`,
|
||||
};
|
||||
stat.timeout += 1;
|
||||
} else {
|
||||
// 仍在录制中且未超时:等下一轮
|
||||
stat.skipped += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
await ctx.model.VideoRecordRequest.update(updates, { where: { id: row.id } });
|
||||
ctx.logger.info(
|
||||
`[videoRecordRequest] 补录状态收敛 id=${row.id} biz=${row.biz_type}:${bizId} status=${updates.status}`
|
||||
);
|
||||
} catch (err) {
|
||||
stat.skipped += 1;
|
||||
ctx.logger.warn(`[videoRecordRequest] 补录状态收敛失败 id=${row.id}: ${err.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
return stat;
|
||||
}
|
||||
|
||||
/**
|
||||
* 补录结果通知:扫描「已收敛为终态且未通知」的补录请求,回信到原群(失败时转人工)。
|
||||
*
|
||||
* 前置条件:状态已由 settleStatuses 收敛为 completed / failed;
|
||||
* 本方法不再读视频表、也不再做超时判定,只负责取文案 + 回信 + 转人工。
|
||||
*
|
||||
* 处理规则(每轮最多 limit 条,按 last_request_at 升序):
|
||||
* - status=completed → 复用「原查询链路」文案(queryPackVideo / queryReturn 的输出,
|
||||
* 含全部视频地址与拆包明细)回信;取不到文案时不标记,下一轮重试;
|
||||
* - status=failed → 回「已转人工处理」,同时向仓库群的客服群推人工处理通知;
|
||||
* - 无群信息 → 仍标记 is_notified=1(remark 说明)避免卡死扫描窗口;
|
||||
* - 回信抛错 → 不标记,下一轮重试。
|
||||
*
|
||||
* 回信对象优先用记录里存下的群/人员(writeOutboundReply 定向回原用户);
|
||||
* 缺少用户信息时退化为群系统通知(pushSystemNotification)。
|
||||
*
|
||||
* @param {Object} [options] 参数。
|
||||
* @param {number} [options.limit] 单轮处理条数上限,默认取 config.inbox.videoRecordNotifyLimit(10)。
|
||||
* @return {Promise<Object>} { scanned, notified, completed, failed, timeout, skipped }。
|
||||
*/
|
||||
async notifyResults(options = {}) {
|
||||
const { ctx } = this;
|
||||
const inboxConfig = (ctx.app.config && ctx.app.config.inbox) || {};
|
||||
const limit = Math.max(1, Number(options.limit) || Number(inboxConfig.videoRecordNotifyLimit) || 10);
|
||||
const { Op } = ctx.app.Sequelize;
|
||||
|
||||
const rows = await ctx.model.VideoRecordRequest.findAll({
|
||||
where: {
|
||||
status: { [Op.in]: TERMINAL_STATUSES },
|
||||
is_notified: 0,
|
||||
deleted_at: null,
|
||||
},
|
||||
// last_request_at 是组合索引 idx_status_notified_last_request 的第三列,按它排序可避免 filesort
|
||||
order: [[ 'last_request_at', 'ASC' ], [ 'id', 'ASC' ]],
|
||||
limit,
|
||||
raw: true,
|
||||
});
|
||||
|
||||
const stat = { scanned: rows.length, notified: 0, completed: 0, failed: 0, timeout: 0, skipped: 0 };
|
||||
|
||||
for (const row of rows) {
|
||||
try {
|
||||
const waybill = row.waybill_code || '-';
|
||||
let content = null;
|
||||
// 非空表示本条需转人工(failed),由仓库群的客服群邀请真人接手
|
||||
let manualReason = null;
|
||||
|
||||
if (row.status === STATUS.COMPLETED) {
|
||||
// 录制成功:按「原查询链路」取结果文案,与用户自己发一次查询看到的完全一致
|
||||
const message = await this._buildResultMessage(row);
|
||||
if (!message) {
|
||||
// 取不到结果文案:本轮不标记,下一轮重试
|
||||
stat.skipped += 1;
|
||||
continue;
|
||||
}
|
||||
content = message;
|
||||
stat.completed += 1;
|
||||
} else {
|
||||
const isTimeout = String(row.request_error || '').startsWith(TIMEOUT_ERROR_PREFIX);
|
||||
content = `【视频补录${isTimeout ? '超时' : '失败'}】\n运单号:${waybill}\n已转人工处理,请稍后留意群内回复`;
|
||||
manualReason = row.request_error || '录制服务返回失败';
|
||||
if (isTimeout) stat.timeout += 1;
|
||||
stat.failed += 1;
|
||||
}
|
||||
|
||||
// 回信到原群(失败时不标记,下一轮重试;无群信息时标记避免卡住扫描窗口)
|
||||
const updates = { is_notified: 1, notified_at: new Date() };
|
||||
const sent = await this._replyResult(row, content);
|
||||
if (sent) {
|
||||
if (manualReason) updates.remark = '已转人工处理';
|
||||
await ctx.model.VideoRecordRequest.update(updates, { where: { id: row.id } });
|
||||
stat.notified += 1;
|
||||
ctx.logger.info(
|
||||
`[videoRecordRequest] 补录结果已通知 id=${row.id} biz=${row.biz_type}:${row.biz_id} status=${row.status}`
|
||||
);
|
||||
// 失败/超时:额外邀请仓库客服群真人接手
|
||||
if (manualReason) {
|
||||
await this._notifyManualHandling(row, manualReason);
|
||||
}
|
||||
} else {
|
||||
await ctx.model.VideoRecordRequest.update(
|
||||
{ ...updates, remark: '无群信息,未推送通知' },
|
||||
{ where: { id: row.id } }
|
||||
);
|
||||
stat.skipped += 1;
|
||||
ctx.logger.warn(`[videoRecordRequest] 补录结果无群信息未通知 id=${row.id} waybill=${waybill}`);
|
||||
}
|
||||
} catch (err) {
|
||||
stat.skipped += 1;
|
||||
ctx.logger.warn(`[videoRecordRequest] 补录结果通知处理失败 id=${row.id}: ${err.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
return stat;
|
||||
}
|
||||
|
||||
/**
|
||||
* 复用「原查询链路」取结果文案(录制成功后回原链路取值)。
|
||||
*
|
||||
* - 打包:调 inbox.functions `queryPackVideo(keyword=运单号)`,与用户发“打包视频+运单号”同一条链路;
|
||||
* - 拆包:调 inbox.functions `queryReturn(waybill_code=运单号)`,与用户发“查退回+运单号”同一条链路。
|
||||
*
|
||||
* 这两个函数是站内信函数注册表里的原实现,因此输出(含多路视频地址、拆包明细等)与用户主动查询完全一致;
|
||||
* 由于可用性/货主鉴权依赖 inboxContext,这里按补录记录里存的群/人员临时还原上下文,用后恢复。
|
||||
*
|
||||
* @param {Object} row 补录请求记录。
|
||||
* @return {Promise<string|null>} 查询链路产出的模板文案,取不到时返回 null。
|
||||
*/
|
||||
async _buildResultMessage(row) {
|
||||
const { ctx } = this;
|
||||
const waybill = String(row.waybill_code || '').trim();
|
||||
if (!waybill) return null;
|
||||
|
||||
const functionsSvc = ctx.service.inbox && ctx.service.inbox.functions;
|
||||
if (!functionsSvc || typeof functionsSvc.callFunction !== 'function') {
|
||||
ctx.logger.warn('[videoRecordRequest] inbox.functions 不可用,无法按原查询链路取结果');
|
||||
return null;
|
||||
}
|
||||
|
||||
const warehouseId = Number(row.warehouse_id || 0);
|
||||
const groupId = String(row.group_id || '').trim();
|
||||
let groupRow = null;
|
||||
if (groupId) {
|
||||
try {
|
||||
groupRow = await ctx.model.InboxGroup.findOne({
|
||||
attributes: [ 'group_id', 'group_name', 'group_type', 'sub_type' ],
|
||||
where: { group_id: groupId, warehouse_id: warehouseId },
|
||||
raw: true,
|
||||
});
|
||||
} catch (err) {
|
||||
ctx.logger.warn(`[videoRecordRequest] 查群信息失败 group=${groupId}: ${err.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
const prevContext = ctx.inboxContext;
|
||||
ctx.inboxContext = {
|
||||
warehouse_id: warehouseId,
|
||||
store_id: Number(row.store_id || 0) || null,
|
||||
group_id: groupId || null,
|
||||
group_name: String(row.group_name || '').trim() || (groupRow && groupRow.group_name) || null,
|
||||
user_id: String(row.user_id || '').trim() || null,
|
||||
user_name: String(row.user_name || '').trim() || null,
|
||||
group_type: (groupRow && groupRow.group_type) || null,
|
||||
sub_type: (groupRow && groupRow.sub_type) || null,
|
||||
};
|
||||
|
||||
try {
|
||||
const result = row.biz_type === BIZ_TYPE_UNPACK
|
||||
? await functionsSvc.callFunction('queryReturn', { waybill_code: waybill })
|
||||
: await functionsSvc.callFunction('queryPackVideo', { keyword: waybill });
|
||||
if (!result || result.success === false) {
|
||||
ctx.logger.warn(
|
||||
`[videoRecordRequest] 原查询链路取结果失败 waybill=${waybill}: ${(result && result.error) || 'unknown'}`
|
||||
);
|
||||
return null;
|
||||
}
|
||||
const message = result.data && result.data.message ? String(result.data.message).trim() : '';
|
||||
return message || null;
|
||||
} catch (err) {
|
||||
ctx.logger.warn(`[videoRecordRequest] 原查询链路取结果异常 waybill=${waybill}: ${err.message}`);
|
||||
return null;
|
||||
} finally {
|
||||
ctx.inboxContext = prevContext;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 失败/超时转人工:向仓库群的客服群推系统通知,邀请真人接手。
|
||||
*
|
||||
* 群范围:wms_inbox_group 中同仓库 `group_type='warehouse'` 且 `sub_type='customer_service'`(客服)
|
||||
* 的未屏蔽群;未命中时不外发,仅记 warn 日志(不退化发送到其他仓库群,避免误扰)。
|
||||
*
|
||||
* @param {Object} row 补录请求记录。
|
||||
* @param {string} reason 需人工处理的原因(录制失败 / 超时)。
|
||||
* @return {Promise<number>} 已通知的内部群数量。
|
||||
*/
|
||||
async _notifyManualHandling(row, reason) {
|
||||
const { ctx } = this;
|
||||
const warehouseId = Number(row.warehouse_id || 0);
|
||||
const processor = ctx.service.inbox && ctx.service.inbox.processor;
|
||||
if (!warehouseId || !processor || typeof processor.pushSystemNotification !== 'function') return 0;
|
||||
|
||||
let groups = [];
|
||||
try {
|
||||
groups = await ctx.model.InboxGroup.findAll({
|
||||
attributes: [ 'group_id', 'group_name', 'sub_type', 'ext_data' ],
|
||||
where: {
|
||||
warehouse_id: warehouseId,
|
||||
group_type: 'warehouse',
|
||||
sub_type: MANUAL_HANDLING_SUB_TYPE,
|
||||
is_blocked: 0,
|
||||
},
|
||||
raw: true,
|
||||
});
|
||||
} catch (err) {
|
||||
ctx.logger.warn(`[videoRecordRequest] 查仓库客服群失败 wh=${warehouseId}: ${err.message}`);
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (!Array.isArray(groups) || groups.length === 0) {
|
||||
ctx.logger.warn(
|
||||
`[videoRecordRequest] 仓库 ${warehouseId} 未配置客服群(warehouse/${MANUAL_HANDLING_SUB_TYPE}),转人工通知未发出 waybill=${row.waybill_code || '-'}`
|
||||
);
|
||||
return 0;
|
||||
}
|
||||
|
||||
const bizLabel = row.biz_type === BIZ_TYPE_UNPACK ? '退件拆包视频' : '打包视频';
|
||||
const content = [
|
||||
'【视频补录需人工处理】',
|
||||
`运单号:${row.waybill_code || '-'}`,
|
||||
`类型:${bizLabel}`,
|
||||
`仓库:${warehouseId}`,
|
||||
`原因:${reason || '录制未成功'}`,
|
||||
'请核实录制电脑/摄像头后人工处理,并回原群同步结果',
|
||||
].join('\n');
|
||||
|
||||
let notified = 0;
|
||||
for (const g of groups) {
|
||||
if (!g || !g.group_id) continue;
|
||||
processor.pushSystemNotification({
|
||||
warehouse_id: warehouseId,
|
||||
group_id: g.group_id,
|
||||
group_name: g.group_name,
|
||||
content,
|
||||
ext_data: g.ext_data || null,
|
||||
store_id: null,
|
||||
});
|
||||
notified += 1;
|
||||
}
|
||||
|
||||
ctx.logger.info(
|
||||
`[videoRecordRequest] 已邀请人工处理 waybill=${row.waybill_code || '-'} groups=${notified} reason=${reason}`
|
||||
);
|
||||
return notified;
|
||||
}
|
||||
|
||||
/**
|
||||
* 把补录结果回信到原群。
|
||||
*
|
||||
* 有用户信息时走 writeOutboundReply(定向回原用户);否则退化到 pushSystemNotification(群提醒)。
|
||||
* 群名与渠道扩展信息优先从 wms_inbox_group 现查,缺失时用补录记录里的快照值。
|
||||
*
|
||||
* @param {Object} row 补录请求记录。
|
||||
* @param {string} content 回信内容。
|
||||
* @return {Promise<boolean>} 是否已发起回信(无群信息时返回 false)。
|
||||
*/
|
||||
async _replyResult(row, content) {
|
||||
const { ctx } = this;
|
||||
const warehouseId = Number(row.warehouse_id || 0);
|
||||
const groupId = String(row.group_id || '').trim();
|
||||
const processor = ctx.service.inbox && ctx.service.inbox.processor;
|
||||
if (!groupId || !processor) return false;
|
||||
|
||||
let groupRow = null;
|
||||
try {
|
||||
groupRow = await ctx.model.InboxGroup.findOne({
|
||||
attributes: [ 'group_id', 'group_name', 'store_id', 'ext_data' ],
|
||||
where: { group_id: groupId, warehouse_id: warehouseId },
|
||||
raw: true,
|
||||
});
|
||||
} catch (err) {
|
||||
ctx.logger.warn(`[videoRecordRequest] 查询群信息失败 group=${groupId}: ${err.message}`);
|
||||
}
|
||||
|
||||
const groupName = String(row.group_name || (groupRow && groupRow.group_name) || '').trim();
|
||||
if (!groupName) return false;
|
||||
|
||||
const storeId = Number(row.store_id || 0) || Number(groupRow && groupRow.store_id) || null;
|
||||
const extData = (groupRow && groupRow.ext_data) || null;
|
||||
const userId = String(row.user_id || '').trim();
|
||||
const userName = String(row.user_name || '').trim();
|
||||
|
||||
if (userId && userName && typeof processor.writeOutboundReply === 'function') {
|
||||
await processor.writeOutboundReply({
|
||||
warehouse_id: warehouseId,
|
||||
group_id: groupId,
|
||||
group_name: groupName,
|
||||
user_id: userId,
|
||||
user_name: userName,
|
||||
store_id: storeId,
|
||||
ext_data: extData,
|
||||
ext_id: `video:record:${row.id}`,
|
||||
}, content, 'ai_reply');
|
||||
return true;
|
||||
}
|
||||
|
||||
processor.pushSystemNotification({
|
||||
warehouse_id: warehouseId,
|
||||
group_id: groupId,
|
||||
group_name: groupName,
|
||||
content,
|
||||
ext_data: extData,
|
||||
store_id: storeId,
|
||||
});
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = VideoRecordRequestService;
|
||||
@ -2,7 +2,6 @@
|
||||
|
||||
const { Service } = require('egg');
|
||||
const crypto = require('crypto');
|
||||
const { normalizeExtDataSource } = require('../../lib/inbox_channel');
|
||||
|
||||
/** 仓库接口类型 ID(interface_type_id=3) */
|
||||
const WAREHOUSE_INTERFACE_TYPE_ID = 3;
|
||||
@ -258,8 +257,6 @@ class WarehouseNotifyService extends Service {
|
||||
const { ctx } = this;
|
||||
const groupId = String((group && group.group_id) || '').trim();
|
||||
const groupName = String((group && group.group_name) || '').trim();
|
||||
// 按群ID格式校正渠道来源(@chatroom→wx / 纯数字→qiwe),避免通知投递到错误渠道
|
||||
const normalizedExtData = normalizeExtDataSource(groupId, extData);
|
||||
// 成员ID规范化:仅接受字符串数组,去重并过滤空值(向后兼容:旧调用不传时为空数组)
|
||||
const normalizedUserIds = Array.isArray(userIds)
|
||||
? [ ...new Set(userIds.map(item => String(item || '').trim()).filter(Boolean)) ]
|
||||
@ -328,7 +325,7 @@ class WarehouseNotifyService extends Service {
|
||||
group_name: groupName || null,
|
||||
user_name: null,
|
||||
content: normalizedContent,
|
||||
ext_data: normalizedExtData,
|
||||
ext_data: extData || null,
|
||||
flags: {},
|
||||
push_status: 1,
|
||||
push_started_at: new Date(),
|
||||
@ -345,7 +342,7 @@ class WarehouseNotifyService extends Service {
|
||||
type: 'system',
|
||||
content: normalizedContent,
|
||||
ext_id: sourceExtId,
|
||||
ext_data: normalizedExtData,
|
||||
ext_data: extData || null,
|
||||
timestamp: Math.floor(Date.now() / 1000),
|
||||
};
|
||||
if (groupId) {
|
||||
|
||||
@ -11,50 +11,6 @@ const CLOSED_WAVE_STATUS = 5;
|
||||
const WAVE_MIN_AGE_MINUTES = 5;
|
||||
// 单次 SQL IN 列表的波次数量上限
|
||||
const WAVE_ID_BATCH_SIZE = 500;
|
||||
// 判空二次确认:同一波次需连续两轮(间隔不小于该毫秒数)都判定为空,才允许终结。
|
||||
// 用于规避"批量解波/订单迁移进行中"造成的瞬时空表误判(2026-09-12 生产事故)。
|
||||
const EMPTY_CONFIRM_MIN_INTERVAL_MS = 30 * 1000;
|
||||
// 判空二次确认状态缓存键(记录上一轮判空结果与首次判定时间)
|
||||
const EMPTY_CONFIRM_CACHE_KEY = 'schedule:sync_finished_wave_batch:empty_confirm';
|
||||
// 判空二次确认状态缓存 TTL(秒)
|
||||
const EMPTY_CONFIRM_CACHE_TTL_SECONDS = 3600;
|
||||
// 判空二次确认状态最多保留的波次数量(防御性上限)
|
||||
const EMPTY_CONFIRM_MAX_WAVE_COUNT = 10000;
|
||||
// 日志中最多打印的波次数量(避免日志爆量)
|
||||
const LOG_WAVE_ID_LIMIT = 200;
|
||||
|
||||
/**
|
||||
* 提取 UPDATE 语句实际影响行数。
|
||||
*
|
||||
* @param {*} updateResult Sequelize query 返回值(UPDATE 通常为 [undefined, metadata])。
|
||||
* @return {number} 影响行数,无法识别时返回 0。
|
||||
*/
|
||||
function extractAffectedRows(updateResult) {
|
||||
const metadata = Array.isArray(updateResult) ? updateResult[1] : updateResult;
|
||||
const rawCount = metadata
|
||||
&& (metadata.affectedRows !== undefined
|
||||
? metadata.affectedRows
|
||||
: metadata.affectedCount !== undefined
|
||||
? metadata.affectedCount
|
||||
: metadata.rowCount);
|
||||
const count = Number(rawCount);
|
||||
return Number.isFinite(count) && count > 0 ? count : 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* 格式化波次ID列表用于日志输出(超长时截断)。
|
||||
*
|
||||
* @param {Array<number>} waveIds 波次ID列表。
|
||||
* @return {string} 日志用字符串。
|
||||
*/
|
||||
function formatWaveIdListForLog(waveIds) {
|
||||
const list = Array.isArray(waveIds) ? waveIds : [];
|
||||
if (list.length <= LOG_WAVE_ID_LIMIT) {
|
||||
return list.join(',');
|
||||
}
|
||||
|
||||
return `${list.slice(0, LOG_WAVE_ID_LIMIT).join(',')},...(共${list.length}个)`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 波次批次自动终结服务。
|
||||
@ -70,22 +26,14 @@ class WaveBatchClosureService extends MainService {
|
||||
/**
|
||||
* 扫描并关闭"订单已全部离表"的活动波次。
|
||||
*
|
||||
* 判空需通过"二次确认":同一波次连续两轮(间隔不小于 confirmMinIntervalMs)
|
||||
* 都被判定为空才允许终结。这样即使某一瞬间待处理表查不到该波次订单
|
||||
* (批量解波、出库迁移、外部 DDL 等并发场景),也不会被误判为 0 单波次。
|
||||
*
|
||||
* @param {Object} [options={}] 执行选项。
|
||||
* @param {boolean} [options.dryRun=false] 仅盘点不更新(用于验证命中范围)。
|
||||
* @param {number} [options.confirmMinIntervalMs] 判空二次确认最小间隔(毫秒),传 0 表示跳过确认、首轮即终结。
|
||||
* @return {Promise<Object>} 执行结果汇总。
|
||||
*/
|
||||
async closeFinishedWaves(options = {}) {
|
||||
const { ctx } = this;
|
||||
const startedAt = Date.now();
|
||||
const normalizedOptions = this.isPlainObject(options) ? options : {};
|
||||
const dryRun = Boolean(normalizedOptions.dryRun);
|
||||
const confirmMinIntervalMs = this.normalizeConfirmIntervalMs(normalizedOptions.confirmMinIntervalMs);
|
||||
const confirmEnabled = !dryRun && confirmMinIntervalMs > 0;
|
||||
const dryRun = Boolean(options && options.dryRun);
|
||||
|
||||
const candidateRows = await ctx.model.query(
|
||||
`SELECT wave_id, wave_no, warehouse_id, wave_status, total_orders
|
||||
@ -120,7 +68,7 @@ class WaveBatchClosureService extends MainService {
|
||||
}
|
||||
|
||||
const warehouseIds = Array.from(warehouseWaveMap.keys());
|
||||
const emptyWaves = [];
|
||||
const closedWaves = [];
|
||||
|
||||
for (const warehouseId of warehouseIds) {
|
||||
const waves = warehouseWaveMap.get(warehouseId);
|
||||
@ -172,50 +120,17 @@ class WaveBatchClosureService extends MainService {
|
||||
|
||||
const finishedWaves = waves.filter(item => !existingWaveIds.has(item.waveId));
|
||||
if (finishedWaves.length > 0) {
|
||||
emptyWaves.push(...finishedWaves);
|
||||
closedWaves.push(...finishedWaves);
|
||||
}
|
||||
}
|
||||
|
||||
const closedWaveIds = closedWaves.map(item => item.waveId);
|
||||
const candidateCount = Array.from(warehouseWaveMap.values()).reduce((sum, waves) => sum + waves.length, 0);
|
||||
|
||||
// 二次确认:只有"上一轮也判空"且距首次判空已满 confirmMinIntervalMs 的波次才允许终结
|
||||
const now = Date.now();
|
||||
const previousState = confirmEnabled ? await this.readEmptyConfirmState() : null;
|
||||
const previousWaveIds = Array.isArray(previousState && previousState.waveIds)
|
||||
? previousState.waveIds
|
||||
: [];
|
||||
const previousWaveIdSet = new Set(previousWaveIds);
|
||||
const previousRoundAt = Number(previousState && previousState.roundAt || 0);
|
||||
const previousStateUsable = Number.isFinite(previousRoundAt)
|
||||
&& previousRoundAt > 0
|
||||
&& (now - previousRoundAt) >= confirmMinIntervalMs;
|
||||
|
||||
const confirmedWaves = [];
|
||||
const pendingConfirmWaves = [];
|
||||
for (const item of emptyWaves) {
|
||||
if (!confirmEnabled || (previousStateUsable && previousWaveIdSet.has(item.waveId))) {
|
||||
confirmedWaves.push(item);
|
||||
} else {
|
||||
pendingConfirmWaves.push(item);
|
||||
}
|
||||
}
|
||||
|
||||
if (confirmEnabled) {
|
||||
// 状态仍在确认窗口内时保留首次判定时间,避免调度频率高于确认间隔时永远无法确认
|
||||
const nextRoundAt = previousRoundAt > 0 && !previousStateUsable ? previousRoundAt : now;
|
||||
await this.writeEmptyConfirmState({
|
||||
roundAt: nextRoundAt,
|
||||
waveIds: emptyWaves.map(item => item.waveId),
|
||||
});
|
||||
}
|
||||
|
||||
const confirmedWaveIds = confirmedWaves.map(item => item.waveId);
|
||||
|
||||
let closedRowCount = 0;
|
||||
if (!dryRun && confirmedWaveIds.length > 0) {
|
||||
for (let offset = 0; offset < confirmedWaveIds.length; offset += WAVE_ID_BATCH_SIZE) {
|
||||
const batchWaveIds = confirmedWaveIds.slice(offset, offset + WAVE_ID_BATCH_SIZE);
|
||||
const updateResult = await ctx.model.query(
|
||||
if (!dryRun && closedWaveIds.length > 0) {
|
||||
for (let offset = 0; offset < closedWaveIds.length; offset += WAVE_ID_BATCH_SIZE) {
|
||||
const batchWaveIds = closedWaveIds.slice(offset, offset + WAVE_ID_BATCH_SIZE);
|
||||
await ctx.model.query(
|
||||
`UPDATE wms_wave_batch
|
||||
SET wave_status = :closedStatus,
|
||||
processed_orders = total_orders,
|
||||
@ -233,128 +148,26 @@ class WaveBatchClosureService extends MainService {
|
||||
type: ctx.model.QueryTypes.UPDATE,
|
||||
}
|
||||
);
|
||||
closedRowCount += extractAffectedRows(updateResult);
|
||||
}
|
||||
}
|
||||
|
||||
const result = {
|
||||
dryRun,
|
||||
confirm_min_interval_ms: confirmMinIntervalMs,
|
||||
candidate_count: candidateCount,
|
||||
empty_count: emptyWaves.length,
|
||||
confirmed_count: confirmedWaves.length,
|
||||
closed_count: dryRun ? 0 : closedRowCount,
|
||||
pending_confirm_count: pendingConfirmWaves.length,
|
||||
pending_confirm_wave_ids: pendingConfirmWaves.map(item => item.waveId),
|
||||
empty_wave_ids: emptyWaves.map(item => item.waveId),
|
||||
closed_count: closedWaves.length,
|
||||
warehouse_ids: warehouseIds,
|
||||
closed_waves: confirmedWaves,
|
||||
closed_waves: closedWaves,
|
||||
duration_ms: Date.now() - startedAt,
|
||||
};
|
||||
|
||||
if (confirmedWaves.length > 0 || pendingConfirmWaves.length > 0) {
|
||||
const pendingSuffix = pendingConfirmWaves.length > 0
|
||||
? ` pendingWaves=${formatWaveIdListForLog(result.pending_confirm_wave_ids)}`
|
||||
: '';
|
||||
const confirmedSuffix = confirmedWaveIds.length > 0
|
||||
? ` waves=${formatWaveIdListForLog(confirmedWaveIds)}`
|
||||
: '';
|
||||
if (closedWaves.length > 0) {
|
||||
ctx.logger.info(
|
||||
`[wave-batch-closure] 波次终结结果 dryRun=${dryRun} candidate=${candidateCount}`
|
||||
+ ` confirmed=${confirmedWaves.length} closedRows=${result.closed_count}`
|
||||
+ ` pendingConfirm=${pendingConfirmWaves.length}${pendingSuffix}${confirmedSuffix}`
|
||||
`[wave-batch-closure] 波次终结结果 dryRun=${dryRun} closed=${closedWaves.length}/${candidateCount} waves=${closedWaveIds.join(',')}`
|
||||
);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 归一化判空二次确认最小间隔。
|
||||
*
|
||||
* @param {*} rawValue 原始入参。
|
||||
* @return {number} 毫秒数;未传/非法/负数时回落默认值,0 表示跳过确认。
|
||||
*/
|
||||
normalizeConfirmIntervalMs(rawValue) {
|
||||
if (rawValue === undefined || rawValue === null || rawValue === '') {
|
||||
return EMPTY_CONFIRM_MIN_INTERVAL_MS;
|
||||
}
|
||||
|
||||
const numberValue = Number(rawValue);
|
||||
if (!Number.isFinite(numberValue) || numberValue < 0) {
|
||||
return EMPTY_CONFIRM_MIN_INTERVAL_MS;
|
||||
}
|
||||
|
||||
return Math.floor(numberValue);
|
||||
}
|
||||
|
||||
/**
|
||||
* 读取上一轮判空二次确认状态。
|
||||
*
|
||||
* 缓存不可用或读取异常时返回 null,调用方据此跳过本轮终结(宁可漏关,不可误关)。
|
||||
*
|
||||
* @return {Promise<{ roundAt: number, waveIds: Array<number> }|null>} 上一轮状态。
|
||||
*/
|
||||
async readEmptyConfirmState() {
|
||||
const { ctx } = this;
|
||||
const app = ctx && ctx.app;
|
||||
if (!app || typeof app.getCacheAsync !== 'function') {
|
||||
ctx.logger.warn('[wave-batch-closure] 判空二次确认状态缓存不可用,本轮不终结任何波次');
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
const cached = await app.getCacheAsync(EMPTY_CONFIRM_CACHE_KEY);
|
||||
if (cached === undefined || cached === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const state = typeof cached === 'string' ? JSON.parse(cached) : cached;
|
||||
if (!state || typeof state !== 'object') {
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
roundAt: Number(state.roundAt || 0),
|
||||
waveIds: Array.isArray(state.waveIds)
|
||||
? state.waveIds.map(waveId => Number(waveId)).filter(waveId => Number.isInteger(waveId) && waveId > 0)
|
||||
: [],
|
||||
};
|
||||
} catch (error) {
|
||||
ctx.logger.warn(`[wave-batch-closure] 读取判空二次确认状态失败,本轮不终结任何波次: ${error.message}`);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 写入本轮判空二次确认状态(供下一轮确认)。
|
||||
*
|
||||
* @param {{ roundAt: number, waveIds: Array<number> }} state 状态。
|
||||
* @return {Promise<void>} 无返回值。
|
||||
*/
|
||||
async writeEmptyConfirmState(state) {
|
||||
const { ctx } = this;
|
||||
const app = ctx && ctx.app;
|
||||
if (!app || typeof app.setCacheAsync !== 'function') {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const waveIds = Array.isArray(state && state.waveIds)
|
||||
? state.waveIds.slice(0, EMPTY_CONFIRM_MAX_WAVE_COUNT)
|
||||
: [];
|
||||
await app.setCacheAsync(
|
||||
EMPTY_CONFIRM_CACHE_KEY,
|
||||
{
|
||||
roundAt: Number(state && state.roundAt || Date.now()),
|
||||
waveIds,
|
||||
},
|
||||
EMPTY_CONFIRM_CACHE_TTL_SECONDS
|
||||
);
|
||||
} catch (error) {
|
||||
ctx.logger.warn(`[wave-batch-closure] 写入判空二次确认状态失败: ${error.message}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = WaveBatchClosureService;
|
||||
|
||||
@ -389,14 +389,13 @@ class WaybillService extends MainService {
|
||||
// 提取所有唯一的 order_id
|
||||
const orderIds = [ ...new Set(rows.map(r => r.order_id).filter(Boolean)) ];
|
||||
|
||||
// SELF JOIN:查询同 order_id 下 business_key=1 的主单号(强制同仓校验,避免跨仓串读)
|
||||
// SELF JOIN:查询同 order_id 下 business_key=1 的主单号
|
||||
const mainWaybillMap = new Map();
|
||||
if (orderIds.length > 0) {
|
||||
const mainRecords = await ctx.model.OrderExpress.findAll({
|
||||
where: {
|
||||
order_id: { [Op.in]: orderIds },
|
||||
business_key: 1,
|
||||
warehouse_id: warehouseId,
|
||||
},
|
||||
attributes: [ 'order_id', 'waybill_code' ],
|
||||
raw: true,
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@ -62,10 +62,6 @@ module.exports = appInfo => {
|
||||
aiFallback: false,
|
||||
// 退回收件登记聚合通知防抖窗口(毫秒):等该时长无新登记后合并推送,默认 5 分钟
|
||||
returnReceivedNotifyDelayMs: 5 * 60 * 1000,
|
||||
// 视频补录结果通知:单轮处理条数上限(定时任务每 1 分钟扫一次)
|
||||
videoRecordNotifyLimit: 10,
|
||||
// 视频补录结果通知:超时阈值(毫秒),超过仍无录像则按超时回信并终止,避免长期占用扫描窗口
|
||||
videoRecordNotifyTimeoutMs: 60 * 60 * 1000,
|
||||
};
|
||||
|
||||
config.tencentCloud = {
|
||||
@ -230,37 +226,8 @@ module.exports = appInfo => {
|
||||
batchSize: 50,
|
||||
force: false,
|
||||
};
|
||||
// 工作台 token 超期强制下线定时任务配置
|
||||
config.workbenchTokenExpire = {
|
||||
enable: true,
|
||||
// 扫描间隔(毫秒),默认每小时扫描一次;开发环境可在 config.local.js 覆盖为短循环
|
||||
scanIntervalMs: 60 * 60 * 1000,
|
||||
// token 有效期阈值(毫秒):token_updated_at 距今超过该时长则强制下线(默认 3 个月,按 30 天/月折算)
|
||||
maxAgeMs: 3 * 30 * 24 * 60 * 60 * 1000,
|
||||
// 单轮批处理大小(按 id 升序分批)
|
||||
batchSize: 50,
|
||||
};
|
||||
// 系统日志超期清理定时任务配置(每日凌晨 03:00 执行,硬删除 wms_system_log 超期数据释放磁盘空间)
|
||||
config.systemLogCleanup = {
|
||||
enable: true,
|
||||
// 触发 cron(秒 分 时 日 月 周):默认每日凌晨 03:00;本地环境可在 config.local.js 覆盖为短间隔
|
||||
cron: '0 0 3 * * *',
|
||||
// 日志保留天数:删除 created_at 早于该天数的日志(默认 60 天,仅接受正整数,非法值回退 60)
|
||||
retainDays: 60,
|
||||
// 单批硬删除行数(按 id 升序分批,走主键索引)
|
||||
batchSize: 2000,
|
||||
// 批间休眠毫秒数下限/上限:在区间内随机取值,降低数据库瞬时压力
|
||||
sleepMinMs: 100,
|
||||
sleepMaxMs: 500,
|
||||
};
|
||||
// 打印自定义区模板出口域名
|
||||
config.customAreaBaseUrl = 'https://api.ye4s.com';
|
||||
// 仓库前端独立部署:证书部署目录。
|
||||
// 保存接口(setting.warehouse.saveFrontCert)已不再写暂存文件,证书/私钥内容直接入库;
|
||||
// 该目录保留供未来定时任务(Egg schedule 或外部 crontab)从库内 cert_pem/cert_key 读取内容后写 nginx 证书目录使用。
|
||||
config.frontConfig = {
|
||||
certStagingDir: '/data/wms/cert-staging',
|
||||
};
|
||||
|
||||
return {
|
||||
...config,
|
||||
|
||||
@ -1,46 +0,0 @@
|
||||
-- wms_workbench pre-migration backup (production 112.124.21.102)
|
||||
-- Generated at: 2026-09-06T13:24:37.798Z
|
||||
-- Row count: 20
|
||||
|
||||
DROP TABLE IF EXISTS `wms_workbench`;
|
||||
CREATE TABLE `wms_workbench` (
|
||||
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT '主键ID',
|
||||
`warehouse_id` bigint(20) unsigned NOT NULL COMMENT '仓库ID',
|
||||
`name` varchar(100) NOT NULL COMMENT '工作台名称(用户自定义)',
|
||||
`status` tinyint(4) NOT NULL DEFAULT '1' COMMENT '状态:0-禁用 1-启用',
|
||||
`type` enum('personal','group') NOT NULL DEFAULT 'personal' COMMENT '工作台类型:personal-个人工作台 group-团体工作台',
|
||||
`remark` varchar(500) DEFAULT NULL COMMENT '备注',
|
||||
`device_ids` json DEFAULT NULL COMMENT '设备ID列表,如 [1,2,3],触发打包任务时透传到 wms_pack_task.device_ids',
|
||||
`created_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
|
||||
`updated_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
|
||||
`deleted_at` datetime DEFAULT NULL COMMENT '软删除时间',
|
||||
`login_code` varchar(64) DEFAULT NULL COMMENT '工作台登录码(前缀+随机,64位,全局唯一)',
|
||||
`token` varchar(64) DEFAULT NULL COMMENT '工作台令牌(随机64位,绑定后生成)',
|
||||
PRIMARY KEY (`id`),
|
||||
UNIQUE KEY `uk_login_code` (`login_code`),
|
||||
KEY `idx_warehouse_id` (`warehouse_id`),
|
||||
KEY `idx_deleted_at` (`deleted_at`),
|
||||
KEY `idx_token` (`token`)
|
||||
) ENGINE=InnoDB AUTO_INCREMENT=21 DEFAULT CHARSET=utf8mb4;
|
||||
|
||||
INSERT INTO `wms_workbench` (`id`, `warehouse_id`, `name`, `status`, `type`, `remark`, `device_ids`, `created_at`, `updated_at`, `deleted_at`, `login_code`, `token`) VALUES
|
||||
(1, 1000028, '工作1', 1, 'personal', '1111', NULL, '2026-07-20 07:57:11', '2026-07-20 07:57:23', '2026-07-20 07:57:23', NULL, NULL),
|
||||
(2, 1000028, '散单1号工作台', 1, 'personal', '11111', '9', '2026-07-20 07:58:16', '2026-07-20 07:58:56', '2026-07-20 07:58:56', NULL, NULL),
|
||||
(3, 1000028, '测试', 1, 'personal', NULL, NULL, '2026-07-20 18:01:00', '2026-09-03 00:27:19', '2026-09-03 00:27:19', NULL, NULL),
|
||||
(4, 1000028, '散单工作台1', 1, 'personal', NULL, '9', '2026-07-25 01:05:53', '2026-07-26 08:02:49', NULL, NULL, NULL),
|
||||
(5, 1000028, '散单工作台2', 1, 'personal', NULL, '10', '2026-07-25 01:05:59', '2026-07-26 08:02:53', NULL, NULL, NULL),
|
||||
(6, 1000028, '散单工作台3', 1, 'personal', NULL, '15', '2026-07-25 01:06:05', '2026-07-26 08:03:02', NULL, NULL, NULL),
|
||||
(7, 1000028, '散单工作台4', 1, 'personal', NULL, '12', '2026-07-25 01:06:11', '2026-07-26 08:03:13', NULL, NULL, NULL),
|
||||
(8, 1000028, '散单工作台5', 1, 'personal', NULL, '11', '2026-07-25 01:06:17', '2026-07-26 08:03:21', NULL, NULL, NULL),
|
||||
(9, 1000028, '散单工作台6', 1, 'personal', NULL, '13', '2026-07-25 01:06:22', '2026-07-26 08:03:27', NULL, NULL, NULL),
|
||||
(10, 1000028, '散单工作台7', 1, 'personal', NULL, '16', '2026-07-25 01:06:27', '2026-07-26 09:01:24', NULL, NULL, NULL),
|
||||
(11, 1000028, '散单工作台8', 1, 'personal', NULL, '25', '2026-07-25 01:06:33', '2026-09-05 07:12:51', NULL, NULL, NULL),
|
||||
(12, 1000028, '团购1', 1, 'personal', NULL, '4', '2026-07-31 04:10:54', '2026-07-31 04:11:32', NULL, NULL, NULL),
|
||||
(13, 1000028, '团购2', 1, 'personal', NULL, '3', '2026-07-31 04:11:06', '2026-07-31 04:11:37', NULL, NULL, NULL),
|
||||
(14, 1000028, '团购3', 1, 'personal', NULL, '2', '2026-07-31 04:11:09', '2026-07-31 04:11:52', NULL, NULL, NULL),
|
||||
(15, 1000028, '团购4', 1, 'personal', NULL, '5', '2026-07-31 04:11:13', '2026-07-31 04:12:04', NULL, NULL, NULL),
|
||||
(16, 1000028, '团购5', 1, 'personal', NULL, '6', '2026-07-31 04:11:16', '2026-07-31 04:12:31', NULL, NULL, NULL),
|
||||
(17, 1000028, '团购6', 1, 'personal', NULL, '7', '2026-07-31 04:11:19', '2026-07-31 04:12:37', NULL, NULL, NULL),
|
||||
(18, 1000028, '团购7', 1, 'personal', NULL, NULL, '2026-07-31 04:11:21', '2026-09-03 00:27:07', '2026-09-03 00:27:07', NULL, NULL),
|
||||
(19, 1000028, '小波次 1 号工作台', 1, 'personal', NULL, '4', '2026-08-28 04:13:19', '2026-08-28 04:21:51', NULL, NULL, NULL),
|
||||
(20, 1000028, '小波次 2 号工作台', 1, 'personal', NULL, '24', '2026-08-28 04:13:26', '2026-08-28 04:21:44', NULL, NULL, NULL);
|
||||
@ -1,129 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 存量订单治理:单品单件散单波次订单回填 wave_scope = 4。
|
||||
*
|
||||
* 口径(与代码写入逻辑 resolveWaveScopeByWaveMeta 一致):
|
||||
* - 订单 wave_id > 0;
|
||||
* - 波次 wms_wave_batch.wave_type = 2(散单);
|
||||
* - 该波次最新拣货任务 pick_mode = 2(单品单件,1-小团购 2-单品单件 3-先拣后分 4-边拣边分 5-大团购)。
|
||||
*
|
||||
* pick_mode 取“每波次最新任务”:wms_wave_pick_task(wave_id 直连)与
|
||||
* wms_wave_pick_task_wave(任务-波次关联)两个来源取 id 最大的一条。
|
||||
* MySQL 5.7 兼容(不使用窗口函数)。
|
||||
*
|
||||
* 覆盖范围:基表 wms_order_delivery 与全部仓库分表(current/history/dispatch/outsourced)。
|
||||
* 幂等:按条件覆盖写入,重复执行结果一致。
|
||||
*/
|
||||
|
||||
const BASE_TABLE = 'wms_order_delivery';
|
||||
|
||||
const SHARD_PATTERN = /^wms_order_delivery_(\d+)(?:_(history|dispatch|outsourced))?$/;
|
||||
|
||||
/** 每波次最新拣货任务的 pick_mode 派生表 SQL(两个来源取 id 最大,DISTINCT 去重防止直连/关联重复行放大) */
|
||||
const LATEST_PICK_MODE_SQL = `
|
||||
SELECT u2.wave_id, u2.pick_mode
|
||||
FROM (
|
||||
SELECT DISTINCT wave_id, pick_mode, id
|
||||
FROM (
|
||||
SELECT wave_id, pick_mode, id FROM wms_wave_pick_task
|
||||
UNION ALL
|
||||
SELECT tw.wave_id, t.pick_mode, t.id
|
||||
FROM wms_wave_pick_task_wave tw
|
||||
JOIN wms_wave_pick_task t ON t.id = tw.task_id
|
||||
) u
|
||||
) u2
|
||||
JOIN (
|
||||
SELECT wave_id, MAX(id) AS max_id
|
||||
FROM (
|
||||
SELECT wave_id, id FROM wms_wave_pick_task
|
||||
UNION ALL
|
||||
SELECT tw.wave_id, t.id
|
||||
FROM wms_wave_pick_task_wave tw
|
||||
JOIN wms_wave_pick_task t ON t.id = tw.task_id
|
||||
) v
|
||||
GROUP BY wave_id
|
||||
) latest ON latest.wave_id = u2.wave_id AND latest.max_id = u2.id
|
||||
`;
|
||||
|
||||
/**
|
||||
* 列举库内全部订单分表。
|
||||
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
|
||||
* @return {Promise<string[]>} 分表名列表。
|
||||
*/
|
||||
async function listOrderShards(queryInterface) {
|
||||
const [ rows ] = await queryInterface.sequelize.query(
|
||||
'SELECT TABLE_NAME AS tableName FROM INFORMATION_SCHEMA.TABLES '
|
||||
+ 'WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME LIKE \'wms_order_delivery\\_%\' '
|
||||
+ 'ORDER BY TABLE_NAME'
|
||||
);
|
||||
return (rows || [])
|
||||
.map(row => String(row.tableName || row.TABLE_NAME || ''))
|
||||
.filter(name => SHARD_PATTERN.test(name));
|
||||
}
|
||||
|
||||
/**
|
||||
* 提取受影响行数。
|
||||
* @param {*} updateResult query 返回结果。
|
||||
* @return {number} 受影响行数。
|
||||
*/
|
||||
function extractAffectedRows(updateResult) {
|
||||
if (Array.isArray(updateResult)) {
|
||||
const meta = updateResult[1];
|
||||
return Number(meta && (meta.affectedRows || meta.affectedCount || meta.rowCount) || 0);
|
||||
}
|
||||
if (updateResult && typeof updateResult === 'object') {
|
||||
return Number(updateResult.affectedRows || updateResult.affectedCount || updateResult.rowCount || 0);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
/**
|
||||
* 执行迁移:单品单件散单波次订单 wave_scope 置为 4。
|
||||
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
|
||||
* @return {Promise<void>} 无返回值。
|
||||
*/
|
||||
async up(queryInterface) {
|
||||
const tables = [ BASE_TABLE, ...await listOrderShards(queryInterface) ];
|
||||
const results = [];
|
||||
|
||||
for (const tableName of tables) {
|
||||
const updateResult = await queryInterface.sequelize.query(`
|
||||
UPDATE \`${tableName}\` o
|
||||
JOIN wms_wave_batch wb ON wb.wave_id = o.wave_id
|
||||
JOIN (
|
||||
${LATEST_PICK_MODE_SQL}
|
||||
) pm ON pm.wave_id = o.wave_id
|
||||
SET o.wave_scope = 4
|
||||
WHERE o.wave_id > 0
|
||||
AND wb.wave_type = 2
|
||||
AND pm.pick_mode = 2
|
||||
`);
|
||||
results.push({ tableName, affectedRows: extractAffectedRows(updateResult) });
|
||||
}
|
||||
|
||||
console.log('[20260906100000-backfill-order-wave-scope-single] up results:', JSON.stringify(results));
|
||||
},
|
||||
|
||||
/**
|
||||
* 回滚迁移:单品单件(wave_scope=4)订单回置为散单(2)。
|
||||
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
|
||||
* @return {Promise<void>} 无返回值。
|
||||
*/
|
||||
async down(queryInterface) {
|
||||
const tables = [ BASE_TABLE, ...await listOrderShards(queryInterface) ];
|
||||
const results = [];
|
||||
|
||||
for (const tableName of tables) {
|
||||
const updateResult = await queryInterface.sequelize.query(`
|
||||
UPDATE \`${tableName}\`
|
||||
SET wave_scope = 2
|
||||
WHERE wave_scope = 4
|
||||
`);
|
||||
results.push({ tableName, affectedRows: extractAffectedRows(updateResult) });
|
||||
}
|
||||
|
||||
console.log('[20260906100000-backfill-order-wave-scope-single] down results:', JSON.stringify(results));
|
||||
},
|
||||
};
|
||||
@ -1,63 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
const TABLE_NAME = 'wms_workbench';
|
||||
|
||||
/**
|
||||
* Migration: add token_updated_at to wms_workbench
|
||||
* - token_updated_at: DATETIME NULL,记录工作台 token 最后更新时间。
|
||||
*
|
||||
* 背景:定时任务将扫描工作台,若 token 超过 3 个月未更新则强制清除 token 使设备下线,
|
||||
* 因此需要记录每个工作台 token 的最后更新时间。
|
||||
*
|
||||
* 回填策略:
|
||||
* - 有 token 的行:token_updated_at = updated_at。token 列由 20260903100000 迁移新增,
|
||||
* 绑定/刷新 token 时同步更新 updated_at,取 updated_at 是当前最接近「token 最后变更」的时间;
|
||||
* - 无 token 的行:保持 NULL(从未绑定 token,不参与过期扫描)。
|
||||
* - 回填语句同时显式赋值 updated_at = updated_at:表结构上 updated_at 带
|
||||
* ON UPDATE CURRENT_TIMESTAMP,显式赋值可阻止其被回填动作顶替为迁移执行时间。
|
||||
*
|
||||
* Idempotent: 通过 describeTable 判断后仅补齐缺失部分,回填按幂等条件覆盖。
|
||||
*/
|
||||
module.exports = {
|
||||
/**
|
||||
* 执行正向迁移:新增 token_updated_at 列并回填存量数据。
|
||||
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
|
||||
* @param {import('sequelize')} Sequelize Sequelize 实例。
|
||||
* @return {Promise<void>} 无返回值。
|
||||
*/
|
||||
up: async (queryInterface, Sequelize) => {
|
||||
const columns = await queryInterface.describeTable(TABLE_NAME);
|
||||
|
||||
if (!columns.token_updated_at) {
|
||||
await queryInterface.addColumn(TABLE_NAME, 'token_updated_at', {
|
||||
type: Sequelize.DATE,
|
||||
allowNull: true,
|
||||
comment: '工作台 token 最后更新时间(无 token 时为 NULL)',
|
||||
});
|
||||
console.log('[token_updated_at] 列已新增');
|
||||
} else {
|
||||
console.log('[token_updated_at] 列已存在,跳过新增');
|
||||
}
|
||||
|
||||
const result = await queryInterface.sequelize.query(
|
||||
`UPDATE ${TABLE_NAME} SET token_updated_at = updated_at, updated_at = updated_at WHERE (token IS NOT NULL AND token != '') AND token_updated_at IS NULL`
|
||||
);
|
||||
const affected = Array.isArray(result)
|
||||
? Number((result[1] && (result[1].affectedRows || result[1].affectedCount || result[1].rowCount)) || 0)
|
||||
: Number((result && (result.affectedRows || result.affectedCount || result.rowCount)) || 0);
|
||||
console.log(`[token_updated_at] 回填完成,影响行数: ${affected}`);
|
||||
},
|
||||
|
||||
/**
|
||||
* 执行回滚迁移:删除 token_updated_at 列(回填数据随之删除)。
|
||||
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
|
||||
* @return {Promise<void>} 无返回值。
|
||||
*/
|
||||
down: async queryInterface => {
|
||||
const columns = await queryInterface.describeTable(TABLE_NAME);
|
||||
if (columns.token_updated_at) {
|
||||
await queryInterface.removeColumn(TABLE_NAME, 'token_updated_at');
|
||||
console.log('[token_updated_at] 列已删除');
|
||||
}
|
||||
},
|
||||
};
|
||||
@ -1,106 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 订单表增加 intercept_time(拦截时间)字段。
|
||||
*
|
||||
* 背景:订单表当前仅维护 intercept_status 状态机,无拦截发生时间点;
|
||||
* 业务需要直接记录订单进入拦截流程/库内拦截确认的时间,避免依赖
|
||||
* 操作日志/售后工单反查。新增本列用于拦截时间直查。
|
||||
*
|
||||
* 取值约定:DATETIME,可空;订单未进入拦截流程时为 NULL,
|
||||
* 拦截状态发生关键变更(拦截发起/库内拦截确认)时由业务写入。
|
||||
*
|
||||
* 覆盖范围:
|
||||
* - 基表 wms_order_delivery;
|
||||
* - 全部仓库分表 wms_order_delivery_{wh}(current)及
|
||||
* _{wh}_history / _{wh}_dispatch / _{wh}_outsourced。
|
||||
*
|
||||
* 幂等:列已存在则跳过。分表模型由 app/model/order_delivery_factory.js
|
||||
* 运行时 drift 同步兜底,本迁移提前补齐避免运行时 ALTER。
|
||||
*/
|
||||
|
||||
const BASE_TABLE = 'wms_order_delivery';
|
||||
|
||||
const SHARD_PATTERN = /^wms_order_delivery_(\d+)(?:_(history|dispatch|outsourced))?$/;
|
||||
|
||||
const COLUMN_NAME = 'intercept_time';
|
||||
|
||||
/**
|
||||
* 列举库内全部订单分表。
|
||||
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
|
||||
* @return {Promise<string[]>} 分表名列表。
|
||||
*/
|
||||
async function listOrderShards(queryInterface) {
|
||||
const [ rows ] = await queryInterface.sequelize.query(
|
||||
'SELECT TABLE_NAME AS tableName FROM INFORMATION_SCHEMA.TABLES '
|
||||
+ 'WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME LIKE \'wms_order_delivery\\_%\' '
|
||||
+ 'ORDER BY TABLE_NAME'
|
||||
);
|
||||
return (rows || [])
|
||||
.map(row => String(row.tableName || row.TABLE_NAME || ''))
|
||||
.filter(name => SHARD_PATTERN.test(name));
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断列是否已存在。
|
||||
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
|
||||
* @param {string} tableName 表名。
|
||||
* @param {string} columnName 列名。
|
||||
* @return {Promise<boolean>} 是否存在。
|
||||
*/
|
||||
async function columnExists(queryInterface, tableName, columnName) {
|
||||
const described = await queryInterface.describeTable(tableName);
|
||||
return Boolean(described && described[columnName]);
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
/**
|
||||
* 执行迁移:为基表与全部分表增加 intercept_time 列。
|
||||
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
|
||||
* @param {import('sequelize')} Sequelize Sequelize 构造器。
|
||||
* @return {Promise<void>} 无返回值。
|
||||
*/
|
||||
async up(queryInterface, Sequelize) {
|
||||
const tables = [ BASE_TABLE, ...await listOrderShards(queryInterface) ];
|
||||
const results = [];
|
||||
|
||||
for (const tableName of tables) {
|
||||
if (await columnExists(queryInterface, tableName, COLUMN_NAME)) {
|
||||
results.push({ tableName, action: 'skip', reason: 'exists' });
|
||||
continue;
|
||||
}
|
||||
|
||||
await queryInterface.addColumn(tableName, COLUMN_NAME, {
|
||||
type: Sequelize.DATE,
|
||||
allowNull: true,
|
||||
defaultValue: null,
|
||||
comment: '拦截时间(进入拦截流程/库内拦截确认时写入)',
|
||||
});
|
||||
results.push({ tableName, action: 'added' });
|
||||
}
|
||||
|
||||
console.log('[20260907100000-add-intercept-time-to-order-delivery] up results:', JSON.stringify(results));
|
||||
},
|
||||
|
||||
/**
|
||||
* 回滚迁移:移除基表与全部分表的 intercept_time 列。
|
||||
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
|
||||
* @return {Promise<void>} 无返回值。
|
||||
*/
|
||||
async down(queryInterface) {
|
||||
const tables = [ BASE_TABLE, ...await listOrderShards(queryInterface) ];
|
||||
const results = [];
|
||||
|
||||
for (const tableName of tables) {
|
||||
if (!await columnExists(queryInterface, tableName, COLUMN_NAME)) {
|
||||
results.push({ tableName, action: 'skip', reason: 'missing' });
|
||||
continue;
|
||||
}
|
||||
|
||||
await queryInterface.removeColumn(tableName, COLUMN_NAME);
|
||||
results.push({ tableName, action: 'removed' });
|
||||
}
|
||||
|
||||
console.log('[20260907100000-add-intercept-time-to-order-delivery] down results:', JSON.stringify(results));
|
||||
},
|
||||
};
|
||||
@ -1,102 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 配送表增加 dispath_time(迁移进配送表时间)字段。
|
||||
*
|
||||
* 背景:出库订单从当前表迁移进配送表时整行复制源数据,
|
||||
* 缺少订单进入配送域的落库时间点;业务需要直接记录迁移时刻供查询与审计。
|
||||
*
|
||||
* 取值约定:DATETIME,可空;迁移链路
|
||||
* app/service/systems/order_delivery_migration.js 的 buildDispatchRow
|
||||
* 在写入配送表时设置 new Date(),源表不写该字段。
|
||||
*
|
||||
* 覆盖范围(仅配送表独有,不加基表/当前分表/history/outsourced):
|
||||
* - 全部配送分表 wms_order_delivery_{wh}_dispatch。
|
||||
*
|
||||
* 幂等:列已存在则跳过。配送表模型由 app/model/order_delivery_factory.js
|
||||
* 运行时 drift 同步兜底,本迁移提前补齐避免运行时 ALTER。
|
||||
*/
|
||||
|
||||
const DISPATCH_SHARD_PATTERN = /^wms_order_delivery_(\d+)_dispatch$/;
|
||||
|
||||
const COLUMN_NAME = 'dispath_time';
|
||||
|
||||
/**
|
||||
* 列举库内全部配送分表。
|
||||
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
|
||||
* @return {Promise<string[]>} 配送分表名列表。
|
||||
*/
|
||||
async function listDispatchShards(queryInterface) {
|
||||
const [ rows ] = await queryInterface.sequelize.query(
|
||||
'SELECT TABLE_NAME AS tableName FROM INFORMATION_SCHEMA.TABLES '
|
||||
+ 'WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME LIKE \'wms_order_delivery\\_%\\_dispatch\' '
|
||||
+ 'ORDER BY TABLE_NAME'
|
||||
);
|
||||
return (rows || [])
|
||||
.map(row => String(row.tableName || row.TABLE_NAME || ''))
|
||||
.filter(name => DISPATCH_SHARD_PATTERN.test(name));
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断列是否已存在。
|
||||
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
|
||||
* @param {string} tableName 表名。
|
||||
* @param {string} columnName 列名。
|
||||
* @return {Promise<boolean>} 是否存在。
|
||||
*/
|
||||
async function columnExists(queryInterface, tableName, columnName) {
|
||||
const described = await queryInterface.describeTable(tableName);
|
||||
return Boolean(described && described[columnName]);
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
/**
|
||||
* 执行迁移:为全部配送分表增加 dispath_time 列。
|
||||
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
|
||||
* @param {import('sequelize')} Sequelize Sequelize 构造器。
|
||||
* @return {Promise<void>} 无返回值。
|
||||
*/
|
||||
async up(queryInterface, Sequelize) {
|
||||
const tables = await listDispatchShards(queryInterface);
|
||||
const results = [];
|
||||
|
||||
for (const tableName of tables) {
|
||||
if (await columnExists(queryInterface, tableName, COLUMN_NAME)) {
|
||||
results.push({ tableName, action: 'skip', reason: 'exists' });
|
||||
continue;
|
||||
}
|
||||
|
||||
await queryInterface.addColumn(tableName, COLUMN_NAME, {
|
||||
type: Sequelize.DATE,
|
||||
allowNull: true,
|
||||
defaultValue: null,
|
||||
comment: '订单迁移进配送表的时间',
|
||||
});
|
||||
results.push({ tableName, action: 'added' });
|
||||
}
|
||||
|
||||
console.log('[20260907120000-add-dispath-time-to-order-delivery-dispatch] up results:', JSON.stringify(results));
|
||||
},
|
||||
|
||||
/**
|
||||
* 回滚迁移:移除全部配送分表的 dispath_time 列。
|
||||
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
|
||||
* @return {Promise<void>} 无返回值。
|
||||
*/
|
||||
async down(queryInterface) {
|
||||
const tables = await listDispatchShards(queryInterface);
|
||||
const results = [];
|
||||
|
||||
for (const tableName of tables) {
|
||||
if (!await columnExists(queryInterface, tableName, COLUMN_NAME)) {
|
||||
results.push({ tableName, action: 'skip', reason: 'missing' });
|
||||
continue;
|
||||
}
|
||||
|
||||
await queryInterface.removeColumn(tableName, COLUMN_NAME);
|
||||
results.push({ tableName, action: 'removed' });
|
||||
}
|
||||
|
||||
console.log('[20260907120000-add-dispath-time-to-order-delivery-dispatch] down results:', JSON.stringify(results));
|
||||
},
|
||||
};
|
||||
@ -1,22 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
module.exports = {
|
||||
async up(queryInterface) {
|
||||
await queryInterface.removeColumn('wms_store', 'logo_url');
|
||||
await queryInterface.removeColumn('wms_store', 'domain');
|
||||
},
|
||||
|
||||
async down(queryInterface, Sequelize) {
|
||||
const { STRING } = Sequelize;
|
||||
await queryInterface.addColumn('wms_store', 'logo_url', {
|
||||
type: STRING(255),
|
||||
allowNull: true,
|
||||
comment: 'logo链接',
|
||||
});
|
||||
await queryInterface.addColumn('wms_store', 'domain', {
|
||||
type: STRING(100),
|
||||
allowNull: true,
|
||||
comment: '绑定域名',
|
||||
});
|
||||
},
|
||||
};
|
||||
@ -1,177 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
const FRONT_CONFIG_TABLE = 'wms_warehouse_front_config';
|
||||
|
||||
/**
|
||||
* Migration: 仓库伪独立部署专表(单表终版)。
|
||||
* - wms_warehouse_front_config:每仓库一行(一仓一域一证书),保存仓库前端
|
||||
* 个性化配置(Logo / 标题 / 登录页图 / 主题)、证书元信息(只存路径不存
|
||||
* 证书内容)与 nginx 同步状态机(pending → success/failed)。
|
||||
* - 证书启用/停用由整行删除或 sync_status 表达;证书到期由 cert_expire_at
|
||||
* 判断,不单独保留证书 status 列。
|
||||
* - domain 可空列唯一索引(uk_domain):MySQL 可空列唯一索引允许多个 NULL,
|
||||
* 非空值的唯一性需应用层校验(详见对应 Model 注释)。
|
||||
* - 演进说明:原双表方案(wms_warehouse_front_config + wms_warehouse_cert)
|
||||
* 已废弃;旧版迁移仅在开发库执行过且两表均为空,已 undo 后以本单表版本
|
||||
* 重跑。生产库从未执行过本迁移,一次发布窗口直接执行本文件即可。
|
||||
*
|
||||
* Idempotent: 表已存在时跳过创建。
|
||||
*/
|
||||
|
||||
/**
|
||||
* 判断表是否存在。
|
||||
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
|
||||
* @param {string} tableName 表名。
|
||||
* @return {Promise<boolean>} 存在返回 true。
|
||||
*/
|
||||
async function tableExists(queryInterface, tableName) {
|
||||
const tables = await queryInterface.showAllTables();
|
||||
return tables.some(t => (typeof t === 'string' ? t : (t.tableName || t.name)) === tableName);
|
||||
}
|
||||
|
||||
/**
|
||||
* 同步状态机字段(nginx 配置下发同步)。
|
||||
* @param {import('sequelize')} Sequelize Sequelize 实例。
|
||||
* @return {Object} 字段定义。
|
||||
*/
|
||||
function syncStateFields(Sequelize) {
|
||||
return {
|
||||
sync_status: {
|
||||
type: Sequelize.TINYINT,
|
||||
allowNull: false,
|
||||
defaultValue: 0,
|
||||
comment: '同步状态:0-待同步,1-同步成功,2-同步失败',
|
||||
},
|
||||
sync_attempts: {
|
||||
type: Sequelize.INTEGER(11),
|
||||
allowNull: false,
|
||||
defaultValue: 0,
|
||||
comment: '同步尝试次数',
|
||||
},
|
||||
last_sync_error: {
|
||||
type: Sequelize.STRING(500),
|
||||
allowNull: true,
|
||||
comment: '最近一次同步失败原因',
|
||||
},
|
||||
last_synced_at: {
|
||||
type: Sequelize.DATE,
|
||||
allowNull: true,
|
||||
comment: '最近一次同步成功时间',
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 时间戳字段(创建/更新时间),与项目既有建表迁移一致。
|
||||
* @param {import('sequelize')} Sequelize Sequelize 实例。
|
||||
* @return {Object} 字段定义。
|
||||
*/
|
||||
function timestampFields(Sequelize) {
|
||||
return {
|
||||
created_at: {
|
||||
type: Sequelize.DATE,
|
||||
allowNull: false,
|
||||
defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'),
|
||||
comment: '创建时间',
|
||||
},
|
||||
updated_at: {
|
||||
type: Sequelize.DATE,
|
||||
allowNull: false,
|
||||
defaultValue: Sequelize.literal('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'),
|
||||
comment: '更新时间',
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
/**
|
||||
* 执行正向迁移:创建仓库前端配置表(单表,含证书元信息)。
|
||||
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
|
||||
* @param {import('sequelize')} Sequelize Sequelize 实例。
|
||||
* @return {Promise<void>} 无返回值。
|
||||
*/
|
||||
up: async (queryInterface, Sequelize) => {
|
||||
if (await tableExists(queryInterface, FRONT_CONFIG_TABLE)) {
|
||||
return;
|
||||
}
|
||||
|
||||
await queryInterface.createTable(FRONT_CONFIG_TABLE, {
|
||||
id: {
|
||||
type: Sequelize.BIGINT(20).UNSIGNED,
|
||||
primaryKey: true,
|
||||
autoIncrement: true,
|
||||
allowNull: false,
|
||||
comment: '主键ID',
|
||||
},
|
||||
store_id: {
|
||||
type: Sequelize.BIGINT(20).UNSIGNED,
|
||||
allowNull: false,
|
||||
comment: '仓库ID,关联 wms_store.id(is_warehouse=1),每仓一行',
|
||||
},
|
||||
domain: {
|
||||
type: Sequelize.STRING(100),
|
||||
allowNull: true,
|
||||
comment: '仓库自持域名;可空列唯一索引允许多个 NULL,非空值唯一性需应用层校验',
|
||||
},
|
||||
title: {
|
||||
type: Sequelize.STRING(100),
|
||||
allowNull: true,
|
||||
comment: '站点标题',
|
||||
},
|
||||
logo_url: {
|
||||
type: Sequelize.STRING(255),
|
||||
allowNull: true,
|
||||
comment: 'Logo地址',
|
||||
},
|
||||
login_bg_url: {
|
||||
type: Sequelize.STRING(255),
|
||||
allowNull: true,
|
||||
comment: '登录页背景图地址',
|
||||
},
|
||||
theme: {
|
||||
type: Sequelize.JSON,
|
||||
allowNull: true,
|
||||
defaultValue: null,
|
||||
comment: '主题配置JSON(颜色/布局等)',
|
||||
},
|
||||
cert_path: {
|
||||
type: Sequelize.STRING(500),
|
||||
allowNull: true,
|
||||
comment: '证书文件路径(只存路径不存内容)',
|
||||
},
|
||||
key_path: {
|
||||
type: Sequelize.STRING(500),
|
||||
allowNull: true,
|
||||
comment: '私钥文件路径(只存路径不存内容)',
|
||||
},
|
||||
cert_expire_at: {
|
||||
type: Sequelize.DATE,
|
||||
allowNull: true,
|
||||
comment: '证书到期时间',
|
||||
},
|
||||
...syncStateFields(Sequelize),
|
||||
...timestampFields(Sequelize),
|
||||
});
|
||||
|
||||
await queryInterface.addIndex(FRONT_CONFIG_TABLE, [ 'store_id' ], {
|
||||
name: 'uk_store_id',
|
||||
unique: true,
|
||||
});
|
||||
await queryInterface.addIndex(FRONT_CONFIG_TABLE, [ 'domain' ], {
|
||||
name: 'uk_domain',
|
||||
unique: true,
|
||||
});
|
||||
await queryInterface.addIndex(FRONT_CONFIG_TABLE, [ 'sync_status' ], {
|
||||
name: 'idx_sync_status',
|
||||
});
|
||||
},
|
||||
|
||||
/**
|
||||
* 回滚:删除仓库前端配置表。
|
||||
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
|
||||
* @return {Promise<void>} 无返回值。
|
||||
*/
|
||||
down: async queryInterface => {
|
||||
await queryInterface.dropTable(FRONT_CONFIG_TABLE);
|
||||
},
|
||||
};
|
||||
@ -1,72 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* wms_entry_order_receiving 绑定表增加 allocated_quantity(数量台账)字段。
|
||||
*
|
||||
* 背景:入库单-收货单绑定后按入库单计划数量向收货单明细累加 stored_quantity,
|
||||
* 同一入库单绑定多个收货单时会重复全额分配(合计超出计划数量)。
|
||||
* 修复方案 A:在绑定行上维护数量台账(收货明细ID → 已分配数量),
|
||||
* 分配时按 SKU 封顶 min(入库单计划数 − 其他绑定已分配量, 收货明细剩余可入量)。
|
||||
*
|
||||
* 取值约定:JSON,可空。
|
||||
* - NULL:迁移前的历史绑定行(未初始化台账,业务代码按“收货单侧已累计量”兜底重建);
|
||||
* - {}:新链路创建/解绑清零后的空台账;
|
||||
* - {"<receiving_detail_id>": <qty>}:明细级分配数量台账。
|
||||
*
|
||||
* 幂等:列已存在则跳过。仅基表(无分表)。
|
||||
*/
|
||||
|
||||
const TABLE_NAME = 'wms_entry_order_receiving';
|
||||
|
||||
const COLUMN_NAME = 'allocated_quantity';
|
||||
|
||||
/**
|
||||
* 判断列是否已存在。
|
||||
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
|
||||
* @param {string} tableName 表名。
|
||||
* @param {string} columnName 列名。
|
||||
* @return {Promise<boolean>} 是否存在。
|
||||
*/
|
||||
async function columnExists(queryInterface, tableName, columnName) {
|
||||
const described = await queryInterface.describeTable(tableName);
|
||||
return Boolean(described && described[columnName]);
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
/**
|
||||
* 执行迁移:为绑定表增加 allocated_quantity 台账列。
|
||||
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
|
||||
* @param {import('sequelize')} Sequelize Sequelize 构造器。
|
||||
* @return {Promise<void>} 无返回值。
|
||||
*/
|
||||
async up(queryInterface, Sequelize) {
|
||||
if (await columnExists(queryInterface, TABLE_NAME, COLUMN_NAME)) {
|
||||
console.log(`[20260907160000-add-allocated-quantity-to-wms-entry-order-receiving] up skip: ${TABLE_NAME}.${COLUMN_NAME} exists`);
|
||||
return;
|
||||
}
|
||||
|
||||
await queryInterface.addColumn(TABLE_NAME, COLUMN_NAME, {
|
||||
type: Sequelize.JSON,
|
||||
allowNull: true,
|
||||
defaultValue: null,
|
||||
comment: '数量台账:收货明细ID→已分配数量(JSON对象);null 表示旧数据未初始化',
|
||||
});
|
||||
|
||||
console.log(`[20260907160000-add-allocated-quantity-to-wms-entry-order-receiving] up added: ${TABLE_NAME}.${COLUMN_NAME}`);
|
||||
},
|
||||
|
||||
/**
|
||||
* 回滚迁移:移除台账列。
|
||||
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
|
||||
* @return {Promise<void>} 无返回值。
|
||||
*/
|
||||
async down(queryInterface) {
|
||||
if (!await columnExists(queryInterface, TABLE_NAME, COLUMN_NAME)) {
|
||||
console.log(`[20260907160000-add-allocated-quantity-to-wms-entry-order-receiving] down skip: ${TABLE_NAME}.${COLUMN_NAME} missing`);
|
||||
return;
|
||||
}
|
||||
|
||||
await queryInterface.removeColumn(TABLE_NAME, COLUMN_NAME);
|
||||
console.log(`[20260907160000-add-allocated-quantity-to-wms-entry-order-receiving] down removed: ${TABLE_NAME}.${COLUMN_NAME}`);
|
||||
},
|
||||
};
|
||||
@ -1,58 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
const TABLE_NAME = 'wms_warehouse_front_config';
|
||||
const COLUMN_NAME = 'favicon_url';
|
||||
|
||||
/**
|
||||
* 判断表是否存在。
|
||||
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
|
||||
* @param {string} tableName 表名。
|
||||
* @return {Promise<boolean>} 存在返回 true。
|
||||
*/
|
||||
async function tableExists(queryInterface, tableName) {
|
||||
const tables = await queryInterface.showAllTables();
|
||||
return tables.some(t => (typeof t === 'string' ? t : (t.tableName || t.name)) === tableName);
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
/**
|
||||
* 执行正向迁移:为仓库前端配置表新增 favicon_url(站点 favicon 图标地址,幂等)。
|
||||
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
|
||||
* @param {import('sequelize')} Sequelize Sequelize 实例。
|
||||
* @return {Promise<void>} 无返回值。
|
||||
*/
|
||||
async up(queryInterface, Sequelize) {
|
||||
if (!(await tableExists(queryInterface, TABLE_NAME))) {
|
||||
return;
|
||||
}
|
||||
|
||||
const columns = await queryInterface.describeTable(TABLE_NAME);
|
||||
if (columns[COLUMN_NAME]) {
|
||||
return;
|
||||
}
|
||||
|
||||
await queryInterface.addColumn(TABLE_NAME, COLUMN_NAME, {
|
||||
type: Sequelize.STRING(255),
|
||||
allowNull: true,
|
||||
comment: '站点 favicon 图标地址',
|
||||
});
|
||||
},
|
||||
|
||||
/**
|
||||
* 回滚迁移:删除 favicon_url 字段(幂等)。
|
||||
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
|
||||
* @return {Promise<void>} 无返回值。
|
||||
*/
|
||||
async down(queryInterface) {
|
||||
if (!(await tableExists(queryInterface, TABLE_NAME))) {
|
||||
return;
|
||||
}
|
||||
|
||||
const columns = await queryInterface.describeTable(TABLE_NAME);
|
||||
if (!columns[COLUMN_NAME]) {
|
||||
return;
|
||||
}
|
||||
|
||||
await queryInterface.removeColumn(TABLE_NAME, COLUMN_NAME);
|
||||
},
|
||||
};
|
||||
@ -1,91 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
const TABLE_NAME = 'wms_warehouse_front_config';
|
||||
const CERT_PEM_COLUMN = 'cert_pem';
|
||||
const CERT_KEY_COLUMN = 'cert_key';
|
||||
|
||||
/**
|
||||
* Migration: 仓库前端配置表新增证书内容列(证书 PEM 文本直接入库)。
|
||||
*
|
||||
* 背景:
|
||||
* 原方案证书内容只存路径(cert_path/key_path),由保存接口写暂存文件后部署;
|
||||
* 现改为证书 PEM 文本直接入库,由定时任务拉取后写文件部署。
|
||||
* 证书链 fullchain PEM 一般 2~10KB,TEXT(上限 64KB)足够,且项目内长文本
|
||||
* 列惯例使用 TEXT(如 20260818190000 wms_order_items.ext_code 改 TEXT);
|
||||
* 不选 VARCHAR(16384):utf8mb4 下 16K 字符已触发 MySQL 5.7 行大小限制风险,
|
||||
* 且 PEM 长度无硬上限,TEXT 更稳。
|
||||
*
|
||||
* 列说明:
|
||||
* - cert_pem:证书 PEM 内容(私钥不在内);
|
||||
* - cert_key:私钥 PEM 内容;
|
||||
* - 均允许为 NULL(未上传证书时为空),无需索引;
|
||||
* - 敏感内容:仅由定时任务读取,禁止写入日志/接口响应。
|
||||
*
|
||||
* Idempotent: up 列已存在时跳过、down 列不存在时跳过。
|
||||
*/
|
||||
|
||||
/**
|
||||
* 判断表是否存在。
|
||||
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
|
||||
* @param {string} tableName 表名。
|
||||
* @return {Promise<boolean>} 存在返回 true。
|
||||
*/
|
||||
async function tableExists(queryInterface, tableName) {
|
||||
const tables = await queryInterface.showAllTables();
|
||||
return tables.some(t => (typeof t === 'string' ? t : (t.tableName || t.name)) === tableName);
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
/**
|
||||
* 执行正向迁移:新增 cert_pem / cert_key 两列(幂等)。
|
||||
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
|
||||
* @param {import('sequelize')} Sequelize Sequelize 实例。
|
||||
* @return {Promise<void>} 无返回值。
|
||||
*/
|
||||
async up(queryInterface, Sequelize) {
|
||||
if (!(await tableExists(queryInterface, TABLE_NAME))) {
|
||||
return;
|
||||
}
|
||||
|
||||
const columns = await queryInterface.describeTable(TABLE_NAME);
|
||||
|
||||
if (!columns[CERT_PEM_COLUMN]) {
|
||||
await queryInterface.addColumn(TABLE_NAME, CERT_PEM_COLUMN, {
|
||||
type: Sequelize.TEXT,
|
||||
allowNull: true,
|
||||
comment: '证书 PEM 内容(私钥不在内);内容仅由定时任务读取,禁止写入日志/接口响应',
|
||||
after: 'cert_path',
|
||||
});
|
||||
}
|
||||
|
||||
if (!columns[CERT_KEY_COLUMN]) {
|
||||
await queryInterface.addColumn(TABLE_NAME, CERT_KEY_COLUMN, {
|
||||
type: Sequelize.TEXT,
|
||||
allowNull: true,
|
||||
comment: '私钥 PEM 内容;内容仅由定时任务读取,禁止写入日志/接口响应',
|
||||
after: 'key_path',
|
||||
});
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* 回滚迁移:删除 cert_pem / cert_key 两列(幂等)。
|
||||
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
|
||||
* @return {Promise<void>} 无返回值。
|
||||
*/
|
||||
async down(queryInterface) {
|
||||
if (!(await tableExists(queryInterface, TABLE_NAME))) {
|
||||
return;
|
||||
}
|
||||
|
||||
const columns = await queryInterface.describeTable(TABLE_NAME);
|
||||
|
||||
if (columns[CERT_PEM_COLUMN]) {
|
||||
await queryInterface.removeColumn(TABLE_NAME, CERT_PEM_COLUMN);
|
||||
}
|
||||
|
||||
if (columns[CERT_KEY_COLUMN]) {
|
||||
await queryInterface.removeColumn(TABLE_NAME, CERT_KEY_COLUMN);
|
||||
}
|
||||
},
|
||||
};
|
||||
@ -1,71 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 为波次表 wms_wave_batch 增加复核开始时间字段。
|
||||
*
|
||||
* 背景:
|
||||
* 复核扫描接口 order.recheckOrder.scanOrder 首次成功加载某波次的复核视图时,
|
||||
* 需要记录该波次的复核开始时间用于统计与审计;此前波次表仅有复核完成时间
|
||||
* (check_time,校验时间),缺少复核开始时间,二者语义不同不可复用。
|
||||
*
|
||||
* 变更:
|
||||
* 1. wms_wave_batch 新增 recheck_start_time:DATETIME,可空、无默认值,复核开始时间。
|
||||
* 2. 不回填任何历史数据(对既有数据零影响,仅后续首次扫描时写入)。
|
||||
* 3. 模型定义同步更新(app/model/wave_batch.js)。
|
||||
*
|
||||
* 幂等:字段已存在则跳过;回滚时字段不存在则跳过。
|
||||
*/
|
||||
|
||||
const TABLE_NAME = 'wms_wave_batch';
|
||||
const COLUMN_NAME = 'recheck_start_time';
|
||||
const FILE_TAG = '[20260908120000-add-recheck-start-time-to-wms-wave-batch]';
|
||||
|
||||
/**
|
||||
* 获取表字段定义。
|
||||
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
|
||||
* @param {string} tableName 表名。
|
||||
* @return {Promise<Object>} 字段定义对象。
|
||||
*/
|
||||
const getTableColumns = async (queryInterface, tableName) => {
|
||||
return queryInterface.describeTable(tableName);
|
||||
};
|
||||
|
||||
module.exports = {
|
||||
/**
|
||||
* 正向迁移:为波次表补充复核开始时间字段(字段已存在则跳过)。
|
||||
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
|
||||
* @param {typeof import('sequelize')} Sequelize Sequelize 类型集合。
|
||||
* @return {Promise<void>} 无返回值。
|
||||
*/
|
||||
up: async (queryInterface, Sequelize) => {
|
||||
const columnsBefore = await getTableColumns(queryInterface, TABLE_NAME);
|
||||
|
||||
if (!columnsBefore[COLUMN_NAME]) {
|
||||
await queryInterface.addColumn(TABLE_NAME, COLUMN_NAME, {
|
||||
type: Sequelize.DATE,
|
||||
allowNull: true,
|
||||
comment: '复核开始时间',
|
||||
after: 'check_result',
|
||||
});
|
||||
console.log(`${FILE_TAG} up: added column ${COLUMN_NAME} on ${TABLE_NAME}`);
|
||||
} else {
|
||||
console.log(`${FILE_TAG} up: skip, column ${COLUMN_NAME} already exists on ${TABLE_NAME}`);
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* 回滚迁移:若复核开始时间字段存在则删除。
|
||||
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
|
||||
* @return {Promise<void>} 无返回值。
|
||||
*/
|
||||
down: async queryInterface => {
|
||||
const columnsBefore = await getTableColumns(queryInterface, TABLE_NAME);
|
||||
|
||||
if (columnsBefore[COLUMN_NAME]) {
|
||||
await queryInterface.removeColumn(TABLE_NAME, COLUMN_NAME);
|
||||
console.log(`${FILE_TAG} down: removed column ${COLUMN_NAME} on ${TABLE_NAME}`);
|
||||
} else {
|
||||
console.log(`${FILE_TAG} down: skip, column ${COLUMN_NAME} not exists on ${TABLE_NAME}`);
|
||||
}
|
||||
},
|
||||
};
|
||||
Some files were not shown because too many files have changed in this diff Show More
Loading…
x
Reference in New Issue
Block a user