421 lines
14 KiB
JavaScript
421 lines
14 KiB
JavaScript
'use strict';
|
||
|
||
const MainService = require('../main');
|
||
const { Op } = require('sequelize');
|
||
|
||
const OUTBOUND_STATUS = 'fin';
|
||
const OUTBOUND_STEP = 4;
|
||
const ORDER_STATUS_FINISHED = 'finished';
|
||
const MAX_BATCH_SIZE = 500;
|
||
const STORAGE_STATUS_FIN = 'fin';
|
||
|
||
/**
|
||
* 订单自动化出库服务。
|
||
* 当订单满足仓库配置的自动化出库规则时,自动标记出库并完成订单。
|
||
*/
|
||
class OrderAutoOutboundService extends MainService {
|
||
/**
|
||
* 获取所有启用了自动化出库的仓库配置。
|
||
*
|
||
* @return {Promise<Array<{storeId: number, warehouseId: number, rules: Object}>>} 仓库配置列表。
|
||
*/
|
||
async getEnabledAutoOutboundWarehouses() {
|
||
const { app } = this;
|
||
const { Store, StoreWarehouse } = app.model;
|
||
|
||
if (!Store || !StoreWarehouse) {
|
||
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) {
|
||
const subjectConfig = this.normalizeSubjectConfigForAutoOutbound(store.subject_config);
|
||
const autoOutboundRules = subjectConfig && subjectConfig.auto_outbound_rules;
|
||
|
||
if (!autoOutboundRules || !autoOutboundRules.enabled) {
|
||
continue;
|
||
}
|
||
|
||
const contracts = await StoreWarehouse.findAll({
|
||
where: {
|
||
store_id: store.id,
|
||
auth_status: 2,
|
||
},
|
||
attributes: [ 'warehouse_id' ],
|
||
raw: true,
|
||
});
|
||
|
||
// 始终将 store.id 自身的仓库加入扫描(store.id 即 warehouse_id)
|
||
const scannedWarehouseIds = new Set();
|
||
result.push({
|
||
storeId: store.id,
|
||
warehouseId: store.id,
|
||
rules: autoOutboundRules,
|
||
});
|
||
scannedWarehouseIds.add(store.id);
|
||
|
||
// 追加外部合同中的仓库(去重)
|
||
for (const contract of contracts) {
|
||
const contractWarehouseId = contract.warehouse_id;
|
||
if (!scannedWarehouseIds.has(contractWarehouseId)) {
|
||
result.push({
|
||
storeId: store.id,
|
||
warehouseId: contractWarehouseId,
|
||
rules: autoOutboundRules,
|
||
});
|
||
scannedWarehouseIds.add(contractWarehouseId);
|
||
}
|
||
}
|
||
}
|
||
|
||
return result;
|
||
}
|
||
|
||
/**
|
||
* 规范化 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 {};
|
||
}
|
||
|
||
/**
|
||
* 构造自动化出库的订单查询条件。
|
||
* 根据配置规则组合各状态字段的 WHERE 条件。
|
||
*
|
||
* @param {Object} rules 自动化出库规则,包含以下可选字段:
|
||
* - {boolean} [rules.require_recheck] 是否要求已复核(recheck_status='fin')
|
||
* - {boolean} [rules.require_pack] 是否要求已打包(pack_status='fin')
|
||
* - {boolean} [rules.require_sync] 是否要求已同步(sync_status='fin')
|
||
* - {boolean} [rules.require_print] 是否要求已打印(print_status='fin')
|
||
* - {boolean} [rules.require_pick] 是否要求已拣货(pick_status='fin')
|
||
* - {boolean} [rules.exclude_same_day_outbound] 是否不出库当天复核订单(默认 true);
|
||
* 为 true 时,在到达当天放开时间(same_day_outbound_release_time,默认北京时间 22:00)前,
|
||
* 北京时间当天「允许当天出库最后时间」(same_day_outbound_deadline_time,默认 06:00)起复核(recheck_time)的订单当天不参与自动出库;
|
||
* recheck_time 早于该最后时间或为 null 的订单不受影响;
|
||
* 到达放开时间后当天复核订单恢复自动出库。
|
||
* - {string} [rules.same_day_outbound_deadline_time] 允许当天出库最后时间(HH:mm,默认 '06:00'),
|
||
* 复核时间早于该时间的订单不受「不出库当天订单」开启的影响。
|
||
* - {string} [rules.same_day_outbound_release_time] 当天放开时间(HH:mm,默认 '22:00'),
|
||
* 仅在 exclude_same_day_outbound 为 true 时生效。
|
||
* @return {Object} Sequelize where 条件对象。
|
||
*/
|
||
buildAutoOutboundWhere(rules) {
|
||
const where = {
|
||
outbound_status: 'none',
|
||
status: {
|
||
[Op.notIn]: [ 'cancel', 'error', 'finished' ],
|
||
},
|
||
storage_status: STORAGE_STATUS_FIN,
|
||
};
|
||
|
||
if (rules.require_recheck) {
|
||
where.recheck_status = 'fin';
|
||
}
|
||
|
||
// 开启「不出库当天订单」(默认开启)时:当天到达放开时间(默认北京时间 22:00)前,
|
||
// 排除当天「允许当天出库最后时间」(默认 06:00)起复核的订单(recheck_time 为 null 不排除);
|
||
// 到达放开时间后不再限制当天复核订单,当天即可出库。
|
||
// 注意:应用按 UTC 读写 DATETIME,recheck_time 存储为 UTC 时刻,边界需按北京时间(UTC+8)换算。
|
||
if (rules.exclude_same_day_outbound !== false) {
|
||
const now = new Date();
|
||
const releaseUtc = this.buildSameDayReleaseUtc(now, rules.same_day_outbound_release_time);
|
||
if (now.getTime() < releaseUtc.getTime()) {
|
||
const sameDayCutoffUtc = this.buildSameDayOutboundCutoffUtc(now, rules.same_day_outbound_deadline_time);
|
||
where.recheck_time = {
|
||
[Op.or]: [
|
||
{ [Op.lt]: sameDayCutoffUtc },
|
||
{ [Op.is]: null },
|
||
],
|
||
};
|
||
}
|
||
}
|
||
|
||
if (rules.require_pack) {
|
||
where.pack_status = 'fin';
|
||
}
|
||
|
||
if (rules.require_sync) {
|
||
where.sync_status = 'fin';
|
||
}
|
||
|
||
if (rules.require_print) {
|
||
where.print_status = 'fin';
|
||
}
|
||
|
||
if (rules.require_pick) {
|
||
where.pick_status = 'fin';
|
||
}
|
||
|
||
return where;
|
||
}
|
||
|
||
/**
|
||
* 获取仓库下满足自动化出库条件的订单ID列表。
|
||
*
|
||
* @param {number} warehouseId 仓库ID。
|
||
* @param {Object} rules 自动化出库规则。
|
||
* @param {number} [limit=MAX_BATCH_SIZE] 单次扫描上限。
|
||
* @return {Promise<Array<{id: number}>>} 订单ID列表。
|
||
*/
|
||
async findAutoOutboundOrders(warehouseId, rules, limit = MAX_BATCH_SIZE) {
|
||
const { ctx } = this;
|
||
const factory = ctx.model && ctx.model.OrderDeliveryFactory;
|
||
|
||
if (!factory || typeof factory.getCurrentModel !== 'function') {
|
||
return [];
|
||
}
|
||
|
||
const orderModel = await factory.getCurrentModel(warehouseId);
|
||
if (!orderModel) {
|
||
return [];
|
||
}
|
||
|
||
const where = this.buildAutoOutboundWhere(rules);
|
||
|
||
if (rules.require_weigh) {
|
||
const orderIdsWithWeigh = await this.findOrderIdsWithWeigh(warehouseId);
|
||
if (orderIdsWithWeigh.length === 0) {
|
||
return [];
|
||
}
|
||
where.id = { [Op.in]: orderIdsWithWeigh };
|
||
}
|
||
|
||
const orders = await orderModel.findAll({
|
||
where,
|
||
attributes: [ 'id' ],
|
||
limit,
|
||
raw: true,
|
||
});
|
||
|
||
return orders;
|
||
}
|
||
|
||
/**
|
||
* 计算「允许当天出库最后时间」边界(UTC 时刻)。
|
||
*
|
||
* 边界为北京时间当天配置时刻(默认 06:00,UTC+8):
|
||
* - recheck_time(UTC 存储)早于该边界 → 不受「不出库当天订单」开启影响,当天允许自动出库;
|
||
* - recheck_time 晚于或等于该边界 → 在到达当天放开时间前不自动出库,
|
||
* 到达放开时间(默认 22:00)后放开。
|
||
*
|
||
* 用 UTC 显式换算,不依赖 Node 进程时区(生产服务器 TZ 可能与北京时间不一致)。
|
||
*
|
||
* @param {Date} [now] 当前时刻(用于计算“今天”,默认 new Date())。
|
||
* @param {string} [timeText] 允许当天出库最后时间(HH:mm,默认 '06:00')。
|
||
* @return {Date} 北京时间当天该时刻对应的 UTC Date。
|
||
*/
|
||
buildSameDayOutboundCutoffUtc(now = new Date(), timeText) {
|
||
const DAY_MS = 24 * 3600 * 1000;
|
||
const BEIJING_OFFSET_MS = 8 * 3600 * 1000;
|
||
const { hour, minute } = this.resolveSameDayTime(timeText, 6, 0);
|
||
// 当前时刻换算为北京时刻后,取北京当天 0 点的毫秒基准
|
||
const beijingNowMs = now.getTime() + BEIJING_OFFSET_MS;
|
||
const beijingMidnightMs = Math.floor(beijingNowMs / DAY_MS) * DAY_MS;
|
||
return new Date(beijingMidnightMs + hour * 3600 * 1000 + minute * 60 * 1000 - BEIJING_OFFSET_MS);
|
||
}
|
||
|
||
/**
|
||
* 解析 HH:mm 时间配置为小时/分钟,缺省或格式非法时回退指定默认值。
|
||
*
|
||
* @param {string} [timeText] 时间文本,如 '22:00'。
|
||
* @param {number} defaultHour 默认小时。
|
||
* @param {number} defaultMinute 默认分钟。
|
||
* @return {{hour: number, minute: number}} 小时与分钟。
|
||
*/
|
||
resolveSameDayTime(timeText, defaultHour, defaultMinute) {
|
||
const text = typeof timeText === 'string' ? timeText.trim() : '';
|
||
const match = /^([01]\d|2[0-3]):([0-5]\d)$/.exec(text);
|
||
if (!match) {
|
||
return { hour: defaultHour, minute: defaultMinute };
|
||
}
|
||
return { hour: Number(match[1]), minute: Number(match[2]) };
|
||
}
|
||
|
||
/**
|
||
* 解析「当天放开时间」配置为小时/分钟(HH:mm)。
|
||
* 缺省或格式非法时回退默认 22:00。
|
||
*
|
||
* @param {string} [timeText] 时间文本,如 '22:00'。
|
||
* @return {{hour: number, minute: number}} 小时与分钟。
|
||
*/
|
||
resolveSameDayReleaseTime(timeText) {
|
||
return this.resolveSameDayTime(timeText, 22, 0);
|
||
}
|
||
|
||
/**
|
||
* 计算北京时间当天「放开时间」对应的 UTC Date。
|
||
*
|
||
* 仅在开启「不出库当天订单」时使用:当前时刻早于该边界时,
|
||
* 当天最后时间之后复核的订单不自动出库;晚于或等于该边界时放开。
|
||
*
|
||
* @param {Date} [now] 当前时刻(默认 new Date())。
|
||
* @param {string} [timeText] 放开时间(HH:mm,默认 22:00)。
|
||
* @return {Date} 北京时间当天放开时间对应的 UTC Date。
|
||
*/
|
||
buildSameDayReleaseUtc(now = new Date(), timeText) {
|
||
const DAY_MS = 24 * 3600 * 1000;
|
||
const BEIJING_OFFSET_MS = 8 * 3600 * 1000;
|
||
const { hour, minute } = this.resolveSameDayReleaseTime(timeText);
|
||
const beijingNowMs = now.getTime() + BEIJING_OFFSET_MS;
|
||
const beijingMidnightMs = Math.floor(beijingNowMs / DAY_MS) * DAY_MS;
|
||
return new Date(beijingMidnightMs + hour * 3600 * 1000 + minute * 60 * 1000 - BEIJING_OFFSET_MS);
|
||
}
|
||
|
||
/**
|
||
* 查找有称重记录的订单ID列表。
|
||
*
|
||
* @param {number} warehouseId 仓库ID。
|
||
* @return {Promise<Array<number>>} 订单ID列表。
|
||
*/
|
||
async findOrderIdsWithWeigh(warehouseId) {
|
||
const { ctx } = this;
|
||
const { OrderExpress } = ctx.model;
|
||
|
||
if (!OrderExpress) {
|
||
return [];
|
||
}
|
||
|
||
const rows = await OrderExpress.findAll({
|
||
where: {
|
||
warehouse_id: warehouseId,
|
||
weighing_weight: { [Op.gt]: 0 },
|
||
},
|
||
attributes: [ 'order_id' ],
|
||
raw: true,
|
||
});
|
||
|
||
return rows
|
||
.map(row => Number(row.order_id))
|
||
.filter(id => Number.isFinite(id) && id > 0);
|
||
}
|
||
|
||
/**
|
||
* 对指定仓库执行单次自动化出库扫描与执行。
|
||
*
|
||
* @param {number} warehouseId 仓库ID。
|
||
* @param {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 orders = await this.findAutoOutboundOrders(warehouseId, rules);
|
||
|
||
if (!orders || orders.length === 0) {
|
||
return result;
|
||
}
|
||
|
||
const orderIds = orders.map(order => Number(order.id)).filter(Boolean);
|
||
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(',')}`
|
||
);
|
||
}
|
||
} catch (error) {
|
||
result.errorMessage = error.message;
|
||
ctx.logger.error(`[auto-outbound] 仓库 ${warehouseId} 自动化出库失败: ${error.message}`);
|
||
}
|
||
|
||
return result;
|
||
}
|
||
|
||
/**
|
||
* 执行全局自动化出库扫描。
|
||
* 遍历所有启用了自动化出库的仓库,对每个仓库扫描并执行符合条件的订单出库。
|
||
*
|
||
* @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;
|