1106 lines
37 KiB
JavaScript
1106 lines
37 KiB
JavaScript
'use strict';
|
||
const Service = require('egg').Service;
|
||
const { normalizeWarehouseShardId } = require('../../lib/warehouse_shard_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',
|
||
});
|
||
|
||
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);
|
||
}
|
||
|
||
/**
|
||
* 将订单操作日志逐条写入数据库。
|
||
*
|
||
* @param {Array<Object>} operationLogs 待写入的日志数组。
|
||
* @param {number|string} orderId 订单ID。
|
||
* @return {Promise<void>} 无返回值。
|
||
*/
|
||
async flushOrderOperationLogs(operationLogs, orderId) {
|
||
const { ctx } = this;
|
||
const operationLogService = ctx.service && ctx.service.systems && ctx.service.systems.operationLog;
|
||
|
||
if (!Array.isArray(operationLogs) || operationLogs.length === 0) {
|
||
return;
|
||
}
|
||
|
||
if (!operationLogService || typeof operationLogService.createOperationLog !== 'function') {
|
||
ctx.logger.warn('[DeliveryOrderService.flushOrderOperationLogs] operationLog service unavailable', {
|
||
orderId,
|
||
logs: operationLogs.length,
|
||
});
|
||
return;
|
||
}
|
||
|
||
for (const logItem of operationLogs) {
|
||
try {
|
||
const result = await operationLogService.createOperationLog({
|
||
businessType: 'order',
|
||
businessId: orderId,
|
||
operationCode: logItem.operationCode,
|
||
extras: {
|
||
message: logItem.message,
|
||
},
|
||
});
|
||
|
||
if (!result) {
|
||
ctx.logger.warn('[DeliveryOrderService.flushOrderOperationLogs] 写入操作日志失败,不影响业务', {
|
||
orderId,
|
||
operationCode: logItem.operationCode,
|
||
message: logItem.message,
|
||
});
|
||
}
|
||
} catch (error) {
|
||
ctx.logger.warn('[DeliveryOrderService.flushOrderOperationLogs] 写入操作日志异常,不影响业务', {
|
||
orderId,
|
||
operationCode: logItem.operationCode,
|
||
message: logItem.message,
|
||
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. 再匹配平台列表里的系统设置项。
|
||
*
|
||
* @param {string} sourcePlatformCode 外部平台编码。
|
||
* @param {Object} storeSubjectConfig 货主签约配置。
|
||
* @param {Object} [info={}] 上下文信息。
|
||
* @param {Array<Object>} [operationLogs=[]] 待写入的操作日志数组。
|
||
* @return {Promise<Object>} 平台快照。
|
||
*/
|
||
async resolvePlatformSnapshot(sourcePlatformCode, storeSubjectConfig, info = {}, operationLogs = []) {
|
||
const platformList = await this.ctx.service.systems.platform.getPlatformList();
|
||
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,
|
||
});
|
||
|
||
const defaultCode = String(storeSubjectConfig && storeSubjectConfig.default_platform_code || '').trim();
|
||
const fallbackPlatform = defaultCode ? this.findPlatformOptionByCode(platformList, defaultCode) : null;
|
||
const fallbackPlatformName = this.getPlatformSnapshotName(fallbackPlatform) || defaultCode;
|
||
|
||
if (defaultCode) {
|
||
this.appendOrderOperationLog(
|
||
operationLogs,
|
||
ORDER_OPERATION_CODES.PLATFORM_FALLBACK,
|
||
`平台编码${externalCode}匹配不到平台,已转为默认平台:${fallbackPlatformName}`
|
||
);
|
||
|
||
if (fallbackPlatform) {
|
||
this.ctx.logger.warn('[DeliveryOrderService.prepareOrderData] platform code fallback to store default', {
|
||
deliveryOrderCode: info.deliveryOrderCode,
|
||
warehouseId: info.warehouseId,
|
||
storeId: info.storeId,
|
||
sourcePlatformCode: externalCode,
|
||
defaultPlatformCode: defaultCode,
|
||
});
|
||
|
||
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 normalizedLogisticsCode = String(logisticsCode || '').trim();
|
||
if (!normalizedLogisticsCode) {
|
||
return '';
|
||
}
|
||
|
||
const expressSettingModel = this.ctx.model && this.ctx.model.ExpressSetting;
|
||
if (!expressSettingModel || typeof expressSettingModel.findOne !== 'function') {
|
||
return '';
|
||
}
|
||
|
||
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: [ 'express_code' ],
|
||
where,
|
||
raw: true,
|
||
});
|
||
|
||
return String(expressSetting && expressSetting.express_code || '').trim();
|
||
}
|
||
|
||
/**
|
||
* 解析订单快递快照。
|
||
*
|
||
* 优先级:
|
||
* 1. 直接匹配 wms_express.code;
|
||
* 2. 再按 wms_express_setting.code + warehouse_id 读取 express_code 映射为系统快递编码;
|
||
* 3. 最后才回退货主默认 express code。
|
||
*
|
||
* @param {string} logisticsCode 外部快递编码。
|
||
* @param {Object} storeSubjectConfig 货主签约配置。
|
||
* @param {Object} [info={}] 上下文信息。
|
||
* @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();
|
||
const defaultCode = String(storeSubjectConfig && storeSubjectConfig.default_express_code || '').trim();
|
||
const matchedExpress = this.findCodeOption(expressList, externalCode);
|
||
|
||
if (matchedExpress) {
|
||
return {
|
||
sysLogisticsCode: String(matchedExpress.express_code || matchedExpress.code || matchedExpress.value || externalCode).trim(),
|
||
sysLogisticsName: this.getOptionName(matchedExpress),
|
||
};
|
||
}
|
||
|
||
const expressSettingCode = await this.resolveExpressCodeFromSetting(externalCode, info.warehouseId);
|
||
if (expressSettingCode) {
|
||
const fallbackExpress = this.findCodeOption(expressList, expressSettingCode);
|
||
if (fallbackExpress) {
|
||
this.ctx.logger.warn('[DeliveryOrderService.prepareOrderData] invalid logistics code fallback to express setting mapping', {
|
||
deliveryOrderCode: info.deliveryOrderCode,
|
||
warehouseId: info.warehouseId,
|
||
storeId: info.storeId,
|
||
logisticsCode: externalCode,
|
||
expressSettingCode,
|
||
});
|
||
|
||
return {
|
||
sysLogisticsCode: String(fallbackExpress.express_code || fallbackExpress.code || fallbackExpress.value || expressSettingCode).trim(),
|
||
sysLogisticsName: this.getOptionName(fallbackExpress),
|
||
};
|
||
}
|
||
|
||
return {
|
||
sysLogisticsCode: expressSettingCode,
|
||
sysLogisticsName: '',
|
||
};
|
||
}
|
||
|
||
const fallbackExpress = this.findCodeOption(expressList, defaultCode);
|
||
if (fallbackExpress) {
|
||
this.ctx.logger.warn('[DeliveryOrderService.prepareOrderData] invalid logistics code fallback to store default', {
|
||
deliveryOrderCode: info.deliveryOrderCode,
|
||
warehouseId: info.warehouseId,
|
||
storeId: info.storeId,
|
||
logisticsCode: externalCode,
|
||
defaultExpressCode: defaultCode,
|
||
});
|
||
|
||
this.appendOrderOperationLog(
|
||
operationLogs,
|
||
ORDER_OPERATION_CODES.EXPRESS_FALLBACK,
|
||
`快递编码${externalCode}匹配不到快递,已转为默认快递:${this.getOptionName(fallbackExpress) || defaultCode}`
|
||
);
|
||
|
||
return {
|
||
sysLogisticsCode: String(fallbackExpress.express_code || fallbackExpress.code || fallbackExpress.value || defaultCode).trim(),
|
||
sysLogisticsName: this.getOptionName(fallbackExpress),
|
||
};
|
||
}
|
||
|
||
this.ctx.logger.warn('[DeliveryOrderService.prepareOrderData] express default not found in express service list', {
|
||
deliveryOrderCode: info.deliveryOrderCode,
|
||
warehouseId: info.warehouseId,
|
||
storeId: info.storeId,
|
||
logisticsCode: externalCode,
|
||
defaultExpressCode: defaultCode,
|
||
});
|
||
|
||
return {
|
||
sysLogisticsCode: defaultCode || externalCode,
|
||
sysLogisticsName: '',
|
||
};
|
||
}
|
||
|
||
/**
|
||
* 创建发货单。
|
||
*
|
||
* @param {Object} data 奇门/系统订单入参。
|
||
* @param {Object} info 当前仓库与货主上下文。
|
||
* @param createChannel
|
||
* @return {Promise<Object>} 创建结果。
|
||
*/
|
||
async addOrder(data, info, createChannel = '') {
|
||
const { ctx } = this;
|
||
const operationLogs = [];
|
||
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;
|
||
const normalizedCreateChannel = String(
|
||
createChannel
|
||
|| deliveryOrder.createChannel
|
||
|| deliveryOrder.create_channel
|
||
|| 'MANUAL'
|
||
).trim().toUpperCase() || 'MANUAL';
|
||
|
||
// 开启事务
|
||
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
|
||
);
|
||
|
||
// 创建订单
|
||
const createdOrder = await DeliveryModel.create(orderData, { transaction });
|
||
const orderId = createdOrder.id;
|
||
this.appendOrderOperationLog(
|
||
operationLogs,
|
||
ORDER_OPERATION_CODES.CREATE,
|
||
`订单创建成功,orderId:${orderId}`,
|
||
{ prepend: true }
|
||
);
|
||
|
||
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(','),
|
||
updated_at: new Date(),
|
||
};
|
||
|
||
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);
|
||
|
||
// 异步处理:订单入队列
|
||
await this.addOrderToQueue(orderId, info.warehouseId);
|
||
|
||
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();
|
||
|
||
return {
|
||
success: false,
|
||
message: `订单创建失败: ${error.message}`,
|
||
data: null,
|
||
};
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 根据货主仓库策略解析订单步骤。
|
||
*
|
||
* @param {Object} info 当前仓库与货主上下文。
|
||
* @param {Object|null} transaction 数据库事务。
|
||
* @return {Promise<number>} 订单步骤,需审批返回 0,免审批返回 1。
|
||
*/
|
||
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,
|
||
use_status: 1,
|
||
},
|
||
attributes: [ 'id' ],
|
||
transaction,
|
||
raw: true,
|
||
});
|
||
|
||
if (!relation) {
|
||
return DELIVERY_ORDER_STEP.PENDING_REVIEW;
|
||
}
|
||
|
||
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;
|
||
}
|
||
|
||
/**
|
||
* 准备订单主表数据。
|
||
*
|
||
* @param {Object} deliveryOrder 订单主信息。
|
||
* @param {Object} info 当前仓库与货主上下文。
|
||
* @param createChannel
|
||
* @param {number} step 订单步骤。
|
||
* @param {Array<Object>} [operationLogs=[]] 待写入的操作日志数组。
|
||
* @return {Promise<Object>} 可入库的订单数据。
|
||
*/
|
||
async prepareOrderData(
|
||
deliveryOrder,
|
||
info,
|
||
createChannel = 'MANUAL',
|
||
step = DELIVERY_ORDER_STEP.PENDING_REVIEW,
|
||
operationLogs = []
|
||
) {
|
||
const {
|
||
deliveryOrderCode,
|
||
preDeliveryOrderCode,
|
||
preDeliveryOrderId,
|
||
orderType,
|
||
warehouseCode,
|
||
orderFlag,
|
||
sourcePlatformCode,
|
||
sourcePlatformName,
|
||
createTime,
|
||
placeOrderTime,
|
||
payTime,
|
||
payNo,
|
||
shopNick,
|
||
sellerNick,
|
||
buyerNick,
|
||
operatorName,
|
||
operateTime,
|
||
totalAmount,
|
||
itemAmount,
|
||
discountAmount,
|
||
freight,
|
||
arAmount,
|
||
gotAmount,
|
||
logisticsCode,
|
||
logisticsName,
|
||
expressCode,
|
||
logisticsAreaCode,
|
||
isUrgency,
|
||
invoiceFlag,
|
||
receiverInfo,
|
||
} = deliveryOrder;
|
||
|
||
const storeSubjectConfig = await this.getStoreSubjectConfig(info.storeId);
|
||
const platformSnapshot = await this.resolvePlatformSnapshot(sourcePlatformCode, storeSubjectConfig, {
|
||
deliveryOrderCode,
|
||
warehouseId: info.warehouseId,
|
||
storeId: info.storeId,
|
||
}, operationLogs);
|
||
const expressSnapshot = await this.resolveExpressSnapshot(logisticsCode, storeSubjectConfig, {
|
||
deliveryOrderCode,
|
||
warehouseId: info.warehouseId,
|
||
storeId: info.storeId,
|
||
}, operationLogs);
|
||
|
||
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 || '',
|
||
create_channel: String(createChannel || 'MANUAL').trim().toUpperCase() || 'MANUAL',
|
||
sys_platform_code: platformSnapshot.sysPlatformCode,
|
||
sys_platform_name: platformSnapshot.sysPlatformName,
|
||
create_at: createTime ? new Date(createTime) : new Date(),
|
||
place_order_time: placeOrderTime ? new Date(placeOrderTime) : null,
|
||
pay_time: payTime ? new Date(payTime) : null,
|
||
pay_no: payNo || '',
|
||
shop_nick: shopNick,
|
||
seller_nick: sellerNick,
|
||
buyer_nick: buyerNick,
|
||
operator_name: operatorName,
|
||
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: logisticsCode || '',
|
||
logistics_name: logisticsName || '',
|
||
sys_logistics_code: expressSnapshot.sysLogisticsCode,
|
||
sys_logistics_name: expressSnapshot.sysLogisticsName,
|
||
express_code: expressCode || '',
|
||
logistics_area_code: logisticsAreaCode || '',
|
||
is_urgency: isUrgency || 'N',
|
||
invoice_flag: invoiceFlag || 'N',
|
||
status: '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 || '',
|
||
// 发件人信息(如果需要存储)
|
||
// 业务关联ID
|
||
store_id: info.storeId,
|
||
warehouse_id: info.warehouseId,
|
||
from_key: this.normalizeOrderFromKey(info.appKey),
|
||
};
|
||
}
|
||
|
||
/**
|
||
* 添加订单明细并完成库存预占。
|
||
*
|
||
* @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)
|
||
const processedItemIds = new Set();
|
||
|
||
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;
|
||
if (!line.itemId) {
|
||
// 查找唯一键(appKey 为空时不作为条件,兼容内部手动建单场景)
|
||
const stockWhere = {
|
||
item_code: line.itemCode,
|
||
warehouse_id: warehouseId,
|
||
store_id: storeId,
|
||
};
|
||
if (appKey) {
|
||
stockWhere.app_key = appKey;
|
||
}
|
||
wms_stock = await app.model.StockStore.findOne({ where: stockWhere, transaction });
|
||
} else {
|
||
wms_stock = await app.model.StockStore.findByPk(line.itemId, { transaction });
|
||
}
|
||
// 如果没有itemId,直接记录错误
|
||
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;
|
||
}
|
||
|
||
if (processedItemIds.has(itemId)) {
|
||
errors.push(`第${i + 1}行: 商品《${wms_stock.item_name}》在同一订单中重复出现`);
|
||
continue;
|
||
}
|
||
processedItemIds.add(itemId);
|
||
|
||
// 锁定库存
|
||
const lockResult = await ctx.service.systems.stockStore.lockItemStorages(
|
||
stockId,
|
||
planQty,
|
||
transaction
|
||
);
|
||
|
||
if (!lockResult.success) {
|
||
errors.push(`SKU${wms_stock.id}商品《${wms_stock.item_name}》编码《${wms_stock.item_code}》\n锁定失败: ${lockResult.error}`);
|
||
continue;
|
||
}
|
||
|
||
const totalQtyForStock = (stockQuantityMap.get(stockId) || 0) + planQty;
|
||
stockQuantityMap.set(stockId, totalQtyForStock);
|
||
|
||
// 优先使用商品主数据重量,缺失时降级为0。
|
||
const weight = parseFloat(wms_stock.gross_weight) || 0;
|
||
stockWeightMap.set(stockId, weight);
|
||
// ========== 库存检查逻辑结束 ==========
|
||
|
||
// 所有检查通过,准备订单行数据
|
||
lineData.push({
|
||
order_id: orderId,
|
||
actual_price: this.safeParseFloat(line.actualPrice, 0),
|
||
retail_price: this.safeParseFloat(line.retailPrice, 0),
|
||
ext_code: line.extCode || '',
|
||
inventory_type: line.inventoryType || '',
|
||
item_code: line.itemCode || '',
|
||
item_id: itemId,
|
||
item_name: line.itemName || '',
|
||
order_line_no: line.orderLineNo || `${i + 1}`,
|
||
owner_code: line.ownerCode || '',
|
||
plan_qty: planQty,
|
||
source_order_code: line.sourceOrderCode || '',
|
||
sub_source_order_code: line.subSourceOrderCode || '',
|
||
extend_props: line.extendProps ?
|
||
(typeof line.extendProps === 'string' ? line.extendProps : JSON.stringify(line.extendProps))
|
||
: null,
|
||
stock_id: stockId,
|
||
item_snapshot: this.buildOrderItemSnapshot(wms_stock, line),
|
||
// 可选:记录重量信息到明细
|
||
item_weight: stockWeightMap.get(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 ]) => {
|
||
// 可选:在字符串中包含重量信息
|
||
const weight = stockWeightMap.get(stockId) || 0;
|
||
return `${stockId}+${quantity}${weight > 0 ? `@${weight}` : ''}`;
|
||
});
|
||
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)); // 订单来源去重集合
|
||
// 格式化重量(保留2位小数)
|
||
total_weight = parseFloat(total_weight.toFixed(2));
|
||
|
||
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 ? '...' : ''),
|
||
});
|
||
}
|
||
|
||
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, // 创建的明细数据
|
||
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;
|
||
}
|
||
|
||
// 订单入队列(异步处理)
|
||
async addOrderToQueue(orderId, warehouseId) {
|
||
const { ctx } = this;
|
||
|
||
if (!orderId || !warehouseId) {
|
||
ctx.logger.warn('[订单入队列] 参数无效', { orderId, warehouseId });
|
||
return;
|
||
}
|
||
|
||
const cacheRedis = ctx.app && ctx.app.redis && ctx.app.redis.get ? ctx.app.redis.get('cache') : null;
|
||
if (!cacheRedis || typeof cacheRedis.publish !== 'function') {
|
||
ctx.logger.warn('[订单入队列] Redis 不可用', { orderId, warehouseId });
|
||
return;
|
||
}
|
||
|
||
const channel = `delivery_order:queue:${warehouseId}`;
|
||
|
||
try {
|
||
await cacheRedis.publish(channel, JSON.stringify({
|
||
orderId,
|
||
warehouseId,
|
||
timestamp: Date.now(),
|
||
action: 'order_created',
|
||
}));
|
||
|
||
ctx.logger.info('[订单入队列] 发布成功', {
|
||
orderId,
|
||
warehouseId,
|
||
channel,
|
||
});
|
||
} catch (error) {
|
||
ctx.logger.warn('[订单入队列] 发布失败', {
|
||
orderId,
|
||
warehouseId,
|
||
channel,
|
||
error: error.message,
|
||
});
|
||
}
|
||
}
|
||
}
|
||
|
||
module.exports = DeliveryOrderService;
|