WMS_MAIN/app/service/systems/delivery_order.js

2709 lines
99 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

'use strict';
const Service = require('egg').Service;
const { normalizeWarehouseShardId } = require('../../lib/warehouse_shard_guard');
const { isLockedOrderStatus } = require('../../lib/lock_guard');
const DELIVERY_ORDER_STEP = Object.freeze({
PENDING_REVIEW: 0,
APPROVED: 1,
PROCESSING: 2,
REJECTED_OR_EXCEPTION: 3,
OUTBOUND_OR_DELIVERING: 4,
COMPLETED: 5,
CLOSED: 9,
});
const DEFAULT_STORE_SUBJECT_CONFIG = Object.freeze({
max_notice_webhook_count: 5,
default_express_code: 'STO',
default_platform_code: 'TB',
});
const ORDER_OPERATION_CODES = Object.freeze({
CREATE: 'ORDER_CREATE',
PLATFORM_FALLBACK: 'ORDER_PLATFORM_FALLBACK',
EXPRESS_FALLBACK: 'ORDER_EXPRESS_FALLBACK',
EXPRESS_POLICY_MATCH: 'ORDER_EXPRESS_POLICY_MATCH',
});
const STORE_SUBJECT_CONFIG_CACHE_TTL_SECONDS = 600;
class DeliveryOrderService extends Service {
getStoreSubjectConfigCacheKey(storeId) {
return `delivery_order:store:${Number(storeId || 0)}:subject_config`;
}
normalizeStoreSubjectConfig(rawValue) {
const storeModel = (this.app.model && this.app.model.Store) || (this.ctx.model && this.ctx.model.Store);
if (storeModel && typeof storeModel.normalizeSubjectConfig === 'function') {
return storeModel.normalizeSubjectConfig(rawValue);
}
return {
...DEFAULT_STORE_SUBJECT_CONFIG,
...(rawValue && typeof rawValue === 'object' && !Array.isArray(rawValue) ? rawValue : {}),
};
}
async getStoreSubjectConfig(storeId) {
const normalizedStoreId = Number(storeId || 0);
if (!Number.isFinite(normalizedStoreId) || normalizedStoreId <= 0) {
return this.normalizeStoreSubjectConfig(null);
}
const cacheKey = this.getStoreSubjectConfigCacheKey(normalizedStoreId);
if (this.app && typeof this.app.getCacheAsync === 'function') {
try {
const cachedValue = await this.app.getCacheAsync(cacheKey);
if (cachedValue && typeof cachedValue === 'object') {
return this.normalizeStoreSubjectConfig(cachedValue);
}
} catch (error) {
this.ctx.logger.warn('[DeliveryOrderService.getStoreSubjectConfig] read cache failed: %s', error.message);
}
}
const storeModel = (this.app.model && this.app.model.Store) || (this.ctx.model && this.ctx.model.Store);
if (!storeModel || typeof storeModel.findByPk !== 'function') {
return this.normalizeStoreSubjectConfig(null);
}
try {
const store = await storeModel.findByPk(normalizedStoreId, {
attributes: [ 'id', 'subject_config' ],
});
const normalizedConfig = this.normalizeStoreSubjectConfig(store && store.subject_config);
if (this.app && typeof this.app.setCacheAsync === 'function') {
await this.app.setCacheAsync(cacheKey, normalizedConfig, STORE_SUBJECT_CONFIG_CACHE_TTL_SECONDS);
}
return normalizedConfig;
} catch (error) {
this.ctx.logger.warn('[DeliveryOrderService.getStoreSubjectConfig] load subject_config failed: %s', error.message);
return this.normalizeStoreSubjectConfig(null);
}
}
findCodeOption(list, code) {
const normalizedCode = String(code || '').trim();
if (!normalizedCode || !Array.isArray(list)) {
return null;
}
return list.find(item => item && String(item.code || item.value || '').trim() === normalizedCode) || null;
}
getOptionName(option) {
if (!option || typeof option !== 'object') {
return '';
}
return String(option.name || option.label || option.code || option.value || '').trim();
}
/**
* 记录待写入的订单操作日志项。
*
* @param {Array<Object>} operationLogs 待写入的日志数组。
* @param {string} operationCode 操作编码。
* @param {string} message 日志内容。
* @param {Object} [options={}] 记录选项。
* @param {boolean} [options.prepend=false] 是否插入到数组首位。
* @return {void}
*/
appendOrderOperationLog(operationLogs, operationCode, message, options = {}) {
if (!Array.isArray(operationLogs)) {
return;
}
const logItem = {
operationCode,
message,
};
if (options && options.prepend) {
operationLogs.unshift(logItem);
return;
}
operationLogs.push(logItem);
}
/**
* 获取订单日志使用的操作人信息。
*
* 取值优先级:employees_id/employees_name -> operator_id/operator_name -> id/real_name/name。
*
* @return {{ id: string|null, name: string }} 操作人信息。
*/
getOrderLogOperator() {
const { ctx } = this;
const stateUser = ctx && ctx.state && typeof ctx.state.user === 'object' && ctx.state.user
? ctx.state.user
: null;
const ctxUser = ctx && ctx.user && typeof ctx.user === 'object'
? ctx.user
: null;
const operatorSource = stateUser || ctxUser || {};
const rawOperatorId = operatorSource.employees_id ?? operatorSource.operator_id ?? operatorSource.id;
const rawOperatorName = operatorSource.employees_name
?? operatorSource.operator_name
?? operatorSource.real_name
?? operatorSource.name;
const operatorId = rawOperatorId === undefined || rawOperatorId === null
? null
: String(rawOperatorId).trim() || null;
const operatorName = rawOperatorName === undefined || rawOperatorName === null
? 'system'
: String(rawOperatorName).trim() || 'system';
return {
id: operatorId,
name: operatorName,
};
}
/**
* 获取订单日志使用的仓库ID。
*
* 取值优先级:显式传入参数 -> this.store.id -> ctx.user.warehouse_id -> ctx.user.store_id。
*
* @param {number|string|null} [preferredWarehouseId=null] 优先使用的仓库ID。
* @return {number|string|null} 归一化后的仓库ID。
*/
getOrderLogWarehouseId(preferredWarehouseId = null) {
const { ctx } = this;
const candidates = [
preferredWarehouseId,
this.store && this.store.id,
ctx && ctx.user && ctx.user.warehouse_id,
ctx && ctx.user && ctx.user.store_id,
];
for (const candidate of candidates) {
if (candidate === undefined || candidate === null || candidate === '') {
continue;
}
return candidate;
}
return null;
}
/**
* 将订单操作日志写入数据库,优先批量写入。
*
* @param {Array<Object>} operationLogs 待写入的日志数组。
* @param {number|string} orderId 订单ID。
* @param {Object} [options={}] 写入选项。
* @param {number|string} [options.warehouseId] 订单所属仓库ID。
* @param {Object} [options.transaction] 事务对象(可选)。
* @return {Promise<void>} 无返回值。
*/
async flushOrderOperationLogs(operationLogs, orderId, options = {}) {
const { ctx } = this;
const operationLogService = ctx.service && ctx.service.systems && ctx.service.systems.operationLog;
const requestOptions = options && typeof options === 'object' ? options : {};
let operator = this.getOrderLogOperator();
const warehouseId = this.getOrderLogWarehouseId(requestOptions.warehouseId ?? requestOptions.warehouse_id);
// 根据创建渠道覆盖操作人名称
const createChannel = String(requestOptions.createChannel ?? requestOptions.create_channel ?? '').trim().toUpperCase();
if (createChannel === 'QM') {
operator = { id: null, name: '奇门' };
} else if (createChannel === 'API') {
operator = { id: null, name: 'API' };
}
if (!Array.isArray(operationLogs) || operationLogs.length === 0) {
return;
}
if (!operationLogService || typeof operationLogService.createOperationLogs !== 'function') {
ctx.logger.warn('[DeliveryOrderService.flushOrderOperationLogs] operationLog service unavailable', {
orderId,
logs: operationLogs.length,
});
return;
}
const payloads = operationLogs.map(logItem => ({
businessType: 'order',
businessId: orderId,
operationCode: logItem.operationCode,
operator,
extras: {
warehouseId,
message: logItem.message,
},
transaction: requestOptions.transaction,
}));
try {
const results = await operationLogService.createOperationLogs(payloads, {
transaction: requestOptions.transaction,
});
for (let index = 0; index < payloads.length; index += 1) {
if (results[index]) {
continue;
}
const logItem = operationLogs[index] || {};
ctx.logger.warn('[DeliveryOrderService.flushOrderOperationLogs] 写入操作日志失败,不影响业务', {
orderId,
operationCode: logItem.operationCode,
message: logItem.message,
});
}
} catch (error) {
ctx.logger.warn('[DeliveryOrderService.flushOrderOperationLogs] 批量写入操作日志异常,不影响业务', {
orderId,
error: error.message,
});
}
}
/**
* 按平台码解析平台列表项,优先基础平台,再匹配平台设置。
*
* @param {Array<Object>} platformList 平台列表。
* @param {string} platformCode 平台编码。
* @return {Object|null} 匹配到的平台项。
*/
findPlatformOptionByCode(platformList, platformCode) {
const normalizedCode = String(platformCode || '').trim();
if (!normalizedCode || !Array.isArray(platformList)) {
return null;
}
const basePlatform = platformList.find(item => item
&& !item.is_system_setting
&& String(item.code || item.value || '').trim() === normalizedCode) || null;
if (basePlatform) {
return basePlatform;
}
return platformList.find(item => item
&& item.is_system_setting
&& String(item.code || item.value || '').trim() === normalizedCode) || null;
}
/**
* 获取平台快照里的系统平台码。
*
* @param {Object} option 平台项。
* @param {string} fallbackCode 兜底编码。
* @return {string} 系统平台码。
*/
getPlatformSnapshotCode(option, fallbackCode = '') {
return String(option && (option.platform_code || option.code || option.value || fallbackCode) || '').trim();
}
/**
* 获取平台快照里的系统平台名称。
*
* @param {Object} option 平台项。
* @return {string} 系统平台名称。
*/
getPlatformSnapshotName(option) {
if (!option || typeof option !== 'object') {
return '';
}
return String(option.platform_name || option.name || option.label || option.code || option.value || '').trim();
}
/**
* 解析平台快照。
*
* 优先级:
* 1. 先匹配平台列表里的基础平台项;
* 2. 再匹配平台列表里的系统设置项;
* 3. 兜底:合约 policy_config.default_platform_code。
*
* @param {string} sourcePlatformCode 外部平台编码。
* @param {Object} storeSubjectConfig 合约 policy_config。
* @param {Object} [policyConfig={}] 合约策略配置。
* @param {Object} [info={}] 上下文信息。
* @param {Array<Object>} [operationLogs=[]] 待写入的操作日志数组。
* @return {Promise<Object>} 平台快照。
*/
async resolvePlatformSnapshot(sourcePlatformCode, storeSubjectConfig, policyConfig = {}, info = {}, operationLogs = []) {
const platformList = await this.ctx.service.systems.platform.getPlatformList(
false,
false,
info.warehouseId
);
const externalCode = String(sourcePlatformCode || '').trim();
const matchedPlatform = this.findPlatformOptionByCode(platformList, externalCode);
if (matchedPlatform) {
return {
sysPlatformCode: this.getPlatformSnapshotCode(matchedPlatform, externalCode),
sysPlatformName: this.getPlatformSnapshotName(matchedPlatform),
};
}
this.ctx.logger.warn('[DeliveryOrderService.prepareOrderData] platform code not found in platform service list', {
deliveryOrderCode: info.deliveryOrderCode,
warehouseId: info.warehouseId,
storeId: info.storeId,
sourcePlatformCode: externalCode,
});
// 兜底优先级:合约 policy_config
const policyDefaultCode = String(policyConfig && policyConfig.default_platform_code || '').trim();
const ownerDefaultCode = String(storeSubjectConfig && storeSubjectConfig.default_platform_code || '').trim();
const defaultCode = policyDefaultCode || ownerDefaultCode;
const fallbackPlatform = defaultCode ? this.findPlatformOptionByCode(platformList, defaultCode) : null;
const fallbackPlatformName = this.getPlatformSnapshotName(fallbackPlatform) || defaultCode;
if (defaultCode) {
const fallbackSource = policyDefaultCode ? 'policy_config' : 'subject_config';
this.appendOrderOperationLog(
operationLogs,
ORDER_OPERATION_CODES.PLATFORM_FALLBACK,
`平台编码${externalCode}匹配不到平台,已转为默认平台:${fallbackPlatformName}(来源:${fallbackSource})`
);
if (fallbackPlatform) {
this.ctx.logger.warn('[DeliveryOrderService.prepareOrderData] platform code fallback to default', {
deliveryOrderCode: info.deliveryOrderCode,
warehouseId: info.warehouseId,
storeId: info.storeId,
sourcePlatformCode: externalCode,
defaultPlatformCode: defaultCode,
fallbackSource,
});
return {
sysPlatformCode: this.getPlatformSnapshotCode(fallbackPlatform, defaultCode),
sysPlatformName: fallbackPlatformName,
};
}
}
this.ctx.logger.warn('[DeliveryOrderService.prepareOrderData] platform default not found in platform service list', {
deliveryOrderCode: info.deliveryOrderCode,
warehouseId: info.warehouseId,
storeId: info.storeId,
sourcePlatformCode: externalCode,
defaultPlatformCode: defaultCode,
});
return {
sysPlatformCode: defaultCode || externalCode,
sysPlatformName: fallbackPlatformName || '',
};
}
/**
* 通过快递设置表解析系统快递编码。
*
* 说明:wms_express_setting 以 `code` 作为匹配键,以 `express_code` 作为系统快递编码。
* 由于该表带有 `warehouse_id` 作用域,这里优先按 `warehouse_id + code` 进行限定查询,
* 命中后直接返回对应的系统快递编码。
*
* @param {string} logisticsCode 外部快递编码。
* @param {number|string} warehouseId 仓库ID。
* @return {Promise<string>} 系统快递编码,未命中时返回空字符串。
*/
async resolveExpressCodeFromSetting(logisticsCode, warehouseId) {
const expressSetting = await this.resolveExpressSettingSnapshot(logisticsCode, warehouseId);
return String(expressSetting && expressSetting.expressCode || '').trim();
}
/**
* 通过快递设置表读取快递映射快照。
*
* @param {string} logisticsCode 外部快递编码。
* @param {number|string} warehouseId 仓库ID。
* @return {Promise<Object|null>} 命中的快递设置快照,未命中返回 null。
*/
async resolveExpressSettingSnapshot(logisticsCode, warehouseId) {
const normalizedLogisticsCode = String(logisticsCode || '').trim();
if (!normalizedLogisticsCode) {
return null;
}
const expressSettingModel = this.ctx.model && this.ctx.model.ExpressSetting;
if (!expressSettingModel || typeof expressSettingModel.findOne !== 'function') {
return null;
}
const where = {
code: normalizedLogisticsCode,
};
const normalizedWarehouseId = Number(warehouseId || 0);
if (Number.isFinite(normalizedWarehouseId) && normalizedWarehouseId > 0) {
where.warehouse_id = normalizedWarehouseId;
}
const expressSetting = await expressSettingModel.findOne({
attributes: [ 'code', 'name', 'express_code' ],
where,
raw: true,
});
if (!expressSetting) {
return null;
}
return {
code: String(expressSetting.code || normalizedLogisticsCode).trim(),
name: String(expressSetting.name || '').trim(),
expressCode: String(expressSetting.express_code || '').trim(),
};
}
/**
* 解析是否启用外部快递编码。
*
* 优先级:显式值 -> policy_config,均未提供时默认关闭。
*
* @param {Object} storeSubjectConfig 合约 policy_config(与 policyConfig 同源)。
* @param {Object} policyConfig 合约策略配置。
* @param {any} explicitValue 显式指定值。
* @return {boolean} 是否启用外部快递编码。
*/
resolveEnableExternalExpressCode(storeSubjectConfig, policyConfig = {}, explicitValue = undefined) {
if (explicitValue !== undefined) {
return this.normalizePolicyFlag(explicitValue);
}
if (policyConfig && Object.prototype.hasOwnProperty.call(policyConfig, 'enable_external_express_code')) {
return this.normalizePolicyFlag(policyConfig.enable_external_express_code);
}
if (storeSubjectConfig && Object.prototype.hasOwnProperty.call(storeSubjectConfig, 'enable_external_express_code')) {
return this.normalizePolicyFlag(storeSubjectConfig.enable_external_express_code);
}
return false;
}
/**
* 解析订单快递快照。
*
* 默认快递编码统一从合约 policy_config 读取。
*
* 分支路由:
* 1. 先读取是否启用外部快递编码开关;
* 2. 开关关闭时,直接使用合约默认快递回填四个快递字段;
* 3. 开关开启时,先匹配 wms_express_setting,再匹配 wms_express,最后回退默认快递。
*
* @param {string} logisticsCode 外部快递编码。
* @param {Object} storeSubjectConfig 合约 policy_config。
* @param {Object} [info={}] 上下文信息,可含 policyConfig / enableExternalExpressCode / warehouseId。
* @param {Array<Object>} [operationLogs=[]] 待写入的操作日志数组。
* @return {Promise<Object>} 快递快照。
*/
async resolveExpressSnapshot(logisticsCode, storeSubjectConfig, info = {}, operationLogs = []) {
const expressList = await this.ctx.service.systems.express.getExpressList();
const externalCode = String(logisticsCode || '').trim();
// 默认快递编码统一从合约 policy_config 读取
const policyConfig = info && info.policyConfig && typeof info.policyConfig === 'object'
? info.policyConfig
: {};
const contractConfig = storeSubjectConfig && typeof storeSubjectConfig === 'object'
? storeSubjectConfig
: {};
const defaultCode = String(
contractConfig.default_express_code
|| policyConfig.default_express_code
|| ''
).trim();
const fallbackExpress = this.findCodeOption(expressList, defaultCode)
|| this.findCodeOption(expressList, DEFAULT_STORE_SUBJECT_CONFIG.default_express_code);
const fallbackLogisticsCode = String(
fallbackExpress && (fallbackExpress.code || fallbackExpress.value || fallbackExpress.express_code || defaultCode || DEFAULT_STORE_SUBJECT_CONFIG.default_express_code)
|| defaultCode
|| DEFAULT_STORE_SUBJECT_CONFIG.default_express_code
).trim();
const fallbackLogisticsName = this.getOptionName(fallbackExpress);
const explicitEnableExternalExpressCode = info && Object.prototype.hasOwnProperty.call(info, 'enableExternalExpressCode')
? info.enableExternalExpressCode
: undefined;
const isEnableExternalExpressCode = this.resolveEnableExternalExpressCode(
storeSubjectConfig,
policyConfig,
explicitEnableExternalExpressCode
);
this.ctx.logger.info('[DeliveryOrderService.resolveExpressSnapshot] 快递解析开始', {
deliveryOrderCode: info.deliveryOrderCode,
warehouseId: info.warehouseId,
storeId: info.storeId,
logisticsCode: externalCode,
enableExternalExpressCode: isEnableExternalExpressCode,
defaultExpressCode: defaultCode,
});
if (!isEnableExternalExpressCode) {
this.ctx.logger.info('[DeliveryOrderService.resolveExpressSnapshot] 未启用外部快递编码,直接使用默认快递', {
deliveryOrderCode: info.deliveryOrderCode,
logisticsCode: externalCode,
matched: false,
fallbackLogisticsCode,
fallbackLogisticsName,
});
return {
logisticsCode: fallbackLogisticsCode,
logisticsName: fallbackLogisticsName,
sysLogisticsCode: fallbackLogisticsCode,
sysLogisticsName: fallbackLogisticsName,
weightType: 0,
};
}
const expressSetting = await this.resolveExpressSettingSnapshot(externalCode, info.warehouseId);
if (expressSetting) {
const matchedSysExpress = this.findCodeOption(expressList, expressSetting.expressCode);
const matchedSysLogisticsCode = String(
matchedSysExpress && (matchedSysExpress.code || matchedSysExpress.value || matchedSysExpress.express_code || expressSetting.expressCode)
|| expressSetting.expressCode
|| ''
).trim();
const matchedSysLogisticsName = this.getOptionName(matchedSysExpress);
this.ctx.logger.info('[DeliveryOrderService.resolveExpressSnapshot] 外部快递编码命中 wms_express_setting 映射', {
deliveryOrderCode: info.deliveryOrderCode,
logisticsCode: externalCode,
matched: true,
source: 'wms_express_setting',
mappedLogisticsCode: String(expressSetting.code || externalCode).trim(),
mappedLogisticsName: String(expressSetting.name || '').trim(),
sysLogisticsCode: matchedSysLogisticsCode,
sysLogisticsName: matchedSysLogisticsName,
});
return {
logisticsCode: String(expressSetting.code || externalCode).trim(),
logisticsName: String(expressSetting.name || '').trim(),
sysLogisticsCode: matchedSysLogisticsCode,
sysLogisticsName: matchedSysLogisticsName,
weightType: 0,
};
}
const matchedExpress = this.findCodeOption(expressList, externalCode);
if (matchedExpress) {
const matchedLogisticsCode = String(
matchedExpress.code || matchedExpress.value || matchedExpress.express_code || externalCode
).trim();
const matchedLogisticsName = this.getOptionName(matchedExpress);
this.ctx.logger.info('[DeliveryOrderService.resolveExpressSnapshot] 外部快递编码命中系统快递列表', {
deliveryOrderCode: info.deliveryOrderCode,
logisticsCode: externalCode,
matched: true,
source: 'wms_express',
matchedLogisticsCode,
matchedLogisticsName,
});
return {
logisticsCode: matchedLogisticsCode,
logisticsName: matchedLogisticsName,
sysLogisticsCode: matchedLogisticsCode,
sysLogisticsName: matchedLogisticsName,
weightType: 0,
};
}
if (fallbackExpress) {
this.ctx.logger.warn('[DeliveryOrderService.resolveExpressSnapshot] 快递编码未匹配到任何快递,兜底为默认快递', {
deliveryOrderCode: info.deliveryOrderCode,
warehouseId: info.warehouseId,
storeId: info.storeId,
logisticsCode: externalCode,
matched: false,
fallbackLogisticsCode,
fallbackLogisticsName,
defaultExpressCode: defaultCode,
});
this.appendOrderOperationLog(
operationLogs,
ORDER_OPERATION_CODES.EXPRESS_FALLBACK,
`快递编码${externalCode}匹配不到快递,已转为默认快递:${fallbackLogisticsName || fallbackLogisticsCode}`
);
return {
logisticsCode: fallbackLogisticsCode,
logisticsName: fallbackLogisticsName,
sysLogisticsCode: fallbackLogisticsCode,
sysLogisticsName: fallbackLogisticsName,
weightType: 0,
};
}
this.ctx.logger.warn('[DeliveryOrderService.resolveExpressSnapshot] 默认快递不在快递列表中,使用全局兜底快递', {
deliveryOrderCode: info.deliveryOrderCode,
warehouseId: info.warehouseId,
storeId: info.storeId,
logisticsCode: externalCode,
matched: false,
fallbackLogisticsCode,
fallbackLogisticsName,
defaultExpressCode: defaultCode,
});
this.appendOrderOperationLog(
operationLogs,
ORDER_OPERATION_CODES.EXPRESS_FALLBACK,
`快递编码${externalCode}匹配不到快递,兜底快递:${fallbackLogisticsName || fallbackLogisticsCode}`
);
return {
logisticsCode: fallbackLogisticsCode,
logisticsName: fallbackLogisticsName,
sysLogisticsCode: fallbackLogisticsCode,
sysLogisticsName: fallbackLogisticsName,
weightType: 0,
};
}
/**
* 创建发货单。
*
* @param {Object} data 奇门/系统订单入参。
* @param {Object} info 当前仓库与货主上下文。
* @param {string} [createChannel=''] 订单创建渠道标识。
* @return {Promise<Object>} 创建结果。
*/
async addOrder(data, info, createChannel = '') {
const { ctx } = this;
let warehouseIdStr;
try {
warehouseIdStr = normalizeWarehouseShardId(info.warehouseId);
} catch (e) {
return {
success: false,
message: `订单创建失败: ${e.message}`,
data: null,
};
}
info = { ...info, warehouseId: warehouseIdStr };
const DeliveryModel = await ctx.model.OrderDeliveryFactory.getCurrentModel(warehouseIdStr);
const { deliveryOrder, orderLines } = data.request;
// 请求级 extendProps,携带 ewaybill_order_code 等关键字段
const requestExtendProps = (data.request && data.request.extendProps && Object.keys(data.request.extendProps).length > 0)
? data.request.extendProps
: undefined;
const normalizedCreateChannel = String(
createChannel
|| deliveryOrder.createChannel
|| deliveryOrder.create_channel
|| 'MANUAL'
).trim().toUpperCase() || 'MANUAL';
// 订单 id 序列表初始化可能执行 DDL(隐式提交),必须在事务外先完成
try {
await ctx.model.OrderDeliveryFactory.ensureLocationSequenceTable(warehouseIdStr);
} catch (error) {
// 初始化失败不降级:后续发号会直接失败并回滚建单,绝不让分表自增介入发号
ctx.logger.warn('[DeliveryOrderService.addOrder] 序列表初始化失败,本次建单将失败:', error.message);
}
// 单次建单执行体:重试时复用,事务随每次尝试重新开启
const createOnce = async operationLogs => {
// 开启事务
const transaction = await ctx.model.transaction();
try {
if (!info.storeId) {
throw new Error('非法参数');
}
if (!deliveryOrder || !deliveryOrder.deliveryOrderCode) {
throw new Error('订单信息不完整');
}
// 检查订单是否已存在(根据唯一索引)
const existingOrder = await DeliveryModel.findOne({
where: {
delivery_order_code: deliveryOrder.deliveryOrderCode,
store_id: info.storeId,
warehouse_id: info.warehouseId,
},
attributes: [ 'id' ],
transaction,
});
if (existingOrder) {
await transaction.rollback();
return {
success: true,
message: '订单已存在',
data: { deliveryOrderId: existingOrder.id },
};
}
// 准备订单数据
const step = await this.resolveOrderStep(info, transaction);
const orderData = await this.prepareOrderData(
deliveryOrder,
info,
normalizedCreateChannel,
step,
operationLogs,
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,
orderId,
info,
transaction
);
} else {
throw new Error('[订单无明细]');
}
// 更新订单统计信息 - 直接使用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 开启时仅"纯货主维度"策略参与漏斗,命中后覆盖外部快递匹配结果;
// 关闭时全维度策略参与,沿用原有逻辑
try {
const funnelPolicyConfig = await this.getStoreWarehousePolicyConfig(info.storeId, info.warehouseId);
const enableExternalExpressCode = this.resolveEnableExternalExpressCode(funnelPolicyConfig, funnelPolicyConfig);
const receiverInfo = deliveryOrder.receiverInfo;
const shopNick = deliveryOrder.shopNick;
// 外部编码开启:仅需货主ID即可参与漏斗(只匹配纯货主维度策略);
// 外部编码关闭:需 shopNick 或收货省/市信息
const hasEnoughData = enableExternalExpressCode
? Boolean(info.storeId)
: Boolean(shopNick || (receiverInfo && (receiverInfo.province || receiverInfo.city)));
if (hasEnoughData) {
const address = [
receiverInfo?.province || '',
receiverInfo?.city || '',
receiverInfo?.area || '',
receiverInfo?.town || '',
receiverInfo?.detail_address || '',
].join('').trim();
const matchResult = await ctx.service.systems.expressPolicy.matchPolicy(
info.warehouseId,
{
storeId: info.storeId,
customShopName: shopNick || '',
address: address || '',
weight: itemsInfo.total_weight || null,
// 从订单商品聚合的违禁品类型ID(StockWarehouse.prohibited_id 去重)
prohibitedTypeIds: itemsInfo && Array.isArray(itemsInfo.prohibited_type_ids)
? itemsInfo.prohibited_type_ids
: null,
},
{
// 启用外部编码时仅匹配纯货主维度策略,命中后覆盖外部快递映射结果
onlyStoreDimension: enableExternalExpressCode,
}
);
if (matchResult && matchResult.expressCode) {
const expressList = await ctx.service.systems.express.getExpressList();
const matchedExpress = expressList.find(
item => item && String(item.code || item.value || '').trim() === String(matchResult.expressCode).trim()
);
let logisticsCode;
let logisticsName;
let sysLogisticsCode;
let sysLogisticsName;
if (matchedExpress) {
if (matchedExpress.is_system_setting) {
// 自定义映射:sys 写映射的系统快递,logistics 写自定义编码
sysLogisticsCode = String(matchedExpress.express_code || '').trim();
const sysItem = expressList.find(
item => item && !item.is_system_setting && String(item.code || item.value || '').trim() === sysLogisticsCode
);
sysLogisticsName = sysItem ? String(sysItem.name || sysItem.label || sysLogisticsCode).trim() : sysLogisticsCode;
logisticsCode = String(matchedExpress.code || matchedExpress.value || matchResult.expressCode).trim();
logisticsName = String(matchedExpress.alias || matchedExpress.name || logisticsCode).trim();
} else {
// 系统快递:4 字段一致
logisticsCode = String(matchedExpress.code || matchedExpress.value || matchResult.expressCode).trim();
logisticsName = String(matchedExpress.name || matchedExpress.label || logisticsCode).trim();
sysLogisticsCode = logisticsCode;
sysLogisticsName = logisticsName;
}
} else {
// 未在列表中,fallback
logisticsCode = String(matchResult.expressCode).trim();
logisticsName = logisticsCode;
sysLogisticsCode = logisticsCode;
sysLogisticsName = logisticsCode;
}
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(
operationLogs,
ORDER_OPERATION_CODES.EXPRESS_POLICY_MATCH,
`快递策略命中: ${matchResult.policyName || '未知'}(${matchResult.policyId || '?'}) → ${sysLogisticsName || sysLogisticsCode}`
);
ctx.logger.info('[ExpressPolicyMatch] 策略命中(延迟匹配)', {
orderId,
orderCode: deliveryOrder.deliveryOrderCode,
logisticsCode,
sysLogisticsCode,
weightType: matchResult.weightType,
policyName: matchResult.policyName,
policyId: matchResult.policyId,
totalWeight: itemsInfo.total_weight,
});
} else if (hasEnoughData) {
// 策略未命中:记快递降级日志(取已落库的初始快递值)
const fallbackCode = orderData.sys_logistics_code || orderData.logistics_code;
const fallbackName = orderData.sys_logistics_name || orderData.logistics_name;
this.appendOrderOperationLog(
operationLogs,
ORDER_OPERATION_CODES.EXPRESS_FALLBACK,
enableExternalExpressCode
? `未命中货主快递策略,保留外部快递: ${fallbackName || fallbackCode}`
: `未命中快递策略,使用默认快递: ${fallbackName || fallbackCode}`
);
}
}
} catch (policyErr) {
ctx.logger.warn('[ExpressPolicyMatch] 策略匹配异常,跳过', {
orderId,
error: policyErr.message,
});
}
await DeliveryModel.update(
stats,
{
where: { id: orderId },
transaction,
}
);
// 记录详细日志
ctx.logger.info('[订单统计信息已更新]', {
orderId,
orderCode: deliveryOrder.deliveryOrderCode,
stats: {
items_count: stats.items_count,
items_total: stats.items_total,
items_weight: stats.items_weight,
items_hash_preview: stats.items_hash?.substring(0, 8) + '...',
items_crc: stats.items_crc,
},
});
}
await transaction.commit();
await this.flushOrderOperationLogs(operationLogs, orderId, {
warehouseId: info.warehouseId,
createChannel: normalizedCreateChannel,
});
// 异步处理订单后续流程
this.asyncProcessOrderCreated(orderId, info, normalizedCreateChannel).catch(error => {
ctx.logger.warn(`[DeliveryOrderService.addOrder] asyncProcessOrderCreated failed: ${error.message}`, {
orderId,
error: error.message,
});
});
return {
success: true,
message: '订单创建成功',
data: {
orderId,
step,
stats: itemsInfo ? {
items_count: itemsInfo.stock_count,
items_total: itemsInfo.item_total_count,
items_weight: itemsInfo.total_weight,
source_order_codes: (itemsInfo.stats && itemsInfo.stats.source_order_codes) || [],
} : null,
},
};
} catch (error) {
console.error('创建订单失败:', error);
// 回滚事务(安全处理,防止事务已结束导致二次回滚异常)
await transaction.rollback().catch(rollbackErr => {
console.error('回滚事务失败:', rollbackErr.message);
});
throw error;
}
};
// 主键冲突(分表自增水位与已有数据重叠)允许修复水位后重试一次
for (let attempt = 1; attempt <= 2; attempt++) {
const operationLogs = [];
try {
return await createOnce(operationLogs);
} catch (error) {
if (this.isPrimaryKeyDuplicate(error) && attempt === 1) {
try {
const factory = ctx.model.OrderDeliveryFactory;
const tableName = factory.generateTableName(warehouseIdStr, 'current');
await factory.ensureAutoIncrementWatermark(tableName);
ctx.logger.warn('[DeliveryOrderService.addOrder] 主键冲突,已修复自增水位,重试建单', {
deliveryOrderCode: deliveryOrder && deliveryOrder.deliveryOrderCode,
warehouseId: warehouseIdStr,
storeId: info.storeId,
error: error.message,
});
} catch (repairError) {
ctx.logger.warn('[DeliveryOrderService.addOrder] 自增水位修复失败,放弃重试', {
error: repairError.message,
});
}
continue;
}
return {
success: false,
message: `订单创建失败: ${this.formatOrderCreateError(error, deliveryOrder)}`,
data: null,
};
}
}
return {
success: false,
message: '订单创建失败: 主键冲突重试后仍未成功',
data: null,
};
}
/**
* 判断是否为分表主键自增冲突。
*
* 分表自增水位被破坏(显式 id 导入、表重建、迁移复制 id)后,自增插入会与
* 已有主键重叠,Sequelize 抛出的 UniqueConstraintError 对外 message 为
* “Validation error”,需按 errors[].path 识别。
*
* @param {Error} error Sequelize 错误对象。
* @return {boolean} 是否为主键唯一冲突。
*/
isPrimaryKeyDuplicate(error) {
if (!error || error.name !== 'SequelizeUniqueConstraintError' || !Array.isArray(error.errors)) {
return false;
}
return error.errors.some(item => item
&& item.type === 'unique violation'
&& (item.path === 'PRIMARY' || item.path === 'id'));
}
/**
* 将建单异常格式化为可读的失败原因。
*
* Sequelize 唯一约束错误的 message 固定为 “Validation error”,若不解析
* errors/parent 会掩盖真实原因,这里优先提取具体冲突字段与值。
*
* @param {Error} error 原始异常。
* @param {Object} [deliveryOrder] 请求中的发货单信息。
* @return {string} 可读的失败原因。
*/
formatOrderCreateError(error, deliveryOrder) {
if (error && error.name === 'SequelizeUniqueConstraintError' && Array.isArray(error.errors)) {
const primaryDup = error.errors.find(item => item
&& item.type === 'unique violation'
&& (item.path === 'PRIMARY' || item.path === 'id'));
if (primaryDup) {
return `订单ID主键冲突(id=${primaryDup.value} 已被占用):分表自增水位与已有数据重叠,已尝试修复并重试,请再次提交`;
}
const codeDup = error.errors.find(item => item && item.path === 'delivery_order_code');
if (codeDup) {
const orderCode = (deliveryOrder && deliveryOrder.deliveryOrderCode) || codeDup.value;
return `订单号 ${orderCode} 已存在`;
}
const firstItem = error.errors[0] || {};
return String(firstItem.message || error.message || '唯一约束冲突').trim();
}
const parentSqlMessage = error && error.parent && error.parent.sqlMessage;
if (parentSqlMessage) {
return `${error.message} (${parentSqlMessage})`;
}
return String((error && error.message) || '').trim() || '未知错误';
}
/**
* 根据货主仓库策略解析订单步骤。
* 若货主与仓库之间不存在已启用已签约的记录(auth_status=2, warehouse_use_status=1),则抛出错误拒绝创建。
*
* @param {Object} info 当前仓库与货主上下文,需包含 storeId 和 warehouseId。
* @param {Object|null} transaction 数据库事务。
* @return {Promise<number>} 订单步骤,需审批返回 0,免审批返回 1。
* @throws {Error} 货主未与当前仓库签约时抛出。
*/
async resolveOrderStep(info, transaction = null) {
const { ctx } = this;
const storeId = Number(info && info.storeId) || 0;
const warehouseId = Number(info && info.warehouseId) || 0;
if (storeId <= 0 || warehouseId <= 0) {
return DELIVERY_ORDER_STEP.PENDING_REVIEW;
}
const relation = await ctx.model.StoreWarehouse.findOne({
where: {
store_id: storeId,
warehouse_id: warehouseId,
auth_status: 2,
warehouse_use_status: 1,
},
attributes: [ 'id' ],
transaction,
raw: true,
});
if (!relation) {
throw new Error('仓库方已暂停接收推单,无法创建订单,请联系仓库方');
}
const relation2 = await ctx.model.StoreWarehouse.findOne({
where: {
store_id: storeId,
warehouse_id: warehouseId,
auth_status: 2,
warehouse_use_status: 1,
},
attributes: [ 'id' ],
transaction,
raw: true,
});
if (!relation2) {
throw new Error('仓库已禁用,无法创建订单,如需继续推单请进入货主后台修改配置');
}
const storeWarehouseService = ctx.service && ctx.service.systems && ctx.service.systems.storeWarehouse;
const policyConfig = storeWarehouseService && typeof storeWarehouseService.getEffectivePolicyConfigByContractId === 'function'
? await storeWarehouseService.getEffectivePolicyConfigByContractId(relation.id, transaction)
: null;
return Number(policyConfig && policyConfig.need_order_approval) === 0
? DELIVERY_ORDER_STEP.APPROVED
: DELIVERY_ORDER_STEP.PENDING_REVIEW;
}
/**
* 生成订单结构哈希值。
*
* @param {Object} itemsInfo 订单明细信息。
* @return {string} 结构哈希值。
*/
generateItemsHash(itemsInfo) {
const crypto = require('crypto');
if (!itemsInfo || !itemsInfo.items_str) {
return '';
}
// 生成哈希
return crypto.createHash('md5')
.update(itemsInfo.items_str)
.digest('hex');
}
/**
* 计算CRC32校验码
* @param {string} str 待计算字符串
* @return {number} CRC32校验值
*/
calculateCRC32(str) {
if (!str) return 0;
try {
const crc32 = require('crc-32');
const crc = crc32.str(str);
return crc >= 0 ? crc : crc + 4294967296;
} catch (error) {
// 降级方案:简单校验和
let crc = 0;
for (let i = 0; i < str.length; i++) {
crc = (crc + str.charCodeAt(i)) % 4294967296;
}
return crc;
}
}
/**
* 标准化订单来源键。
*
* @param {any} value 来源键原始值。
* @return {number|null} 有限整数返回整数值,否则返回 null。
*/
normalizeOrderFromKey(value) {
if (value === null || value === undefined) {
return null;
}
if (typeof value === 'string' && value.trim() === '') {
return null;
}
const normalizedValue = Number(value);
if (Number.isFinite(normalizedValue) && Number.isInteger(normalizedValue)) {
return normalizedValue;
}
return null;
}
/**
* 解析订单操作人名称。
*
* 优先使用外部传入的操作人;当未传入时按创建渠道自动补齐:
* - QM:奇门-${应用名称}
* - API:API-${应用名称}
* - MANUAL/其他:当前登录用户姓名(employees_name -> real_name -> name)
*
* @param {string|null|undefined} operatorName 外部传入的操作人名称。
* @param {string} [createChannel='MANUAL'] 订单创建渠道标识。
* @param {Object} [info={}] 当前仓库与货主上下文。
* @return {Promise<string|null>} 解析后的操作人名称。
*/
async resolveOperatorName(operatorName, createChannel = 'MANUAL', info = {}) {
const explicitOperatorName = operatorName === undefined || operatorName === null
? ''
: String(operatorName).trim();
if (explicitOperatorName) {
return explicitOperatorName;
}
const normalizedCreateChannel = String(createChannel || 'MANUAL').trim().toUpperCase() || 'MANUAL';
const appKey = String(
(info && info.appKey)
|| (this.ctx.user && this.ctx.user.app_key)
|| ''
).trim();
if (normalizedCreateChannel === 'QM') {
if (!appKey) {
return '奇门';
}
try {
const app = await this.ctx.model.QimenApp.findOne({
where: { app_key: appKey },
attributes: [ 'name' ],
raw: true,
});
const appName = String(app && app.name || '').trim();
return appName ? `奇门-${appName}` : '奇门';
} catch (error) {
this.ctx.logger.warn('[DeliveryOrderService.resolveOperatorName] 查询奇门应用失败,不影响主流程: %s', error.message);
return '奇门';
}
}
if (normalizedCreateChannel === 'API') {
if (!appKey) {
return 'API';
}
try {
const app = await this.ctx.model.ApiApp.findOne({
where: { self_app_key: appKey },
attributes: [ 'app_name' ],
raw: true,
});
const appName = String(app && app.app_name || '').trim();
return appName ? `API-${appName}` : 'API';
} catch (error) {
this.ctx.logger.warn('[DeliveryOrderService.resolveOperatorName] 查询API应用失败,不影响主流程: %s', error.message);
return 'API';
}
}
const loginUser = this.ctx.user && typeof this.ctx.user === 'object'
? this.ctx.user
: (this.ctx.state && this.ctx.state.user && typeof this.ctx.state.user === 'object' ? this.ctx.state.user : {});
const manualOperatorName = String(
loginUser.employees_name
|| loginUser.real_name
|| loginUser.name
|| ''
).trim();
return manualOperatorName || null;
}
/**
* 准备订单主表数据。
*
* @param {Object} deliveryOrder 订单主信息。
* @param {Object} info 当前仓库与货主上下文。
* @param {string} [createChannel='MANUAL'] 订单创建渠道标识。
* @param {number} step 订单步骤。
* @param {Array<Object>} [operationLogs=[]] 待写入的操作日志数组。
* @param {Object} [requestExtendProps] 请求级扩展属性,携带 ewaybill_order_code 等关键字段。
* @return {Promise<Object>} 可入库的订单数据。
*/
async prepareOrderData(
deliveryOrder,
info,
createChannel = 'MANUAL',
step = DELIVERY_ORDER_STEP.PENDING_REVIEW,
operationLogs = [],
requestExtendProps
) {
const {
deliveryOrderCode,
preDeliveryOrderCode,
preDeliveryOrderId,
orderType,
warehouseCode,
orderFlag,
sourcePlatformCode,
sourcePlatformName,
oaidOrderSourceCode,
placeOrderTime,
payTime,
payNo,
shopNick,
sellerNick,
buyerNick,
buyerMessage,
sellerMessage,
remark,
operatorName,
operateTime,
totalAmount,
itemAmount,
discountAmount,
freight,
arAmount,
gotAmount,
logisticsCode,
expressCode,
logisticsAreaCode,
isUrgency,
invoiceFlag,
receiverInfo,
sourceOrderCode,
} = deliveryOrder;
const policyConfig = await this.getStoreWarehousePolicyConfig(info.storeId, info.warehouseId);
const enableExternalExpressCode = this.resolveEnableExternalExpressCode(policyConfig, policyConfig);
const platformSnapshot = await this.resolvePlatformSnapshot(sourcePlatformCode, policyConfig, policyConfig, {
deliveryOrderCode,
warehouseId: info.warehouseId,
storeId: info.storeId,
}, operationLogs);
const expressSnapshot = await this.resolveExpressSnapshot(logisticsCode, policyConfig, {
deliveryOrderCode,
warehouseId: info.warehouseId,
storeId: info.storeId,
policyConfig,
enableExternalExpressCode,
}, operationLogs);
const resolvedOperatorName = await this.resolveOperatorName(operatorName, createChannel, info);
const fromKey = this.normalizeOrderFromKey(info.appKey);
return {
delivery_order_code: deliveryOrderCode,
pre_delivery_order_code: preDeliveryOrderCode || '',
pre_delivery_order_id: preDeliveryOrderId || '',
order_type: orderType,
warehouse_code: warehouseCode,
order_flag: orderFlag || '',
source_platform_code: sourcePlatformCode || '',
source_platform_name: sourcePlatformName || '',
oaid_order_source_code: oaidOrderSourceCode || '',
create_channel: String(createChannel || 'MANUAL').trim().toUpperCase() || 'MANUAL',
sys_platform_code: platformSnapshot.sysPlatformCode,
sys_platform_name: platformSnapshot.sysPlatformName,
// 创建时间统一取服务器当前时间,不采用报文 createTime,避免被平台上报时间覆盖
create_at: new Date(),
place_order_time: placeOrderTime ? new Date(placeOrderTime) : null,
pay_time: payTime ? new Date(payTime) : null,
pay_no: payNo || sourceOrderCode || '',
shop_nick: shopNick,
seller_nick: sellerNick,
buyer_nick: buyerNick,
buyer_message: buyerMessage || '',
seller_message: sellerMessage || '',
remark: remark || '',
operator_name: resolvedOperatorName,
operate_time: operateTime ? new Date(operateTime) : null,
total_amount: totalAmount ? parseFloat(totalAmount) : 0,
item_amount: itemAmount ? parseFloat(itemAmount) : 0,
discount_amount: discountAmount ? parseFloat(discountAmount) : 0,
freight: freight ? parseFloat(freight) : 0,
ar_amount: arAmount ? parseFloat(arAmount) : 0,
got_amount: gotAmount ? parseFloat(gotAmount) : 0,
logistics_code: expressSnapshot.logisticsCode,
logistics_name: expressSnapshot.logisticsName,
sys_logistics_code: expressSnapshot.sysLogisticsCode,
sys_logistics_name: expressSnapshot.sysLogisticsName,
express_code: expressCode || '',
weight_type: expressSnapshot.weightType ?? 0,
logistics_area_code: logisticsAreaCode || '',
is_urgency: isUrgency || 'N',
invoice_flag: invoiceFlag || 'N',
status: Number(step) >= DELIVERY_ORDER_STEP.APPROVED ? 'created' : 'pedding',
step: Number.isInteger(Number(step)) ? Number(step) : DELIVERY_ORDER_STEP.PENDING_REVIEW,
// 收件人信息
name: receiverInfo?.name || '',
tel: receiverInfo?.tel || '',
mobile: receiverInfo?.mobile || '',
email: receiverInfo?.email || '',
country_code: receiverInfo?.countryCode || '',
province: receiverInfo?.province || '',
city: receiverInfo?.city || '',
area: receiverInfo?.area || '',
town: receiverInfo?.town || '',
detail_address: receiverInfo?.detailAddress || '',
zip_code: receiverInfo?.zipCode || '',
oaid: receiverInfo?.oaid || '',
// 发件人信息(如果需要存储)
// 业务关联ID
extend_props: requestExtendProps || null,
store_id: info.storeId,
warehouse_id: info.warehouseId,
from_key: fromKey,
};
}
/**
* 添加订单明细并完成库存预占。
*
* @param {Object|Array} orderLines 订单明细数据。
* @param {number} orderId 订单主键。
* @param {Object} info 当前仓库与货主上下文。
* @param {Object} transaction 数据库事务。
* @return {Promise<Object>} 明细创建与库存统计结果。
*/
async addOrderLines(orderLines, orderId, info, transaction) {
const { ctx, app } = this;
const { warehouseId, appKey, storeId } = info;
let order_items = [];
if (orderLines && typeof orderLines === 'object') {
if (orderLines.itemCode) {
order_items = [ orderLines ];
} else if (Array.isArray(orderLines)) {
order_items = orderLines;
} else if (orderLines.orderLine && Array.isArray(orderLines.orderLine)) {
order_items = orderLines.orderLine;
} else if (orderLines.orderLine && typeof orderLines.orderLine === 'object') {
order_items = [ orderLines.orderLine ];
}
}
if (!order_items || !Array.isArray(order_items) || order_items.length === 0) {
throw new Error('没有有效的订单明细数据');
}
const OrderItemsModel = await ctx.model.OrderItemsFactory.getCurrentModel(warehouseId);
const lineData = [];
const errors = [];
const stockQuantityMap = new Map(); // stock_id -> 数量
const stockWeightMap = new Map(); // stock_id -> 单件重量(grossWeight)
// 预取签约策略配置(避免锁内查DB,减少锁持有时间)
const oversellConfig = await ctx.service.systems.stockStore
.getStoreWarehousePolicyByStoreAndWarehouse(storeId, warehouseId);
// ===== Phase 1: 解析阶段(不锁)=====
// 遍历所有 orderLine,解析 StockStore、验证数据、合并重复商品,
// 但不对 wms_stock_warehouse 加锁,避免因传入顺序不同导致死锁。
const resolvedItems = [];
for (let i = 0; i < order_items.length; i++) {
const line = order_items[i];
// 跳过空值
if (!line || typeof line !== 'object') {
errors.push(`第${i + 1}行: 数据格式无效`);
continue;
}
// 数量验证
const planQty = line.planQty ? parseInt(line.planQty) : 0;
if (planQty <= 0) {
errors.push(`商品《${line.itemName}》数量必须大于0`);
continue;
}
let wms_stock = null;
// 手工单:调用方直接传入 stockId 时需查 StockStore 获取完整信息(含 gross_weight)
if (line.stockId && line.stockId > 0) {
wms_stock = await app.model.StockStore.findByPk(line.stockId, { transaction });
if (!wms_stock) {
// 降级:查不到记录时用调用方传入的字段构造最小对象
wms_stock = {
id: line.stockId,
stock_id: line.stockId,
item_name: line.itemName || '',
item_code: line.itemCode || '',
gross_weight: 0,
};
}
// 手工单直接传仓库 stock_id:校验库存记录归属当前货主,禁止跨货主下单
const stockWarehouseRecord = await app.model.StockWarehouse.findByPk(line.stockId, {
attributes: [ 'id', 'store_id' ],
transaction,
raw: true,
});
if (stockWarehouseRecord && Number(stockWarehouseRecord.store_id) !== Number(storeId)) {
errors.push(`商品《${line.itemName}》编码《${line.itemCode}》\n库存归属货主(store_id=${stockWarehouseRecord.store_id})与当前货主(store_id=${storeId})不一致,无法创建订单`);
continue;
}
} else {
// 查找唯一键(appKey 为空时不作为条件,兼容内部手动建单场景)
const findByItemCode = async () => {
if (!line.itemCode) return null;
const stockWhere = {
item_code: line.itemCode,
warehouse_id: warehouseId,
store_id: storeId,
};
if (appKey) {
stockWhere.app_key = appKey;
}
return await app.model.StockStore.findOne({ where: stockWhere, transaction });
};
if (!line.itemId) {
wms_stock = await findByItemCode();
} else {
wms_stock = await app.model.StockStore.findByPk(line.itemId, { transaction });
// 校验 StockStore 记录的 store_id 与当前上下文一致,防止跨货主越权
if (wms_stock && Number(wms_stock.store_id) !== Number(storeId)) {
wms_stock = null;
}
// 外部渠道(奇门/开放平台)itemId 可能是平台商品标识或条码而非 WMS 主键,
// 主键查不到或跨货主时降级按 item_code 查找,避免误报“未同步推送到仓库”
if (!wms_stock) {
wms_stock = await findByItemCode();
}
}
}
if (!wms_stock) {
errors.push(`商品《${line.itemName}》编码《${line.itemCode}》\n未同步推送到仓库`);
continue;
}
const itemId = parseInt(wms_stock.id);
const stockId = Number(wms_stock.stock_id) || 0;
if (!stockId) {
errors.push(`第${i + 1}行: 商品《${wms_stock.item_name}》库存记录不存在`);
continue;
}
// 重复商品:累加到已存在的条目
const existingIdx = resolvedItems.findIndex(ri => ri.itemId === itemId);
if (existingIdx >= 0) {
resolvedItems[existingIdx].planQty += planQty;
ctx.logger.info(`[addOrderLines] 合并重复行: itemId=${itemId}, 额外数量=${planQty}, 累加后=${resolvedItems[existingIdx].planQty}`);
continue;
}
resolvedItems.push({
itemId,
stockId,
planQty,
wms_stock,
line,
lineIndex: i,
});
}
// ===== Sort: 按 stockId 升序排序,保证所有事务加锁顺序一致,从根本上消除死锁 =====
resolvedItems.sort((a, b) => a.stockId - b.stockId);
// ===== 批量查询 wms_stock_warehouse 获取仓库侧称重毛重 & 违禁品类型 =====
const stockIds = [ ...new Set(resolvedItems.map(item => item.stockId).filter(Boolean)) ];
const warehouseWeightMap = new Map();
const stockProhibitedMap = new Map(); // stock_id -> 违禁品类型ID
if (stockIds.length > 0) {
const warehouseRecords = await app.model.StockWarehouse.findAll({
where: { id: stockIds },
attributes: [ 'id', 'gross_weight', 'prohibited_id' ],
transaction,
raw: true,
});
for (const record of warehouseRecords) {
const gw = parseFloat(record.gross_weight) || 0;
if (gw > 0) {
warehouseWeightMap.set(record.id, gw);
}
const prohibitedId = Number(record.prohibited_id) || 0;
if (prohibitedId > 0) {
stockProhibitedMap.set(record.id, prohibitedId);
}
}
}
// ===== Phase 2: 锁定阶段(按排序后顺序逐个加锁)=====
for (const item of resolvedItems) {
const lockResult = await ctx.service.systems.stockStore.lockItemStorages(
item.stockId,
item.planQty,
transaction,
oversellConfig,
{ orderType: 'DELIVERY_ORDER', orderNo: String(orderId), orderId }
);
if (!lockResult.success) {
errors.push(`SKU${item.wms_stock.id}商品《${item.wms_stock.item_name}》编码《${item.wms_stock.item_code}》\n锁定失败: ${lockResult.error}`);
continue;
}
const totalQtyForStock = (stockQuantityMap.get(item.stockId) || 0) + item.planQty;
stockQuantityMap.set(item.stockId, totalQtyForStock);
// 优先取 wms_stock_warehouse.gross_weight(仓库称重),其次取 wms_stock_store.gross_weight
const warehouseWeight = warehouseWeightMap.get(item.stockId);
const weight = (warehouseWeight != null && warehouseWeight > 0)
? warehouseWeight
: (parseFloat(item.wms_stock.gross_weight) || 0);
stockWeightMap.set(item.stockId, weight);
// 所有检查通过,准备订单行数据
lineData.push({
order_id: orderId,
actual_price: this.safeParseFloat(item.line.actualPrice, 0),
retail_price: this.safeParseFloat(item.line.retailPrice, 0),
ext_code: item.line.extCode || '',
inventory_type: item.line.inventoryType || '',
item_code: item.line.itemCode || '',
item_id: item.itemId,
item_name: item.line.itemName || '',
order_line_no: item.line.orderLineNo || `${item.lineIndex + 1}`,
owner_code: item.line.ownerCode || '',
plan_qty: item.planQty,
source_order_code: item.line.sourceOrderCode || '',
sub_source_order_code: item.line.subSourceOrderCode || '',
extend_props: item.line.extendProps ?
(typeof item.line.extendProps === 'string' ? item.line.extendProps : JSON.stringify(item.line.extendProps))
: null,
stock_id: item.stockId,
item_snapshot: this.buildOrderItemSnapshot(item.wms_stock, item.line),
// 可选:记录重量信息到明细
item_weight: stockWeightMap.get(item.stockId) || 0,
});
}
// ========== 计算订单统计信息 ==========
let items_str = '';
let total_weight = 0; // 总重量
let stock_count = 0; // stock种类数
let item_total_count = 0; // 商品总数
let source_order_codes = new Set(); // 订单来源去重集合
if (stockQuantityMap.size > 0) {
// 生成结构字符串
const sortedStocks = Array.from(stockQuantityMap.entries())
.sort(([ stockIdA ], [ stockIdB ]) => stockIdA - stockIdB)
.map(([ stockId, quantity ]) => {
return `${stockId}+${quantity}`;
});
items_str = sortedStocks.join('|');
// 计算统计信息
stock_count = stockQuantityMap.size; // stock种类数
// 计算商品总数
item_total_count = Array.from(stockQuantityMap.values())
.reduce((sum, quantity) => sum + (parseInt(quantity) || 0), 0);
// 计算总重量:重量 × 数量
total_weight = Array.from(stockQuantityMap.entries())
.reduce((sum, [ stockId, quantity ]) => {
const weight = stockWeightMap.get(stockId) || 0;
const qty = parseInt(quantity) || 0;
return sum + (weight * qty);
}, 0);
source_order_codes = new Set(lineData.map(line => line.source_order_code).filter(code => code)); // 订单来源去重集合
ctx.logger.debug('[订单统计信息]', {
orderId,
stock_count,
item_total_count,
total_weight,
items_str_length: items_str.length,
items_preview: items_str.substring(0, 100) + (items_str.length > 100 ? '...' : ''),
});
} else if (lineData.length > 0) {
// MANUAL 降级:stockQuantityMap 为空时,从 lineData 直接计算统计
stock_count = lineData.length;
item_total_count = lineData.reduce((sum, ld) => sum + (Number(ld.plan_qty) || 0), 0);
total_weight = 0;
// items_str 用 item_id 作为标识
const itemEntries = new Map();
for (const ld of lineData) {
const iid = Number(ld.item_id) || 0;
const qty = Number(ld.plan_qty) || 0;
itemEntries.set(iid, (itemEntries.get(iid) || 0) + qty);
}
items_str = Array.from(itemEntries.entries())
.sort(([ a ], [ b ]) => a - b)
.map(([ iid, qty ]) => `${iid}+${qty}`)
.join('|');
source_order_codes = new Set(lineData.map(line => line.source_order_code).filter(code => code));
ctx.logger.debug('[订单统计信息-MANUAL降级]', {
orderId,
stock_count,
item_total_count,
total_weight,
items_str_length: items_str.length,
items_preview: items_str.substring(0, 100) + (items_str.length > 100 ? '...' : ''),
});
}
if (errors.length > 0) {
throw new Error(`创建订单错误:\n${errors.join('\n')}`);
}
if (lineData.length === 0) {
throw new Error('没有有效的商品明细可以创建');
}
// 批量创建订单明细
await OrderItemsModel.bulkCreate(lineData, { transaction });
ctx.logger.info(`成功添加 ${lineData.length} 个订单明细项,订单ID: ${orderId}`);
// 返回完整信息
return {
length: lineData.length, // 商品种类数(与stock_count相同)
items_str, // 结构字符串
stock_count, // stock种类数
item_total_count, // 商品总数
total_weight, // 总重量
stock_quantity_map: Object.fromEntries(stockQuantityMap), // stock_id -> 数量
stock_weight_map: Object.fromEntries(stockWeightMap), // stock_id -> 单件重量
line_data: lineData, // 创建的明细数据
prohibited_type_ids: [ ...new Set(stockProhibitedMap.values()) ], // 违禁品类型ID去重数组(快递策略匹配用)
stats: { // 统计信息汇总
unique_items: stock_count,
total_items: item_total_count,
total_weight,
avg_weight_per_item: stock_count > 0 ? (total_weight / item_total_count).toFixed(2) : 0,
source_order_codes: Array.from(source_order_codes), // 订单来源去重集合
},
};
}
buildOrderItemSnapshot(stockRecord = {}, line = {}) {
return {
id: Number(stockRecord.id || 0) || null,
stock_id: Number(stockRecord.stock_id || 0) || null,
item_code: String(stockRecord.item_code || line.itemCode || '').trim(),
item_name: String(stockRecord.item_name || line.itemName || '').trim(),
goods_code: String(stockRecord.goods_code || '').trim(),
sku_property: String(stockRecord.sku_property || '').trim(),
barcode: String(stockRecord.barcode || '').trim(),
brand_name: String(stockRecord.brand_name || '').trim(),
category_id: Number(stockRecord.category_id || 0) || null,
category_name: String(stockRecord.category_name || '').trim(),
item_type: String(stockRecord.item_type || '').trim(),
stock_unit: String(stockRecord.stock_unit || '').trim(),
inventory_type: String(line.inventoryType || '').trim(),
retail_price: this.safeParseFloat(stockRecord.retail_price, this.safeParseFloat(line.retailPrice, 0)),
gross_weight: this.safeParseFloat(stockRecord.gross_weight, 0),
net_weight: this.safeParseFloat(stockRecord.net_weight, 0),
length: this.safeParseFloat(stockRecord.length, 0),
width: this.safeParseFloat(stockRecord.width, 0),
height: this.safeParseFloat(stockRecord.height, 0),
volume: this.safeParseFloat(stockRecord.volume, 0),
};
}
// 添加工具方法
safeParseFloat(value, defaultValue = 0) {
if (value === null || value === undefined) return defaultValue;
const num = parseFloat(value);
return isNaN(num) ? defaultValue : num;
}
/**
* 在当前调用内临时注入 ctx.user 上下文,并在结束后恢复。
*
* 仅用于复用依赖登录上下文的既有 service 能力,避免扩大影响范围。
*
* @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;
}
}
/**
* 构建订单创建后异步处理所需上下文。
*
* @param {number|string} orderId 订单ID。
* @param {Object} info 订单创建上下文。
* @return {Promise<Object|null>} 异步处理上下文。
*/
async buildAsyncProcessContext(orderId, info = {}) {
const { ctx } = this;
const normalizedOrderId = Number(orderId || 0);
const warehouseId = Number(info && info.warehouseId || 0);
const storeId = Number(info && info.storeId || 0);
if (!Number.isInteger(normalizedOrderId) || normalizedOrderId <= 0) {
return null;
}
if (!Number.isInteger(warehouseId) || warehouseId <= 0) {
return null;
}
const DeliveryModel = await ctx.model.OrderDeliveryFactory.getCurrentModel(warehouseId);
const order = await DeliveryModel.findOne({
where: {
id: normalizedOrderId,
warehouse_id: warehouseId,
},
raw: true,
});
if (!order) {
return null;
}
const OrderItemsModel = await ctx.model.OrderItemsFactory.getCurrentModel(warehouseId);
const orderItemRows = await OrderItemsModel.findAll({
where: {
order_id: normalizedOrderId,
},
attributes: [ 'order_id', 'plan_qty', 'stock_id', 'item_code', 'item_name', 'item_snapshot' ],
raw: true,
});
return {
orderId: normalizedOrderId,
warehouseId,
storeId: storeId > 0 ? storeId : Number(order.store_id || 0),
order,
orderItemRows: Array.isArray(orderItemRows) ? orderItemRows : [],
};
}
/**
* 构建快递分配显式请求体。
*
* @param {Object} context 异步处理上下文。
* @return {Object} 快递分配请求。
*/
buildExpressAllocateRequest(context) {
const order = context && context.order ? context.order : {};
return {
ids: [ Number(order.id || context.orderId || 0) ],
};
}
/**
* 将订单入队到自动分配快递消费队列(wms_waybill_allocate_queue)。
*
* 仅写入队列不取号,由定时任务 app/schedule/consume_waybill_allocate_queue.js
* 按仓库+货主串行批量消费。入队幂等(uk_order_id_business_key),重复入队忽略。
* 调用方需保证截单/未审核订单不会走到此方法。
*
* @param {Object} context 异步处理上下文。
* @return {Promise<void>} 无返回值。
*/
async enqueueAutoWaybillAllocation(context) {
const queueModel = this.ctx.model && this.ctx.model.WaybillAllocateQueue;
if (!queueModel || typeof queueModel.findOrCreate !== 'function') {
this.ctx.logger.warn('[DeliveryOrderService.enqueueAutoWaybillAllocation] 运单分配队列模型未初始化,跳过入队');
return;
}
const orderId = Number(context && context.orderId || 0);
const warehouseId = Number(context && context.warehouseId || 0);
const storeId = Number(context && context.storeId || 0);
if (!Number.isInteger(orderId) || orderId <= 0 || !Number.isInteger(warehouseId) || warehouseId <= 0) {
return;
}
try {
await queueModel.findOrCreate({
where: {
order_id: orderId,
business_key: 1,
},
defaults: {
order_id: orderId,
business_key: 1,
warehouse_id: warehouseId,
store_id: storeId > 0 ? storeId : 0,
status: 'pending',
retry_count: 0,
next_retry_at: null,
error_message: null,
created_at: new Date(),
updated_at: new Date(),
},
});
this.ctx.logger.info('[DeliveryOrderService.enqueueAutoWaybillAllocation] 订单已入队等待批量分配快递', {
orderId,
warehouseId,
storeId,
});
} catch (error) {
// 唯一键冲突(重复入队)或 DB 异常仅记录,不阻断订单创建后续异步流程
this.ctx.logger.warn('[DeliveryOrderService.enqueueAutoWaybillAllocation] 入队失败: %s', error.message, {
orderId,
error: error.message,
});
}
}
/**
* 构建储位分配显式请求体。
*
* @param {Object} context 异步处理上下文。
* @return {Object} 储位分配请求。
*/
buildStorageAllocateRequest(context) {
return {
allow_storage_location: true,
order_ids: [ Number(context && context.orderId || 0) ],
// 显式携带仓库上下文,避免依赖 ctx.user(Qimen 链路无登录用户)
warehouse_id: Number(context && context.warehouseId || 0),
};
}
/**
* 读取货主-仓库策略配置。
*
* @param {number} storeId 货主ID。
* @param {number} warehouseId 仓库ID。
* @return {Promise<Object>} 策略配置。
*/
async getStoreWarehousePolicyConfig(storeId, warehouseId) {
const storeWarehouseService = this.ctx.service
&& this.ctx.service.systems
&& this.ctx.service.systems.storeWarehouse;
if (!storeWarehouseService || typeof storeWarehouseService.getContractConfig !== 'function') {
return {};
}
try {
const contractConfig = await storeWarehouseService.getContractConfig(
Number(warehouseId || 0),
Number(storeId || 0)
);
const policyConfig = contractConfig && typeof contractConfig.policy_config === 'object'
? contractConfig.policy_config
: {};
return policyConfig;
} catch (error) {
this.ctx.logger.warn(`[DeliveryOrderService.getStoreWarehousePolicyConfig] read contract config failed: ${error.message}`, {
storeId,
warehouseId,
error: error.message,
});
return {};
}
}
/**
* 归一化策略开关值。
*
* @param {any} value 原始开关值。
* @return {boolean} 是否开启。
*/
normalizePolicyFlag(value) {
if (typeof value === 'boolean') {
return value;
}
const normalizedText = String(value === undefined || value === null ? '' : value).trim().toLowerCase();
return [ '1', 'true', 'yes', 'on' ].includes(normalizedText);
}
/**
* 解析自动分配时间窗口配置,货主-仓库级优先,未启用时由仓库级兜底。
*
* @param {Object} policyConfig 货主-仓库级策略配置。
* @param {Object|null} warehouseSubjectConfig 仓库级主体配置。
* @return {{cutoffEnabled: boolean, cutoffTime: string, allocateStartTime: string}}
* 最终生效的截单开关、截单时间与开始自动分配时间。
*/
resolveCutoffOrderConfig(policyConfig, warehouseSubjectConfig) {
const policyEnabled = this.normalizePolicyFlag(
(policyConfig && policyConfig.cutoff_order_enabled)
);
const policyTime = (policyConfig && typeof policyConfig.cutoff_order_time === 'string'
? policyConfig.cutoff_order_time.trim()
: '') || '18:00';
const policyStartTime = (policyConfig && typeof policyConfig.allocate_start_time === 'string'
? policyConfig.allocate_start_time.trim()
: '') || '08:00';
// 货主-仓库级已启用截单,直接使用
if (policyEnabled) {
return {
cutoffEnabled: true,
cutoffTime: policyTime,
allocateStartTime: policyStartTime,
};
}
// 货主-仓库级未启用,由仓库级兜底
if (warehouseSubjectConfig && warehouseSubjectConfig.cutoff_order_enabled) {
const warehouseTime = (typeof warehouseSubjectConfig.cutoff_order_time === 'string'
? warehouseSubjectConfig.cutoff_order_time.trim()
: '') || '18:00';
const warehouseStartTime = (typeof warehouseSubjectConfig.allocate_start_time === 'string'
? warehouseSubjectConfig.allocate_start_time.trim()
: '') || '08:00';
return {
cutoffEnabled: true,
cutoffTime: warehouseTime,
allocateStartTime: warehouseStartTime,
};
}
return {
cutoffEnabled: false,
cutoffTime: '18:00',
allocateStartTime: '08:00',
};
}
/**
* 判断当前时间是否已超过指定截单时间。
*
* @param {string} cutoffTimeStr 截单时间,格式 HH:mm。
* @return {boolean} 是否已超过截单时间。
*/
isPastCutoffTime(cutoffTimeStr) {
if (!cutoffTimeStr || typeof cutoffTimeStr !== 'string') {
return false;
}
const trimmed = cutoffTimeStr.trim();
if (!/^\d{2}:\d{2}$/.test(trimmed)) {
return false;
}
const now = new Date();
const [ hours, minutes ] = trimmed.split(':').map(Number);
const cutoffTotalMinutes = hours * 60 + minutes;
const nowTotalMinutes = now.getHours() * 60 + now.getMinutes();
return nowTotalMinutes >= cutoffTotalMinutes;
}
/**
* 判断当前时间是否处于自动分配窗口之外。
*
* 同天窗口(开始时间早于截单时间):now < start 或 now >= cutoff 时禁止;
* 跨天窗口(开始时间晚于截单时间,截单时间视为次日):now in [cutoff, start) 时禁止;
* 开始时间与截单时间相同时窗口恒空,防御性全天禁止。
*
* @param {string} allocateStartTimeStr 开始自动分配时间,格式 HH:mm。
* @param {string} cutoffTimeStr 截单时间,格式 HH:mm。
* @param {Date} [nowDate=new Date()] 当前时间(测试可注入)。
* @return {boolean} 是否禁止自动分配。
*/
isAllocationWindowClosed(allocateStartTimeStr, cutoffTimeStr, nowDate = new Date()) {
const parseTime = value => {
if (!value || typeof value !== 'string') {
return null;
}
const trimmed = value.trim();
if (!/^\d{2}:\d{2}$/.test(trimmed)) {
return null;
}
const [ hours, minutes ] = trimmed.split(':').map(Number);
return hours * 60 + minutes;
};
const startMinutes = parseTime(allocateStartTimeStr);
const cutoffMinutes = parseTime(cutoffTimeStr);
const nowMinutes = nowDate.getHours() * 60 + nowDate.getMinutes();
if (startMinutes === null || cutoffMinutes === null) {
return false;
}
if (startMinutes === cutoffMinutes) {
return true; // 窗口为空,防御性全天禁止
}
if (startMinutes < cutoffMinutes) {
// 同天窗口 [start, cutoff)
return nowMinutes < startMinutes || nowMinutes >= cutoffMinutes;
}
// 跨天窗口:截单时间视为次日 [start, 24:00) ∪ [00:00, cutoff)
return nowMinutes >= cutoffMinutes && nowMinutes < startMinutes;
}
/**
* 构建自动加团结构信息。
*
* @param {Object} context 异步处理上下文。
* @return {Object|null} 自动加团结构信息。
*/
buildAutoGroupingStructure(context) {
const waveService = this.ctx.service && this.ctx.service.systemMethods
&& this.ctx.service.systemMethods.order
&& this.ctx.service.systemMethods.order.wave;
if (!waveService) {
return null;
}
const order = context && context.order ? context.order : {};
const itemPartType = String(order.items_hash || '').trim() ? 'items_hash' : 'items';
const itemPart = String(itemPartType === 'items_hash' ? order.items_hash : order.items || '').trim();
if (!itemPart) {
return null;
}
const logisticsName = String(order.sys_logistics_code || '').trim();
const mergedItemDetails = typeof waveService.mergeOrderItemDetails === 'function'
? waveService.mergeOrderItemDetails(context && context.orderItemRows ? context.orderItemRows : [])
: [];
const itemSnapshotKey = typeof waveService.buildItemSnapshotKey === 'function'
? waveService.buildItemSnapshotKey(mergedItemDetails)
: '';
const itemDetailMachine = typeof waveService.buildMachineStructureToken === 'function'
? waveService.buildMachineStructureToken({
item_part_type: itemPartType,
item_part: itemPart,
distinguish_express: true,
logistics_name: logisticsName,
item_snapshot_key: itemSnapshotKey,
})
: '';
return {
itemPartType,
itemPart,
logisticsName,
itemSnapshotKey,
itemDetailMachine,
};
}
/**
* 查找自动加团中的匹配波次。
*
* @param {Object} context 异步处理上下文。
* @param {Object} structure 自动加团结构信息。
* @return {Promise<number>} 命中的波次ID,未命中返回 0。
*/
async findAutoGroupingWaveId(context, structure) {
const { ctx } = this;
const waveService = ctx.service.systemMethods.order.wave;
const request = {
page: 1,
pageSize: 50,
where: {
wave_status: 0,
item_part_type: structure.itemPartType,
item_part: structure.itemPart,
item_snapshot_key: structure.itemSnapshotKey,
distinguish_express: 1,
logistics_name: structure.logisticsName,
},
};
const response = await this.withPatchedCtxUser({
store_id: context.warehouseId,
warehouse_id: context.warehouseId,
}, async () => {
return await waveService.batchList(request);
});
const list = response && response.list;
if (!Array.isArray(list) || list.length === 0) {
return 0;
}
return Number(list[0] && list[0].wave_id || 0);
}
/**
* 将订单加入指定波次,并回写波次统计。
*
* @param {Object} context 异步处理上下文。
* @param {number} waveId 波次ID。
* @return {Promise<boolean>} 是否成功加入。
*/
async appendOrderToWave(context, waveId) {
const { ctx } = this;
const normalizedWaveId = Number(waveId || 0);
if (!Number.isInteger(normalizedWaveId) || normalizedWaveId <= 0) {
return false;
}
const warehouseId = Number(context.warehouseId || 0);
const orderId = Number(context.orderId || 0);
if (!Number.isInteger(warehouseId) || warehouseId <= 0 || !Number.isInteger(orderId) || orderId <= 0) {
return false;
}
const DeliveryModel = await ctx.model.OrderDeliveryFactory.getCurrentModel(warehouseId);
const transaction = await ctx.model.transaction();
try {
const orderRow = await DeliveryModel.findOne({
where: {
id: orderId,
warehouse_id: warehouseId,
},
attributes: [ 'id', 'wave_id', 'step', 'status', 'outbound_status', 'lock_status' ],
transaction,
lock: transaction.LOCK.UPDATE,
});
if (!orderRow) {
await transaction.commit();
return false;
}
// 已锁定的订单不允许自动加团
if (isLockedOrderStatus(orderRow.lock_status)) {
await transaction.commit();
return false;
}
const currentWaveId = Number(orderRow.wave_id || 0);
if (currentWaveId === normalizedWaveId) {
await transaction.commit();
return true;
}
if (currentWaveId > 0) {
await transaction.commit();
return false;
}
const currentStep = Number(orderRow.step || 0);
const currentStatus = String(orderRow.status || '').trim();
const currentOutboundStatus = String(orderRow.outbound_status || '').trim();
if (![ 1, 2, 3 ].includes(currentStep) || currentStatus === 'cancel' || currentOutboundStatus === 'padding') {
await transaction.commit();
return false;
}
const waveRows = await ctx.model.query(`
SELECT wave_id, wave_no, total_orders
FROM wms_wave_batch
WHERE warehouse_id = :warehouseId
AND wave_id = :waveId
LIMIT 1
FOR UPDATE
`, {
replacements: {
warehouseId,
waveId: normalizedWaveId,
},
type: ctx.model.QueryTypes.SELECT,
transaction,
});
const wave = Array.isArray(waveRows) && waveRows[0] ? waveRows[0] : null;
if (!wave) {
await transaction.commit();
return false;
}
await DeliveryModel.update({
wave_id: normalizedWaveId,
wave_no: String(wave.wave_no || '').trim(),
}, {
where: {
id: orderId,
warehouse_id: warehouseId,
wave_id: 0,
lock_status: 'none',
},
transaction,
});
await ctx.service.systemMethods.order.wave.rebuildOrderWaveIndex({
warehouseId,
waveId: normalizedWaveId,
orderIds: [ orderId ],
orderModel: DeliveryModel,
transaction,
});
await ctx.model.query(`
UPDATE wms_wave_batch
SET total_orders = total_orders + 1,
update_time = NOW()
WHERE warehouse_id = :warehouseId
AND wave_id = :waveId
`, {
replacements: {
warehouseId,
waveId: normalizedWaveId,
},
transaction,
});
await transaction.commit();
// 写入订单操作日志:自动加团
try {
const operationLogService = this.ctx
&& this.ctx.service
&& this.ctx.service.systems
&& this.ctx.service.systems.operationLog;
if (operationLogService && typeof operationLogService.createOperationLogs === 'function') {
await operationLogService.createOperationLogs([{
businessType: 'order',
businessId: `${orderId}`,
operationCode: 'ORDER_WAVE_AUTO_GROUP',
operator: {
id: null,
name: 'system',
},
extras: {
message: `自动加团到波次 ${wave.wave_no || normalizedWaveId}`,
warehouseId,
waveId: normalizedWaveId,
waveNo: wave.wave_no || '',
},
}]);
}
} catch (e) {
this.ctx.logger.warn('[delivery_order.appendOrderToWave] 写入 operation_log 失败,不影响主流程', {
error: e && e.message,
orderId,
waveId: normalizedWaveId,
});
}
return true;
} catch (error) {
await transaction.rollback();
throw error;
}
}
/**
* 统计可参与新团购波次的订单数量。
*
* @param {Object} context 异步处理上下文。
* @param {Object} structure 自动加团结构信息。
* @return {Promise<number>} 可参与数量。
*/
async countCandidateGroupOrders(context, structure) {
const { ctx } = this;
const DeliveryModel = await ctx.model.OrderDeliveryFactory.getCurrentModel(context.warehouseId);
const where = {
warehouse_id: context.warehouseId,
wave_id: 0,
step: { [ctx.app.Sequelize.Op.in]: [ 1, 2, 3 ] },
status: { [ctx.app.Sequelize.Op.ne]: 'cancel' },
outbound_status: { [ctx.app.Sequelize.Op.ne]: 'padding' },
lock_status: 'none',
sys_logistics_code: structure.logisticsName,
};
where[structure.itemPartType] = structure.itemPart;
return await DeliveryModel.count({ where });
}
/**
* 按结构创建团购波次。
*
* @param {Object} context 异步处理上下文。
* @param {Object} structure 自动加团结构信息。
* @param {number} minGroupOrderFetchQuantity 最小团购抓取数量。
* @param {number} maxWaveQuantity 最大加团数量。
* @return {Promise<Object>} 抓取结果。
*/
async createGroupingWave(context, structure, minGroupOrderFetchQuantity, maxWaveQuantity) {
const { ctx } = this;
const waveService = ctx.service.systemMethods.order.wave;
const DeliveryModel = await ctx.model.OrderDeliveryFactory.getCurrentModel(context.warehouseId);
const requestStructure = {
item_part_type: structure.itemPartType,
item_part: structure.itemPart,
distinguish_express: true,
logistics_name: structure.logisticsName,
sys_logistics_code: structure.logisticsName,
item_snapshot_key: structure.itemSnapshotKey,
item_detail_machine: structure.itemDetailMachine,
quantity: maxWaveQuantity,
};
return await this.withPatchedCtxUser({
store_id: context.warehouseId,
warehouse_id: context.warehouseId,
}, async () => {
return await waveService.fetchSingleStructure(
DeliveryModel,
requestStructure,
context.warehouseId,
'B',
minGroupOrderFetchQuantity,
{ maxFetchQuantity: maxWaveQuantity }
);
});
}
/**
* 将波次标记为自动加团中。
*
* @param {Object} context 异步处理上下文。
* @param {number[]} waveIds 波次ID集合。
* @return {Promise<void>} 无返回值。
*/
async markWaveAutoGrouping(context, waveIds) {
const waveService = this.ctx.service.systemMethods.order.wave;
await this.withPatchedCtxUser({
store_id: context.warehouseId,
warehouse_id: context.warehouseId,
}, async () => {
await waveService.batchAutoGrouping({ ids: waveIds });
});
}
/**
* 达到最大加团数时将波次结束自动加团。
*
* @param {Object} context 异步处理上下文。
* @param {number} waveId 波次ID。
* @param {number} maxWaveQuantity 最大加团数量。
* @return {Promise<void>} 无返回值。
*/
async finishAutoGroupingIfNeeded(context, waveId, maxWaveQuantity) {
const { ctx } = this;
const normalizedWaveId = Number(waveId || 0);
const normalizedMaxWaveQuantity = Number(maxWaveQuantity || 0);
if (!Number.isInteger(normalizedWaveId) || normalizedWaveId <= 0) {
return;
}
if (!Number.isInteger(normalizedMaxWaveQuantity) || normalizedMaxWaveQuantity <= 0) {
return;
}
const rows = await ctx.model.query(`
SELECT total_orders
FROM wms_wave_batch
WHERE warehouse_id = :warehouseId
AND wave_id = :waveId
LIMIT 1
`, {
replacements: {
warehouseId: context.warehouseId,
waveId: normalizedWaveId,
},
type: ctx.model.QueryTypes.SELECT,
});
const totalOrders = Number(Array.isArray(rows) && rows[0] ? rows[0].total_orders : 0);
if (!Number.isInteger(totalOrders) || totalOrders < normalizedMaxWaveQuantity) {
return;
}
const waveService = this.ctx.service.systemMethods.order.wave;
await this.withPatchedCtxUser({
store_id: context.warehouseId,
warehouse_id: context.warehouseId,
}, async () => {
await waveService.batchFinishAutoGrouping({ ids: [ normalizedWaveId ] });
});
}
/**
* 执行自动加团逻辑(仅团购),从仓库级配置读取 auto_grouping_enabled。
*
* @param {Object} context 异步处理上下文。
* @param {number} context.storeId 货主ID。
* @param {number} context.warehouseId 仓库ID。
* @return {Promise<void>} 无返回值。
*/
async runAutoGrouping(context) {
const { ctx } = this;
const warehouseSubjectConfig = await this.getStoreSubjectConfig(context.warehouseId);
if (!warehouseSubjectConfig || !warehouseSubjectConfig.auto_grouping_enabled) {
return;
}
const maxWaveQuantity = Number(warehouseSubjectConfig.max_wave_quantity || 0) > 0
? Number(warehouseSubjectConfig.max_wave_quantity)
: 500;
const structure = this.buildAutoGroupingStructure(context);
if (!structure) {
return;
}
const waveService = ctx.service.systemMethods.order.wave;
const minGroupOrderFetchQuantity = await this.withPatchedCtxUser({
store_id: context.warehouseId,
warehouse_id: context.warehouseId,
}, async () => {
return await waveService.getMinGroupOrderFetchQuantity(context.warehouseId);
});
const matchedAutoGroupingWaveId = await this.findAutoGroupingWaveId(context, structure);
if (matchedAutoGroupingWaveId > 0) {
const joined = await this.appendOrderToWave(context, matchedAutoGroupingWaveId);
if (!joined) {
return;
}
await this.finishAutoGroupingIfNeeded(context, matchedAutoGroupingWaveId, maxWaveQuantity);
// appendOrderToWave 内部已写入 ORDER_WAVE_AUTO_GROUP 日志
return;
}
const candidateCount = await this.countCandidateGroupOrders(context, structure);
if (candidateCount < minGroupOrderFetchQuantity) {
return;
}
const fetchResult = await this.createGroupingWave(
context,
structure,
minGroupOrderFetchQuantity,
maxWaveQuantity
);
const createdWaveIds = Array.isArray(fetchResult && fetchResult.wave_ids)
? fetchResult.wave_ids.filter(id => Number.isInteger(Number(id)) && Number(id) > 0).map(id => Number(id))
: [];
if (createdWaveIds.length <= 0) {
return;
}
await this.markWaveAutoGrouping(context, createdWaveIds);
await this.finishAutoGroupingIfNeeded(context, createdWaveIds[0], maxWaveQuantity);
// 写入 ORDER_WAVE_AUTO_GROUP 日志(新建波次路径)
if (context.orderId) {
try {
const waveRows = await ctx.model.query(`
SELECT wave_no FROM wms_wave_batch
WHERE warehouse_id = :warehouseId AND wave_id = :waveId
LIMIT 1
`, {
replacements: { warehouseId: context.warehouseId, waveId: createdWaveIds[0] },
type: ctx.model.QueryTypes.SELECT,
});
const waveNo = (Array.isArray(waveRows) && waveRows[0]) ? String(waveRows[0].wave_no || '').trim() : '';
const opLogService = ctx.service && ctx.service.systems && ctx.service.systems.operationLog;
if (opLogService && typeof opLogService.createOperationLogs === 'function') {
await opLogService.createOperationLogs([{
businessType: 'order',
businessId: `${context.orderId}`,
operationCode: 'ORDER_WAVE_AUTO_GROUP',
operator: { id: null, name: 'system' },
extras: {
message: `自动加团到波次 ${waveNo || createdWaveIds[0]}`,
warehouseId: context.warehouseId,
waveId: createdWaveIds[0],
waveNo,
},
}]);
}
} catch (e) {
ctx.logger.warn('[delivery_order.runAutoGrouping] 写入 ORDER_WAVE_AUTO_GROUP 日志失败', {
error: e && e.message,
orderId: context.orderId,
waveId: createdWaveIds[0],
});
}
}
}
/**
* 执行订单创建后的单步动作,单步失败不影响后续。
*
* @param {string} stepName 步骤名称。
* @param {Function} stepHandler 步骤处理函数。
* @return {Promise<void>} 无返回值。
*/
async runAsyncProcessStep(stepName, stepHandler) {
try {
await stepHandler();
} catch (error) {
this.ctx.logger.warn(`[DeliveryOrderService.asyncProcessOrderCreated] ${stepName} failed: ${error.message}`, {
step: stepName,
error: error.message,
});
}
}
// 订单异步流程
/**
* 订单创建后的异步流程。
*
* 按顺序执行:自动分配快递 -> 自动分配储位 -> 自动加团。
* 每一步都使用显式请求对象调用下游能力,单步异常不中断后续。
*
* @param {number|string} orderId 订单ID。
* @param {Object} info 当前仓库与货主上下文。
* @param {string} createChannel 订单创建渠道。
* @return {Promise<void>} 无返回值。
*/
async asyncProcessOrderCreated(orderId, info, createChannel) {
const normalizedCreateChannel = String(createChannel || '').trim().toUpperCase();
if (![ 'API', 'QM' ].includes(normalizedCreateChannel)) {
return;
}
const context = await this.buildAsyncProcessContext(orderId, info);
if (!context) {
return;
}
// 已锁定的订单不自动分配快递、储位,不自动加团
if (isLockedOrderStatus(context.order && context.order.lock_status)) {
this.ctx.logger.info('[DeliveryOrderService.asyncProcessOrderCreated] 订单已锁定,跳过自动分配快递/储位/自动加团', {
warehouseId: context.warehouseId,
orderId: context.orderId,
lockStatus: context.order.lock_status,
});
return;
}
const policyConfig = await this.getStoreWarehousePolicyConfig(context.storeId, context.warehouseId);
// 截单时间兜底:货主-仓库级未启用时,fallback 到仓库级配置
const warehouseSubjectConfig = await this.getStoreSubjectConfig(context.warehouseId);
const { cutoffEnabled, cutoffTime, allocateStartTime } = this.resolveCutoffOrderConfig(policyConfig, warehouseSubjectConfig);
// 早于开始自动分配时间或超过截单时间(开始时间晚于截单时间时截单时间视为次日),均不自动分配
const isAllocationBlocked = cutoffEnabled
&& this.isAllocationWindowClosed(allocateStartTime, cutoffTime);
// 如果需要审核,不触发自动分配快递、储位、加团
const needApproval = Number(policyConfig && policyConfig.need_order_approval) !== 0;
const isAutoAllocateExpressEnabled = !isAllocationBlocked && !needApproval && this.normalizePolicyFlag(policyConfig.auto_allocate_express);
const isAutoAllocateStorageEnabled = !isAllocationBlocked && !needApproval && this.normalizePolicyFlag(policyConfig.auto_allocate_storage);
// 记录开关判定结果,便于排查自动分配快递/储位未触发的问题
this.ctx.logger.info('[DeliveryOrderService.asyncProcessOrderCreated] 自动流程开关判定', {
warehouseId: context.warehouseId,
orderId: context.orderId,
storeId: context.storeId,
cutoffEnabled,
allocateStartTime,
cutoffTime,
isAllocationBlocked,
needApproval,
autoAllocateExpressFlag: policyConfig && policyConfig.auto_allocate_express,
autoAllocateStorageFlag: policyConfig && policyConfig.auto_allocate_storage,
isAutoAllocateExpressEnabled,
isAutoAllocateStorageEnabled,
});
if (isAutoAllocateExpressEnabled) {
await this.runAsyncProcessStep('allocateExpress', async () => {
// 不再逐单直接取号:改为写入消费队列,由定时任务按仓库+货主串行批量消费,
// 避免大批量订单创建时 N 条并发取号事务的 AB-BA 死锁。截单/未审核订单在此处不会入队。
await this.enqueueAutoWaybillAllocation(context);
});
}
if (isAutoAllocateStorageEnabled) {
await this.runAsyncProcessStep('allocateStorage', async () => {
const request = this.buildStorageAllocateRequest(context);
await this.withPatchedCtxUser({
store_id: context.warehouseId,
warehouse_id: context.warehouseId,
}, async () => {
await this.ctx.service.systems.orderStorageAllocation.allocateStorage(request);
});
});
}
if (!isAllocationBlocked && !needApproval) {
await this.runAsyncProcessStep('autoGrouping', async () => {
await this.runAutoGrouping(context);
});
}
await this.runAsyncProcessStep('waveStrategyQuickScan', async () => {
await this.withPatchedCtxUser({
store_id: context.warehouseId,
warehouse_id: context.warehouseId,
}, async () => {
const result = await this.ctx.service.systemMethods.order.wave.submitWaveStrategyQuickScanForWarehouse(
context.warehouseId
);
const taskId = result && typeof result === 'object'
? (result.taskId || result.task_id || result.id || null)
: result;
this.ctx.logger.info('[DeliveryOrderService.asyncProcessOrderCreated] wave strategy quick scan triggered', {
warehouseId: context.warehouseId,
orderId: context.orderId,
taskId,
});
});
});
}
}
module.exports = DeliveryOrderService;