'use strict'; const { Service } = require('egg'); const { isInterceptedOrderStatus } = require('../../lib/intercept_guard'); const { isLockedOrderStatus } = require('../../lib/lock_guard'); const DEFAULT_CACHE_TTL_SECONDS = 600; const DEFAULT_EXPRESS_PRODUCT_TYPE_CACHE_TTL_SECONDS = 60 * 60; const DEFAULT_WAYBILL_BATCH_SIZE = 10; const WAYBILL_EXCEPTION_STEP = 3; const WAYBILL_ASYNC_SINGLE_ORDER_PLATFORM_CODES = new Set([ 'cainiao', 'pdd' ]); const WAYBILL_ORDER_DELIVERY_MIN_ATTRIBUTES = Object.freeze([ 'id', 'store_id', 'warehouse_id', 'delivery_order_code', 'source_platform_code', 'source_platform_name', 'oaid_order_source_code', 'sys_platform_code', 'sys_platform_name', 'order_type', 'status', 'post_status', 'step', 'order_flag', 'from_key', 'create_at', 'place_order_time', 'pay_time', 'operate_time', 'delivery_time', 'name', 'tel', 'mobile', 'email', 'country_code', 'province', 'city', 'area', 'town', 'detail_address', 'zip_code', 'total_amount', 'item_amount', 'discount_amount', 'freight', 'ar_amount', 'got_amount', 'items', 'items_count', 'items_total', 'items_weight', 'logistics_name', 'sys_logistics_code', 'sys_logistics_name', 'express_code', 'logistics_area_code', 'oaid', 'source_order_codes', 'logistics_code', 'extend_props', 'buyer_nick', 'pay_no', 'from_key', ]); class ExpressService extends Service { /** * 生成快递列表缓存键。 * * @param {number|string} warehouseId 仓库ID * @param {boolean} [systemOnly=false] 是否仅返回系统基础快递列表 * @param {string} [systemExpressCode=''] 系统快递编码 * @return {string} 缓存键 */ getExpressListCacheKey(warehouseId = 0, systemOnly = false, systemExpressCode = '') { const normalizedExpressCode = String(systemExpressCode || '').trim().toUpperCase(); if (systemOnly) { if (normalizedExpressCode) { return `express:list:system:${normalizedExpressCode}`; } return 'express:list:system'; } const normalizedWarehouseId = Number(warehouseId || 0); if (Number.isFinite(normalizedWarehouseId) && normalizedWarehouseId > 0) { if (normalizedExpressCode) { return `express:list:${normalizedWarehouseId}:express:${normalizedExpressCode}`; } return `express:list:${normalizedWarehouseId}`; } if (normalizedExpressCode) { return `express:list:express:${normalizedExpressCode}`; } return 'express:list'; } /** * 获取当前上下文中的仓库ID。 * * @return {number} 仓库ID,未获取到时返回 0 */ getCurrentWarehouseId() { const warehouseId = Number(this.ctx && this.ctx.user && this.ctx.user.store_id || 0); if (Number.isFinite(warehouseId) && warehouseId > 0) { return warehouseId; } return 0; } /** * 构建快递号分配链路追踪ID。 * * 优先使用入参中的 trace_id/traceId,其次读取上下文 trace 信息,最后兜底生成。 * * @param {Object} [data={}] 入参。 * @param {string} [fallback=''] 兜底标识。 * @return {string} 追踪ID。 */ buildWaybillTraceId(data = {}, fallback = '') { const normalizedData = data && typeof data === 'object' ? data : {}; const ctxTraceId = this.ctx && this.ctx.traceId !== undefined ? this.ctx.traceId : this.ctx && this.ctx.requestId !== undefined ? this.ctx.requestId : this.ctx && this.ctx.state && this.ctx.state.traceId !== undefined ? this.ctx.state.traceId : ''; const normalizedTraceId = String( normalizedData.trace_id || normalizedData.traceId || ctxTraceId || fallback || '' ).trim(); if (normalizedTraceId) { return normalizedTraceId; } return `waybill_trace_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`; } /** * 获取订单日志使用的操作人信息。 * * 取值优先级:employees_id/employees_name -> operator_id/operator_name -> id/real_name/name。 * * @return {{ id: string|null, name: string }} 操作人信息。 */ getOrderLogOperator() { const stateUser = this.ctx && this.ctx.state && this.ctx.state.user && typeof this.ctx.state.user === 'object' ? this.ctx.state.user : null; const ctxUser = this.ctx && this.ctx.user && typeof this.ctx.user === 'object' ? this.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。 * * @param {number|string|null} [preferredWarehouseId=null] 优先仓库ID。 * @return {number|string|null} 仓库ID。 */ getOrderLogWarehouseId(preferredWarehouseId = null) { const candidates = [ preferredWarehouseId, this.getCurrentWarehouseId(), this.ctx && this.ctx.user ? this.ctx.user.warehouse_id : null, this.ctx && this.ctx.user ? this.ctx.user.store_id : null, ]; for (const candidate of candidates) { if (candidate === undefined || candidate === null || candidate === '') { continue; } return candidate; } return null; } /** * 为分配快递失败订单写入订单操作日志。 * * @param {Array} orderIds 订单ID数组。 * @param {string} errorMessage 失败原因。 * @param {number|string|null} warehouseId 仓库ID。 * @return {Promise} 无返回值。 */ async createAllocateExpressFailureLogs(orderIds = [], errorMessage = '', warehouseId = null) { const operationLogService = this.service && this.service.systems && this.service.systems.operationLog; if (!operationLogService || typeof operationLogService.createOperationLogs !== 'function') { return; } const operator = this.getOrderLogOperator(); const normalizedWarehouseId = this.getOrderLogWarehouseId(warehouseId); const normalizedOrderIds = Array.from(new Set((Array.isArray(orderIds) ? orderIds : []) .map(orderId => Number(orderId)) .filter(orderId => Number.isFinite(orderId) && orderId > 0))); const normalizedErrorMessage = String(errorMessage || '').trim() || '未知异常'; const payloads = normalizedOrderIds.map(orderId => ({ businessType: 'order', businessId: String(orderId), operationCode: 'ORDER_EXPRESS_ALLOCATE_FAILED', operator, extras: { message: `分配快递失败:${normalizedErrorMessage}`, warehouseId: normalizedWarehouseId, externalLogType: 'API', }, })); await operationLogService.createOperationLogs(payloads); } /** * 将 business_key 规范化为内部可处理的正整数列表。 *【已使用】 * @param {*} businessKey 原始 business_key 值。 * @return {Array} 正整数业务键列表。 */ normalizeWaybillBusinessKeys(businessKey = null) { const rawBusinessKeys = Array.isArray(businessKey) ? businessKey.flat(Infinity) : [ businessKey ]; const normalizedBusinessKeys = []; const seenBusinessKeys = new Set(); for (const rawBusinessKey of rawBusinessKeys) { const normalizedBusinessKey = Number(rawBusinessKey); if (!Number.isInteger(normalizedBusinessKey) || normalizedBusinessKey <= 0 || seenBusinessKeys.has(normalizedBusinessKey)) { continue; } seenBusinessKeys.add(normalizedBusinessKey); normalizedBusinessKeys.push(normalizedBusinessKey); } return normalizedBusinessKeys; } /** * 规范化运单创建时携带的平台上下文编码。 * * 该值仅作为异步后处理的辅助上下文,不参与主流程分组与去重。 *【已使用】 * @param {Object} order 原始订单。 * @return {string} 平台编码,小写。 */ normalizeWaybillCreatePlatformCode(order = {}) { if (!order || typeof order !== 'object') { return ''; } const expressPlatform = order.wms_express_platform && typeof order.wms_express_platform === 'object' ? order.wms_express_platform : (order.wmsExpressPlatform && typeof order.wmsExpressPlatform === 'object' ? order.wmsExpressPlatform : null); const rawPlatformCode = (expressPlatform && (expressPlatform.platform_code || expressPlatform.platformCode)) || (typeof order.wms_express_platform === 'string' ? order.wms_express_platform : '') || (typeof order.wmsExpressPlatform === 'string' ? order.wmsExpressPlatform : '') || order.platform_code || order.platformCode || order.express_platform_code || order.expressPlatformCode || ''; return String(rawPlatformCode).trim().toLowerCase(); } /** * 规范化运单余额相关策略配置。 * * @param {*} policyConfig 策略配置。 * @return {Object} 规范化后的策略配置对象。 */ normalizeWaybillPolicyConfig(policyConfig) { const storeWarehouseModel = this.ctx.model && this.ctx.model.StoreWarehouse; if (storeWarehouseModel && typeof storeWarehouseModel.normalizePolicyConfig === 'function') { try { return storeWarehouseModel.normalizePolicyConfig(policyConfig, { fieldName: 'policy_config', allowEmpty: true, sanitizeOnly: true, }) || {}; } catch (error) { this.ctx.logger.warn('[ExpressService.normalizeWaybillPolicyConfig] policy_config 解析失败: %s', error.message); return {}; } } if (policyConfig && typeof policyConfig === 'object' && !Array.isArray(policyConfig)) { return policyConfig; } if (typeof policyConfig !== 'string') { return {}; } try { const parsedConfig = JSON.parse(policyConfig); if (parsedConfig && typeof parsedConfig === 'object' && !Array.isArray(parsedConfig)) { return parsedConfig; } } catch (error) { this.ctx.logger.warn('[ExpressService.normalizeWaybillPolicyConfig] policy_config 解析失败: %s', error.message); } return {}; } /** * 生成运单余额不足的异常文案。 * * @param {Object} options 文案参数。 * @param {number} options.availableQuantity 当前可用余额。 * @param {number} options.requestedQuantity 本次请求数量。 * @param {number} options.shortageQuantity 不足数量。 * @param {number} options.expressQuota 快递额度。 * @param {number} options.usedQuantity 已用额度。 * @return {string} 异常文案。 */ buildWaybillBalanceExceptionText({ availableQuantity = 0, requestedQuantity = 0, shortageQuantity = 0, expressQuota = 0, usedQuantity = 0, } = {}) { return `货主快递余额不足:余额 ${Math.max(0, Number(usedQuantity) || 0) + Math.max(0, Number(availableQuantity) || 0)},已用 ${Math.max(0, Number(usedQuantity) || 0)},可用 ${Math.max(0, Number(availableQuantity) || 0)},额度 ${Math.max(0, Number(expressQuota) || 0)},需要 ${Math.max(0, Number(requestedQuantity) || 0)},不足 ${Math.max(0, Number(shortageQuantity) || 0)}`; } /** * 规范化运单创建入参并按订单与业务键去重。 * * 仅当输入已经完成基础规整时,直接做最小必要校验与去重; * 如果还保留数组业务键或缺失主字段,则回退到完整规整流程。 *【已使用】 * @param {Array} orders 原始运单创建入参,business_key 可为单值或数组。 * @return {Array} 规范化后的订单列表。 */ async normalizeWaybillCreateOrders(orders = []) { const normalizedOrders = Array.isArray(orders) ? orders : []; const normalizedOrderMap = new Map(); await this.loadExpressList(); for (const order of normalizedOrders) { if (!order || typeof order !== 'object') { continue; } const orderId = Number(order.id || order.order_id); const businessKeys = this.normalizeWaybillBusinessKeys(order.business_key); if (!Number.isInteger(orderId) || orderId <= 0 || businessKeys.length === 0) { continue; } const sysPlatformCode = String(order.sys_platform_code || order.sysPlatformCode || '').trim(); const logisticsCode = String(order.logistics_code || order.logisticsCode || '').trim(); const platformCode = this.normalizeWaybillCreatePlatformCode(order); for (const businessKey of businessKeys) { const orderKey = `${orderId}:${businessKey}`; if (normalizedOrderMap.has(orderKey)) { continue; } normalizedOrderMap.set(orderKey, { order_id: orderId, business_key: businessKey, ...(sysPlatformCode ? { sys_platform_code: sysPlatformCode } : {}), ...(logisticsCode ? { logistics_code: logisticsCode } : {}), ...(platformCode ? { platform_code: platformCode } : {}), }); } } return Array.from(normalizedOrderMap.values()); } /** * 根据订单主表记录构建签约关系分组,并标记缺失订单。 *【已使用】 * @param {Array} normalizedOrders 规范化后的订单列表。 * @param {Array} orderDeliveryRows 订单主表查询结果。 * @param {number} currentWarehouseId 当前仓库 ID。 * @return {Object} 分组结果,包含 relationGroupMap 和 missingOrderIds。 */ buildWaybillCreateRelationGroups(normalizedOrders = [], orderDeliveryRows = [], currentWarehouseId = 0) { const orderDeliveryMap = new Map(); for (const row of Array.isArray(orderDeliveryRows) ? orderDeliveryRows : []) { const orderId = Number(row && row.id); if (Number.isFinite(orderId) && orderId > 0) { orderDeliveryMap.set(orderId, row); } } const relationGroupMap = new Map(); const missingOrderIds = []; for (const order of Array.isArray(normalizedOrders) ? normalizedOrders : []) { const orderRow = orderDeliveryMap.get(order.order_id); if (!orderRow) { missingOrderIds.push(order.order_id); continue; } const storeId = Number(orderRow.store_id || 0); const warehouseId = Number(orderRow.warehouse_id || currentWarehouseId); if (!Number.isFinite(storeId) || storeId <= 0 || !Number.isFinite(warehouseId) || warehouseId <= 0) { missingOrderIds.push(order.order_id); continue; } const relationKey = `${storeId}:${warehouseId}`; let relationGroup = relationGroupMap.get(relationKey); if (!relationGroup) { relationGroup = { store_id: storeId, warehouse_id: warehouseId, orders: [], }; relationGroupMap.set(relationKey, relationGroup); } relationGroup.orders.push({ ...order, store_id: storeId, warehouse_id: warehouseId, }); } return { relationGroupMap, missingOrderIds, }; } /** * 处理签约关系分组中的可创建与失败订单。 *【已使用】 * @param {Map} relationGroupMap 签约关系分组。 * @param {Map} relationMap 签约关系记录映射。 * @return {Promise} 处理结果,包含 successOrderKeySet、failedOrdersByReason 和 balanceWarnings。 */ async collectWaybillRelationProcessingState(relationGroupMap, relationMap) { const successOrderKeySet = new Set(); const failedOrdersByReason = new Map(); const balanceWarnings = []; for (const relationGroup of relationGroupMap.values()) { const relationKey = `${relationGroup.store_id}:${relationGroup.warehouse_id}`; const relation = relationMap.get(relationKey); if (!relation) { const exceptionText = '签约关系不存在,无法创建运单'; const failedOrderIds = relationGroup.orders.map(order => order.order_id); failedOrdersByReason.set(exceptionText, (failedOrdersByReason.get(exceptionText) || []).concat(failedOrderIds)); continue; } const policyConfig = this.normalizeWaybillPolicyConfig(relation.policy_config); const expressQuota = Math.max(0, Number(policyConfig.express_quota || 0) || 0); const requestCount = relationGroup.orders.length; const currentPrintQuantity = Number(relation.print_quantity || 0); const currentLockedQuantity = Number(relation.print_quantity_locked || 0); const availableQuantity = currentPrintQuantity - currentLockedQuantity; const allowedQuantity = Math.max(0, availableQuantity + expressQuota); const successCount = Math.min(requestCount, allowedQuantity); const failedCount = requestCount - successCount; const successOrders = relationGroup.orders.slice(0, successCount); const failedOrders = relationGroup.orders.slice(successCount); this.ctx.logger.info(`[waybill-balance] store_id=${relation.store_id} warehouse_id=${relation.warehouse_id} print_quantity=${currentPrintQuantity} print_quantity_locked=${currentLockedQuantity} availableQuantity=${availableQuantity} expressQuota=${expressQuota} allowedQuantity=${allowedQuantity} requestCount=${requestCount} successCount=${successCount} failedCount=${failedCount}`); for (const order of successOrders) { successOrderKeySet.add(`${order.order_id}:${order.business_key}`); } if (failedCount > 0) { const exceptionText = this.buildWaybillBalanceExceptionText({ availableQuantity, requestedQuantity: requestCount, shortageQuantity: failedCount, expressQuota, usedQuantity: Math.max(0, currentLockedQuantity), }); const failedOrderIds = failedOrders.map(order => order.order_id); failedOrdersByReason.set(exceptionText, (failedOrdersByReason.get(exceptionText) || []).concat(failedOrderIds)); } } return { successOrderKeySet, failedOrdersByReason, balanceWarnings, }; } /** * 根据成功订单、订单主表快照和已存在快递记录,统计需要新增锁定的余额数量。 * * 只统计真正会进入 `rowsToCreate` 的记录,避免把已存在且状态不同的记录重复计入。 * * @param {Array} successOrders 成功订单列表。 * @param {Map} orderDeliveryMap 订单主表快照映射。 * @param {Map} existingMap 已存在快递记录映射。 * @return {Map} 关系分组锁定统计。 */ buildWaybillRelationLockMap(successOrders = [], orderDeliveryMap = new Map(), existingMap = new Map()) { const relationLockMap = new Map(); for (const order of Array.isArray(successOrders) ? successOrders : []) { const orderKey = `${order.order_id}:${order.business_key}`; if (existingMap.has(orderKey)) { continue; } const orderDelivery = orderDeliveryMap.get(Number(order.order_id)); const storeId = Number(orderDelivery && orderDelivery.store_id) || 0; const warehouseId = Number(orderDelivery && orderDelivery.warehouse_id) || 0; if (!Number.isFinite(storeId) || storeId <= 0 || !Number.isFinite(warehouseId) || warehouseId <= 0) { continue; } const relationKey = `${storeId}:${warehouseId}`; const currentRelationLock = relationLockMap.get(relationKey) || { store_id: storeId, warehouse_id: warehouseId, locked_quantity: 0, }; currentRelationLock.locked_quantity += 1; relationLockMap.set(relationKey, currentRelationLock); } return relationLockMap; } /** * 按店铺和仓库分组锁定新增的运单余额。 * * @param {Map} relationLockMap 关系分组锁定统计。 * @param {Map} relationMap 签约关系记录映射。 * @param {Object} storeWarehouseModel 签约关系模型。 * @param {Object} transaction 数据库事务。 * @return {Promise} 无返回值。 */ async lockWaybillRelationBalance(relationLockMap, relationMap, storeWarehouseModel, transaction) { if (!relationLockMap || relationLockMap.size === 0) { return; } for (const relationLock of relationLockMap.values()) { const relationKey = `${relationLock.store_id}:${relationLock.warehouse_id}`; const relation = relationMap.get(relationKey); if (!relation) { continue; } const currentLockedQuantity = Number(relation.print_quantity_locked || 0); const incrementQuantity = Number(relationLock.locked_quantity || 0); if (incrementQuantity <= 0) { continue; } await storeWarehouseModel.update({ print_quantity_locked: currentLockedQuantity + incrementQuantity, }, { where: { id: relation.id, }, transaction, }); } } /** * 将运单失败订单批量回写为异常状态。 * * @param {Object} orderDeliveryModel 订单主表模型。 * @param {Array} orderIds 订单ID 列表。 * @param {string} exceptionText 异常信息。 * @param {Object} transaction 数据库事务。 * @return {Promise} 无返回值。 */ async markWaybillOrdersAsException(orderDeliveryModel, orderIds = [], exceptionText = '', transaction) { const { Op } = this.app.Sequelize; const normalizedOrderIds = Array.from(new Set((Array.isArray(orderIds) ? orderIds : []) .map(orderId => Number(orderId)) .filter(orderId => Number.isFinite(orderId) && orderId > 0))); if (normalizedOrderIds.length === 0 || !exceptionText) { return; } await orderDeliveryModel.update({ inspection_status: 'error', step: WAYBILL_EXCEPTION_STEP, order_flag: exceptionText, updated_at: new Date(), }, { where: { id: { [Op.in]: normalizedOrderIds, }, status: { [Op.ne]: 'cancel', }, // 保护配送中(step=4)订单不被回退为异常状态 step: { [Op.ne]: 4, }, }, transaction, }); } /** * 批量回写运单创建失败订单的异常状态。 *【已使用】 * @param {Object} orderDeliveryModel 订单主表模型。 * @param {Map>} failedOrdersByReason 失败原因与订单 ID 映射。 * @param {Object} transaction 数据库事务。 * @return {Promise} 无返回值。 */ async writeWaybillOrderExceptions(orderDeliveryModel, failedOrdersByReason = new Map(), transaction) { if (!failedOrdersByReason || typeof failedOrdersByReason.forEach !== 'function') { return; } for (const [ exceptionText, orderIds ] of failedOrdersByReason.entries()) { await this.markWaybillOrdersAsException(orderDeliveryModel, orderIds, exceptionText, transaction); } } /** * 补写 dispatch 表订单的 order_flag 异常信息。 * dispatch 表中的配送中订单(step=4)不应回退 step,仅记录异常标记。 * * @param {Array} dispatchOrderDeliveryRows dispatch 表中的订单行。 * @param {Map>} failedOrdersByReason 失败原因与订单 ID 映射。 * @param {Object} transaction 数据库事务。 * @return {Promise} 无返回值。 */ async writeDispatchOrderFlags(dispatchOrderDeliveryRows = [], failedOrdersByReason = new Map(), transaction) { if (!failedOrdersByReason || typeof failedOrdersByReason.forEach !== 'function') { return; } const { Op } = this.app.Sequelize; const dispatchOrderIdSet = new Set( (Array.isArray(dispatchOrderDeliveryRows) ? dispatchOrderDeliveryRows : []) .map(row => Number(row && row.id)) .filter(id => Number.isFinite(id) && id > 0) ); if (dispatchOrderIdSet.size === 0) { return; } this.ctx.logger.info('[ExpressService.writeDispatchOrderFlags] 入口 dispatchOrderIds=%s failedReasons=%d', Array.from(dispatchOrderIdSet).join(','), failedOrdersByReason.size); // 找到同时属于 dispatch 表且失败的订单 const dispatchFactory = this.ctx.model && this.ctx.model.OrderDeliveryFactory; if (!dispatchFactory || typeof dispatchFactory.getDispatchModel !== 'function') { this.ctx.logger.warn('[ExpressService.writeDispatchOrderFlags] dispatchFactory 不可用'); return; } const currentWarehouseId = this.getCurrentWarehouseId(); if (!currentWarehouseId) return; for (const [ exceptionText, orderIds ] of failedOrdersByReason.entries()) { const failedDispatchIds = (Array.isArray(orderIds) ? orderIds : []) .map(id => Number(id)) .filter(id => dispatchOrderIdSet.has(id)); if (failedDispatchIds.length === 0) continue; this.ctx.logger.info('[ExpressService.writeDispatchOrderFlags] 准备写入 order_flag: ids=%s reason=%s', failedDispatchIds.join(','), exceptionText); try { const dispatchModel = await dispatchFactory.getDispatchModel(currentWarehouseId); if (dispatchModel && typeof dispatchModel.update === 'function') { await dispatchModel.update({ order_flag: exceptionText, updated_at: new Date(), }, { where: { id: { [Op.in]: failedDispatchIds }, status: { [Op.ne]: 'cancel' }, }, transaction, }); this.ctx.logger.info('[ExpressService.writeDispatchOrderFlags] 写入成功 ids=%s', failedDispatchIds.join(',')); } } catch (err) { this.ctx.logger.warn('[ExpressService.writeDispatchOrderFlags] 写入 dispatch order_flag 失败: %s', err && err.message ? err.message : err); } } } /** * 将运单异步后处理失败订单批量回写为错误状态。 * * @param {Object} orderDeliveryModel 订单主表模型。 * @param {Array} orderIds 订单ID 列表。 * @param {string} errorMessage 错误信息。 * @param {Object} [extraWhere={}] 追加 where 约束,用于限制更新边界。 * @return {Promise} 无返回值。 */ async markWaybillAsyncOrdersAsError(orderDeliveryModel, orderIds = [], errorMessage = '', extraWhere = {}) { if (!orderDeliveryModel || typeof orderDeliveryModel.update !== 'function') { return; } const { Op } = this.app.Sequelize; const normalizedOrderIds = Array.from(new Set((Array.isArray(orderIds) ? orderIds : []) .map(orderId => Number(orderId)) .filter(orderId => Number.isFinite(orderId) && orderId > 0))); const normalizedErrorMessage = String(errorMessage || '').trim() || '接口调用失败'; if (normalizedOrderIds.length === 0) { return; } const normalizedExtraWhere = extraWhere && typeof extraWhere === 'object' && !Array.isArray(extraWhere) ? { ...extraWhere } : {}; const where = { ...normalizedExtraWhere, id: { [Op.in]: normalizedOrderIds, }, }; await orderDeliveryModel.update({ post_status: 'error', step: 3, order_flag: normalizedErrorMessage, updated_at: new Date(), }, { where: { ...where, status: { [Op.ne]: 'cancel', }, // 保护配送中(step=4)订单不被回退为异常状态 step: { [Op.ne]: 4, }, }, }); } /** * 生成合并后的快递项展示名称。 * * @param {string} settingCode 快递设置编码 * @param {Object} expressItem 系统快递项 * @return {string} 展示名称 */ buildMergedExpressLabel(settingCode, expressItem) { const normalizedSettingCode = String(settingCode || '').trim(); const expressName = String(expressItem && (expressItem.name || expressItem.label || expressItem.code || expressItem.value) || '').trim(); if (!normalizedSettingCode) { return expressName; } if (!expressName) { return normalizedSettingCode; } return `${normalizedSettingCode} (${expressName})`; } /** * 规范化快递设置记录。 * * @param {Object} row 数据库记录 * @param {Map} expressMap 系统快递映射 * @return {Object|null} 规范化后的记录 */ normalizeExpressSettingRow(row, expressMap) { if (!row || typeof row !== 'object') { return null; } const code = String(row.code || '').trim(); if (!code) { return null; } const expressCode = String(row.express_code || '').trim(); const expressItem = expressMap instanceof Map ? expressMap.get(expressCode) : null; const settingName = String(row.name || '').trim(); const label = settingName ? `${code} (${settingName})` : this.buildMergedExpressLabel(code, expressItem); return { code, name: settingName || code, value: code, label, is_system_setting: true, id: row.id === undefined || row.id === null ? null : row.id, alias: String(row.name || '').trim(), express_code: String((expressItem && (expressItem.code || expressItem.value)) || expressCode || '').trim(), }; } /** * 从数据库加载快递设置列表。 * * @param {number|string} warehouseId 仓库ID * @param {string} [systemExpressCode=''] 系统快递编码 * @return {Promise} 快递设置列表 */ async loadExpressSettingListFromDatabase(warehouseId = 0, systemExpressCode = '') { const normalizedWarehouseId = Number(warehouseId || 0); if (!Number.isFinite(normalizedWarehouseId) || normalizedWarehouseId <= 0) { return []; } const normalizedExpressCode = String(systemExpressCode || '').trim().toUpperCase(); const expressSettingModel = this.ctx.model && this.ctx.model.ExpressSetting; if (!expressSettingModel || typeof expressSettingModel.findAll !== 'function') { return []; } const where = { warehouse_id: normalizedWarehouseId, deleted_at: null, }; if (normalizedExpressCode) { where.express_code = normalizedExpressCode; } const rows = await expressSettingModel.findAll({ attributes: [ 'id', 'code', 'name', 'express_code' ], where, order: [[ 'code', 'ASC' ]], raw: true, }); if (!Array.isArray(rows)) { return []; } return rows; } /** * 构建仓库快递自定义编码列表。 * * 仅返回快递设置记录,不合并系统快递记录;用于按快递公司编码筛选场景。 * * @param {Array} expressList 系统快递列表 * @param {Array} expressSettingList 快递设置列表 * @return {Array} 自定义编码列表 */ buildExpressSettingCustomCodeList(expressList, expressSettingList) { const normalizedExpressList = Array.isArray(expressList) ? expressList : []; const expressMap = new Map(); for (const expressItem of normalizedExpressList) { if (!expressItem || typeof expressItem !== 'object') { continue; } const code = String(expressItem.code || expressItem.value || '').trim(); if (!code || expressMap.has(code)) { continue; } expressMap.set(code, expressItem); } const result = []; for (const row of Array.isArray(expressSettingList) ? expressSettingList : []) { const mergedItem = this.normalizeExpressSettingRow(row, expressMap); if (!mergedItem) { continue; } result.push(mergedItem); } return result; } /** * 合并系统快递和快递设置列表。 * * @param {Array} expressList 系统快递列表 * @param {Array} expressSettingList 快递设置列表 * @return {Array} 合并后的快递列表 */ buildMergedExpressList(expressList, expressSettingList) { const mergedList = []; const seenCodeMap = new Set(); const normalizedExpressList = Array.isArray(expressList) ? expressList : []; const expressMap = new Map(); for (const expressItem of normalizedExpressList) { if (!expressItem || typeof expressItem !== 'object') { continue; } const code = String(expressItem.code || expressItem.value || '').trim(); if (!code) { continue; } if (!expressMap.has(code)) { expressMap.set(code, expressItem); } } for (const expressItem of normalizedExpressList) { if (!expressItem || typeof expressItem !== 'object') { continue; } const code = String(expressItem.code || expressItem.value || '').trim(); if (!code || seenCodeMap.has(code)) { continue; } mergedList.push(expressItem); seenCodeMap.add(code); } for (const row of Array.isArray(expressSettingList) ? expressSettingList : []) { const mergedItem = this.normalizeExpressSettingRow(row, expressMap); if (!mergedItem || seenCodeMap.has(mergedItem.code)) { continue; } mergedList.push(mergedItem); seenCodeMap.add(mergedItem.code); } return mergedList; } /** * 生成快递产品类型列表缓存键。 * * @param {string} expressCode 快递公司编码 * @return {string} 缓存键 */ getExpressProductTypeListCacheKey(expressCode = '') { const normalizedExpressCode = String(expressCode || '').trim(); if (!normalizedExpressCode) { return 'express:product-type:list'; } return `express:product-type:list:${normalizedExpressCode}`; } /** * 规范化快递产品类型记录。 * * @param {Object} row 数据库记录 * @return {Object|null} 规范化后的记录 */ normalizeExpressProductTypeRow(row) { if (!row || typeof row !== 'object') { return null; } const code = String(row.code || '').trim(); if (!code) { return null; } const name = String(row.name || '').trim(); return { code, express_code: String(row.express_code || '').trim(), name, value: code, label: name || code, }; } /** * 规范化快递编码为大写键值。 * * @param {*} expressCode 原始快递编码 * @return {string} 规范化后的快递编码 */ normalizeExpressCodeKey(expressCode) { return String(expressCode || '').trim().toUpperCase(); } /** * 判断是否为顺丰快递编码。 * * @param {*} expressCode 原始快递编码 * @return {boolean} 是否顺丰 */ isSfExpressCode(expressCode) { const normalizedExpressCode = this.normalizeExpressCodeKey(expressCode); return normalizedExpressCode === 'SF' || normalizedExpressCode === 'SHUNFENG'; } /** * 从 type_desc 中提取快递产品类型映射。 * * @param {*} typeDesc 原始 type_desc * @return {Array<{ code: string, name: string }>} 提取后的产品类型列表 */ extractExpressProductTypesFromTypeDesc(typeDesc) { const rawTypeDesc = String(typeDesc || '').trim(); if (!rawTypeDesc) { return []; } const normalizeCode = value => String(value || '').trim(); const normalizeName = value => String(value || '').trim(); const toPair = (codeValue, nameValue) => { const code = normalizeCode(codeValue); if (!code) { return null; } return { code, name: normalizeName(nameValue) || code, }; }; const pairs = []; const appendMapObject = source => { if (!source || typeof source !== 'object' || Array.isArray(source)) { return; } const preferredSource = source.desc && typeof source.desc === 'object' && !Array.isArray(source.desc) ? source.desc : source; for (const [ key, value ] of Object.entries(preferredSource)) { if (value && typeof value === 'object' && !Array.isArray(value)) { const nestedCode = String(value.code || value.value || key || '').trim(); const nestedName = String(value.name || value.label || value.desc || value.text || nestedCode || '').trim(); const pair = toPair(nestedCode, nestedName); if (pair) { pairs.push(pair); } continue; } const pair = toPair(key, value); if (pair) { pairs.push(pair); } } }; const appendArray = source => { if (!Array.isArray(source)) { return; } for (const item of source) { if (item && typeof item === 'object') { const code = item.code || item.value || item.key || item.id || ''; const name = item.name || item.label || item.desc || item.text || item.title || code; const pair = toPair(code, name); if (pair) { pairs.push(pair); } continue; } const text = String(item || '').trim(); if (!text) { continue; } const splitIndex = text.indexOf(':') >= 0 ? text.indexOf(':') : text.indexOf('='); if (splitIndex > 0) { const pair = toPair(text.slice(0, splitIndex), text.slice(splitIndex + 1)); if (pair) { pairs.push(pair); } continue; } const pair = toPair(text, text); if (pair) { pairs.push(pair); } } }; try { const parsed = JSON.parse(rawTypeDesc); if (Array.isArray(parsed)) { appendArray(parsed); } else if (parsed && typeof parsed === 'object') { appendMapObject(parsed); } } catch (error) { const segments = rawTypeDesc.split(/[,,;;]+/).map(item => item.trim()).filter(Boolean); appendArray(segments); } const dedupedMap = new Map(); for (const item of pairs) { if (!item || !item.code) { continue; } const existing = dedupedMap.get(item.code); if (!existing || (!existing.name && item.name)) { dedupedMap.set(item.code, item); } } return Array.from(dedupedMap.values()); } /** * 从拼多多网点服务列表中提取顺丰定时派送产品类型。 * * @param {Array} shopExpressList 店铺快递签约列表 * @return {Array<{ express_code: string, code: string, name: string }>} 可写入的产品类型列表 */ collectPddSfTimedDeliveryProductTypes(shopExpressList = []) { const result = []; for (const expressItem of Array.isArray(shopExpressList) ? shopExpressList : []) { const expressCode = this.normalizeExpressCodeKey(expressItem && expressItem.sys_express_code); if (!this.isSfExpressCode(expressCode)) { continue; } const accounts = Array.isArray(expressItem && expressItem.accounts) ? expressItem.accounts : []; for (const account of accounts) { const services = Array.isArray(account && account.services) ? account.services : []; for (const serviceItem of services) { const serviceCode = String(serviceItem && serviceItem.service_code || '').trim().toUpperCase(); if (serviceCode !== 'TIMED-DELIVERY') { continue; } const attributes = Array.isArray(serviceItem && serviceItem.attributes) ? serviceItem.attributes : []; for (const attribute of attributes) { const typeDesc = attribute && attribute.type_desc; const productTypeList = this.extractExpressProductTypesFromTypeDesc(typeDesc); for (const productType of productTypeList) { result.push({ express_code: expressCode, code: String(productType.code || '').trim(), name: String(productType.name || '').trim() || String(productType.code || '').trim(), }); } } } } } const dedupedMap = new Map(); for (const item of result) { if (!item || !item.express_code || !item.code) { continue; } const key = `${item.express_code}:${item.code}`; const existed = dedupedMap.get(key); if (!existed || (!existed.name && item.name)) { dedupedMap.set(key, item); } } return Array.from(dedupedMap.values()); } /** * 清理快递产品类型缓存。 * * @param {string} expressCode 快递公司编码 * @return {Promise} 无返回值 */ async clearExpressProductTypeCache(expressCode = '') { const cacheKeys = [ this.getExpressProductTypeListCacheKey() ]; const normalizedExpressCode = this.normalizeExpressCodeKey(expressCode); if (normalizedExpressCode) { cacheKeys.push(this.getExpressProductTypeListCacheKey(normalizedExpressCode)); } for (const cacheKey of cacheKeys) { if (!cacheKey) { continue; } if (this.app && typeof this.app.delCacheAsync === 'function') { await this.app.delCacheAsync(cacheKey); } else if (this.app && typeof this.app.setCacheAsync === 'function') { await this.app.setCacheAsync(cacheKey, null, 0); } } } /** * 将快递产品类型列表幂等写入数据库。 * * @param {Array<{ express_code: string, code: string, name: string }>} items 快递产品类型列表 * @return {Promise<{ createdCount: number, updatedCount: number }>} 写入结果 */ async upsertExpressProductTypeList(items = []) { const expressProductTypeModel = this.ctx.model && this.ctx.model.ExpressProductType; if (!expressProductTypeModel || typeof expressProductTypeModel.findAll !== 'function') { return { createdCount: 0, updatedCount: 0 }; } const validItems = Array.isArray(items) ? items.filter(item => item && item.express_code && item.code) : []; if (validItems.length === 0) { return { createdCount: 0, updatedCount: 0 }; } const { Op } = this.app.Sequelize; let createdCount = 0; let updatedCount = 0; const changedExpressCodeSet = new Set(); const groupedByExpressCode = validItems.reduce((result, item) => { const expressCode = this.normalizeExpressCodeKey(item.express_code); if (!expressCode) { return result; } if (!result[expressCode]) { result[expressCode] = []; } result[expressCode].push({ express_code: expressCode, code: String(item.code || '').trim(), name: String(item.name || '').trim() || String(item.code || '').trim(), }); return result; }, {}); for (const [ expressCode, groupItems ] of Object.entries(groupedByExpressCode)) { const codeList = Array.from(new Set(groupItems.map(item => item.code).filter(Boolean))); if (codeList.length === 0) { continue; } const existedRows = await expressProductTypeModel.findAll({ attributes: [ 'id', 'express_code', 'code', 'name' ], where: { express_code: expressCode, code: { [Op.in]: codeList, }, }, order: [[ 'id', 'ASC' ]], raw: true, }); const existedMap = new Map(); for (const row of Array.isArray(existedRows) ? existedRows : []) { const rowCode = String(row && row.code || '').trim(); if (!rowCode || existedMap.has(rowCode)) { continue; } existedMap.set(rowCode, row); } for (const item of groupItems) { const existed = existedMap.get(item.code); if (!existed) { if (typeof expressProductTypeModel.create === 'function') { await expressProductTypeModel.create({ express_code: expressCode, code: item.code, name: item.name, }); createdCount += 1; changedExpressCodeSet.add(expressCode); } continue; } const existedName = String(existed.name || '').trim(); if (item.name && item.name !== existedName && typeof expressProductTypeModel.update === 'function') { await expressProductTypeModel.update({ name: item.name, }, { where: { id: existed.id, }, }); updatedCount += 1; changedExpressCodeSet.add(expressCode); } } } if (changedExpressCodeSet.size > 0) { await this.clearExpressProductTypeCache(); for (const expressCode of changedExpressCodeSet) { await this.clearExpressProductTypeCache(expressCode); } } return { createdCount, updatedCount, }; } /** * 同步拼多多顺丰定时派送服务中的快递产品类型。 * * 仅处理 service_code 为 TIMED-DELIVERY 且系统快递编码为 SF/SHUNFENG 的数据。 * * @param {Object} payload 入参 * @param {Array} payload.shopExpressList 店铺快递签约列表 * @return {Promise<{ createdCount: number, updatedCount: number, parsedCount: number }>} 同步结果 */ async syncPddSfTimedDeliveryExpressProductTypes(payload = {}) { const { shopExpressList = [] } = payload && typeof payload === 'object' ? payload : {}; const productTypeList = this.collectPddSfTimedDeliveryProductTypes(shopExpressList); if (productTypeList.length === 0) { return { createdCount: 0, updatedCount: 0, parsedCount: 0, }; } const upsertResult = await this.upsertExpressProductTypeList(productTypeList); return { createdCount: Number(upsertResult.createdCount || 0), updatedCount: Number(upsertResult.updatedCount || 0), parsedCount: productTypeList.length, }; } normalizeExpressRow(row) { if (!row || typeof row !== 'object') { return null; } const code = String(row.code || '').trim(); if (!code) { return null; } return { code, name: String(row.name || '').trim(), value: code, label: String(row.name || code).trim(), is_system_setting: false, id: null, alias: null, }; } async loadExpressList() { const cachedList = await this.loadExpressListFromCache(); if (cachedList !== null) { return cachedList; } const expressList = await this.loadExpressListFromDatabase(); await this.app.setCacheAsync('express:list:system:normal', expressList, DEFAULT_CACHE_TTL_SECONDS); return expressList; } async loadExpressListFromCache() { const key = 'express:list:system:normal'; try { const cachedList = await this.app.getCacheAsync(key); if (cachedList !== null && cachedList !== undefined) { return Array.isArray(cachedList) ? cachedList : []; } } catch (error) { this.ctx.logger.warn('[ExpressService.loadExpressListFromCache] 获取系统快递列表缓存失败: %s', error.message); } return null; } async loadExpressListFromDatabase() { const rows = await this.ctx.model.Express.findAll({ order: [[ 'code', 'ASC' ]], raw: true, }); if (!Array.isArray(rows)) { return []; } return rows; } /** * 获取系统快递编码和名称列表。 * * 该接口只返回系统基础快递数据,不合并仓库自定义映射。 * * @return {Promise} 系统快递编码和名称列表 */ async getSystemExpressList() { return await this.loadExpressListFromDatabase(); } /** * 从数据库加载快递产品类型列表。 * * @param {string} expressCode 快递公司编码 * @return {Promise} 快递产品类型列表 */ async loadExpressProductTypeListFromDatabase(expressCode = '') { const normalizedExpressCode = String(expressCode || '').trim(); const query = { attributes: [ 'code', 'name', 'express_code' ], order: [[ 'express_code', 'ASC' ], [ 'code', 'ASC' ]], raw: true, }; if (normalizedExpressCode) { query.where = { express_code: normalizedExpressCode, }; } const rows = await this.ctx.model.ExpressProductType.findAll(query); if (!Array.isArray(rows)) { return []; } return rows .map(row => this.normalizeExpressProductTypeRow(row)) .filter(Boolean); } /** * 获取快递列表。 * * 默认先读取系统快递,再按当前仓库合并快递设置;同一编码只保留一条记录。 * systemOnly 为 true 时仅返回系统快递列表。 * * 当传入系统快递编码时,按当前仓库与 `express_code` 字段仅返回对应自定义编码列表。 * * @param {boolean} [systemOnly=false] 是否仅返回系统基础快递列表 * @param {string} [systemExpressCode=''] 系统快递编码 * @return {Promise} 快递列表 */ async getExpressList(systemOnly = false, systemExpressCode = '') { const warehouseId = this.getCurrentWarehouseId(); const normalizedExpressCode = String(systemExpressCode || '').trim().toUpperCase(); const cacheKey = this.getExpressListCacheKey(warehouseId, systemOnly, normalizedExpressCode); try { const cachedList = await this.app.getCacheAsync(cacheKey); if (cachedList !== null && cachedList !== undefined) { return Array.isArray(cachedList) ? cachedList : []; } if (systemOnly) { const expressList = await this.getSystemExpressList(); const filteredExpressList = normalizedExpressCode ? expressList.filter(item => String(item && (item.code || item.value) || '').trim().toUpperCase() === normalizedExpressCode) : expressList; await this.app.setCacheAsync(cacheKey, filteredExpressList, DEFAULT_CACHE_TTL_SECONDS); return filteredExpressList; } const [ expressList, expressSettingList ] = await Promise.all([ this.loadExpressListFromDatabase(), this.loadExpressSettingListFromDatabase(warehouseId, normalizedExpressCode), ]); if (normalizedExpressCode) { const customCodeList = this.buildExpressSettingCustomCodeList(expressList, expressSettingList); await this.app.setCacheAsync(cacheKey, customCodeList, DEFAULT_CACHE_TTL_SECONDS); return customCodeList; } const mergedList = this.buildMergedExpressList(expressList, expressSettingList); await this.app.setCacheAsync(cacheKey, mergedList, DEFAULT_CACHE_TTL_SECONDS); return mergedList; } catch (error) { this.ctx.logger.error('[ExpressService.getExpressList] 获取快递列表失败', { error: error.message, stack: error.stack, }); throw error; } } /** * 获取快递产品类型列表。 * * @param {string} expressCode 快递公司编码 * @return {Promise} 快递产品类型列表 */ async getExpressProductTypeList(expressCode = '') { const cacheKey = this.getExpressProductTypeListCacheKey(expressCode); const normalizedExpressCode = String(expressCode || '').trim(); try { const cachedList = await this.app.getCacheAsync(cacheKey); if (cachedList !== null && cachedList !== undefined) { return Array.isArray(cachedList) ? cachedList : []; } const expressProductTypeList = await this.loadExpressProductTypeListFromDatabase(normalizedExpressCode); await this.app.setCacheAsync(cacheKey, expressProductTypeList, DEFAULT_EXPRESS_PRODUCT_TYPE_CACHE_TTL_SECONDS); return expressProductTypeList; } catch (error) { this.ctx.logger.error('[ExpressService.getExpressProductTypeList] 获取快递产品类型失败', { error: error.message, stack: error.stack, expressCode: normalizedExpressCode, }); throw error; } } /** * 规范化打印平台编码。 * * @param {*} platformCode 原始平台编码。 * @return {string} 规范化后的平台编码。 */ normalizeWaybillPrintPlatformCode(platformCode) { return String(platformCode || '').trim(); } /** * 按系统平台列表加载“系统平台编码 -> 请求平台编码”映射。 * * @param {Array} platformList 系统平台列表。 * @return {Promise>} 映射结果。 */ async loadWaybillPrintPlatformCodeMap(platformList = []) { const { Op } = this.app.Sequelize; const printPlatformModel = this.ctx.model && this.ctx.model.PrintPlatform; const normalizedPlatformList = Array.isArray(platformList) ? platformList : []; const platformCodeByPrintPlatformIdMap = new Map(); for (const platform of normalizedPlatformList) { const platformCode = this.normalizeWaybillPrintPlatformCode(platform && platform.code).toLowerCase(); const printPlatformId = Number(platform && platform.print_platform_id); if (!platformCode || !Number.isFinite(printPlatformId) || printPlatformId <= 0) { continue; } if (!platformCodeByPrintPlatformIdMap.has(printPlatformId)) { platformCodeByPrintPlatformIdMap.set(printPlatformId, []); } platformCodeByPrintPlatformIdMap.get(printPlatformId).push(platformCode); } if (!printPlatformModel || typeof printPlatformModel.findAll !== 'function' || platformCodeByPrintPlatformIdMap.size <= 0) { return new Map(); } const printPlatformRows = await printPlatformModel.findAll({ where: { id: { [Op.in]: Array.from(platformCodeByPrintPlatformIdMap.keys()), }, }, attributes: [ 'id', 'platform_code' ], raw: true, }); const printPlatformCodeMap = new Map(); for (const row of Array.isArray(printPlatformRows) ? printPlatformRows : []) { const printPlatformId = Number(row && row.id); const platformCode = this.normalizeWaybillPrintPlatformCode(row && row.platform_code); if (!Number.isFinite(printPlatformId) || printPlatformId <= 0 || !platformCode) { continue; } const systemPlatformCodes = platformCodeByPrintPlatformIdMap.get(printPlatformId); if (!Array.isArray(systemPlatformCodes) || systemPlatformCodes.length === 0) { continue; } for (const systemPlatformCode of systemPlatformCodes) { printPlatformCodeMap.set(systemPlatformCode, platformCode); } } return printPlatformCodeMap; } /** * 按系统平台列表加载“系统平台编码 -> 异步分流请求平台编码”映射。 * * 该映射仅用于运单异步后处理分流,来源必须是 * `wms_print_platform.request_platform_code`,避免与分组/快递接口匹配使用的 * `wms_print_platform.platform_code` 语义混用。 * * @param {Array} platformList 系统平台列表。 * @return {Promise>} 映射结果。 */ async loadWaybillAsyncRequestPlatformCodeMap(platformList = []) { const { Op } = this.app.Sequelize; const printPlatformModel = this.ctx.model && this.ctx.model.PrintPlatform; const normalizedPlatformList = Array.isArray(platformList) ? platformList : []; const platformCodeByPrintPlatformIdMap = new Map(); for (const platform of normalizedPlatformList) { const platformCode = this.normalizeWaybillPrintPlatformCode(platform && platform.code).toLowerCase(); const printPlatformId = Number(platform && platform.print_platform_id); if (!platformCode || !Number.isFinite(printPlatformId) || printPlatformId <= 0) { continue; } if (!platformCodeByPrintPlatformIdMap.has(printPlatformId)) { platformCodeByPrintPlatformIdMap.set(printPlatformId, []); } platformCodeByPrintPlatformIdMap.get(printPlatformId).push(platformCode); } if (!printPlatformModel || typeof printPlatformModel.findAll !== 'function' || platformCodeByPrintPlatformIdMap.size <= 0) { return new Map(); } const printPlatformRows = await printPlatformModel.findAll({ where: { id: { [Op.in]: Array.from(platformCodeByPrintPlatformIdMap.keys()), }, }, attributes: [ 'id', 'request_platform_code' ], raw: true, }); const requestPlatformCodeMap = new Map(); for (const row of Array.isArray(printPlatformRows) ? printPlatformRows : []) { const printPlatformId = Number(row && row.id); const requestPlatformCode = this.normalizeWaybillPrintPlatformCode(row && row.request_platform_code); if (!Number.isFinite(printPlatformId) || printPlatformId <= 0 || !requestPlatformCode) { continue; } const systemPlatformCodes = platformCodeByPrintPlatformIdMap.get(printPlatformId); if (!Array.isArray(systemPlatformCodes) || systemPlatformCodes.length === 0) { continue; } for (const systemPlatformCode of systemPlatformCodes) { requestPlatformCodeMap.set(systemPlatformCode, requestPlatformCode); } } return requestPlatformCodeMap; } /** * 解析运单异步分流所需的请求平台编码。 * * @param {string} sysPlatformCode 订单系统平台编码。 * @param {Map} [requestPlatformCodeMap=new Map()] 系统平台到请求平台编码映射。 * @return {string} 请求平台编码;未命中时返回空字符串。 */ resolveWaybillAsyncRequestPlatformCode(sysPlatformCode = '', requestPlatformCodeMap = new Map()) { const normalizedSysPlatformCode = this.normalizeWaybillPrintPlatformCode(sysPlatformCode).toLowerCase(); if (!normalizedSysPlatformCode) { return ''; } return requestPlatformCodeMap instanceof Map ? this.normalizeWaybillPrintPlatformCode(requestPlatformCodeMap.get(normalizedSysPlatformCode)) : ''; } /** * 解析运单分组所需的打印平台编码。 * * @param {string} sysPlatformCode 订单系统平台编码。 * @param {Map} printPlatformCodeMap 打印平台编码映射。 * @return {string} 打印平台编码;未命中时回退系统平台编码。 */ resolveWaybillGroupPrintPlatformCode(sysPlatformCode = '', printPlatformCodeMap = new Map()) { const normalizedSysPlatformCode = this.normalizeWaybillPrintPlatformCode(sysPlatformCode).toLowerCase(); if (!normalizedSysPlatformCode) { return ''; } const mappedPrintPlatformCode = printPlatformCodeMap instanceof Map ? this.normalizeWaybillPrintPlatformCode(printPlatformCodeMap.get(normalizedSysPlatformCode)) : ''; this.ctx.logger.info('[ExpressService.resolveWaybillGroupPrintPlatformCode] 映射查找', { sysPlatformCode, normalizedSysPlatformCode, mapSize: printPlatformCodeMap instanceof Map ? printPlatformCodeMap.size : 'not-a-map', mapKeys: printPlatformCodeMap instanceof Map ? JSON.stringify(Array.from(printPlatformCodeMap.keys())) : 'N/A', mappedValue: printPlatformCodeMap instanceof Map ? printPlatformCodeMap.get(normalizedSysPlatformCode) : 'N/A', finalResult: mappedPrintPlatformCode || '(空)', }); return mappedPrintPlatformCode; } /** * 按打印平台编码和 logistics_code 对订单进行分组。 *【已使用】 * @param {Array} orders 已规范化的订单列表。 * @param {Map} [printPlatformCodeMap=new Map()] 系统平台到打印平台编码映射。 * @return {Array} 分组结果。 */ groupWaybillOrdersByPlatformAndLogistics(orders = [], printPlatformCodeMap = new Map()) { // 【step2】按平台 + 快递编码+货主id分组,后续按组串行处理。 const groupedOrders = []; const groupedOrderMap = new Map(); for (const order of Array.isArray(orders) ? orders : []) { if (!order || typeof order !== 'object') { continue; } const sysPlatformCode = String(order.sys_platform_code || '').trim(); const logisticsCode = String(order.logistics_code || '').trim(); const printPlatformCode = this.resolveWaybillGroupPrintPlatformCode(sysPlatformCode, printPlatformCodeMap); if (!sysPlatformCode || !logisticsCode || !printPlatformCode) { this.ctx.logger.warn('[ExpressService.groupWaybillOrdersByPlatformAndLogistics] 订单分组被跳过', { orderId: order.id, sysPlatformCode: sysPlatformCode || '(空)', logisticsCode: logisticsCode || '(空)', printPlatformCode: printPlatformCode || '(空)', reason: !sysPlatformCode ? 'sysPlatformCode为空' : !logisticsCode ? 'logisticsCode为空' : 'printPlatformCode映射失败', }); continue; } const groupKey = `${printPlatformCode}:${logisticsCode}:${order.store_id || 0}`; let groupedOrder = groupedOrderMap.get(groupKey); if (!groupedOrder) { groupedOrder = { options: { sys_platform_code: sysPlatformCode, print_platform_code: printPlatformCode, logistics_code: logisticsCode, sys_logistics_code: String(order.sys_logistics_code || '').trim(), weight_type: order.weight_type !== undefined ? Number(order.weight_type) : 0, sys_platform_name: order.sys_platform_name || '', logistics_name: order.logistics_name || '', store_id: order.store_id || 0, }, orders: [], }; groupedOrderMap.set(groupKey, groupedOrder); groupedOrders.push(groupedOrder); } groupedOrder.orders.push(order); } return groupedOrders; } /** * 将订单按指定数量拆分为多个批次。 *【已使用】 * @param {Array} orders 订单列表 * @param {number} [batchSize=10] 每批最大数量 * @return {Array>} 批次列表 */ splitWaybillOrdersIntoBatches(orders = [], batchSize = DEFAULT_WAYBILL_BATCH_SIZE) { // 【step3】按批大小切分订单,控制单次创建量。 const normalizedOrders = Array.isArray(orders) ? orders : []; const normalizedBatchSize = Math.floor(Number(batchSize)); const effectiveBatchSize = Number.isFinite(normalizedBatchSize) && normalizedBatchSize > 0 ? normalizedBatchSize : DEFAULT_WAYBILL_BATCH_SIZE; const batches = []; for (let index = 0; index < normalizedOrders.length; index += effectiveBatchSize) { batches.push(normalizedOrders.slice(index, index + effectiveBatchSize)); } return batches; } /** * 从仓库+平台接口配置列表中按订单分组快递编码选择可用配置。 * * 匹配字段顺序:sys_express_code -> express_code -> express[platform_code]。 * 比对时统一去空格并转小写,匹配命中后按原列表顺序返回首条。 * * @param {Array} interfaceList 接口配置列表。 * @param {Object} groupedOrder 订单分组信息。 * @param {Object} matchedPlatform 平台配置。 * @return {Object|null} 匹配到的接口配置,未匹配返回 null。 */ pickWaybillExpressInterface(interfaceList = [], groupedOrder = {}, matchedPlatform = null) { const normalizeCode = value => String(value || '').trim().toLowerCase(); const logisticsCode = normalizeCode( groupedOrder && groupedOrder.options && groupedOrder.options.logistics_code ); const sysLogisticsCode = normalizeCode( groupedOrder && groupedOrder.options && groupedOrder.options.sys_logistics_code ); const orderWeightType = Number( groupedOrder && groupedOrder.options && groupedOrder.options.weight_type ) || 0; const platformCode = normalizeCode( groupedOrder && groupedOrder.options && groupedOrder.options.print_platform_code || matchedPlatform && matchedPlatform.route_platform_code || matchedPlatform && matchedPlatform.default_express_interface || matchedPlatform && matchedPlatform.print_platform_code ); const enabledList = (Array.isArray(interfaceList) ? interfaceList : []) .filter(item => item && typeof item === 'object' && Number(item.is_enabled) === 1); // 通用匹配函数 const matchByCode = (item, targetCode, useSysCode = true) => { if (!targetCode) return false; const candidateCodes = [ normalizeCode(item.express_code) ]; if (useSysCode) { candidateCodes.push(normalizeCode(item.sys_express_code)); } const expressMap = item.express && typeof item.express === 'object' ? item.express : null; if (expressMap && platformCode) { candidateCodes.push(normalizeCode(expressMap[platformCode])); } if (!candidateCodes.some(code => code && code === targetCode)) return false; const itemWeightType = item.weight_type !== null && item.weight_type !== undefined ? Number(item.weight_type) : null; if (itemWeightType !== null && itemWeightType !== orderWeightType) return false; return true; }; // 第一步:logistics_code 仅匹配 express_code + 平台码(不用 sys_express_code) if (logisticsCode) { for (const item of enabledList) { if (matchByCode(item, logisticsCode, false)) { return item; } } } // 第二步:sys_logistics_code 匹配 sys_express_code + express_code(全放开) if (sysLogisticsCode) { for (const item of enabledList) { if (matchByCode(item, sysLogisticsCode, true)) { return item; } } } return null; } /** * 解析运单后处理可用的平台编码。 * * @param {Object} order 订单或平台上下文。 // 【step4】检查余额、锁定可用数量,并拆出成功与失败订单。 * @return {string} 平台编码,小写。 */ resolveWaybillAsyncPlatformCode(order = {}) { if (!order || typeof order !== 'object') { return ''; } const expressPlatform = order.wms_express_platform && typeof order.wms_express_platform === 'object' ? order.wms_express_platform : (order.wmsExpressPlatform && typeof order.wmsExpressPlatform === 'object' ? order.wmsExpressPlatform : null); const rawPlatformCode = (expressPlatform && (expressPlatform.platform_code || expressPlatform.platformCode)) || order.express_platform_code || order.expressPlatformCode || order.platform_code || order.platformCode || order.sys_platform_code || order.sysPlatformCode || (typeof order.wms_express_platform === 'string' ? order.wms_express_platform : '') || (typeof order.wmsExpressPlatform === 'string' ? order.wmsExpressPlatform : ''); return String(rawPlatformCode || '').trim().toLowerCase(); } /** * 按平台编码汇总需要异步后处理的订单。 * * @param {Array} orders 成功订单列表。 // 【step5】把失败订单回写为异常状态,供主链路统一收口。 * @return {Array} 平台分组结果。 */ groupWaybillAsyncOrdersByPlatform(orders = []) { const groupedOrderMap = new Map(); for (const order of Array.isArray(orders) ? orders : []) { if (!order || typeof order !== 'object') { continue; } const platformCode = this.resolveWaybillAsyncPlatformCode(order); let groupedOrder = groupedOrderMap.get(platformCode); if (!groupedOrder) { groupedOrder = { platform_code: platformCode, orders: [], }; groupedOrderMap.set(platformCode, groupedOrder); } groupedOrder.orders.push(order); } return Array.from(groupedOrderMap.values()); } /** * 将订单主表快照按订单 ID 建立映射。 *【已使用】 * @param {Array} orderDeliveryRows 订单主表查询结果。 // 【step5】按失败原因分批回写异常,避免失败链路遗漏。 * @return {Map} 订单快照映射。 */ buildWaybillOrderDeliveryMap(orderDeliveryRows = []) { const orderDeliveryMap = new Map(); for (const row of Array.isArray(orderDeliveryRows) ? orderDeliveryRows : []) { const orderId = Number(row && row.id); if (Number.isFinite(orderId) && orderId > 0) { orderDeliveryMap.set(orderId, row); } } return orderDeliveryMap; } /** * 将异步后处理文本字段标准化。 * * @param {*} value 原始值。 * @return {string|null} 标准化结果。 */ normalizeWaybillAsyncText(value) { if (value === undefined || value === null) { return null; } const normalizedValue = String(value).trim(); return normalizedValue ? normalizedValue : null; } /** * 将异步后处理数值字段标准化。 * * @param {*} value 原始值。 * @return {number} 标准化结果。 */ normalizeWaybillAsyncNumber(value) { const normalizedValue = Number(value); return Number.isFinite(normalizedValue) ? normalizedValue : 0; } /** * 将异步后处理日期字段标准化为 ISO 字符串。 * * @param {*} value 原始值。 * @return {string|null} 标准化结果。 */ formatWaybillAsyncDate(value) { if (value === undefined || value === null || value === '') { return null; } const date = value instanceof Date ? value : new Date(value); if (Number.isNaN(date.getTime())) { return null; } return date.toISOString(); } /** * 标准化异步后处理商品明细字段。 * * @param {*} value 原始值。 * @return {Array} 标准化结果。 */ normalizeWaybillAsyncItems(value) { if (Array.isArray(value)) { return value.map(item => (typeof item === 'string' ? item.trim() : item)); } if (typeof value === 'string') { return value .split('|') .map(item => item.trim()) .filter(Boolean); } return []; } /** * 构建异步后处理中的路由信息块。 * * @param {Object} order 订单上下文。 * @param {Object} orderDelivery 订单主表快照。 * @return {Object} 路由信息块。 */ buildWaybillAsyncRouteInfo(order = {}, orderDelivery = {}) { return { source_platform_code: this.normalizeWaybillAsyncText(orderDelivery.source_platform_code), source_platform_name: this.normalizeWaybillAsyncText(orderDelivery.source_platform_name), sys_platform_code: this.normalizeWaybillAsyncText(orderDelivery.sys_platform_code || order.sys_platform_code), sys_platform_name: this.normalizeWaybillAsyncText(orderDelivery.sys_platform_name), logistics_code: this.normalizeWaybillAsyncText(order.logistics_code || orderDelivery.logistics_code), logistics_name: this.normalizeWaybillAsyncText(orderDelivery.logistics_name), sys_logistics_code: this.normalizeWaybillAsyncText(orderDelivery.sys_logistics_code), sys_logistics_name: this.normalizeWaybillAsyncText(orderDelivery.sys_logistics_name), express_code: this.normalizeWaybillAsyncText(orderDelivery.express_code), logistics_area_code: this.normalizeWaybillAsyncText(orderDelivery.logistics_area_code), }; } /** * 构建异步后处理中的订单信息块。 * * @param {Object} orderDelivery 订单主表快照。 * @return {Object} 订单信息块。 */ buildWaybillAsyncOrderInfo(orderDelivery = {}) { return { delivery_order_code: this.normalizeWaybillAsyncText(orderDelivery.delivery_order_code), order_type: this.normalizeWaybillAsyncText(orderDelivery.order_type), status: this.normalizeWaybillAsyncText(orderDelivery.status), step: this.normalizeWaybillAsyncNumber(orderDelivery.step), order_flag: this.normalizeWaybillAsyncText(orderDelivery.order_flag), from_key: this.normalizeWaybillAsyncText(orderDelivery.from_key), create_at: this.formatWaybillAsyncDate(orderDelivery.create_at), place_order_time: this.formatWaybillAsyncDate(orderDelivery.place_order_time), pay_time: this.formatWaybillAsyncDate(orderDelivery.pay_time), operate_time: this.formatWaybillAsyncDate(orderDelivery.operate_time), delivery_time: this.formatWaybillAsyncDate(orderDelivery.delivery_time), }; } /** * 构建异步后处理中的收件人信息块。 * * @param {Object} orderDelivery 订单主表快照。 * @return {Object} 收件人信息块。 */ buildWaybillAsyncReceiverInfo(orderDelivery = {}) { return { name: this.normalizeWaybillAsyncText(orderDelivery.name), tel: this.normalizeWaybillAsyncText(orderDelivery.tel), mobile: this.normalizeWaybillAsyncText(orderDelivery.mobile), email: this.normalizeWaybillAsyncText(orderDelivery.email), country_code: this.normalizeWaybillAsyncText(orderDelivery.country_code), province: this.normalizeWaybillAsyncText(orderDelivery.province), city: this.normalizeWaybillAsyncText(orderDelivery.city), area: this.normalizeWaybillAsyncText(orderDelivery.area), town: this.normalizeWaybillAsyncText(orderDelivery.town), detail_address: this.normalizeWaybillAsyncText(orderDelivery.detail_address), zip_code: this.normalizeWaybillAsyncText(orderDelivery.zip_code), }; } /** * 构建异步后处理中的结算信息块。 * * @param {Object} orderDelivery 订单主表快照。 * @return {Object} 结算信息块。 */ buildWaybillAsyncSettlementInfo(orderDelivery = {}) { return { total_amount: this.normalizeWaybillAsyncNumber(orderDelivery.total_amount), item_amount: this.normalizeWaybillAsyncNumber(orderDelivery.item_amount), discount_amount: this.normalizeWaybillAsyncNumber(orderDelivery.discount_amount), freight: this.normalizeWaybillAsyncNumber(orderDelivery.freight), ar_amount: this.normalizeWaybillAsyncNumber(orderDelivery.ar_amount), got_amount: this.normalizeWaybillAsyncNumber(orderDelivery.got_amount), }; } /** * 构建异步后处理中的商品汇总信息块。 * * @param {Object} orderDelivery 订单主表快照。 * @return {Object} 商品汇总信息块。 */ buildWaybillAsyncItemsSummary(orderDelivery = {}) { return { items: this.normalizeWaybillAsyncItems(orderDelivery.items), items_count: this.normalizeWaybillAsyncNumber(orderDelivery.items_count), items_total: this.normalizeWaybillAsyncNumber(orderDelivery.items_total), items_weight: this.normalizeWaybillAsyncNumber(orderDelivery.items_weight), // 单位 g,传递给下游快递平台 }; } /** * 构建异步后处理中的单个订单项。 * * @param {Object} order 成功订单上下文。 * @return {Object} 订单项快照。 */ buildWaybillAsyncOrderListItem(order = {}) { const orderDelivery = order && typeof order.order_delivery === 'object' ? order.order_delivery : {}; return { order_id: this.normalizeWaybillAsyncNumber(order.order_id), business_key: this.normalizeWaybillAsyncNumber(order.business_key), sys_platform_code: this.normalizeWaybillAsyncText(order.sys_platform_code || orderDelivery.sys_platform_code), logistics_code: this.normalizeWaybillAsyncText(order.logistics_code || orderDelivery.logistics_code), express_platform_code: this.normalizeWaybillAsyncText(order.express_platform_code || orderDelivery.express_platform_code || this.resolveWaybillAsyncPlatformCode(order)), route_info: this.buildWaybillAsyncRouteInfo(order, orderDelivery), order_info: this.buildWaybillAsyncOrderInfo(orderDelivery), receiver_info: this.buildWaybillAsyncReceiverInfo(orderDelivery), settlement_info: this.buildWaybillAsyncSettlementInfo(orderDelivery), items_summary: this.buildWaybillAsyncItemsSummary(orderDelivery), }; } /** * 运单后处理 bizcontent 骨架的返回结构。 * * 顶层返回对象仅包含一个 `bizcontent` 字段,方便后续按平台继续扩展。 * * @typedef {Object} WaybillAsyncBizcontentSkeletonResult * @property {WaybillAsyncBizcontentSkeleton} bizcontent 顶层业务载荷对象。 */ /** * 运单后处理 bizcontent 的完整结构。 * * 该结构当前只负责承载统一字段与订单列表骨架,平台差异字段按需挂载。 * * @typedef {Object} WaybillAsyncBizcontentSkeleton * @property {string} platform_code 平台编码,来源于当前业务上下文或订单分组结果。 * @property {string} [express_platform_code] 物流平台编码,仅在上游传入时保留。 * @property {number} store_id 店铺 ID,未传时为 `0`。 * @property {number} warehouse_id 仓库 ID,未传时为 `0`。 * @property {Array} order_list 订单列表骨架。 * @property {Object} platform_payload 平台专属载荷占位对象,当前固定为空对象。 */ /** * `order_list` 中单个订单项的结构。 * * @typedef {Object} WaybillAsyncOrderItemSkeleton * @property {number} order_id 订单 ID,未能解析时为 `0`。 * @property {number} business_key 业务主键,未能解析时为 `0`。 * @property {string} sys_platform_code 系统平台编码,做了去空格处理。 * @property {string} logistics_code 物流编码,做了去空格处理。 * @property {string} express_platform_code 当前订单对应的物流平台编码。 */ /** * 构建运单后处理统一业务数据骨架。 * * 仅保留请求级公共字段与订单列表骨架,平台差异字段暂时留空,后续再补充。 * * 返回数据结构如下: * - 顶层返回对象:`{ bizcontent: WaybillAsyncBizcontentSkeleton }` * - `bizcontent`:包含平台编码、店铺 ID、仓库 ID、订单列表和平台专属载荷占位 * - `order_list`:由多个 `WaybillAsyncOrderItemSkeleton` 组成 * - `platform_payload`:当前固定为空对象 `{}`,用于后续按平台补充差异字段 * * @param {Array} orders 成功订单列表。 * @param {Object} [options={}] 业务上下文。 * @return {WaybillAsyncBizcontentSkeletonResult} 统一业务数据骨架。 */ buildWaybillAsyncBizcontentSkeleton(orders = [], options = {}) { const normalizedOrders = Array.isArray(orders) ? orders : []; const platformCode = this.resolveWaybillAsyncPlatformCode({ ...options, wms_express_platform: options.wms_express_platform || options.wmsExpressPlatform || null, }); const expressPlatformCode = String(options.express_platform_code || options.expressPlatformCode || '').trim(); return { bizcontent: { platform_code: platformCode, store_id: Number(options.store_id || options.storeId || 0) || 0, warehouse_id: Number(options.warehouse_id || options.warehouseId || 0) || 0, order_list: normalizedOrders.map(order => this.buildWaybillAsyncOrderListItem(order)), platform_payload: {}, ...(expressPlatformCode ? { express_platform_code: expressPlatformCode } : {}), // 这里先不拼平台公共字段,后续再补充平台凭证、接口版本、渠道参数等内容。 }, }; } /** * 判断异步取号平台是否需要逐单分发。 * * 当前菜鸟、拼多多平台要求按单请求,避免整批订单透传到平台侧。 * * @param {string} platformCode 平台编码。 * @return {boolean} 是否逐单分发。 */ shouldDispatchWaybillAsyncPerOrder(platformCode = '') { const normalizedPlatformCode = String(platformCode || '').trim().toLowerCase(); return WAYBILL_ASYNC_SINGLE_ORDER_PLATFORM_CODES.has(normalizedPlatformCode); } /** * 将统一业务数据骨架按wms_print_platform.request_platform_code分流。 * * 直接调用平台服务实例上的同名方法;如果方法不存在,或平台方法返回失败结果,则向上抛出异常。 * * @param {string} platformCode 平台编码。 * @param {Object} bizcontent 统一业务数据骨架。 * @return {Promise} 无返回值。 */ async dispatchWaybillAsyncPlatform(platformCode = '', bizcontent = {}) { const normalizedPlatformCode = String(platformCode).trim().toLowerCase(); const expressPlatformService = this.service && this.service.systems && (this.service.systems.expressPlatform || this.service.systems.express_platform); const dispatchMethod = expressPlatformService && expressPlatformService[normalizedPlatformCode]; if (typeof dispatchMethod !== 'function') { throw new Error(normalizedPlatformCode + '接口未实现'); } const normalizedOrders = Array.isArray(bizcontent && bizcontent.orders) ? bizcontent.orders : []; // 需要逐单调用的平台(cainiao/pdd):拆分为逐单 payload,并发调用 if (this.shouldDispatchWaybillAsyncPerOrder(normalizedPlatformCode) && normalizedOrders.length > 1) { const perOrderPayloads = normalizedOrders.map(order => ({ ...bizcontent, orders: [ order ], })); const perOrderResults = await Promise.all( perOrderPayloads.map(payload => dispatchMethod.call(expressPlatformService, payload).then( dispatchResult => ({ payload, dispatchResult, error: null }), error => ({ payload, dispatchResult: null, error }) ) ) ); // 检查是否有失败结果;取第一个失败原因作为异常抛出 const firstFailure = perOrderResults.find( item => item.error || (item.dispatchResult && typeof item.dispatchResult === 'object' && item.dispatchResult.flag === 'failure') ); if (firstFailure) { const failureMessage = firstFailure.error ? (firstFailure.error.message || String(firstFailure.error)) : (firstFailure.dispatchResult && firstFailure.dispatchResult.message); throw new Error(failureMessage || normalizedPlatformCode + '接口调用失败'); } return; } // 非逐单平台:保持原有单次批量调用 const dispatchResult = await dispatchMethod.call(expressPlatformService, bizcontent); if (dispatchResult && typeof dispatchResult === 'object' && dispatchResult.flag === 'failure') { throw new Error(dispatchResult.message || normalizedPlatformCode + '接口调用失败'); } } /** * 解析运单后处理分发平台编码。 * * 优先使用 `wms_print_platform.request_platform_code`,未提供时兼容历史字段。 * * @param {Object} [matchedPlatform={}] 平台匹配信息。 * @return {string} 后处理分发平台编码。 */ resolveWaybillAsyncDispatchPlatformCode(matchedPlatform = {}) { return String( matchedPlatform.request_platform_code || matchedPlatform.route_platform_code || matchedPlatform.platform_code || matchedPlatform.code || matchedPlatform.default_express_interface || '' ).trim(); } /** * 硬删除运单异步失败分组对应的订单快递记录(仅删除 status=0 的未完成记录,保护手工录入等已完成记录)。 * * 删除条件必须同时包含订单ID和业务键,若任一订单缺少 business_key,则记录原因并跳过整个分组,避免误删。 * * @param {Array} orders 失败分组订单列表。 * @param {Object} [options={}] 分组上下文。 * @param {string} [options.platform_code=''] 平台编码。 * @param {string} [options.error_message=''] 失败原因。 * @return {Promise} 是否已成功执行硬删除。 */ async hardDeleteWaybillAsyncOrderExpressRows(orders = [], options = {}) { const { Op } = this.app.Sequelize; const orderExpressModel = this.ctx.model && this.ctx.model.OrderExpress; if (!orderExpressModel || typeof orderExpressModel.destroy !== 'function') { this.ctx.logger.error('[ExpressService.hardDeleteWaybillAsyncOrderExpressRows] 订单快递模型未初始化,跳过失败分组硬删', { platform_code: String(options.platform_code || '').trim(), error_message: String(options.error_message || '').trim(), }); return false; } const normalizedOrders = Array.isArray(orders) ? orders : []; const deleteConditions = []; for (const order of normalizedOrders) { const orderId = Number(order && order.order_id); const businessKey = Number(order && order.business_key); if (!Number.isFinite(orderId) || orderId <= 0) { this.ctx.logger.error('[ExpressService.hardDeleteWaybillAsyncOrderExpressRows] 失败分组订单缺少有效 order_id,已跳过该分组硬删', { order_id: order && order.order_id, business_key: order && order.business_key, platform_code: String(options.platform_code || '').trim(), error_message: String(options.error_message || '').trim(), }); return false; } if (!Number.isFinite(businessKey) || businessKey <= 0) { this.ctx.logger.error('[ExpressService.hardDeleteWaybillAsyncOrderExpressRows] 失败分组订单缺少 business_key,已跳过该分组硬删与回写', { order_id: orderId, business_key: order && order.business_key, platform_code: String(options.platform_code || '').trim(), error_message: String(options.error_message || '').trim(), }); return false; } deleteConditions.push({ order_id: orderId, business_key: businessKey, }); } if (deleteConditions.length === 0) { return false; } try { await orderExpressModel.destroy({ where: { [Op.or]: deleteConditions, status: 0, }, }); return true; } catch (error) { this.ctx.logger.error('[ExpressService.hardDeleteWaybillAsyncOrderExpressRows] 失败分组硬删订单快递记录失败', { error: error.message, stack: error.stack, platform_code: String(options.platform_code || '').trim(), error_message: String(options.error_message || '').trim(), delete_conditions: deleteConditions, }); return false; } } /** * 获取运单异步后处理使用的订单主表模型。 * * 优先使用当前上下文中已挂载的订单主表模型;如果只有工厂,则按仓库 ID 取当前模型。 * * @param {number} currentWarehouseId 当前仓库 ID。 * @return {Promise} 订单主表模型或空值。 * 【已使用】 */ async getWaybillAsyncOrderDeliveryModel(currentWarehouseId = 0) { const orderDeliveryFactory = this.ctx.model && this.ctx.model.OrderDeliveryFactory; if (!currentWarehouseId || !orderDeliveryFactory || typeof orderDeliveryFactory.getCurrentModel !== 'function') { return null; } const orderDeliveryModel = await orderDeliveryFactory.getCurrentModel(currentWarehouseId); if (!orderDeliveryModel || typeof orderDeliveryModel.update !== 'function') { return null; } return orderDeliveryModel; } /** * 按分组和批次顺序初始化订单运单表。 * * 先标准化订单,再按 print_platform_code 和 logistics_code 分组, * 最后按每批最多 10 条的规则顺序调用现有 createWaybillCode。 * business_key 支持单值或数组输入,内部会展开成多条记录后再分组批处理。 *【已使用】 * @param {Array} orders 订单与业务键列表。 * @param {Object} [options] 可选配置。 * @param {boolean} [options.awaitTasks=false] 是否等待所有异步任务完成后再返回。 * @param {Function} [options.onBatchComplete] 单批完成回调 ({ processed, total })。 * @param {number} [options.warehouseId] 仓库ID覆盖值,用于 setImmediate 等异步上下文中 ctx.user 不可用的场景。 * @return {Promise} 处理结果,包含 orders、waybill_codes 和 skippedOrders。 */ async createWaybillCodePipeline(orders = [], options = {}) { const { app } = this; const { Op } = app.Sequelize; const orderList = Array.isArray(orders) ? orders : []; const traceId = this.buildWaybillTraceId({}, `pipeline_${Date.now()}`); const pipelineOptions = options && typeof options === 'object' ? options : {}; this.ctx.logger.info('[ExpressService.createWaybillCodePipeline] 入口请求', { traceId, orderCount: orderList.length, orderIds: orderList.slice(0, 50).map(order => Number(order && order.order_id)).filter(orderId => Number.isFinite(orderId) && orderId > 0), waveIds: orderList.slice(0, 50).map(order => Number(order && order.wave_id)).filter(waveId => Number.isFinite(waveId) && waveId > 0), }); const warehouseId = Number(options.warehouseId) > 0 ? Number(options.warehouseId) : this.getCurrentWarehouseId(); const orderDeliveryModel = await this.getWaybillAsyncOrderDeliveryModel(warehouseId); if (!orderDeliveryModel || typeof orderDeliveryModel.findAll !== 'function') { this.ctx.logger.error('[ExpressService.createWaybillCodePipeline] 分配前置条件失败-订单主表模型不可用', { traceId, warehouseId, }); throw new Error('订单主表模型未初始化'); } // 【step1】先按订单ID和业务键筛选,找出已存在的快递记录,避免重复创建。 // 先从 current 表查;若存在未覆盖的 order_id,再从 dispatch 表补查(配送中订单可能已迁移) const inputOrderIds = orderList.map(order => Number(order && order.order_id)).filter(orderId => Number.isFinite(orderId) && orderId > 0); const currentOrders = await orderDeliveryModel.findAll({ where: { id: inputOrderIds, warehouse_id: warehouseId, step: { [Op.in]: [ 1, 2, 3, 4 ], }, status: { [Op.ne]: 'cancel', }, }, attributes: [ 'id', 'sys_platform_code', 'logistics_code', 'sys_platform_name', 'logistics_name', 'store_id', 'pay_no', 'from_key', 'intercept_status', 'lock_status' ], raw: true, }); // 补查 dispatch 表:获取 current 表未覆盖的 order_id const currentCoveredIds = new Set((Array.isArray(currentOrders) ? currentOrders : []).map(o => Number(o.id))); const uncoveredIds = inputOrderIds.filter(id => !currentCoveredIds.has(id)); let dispatchOrders = []; if (uncoveredIds.length > 0) { const dispatchModel = this.ctx.model && this.ctx.model.OrderDeliveryFactory ? await this.ctx.model.OrderDeliveryFactory.getDispatchModel(warehouseId) : null; if (dispatchModel && typeof dispatchModel.findAll === 'function') { dispatchOrders = await dispatchModel.findAll({ where: { id: uncoveredIds, warehouse_id: warehouseId, step: { [Op.in]: [ 4 ], }, status: { [Op.ne]: 'cancel', }, }, attributes: [ 'id', 'sys_platform_code', 'logistics_code', 'sys_platform_name', 'logistics_name', 'store_id', 'pay_no', 'from_key', 'intercept_status', 'lock_status' ], raw: true, }); } } // 拦截订单跳过(除 none 外一律视为已拦截) const mergedOrders = [ ...(Array.isArray(currentOrders) ? currentOrders : []), ...dispatchOrders ]; const interceptedOrderIdSet = new Set(mergedOrders .filter(order => isInterceptedOrderStatus(order && order.intercept_status)) .map(order => Number(order && order.id || 0)) .filter(orderId => Number.isInteger(orderId) && orderId > 0)); const skippedInterceptedOrderIds = Array.from(interceptedOrderIdSet); const orders_arr = mergedOrders.filter(order => !interceptedOrderIdSet.has(Number(order && order.id || 0))); if (skippedInterceptedOrderIds.length > 0) { this.ctx.logger.info('[ExpressService.createWaybillCodePipeline] 跳过拦截订单', { traceId, warehouseId, skippedInterceptedOrderIds, }); } // 锁定订单跳过(除 none 外一律视为已锁定,锁定期间不允许分配快递) const lockedOrderIdSet = new Set(orders_arr .filter(order => isLockedOrderStatus(order && order.lock_status)) .map(order => Number(order && order.id || 0)) .filter(orderId => Number.isInteger(orderId) && orderId > 0)); const skippedLockedOrderIds = Array.from(lockedOrderIdSet); const activeOrders = orders_arr.filter(order => !lockedOrderIdSet.has(Number(order && order.id || 0))); if (skippedLockedOrderIds.length > 0) { this.ctx.logger.info('[ExpressService.createWaybillCodePipeline] 跳过锁定订单', { traceId, warehouseId, skippedLockedOrderIds, }); } this.ctx.logger.info('[ExpressService.createWaybillCodePipeline] 订单筛选结果', { traceId, warehouseId, inputOrderCount: orderList.length, currentCount: (Array.isArray(currentOrders) ? currentOrders : []).length, dispatchCount: dispatchOrders.length, matchedOrderCount: activeOrders.length, skippedInterceptedOrderIds, skippedLockedOrderIds, }); // 【step1.5】过滤已分配运单号(status=1)且传入 business_key=1 的订单,避免重复分配。 const orderExpressModel = this.ctx.model && this.ctx.model.OrderExpress; let filteredOrdersArr = activeOrders; if (orderExpressModel && activeOrders.length > 0) { const orderIds = activeOrders.map(o => Number(o.id)).filter(id => id > 0); const completedRows = await orderExpressModel.findAll({ where: { order_id: { [Op.in]: orderIds }, warehouse_id: warehouseId, status: 1, }, attributes: [ 'order_id', 'business_key' ], raw: true, }); const skipSet = new Set(); for (const row of completedRows) { skipSet.add(`${Number(row.order_id)}:${Number(row.business_key)}`); } if (skipSet.size > 0) { const beforeCount = activeOrders.length; filteredOrdersArr = activeOrders.filter(order => { const matchedExpress = orderList.find(express => Number(order.id) === Number(express.order_id)); const businessKey = matchedExpress ? Number(matchedExpress.business_key) : 1; if (businessKey === 1 && skipSet.has(`${Number(order.id)}:1`)) { return false; } return true; }); if (filteredOrdersArr.length < beforeCount) { this.ctx.logger.info('[ExpressService.createWaybillCodePipeline] 跳过已分配运单号(business_key=1)的订单', { traceId, skippedCount: beforeCount - filteredOrdersArr.length, skippedOrderIds: activeOrders .filter(order => { const matchedExpress = orderList.find(express => Number(order.id) === Number(express.order_id)); const businessKey = matchedExpress ? Number(matchedExpress.business_key) : 1; return businessKey === 1 && skipSet.has(`${Number(order.id)}:1`); }) .map(o => o.id), }); } } } if (filteredOrdersArr.length === 0) { this.ctx.logger.info('[ExpressService.createWaybillCodePipeline] 所有订单均已分配运单号,无需处理', { traceId }); return { message: '所有订单均已分配运单号,无需处理', skipped_intercepted_order_ids: skippedInterceptedOrderIds, skipped_locked_order_ids: skippedLockedOrderIds, }; } // orders_arr和orderList合并:同一 order_id 在 orderList 中可能有多条(不同 business_key), // 需要展开为多条 ordersWithExpress,不能用 find() 只取第一条 const ordersWithExpress = []; for (const order of filteredOrdersArr) { const matchingExpresses = orderList.filter(express => Number(order.id) === Number(express.order_id)); if (matchingExpresses.length > 0) { for (const express of matchingExpresses) { ordersWithExpress.push({ ...order, business_key: express.business_key || 1, }); } } else { // 兜底:orderList 中无对应记录,business_key 默认为 1 ordersWithExpress.push({ ...order, business_key: 1, }); } } const platformList = await this.service.systems.platform.getPlatformList(true, true); const printPlatformCodeMap = await this.loadWaybillPrintPlatformCodeMap(platformList); const requestPlatformCodeMap = await this.loadWaybillAsyncRequestPlatformCodeMap(platformList); const groupedOrders = this.groupWaybillOrdersByPlatformAndLogistics(ordersWithExpress, printPlatformCodeMap); this.ctx.logger.info('[ExpressService.createWaybillCodePipeline] 平台物流分组结果', { traceId, groupedCount: groupedOrders.length, }); // 【step2】按平台 + 快递编码分组,后续按组串行处理。 for (const groupedOrder of groupedOrders) { const matchedPlatform = platformList.find(platform => String(platform.code || '').trim().toLowerCase() === String(groupedOrder.options.sys_platform_code || '').trim().toLowerCase()); const matchedPlatformWithRequestCode = matchedPlatform ? { ...matchedPlatform, request_platform_code: this.resolveWaybillAsyncRequestPlatformCode( groupedOrder.options.sys_platform_code, requestPlatformCodeMap ) || String(matchedPlatform.request_platform_code || '').trim(), } : null; const batches = this.splitWaybillOrdersIntoBatches(groupedOrder.orders); const expressInterfacePlatformCode = String( groupedOrder.options.print_platform_code || '' ).trim(); const listByWarehousePlatformCode = expressInterfacePlatformCode ? await this.service.systems.setting.expressInterface.listByWarehousePlatformCode({ warehouseId, platform_code: expressInterfacePlatformCode, }) : { data: [] }; const expressInterface = this.pickWaybillExpressInterface( listByWarehousePlatformCode && listByWarehousePlatformCode.data, groupedOrder, matchedPlatformWithRequestCode ); this.ctx.logger.info('[ExpressService.createWaybillCodePipeline] 分组前置条件检查', { traceId, warehouseId, storeId: groupedOrder.options.store_id || 0, sysPlatformCode: groupedOrder.options.sys_platform_code, printPlatformCode: groupedOrder.options.print_platform_code, expressInterfacePlatformCode, logisticsCode: groupedOrder.options.logistics_code, sysLogisticsCode: groupedOrder.options.sys_logistics_code, weightType: groupedOrder.options.weight_type, matchedPlatformCode: matchedPlatformWithRequestCode && matchedPlatformWithRequestCode.code, requestPlatformCode: matchedPlatformWithRequestCode && matchedPlatformWithRequestCode.request_platform_code, hasExpressInterface: Boolean(expressInterface), }); // 发件人相关字段统一走接口配置,货主配置仅用于打印链路。 const expressInterfaceConfig = expressInterface ? { ...expressInterface, } : null; // 各批次并发执行:同组内不同批次的订单相互独立,无重叠,可安全并发 if (pipelineOptions.awaitTasks) { await Promise.all(batches.map(batch => this.asyncTask(batch, { ...groupedOrder.options, trace_id: traceId, warehouse_id: warehouseId, }, matchedPlatformWithRequestCode, expressInterfaceConfig) )); } else { // 非等待模式:fire-and-forget,所有批次同时触发 for (const batch of batches) { this.asyncTask(batch, { ...groupedOrder.options, trace_id: traceId, warehouse_id: warehouseId, }, matchedPlatformWithRequestCode, expressInterfaceConfig); } } } this.ctx.logger.info('[ExpressService.createWaybillCodePipeline] 流水线任务提交完成', { traceId, groupedCount: groupedOrders.length, }); return { message: '分配快递任务已提交', skipped_intercepted_order_ids: skippedInterceptedOrderIds, skipped_locked_order_ids: skippedLockedOrderIds, }; } /** * 异步执行订单快递分配任务。错误订单转异常,并记录失败订单列表。 * 【已使用】 * @param {*} batch * @param {*} sysPlatformCode * @param {*} logisticsCode * @param {*} matchedPlatform * @param {*} listByWarehousePlatformCode */ async asyncTask(batch, options, matchedPlatform, listByWarehousePlatformCode) { const traceId = this.buildWaybillTraceId(options || {}, 'asyncTask'); this.ctx.logger.info('[ExpressService.asyncTask] 任务入口', { traceId, warehouseId: options && options.warehouse_id, sysPlatformCode: options && options.sys_platform_code, logisticsCode: options && options.logistics_code, orderIds: (Array.isArray(batch) ? batch : []).map(order => Number(order && (order.id || order.order_id))).filter(orderId => Number.isFinite(orderId) && orderId > 0), waveIds: (Array.isArray(batch) ? batch : []).map(order => Number(order && order.wave_id)).filter(waveId => Number.isFinite(waveId) && waveId > 0), }); try { if (!listByWarehousePlatformCode) { this.ctx.logger.warn('[ExpressService.asyncTask] 分配前置条件失败-快递接口配置缺失', { traceId, sysPlatformCode: options && options.sys_platform_code, logisticsCode: options && options.logistics_code, }); throw new Error(`当前订单平台【${options.sys_platform_name}】,快递【${options.logistics_name}】,未配置有效的快递接口`); } if (!matchedPlatform) { this.ctx.logger.warn('[ExpressService.asyncTask] 分配前置条件失败-平台配置缺失', { traceId, sysPlatformCode: options && options.sys_platform_code, logisticsCode: options && options.logistics_code, }); throw new Error(`未找到订单平台【${options.sys_platform_name}】的有效平台配置`); } this.ctx.logger.info('[ExpressService.asyncTask] 调用 createWaybillCode 前', { traceId, batchCount: Array.isArray(batch) ? batch.length : 0, }); await this.createWaybillCode(batch, matchedPlatform, { ...(listByWarehousePlatformCode || {}), trace_id: traceId, }); this.ctx.logger.info('[ExpressService.asyncTask] 调用 createWaybillCode 后', { traceId, batchCount: Array.isArray(batch) ? batch.length : 0, }); } catch (error) { console.error('异步任务执行失败:', error.message); this.ctx.logger.error('[ExpressService.asyncTask] 异步任务执行异常', { traceId, error: error && error.message ? error.message : `${error}`, stack: error && error.stack ? error.stack : '', }); const err_orders = batch.map(order => ({ order_id: order && (order.id || order.order_id), business_key: order.business_key, })); const allOrderIds = err_orders .map(order => Number(order && order.order_id)) .filter(orderId => Number.isFinite(orderId) && orderId > 0); // 查询已成功分配(status=1)的订单,从失败列表中排除,避免误标异常 const successOrderIdSet = new Set(); const orderExpressModel = this.ctx.model && this.ctx.model.OrderExpress; if (orderExpressModel && allOrderIds.length > 0) { try { const successRows = await orderExpressModel.findAll({ where: { order_id: { [this.app.Sequelize.Op.in]: allOrderIds }, status: 1, }, attributes: [ 'order_id' ], raw: true, }); for (const row of Array.isArray(successRows) ? successRows : []) { const successOrderId = Number(row && row.order_id); if (Number.isFinite(successOrderId) && successOrderId > 0) { successOrderIdSet.add(successOrderId); } } if (successOrderIdSet.size > 0) { this.ctx.logger.info('[ExpressService.asyncTask] 排除已成功分配的订单,不标记异常', { traceId, successOrderIds: Array.from(successOrderIdSet), }); } } catch (statusCheckError) { this.ctx.logger.error('[ExpressService.asyncTask] 查询已成功订单状态失败,降级为全量标记', { traceId, error: statusCheckError && statusCheckError.message ? statusCheckError.message : `${statusCheckError}`, }); } } const failedOrderIds = allOrderIds.filter(orderId => !successOrderIdSet.has(orderId)); const logWarehouseId = this.getOrderLogWarehouseId(options && options.warehouse_id); const errorMessage = error && error.message ? String(error.message) : String(error); if (failedOrderIds.length > 0) { this.service.systems.orderPendingException.markPendingException( { ids: failedOrderIds, exception_text: `订单快递分配失败: ${errorMessage}`, } ); } await this.createAllocateExpressFailureLogs(failedOrderIds, errorMessage, logWarehouseId); await this.hardDeleteWaybillAsyncOrderExpressRows(err_orders, { platform_code: options.sys_platform_code, error_message: errorMessage, }); } } /** * 处理订单快递记录。 * 先按订单ID和业务键筛选 wms_order_express,再排除已存在且状态不为 0 的记录, * 对可重试记录重置 retry_count,并为缺失记录补插状态为 0 的快递记录。 *【已使用】 * @param {Array} orders 订单与业务键列表,business_key 可为单值或数组。 * @param {number} orders[].order_id 订单ID。 * @param {number|Array} orders[].business_key 业务键。 * @return {Promise} 处理后的订单列表与运单号列表。 */ /** * 创建运单编码并在事务后触发异步后处理。 * * 事务成功后,如果异步后处理失败,则回补本次事务中已经增加的 * `print_quantity_locked`,避免锁定量长期偏高。 * * @param {Array} orders 运单创建入参。 * @param {Object} [matchedPlatform={}] 平台匹配结果。 * @param {Object} [listByWarehousePlatformCode={}] 按仓库和平台分组的接口信息。 * @return {Promise} 创建结果。 */ async createWaybillCode(orders, matchedPlatform, listByWarehousePlatformCode) { const traceId = this.buildWaybillTraceId({ trace_id: listByWarehousePlatformCode && listByWarehousePlatformCode.trace_id, traceId: listByWarehousePlatformCode && listByWarehousePlatformCode.traceId, }, 'createWaybillCode'); this.ctx.logger.info('[ExpressService.createWaybillCode] 入口请求', { traceId, orderCount: Array.isArray(orders) ? orders.length : 0, orderIds: (Array.isArray(orders) ? orders : []).slice(0, 50).map(order => Number(order && (order.id || order.order_id))).filter(orderId => Number.isFinite(orderId) && orderId > 0), platformCode: matchedPlatform && matchedPlatform.code, requestPlatformCode: matchedPlatform && matchedPlatform.request_platform_code, routePlatformCode: this.resolveWaybillAsyncDispatchPlatformCode(matchedPlatform), defaultExpressInterface: matchedPlatform && matchedPlatform.default_express_interface, warehouseId: listByWarehousePlatformCode && listByWarehousePlatformCode.warehouse_id, }); const { app, ctx } = this; const { Op } = app.Sequelize; const orderExpressModel = ctx.model && ctx.model.OrderExpress; const currentWarehouseId = Number( (listByWarehousePlatformCode && listByWarehousePlatformCode.warehouse_id) || this.getCurrentWarehouseId() ); if (!orderExpressModel || typeof orderExpressModel.findAll !== 'function' || typeof orderExpressModel.update !== 'function' || typeof orderExpressModel.bulkCreate !== 'function') { throw new Error('订单快递模型未初始化'); } const normalizedOrders = await this.normalizeWaybillCreateOrders(orders); if (normalizedOrders.length === 0) { return { orders: [], waybill_codes: [], }; } const orderDeliveryFactory = ctx.model && ctx.model.OrderDeliveryFactory; const storeWarehouseModel = ctx.model && ctx.model.StoreWarehouse; if (!currentWarehouseId) { throw new Error('当前仓库ID不能为空'); } if (!orderDeliveryFactory || typeof orderDeliveryFactory.getCurrentModel !== 'function') { throw new Error('订单主表模型未初始化'); } if (!storeWarehouseModel || typeof storeWarehouseModel.findAll !== 'function' || typeof storeWarehouseModel.update !== 'function') { throw new Error('签约关系模型未初始化'); } const maxAttempts = 3; /** * 执行运单创建事务,并在死锁或锁等待超时时按次数重试。 * @param {number} attempt 当前尝试次数。 * @return {Promise} 运单创建事务结果。 */ const executeCreateWaybillTransactionWithRetry = async attempt => { try { // 【step6】开启事务,确保余额锁定、异常回写和快递记录写入保持原子性。 return await app.model.transaction(async transaction => { // 【step6】事务内先加载订单主表快照,后续所有判断都基于同一批视图。 const orderDeliveryModel = await orderDeliveryFactory.getCurrentModel(currentWarehouseId); const orderItemsFactory = ctx.model && ctx.model.OrderItemsFactory; const orderItemsModel = orderItemsFactory && typeof orderItemsFactory.getCurrentModel === 'function' ? await orderItemsFactory.getCurrentModel(currentWarehouseId) : null; if (!orderDeliveryModel || typeof orderDeliveryModel.findAll !== 'function' || typeof orderDeliveryModel.update !== 'function') { throw new Error('订单主表模型未初始化'); } const orderDeliveryInclude = []; if (orderItemsModel) { orderDeliveryInclude.push({ model: orderItemsModel, as: 'orderItems', attributes: [ 'id', 'order_id', 'item_code', 'item_name', 'plan_qty', 'source_order_code' ], required: false, }); } const orderDeliveryRows = await orderDeliveryModel.findAll({ // 保留后处理 order_list 需要的最小字段集,同时控制在 15 个字段以内。 // warehouse_id 由当前仓库 ID 兜底,因此不额外查询。 attributes: WAYBILL_ORDER_DELIVERY_MIN_ATTRIBUTES, where: { id: { [Op.in]: normalizedOrders.map(order => order.order_id), }, }, include: orderDeliveryInclude, transaction, }); // 补查 dispatch 表:配送中订单可能已迁移,current 表未覆盖的从 dispatch 补齐 const currentCoveredOrderIds = new Set( (Array.isArray(orderDeliveryRows) ? orderDeliveryRows : []).map(row => Number(row && row.id)) ); const uncoveredOrderIds = normalizedOrders .map(o => o.order_id) .filter(id => !currentCoveredOrderIds.has(id)); let dispatchOrderDeliveryRows = []; if (uncoveredOrderIds.length > 0) { ctx.logger.info('[ExpressService.createWaybillCode] dispatch 补查 uncoveredOrderIds=%s', [ ...new Set(uncoveredOrderIds) ].join(',')); const dispatchModel = orderDeliveryFactory && typeof orderDeliveryFactory.getDispatchModel === 'function' ? await orderDeliveryFactory.getDispatchModel(currentWarehouseId) : null; if (dispatchModel && typeof dispatchModel.findAll === 'function') { // dispatch 表 items 关联可能不同,去掉 include 避免关联查询报错 dispatchOrderDeliveryRows = await dispatchModel.findAll({ attributes: WAYBILL_ORDER_DELIVERY_MIN_ATTRIBUTES, where: { id: { [Op.in]: uncoveredOrderIds }, }, transaction, }); ctx.logger.info('[ExpressService.createWaybillCode] dispatch 补查结果 count=%d', dispatchOrderDeliveryRows.length); // 补查 dispatch 表的商品明细(物流 API 需要 items 信息) if (dispatchOrderDeliveryRows.length > 0) { const dispatchItemsFactory = ctx.model && ctx.model.OrderItemsFactory; const dispatchItemsModel = dispatchItemsFactory && typeof dispatchItemsFactory.getDispatchModel === 'function' ? await dispatchItemsFactory.getDispatchModel(currentWarehouseId) : null; if (dispatchItemsModel && typeof dispatchItemsModel.findAll === 'function') { const dispatchOrderIds = dispatchOrderDeliveryRows.map(row => Number(row.id)).filter(id => id > 0); const dispatchItems = await dispatchItemsModel.findAll({ where: { order_id: { [Op.in]: dispatchOrderIds } }, attributes: [ 'id', 'order_id', 'item_code', 'item_name', 'plan_qty', 'source_order_code' ], raw: true, transaction, }); // 将 items 以 Sequelize include 格式附加到 dispatch 行上 if (Array.isArray(dispatchItems) && dispatchItems.length > 0) { const itemsByOrderId = new Map(); for (const item of dispatchItems) { const oid = Number(item.order_id); if (!itemsByOrderId.has(oid)) itemsByOrderId.set(oid, []); itemsByOrderId.get(oid).push(item); } for (const row of dispatchOrderDeliveryRows) { const oid = Number(row.id); row.orderItems = itemsByOrderId.get(oid) || []; } } } } } else { ctx.logger.warn('[ExpressService.createWaybillCode] dispatch 模型不可用'); } } const allOrderDeliveryRows = [ ...(Array.isArray(orderDeliveryRows) ? orderDeliveryRows : []), ...dispatchOrderDeliveryRows ]; const orderDeliveryMap = this.buildWaybillOrderDeliveryMap(allOrderDeliveryRows); const existingCompletedRows = await orderExpressModel.findAll({ where: { warehouse_id: currentWarehouseId, [Op.or]: normalizedOrders.map(order => ({ order_id: order.order_id, business_key: order.business_key, })), }, attributes: [ 'order_id', 'business_key', 'status' ], raw: true, transaction, }); const completedOrderKeySet = new Set(); for (const row of Array.isArray(existingCompletedRows) ? existingCompletedRows : []) { const orderId = Number(row && row.order_id); const businessKey = Number(row && row.business_key); const status = Number(row && row.status); if (Number.isFinite(orderId) && orderId > 0 && Number.isInteger(businessKey) && status === 1) { completedOrderKeySet.add(`${orderId}:${businessKey}`); } } const pendingOrders = normalizedOrders.filter(order => !completedOrderKeySet.has(`${order.order_id}:${order.business_key}`)); if (pendingOrders.length === 0) { return { orders: [], waybill_codes: [], }; } // 跳过已取消订单:已取消订单不允许取号,且不标记异常、不写失败日志。 const cancelledOrderIdSet = new Set( allOrderDeliveryRows .filter(row => String(row.status || '').trim() === 'cancel') .map(row => Number(row.id)) .filter(id => Number.isFinite(id) && id > 0) ); let effectivePendingOrders = pendingOrders; if (cancelledOrderIdSet.size > 0) { effectivePendingOrders = pendingOrders.filter(order => !cancelledOrderIdSet.has(Number(order.order_id))); ctx.logger.info('[ExpressService.createWaybillCode] 跳过已取消订单取号', { traceId, skippedOrderIds: Array.from(cancelledOrderIdSet), }); } if (effectivePendingOrders.length === 0) { return { orders: [], waybill_codes: [], }; } const { relationGroupMap, missingOrderIds, } = this.buildWaybillCreateRelationGroups(effectivePendingOrders, allOrderDeliveryRows, currentWarehouseId); const relationWhereList = Array.from(relationGroupMap.values()).map(group => ({ store_id: group.store_id, warehouse_id: group.warehouse_id, })); const relationRows = relationWhereList.length > 0 ? await storeWarehouseModel.findAll({ attributes: [ 'id', 'store_id', 'warehouse_id', 'print_quantity', 'print_quantity_locked', 'policy_config' ], where: { [Op.or]: relationWhereList, }, raw: true, transaction, lock: transaction.LOCK.UPDATE, }) : []; const relationMap = new Map(); for (const relation of Array.isArray(relationRows) ? relationRows : []) { const relationKey = `${Number(relation.store_id || 0)}:${Number(relation.warehouse_id || 0)}`; if (relationKey !== '0:0') { relationMap.set(relationKey, relation); } } const { successOrderKeySet, failedOrdersByReason, balanceWarnings, } = await this.collectWaybillRelationProcessingState(relationGroupMap, relationMap); if (missingOrderIds.length > 0) { const exceptionText = '订单不存在或不属于当前仓库'; failedOrdersByReason.set(exceptionText, (failedOrdersByReason.get(exceptionText) || []).concat(missingOrderIds)); } // 【step5】事务内统一回写失败订单异常,避免成功与失败状态分离。 await this.writeWaybillOrderExceptions(orderDeliveryModel, failedOrdersByReason, transaction); // 补写 dispatch 表 order_flag:dispatch 订单的异常信息需单独写(current 表写不到) if (dispatchOrderDeliveryRows.length > 0 && failedOrdersByReason.size > 0) { try { await this.writeDispatchOrderFlags(dispatchOrderDeliveryRows, failedOrdersByReason, transaction); } catch (dispatchFlagErr) { ctx.logger.warn('[ExpressService.createWaybillCode] 补写 dispatch order_flag 失败: %s', dispatchFlagErr && dispatchFlagErr.message ? dispatchFlagErr.message : dispatchFlagErr); } } if (balanceWarnings.length > 0) { ctx.logger.warn('[ExpressService.createWaybillCode] 余额不足但允许超额分配: %s', balanceWarnings.join(';')); } const successOrders = effectivePendingOrders.filter(order => successOrderKeySet.has(`${order.order_id}:${order.business_key}`)); const existingRows = await orderExpressModel.findAll({ where: { [Op.or]: successOrders.map(order => ({ order_id: order.order_id, business_key: order.business_key, warehouse_id: currentWarehouseId, })), }, attributes: [ 'id', 'order_id', 'business_key', 'status', 'retry_count', 'warehouse_id' ], raw: true, transaction, lock: transaction.LOCK.UPDATE, }); const existingMap = new Map(); const retryIds = []; for (const row of Array.isArray(existingRows) ? existingRows : []) { const orderId = Number(row && row.order_id); const businessKey = Number(row && row.business_key); if (!Number.isFinite(orderId) || orderId <= 0 || !Number.isInteger(businessKey)) { continue; } const orderKey = `${orderId}:${businessKey}`; existingMap.set(orderKey, row); // 过滤 status != 0 的已存在记录。 if (Number(row && row.status) === 0) { retryIds.push(row.id); } } // 【step6】先重置可重试记录,再补插缺失记录。 const retryableIds = Array.from(new Set(retryIds.filter(id => Number.isFinite(Number(id)) && Number(id) > 0))); if (retryableIds.length > 0) { await orderExpressModel.update({ retry_count: 0, }, { where: { id: { [Op.in]: retryableIds, }, }, transaction, }); } const successOrdersWithDelivery = successOrders .filter(order => { const existingRow = existingMap.get(`${order.order_id}:${order.business_key}`); return !existingRow || Number(existingRow.status) === 0; }) .map(order => ({ ...order, order_delivery: orderDeliveryMap.get(order.order_id) || null, })); if (successOrdersWithDelivery.length > 0) { const successOrderIds = Array.from(new Set(successOrdersWithDelivery .map(order => Number(order.order_id)) .filter(orderId => Number.isFinite(orderId) && orderId > 0))); if (successOrderIds.length > 0) { // 仅对非配送中(step != 4)的订单更新 step 为 2;配送中订单保持 step 不变 const step4OrderIdSet = new Set(); for (const orderId of successOrderIds) { const orderRow = orderDeliveryMap.get(orderId); if (orderRow && Number(orderRow.step) === 4) { step4OrderIdSet.add(orderId); } } const stepUpdatableIds = successOrderIds.filter(id => !step4OrderIdSet.has(id)); if (stepUpdatableIds.length > 0) { await orderDeliveryModel.update({ step: 2, updated_at: new Date(), }, { where: { id: { [Op.in]: stepUpdatableIds, }, status: { [Op.ne]: 'cancel', }, }, transaction, }); } } } if (successOrdersWithDelivery.length === 0) { return { orders: [], waybill_codes: [], }; } // 【step6】组装待插入记录,保持已存在且非 0 状态的记录不被覆盖。 const rowsToCreate = []; for (const order of successOrders) { const orderKey = `${order.order_id}:${order.business_key}`; const existingRow = existingMap.get(orderKey); if (existingRow) { const status = Number(existingRow.status); if (status !== 0) { continue; } continue; } ctx.logger.info('[DEBUG] rowsToCreate order', JSON.stringify({ order_id: order.order_id, store_id: order.store_id, has_delivery: !!order.order_delivery, delivery_store_id: order.order_delivery && order.order_delivery.store_id, delivery_doc: order.order_delivery && order.order_delivery.delivery_order_code, })); rowsToCreate.push({ order_id: order.order_id, business_key: order.business_key, status: 0, retry_count: 0, warehouse_id: currentWarehouseId, store_id: order.store_id || null, logistics_code: (listByWarehousePlatformCode && listByWarehousePlatformCode.sys_express_code) || '', delivery_order_code: (orderDeliveryMap.get(order.order_id) && orderDeliveryMap.get(order.order_id).delivery_order_code) || null, source_order_codes: (orderDeliveryMap.get(order.order_id) && orderDeliveryMap.get(order.order_id).source_order_codes) || null, }); } const relationLockMap = this.buildWaybillRelationLockMap(successOrders, orderDeliveryMap, existingMap); if (relationLockMap.size > 0) { await this.lockWaybillRelationBalance(relationLockMap, relationMap, storeWarehouseModel, transaction); } // 【step6】批量插入新快递记录后,事务提交。 if (rowsToCreate.length > 0) { await orderExpressModel.bulkCreate(rowsToCreate, { transaction, }); } return { orders: successOrdersWithDelivery, waybill_codes: [], }; }); } catch (err) { const errorCode = err && err.parent && err.parent.code; const errorMessage = String((err && err.message) || (err && err.parent && err.parent.message) || ''); const isRetryableDeadlock = errorCode === 'ER_LOCK_DEADLOCK' || errorCode === 'ER_LOCK_WAIT_TIMEOUT' || errorMessage.includes('Deadlock found when trying to get lock'); if (!isRetryableDeadlock || attempt >= maxAttempts) { throw err; } ctx.logger.warn(`[ExpressService.createWaybillCode] deadlock retry attempt=${attempt} maxAttempts=${maxAttempts} code=${errorCode || 'UNKNOWN'} message=${errorMessage}`); await new Promise(resolve => setTimeout(resolve, 50 * attempt)); return executeCreateWaybillTransactionWithRetry(attempt + 1); } }; this.ctx.logger.info('[ExpressService.createWaybillCode] DB 回写事务前', { traceId, orderCount: normalizedOrders.length, }); const createWaybillResult = await executeCreateWaybillTransactionWithRetry(1); this.ctx.logger.info('[ExpressService.createWaybillCode] DB 回写事务后', { traceId, successOrderCount: Array.isArray(createWaybillResult && createWaybillResult.orders) ? createWaybillResult.orders.length : 0, }); try { const dispatchPlatformCode = this.resolveWaybillAsyncDispatchPlatformCode(matchedPlatform); if (Array.isArray(createWaybillResult.orders) && createWaybillResult.orders.length > 0 && matchedPlatform && dispatchPlatformCode) { try { this.ctx.logger.info('[ExpressService.createWaybillCode] 平台后处理调用前', { traceId, platformInterface: dispatchPlatformCode, orderCount: createWaybillResult.orders.length, }); await this.dispatchWaybillAsyncPlatform(dispatchPlatformCode, { matchedPlatform, listByWarehousePlatformCode, orders: createWaybillResult.orders, trace_id: traceId, }); this.ctx.logger.info('[ExpressService.createWaybillCode] 平台后处理调用后', { traceId, platformInterface: dispatchPlatformCode, }); } catch (error) { throw error; } } } catch (error) { const restoreRelationMap = new Map(); for (const order of Array.isArray(createWaybillResult.orders) ? createWaybillResult.orders : []) { const orderDelivery = order && order.order_delivery; const storeId = Number(order && order.store_id) || Number(orderDelivery && orderDelivery.store_id) || 0; const warehouseId = Number(order && order.warehouse_id) || Number(orderDelivery && orderDelivery.warehouse_id) || 0; if (!Number.isFinite(storeId) || storeId <= 0 || !Number.isFinite(warehouseId) || warehouseId <= 0) { continue; } const relationKey = `${storeId}:${warehouseId}`; const currentRelation = restoreRelationMap.get(relationKey) || { store_id: storeId, warehouse_id: warehouseId, success_count: 0, }; currentRelation.success_count += 1; restoreRelationMap.set(relationKey, currentRelation); } console.error('运单后处理失败,准备回补锁定量:', error.message, 'restoreRelationList', Array.from(restoreRelationMap.values())); this.ctx.logger.error('[ExpressService.createWaybillCode] 平台后处理异常,准备回补锁定量', { traceId, error: error && error.message ? error.message : `${error}`, stack: error && error.stack ? error.stack : '', restoreRelationList: Array.from(restoreRelationMap.values()), }); if (restoreRelationMap.size > 0) { const restoreRelationList = Array.from(restoreRelationMap.values()); const restoreRows = await storeWarehouseModel.findAll({ attributes: [ 'id', 'store_id', 'warehouse_id', 'print_quantity_locked' ], where: { [Op.or]: restoreRelationList.map(item => ({ store_id: item.store_id, warehouse_id: item.warehouse_id, })), }, raw: true, }); const restoreRowMap = new Map(); for (const row of Array.isArray(restoreRows) ? restoreRows : []) { const relationKey = `${Number(row && row.store_id) || 0}:${Number(row && row.warehouse_id) || 0}`; if (relationKey !== '0:0') { restoreRowMap.set(relationKey, row); } } const canIncrementLockedQuantity = typeof storeWarehouseModel.increment === 'function'; for (const item of restoreRelationList) { const relationKey = `${item.store_id}:${item.warehouse_id}`; const row = restoreRowMap.get(relationKey); if (!row) { continue; } const currentLockedQuantity = Math.max(0, Number(row.print_quantity_locked || 0)); const restoreQuantity = Math.min(currentLockedQuantity, item.success_count); if (restoreQuantity <= 0) { continue; } if (canIncrementLockedQuantity) { await storeWarehouseModel.increment('print_quantity_locked', { by: -restoreQuantity, where: { id: row.id, }, }); continue; } await storeWarehouseModel.update({ print_quantity_locked: currentLockedQuantity - restoreQuantity, }, { where: { id: row.id, }, }); } } throw error; } this.ctx.logger.info('[ExpressService.createWaybillCode] 处理完成', { traceId, successOrderCount: Array.isArray(createWaybillResult && createWaybillResult.orders) ? createWaybillResult.orders.length : 0, }); return createWaybillResult; } } module.exports = ExpressService;