'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} 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} operationLogs 待写入的日志数组。 * @param {number|string} orderId 订单ID。 * @param {Object} [options={}] 写入选项。 * @param {number|string} [options.warehouseId] 订单所属仓库ID。 * @param {Object} [options.transaction] 事务对象(可选)。 * @return {Promise} 无返回值。 */ 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} 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. 兜底:签约策略 default_platform_code(货主-仓库级)→ 货主 subject_config.default_platform_code。 * * @param {string} sourcePlatformCode 外部平台编码。 * @param {Object} storeSubjectConfig 货主签约配置。 * @param {Object} [policyConfig={}] 货主-仓库签约策略配置。 * @param {Object} [info={}] 上下文信息。 * @param {Array} [operationLogs=[]] 待写入的操作日志数组。 * @return {Promise} 平台快照。 */ 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, }); // 兜底优先级:签约策略(货主-仓库级)→ 货主 subject_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} 系统快递编码,未命中时返回空字符串。 */ 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} 命中的快递设置快照,未命中返回 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 -> storeSubjectConfig,均未提供时默认关闭。 * * @param {Object} storeSubjectConfig 货主签约配置。 * @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; } /** * 解析订单快递快照。 * * 优先级: * 1. 先读取是否启用外部快递编码开关; * 2. 开关关闭时,直接使用货主默认快递回填四个快递字段; * 3. 开关开启时,先匹配 wms_express_setting,再匹配 wms_express,最后回退货主默认快递。 * * @param {string} logisticsCode 外部快递编码。 * @param {Object} storeSubjectConfig 货主签约配置。 * @param {Object} [info={}] 上下文信息。 * @param {Array} [operationLogs=[]] 待写入的操作日志数组。 * @return {Promise} 快递快照。 */ 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 fallbackExpress = this.findCodeOption(expressList, defaultCode); const fallbackLogisticsCode = String( fallbackExpress && (fallbackExpress.code || fallbackExpress.value || fallbackExpress.express_code || defaultCode) || defaultCode || '' ).trim(); const fallbackLogisticsName = this.getOptionName(fallbackExpress); const explicitEnableExternalExpressCode = info && Object.prototype.hasOwnProperty.call(info, 'enableExternalExpressCode') ? info.enableExternalExpressCode : undefined; const policyConfig = info && info.policyConfig && typeof info.policyConfig === 'object' ? info.policyConfig : {}; const isEnableExternalExpressCode = this.resolveEnableExternalExpressCode( storeSubjectConfig, policyConfig, explicitEnableExternalExpressCode ); if (!isEnableExternalExpressCode) { return { logisticsCode: fallbackLogisticsCode, logisticsName: fallbackLogisticsName, sysLogisticsCode: fallbackLogisticsCode, sysLogisticsName: fallbackLogisticsName, }; } 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); return { logisticsCode: String(expressSetting.code || externalCode).trim(), logisticsName: String(expressSetting.name || '').trim(), sysLogisticsCode: matchedSysLogisticsCode, sysLogisticsName: matchedSysLogisticsName, }; } 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); return { logisticsCode: matchedLogisticsCode, logisticsName: matchedLogisticsName, sysLogisticsCode: matchedLogisticsCode, sysLogisticsName: matchedLogisticsName, }; } 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 { logisticsCode: fallbackLogisticsCode, logisticsName: fallbackLogisticsName, sysLogisticsCode: fallbackLogisticsCode, sysLogisticsName: fallbackLogisticsName, }; } 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 { logisticsCode: fallbackLogisticsCode, logisticsName: fallbackLogisticsName, sysLogisticsCode: fallbackLogisticsCode, sysLogisticsName: fallbackLogisticsName, }; } /** * 创建发货单。 * * @param {Object} data 奇门/系统订单入参。 * @param {Object} info 当前仓库与货主上下文。 * @param {string} [createChannel=''] 订单创建渠道标识。 * @return {Promise} 创建结果。 */ 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; // 请求级 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'; // 开启事务 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 ); // 创建订单 const createdOrder = await DeliveryModel.create(orderData, { transaction }); const orderId = createdOrder.id; 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(), }; 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); }); return { success: false, message: `订单创建失败: ${error.message}`, data: null, }; } } /** * 根据货主仓库策略解析订单步骤。 * 若货主与仓库之间不存在已启用已签约的记录(auth_status=2, warehouse_use_status=1),则抛出错误拒绝创建。 * * @param {Object} info 当前仓库与货主上下文,需包含 storeId 和 warehouseId。 * @param {Object|null} transaction 数据库事务。 * @return {Promise} 订单步骤,需审批返回 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 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} 解析后的操作人名称。 */ 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} [operationLogs=[]] 待写入的操作日志数组。 * @param {Object} [requestExtendProps] 请求级扩展属性,携带 ewaybill_order_code 等关键字段。 * @return {Promise} 可入库的订单数据。 */ async prepareOrderData( deliveryOrder, info, createChannel = 'MANUAL', step = DELIVERY_ORDER_STEP.PENDING_REVIEW, operationLogs = [], requestExtendProps ) { const { deliveryOrderCode, preDeliveryOrderCode, preDeliveryOrderId, orderType, warehouseCode, orderFlag, sourcePlatformCode, sourcePlatformName, createTime, placeOrderTime, payTime, payNo, shopNick, sellerNick, buyerNick, buyerMessage, sellerMessage, remark, operatorName, operateTime, totalAmount, itemAmount, discountAmount, freight, arAmount, gotAmount, logisticsCode, expressCode, logisticsAreaCode, isUrgency, invoiceFlag, receiverInfo, } = deliveryOrder; const storeSubjectConfig = await this.getStoreSubjectConfig(info.storeId); const policyConfig = await this.getStoreWarehousePolicyConfig(info.storeId, info.warehouseId); const enableExternalExpressCode = this.resolveEnableExternalExpressCode(storeSubjectConfig, policyConfig); const platformSnapshot = await this.resolvePlatformSnapshot(sourcePlatformCode, storeSubjectConfig, policyConfig, { deliveryOrderCode, warehouseId: info.warehouseId, storeId: info.storeId, }, operationLogs); const expressSnapshot = await this.resolveExpressSnapshot(logisticsCode, storeSubjectConfig, { deliveryOrderCode, warehouseId: info.warehouseId, storeId: info.storeId, policyConfig, enableExternalExpressCode, }, operationLogs); const resolvedOperatorName = await this.resolveOperatorName(operatorName, createChannel, info); 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, 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 || '', 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: this.normalizeOrderFromKey(info.appKey), }; } /** * 添加订单明细并完成库存预占。 * * @param {Object|Array} orderLines 订单明细数据。 * @param {number} orderId 订单主键。 * @param {Object} info 当前仓库与货主上下文。 * @param {Object} transaction 数据库事务。 * @return {Promise} 明细创建与库存统计结果。 */ 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 时跳过 stock_store 查表,直接使用 if (line.stockId && line.stockId > 0) { wms_stock = { id: line.stockId, stock_id: line.stockId, item_name: line.itemName || '', item_code: line.itemCode || '', gross_weight: 0, }; } else 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 }); } 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); // ===== 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); const weight = 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)); // 订单来源去重集合 // 格式化重量(保留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 ? '...' : ''), }); } 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, // 创建的明细数据 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} 回调执行结果。 */ 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} 异步处理上下文。 */ 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 { orders: [{ order_id: Number(order.id || context.orderId || 0), business_key: 1, sys_platform_code: String(order.sys_platform_code || '').trim(), logistics_code: String(order.logistics_code || '').trim(), store_id: Number(order.store_id || context.storeId || 0), warehouse_id: Number(order.warehouse_id || context.warehouseId || 0), }], }; } /** * 构建储位分配显式请求体。 * * @param {Object} context 异步处理上下文。 * @return {Object} 储位分配请求。 */ buildStorageAllocateRequest(context) { return { allow_storage_location: true, order_ids: [ Number(context && context.orderId || 0) ], }; } /** * 读取货主-仓库策略配置。 * * @param {number} storeId 货主ID。 * @param {number} warehouseId 仓库ID。 * @return {Promise} 策略配置。 */ 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}} 最终生效的截单开关与截单时间。 */ 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'; // 货主-仓库级已启用截单,直接使用 if (policyEnabled) { return { cutoffEnabled: true, cutoffTime: policyTime, }; } // 货主-仓库级未启用,由仓库级兜底 if (warehouseSubjectConfig && warehouseSubjectConfig.cutoff_order_enabled) { const warehouseTime = (typeof warehouseSubjectConfig.cutoff_order_time === 'string' ? warehouseSubjectConfig.cutoff_order_time.trim() : '') || '18:00'; return { cutoffEnabled: true, cutoffTime: warehouseTime, }; } return { cutoffEnabled: false, cutoffTime: '18: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; } /** * 构建自动加团结构信息。 * * @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} 命中的波次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} 是否成功加入。 */ 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' ], transaction, lock: transaction.LOCK.UPDATE, }); if (!orderRow) { 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, }, 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} 可参与数量。 */ 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' }, 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} 抓取结果。 */ 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} 无返回值。 */ 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} 无返回值。 */ 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} 无返回值。 */ 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} 无返回值。 */ 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} 无返回值。 */ 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; } const policyConfig = await this.getStoreWarehousePolicyConfig(context.storeId, context.warehouseId); // 截单时间兜底:货主-仓库级未启用时,fallback 到仓库级配置 const warehouseSubjectConfig = await this.getStoreSubjectConfig(context.warehouseId); const { cutoffEnabled, cutoffTime } = this.resolveCutoffOrderConfig(policyConfig, warehouseSubjectConfig); const isCutoffActive = cutoffEnabled && this.isPastCutoffTime(cutoffTime); // 如果需要审核,不触发自动分配快递、储位、加团 const needApproval = Number(policyConfig && policyConfig.need_order_approval) !== 0; const isAutoAllocateExpressEnabled = !isCutoffActive && !needApproval && this.normalizePolicyFlag(policyConfig.auto_allocate_express); const isAutoAllocateStorageEnabled = !isCutoffActive && !needApproval && this.normalizePolicyFlag(policyConfig.auto_allocate_storage); if (isAutoAllocateExpressEnabled) { await this.runAsyncProcessStep('allocateExpress', async () => { const request = this.buildExpressAllocateRequest(context); await this.withPatchedCtxUser({ store_id: context.warehouseId, warehouse_id: context.warehouseId, }, async () => { await this.ctx.service.systemMethods.order.pendingOrder.allocateExpressCode(request); }); }); } 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 (!isCutoffActive && !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;