- pick.js: 修复拣货车绑定逻辑,禁止已绑定任务直接换车 - wave.js: 修复波次拣货车查询(移除 current_task_id) - recheckOrder.js: 新增 batchQuickRecheckByWave 按波次批量快速复核 - order_packing.js: 时间字段统一格式化输出 - order_auto_outbound.js: 修复仓库去重逻辑
323 lines
8.8 KiB
JavaScript
323 lines
8.8 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')
|
||
* @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';
|
||
}
|
||
|
||
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;
|
||
}
|
||
|
||
/**
|
||
* 查找有称重记录的订单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;
|