961 lines
33 KiB
JavaScript
961 lines
33 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 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>} 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. 直接匹配 wms_platform.code;
|
||
* 2. 再按 wms_platfrom_setting.code 读取平台映射;
|
||
* 3. 最后才回退货主默认平台 code。
|
||
*
|
||
* @param {string} sourcePlatformCode 外部平台编码。
|
||
* @param {Object} storeSubjectConfig 货主签约配置。
|
||
* @param {Object} [info={}] 上下文信息。
|
||
* @return {Promise<Object>} 平台快照。
|
||
*/
|
||
async resolvePlatformSnapshot(sourcePlatformCode, storeSubjectConfig, info = {}) {
|
||
const platformList = await this.ctx.service.systems.platform.getPlatformList();
|
||
const externalCode = String(sourcePlatformCode || '').trim();
|
||
const defaultCode = String(storeSubjectConfig && storeSubjectConfig.default_platform_code || '').trim();
|
||
const matchedPlatform = this.findPlatformOptionByCode(platformList, externalCode);
|
||
|
||
if (matchedPlatform) {
|
||
return {
|
||
sysPlatformCode: this.getPlatformSnapshotCode(matchedPlatform, externalCode),
|
||
sysPlatformName: this.getPlatformSnapshotName(matchedPlatform),
|
||
};
|
||
}
|
||
|
||
const fallbackPlatform = this.findPlatformOptionByCode(platformList, defaultCode);
|
||
if (fallbackPlatform) {
|
||
this.ctx.logger.warn('[DeliveryOrderService.prepareOrderData] invalid 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: this.getPlatformSnapshotName(fallbackPlatform),
|
||
};
|
||
}
|
||
|
||
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: '',
|
||
};
|
||
}
|
||
|
||
/**
|
||
* 通过快递设置表解析系统快递编码。
|
||
*
|
||
* 说明: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={}] 上下文信息。
|
||
* @return {Promise<Object>} 快递快照。
|
||
*/
|
||
async resolveExpressSnapshot(logisticsCode, storeSubjectConfig, info = {}) {
|
||
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,
|
||
});
|
||
|
||
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 当前仓库与货主上下文。
|
||
* @return {Promise<Object>} 创建结果。
|
||
*/
|
||
async addOrder(data, info) {
|
||
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;
|
||
|
||
// 开启事务
|
||
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, step);
|
||
|
||
// 创建订单
|
||
const createdOrder = await DeliveryModel.create(orderData, { transaction });
|
||
const orderId = createdOrder.id;
|
||
|
||
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校验
|
||
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.addOrderToQueue(orderId, info.warehouseId);
|
||
|
||
return {
|
||
success: true,
|
||
message: '订单创建成功',
|
||
data: {
|
||
orderId,
|
||
stats: itemsInfo ? {
|
||
items_count: itemsInfo.stock_count,
|
||
items_total: itemsInfo.item_total_count,
|
||
items_weight: itemsInfo.total_weight,
|
||
} : 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 {Object} deliveryOrder 订单主信息。
|
||
* @param {Object} info 当前仓库与货主上下文。
|
||
* @param {number} step 订单步骤。
|
||
* @return {Promise<Object>} 可入库的订单数据。
|
||
*/
|
||
async prepareOrderData(deliveryOrder, info, step = DELIVERY_ORDER_STEP.PENDING_REVIEW) {
|
||
const { service } = this;
|
||
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,
|
||
});
|
||
const expressSnapshot = await this.resolveExpressSnapshot(logisticsCode, storeSubjectConfig, {
|
||
deliveryOrderCode,
|
||
warehouseId: info.warehouseId,
|
||
storeId: info.storeId,
|
||
});
|
||
|
||
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 || '',
|
||
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: 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) {
|
||
// 查找唯一键
|
||
wms_stock = await app.model.StockStore.findOne({ where: {
|
||
item_code: line.itemCode,
|
||
app_key: appKey,
|
||
warehouse_id: warehouseId,
|
||
store_id: storeId,
|
||
}, 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 stockResult = await ctx.service.systems.stockStore.getItemStorages(wms_stock.id, transaction);
|
||
if (!stockResult.success) {
|
||
errors.push(`SKU${wms_stock.id}商品《${wms_stock.item_name}》编码《${wms_stock.item_code}》\n${stockResult.error}`);
|
||
continue;
|
||
}
|
||
|
||
const { storage } = stockResult.data;
|
||
const stockId = storage.id;
|
||
|
||
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 totalQtyForStock = (stockQuantityMap.get(stockId) || 0) + planQty;
|
||
stockQuantityMap.set(stockId, totalQtyForStock);
|
||
|
||
// 记录商品重量(如果storage中有grossWeight)
|
||
if (storage.grossWeight !== undefined && storage.grossWeight !== null) {
|
||
const weight = parseFloat(storage.grossWeight) || 0;
|
||
stockWeightMap.set(stockId, weight);
|
||
} else {
|
||
// 如果库存中没有重量信息,记录0
|
||
stockWeightMap.set(stockId, 0);
|
||
}
|
||
|
||
if (storage.canUse < totalQtyForStock) {
|
||
const allowOversell = stockResult.data && stockResult.data.allow_oversell === true
|
||
? true
|
||
: (await ctx.service.systems.stockStore.getStoreWarehousePolicyConfigByStockId(stockId, transaction)).allowOversell;
|
||
|
||
if (!allowOversell) {
|
||
errors.push(`第${i + 1}行: 商品《${wms_stock.item_name}》库存不足,可用 ${storage.canUse},需求 ${totalQtyForStock}`);
|
||
stockQuantityMap.set(stockId, totalQtyForStock - planQty);
|
||
continue;
|
||
}
|
||
}
|
||
|
||
// 锁定库存
|
||
const lockResult = await ctx.service.systems.stockStore.lockItemStorages(
|
||
storage.id,
|
||
planQty,
|
||
transaction
|
||
);
|
||
|
||
if (!lockResult.success) {
|
||
errors.push(`SKU${wms_stock.id}商品《${wms_stock.item_name}》编码《${wms_stock.item_code}》\n锁定失败: ${lockResult.error}`);
|
||
stockQuantityMap.set(stockId, totalQtyForStock - planQty);
|
||
continue;
|
||
}
|
||
// ========== 库存检查逻辑结束 ==========
|
||
|
||
// 所有检查通过,准备订单行数据
|
||
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; // 商品总数
|
||
|
||
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);
|
||
|
||
// 格式化重量(保留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,
|
||
},
|
||
};
|
||
}
|
||
|
||
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;
|