原实现先捞全量称重订单ID(wms_order_express 全表扫描,生产 167 万行/165s)再拼 id IN 约束,既慢又会产生巨型 IN 列表。改为关联 EXISTS 子查询:订单表驱动,快递表按 order_id 唯一索引逐行点查,命中语义不变(同一订单任一快递记录 weighing_weight > 0 即算已称重)。生产实测该查询由 165s 降至 0.03~0.07s。 Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
659 lines
23 KiB
JavaScript
659 lines
23 KiB
JavaScript
'use strict';
|
||
|
||
const MainService = require('../main');
|
||
const Sequelize = require('sequelize');
|
||
const { Op } = Sequelize;
|
||
|
||
const OUTBOUND_STATUS = 'fin';
|
||
const OUTBOUND_STEP = 4;
|
||
const ORDER_STATUS_FINISHED = 'finished';
|
||
const MAX_BATCH_SIZE = 500;
|
||
const STORAGE_STATUS_FIN = 'fin';
|
||
const RECHECK_STATUS_FIN = 'fin';
|
||
const DAY_MS = 24 * 3600 * 1000;
|
||
const BEIJING_OFFSET_MS = 8 * 3600 * 1000;
|
||
// 出库操作日志编码(app/dict/businessDict.js OPERATION_CODE)
|
||
const AUTO_OUTBOUND_OPERATION_CODE = 'ORDER_AUTO_OUTBOUND';
|
||
// 定时任务无用户上下文,按系统操作人记录
|
||
const AUTO_OUTBOUND_OPERATOR = Object.freeze({ id: null, name: '系统' });
|
||
|
||
/**
|
||
* 订单自动化出库服务。
|
||
*
|
||
* 当仓库开启 auto_outbound_enabled 且配置了 auto_outbound_rules(数组,任一命中即出库)时,
|
||
* 自动将满足条件的订单标记为出库并将订单状态更新为已完成。
|
||
* 规则前置条件固定为「已复核」(recheck_status=fin)+「已分配储位」(storage_status=fin)。
|
||
*/
|
||
class OrderAutoOutboundService extends MainService {
|
||
/**
|
||
* 获取所有启用了自动化出库且配置了规则的仓库。
|
||
*
|
||
* 自动出库配置以仓库为单位生效(wms_store.id 即 warehouse_id),
|
||
* 处理范围仅限当前仓库,不再扩散到该货主签约的外部合同仓。
|
||
*
|
||
* @return {Promise<Array<{storeId: number, warehouseId: number, rules: Array<Object>}>>} 仓库配置列表。
|
||
*/
|
||
async getEnabledAutoOutboundWarehouses() {
|
||
const { app } = this;
|
||
const { Store } = app.model;
|
||
|
||
if (!Store) {
|
||
return [];
|
||
}
|
||
|
||
const stores = await Store.findAll({
|
||
where: {
|
||
status: 1,
|
||
deleted_at: null,
|
||
},
|
||
attributes: [ 'id', 'subject_config' ],
|
||
raw: true,
|
||
});
|
||
|
||
const result = [];
|
||
|
||
for (const store of stores) {
|
||
if (!this.isAutoOutboundEnabled(store.subject_config)) {
|
||
continue;
|
||
}
|
||
|
||
const rules = this.resolveAutoOutboundRules(store.subject_config);
|
||
|
||
// 空数组表示不出库任何订单,直接跳过(无需告警)
|
||
if (rules.length === 0) {
|
||
continue;
|
||
}
|
||
|
||
result.push({
|
||
storeId: store.id,
|
||
warehouseId: store.id,
|
||
rules,
|
||
});
|
||
}
|
||
|
||
return result;
|
||
}
|
||
|
||
/**
|
||
* 判断仓库是否启用自动出库(subject_config.auto_outbound_enabled)。
|
||
*
|
||
* @param {Object|string|null|undefined} rawConfig subject_config 原始值。
|
||
* @return {boolean} 是否启用。
|
||
*/
|
||
isAutoOutboundEnabled(rawConfig) {
|
||
const subjectConfig = this.normalizeSubjectConfigForAutoOutbound(rawConfig);
|
||
const enabled = subjectConfig && subjectConfig.auto_outbound_enabled;
|
||
|
||
return enabled === true || enabled === 1 || enabled === '1' || enabled === 'true';
|
||
}
|
||
|
||
/**
|
||
* 解析自动出库规则数组(复用 Store 模型归一化,补齐缺省字段)。
|
||
* 旧对象结构或非法规则一律按空数组处理(空数组 = 不出库任何订单)。
|
||
*
|
||
* @param {Object|string|null|undefined} rawConfig subject_config 原始值。
|
||
* @return {Array<Object>} 规则数组。
|
||
*/
|
||
resolveAutoOutboundRules(rawConfig) {
|
||
const subjectConfig = this.normalizeSubjectConfigForAutoOutbound(rawConfig);
|
||
const rules = subjectConfig && subjectConfig.auto_outbound_rules;
|
||
const storeModel = this.app && this.app.model && this.app.model.Store;
|
||
|
||
if (storeModel && typeof storeModel.normalizeAutoOutboundRules === 'function') {
|
||
try {
|
||
return storeModel.normalizeAutoOutboundRules(rules);
|
||
} catch (error) {
|
||
this.ctx.logger.warn(`[auto-outbound] 自动出库规则配置非法,已按空规则处理: ${error.message}`);
|
||
return [];
|
||
}
|
||
}
|
||
|
||
if (!Array.isArray(rules)) {
|
||
return [];
|
||
}
|
||
|
||
return rules.filter(rule => rule && typeof rule === 'object' && !Array.isArray(rule));
|
||
}
|
||
|
||
/**
|
||
* 规范化 subject_config,支持字符串 JSON 和对象两种格式。
|
||
*
|
||
* @param {Object|string} rawConfig 原始主体配置。
|
||
* @return {Object} 规范化后的配置对象。
|
||
*/
|
||
normalizeSubjectConfigForAutoOutbound(rawConfig) {
|
||
if (!rawConfig) {
|
||
return {};
|
||
}
|
||
|
||
if (typeof rawConfig === 'object' && !Array.isArray(rawConfig)) {
|
||
return rawConfig;
|
||
}
|
||
|
||
if (typeof rawConfig === 'string') {
|
||
try {
|
||
return JSON.parse(rawConfig);
|
||
} catch (error) {
|
||
return {};
|
||
}
|
||
}
|
||
|
||
return {};
|
||
}
|
||
|
||
/**
|
||
* 构造单条自动化出库规则的订单查询条件。
|
||
*
|
||
* 基础条件(所有规则固定):已复核(recheck_status='fin')+ 已分配储位(storage_status='fin')
|
||
* + 未出库(outbound_status='none')+ 状态非 cancel/error/finished。
|
||
*
|
||
* @param {Object} rule 自动化出库规则(单条),支持字段:
|
||
* - {boolean} [rule.require_pack] 是否要求已打包(pack_status='fin')
|
||
* - {boolean} [rule.require_sync] 是否要求已同步(sync_status='fin')
|
||
* - {boolean} [rule.exclude_same_day_outbound] 是否不出库当天复核订单(默认 true);
|
||
* 开启后按「复核时间所在北京日 D」判定:
|
||
* recheck_time < D + deadline(默认 06:00)的订单不受影响;
|
||
* recheck_time ≥ D + deadline 的订单在 now < D + release(默认 22:00)前不出库,到达后放行。
|
||
* release 支持跨天(最大 47:59),如 27:00 表示次日 03:00 放行;
|
||
* recheck_time 为 null 的订单不受限制。
|
||
* - {string} [rule.same_day_outbound_deadline_time] 允许当天出库最后时间(HH:mm,默认 '06:00',当天内)。
|
||
* - {string} [rule.same_day_outbound_release_time] 放行时间(HH:mm,默认 '22:00',支持 00:00~47:59)。
|
||
* 常用组合:deadline='00:00' + release='23:59' → 当天复核的订单当天不出库,过了零点全部出库;
|
||
* deadline='00:00' + release='27:00' → 到次日 03:00 才全部出库。
|
||
* 注:require_weigh(已称重)涉及 wms_order_express,由调用方通过订单ID 子集约束,不在此处拼装。
|
||
*
|
||
* @return {Object} Sequelize where 条件对象。
|
||
*/
|
||
buildAutoOutboundWhere(rule) {
|
||
const safeRule = rule && typeof rule === 'object' ? rule : {};
|
||
const where = {
|
||
outbound_status: 'none',
|
||
status: {
|
||
[Op.notIn]: [ 'cancel', 'error', 'finished' ],
|
||
},
|
||
storage_status: STORAGE_STATUS_FIN,
|
||
// 未复核订单一律不自动出库(固定基线)
|
||
recheck_status: RECHECK_STATUS_FIN,
|
||
};
|
||
|
||
// 开启「不出库当天订单」(默认开启)时:按复核时间所在北京日计算未放行窗口,
|
||
// 未放行窗口内的订单(recheck_time ∈ [D+deadline, D+24h) 且 now < D+release)不自动出库。
|
||
// 注意:应用按 UTC 读写 DATETIME,recheck_time 存储为 UTC 时刻,边界需按北京时间(UTC+8)换算。
|
||
if (safeRule.exclude_same_day_outbound !== false) {
|
||
const recheckCondition = this.buildSameDayOutboundRecheckCondition(new Date(), safeRule);
|
||
if (recheckCondition) {
|
||
where.recheck_time = recheckCondition;
|
||
}
|
||
}
|
||
|
||
if (safeRule.require_pack) {
|
||
where.pack_status = 'fin';
|
||
}
|
||
|
||
if (safeRule.require_sync) {
|
||
where.sync_status = 'fin';
|
||
}
|
||
|
||
return where;
|
||
}
|
||
|
||
/**
|
||
* 扫描仓库下命中任一自动出库规则的订单ID。
|
||
*
|
||
* 逐条规则查询(规则内条件 AND),命中即纳入结果;订单ID 去重并保留首个命中的规则下标。
|
||
* 需要称重的规则通过关联 EXISTS 子查询(订单表驱动、快递表按 order_id 点查)约束。
|
||
*
|
||
* @param {number} warehouseId 仓库ID。
|
||
* @param {Array<Object>} rules 自动化出库规则数组。
|
||
* @param {number} [limit=MAX_BATCH_SIZE] 单次扫描上限(按仓库汇总)。
|
||
* @return {Promise<{orderIds: Array<number>, ruleIndexById: Map<number, number>}>} 命中订单ID与规则下标映射。
|
||
*/
|
||
async findAutoOutboundOrderIds(warehouseId, rules, limit = MAX_BATCH_SIZE) {
|
||
const { ctx } = this;
|
||
const factory = ctx.model && ctx.model.OrderDeliveryFactory;
|
||
const emptyResult = { orderIds: [], ruleIndexById: new Map() };
|
||
|
||
if (!factory || typeof factory.getCurrentModel !== 'function') {
|
||
return emptyResult;
|
||
}
|
||
|
||
const orderModel = await factory.getCurrentModel(warehouseId);
|
||
if (!orderModel) {
|
||
return emptyResult;
|
||
}
|
||
|
||
const ruleList = Array.isArray(rules) ? rules : [];
|
||
const orderIds = [];
|
||
const ruleIndexById = new Map();
|
||
|
||
for (let index = 0; index < ruleList.length; index += 1) {
|
||
const remaining = limit - orderIds.length;
|
||
if (remaining <= 0) {
|
||
break;
|
||
}
|
||
|
||
const rule = ruleList[index] && typeof ruleList[index] === 'object' ? ruleList[index] : {};
|
||
const where = this.buildAutoOutboundWhere(rule);
|
||
|
||
if (rule.require_weigh) {
|
||
const weighCondition = this.buildWeighExistsCondition(orderModel, warehouseId);
|
||
if (!weighCondition) {
|
||
ctx.logger.warn(
|
||
`[auto-outbound] 仓库 ${warehouseId} 缺少订单快递模型或仓库ID非法,跳过「需已称重」规则${index + 1}`
|
||
);
|
||
continue;
|
||
}
|
||
where[Op.and] = [ ...(Array.isArray(where[Op.and]) ? where[Op.and] : []), weighCondition ];
|
||
}
|
||
|
||
const orders = await orderModel.findAll({
|
||
where,
|
||
attributes: [ 'id' ],
|
||
limit: remaining,
|
||
raw: true,
|
||
});
|
||
|
||
for (const order of orders) {
|
||
const orderId = Number(order && order.id);
|
||
if (!Number.isFinite(orderId) || orderId <= 0 || ruleIndexById.has(orderId)) {
|
||
continue;
|
||
}
|
||
ruleIndexById.set(orderId, index);
|
||
orderIds.push(orderId);
|
||
}
|
||
}
|
||
|
||
return { orderIds, ruleIndexById };
|
||
}
|
||
|
||
/**
|
||
* 解析 HH:mm 时间配置为小时/分钟,支持跨天(小时可超过 23)。
|
||
* 缺省、格式非法或超出 maxHour 时回退指定默认值。
|
||
*
|
||
* @param {string} [timeText] 时间文本,如 '22:00'、'27:00'(= 次日 03:00)。
|
||
* @param {number} defaultHour 默认小时。
|
||
* @param {number} defaultMinute 默认分钟。
|
||
* @param {number} [maxHour=23] 允许的最大小时(放开时间支持 47,表示可跨到次日)。
|
||
* @return {{hour: number, minute: number}} 小时与分钟。
|
||
*/
|
||
resolveSameDayTime(timeText, defaultHour, defaultMinute, maxHour = 23) {
|
||
const text = typeof timeText === 'string' ? timeText.trim() : '';
|
||
const match = /^(\d{1,2}):([0-5]\d)$/.exec(text);
|
||
if (!match) {
|
||
return { hour: defaultHour, minute: defaultMinute };
|
||
}
|
||
const hour = Number(match[1]);
|
||
if (hour > maxHour) {
|
||
return { hour: defaultHour, minute: defaultMinute };
|
||
}
|
||
return { hour, minute: Number(match[2]) };
|
||
}
|
||
|
||
/**
|
||
* 解析「允许当天出库最后时间」(当天内,最大 23:59;缺省/非法回退 06:00)。
|
||
*
|
||
* @param {string} [timeText] 时间文本。
|
||
* @return {{hour: number, minute: number}} 小时与分钟。
|
||
*/
|
||
resolveSameDayDeadlineTime(timeText) {
|
||
return this.resolveSameDayTime(timeText, 6, 0, 23);
|
||
}
|
||
|
||
/**
|
||
* 解析「放行时间」(支持跨天,最大 47:59;27:00 = 次日 03:00;缺省/非法回退 22:00)。
|
||
*
|
||
* @param {string} [timeText] 时间文本。
|
||
* @return {{hour: number, minute: number}} 小时与分钟。
|
||
*/
|
||
resolveSameDayReleaseTime(timeText) {
|
||
return this.resolveSameDayTime(timeText, 22, 0, 47);
|
||
}
|
||
|
||
/**
|
||
* 计算北京时间「当天 00:00」对应的 UTC 时刻。
|
||
*
|
||
* 用 UTC 显式换算,不依赖 Node 进程时区(生产服务器 TZ 可能与北京时间不一致)。
|
||
*
|
||
* @param {Date} [now] 当前时刻(默认 new Date())。
|
||
* @return {Date} 北京时间当天 0 点对应的 UTC Date。
|
||
*/
|
||
buildBeijingDayStartUtc(now = new Date()) {
|
||
const beijingNowMs = now.getTime() + BEIJING_OFFSET_MS;
|
||
const beijingMidnightMs = Math.floor(beijingNowMs / DAY_MS) * DAY_MS;
|
||
return new Date(beijingMidnightMs - BEIJING_OFFSET_MS);
|
||
}
|
||
|
||
/**
|
||
* 计算「不出库当天订单」的未放行窗口(按**复核时间所在北京日**对齐,支持跨天)。
|
||
*
|
||
* 口径(第 D 天复核的订单,D 为复核时间的北京日):
|
||
* - recheck_time < D + deadline → 不受限制(豁免,照常出库);
|
||
* - recheck_time ≥ D + deadline 且 now < D + release → 未放行,不出库;
|
||
* - now ≥ D + release → 放行(照常出库)。
|
||
*
|
||
* 由于 release 最大 47:59,复核日只可能是「今天」或「昨天」,故返回至多两个窗口。
|
||
*
|
||
* @param {Date} now 当前时刻。
|
||
* @param {Object} rule 自动化出库规则(单条)。
|
||
* @return {Array<{start: number, end: number}>} 未放行窗口(UTC 毫秒区间,已合并相邻/重叠)。
|
||
*/
|
||
buildSameDayOutboundHoldWindows(now, rule) {
|
||
const safeRule = rule && typeof rule === 'object' ? rule : {};
|
||
const release = this.resolveSameDayReleaseTime(safeRule.same_day_outbound_release_time);
|
||
const deadline = this.resolveSameDayDeadlineTime(safeRule.same_day_outbound_deadline_time);
|
||
const releaseMs = (release.hour * 60 + release.minute) * 60000;
|
||
const deadlineMs = (deadline.hour * 60 + deadline.minute) * 60000;
|
||
const todayStartMs = this.buildBeijingDayStartUtc(now).getTime();
|
||
|
||
const windows = [];
|
||
for (const dayOffset of [ -1, 0 ]) {
|
||
const dayStartMs = todayStartMs + dayOffset * DAY_MS;
|
||
if (now.getTime() >= dayStartMs + releaseMs) {
|
||
continue; // 该复核日的放行时刻已到
|
||
}
|
||
windows.push({ start: dayStartMs + deadlineMs, end: dayStartMs + DAY_MS });
|
||
}
|
||
|
||
windows.sort((a, b) => a.start - b.start);
|
||
const merged = [];
|
||
for (const window of windows) {
|
||
const last = merged[merged.length - 1];
|
||
if (last && window.start <= last.end) {
|
||
last.end = Math.max(last.end, window.end);
|
||
} else {
|
||
merged.push({ ...window });
|
||
}
|
||
}
|
||
|
||
return merged;
|
||
}
|
||
|
||
/**
|
||
* 生成「不出库当天订单」对 recheck_time 的查询约束(允许集 = 未放行窗口的补集 + NULL)。
|
||
*
|
||
* 返回 null 表示当前时刻没有任何未放行窗口(即完全不限制)。
|
||
*
|
||
* @param {Date} now 当前时刻。
|
||
* @param {Object} rule 自动化出库规则(单条)。
|
||
* @return {Object|null} Sequelize 条件对象或 null。
|
||
*/
|
||
buildSameDayOutboundRecheckCondition(now, rule) {
|
||
const windows = this.buildSameDayOutboundHoldWindows(now, rule);
|
||
if (windows.length === 0) {
|
||
return null;
|
||
}
|
||
|
||
const ranges = [];
|
||
let cursor = null;
|
||
for (const window of windows) {
|
||
if (cursor === null) {
|
||
ranges.push({ [Op.lt]: new Date(window.start) });
|
||
} else if (window.start > cursor) {
|
||
ranges.push({ [Op.gte]: new Date(cursor), [Op.lt]: new Date(window.start) });
|
||
}
|
||
cursor = cursor === null ? window.end : Math.max(cursor, window.end);
|
||
}
|
||
ranges.push({ [Op.gte]: new Date(cursor) });
|
||
// recheck_time 为 null 的订单不受限制(既有口径)
|
||
ranges.push({ [Op.is]: null });
|
||
|
||
return { [Op.or]: ranges };
|
||
}
|
||
|
||
/**
|
||
* 构造「已称重」半连接条件(关联 EXISTS 子查询)。
|
||
*
|
||
* `wms_order_express.weighing_weight` 无索引且历史命中率极高,若先捞出全量称重订单ID
|
||
* 再用 `id IN (...)` 约束,会全表扫描快递大表,并把百万级订单ID 塞进 SQL 与内存。
|
||
* 改为关联 EXISTS 后由订单表驱动,快递表按 order_id 唯一索引逐行点查。
|
||
*
|
||
* @param {Object} orderModel 当前仓库的订单模型(Sequelize 模型)。
|
||
* @param {number} warehouseId 仓库ID。
|
||
* @return {Object|null} Sequelize literal 条件;模型缺失或仓库ID非法时返回 null。
|
||
*/
|
||
buildWeighExistsCondition(orderModel, warehouseId) {
|
||
const { ctx } = this;
|
||
const { OrderExpress } = ctx.model;
|
||
|
||
if (!OrderExpress) {
|
||
return null;
|
||
}
|
||
|
||
const safeWarehouseId = Number(warehouseId);
|
||
if (!Number.isInteger(safeWarehouseId) || safeWarehouseId <= 0) {
|
||
return null;
|
||
}
|
||
|
||
const orderTableRef = this.buildSqlTableRef(orderModel);
|
||
const expressTableRef = this.buildSqlTableRef(OrderExpress);
|
||
if (!orderTableRef || !expressTableRef) {
|
||
return null;
|
||
}
|
||
|
||
return Sequelize.literal(
|
||
`EXISTS (SELECT 1 FROM ${expressTableRef}`
|
||
+ ` WHERE ${expressTableRef}.\`order_id\` = ${orderTableRef}.\`id\``
|
||
+ ` AND ${expressTableRef}.\`warehouse_id\` = ${safeWarehouseId}`
|
||
+ ` AND ${expressTableRef}.\`weighing_weight\` > 0)`
|
||
);
|
||
}
|
||
|
||
/**
|
||
* 把模型解析为 SQL 中可直接引用的表名(含 schema)。
|
||
*
|
||
* @param {Object} model Sequelize 模型。
|
||
* @return {string|null} 形如 `table` 或 `schema`.`table` 的表引用;无法解析时返回 null。
|
||
*/
|
||
buildSqlTableRef(model) {
|
||
if (!model) {
|
||
return null;
|
||
}
|
||
|
||
const raw = typeof model.getTableName === 'function' ? model.getTableName() : model;
|
||
const tableName = typeof raw === 'string' ? raw : (raw && raw.tableName);
|
||
const schema = raw && typeof raw === 'object' ? raw.schema : null;
|
||
const safeTable = this.quoteSqlIdentifier(tableName);
|
||
|
||
if (!safeTable) {
|
||
return null;
|
||
}
|
||
|
||
if (schema) {
|
||
const safeSchema = this.quoteSqlIdentifier(schema);
|
||
return safeSchema ? `${safeSchema}.${safeTable}` : null;
|
||
}
|
||
|
||
return safeTable;
|
||
}
|
||
|
||
/**
|
||
* 转义 SQL 标识符(仅允许字母、数字、下划线与 $,避免拼接注入)。
|
||
*
|
||
* @param {string} name 标识符。
|
||
* @return {string|null} 反引号包裹的标识符;非法时返回 null。
|
||
*/
|
||
quoteSqlIdentifier(name) {
|
||
if (typeof name !== 'string' || !/^[A-Za-z0-9_$]+$/.test(name)) {
|
||
return null;
|
||
}
|
||
return `\`${name}\``;
|
||
}
|
||
|
||
/**
|
||
* 对指定仓库执行单次自动化出库扫描与执行。
|
||
*
|
||
* 按规则逐条扫描(任一规则命中即出库),订单ID 去重后一次性更新,
|
||
* 并对本次出库订单写入操作日志(写日志失败仅告警,不影响出库主流程)。
|
||
*
|
||
* @param {number} warehouseId 仓库ID。
|
||
* @param {Array<Object>} rules 自动化出库规则数组。
|
||
* @return {Promise<{warehouseId: number, processedCount: number, errorMessage: string|null}>} 执行结果。
|
||
*/
|
||
async processWarehouseAutoOutbound(warehouseId, rules) {
|
||
const { ctx } = this;
|
||
const result = {
|
||
warehouseId,
|
||
processedCount: 0,
|
||
errorMessage: null,
|
||
};
|
||
|
||
try {
|
||
const { orderIds, ruleIndexById } = await this.findAutoOutboundOrderIds(warehouseId, rules);
|
||
|
||
if (orderIds.length === 0) {
|
||
return result;
|
||
}
|
||
|
||
const now = new Date();
|
||
const factory = ctx.model && ctx.model.OrderDeliveryFactory;
|
||
const orderModel = await factory.getCurrentModel(warehouseId);
|
||
|
||
const [ affectedRows ] = await orderModel.update(
|
||
{
|
||
outbound_status: OUTBOUND_STATUS,
|
||
step: OUTBOUND_STEP,
|
||
status: ORDER_STATUS_FINISHED,
|
||
delivery_time: now,
|
||
updated_at: now,
|
||
},
|
||
{
|
||
where: {
|
||
id: { [Op.in]: orderIds },
|
||
warehouse_id: warehouseId,
|
||
},
|
||
}
|
||
);
|
||
|
||
result.processedCount = Number(affectedRows) || 0;
|
||
|
||
if (result.processedCount > 0) {
|
||
ctx.logger.info(
|
||
`[auto-outbound] 仓库 ${warehouseId} 自动化出库 ${result.processedCount} 条订单,订单ID: ${orderIds.join(',')}`
|
||
);
|
||
|
||
await this.writeAutoOutboundOperationLogs(warehouseId, orderIds, rules, ruleIndexById);
|
||
}
|
||
} catch (error) {
|
||
result.errorMessage = error.message;
|
||
ctx.logger.error(`[auto-outbound] 仓库 ${warehouseId} 自动化出库失败: ${error.message}`);
|
||
}
|
||
|
||
return result;
|
||
}
|
||
|
||
/**
|
||
* 写入自动出库订单操作日志(business_type=order,operation_code=ORDER_AUTO_OUTBOUND)。
|
||
*
|
||
* 日志写入失败仅告警,不影响出库主流程。
|
||
*
|
||
* @param {number} warehouseId 仓库ID。
|
||
* @param {Array<number>} orderIds 本次出库的订单ID列表。
|
||
* @param {Array<Object>} rules 自动化出库规则数组。
|
||
* @param {Map<number, number>} ruleIndexById 订单ID → 命中规则下标。
|
||
* @return {Promise<void>} 无返回值。
|
||
*/
|
||
async writeAutoOutboundOperationLogs(warehouseId, orderIds, rules, ruleIndexById) {
|
||
const { ctx } = this;
|
||
const operationLogService = ctx.service
|
||
&& ctx.service.systems
|
||
&& ctx.service.systems.operationLog;
|
||
|
||
if (!operationLogService || typeof operationLogService.createOperationLogs !== 'function') {
|
||
return;
|
||
}
|
||
|
||
const ruleList = Array.isArray(rules) ? rules : [];
|
||
const payloads = orderIds.map(orderId => {
|
||
const ruleIndex = ruleIndexById && typeof ruleIndexById.get === 'function' && ruleIndexById.has(orderId)
|
||
? ruleIndexById.get(orderId)
|
||
: -1;
|
||
const rule = ruleIndex >= 0 ? ruleList[ruleIndex] : null;
|
||
|
||
return {
|
||
businessType: 'order',
|
||
businessId: orderId,
|
||
operationCode: AUTO_OUTBOUND_OPERATION_CODE,
|
||
operator: AUTO_OUTBOUND_OPERATOR,
|
||
extras: {
|
||
warehouseId,
|
||
message: ruleIndex >= 0
|
||
? `自动出库(命中规则${ruleIndex + 1}:${this.buildAutoOutboundRuleSummary(rule)})`
|
||
: '自动出库',
|
||
},
|
||
};
|
||
});
|
||
|
||
try {
|
||
await operationLogService.createOperationLogs(payloads);
|
||
} catch (error) {
|
||
ctx.logger.warn(
|
||
`[auto-outbound] 仓库 ${warehouseId} 写入自动出库操作日志失败,不影响出库: ${error.message}`
|
||
);
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 生成规则条件摘要(用于操作日志 message)。
|
||
*
|
||
* @param {Object} rule 自动化出库规则。
|
||
* @return {string} 规则摘要文本。
|
||
*/
|
||
buildAutoOutboundRuleSummary(rule) {
|
||
const safeRule = rule && typeof rule === 'object' ? rule : {};
|
||
const conditions = [];
|
||
|
||
if (safeRule.require_pack) {
|
||
conditions.push('需已打包');
|
||
}
|
||
if (safeRule.require_weigh) {
|
||
conditions.push('需已称重');
|
||
}
|
||
if (safeRule.require_sync) {
|
||
conditions.push('需已同步');
|
||
}
|
||
if (safeRule.exclude_same_day_outbound !== false) {
|
||
conditions.push('不出库当天订单');
|
||
}
|
||
|
||
return conditions.length > 0 ? conditions.join('、') : '无附加条件';
|
||
}
|
||
|
||
/**
|
||
* 执行全局自动化出库扫描。
|
||
* 遍历所有启用了自动化出库的仓库,对每个仓库扫描并执行符合条件的订单出库。
|
||
*
|
||
* @return {Promise<{totalProcessed: number, warehouseResults: Array<Object>}>} 全局执行结果。
|
||
*/
|
||
async executeAutoOutbound() {
|
||
const { ctx } = this;
|
||
|
||
ctx.app._autoOutboundRunning = true;
|
||
|
||
try {
|
||
const warehouses = await this.getEnabledAutoOutboundWarehouses();
|
||
|
||
if (!warehouses || warehouses.length === 0) {
|
||
return { totalProcessed: 0, warehouseResults: [] };
|
||
}
|
||
|
||
let totalProcessed = 0;
|
||
const warehouseResults = [];
|
||
|
||
for (const { warehouseId, rules } of warehouses) {
|
||
const result = await this.processWarehouseAutoOutbound(warehouseId, rules);
|
||
warehouseResults.push(result);
|
||
totalProcessed += result.processedCount;
|
||
}
|
||
|
||
return { totalProcessed, warehouseResults };
|
||
} catch (error) {
|
||
ctx.logger.error(`[auto-outbound] 全局自动化出库执行失败: ${error.message}`);
|
||
return { totalProcessed: 0, warehouseResults: [] };
|
||
} finally {
|
||
ctx.app._autoOutboundRunning = false;
|
||
}
|
||
}
|
||
}
|
||
|
||
module.exports = OrderAutoOutboundService;
|