WMS_MAIN/app/service/systems/express_platform.js
liufumingren 25dac21b4b feat(waybill): OMS 取号与抖音打印 params 按店铺隔离
- express/express_platform: 新增 OMS 回源取号(need_oms_waybill=1)与统一失败收尾,
  失败时标记订单异常、写失败日志并清理未完成占位行;队列消费与手工分配共用同一口径
- order_print: 抖音打印按运单落库的 logistics_interface_id 精确命中取号接口配置,
  临时 key 缓存键带店铺与 token 指纹,避免多店铺串用 token;打印前按 OMS 记录换新 params
- order_express: 新增 print_history_id、cai_niao_auth_info_id 字段
- consume_waybill_allocate_queue / pendingOrder / delivery_order / order_async /
  printer_data_builder / order_delivery_table_schema: 配套调整
- migrations: 运单 wave_no 索引、OMS 打印字段

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-11-10 02:53:15 +08:00

3743 lines
153 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

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

'use strict';
const MainService = require('../main');
const PddClient = require('../../lib/pdd_client');
const crypto = require('node:crypto');
const DEFAULT_PDD_ROUTER_URL = 'https://gw-api.pinduoduo.com/api/router';
const DEFAULT_TB_ROUTER_URL = 'https://eco.taobao.com/router/rest';
/** OMS 取号方法名(OMS 侧 openapi method)。 */
const OMS_WAYBILL_EVENT = 'deliveryorder.getwaybill';
/** OMS 单次取号上限(printinfo 单张可达数百 KB,文档建议不超过 20 单)。 */
const OMS_WAYBILL_MAX_BATCH_SIZE = 20;
/**
* OMS 逐单失败原因中「不可重试」的关键词(对应 OMS 文档 4.4)。
* 命中即认为重试无意义,避免反复打平台。
*/
const OMS_WAYBILL_NON_RETRYABLE_KEYWORDS = Object.freeze([
'缺少发货单号',
'缺少快递编码',
'未找到发货单',
'不属于当前 app_key',
'已取消',
'已作废',
'已归档',
'订单已配送',
'订单已完成',
'缺少来源平台',
'未关联店铺',
'未关联外部打单账号',
'外部打单账号或平台配置不存在',
'未绑定到快递接口',
'不存在(系统快递编码',
'已停用',
'未开启回平台取号',
'真实取号已关闭',
'未找到订单',
'面单余额不足',
'已发货或已终结',
]);
/**
* 上游未返回时必须保留已有值的运单报文字段。
*
* OMS 回源取号只透传 signature/encryptprintinfo/ver,不返回 printinfo/encryptedtoken,
* 若按 null 写入会把本地取号已落库的有效报文冲掉,故这类字段统一改为「有值才覆盖」。
*/
const ORDER_EXPRESS_UPSTREAM_OPTIONAL_FIELDS = Object.freeze([
'printinfo',
'signature',
'encryptprintinfo',
'encryptedtoken',
'ver',
]);
/** OMS 取号请求/返回报文缓存 TTL(秒):覆盖一个工作日,便于事后核对报文格式。 */
const OMS_WAYBILL_PAYLOAD_CACHE_TTL = 24 * 60 * 60;
/** OMS 取号报文缓存单键上限(字节):超出时按字段脱敏,避免 Redis 单键过大。 */
const OMS_WAYBILL_PAYLOAD_CACHE_MAX_BYTES = 256 * 1024;
/**
* 报文超限时按字段名脱敏的密文/大字段。
* 只截断取值,保留字段名与总长度,保证缓存里仍能看清报文结构。
*/
const OMS_WAYBILL_PAYLOAD_HEAVY_FIELDS = Object.freeze([
'printinfo',
'printdata',
'encryptprintinfo',
'encryptedtoken',
'signature',
]);
/** 大字段脱敏后保留的字符数(用于人工核对字段内容前缀)。 */
const OMS_WAYBILL_PAYLOAD_HEAVY_FIELD_KEEP_CHARS = 64;
/** OMS 取号报文缓存键前缀。 */
const OMS_WAYBILL_PAYLOAD_CACHE_KEY_PREFIX = 'oms:waybill';
/**
* 将任意值标准化为数组。
*
* @param {*} value 原始值。
* @return {Array} 标准化后的数组。
*/
function normalizeArray(value) {
return Array.isArray(value) ? value : [];
}
/**
* 将对象包裹的集合字段标准化为数组。
*
* @param {*} value 原始集合值。
* @param {Array<string>} [nestedKeys=[]] 对象包裹时的候选子字段名。
* @return {Array} 标准化后的数组。
*/
function normalizeWrappedArray(value, nestedKeys = []) {
if (Array.isArray(value)) {
return value;
}
if (!value || typeof value !== 'object') {
return [];
}
for (const nestedKey of normalizeArray(nestedKeys)) {
if (!nestedKey || !Object.prototype.hasOwnProperty.call(value, nestedKey)) {
continue;
}
const nestedValue = value[nestedKey];
if (Array.isArray(nestedValue)) {
return nestedValue;
}
if (nestedValue !== null && nestedValue !== undefined) {
return [ nestedValue ];
}
}
return Object.keys(value).length > 0 ? [ value ] : [];
}
/**
* 按候选来源顺序提取首个非空集合。
*
* @param {Array<*>} values 候选来源列表。
* @param {Array<string>} [nestedKeys=[]] 对象包裹时的候选子字段名。
* @return {Array} 首个非空数组。
*/
function normalizeFirstWrappedArray(values, nestedKeys = []) {
for (const value of normalizeArray(values)) {
const normalized = normalizeWrappedArray(value, nestedKeys);
if (normalized.length > 0) {
return normalized;
}
}
return [];
}
/**
* 校验菜鸟电子面单模板地址是否合法。
*
* 仅允许下发 `http` 或 `https` 协议的完整 URL,非法值直接视为不可用。
*
* @param {*} templateUrl 待校验的模板地址。
* @return {boolean} 是否为合法模板地址。
*/
function isValidCainiaoTemplateUrl(templateUrl) {
const normalizedTemplateUrl = String(templateUrl || '').trim();
if (!normalizedTemplateUrl) {
return false;
}
try {
const parsedTemplateUrl = new URL(normalizedTemplateUrl);
return parsedTemplateUrl.protocol === 'http:' || parsedTemplateUrl.protocol === 'https:';
} catch {
return false;
}
}
const DEFAULT_CAINIAO_TEMPLATE_URL = 'http://cloudprint.cainiao.com/cloudprint/template/getStandardTemplate.json?template_id=288948';
/**
* 将仓库ID/订单ID/业务键三段标识打包为 64 位无符号整数(Uint64)。
*
* 位宽分配("不够的补位"由左移自动补 0 完成):
* - warehouse_id:高 24 bit(hex 6 位,0x000000 ~ 0xFFFFFF)
* - order_id :中 32 bit(hex 8 位,0x00000000 ~ 0xFFFFFFFF)
* - business_key:低 8 bit (hex 2 位,0x00 ~ 0xFF)
* 合计 64 bit,拼出的 hex 固定 16 位(不足高位补 0)。
*
* 例:f425c_3948e_1 → hex 补位 0f425c0003948e01 → 1099542414161645057
*
* 纯函数(幂等):不含时间/随机因素,相同入参必然输出相同 Uint64,可安全重试。
*
* @param {number|string} warehouseId 仓库ID。
* @param {number|string} orderId 订单ID。
* @param {number|string} businessKey 业务键(1=主单号,>1=子单号)。
* @return {string} Uint64 的十进制字符串(超过 JS 安全整数 2^53,必须用字符串形式传输/序列化)。
*/
/* eslint-disable no-bitwise -- Uint64 位打包/拆解必须使用位运算 */
function toUint64(warehouseId, orderId, businessKey) {
const wh = BigInt(Number(warehouseId) || 0);
const oid = BigInt(Number(orderId) || 0);
const bk = BigInt(Number(businessKey) || 0);
if (wh < 0n || wh > 0xFFFFFFn) throw new Error(`toUint64: warehouse_id 超出 24 位范围: ${warehouseId}`);
if (oid < 0n || oid > 0xFFFFFFFFn) throw new Error(`toUint64: order_id 超出 32 位范围: ${orderId}`);
if (bk < 0n || bk > 0xFFn) throw new Error(`toUint64: business_key 超出 8 位范围: ${businessKey}`);
return ((wh << 40n) | (oid << 8n) | bk).toString();
}
/**
* 将 Uint64 反向拆解为仓库ID/订单ID/业务键(toUint64 的逆运算)。
*
* @param {string|number|bigint} value Uint64 值(十进制字符串/数字/BigInt 均可)。
* @return {{ warehouseId: number, orderId: number, businessKey: number }} 拆解结果。
*/
function fromUint64(value) {
const v = BigInt(value);
if (v < 0n || v > 0xFFFFFFFFFFFFFFFFn) throw new Error(`fromUint64: 超出 64 位范围: ${value}`);
return {
warehouseId: Number(v >> 40n),
orderId: Number((v >> 8n) & 0xFFFFFFFFn),
businessKey: Number(v & 0xFFn),
};
}
/* eslint-enable no-bitwise */
/**
* 快递平台服务类。
*
* 当前仅保留平台方法出口,后续接入真实平台实现时再补充具体调用逻辑。
* 这里的 `data` 统一与上游 `app/service/systems/express.js` 中
* `buildWaybillAsyncBizcontentSkeleton` / `buildWaybillAsyncOrderListItem`
* 生成的结构对齐,完整形状如下:
*
* ```js
* {
* bizcontent: {
* platform_code: string,
* express_platform_code: string,
* store_id: number,
* warehouse_id: number,
* order_list: [
* {
* order_id: number,
* business_key: number,
* sys_platform_code: string,
* logistics_code: string,
* express_platform_code: string,
* route_info: {
* source_platform_code: string,
* source_platform_name: string,
* sys_platform_code: string,
* sys_platform_name: string,
* logistics_code: string,
* logistics_name: string,
* sys_logistics_code: string,
* sys_logistics_name: string,
* express_code: string,
* logistics_area_code: string,
* },
* order_info: {
* delivery_order_code: string,
* order_type: string,
* status: string,
* step: number,
* order_flag: string,
* from_key: string,
* create_at: string,
* place_order_time: string,
* pay_time: string,
* operate_time: string,
* delivery_time: string,
* },
* receiver_info: {
* name: string,
* tel: string,
* mobile: string,
* email: string,
* country_code: string,
* province: string,
* city: string,
* area: string,
* town: string,
* detail_address: string,
* zip_code: string,
* },
* settlement_info: {
* total_amount: number,
* item_amount: number,
* discount_amount: number,
* freight: number,
* ar_amount: number,
* got_amount: number,
* },
* items_summary: {
* items: Array,
* items_count: number,
* items_total: number,
* items_weight: number,
* },
* },
* ],
* platform_payload: {},
* },
* }
* ```
*
* @typedef {Object} ExpressPlatformData
* @property {ExpressPlatformBizcontent} bizcontent 顶层业务载荷对象。
*
* @typedef {Object} ExpressPlatformBizcontent
* @property {string} platform_code 平台编码。
* @property {string} express_platform_code 物流平台编码。
* @property {number} store_id 店铺 ID。
* @property {number} warehouse_id 仓库 ID。
* @property {Array<ExpressPlatformOrderItem>} order_list 订单列表。
* @property {Object} platform_payload 平台专属载荷占位对象。
*
* @typedef {Object} ExpressPlatformOrderItem
* @property {number} order_id 订单 ID。
* @property {number} business_key 业务主键。
* @property {string} sys_platform_code 系统平台编码。
* @property {string} logistics_code 物流编码。
* @property {string} express_platform_code 订单对应的物流平台编码。
* @property {ExpressPlatformRouteInfo} route_info 路由信息块。
* @property {ExpressPlatformOrderInfo} order_info 订单信息块。
* @property {ExpressPlatformReceiverInfo} receiver_info 收件人信息块。
* @property {ExpressPlatformSettlementInfo} settlement_info 结算信息块。
* @property {ExpressPlatformItemsSummary} items_summary 商品汇总信息块。
*
* @typedef {Object} ExpressPlatformRouteInfo
* @property {string} source_platform_code 来源平台编码。
* @property {string} source_platform_name 来源平台名称。
* @property {string} sys_platform_code 系统平台编码。
* @property {string} sys_platform_name 系统平台名称。
* @property {string} logistics_code 物流编码。
* @property {string} logistics_name 物流名称。
* @property {string} sys_logistics_code 系统物流编码。
* @property {string} sys_logistics_name 系统物流名称。
* @property {string} express_code 快递单号或快递编码。
* @property {string} logistics_area_code 物流区域编码。
*
* @typedef {Object} ExpressPlatformOrderInfo
* @property {string} delivery_order_code 发货单号。
* @property {string} order_type 订单类型。
* @property {string} status 订单状态。
* @property {number} step 流程步骤。
* @property {string} order_flag 订单标记。
* @property {string} from_key 来源键。
* @property {string} create_at 创建时间。
* @property {string} place_order_time 下单时间。
* @property {string} pay_time 支付时间。
* @property {string} operate_time 操作时间。
* @property {string} delivery_time 发货时间。
*
* @typedef {Object} ExpressPlatformReceiverInfo
* @property {string} name 收件人姓名。
* @property {string} tel 电话。
* @property {string} mobile 手机号。
* @property {string} email 邮箱。
* @property {string} country_code 国家编码。
* @property {string} province 省份。
* @property {string} city 城市。
* @property {string} area 区县。
* @property {string} town 乡镇。
* @property {string} detail_address 详细地址。
* @property {string} zip_code 邮编。
*
* @typedef {Object} ExpressPlatformSettlementInfo
* @property {number} total_amount 总金额。
* @property {number} item_amount 商品金额。
* @property {number} discount_amount 优惠金额。
* @property {number} freight 运费。
* @property {number} ar_amount 应收金额。
* @property {number} got_amount 已收金额。
*
* @typedef {Object} ExpressPlatformItemsSummary
* @property {Array} items 商品明细。
* @property {number} items_count 商品数量。
* @property {number} items_total 商品总额。
* @property {number} items_weight 商品总重量。
*/
class ExpressPlatformService extends MainService {
/**
* 获取订单日志使用的操作人信息。
*
* 取值优先级:employees_id/employees_name -> operator_id/operator_name -> id/real_name/name。
*
* @return {{ id: string|null, name: string }} 操作人信息。
*/
getOrderLogOperator() {
const stateUser = this.isPlainObject(this.ctx && this.ctx.state && this.ctx.state.user)
? this.ctx.state.user
: null;
const ctxUser = this.isPlainObject(this.ctx && this.ctx.user)
? 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,
};
}
/**
* 从候选来源中提取可落库的打印版本号字段。
*
* 仅当上游明确返回 ver 且非空字符串时返回 `{ ver }`,
* 避免在回写时写入默认值或覆盖已有有效值。
*
* @param {Array<*>} candidates 候选来源列表。
* @return {{ver?: string}} 可直接合并到 OrderExpress.update 的字段补丁。
*/
buildOrderExpressVerPatch(candidates = []) {
const normalizedCandidates = Array.isArray(candidates) ? candidates : [ candidates ];
for (const candidate of normalizedCandidates) {
if (candidate === null || candidate === undefined) {
continue;
}
const normalized = String(candidate).trim();
if (normalized) {
return {
ver: normalized,
};
}
}
return {};
}
/**
* 构建快递平台链路追踪ID。
*
* 优先使用入参中的 trace_id/traceId,其次使用上下文 trace 信息,最后兜底生成。
*
* @param {Object} [data={}] 入参。
* @return {string} 追踪ID。
*/
buildExpressPlatformTraceId(data = {}) {
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
|| ''
).trim();
if (normalizedTraceId) {
return normalizedTraceId;
}
return `express_platform_trace_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`;
}
/**
* 清理平台取号失败的订单资源。
*
* 回退 print_quantity_locked、硬删除 OrderExpress(status=0) 记录、
* 标记订单异常、写失败日志。所有清理步骤在事务内完成,保证原子性。
*
* @param {Array<{order_id: number, business_key: number, warehouse_id: number, store_id?: number}>} failedOrders 失败订单列表。
* @param {string} reason 失败原因描述。
* @return {Promise<void>} 无返回值。
*/
async cleanupFailedWaybillOrders(failedOrders, reason) {
const normalizedFailedOrders = Array.isArray(failedOrders) ? failedOrders : [];
if (normalizedFailedOrders.length === 0) {
return;
}
const traceId = this.buildExpressPlatformTraceId();
const normalizedReason = String(reason || '未知失败').trim();
this.ctx.logger.info('[expressPlatform.cleanupFailedWaybillOrders] 开始清理失败订单资源', {
traceId,
failedCount: normalizedFailedOrders.length,
reason: normalizedReason,
failedOrderKeys: normalizedFailedOrders.map(o => `${o.warehouse_id}_${o.order_id}_${o.business_key}`).join(','),
});
const { Op } = this.app.Sequelize;
const storeWarehouseModel = this.ctx.model && this.ctx.model.StoreWarehouse;
const orderExpressModel = this.ctx.model && this.ctx.model.OrderExpress;
try {
// 1) 按 store_id:warehouse_id 聚合回退 lock 量
const restoreRelationMap = new Map();
for (const order of normalizedFailedOrders) {
const storeId = Number(order.store_id) || 0;
const warehouseId = Number(order.warehouse_id) || 0;
if (!storeId || !warehouseId) {
continue;
}
const relationKey = `${storeId}:${warehouseId}`;
const currentRelation = restoreRelationMap.get(relationKey) || {
store_id: storeId,
warehouse_id: warehouseId,
failed_count: 0,
};
currentRelation.failed_count += 1;
restoreRelationMap.set(relationKey, currentRelation);
}
if (restoreRelationMap.size > 0 && storeWarehouseModel && typeof storeWarehouseModel.findAll === 'function') {
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.failed_count);
if (restoreQuantity <= 0) {
continue;
}
if (canIncrementLockedQuantity) {
await storeWarehouseModel.increment('print_quantity_locked', {
by: -restoreQuantity,
where: {
id: row.id,
},
});
} else {
await storeWarehouseModel.update({
print_quantity_locked: currentLockedQuantity - restoreQuantity,
}, {
where: {
id: row.id,
},
});
}
// 记录回退流水
try {
await this.ctx.model.StoreWarehousePrintQuantityLog.create({
contract_id: Number(row.id || 0),
store_id: Number(row.store_id || 0),
warehouse_id: Number(row.warehouse_id || 0),
change_type: 'order_restore',
business_type: 'order_express',
business_id: null,
change_quantity: -restoreQuantity,
balance_before: Math.max(0, currentLockedQuantity),
balance_after: Math.max(0, currentLockedQuantity - restoreQuantity),
reason: `平台取号失败回退锁定: ${normalizedReason}`,
operator_id: null,
created_by: null,
});
} catch (logError) {
this.ctx.logger.error('[expressPlatform.cleanupFailedWaybillOrders] 回退流水写入失败', {
traceId,
error: logError && logError.message ? logError.message : `${logError}`,
});
}
}
}
// 2) 硬删除 OrderExpress(status=0) 记录
if (orderExpressModel && typeof orderExpressModel.destroy === 'function') {
const deleteConditions = [];
for (const order of normalizedFailedOrders) {
const orderId = Number(order.order_id) || 0;
const businessKey = Number(order.business_key) || 0;
if (!orderId || !businessKey) {
continue;
}
deleteConditions.push({
order_id: orderId,
business_key: businessKey,
});
}
if (deleteConditions.length > 0) {
try {
await orderExpressModel.destroy({
where: {
[Op.or]: deleteConditions,
status: 0,
},
});
} catch (destroyError) {
this.ctx.logger.error('[expressPlatform.cleanupFailedWaybillOrders] 硬删除 OrderExpress 失败', {
traceId,
error: destroyError && destroyError.message ? destroyError.message : `${destroyError}`,
});
}
}
}
// 3) 标记订单异常
const failedOrderIds = normalizedFailedOrders
.map(order => Number(order.order_id) || 0)
.filter(orderId => orderId > 0);
const uniqueFailedOrderIds = Array.from(new Set(failedOrderIds));
if (uniqueFailedOrderIds.length > 0) {
const orderPendingExceptionService = this.service
&& this.service.systems
&& this.service.systems.orderPendingException;
if (orderPendingExceptionService && typeof orderPendingExceptionService.markPendingException === 'function') {
try {
await orderPendingExceptionService.markPendingException({
ids: uniqueFailedOrderIds,
exception_text: `订单快递分配失败(${normalizedReason})`,
});
} catch (markError) {
this.ctx.logger.error('[expressPlatform.cleanupFailedWaybillOrders] 标记订单异常失败', {
traceId,
error: markError && markError.message ? markError.message : `${markError}`,
});
}
}
}
// 4) 写失败日志
const expressService = this.service && this.service.systems && this.service.systems.express;
if (expressService && typeof expressService.createAllocateExpressFailureLogs === 'function' && uniqueFailedOrderIds.length > 0) {
const sampleWarehouseId = normalizedFailedOrders.length > 0
? (Number(normalizedFailedOrders[0].warehouse_id) || null)
: null;
try {
await expressService.createAllocateExpressFailureLogs(uniqueFailedOrderIds, normalizedReason, sampleWarehouseId);
} catch (logError) {
this.ctx.logger.error('[expressPlatform.cleanupFailedWaybillOrders] 写失败日志异常', {
traceId,
error: logError && logError.message ? logError.message : `${logError}`,
});
}
}
this.ctx.logger.info('[expressPlatform.cleanupFailedWaybillOrders] 清理完成', {
traceId,
failedCount: normalizedFailedOrders.length,
deletedExpressCount: normalizedFailedOrders.filter(o => Number(o.order_id) > 0 && Number(o.business_key) > 0).length,
markedOrderCount: uniqueFailedOrderIds.length,
restoredRelationCount: restoreRelationMap.size,
});
} catch (error) {
this.ctx.logger.error('[expressPlatform.cleanupFailedWaybillOrders] 清理流程异常', {
traceId,
error: error && error.message ? error.message : `${error}`,
stack: error && error.stack ? error.stack : '',
});
// 清理异常不抛给上游,避免干扰主流程
}
}
/**
* 取号回写前兜底校验:比对订单主表当前快递编码与本次取号请求的快递编码。
*
* 取号请求为外部 HTTP 调用且耗时较长,期间订单快递可能被并发修改;
* 此处只做告警记录,不阻断回写,用于事后定位编码错位问题。
*
* @param {Object} params 校验入参。
* @param {string} params.traceId 本次取号链路标识。
* @param {Array<Object>} params.successUpdates 即将回写的成功取号项列表。
* @param {string} [params.requestExpressCode] 本次取号请求使用的快递编码。
* @param {Object} [params.transaction] 回写事务对象。
* @return {Promise<void>} 无返回值。
*/
async warnExpressCodeMismatch(params = {}) {
const {
traceId,
successUpdates,
requestExpressCode,
transaction,
} = params;
const updates = Array.isArray(successUpdates) ? successUpdates : [];
const requestCode = String(requestExpressCode || '').trim();
if (!requestCode || updates.length === 0) {
return;
}
const firstWarehouseId = Number(updates[0] && updates[0].warehouse_id) || 0;
if (!firstWarehouseId) {
return;
}
try {
const orderModel = await this.service.systems.express.getWaybillAsyncOrderDeliveryModel(firstWarehouseId);
const orderIds = updates
.map(item => Number(item && item.order_id))
.filter(v => Number.isFinite(v) && v > 0);
if (orderIds.length === 0) {
return;
}
const rows = await orderModel.findAll({
attributes: [ 'id', 'logistics_code' ],
where: { id: orderIds },
transaction,
raw: true,
});
const currentCodeMap = new Map(
(Array.isArray(rows) ? rows : [])
.map(row => [ Number(row && row.id) || 0, String(row && row.logistics_code || '').trim() ])
);
for (const item of updates) {
const orderId = Number(item && item.order_id) || 0;
const currentCode = currentCodeMap.get(orderId) || '';
if (currentCode && currentCode !== requestCode) {
this.ctx.logger.error('[expressPlatform.polyapi] 回写前快递编码不一致告警', {
traceId,
order_id: orderId,
request_express_code: requestCode,
current_logistics_code: currentCode,
});
}
}
} catch (error) {
// 兜底校验失败不影响回写主流程
this.ctx.logger.warn('[expressPlatform.polyapi] 回写前快递编码校验异常,跳过', {
traceId,
error: error && error.message ? error.message : `${error}`,
});
}
}
/**
* 从 orders 数据中提取失败订单清理所需的基本字段。
*
* @param {Array<Object>} orders 订单列表。
* @return {Array<{order_id: number, business_key: number, warehouse_id: number, store_id: number}>} 标准化后的失败订单列表。
*/
buildFailedOrderCleanupList(orders = []) {
const normalizedOrders = Array.isArray(orders) ? orders : [];
const result = [];
for (const order of normalizedOrders) {
const orderDelivery = order && order.order_delivery ? order.order_delivery : {};
const orderId = Number(orderDelivery.id) || Number(order.order_id) || 0;
const businessKey = Number(order.business_key) || 0;
const warehouseId = Number(orderDelivery.warehouse_id) || Number(order.warehouse_id) || 0;
const storeId = Number(orderDelivery.store_id) || Number(order.store_id) || 0;
if (!orderId || !businessKey) {
continue;
}
result.push({
order_id: orderId,
business_key: businessKey,
warehouse_id: warehouseId,
store_id: storeId,
});
}
return result;
}
/**
* 菠萝派(PolyAPI)平台取号接口。
*
* 流程:查询已分配运单号 → 调用平台字典接口 → 按平台编码构造订单载荷并调用
* Differ.JH.Logistics.PostOrder 取号 → 逐条校验结果 → 事务回写运单号与快递编码。
* 回写前会兜底校验主表当前快递编码与本次取号接口编码是否一致,不一致仅告警。
*
* @param {Object} [data={}] 平台业务入参。
* @param {Object} [data.matchedPlatform] 匹配到的快递平台配置。
* @param {Object} [data.listByWarehousePlatformCode] 当前仓库平台快递接口配置。
* @param {Array} [data.orders] 待取号订单列表(含 order_delivery 与 business_key)。
* @return {Promise<void>} 无返回值;内部完成回写与日志,失败时抛出异常。
*/
async polyapi(data = {}) {
const { matchedPlatform, listByWarehousePlatformCode, orders } = data;
const traceId = this.buildExpressPlatformTraceId(data);
const normalizedOrders = Array.isArray(orders) ? orders : [];
const orderIdListForLog = normalizedOrders
.map(item => Number(item && item.order_id) || Number(item && item.order_delivery && item.order_delivery.id) || 0)
.filter(orderId => Number.isFinite(orderId) && orderId > 0);
const waveIdListForLog = normalizedOrders
.map(item => Number(item && item.wave_id) || Number(item && item.order_delivery && item.order_delivery.wave_id) || 0)
.filter(waveId => Number.isFinite(waveId) && waveId > 0);
this.ctx.logger.info('[expressPlatform.polyapi] 入口请求', {
traceId,
waveIds: Array.from(new Set(waveIdListForLog)),
orderIds: Array.from(new Set(orderIdListForLog)).slice(0, 50),
orderCount: normalizedOrders.length,
requestSnapshot: {
matchedPlatformCode: matchedPlatform && matchedPlatform.code,
defaultExpressInterface: matchedPlatform && matchedPlatform.default_express_interface,
platformCode: listByWarehousePlatformCode && listByWarehousePlatformCode.platform_code,
logisticsCode: listByWarehousePlatformCode && listByWarehousePlatformCode.logistics_code,
warehouseId: listByWarehousePlatformCode && listByWarehousePlatformCode.warehouse_id,
},
});
const ExpressList = await this.service.systems.express.loadExpressList();
const sysExpressName = (ExpressList.find(item => item.code === listByWarehousePlatformCode.sys_express_code) || {}).name || '';
const orderDataMap = new Map();
for (const order_tmp of normalizedOrders) {
const od = order_tmp && order_tmp.order_delivery;
if (!od) continue;
orderDataMap.set(`${od.id}_${order_tmp.business_key}`, {
delivery_order_code: od.delivery_order_code || '',
source_order_codes: od.source_order_codes || '',
store_id: od.store_id || 0,
});
}
const orderExpressModel = this.ctx.model && this.ctx.model.OrderExpress;
const allocatedWaybillMap = new Map();
if (orderExpressModel && typeof orderExpressModel.findAll === 'function') {
const { Op } = this.app.Sequelize;
const orderIdList = Array.from(new Set((Array.isArray(orders) ? orders : [])
.map(order => Number(order && order.order_id))
.filter(orderId => Number.isFinite(orderId) && orderId > 0)));
if (orderIdList.length > 0) {
this.ctx.logger.info('[expressPlatform.polyapi] 查询已分配快递号前', {
traceId,
orderCount: orderIdList.length,
orderIds: orderIdList.slice(0, 50),
});
// 强制同仓校验:读取已分配运单必须同时限定订单ID与仓库ID,禁止跨仓串读
const allocatedWarehouseId = Number(listByWarehousePlatformCode && listByWarehousePlatformCode.warehouse_id)
|| Number(this.ctx && this.ctx.user && this.ctx.user.store_id)
|| 0;
const allocatedWaybillRows = allocatedWarehouseId > 0
? await orderExpressModel.findAll({
attributes: [ 'order_id', 'business_key', 'waybill_code' ],
where: {
order_id: {
[Op.in]: orderIdList,
},
warehouse_id: allocatedWarehouseId,
},
order: [[ 'id', 'ASC' ]],
raw: true,
})
: [];
this.ctx.logger.info('[expressPlatform.polyapi] 查询已分配快递号后', {
traceId,
hitRowCount: Array.isArray(allocatedWaybillRows) ? allocatedWaybillRows.length : 0,
});
for (const row of Array.isArray(allocatedWaybillRows) ? allocatedWaybillRows : []) {
const orderId = Number(row && row.order_id);
const businessKey = Number(row && row.business_key);
const waybillCode = String(row && row.waybill_code || '').trim();
if (!Number.isFinite(orderId) || orderId <= 0 || !Number.isFinite(businessKey) || businessKey <= 0 || !waybillCode) {
continue;
}
const waybillKey = `${orderId}:${businessKey}`;
if (!allocatedWaybillMap.has(waybillKey)) {
allocatedWaybillMap.set(waybillKey, waybillCode);
}
}
}
}
const Dictionary_bizcontent = {
};
this.ctx.logger.info('[expressPlatform.polyapi] PolyAPI 字典接口调用前', {
traceId,
api: 'Differ.JH.LogisticsPlatFeatures',
request: Dictionary_bizcontent,
tokenPresent: Boolean(listByWarehousePlatformCode && listByWarehousePlatformCode.token),
});
const Dictionary_result = await this.service.systems.poloApi.request('Differ.JH.LogisticsPlatFeatures', Dictionary_bizcontent, matchedPlatform, listByWarehousePlatformCode.token);
this.ctx.logger.info('[expressPlatform.polyapi] PolyAPI 字典接口调用后', {
traceId,
api: 'Differ.JH.LogisticsPlatFeatures',
response: Dictionary_result,
});
if (Dictionary_result && Dictionary_result.code && String(Dictionary_result.code) !== '10000') {
const dictErrorMessage = String(Dictionary_result.submessage || Dictionary_result.message || '字典接口调用失败').trim();
this.ctx.logger.error('[expressPlatform.polyapi] PolyAPI 字典接口返回业务失败', {
traceId,
code: Dictionary_result.code,
message: dictErrorMessage,
response: Dictionary_result,
});
// 字典接口失败,清理所有订单后抛出
const allFailedOrders = this.buildFailedOrderCleanupList(orders);
await this.cleanupFailedWaybillOrders(allFailedOrders, `字典接口失败: ${dictErrorMessage}`);
throw new Error(`菠萝派字典接口返回错误: ${dictErrorMessage}`);
}
const last3day = new Date();
last3day.setDate(last3day.getDate() + 3);
const pickUpDate = this.app.formatDate(last3day);
const last4day = new Date();
last4day.setDate(last4day.getDate() + 4);
const pickUpEndDate = this.app.formatDate(last4day);
console.log('listByWarehousePlatformCode', listByWarehousePlatformCode);
const order_bizcontent = {
orders: orders.map(order_tmp => {
const order = order_tmp.order_delivery;
console.log('order', order);
const expressListItem = ExpressList.find(item => item.code === listByWarehousePlatformCode.sys_express_code) || {};
let plattradeno = order.oaid_order_source_code || order.source_order_codes || '';
if (listByWarehousePlatformCode.platform_code === 'DY' && String(order.from_key || '') === '23060081' && !!order.pay_no && plattradeno.indexOf(',') > -1) {
plattradeno = order.pay_no;
}
let playload = {
object_Id: `${order.warehouse_id.toString(16)}_${Number(order.id || 0).toString(16)}_${order_tmp.business_key}`, // 菠萝派平台要求订单唯一标识必须为字符串
orderno: `${order.warehouse_id.toString(16)}_${Number(order.id || 0).toString(16)}_${order_tmp.business_key}`, // 菠萝派平台要求订单号必须为字符串
plattradeno,
tid: plattradeno,
ismultiplepieces: order.package_count > 1 ? 1 : 0,
logisticno: allocatedWaybillMap.get(`${Number(order.id) || 0}:${Number(order_tmp.business_key) || 0}`) || '',
logistictype: expressListItem[listByWarehousePlatformCode.platform_code] || '',
providercode: expressListItem[listByWarehousePlatformCode.platform_code] || order.logistics_code || '',
numpackage: order.package_count || '1',
Businesstype: listByWarehousePlatformCode.product_type,
Expresstype: listByWarehousePlatformCode.product_type,
ProductType: listByWarehousePlatformCode.product_type || '',
transtype: '0',
transtypecode: '1',
mainsubpaymode: '1',
businessplat: order.sys_platform_code === 'KS' ? order.sys_platform_code : 'OTHERS',
paymode: '1',
ordertype: listByWarehousePlatformCode.ordertype ?? 'JH_Normal',
ProviderID: '',
procode: order.procode || '普通商品',
codpaymoney: order.ar_amount ?? null,
packagemoney: order.item_amount ?? null,
weight: Number(order.items_weight) || 0, // 单位 g,需确认 PolyAPI 期望单位
supporpaymoney: order.total_amount ?? null,
length: Number(order.length) || 0,
width: Number(order.width) || 0,
height: Number(order.height) || 0,
volume: Number(order.volume) || 0,
ispickup: listByWarehousePlatformCode.ispickup ?? 0,
Sipshopid: listByWarehousePlatformCode.platform_shop_id || '',
oaid: order.oaid || '',
cpcode: expressListItem[listByWarehousePlatformCode.platform_code] || '',
logisticsproductname: 'JH_02',
dmssorting: 0,
brandno: listByWarehousePlatformCode.brandno || null,
needencrypt: 1,
ordertime: order.place_order_time || '',
customername: '测试',
ordersource: matchedPlatform.ordersource || '',
inputsite: listByWarehousePlatformCode.site_code || '',
sitecode: listByWarehousePlatformCode.site_code || '',
shipperno: listByWarehousePlatformCode.shipperno || '',
customercode: order.sys_platform_code === 'XHS' ? listByWarehousePlatformCode.shipperno || '' : listByWarehousePlatformCode.shipperno || listByWarehousePlatformCode.client_id || '',
sender: {
Company: listByWarehousePlatformCode.shop_name || '',
name: listByWarehousePlatformCode.sender_name || '',
phone: order.sys_platform_code === 'XHS' ? undefined : listByWarehousePlatformCode.sender_tel || '',
mobile: order.sys_platform_code === 'XHS' ? listByWarehousePlatformCode.sender_tel : undefined,
country: 'CN',
city: listByWarehousePlatformCode.city_name || '',
province: listByWarehousePlatformCode.province_name || '',
area: listByWarehousePlatformCode.district_name || '',
town: listByWarehousePlatformCode.town_name || '',
address: listByWarehousePlatformCode.address || '',
}, // 需要实现
receiver: {
name: order.name || '',
company: order.company || '',
phone: order.sys_platform_code === 'KS' || order.sys_platform_code === 'KS' ? undefined : (order.mobile || order.tel || ''),
mobile: order.mobile || order.tel || '',
country: order.country_code || 'CN',
province: order.province || '',
city: order.city || '',
area: order.area || '',
town: order.town || '',
address: order.detail_address || '',
zip: order.zip_code || '',
email: order.email || '',
},
goods: (order.orderItems && order.orderItems.map(item => ({
productid: item.item_code,
cnname: 'sp',
count: item.plan_qty || 0,
}))) || [],
// Mallmaskid: '',
template_url: listByWarehousePlatformCode.template_id || '',
labelformat: listByWarehousePlatformCode.labelformat || '',
extraInfo: ExpressList.find(item => item.code === listByWarehousePlatformCode.sys_express_code)?.polyapi_extra_info || '',
};
console.log('matchedPlatform.platid', matchedPlatform.platid);
console.log('startPlayload', playload);
if (playload.providercode === 'JD') {
playload.pickUpDate = pickUpDate;
playload.pickUpEndDate = pickUpEndDate;
playload.shipperno = listByWarehousePlatformCode.shipperno || '';
}
if (Number(matchedPlatform.platid) === 673) {
playload.BizVersion = '2';
playload.brandno = listByWarehousePlatformCode.brandno === 'SF' ? listByWarehousePlatformCode.brandno : undefined;
}
if (Number(matchedPlatform.platid) === 544) {
const {
orderno,
plattradeno,
logistictype,
ProductType,
providercode,
numpackage,
businessplat,
oaid,
ordertype,
businessType,
codpaymoney,
ProviderID,
cpcode,
logisticsproductname,
needencrypt,
ordersource,
shipperno,
sitecode,
customercode,
goods,
sender = {},
receiver = {},
} = playload;
const {
name: senderNameRaw,
company: senderCompanyRaw,
phone: senderPhoneRaw,
mobile: senderMobileRaw,
country,
city: senderCity,
province: senderProvince,
address: senderAddress,
} = sender;
const {
name,
phone,
province: receiverProvince,
city: receiverCity,
address: receiverAddress,
} = receiver;
const senderName = senderNameRaw || listByWarehousePlatformCode.sender_name || listByWarehousePlatformCode.shop_name || '';
const senderCompany = senderCompanyRaw || listByWarehousePlatformCode.shop_name || '';
const customername = senderNameRaw || senderCompanyRaw || listByWarehousePlatformCode.shop_name || '测试';
playload = {
orderno,
plattradeno,
ProductType,
businesstype: ProductType,
expresstype: ProductType,
logistictype,
providercode: providercode || cpcode || logistictype || '',
numpackage,
businessplat,
platcode: plattradeno,
mainsubpaymode: '1',
ordertype,
businessType: businessType || ordertype || 'JH_Normal',
codpaymoney,
ProviderID,
cpcode,
logisticsproductname,
needencrypt,
ordersource,
shipperno,
sitecode,
customername,
goods,
oaid,
customercode: logistictype === 'SF' ? undefined : customercode || shipperno || listByWarehousePlatformCode.shipperno || listByWarehousePlatformCode.client_id || '',
sender: {
name: senderName,
phone: senderPhoneRaw,
mobile: senderMobileRaw,
company: senderCompany,
country,
city: senderCity,
province: senderProvince,
address: senderAddress,
},
receiver: {
name,
phone,
province: receiverProvince,
city: receiverCity,
address: receiverAddress,
},
};
console.log('playload.providercode', playload.providercode);
if (playload.providercode === 'SF') {
playload.expressPayMethod = '1';
} else {
playload.paymode = '1';
playload.codpaymoney = '';
}
}
if (matchedPlatform.platid === 672) {
/* if (!order.source_order_codes) {
throw new Error('订单数据错误,缺失平台订单号');
}
*/
playload.object_Id = toUint64(order.warehouse_id, order.id, order_tmp.business_key);
// extend_props 可能为 null,先做空值保护,避免直接抛 TypeError 掩盖业务错误
const ewaybillOrderCode = order.extend_props && order.extend_props.ewaybill_order_code;
if (!ewaybillOrderCode) {
throw new Error('订单数据错误,参数不全缺失extend_props.ewaybill_order_code,请核实非手工单(视频号手工单分配不了运单号),复制次信息给ERP方反馈');
}
playload.oaid = ewaybillOrderCode;
playload.transtype = '0';
playload.Mallmaskid = order.buyer_nick;
playload.mainsubpaymode = '1';
delete playload.plattradeno;
}
playload.ProviderID = listByWarehousePlatformCode.providerid || '';
console.log('playload', playload);
return playload;
}),
shoptype: matchedPlatform.shoptype,
};
// 调用菠萝派平台接口进行数据处理
this.ctx.logger.info('[expressPlatform.polyapi] PolyAPI 分配快递号接口调用前', {
traceId,
api: 'Differ.JH.Logistics.PostOrder',
waveIds: Array.from(new Set(waveIdListForLog)),
orderIds: Array.from(new Set(orderIdListForLog)).slice(0, 50),
request: order_bizcontent,
});
const result = await this.service.systems.poloApi.request('Differ.JH.Logistics.PostOrder', order_bizcontent, matchedPlatform, listByWarehousePlatformCode.token);
this.ctx.logger.info('[expressPlatform.polyapi] PolyAPI 分配快递号接口调用后', {
traceId,
api: 'Differ.JH.Logistics.PostOrder',
response: JSON.stringify(result),
});
console.log('分配运单号结果', result);
// 统一处理:不再依赖顶层 code,直接从 results 逐条提取 issuccess 和 submessage
{
// 逐条检查 issuccess,将平台返回的业务失败项单独提取,避免因 logisticno 为空被误判为"运单号为空"
const allResults = Array.isArray(result.results) ? result.results : [];
// 平台系统级失败(如 code=40000 / GSE.REQUEST_FAILURE.SYSTEMERROR)时 results 是空数组,
// 继续往下走会把"0 条结果"当成成功,订单既不回写运单号也不标记异常,这里直接按失败抛出。
if (allResults.length === 0 && normalizedOrders.length > 0) {
const polyapiRequestId = String(
result && (result.polyapirequestid || result.requestid || result.request_id) || ''
).trim();
const emptyResultReason = String(
result && (result.submessage || result.message) || ''
).trim() || `菠萝派平台接口未返回取号结果(code=${String(result && result.code || '') || '空'})`;
// 带上菠萝派请求ID,便于平台侧按 polyapirequestid 定位本次调用
const reasonWithRequestId = polyapiRequestId
? `${emptyResultReason}(polyapirequestid=${polyapiRequestId})`
: emptyResultReason;
this.ctx.logger.error('[expressPlatform.polyapi] 平台返回空 results,判定为系统级失败', {
traceId,
polyapirequestid: polyapiRequestId,
code: result && result.code,
subcode: result && result.subcode,
reason: emptyResultReason,
orderCount: normalizedOrders.length,
response: JSON.stringify(result),
});
const allFailedOrders = this.buildFailedOrderCleanupList(orders);
await this.cleanupFailedWaybillOrders(allFailedOrders, reasonWithRequestId);
throw new Error(`菠萝派分配快递号失败: ${reasonWithRequestId}`);
}
const itemFailedList = [];
const itemSuccessList = [];
for (const item of allResults) {
const isSuccess = String(item.issuccess || '') === '1';
if (isSuccess) {
itemSuccessList.push(item);
} else {
itemFailedList.push(item);
}
}
// 逐条失败项:按 submessage 分组,每组使用各自的失败原因
if (itemFailedList.length > 0) {
// 按 submessage 分组
const reasonGroups = new Map();
for (const failedItem of itemFailedList) {
const itemReason = String(
failedItem.submessage || failedItem.message || failedItem.subcode || '平台返回逐条业务失败'
).trim();
if (!reasonGroups.has(itemReason)) {
reasonGroups.set(itemReason, []);
}
reasonGroups.get(itemReason).push(failedItem);
}
this.ctx.logger.error('[expressPlatform.polyapi] results 中存在逐条业务失败项', {
traceId,
totalCount: allResults.length,
failedCount: itemFailedList.length,
successCount: itemSuccessList.length,
reasonGroups: Array.from(reasonGroups.keys()),
sampleFailItem: JSON.stringify(itemFailedList.slice(0, 3)),
});
// 逐组清理
for (const [ groupReason, groupItems ] of reasonGroups) {
const itemFailedOrders = [];
for (const failedItem of groupItems) {
const [ , order_id_hex, business_key ] = String(failedItem.orderno || '').split('_');
const orderId = parseInt(order_id_hex, 16) || 0;
const businessKey = Number(business_key) || 0;
if (!orderId || !businessKey) continue;
let storeId = 0;
let warehouseId = 0;
for (const order of Array.isArray(orders) ? orders : []) {
const orderDelivery = order && order.order_delivery;
const oId = Number(orderDelivery && orderDelivery.id) || 0;
const bk = Number(order && order.business_key) || 0;
if (oId === orderId && bk === businessKey) {
storeId = Number(orderDelivery && orderDelivery.store_id) || 0;
warehouseId = Number(orderDelivery && orderDelivery.warehouse_id) || 0;
break;
}
}
itemFailedOrders.push({
order_id: orderId,
business_key: businessKey,
warehouse_id: warehouseId,
store_id: storeId,
});
}
if (itemFailedOrders.length > 0) {
await this.cleanupFailedWaybillOrders(itemFailedOrders, groupReason);
}
}
// 全部订单都失败则抛出
if (itemSuccessList.length === 0) {
const firstReason = Array.from(reasonGroups.keys())[0] || '平台返回逐条业务失败';
throw new Error(firstReason);
}
}
// 仅用成功的 items 继续处理
result.results = itemSuccessList;
const resolveWaybillCode = item => String(item && (item.waybill_code || item.logisticno) || '').trim();
let successUpdates = [];
switch (listByWarehousePlatformCode.platform_code) {
case 'KS':
successUpdates = (result.results || []).map(item => {
const [ warehouse_id_hex, order_id_hex, business_key ] = String(item.orderno || '').split('_');
const warehouse_id = parseInt(warehouse_id_hex, 16);
const order_id = parseInt(order_id_hex, 16) || 0;
const waybillCode = resolveWaybillCode(item);
return {
warehouse_id,
order_id,
business_key,
waybill_code: waybillCode,
orderExpressValues: {
waybill_code: waybillCode,
printinfo: item.printinfo,
signature: item.signature,
encryptprintinfo: item.encryptprintinfo,
...this.buildOrderExpressVerPatch([ item.ver ]),
create_at: new Date(),
delivery_order_code: orderDataMap.get(`${order_id}_${business_key}`)?.delivery_order_code || null,
source_order_codes: orderDataMap.get(`${order_id}_${business_key}`)?.source_order_codes || null,
store_id: orderDataMap.get(`${order_id}_${business_key}`)?.store_id || null,
logistics_code: listByWarehousePlatformCode.sys_express_code || '',
logistics_interface_id: listByWarehousePlatformCode.id || null,
logistics_name: sysExpressName || '',
logistics_interface_name: listByWarehousePlatformCode.name || '',
platform_code: listByWarehousePlatformCode.platform_code || '',
status: 1,
retry_count: 0,
},
orderDeliveryValues: {
post_status: 'fin',
order_flag: '',
},
};
});
break;
case 'DY':
successUpdates = (result.results || []).map(item => {
const [ warehouse_id_hex, order_id_hex, business_key ] = String(item.orderno || '').split('_');
const warehouse_id = parseInt(warehouse_id_hex, 16);
const order_id = parseInt(order_id_hex, 16) || 0;
const waybillCode = resolveWaybillCode(item);
return {
warehouse_id,
order_id,
business_key,
waybill_code: waybillCode,
orderExpressValues: {
waybill_code: waybillCode,
signature: item.signature,
encryptedtoken: item.encryptedtoken,
encryptprintinfo: item.encryptprintinfo,
...this.buildOrderExpressVerPatch([ item.ver ]),
create_at: new Date(),
delivery_order_code: orderDataMap.get(`${order_id}_${business_key}`)?.delivery_order_code || null,
source_order_codes: orderDataMap.get(`${order_id}_${business_key}`)?.source_order_codes || null,
store_id: orderDataMap.get(`${order_id}_${business_key}`)?.store_id || null,
logistics_code: listByWarehousePlatformCode.sys_express_code || '',
logistics_interface_id: listByWarehousePlatformCode.id || null,
logistics_name: sysExpressName || '',
logistics_interface_name: listByWarehousePlatformCode.name || '',
platform_code: listByWarehousePlatformCode.platform_code || '',
status: 1,
retry_count: 0,
},
orderDeliveryValues: {
post_status: 'fin',
order_flag: '',
},
};
});
break;
case 'JD':{
const batchPrintOrders = (result.results || []).map(item => ({
orderno: String(item.orderno),
logisticno: String(item.logisticno),
outputformat: 'JH_PDF',
labelformat: 'JH_A4',
printobjecttype: 'JH_Label',
numpackage: '1',
countrycode: '',
logisticsid: '',
orderitemno: '',
sendername: '',
sendercompany: '',
senderprovince: '',
sendercity: '',
senderarea: '',
senderaddress: '',
sendertel: '',
receivername: '',
receivercompany: '',
receiverprovince: '',
receivercity: '',
receiverarea: '',
receiveraddress: '',
receivertel: '',
cargoname: '',
senddata: '',
// weight: '',
eCustomerCode: '',
remark: '',
selleruserid: '',
printno: '',
iscloudprint: 'false',
needprintdetail: 'false',
extenddata: '',
providercode: String(item.procode || item.realcpcode || item.logisticcompanycode || ''),
packageno: '',
fontsize: '',
platorderno: '',
sipshopid: 0,
}));
console.log('京东批量打印请求参数', JSON.stringify({
api: 'Differ.JH.Logistics.BatchPrintOrder',
orders: batchPrintOrders,
}));
const batchPrintPlatform = {
...matchedPlatform,
platid: 611,
interface_url: 'https://apijd.polyapi.com/OpenAPI/do',
};
const batchPrintResult = await this.service.systems.poloApi.request(
'Differ.JH.Logistics.BatchPrintOrder',
{ orders: batchPrintOrders },
batchPrintPlatform,
listByWarehousePlatformCode.token
);
console.log('京东批量打印返回结果', JSON.stringify(batchPrintResult));
if (String(batchPrintResult && batchPrintResult.code || '') !== '10000') {
const errorMessage = String(
batchPrintResult && (batchPrintResult.submessage || batchPrintResult.message)
|| '京东批量打印接口调用失败'
).trim();
throw new Error(errorMessage);
}
successUpdates = (batchPrintResult && batchPrintResult.results || []).map(item => {
const objectId = String(item && item.orderno || '').trim();
const [ warehouse_id_hex, order_id_hex, business_key ] = objectId.split('_');
const warehouse_id = parseInt(warehouse_id_hex, 16);
const order_id = parseInt(order_id_hex, 16) || 0;
const waybillCode = String(item && (item.logisticno || item.waybill_code) || '').trim();
const rawPrintData = item && Object.prototype.hasOwnProperty.call(item, 'printdata')
? item.printdata
: item && Object.prototype.hasOwnProperty.call(item, 'htmldata')
? item.htmldata
: item && Object.prototype.hasOwnProperty.call(item, 'urldata')
? item.urldata
: item && Object.prototype.hasOwnProperty.call(item, 'batchprintdata')
? item.batchprintdata
: null;
const printinfo = this.stringifyPlatformPrintData(rawPrintData, rawPrintData)
|| JSON.stringify(item);
const signature = String(item && item.signature || '').trim() || null;
const encryptprintinfo = String(item && item.encryptprintinfo || '').trim() || null;
const encryptedtoken = String(item && item.encryptedtoken || '').trim() || null;
return {
warehouse_id,
order_id,
business_key,
waybill_code: waybillCode,
orderExpressValues: {
waybill_code: waybillCode,
printinfo,
signature,
encryptprintinfo,
encryptedtoken,
...this.buildOrderExpressVerPatch([ item && item.ver ]),
create_at: new Date(),
delivery_order_code: orderDataMap.get(`${order_id}_${business_key}`)?.delivery_order_code || null,
source_order_codes: orderDataMap.get(`${order_id}_${business_key}`)?.source_order_codes || null,
store_id: orderDataMap.get(`${order_id}_${business_key}`)?.store_id || null,
logistics_code: listByWarehousePlatformCode.sys_express_code || '',
logistics_interface_id: listByWarehousePlatformCode.id || null,
logistics_name: sysExpressName || '',
logistics_interface_name: listByWarehousePlatformCode.name || '',
platform_code: listByWarehousePlatformCode.platform_code || '',
status: 1,
retry_count: 0,
},
orderDeliveryValues: {
post_status: 'fin',
order_flag: '',
},
};
});
break;
}
case 'XHS':{
successUpdates = (result.results || []).map(item => {
const [ warehouse_id_hex, order_id_hex, business_key ] = String(item.orderno || '').split('_');
const warehouse_id = parseInt(warehouse_id_hex, 16);
const order_id = parseInt(order_id_hex, 16) || 0;
const waybillCode = resolveWaybillCode(item);
const printInfo = item.print_info ?? item.printinfo;
return {
warehouse_id,
order_id,
business_key,
waybill_code: waybillCode,
orderExpressValues: {
waybill_code: waybillCode,
printinfo: printInfo,
signature: item.signature,
encryptedtoken: item.encryptedtoken,
encryptprintinfo: item.encryptprintinfo,
...this.buildOrderExpressVerPatch([ item.ver ]),
create_at: new Date(),
delivery_order_code: orderDataMap.get(`${order_id}_${business_key}`)?.delivery_order_code || null,
source_order_codes: orderDataMap.get(`${order_id}_${business_key}`)?.source_order_codes || null,
store_id: orderDataMap.get(`${order_id}_${business_key}`)?.store_id || null,
logistics_code: listByWarehousePlatformCode.sys_express_code || '',
logistics_interface_id: listByWarehousePlatformCode.id || null,
logistics_name: sysExpressName || '',
logistics_interface_name: listByWarehousePlatformCode.name || '',
platform_code: listByWarehousePlatformCode.platform_code || '',
status: 1,
retry_count: 0,
},
orderDeliveryValues: {
post_status: 'fin',
order_flag: '',
},
};
});
break;
}
case 'SPH':{
successUpdates = (result.results || []).map(item => {
const objectId = String(item && (item.object_id || item.object_Id || item.orderno) || '').trim();
const objectIdParts = objectId.split('_');
if (!objectId || objectIdParts.length < 3) {
throw new Error(`视频号取号返回 object_id 无法解析: ${objectId || JSON.stringify(item)}`);
}
const [ warehouse_id_hex, order_id_hex, business_key ] = objectIdParts;
const warehouse_id = parseInt(warehouse_id_hex, 16);
const order_id = parseInt(order_id_hex, 16) || 0;
const waybillCode = resolveWaybillCode(item);
const rawPrintData = item && Object.prototype.hasOwnProperty.call(item, 'raw')
? item.raw
: null;
const printinfo = this.stringifyPlatformPrintData(item && item.printinfo, item && item.printinfo)
|| this.stringifyPlatformPrintData(rawPrintData, rawPrintData)
|| null;
const signature = item && Object.prototype.hasOwnProperty.call(item, 'signature')
? item.signature
: rawPrintData && typeof rawPrintData === 'object' && Object.prototype.hasOwnProperty.call(rawPrintData, 'signature')
? rawPrintData.signature
: undefined;
const encryptprintinfo = item && Object.prototype.hasOwnProperty.call(item, 'encryptprintinfo')
? item.encryptprintinfo
: rawPrintData && typeof rawPrintData === 'object' && Object.prototype.hasOwnProperty.call(rawPrintData, 'encryptprintinfo')
? rawPrintData.encryptprintinfo
: undefined;
const encryptedtoken = item && Object.prototype.hasOwnProperty.call(item, 'encryptedtoken')
? item.encryptedtoken
: rawPrintData && typeof rawPrintData === 'object' && Object.prototype.hasOwnProperty.call(rawPrintData, 'encryptedtoken')
? rawPrintData.encryptedtoken
: undefined;
const ver = item && Object.prototype.hasOwnProperty.call(item, 'ver')
? item.ver
: rawPrintData && typeof rawPrintData === 'object' && Object.prototype.hasOwnProperty.call(rawPrintData, 'ver')
? rawPrintData.ver
: undefined;
return {
warehouse_id,
order_id,
business_key,
waybill_code: waybillCode,
orderExpressValues: {
waybill_code: waybillCode,
printinfo,
signature,
encryptprintinfo,
encryptedtoken,
...this.buildOrderExpressVerPatch([ ver ]),
create_at: new Date(),
delivery_order_code: orderDataMap.get(`${order_id}_${business_key}`)?.delivery_order_code || null,
source_order_codes: orderDataMap.get(`${order_id}_${business_key}`)?.source_order_codes || null,
store_id: orderDataMap.get(`${order_id}_${business_key}`)?.store_id || null,
logistics_code: listByWarehousePlatformCode.sys_express_code || '',
logistics_interface_id: listByWarehousePlatformCode.id || null,
logistics_name: sysExpressName || '',
logistics_interface_name: listByWarehousePlatformCode.name || '',
platform_code: listByWarehousePlatformCode.platform_code || '',
status: 1,
retry_count: 0,
},
orderDeliveryValues: {
post_status: 'fin',
order_flag: '',
},
};
});
break;
}
case 'PDD':
successUpdates = (result.results || []).map(item => {
const [ warehouse_id_hex, order_id_hex, business_key ] = String(item.orderno || '').split('_');
const warehouse_id = parseInt(warehouse_id_hex, 16);
const order_id = parseInt(order_id_hex, 16) || 0;
const waybillCode = resolveWaybillCode(item);
return {
warehouse_id,
order_id,
business_key,
waybill_code: waybillCode,
orderExpressValues: {
waybill_code: waybillCode,
signature: item.signature,
encryptedtoken: item.encryptedtoken,
encryptprintinfo: item.encryptprintinfo,
...this.buildOrderExpressVerPatch([ item.ver ]),
create_at: new Date(),
delivery_order_code: orderDataMap.get(`${order_id}_${business_key}`)?.delivery_order_code || null,
source_order_codes: orderDataMap.get(`${order_id}_${business_key}`)?.source_order_codes || null,
store_id: orderDataMap.get(`${order_id}_${business_key}`)?.store_id || null,
logistics_code: listByWarehousePlatformCode.sys_express_code || '',
logistics_interface_id: listByWarehousePlatformCode.id || null,
logistics_name: sysExpressName || '',
logistics_interface_name: listByWarehousePlatformCode.name || '',
platform_code: listByWarehousePlatformCode.platform_code || '',
status: 1,
retry_count: 0,
},
orderDeliveryValues: {
post_status: 'fin',
order_flag: '',
},
};
});
break;
case 'QT':
case 'OTHER':
successUpdates = (result.results || []).map(item => {
const [ warehouse_id_hex, order_id_hex, business_key ] = String(item.orderno || '').split('_');
const warehouse_id = parseInt(warehouse_id_hex, 16);
const order_id = parseInt(order_id_hex, 16) || 0;
const waybillCode = String(item.logisticno || item.waybill_code || '').trim();
return {
warehouse_id,
order_id,
business_key,
waybill_code: waybillCode,
orderExpressValues: {
waybill_code: waybillCode,
printinfo: item.printinfo,
signature: item.signature,
encryptprintinfo: item.encryptprintinfo,
encryptedtoken: item.encryptedtoken,
...this.buildOrderExpressVerPatch([ item.ver ]),
create_at: new Date(),
delivery_order_code: orderDataMap.get(`${order_id}_${business_key}`)?.delivery_order_code || null,
source_order_codes: orderDataMap.get(`${order_id}_${business_key}`)?.source_order_codes || null,
store_id: orderDataMap.get(`${order_id}_${business_key}`)?.store_id || null,
logistics_code: listByWarehousePlatformCode.sys_express_code || '',
logistics_interface_id: listByWarehousePlatformCode.id || null,
logistics_name: sysExpressName || '',
logistics_interface_name: listByWarehousePlatformCode.name || '',
platform_code: listByWarehousePlatformCode.platform_code || '',
status: 1,
retry_count: 0,
},
orderDeliveryValues: {
post_status: 'fin',
order_flag: '',
},
};
});
break;
default: {
const unmatchedPlatformCode = String(listByWarehousePlatformCode && listByWarehousePlatformCode.platform_code || '').trim();
this.ctx.logger.error('[expressPlatform.polyapi] switch 无匹配 platform_code', {
traceId,
platform_code: unmatchedPlatformCode,
});
// 未知平台编码,清理本批次全部订单资源后抛出
const allFailedOrders = this.buildFailedOrderCleanupList(orders);
await this.cleanupFailedWaybillOrders(allFailedOrders, `未知平台编码: ${unmatchedPlatformCode || '空'}`);
throw new Error(`当前快递平台编码【${unmatchedPlatformCode}】未在system接口中实现,无法获取快递号`);
}
}
// 统一校验:过滤掉运单号为空的 successUpdates,避免空字符串写入 OrderExpress.waybill_code
const emptyWaybillUpdates = [];
const validSuccessUpdates = [];
for (const item of successUpdates) {
if (!item.waybill_code) {
emptyWaybillUpdates.push(item);
this.ctx.logger.error('[expressPlatform.polyapi] 运单号为空,跳过回写', {
warehouse_id: item.warehouse_id,
order_id: item.order_id,
business_key: item.business_key,
});
} else {
validSuccessUpdates.push(item);
}
}
successUpdates = validSuccessUpdates;
if (emptyWaybillUpdates.length > 0) {
this.ctx.logger.error('[expressPlatform.polyapi] 存在运单号为空的订单', {
count: emptyWaybillUpdates.length,
emptyOrderIds: emptyWaybillUpdates.map(i => `${i.warehouse_id}_${i.order_id}_${i.business_key}`).join(','),
totalSuccessUpdates: successUpdates.length,
});
// 反查 orders 找到运单号为空订单对应的 store_id,补齐清理所需信息后统一清理
const emptyFailedOrders = [];
for (const emptyItem of emptyWaybillUpdates) {
const orderId = Number(emptyItem.order_id) || 0;
const warehouseId = Number(emptyItem.warehouse_id) || 0;
const businessKey = Number(emptyItem.business_key) || 0;
let storeId = 0;
for (const order of Array.isArray(orders) ? orders : []) {
const orderDelivery = order && order.order_delivery;
const oId = Number(orderDelivery && orderDelivery.id) || 0;
const bk = Number(order && order.business_key) || 0;
if (oId === orderId && bk === businessKey) {
storeId = Number(orderDelivery && orderDelivery.store_id) || 0;
break;
}
}
emptyFailedOrders.push({
order_id: orderId,
business_key: businessKey,
warehouse_id: warehouseId,
store_id: storeId,
});
}
await this.cleanupFailedWaybillOrders(emptyFailedOrders, '运单号为空');
// 全部订单都失败则抛出
if (successUpdates.length === 0) {
throw new Error(`菠萝派平台接口返回运单号全部为空,共${emptyWaybillUpdates.length}笔订单取号失败`);
}
}
const orderMetaMap = new Map();
for (const order of Array.isArray(orders) ? orders : []) {
const orderDelivery = order && order.order_delivery;
const warehouseId = Number(orderDelivery && orderDelivery.warehouse_id) || 0;
const orderId = Number(orderDelivery && orderDelivery.id) || 0;
const businessKey = Number(order && order.business_key) || 0;
if (!warehouseId || !orderId || !businessKey) {
continue;
}
orderMetaMap.set(`${warehouseId}_${orderId}_${businessKey}`, {
store_id: Number(orderDelivery && orderDelivery.store_id) || 0,
warehouse_id: warehouseId,
});
}
const settlementRelationMap = new Map();
for (const item of successUpdates) {
const warehouseId = Number(item.warehouse_id) || 0;
const orderId = Number(item.order_id) || 0;
const businessKey = Number(item.business_key) || 0;
if (!warehouseId || !orderId || !businessKey) {
continue;
}
const orderMeta = orderMetaMap.get(`${warehouseId}_${orderId}_${businessKey}`);
if (!orderMeta) {
continue;
}
const storeId = Number(orderMeta.store_id) || 0;
if (!storeId) {
continue;
}
const relationKey = `${storeId}:${warehouseId}`;
const currentRelation = settlementRelationMap.get(relationKey) || {
store_id: storeId,
warehouse_id: warehouseId,
success_count: 0,
};
currentRelation.success_count += 1;
settlementRelationMap.set(relationKey, currentRelation);
}
const storeWarehouseModel = this.ctx.model && this.ctx.model.StoreWarehouse;
if (typeof this.ctx.model.transaction === 'function' && successUpdates.length > 0) {
this.ctx.logger.info('[expressPlatform.polyapi] DB 回写事务开始前', {
traceId,
successUpdateCount: successUpdates.length,
relationCount: settlementRelationMap.size,
sampleOrderIds: successUpdates.slice(0, 50).map(item => Number(item && item.order_id || 0)).filter(Boolean),
});
try {
await this.ctx.model.transaction(async transaction => {
// 统一加锁顺序:先锁 store_warehouse 再更新 order_express,
// 与 createWaybillCode 回写事务一致,避免 AB-BA 死锁
await this.lockAndDeductWaybillSettlement(settlementRelationMap, storeWarehouseModel, transaction);
// 回写前兜底校验:主表当前快递编码与本次取号接口编码不一致时告警,
// 防止取号期间订单快递被并发修改导致回写编码错位
await this.warnExpressCodeMismatch({
traceId,
successUpdates,
requestExpressCode: listByWarehousePlatformCode && listByWarehousePlatformCode.sys_express_code,
transaction,
});
for (const item of successUpdates) {
const warehouseId = Number(item.warehouse_id) || 0;
const orderId = Number(item.order_id) || 0;
const businessKey = Number(item.business_key) || 0;
if (!warehouseId || !orderId || !businessKey) {
continue;
}
await this.ctx.model.OrderExpress.update(item.orderExpressValues, {
where: {
order_id: orderId,
business_key: businessKey,
warehouse_id: warehouseId,
},
transaction,
});
if (item.orderDeliveryValues) {
const orderModel = await this.service.systems.express.getWaybillAsyncOrderDeliveryModel(item.warehouse_id);
await orderModel.update(item.orderDeliveryValues, {
where: {
id: orderId,
},
transaction,
});
}
}
});
} catch (error) {
this.ctx.logger.error('[expressPlatform.polyapi] DB 回写事务异常', {
traceId,
successUpdateCount: successUpdates.length,
error: error && error.message ? error.message : `${error}`,
stack: error && error.stack ? error.stack : '',
});
throw error;
}
this.ctx.logger.info('[expressPlatform.polyapi] DB 回写事务完成后', {
traceId,
successUpdateCount: successUpdates.length,
relationCount: settlementRelationMap.size,
});
const operationLogService = this.service
&& this.service.systems
&& this.service.systems.operationLog;
const operator = this.getOrderLogOperator();
const logPayloads = [];
for (const item of successUpdates) {
const warehouseId = Number(item.warehouse_id) || 0;
const orderId = Number(item.order_id) || 0;
if (!warehouseId || !orderId) {
continue;
}
logPayloads.push({
businessType: 'order',
businessId: `${orderId}`,
operationCode: 'WAYBILL',
operator,
extras: {
message: `订单${orderId}获取快递单成功,单号:${item.waybill_code}`,
warehouseId,
externalLogType: 'API',
},
});
}
if (operationLogService && typeof operationLogService.createOperationLogs === 'function') {
await operationLogService.createOperationLogs(logPayloads);
} else {
this.ctx.logger.warn('[expressPlatform.polyapi] operationLog 批量写入服务不可用,跳过日志写入', {
traceId,
count: logPayloads.length,
});
}
this.ctx.logger.info('[expressPlatform.polyapi] 订单操作日志写入完成', {
traceId,
operationLogCount: successUpdates.length,
});
// 自动同步回传:快递号分配成功后异步触发订单同步
try {
const settlementEntries = Array.from(settlementRelationMap.entries());
for (const [ key, relation ] of settlementEntries) {
const successCount = Number(relation && relation.success_count) || 0;
if (successCount <= 0) continue;
const [ storeId, warehouseId ] = key.split(':').map(Number);
if (!storeId || !warehouseId) continue;
const contractConfig = await this.service.systems.storeWarehouse.getContractConfig(
warehouseId,
storeId
);
if (
contractConfig
&& contractConfig.policy_config
&& contractConfig.policy_config.auto_sync_back === 1
) {
// 收集本次分配成功的订单ID
const syncedOrderIds = successUpdates
.filter(u => {
const orderId = Number(u.order_id) || 0;
const wid = Number(u.warehouse_id) || 0;
const bk = Number(u.business_key) || 0;
const meta = orderMetaMap.get(`${wid}_${orderId}_${bk}`);
return meta && meta.store_id === storeId && wid === warehouseId;
})
.map(u => Number(u.order_id) || 0)
.filter(Boolean);
if (syncedOrderIds.length > 0) {
// 异步调用,不阻塞主流程
// 显式传仓库上下文:Qimen 创建订单等链路 ctx.user 为空,
// 不传会导致 syncOrderIds 因"缺少仓库上下文"静默失败
this.ctx.service.systemMethods.order.pendingOrder.syncOrderIds({
orderIds: syncedOrderIds,
warehouseId,
}).catch(err => {
this.ctx.logger.error(
`[auto_sync_back] polyapi 自动同步失败: ${err.message}`
);
});
}
}
}
} catch (err) {
this.ctx.logger.error(
`[auto_sync_back] polyapi 自动同步异常: ${err.message}`
);
}
}
}
this.ctx.logger.info('[expressPlatform.polyapi] 处理完成', {
traceId,
orderCount: normalizedOrders.length,
});
return {
flag: true,
code: 0,
message: '菠萝派平台数据处理成功',
data: result,
};
// throw new Error('菠萝派平台接口未实现');
}
/**
* 菜鸟数据处理接口。
*
* @param {Object} [data={}] 平台业务入参。
* @return {Promise<Object>} 处理结果。
*/
async cainiao(data = {}) {
const {
matchedPlatform = {},
listByWarehousePlatformCode = {},
orders = [],
} = data && typeof data === 'object' ? data : {};
const normalizedOrders = Array.isArray(orders) ? orders : [];
const normalizedExtData = this.normalizePddExtData(listByWarehousePlatformCode.ext_data);
const qimenConfig = this.app.config && this.app.config.qimen ? this.app.config.qimen : {};
const appKey = String(qimenConfig.appKey || '').trim();
const appSecret = String(qimenConfig.security || '').trim();
const signService = this.service && this.service.systems ? this.service.systems.sign : null;
const normalizedTemplateUrl = isValidCainiaoTemplateUrl(listByWarehousePlatformCode.template_url)
? String(listByWarehousePlatformCode.template_url).trim()
: DEFAULT_CAINIAO_TEMPLATE_URL;
const ExpressList = await this.service.systems.express.loadExpressList();
const sysExpressName = (ExpressList.find(item => item.code === listByWarehousePlatformCode.sys_express_code) || {}).name || '';
const orderDataMap = new Map();
for (const order_tmp of normalizedOrders) {
const od = order_tmp && order_tmp.order_delivery;
if (!od) continue;
orderDataMap.set(`${od.id}_${order_tmp.business_key}`, {
delivery_order_code: od.delivery_order_code || '',
source_order_codes: od.source_order_codes || '',
store_id: od.store_id || 0,
});
}
if (!appKey || !appSecret) {
throw new Error('淘宝接口配置缺失');
}
if (!signService || typeof signService.signTopRequest !== 'function') {
throw new Error('签名服务不可用');
}
const tradeOrderList = normalizedOrders.map(
order_tmp => {
const orderDelivery = order_tmp && order_tmp.order_delivery ? order_tmp.order_delivery : {};
const sourceOrderCodes = orderDelivery && orderDelivery.source_order_codes
? String(orderDelivery.source_order_codes)
.split(',')
.map(item => String(item || '').trim())
.filter(Boolean)
: [];
// tid 优先取订单表 oaid_order_source_code,为空/空字符串时兜底到原逻辑
const oaidOrderSourceCodes = orderDelivery && orderDelivery.oaid_order_source_code
? String(orderDelivery.oaid_order_source_code)
.split(',')
.map(item => String(item || '').trim())
.filter(Boolean)
: [];
const recipientMobile = orderDelivery && (orderDelivery.mobile || orderDelivery.tel) || '';
const orderDeliveryOaid = orderDelivery && orderDelivery.oaid ? String(orderDelivery.oaid).trim() : '';
const oaidTooLong = orderDeliveryOaid.indexOf('-') !== -1 || orderDeliveryOaid.length > 128;
const tradeOrderInfo = {
logistics_services: normalizedExtData,
object_id: `${orderDelivery.warehouse_id}_${orderDelivery.id}_${order_tmp.business_key}`,
order_info: {
order_channels_type: String(
orderDelivery.sys_platform_code
|| order_tmp.sys_platform_code
|| matchedPlatform.platform_code
|| listByWarehousePlatformCode.platform_code
|| 'CAINIAO'
).trim() || 'CAINIAO',
trade_order_list: sourceOrderCodes.length > 0
? sourceOrderCodes
: [ orderDelivery && orderDelivery.delivery_order_code || '' ],
},
package_info: {
items: (orderDelivery && orderDelivery.orderItems || []).map(item => ({
name: item.item_name || '商品',
count: item.plan_qty,
})) || [],
goods_description: '化妆品',
id: `${orderDelivery.warehouse_id}_${orderDelivery.id}_${order_tmp.business_key}`,
length: Number(orderDelivery.length || 1),
width: Number(orderDelivery.width || 1),
height: Number(orderDelivery.height || 1),
weight: Number(orderDelivery.items_weight || 1),
},
recipient: {
address: {
country: '中国',
city: orderDelivery && orderDelivery.city || '',
province: orderDelivery && orderDelivery.province || '',
district: orderDelivery && orderDelivery.area || '',
town: orderDelivery && orderDelivery.town || null,
detail: orderDelivery && orderDelivery.detail_address || '',
},
mobile: recipientMobile,
name: orderDelivery && orderDelivery.name || '',
phone: recipientMobile,
oaid: oaidTooLong ? '' : orderDeliveryOaid,
caid: oaidTooLong ? orderDeliveryOaid : '',
tid: oaidOrderSourceCodes.length > 0
? oaidOrderSourceCodes[0]
: sourceOrderCodes.length > 0
? sourceOrderCodes[0]
: orderDelivery && orderDelivery.delivery_order_code || '',
},
user_id: listByWarehousePlatformCode.shop && listByWarehousePlatformCode.shop.owner_id || 0,
notify_extend_info: normalizedExtData,
};
tradeOrderInfo.template_url = isValidCainiaoTemplateUrl(listByWarehousePlatformCode.template_url)
? String(listByWarehousePlatformCode.template_url).trim()
: normalizedTemplateUrl;
return tradeOrderInfo;
}
);
const cainiaoPayload = {
param_waybill_cloud_print_apply_new_request: {
cp_code: listByWarehousePlatformCode && listByWarehousePlatformCode.express
? (listByWarehousePlatformCode.express.CAINIAO || listByWarehousePlatformCode.express.cainiao_code || '')
: '',
product_code: String(listByWarehousePlatformCode.product_type || '').trim(),
sender: {
address: {
city: listByWarehousePlatformCode.city_name,
detail: listByWarehousePlatformCode.address,
district: listByWarehousePlatformCode.district_name,
province: listByWarehousePlatformCode.province_name,
town: listByWarehousePlatformCode.town_name || null,
},
mobile: listByWarehousePlatformCode.sender_tel,
name: listByWarehousePlatformCode.sender_name,
phone: listByWarehousePlatformCode.sender_tel,
},
trade_order_info_dtos: tradeOrderList,
brand_code: String(listByWarehousePlatformCode.site_code || 'default').trim(),
need_encrypt: true,
customer_code: String(
listByWarehousePlatformCode.customer_code
|| listByWarehousePlatformCode.client_id
|| listByWarehousePlatformCode.shipperno
|| ''
).trim(),
shipping_branch_code: String(listByWarehousePlatformCode.site_code || '').trim(),
},
};
await this.app.setCacheAsync('Cainiaoquery', JSON.stringify(cainiaoPayload), 3600);
const requestParams = {
method: 'cainiao.waybill.ii.get',
app_key: appKey,
session: String(listByWarehousePlatformCode.token || '').trim(),
timestamp: this.app.formatDate(new Date()),
format: 'json',
v: '2.0',
sign_method: 'md5',
param_waybill_cloud_print_apply_new_request: JSON.stringify(
cainiaoPayload.param_waybill_cloud_print_apply_new_request
),
};
const sign = signService.signTopRequest(requestParams, '', appSecret, 'md5');
const response = await this.ctx.curl(DEFAULT_TB_ROUTER_URL, {
method: 'POST',
contentType: 'form',
dataType: 'json',
data: {
...requestParams,
sign,
},
});
await this.app.setCacheAsync('Cainiaoresult', JSON.stringify(response), 3600);
const responseData = response && Object.prototype.hasOwnProperty.call(response, 'data')
? response.data
: response;
if (responseData && typeof responseData === 'object' && responseData.error_response) {
const errorResponse = responseData.error_response;
throw new Error(errorResponse.sub_msg || errorResponse.msg || '菜鸟平台接口调用失败');
}
const responseRoot = responseData && responseData.cainiao_waybill_ii_get_response
? responseData.cainiao_waybill_ii_get_response
: {};
const modules = normalizeFirstWrappedArray([
responseRoot.modules,
responseRoot.waybill_cloud_print_response_infos,
responseRoot.waybill_cloud_print_response_list,
responseRoot.waybill_cloud_print_response,
], [ 'waybill_cloud_print_response', 'modules', 'module', 'waybill_cloud_print_response_info' ]);
if (modules.length === 0) {
throw new Error('菜鸟平台接口返回数据为空');
}
if (modules.length !== normalizedOrders.length) {
throw new Error(`菜鸟平台接口返回数量异常: 请求 ${normalizedOrders.length} 条, 返回 ${modules.length} 条`);
}
const requestedObjectIdSet = new Set(normalizedOrders.map(order => {
const orderDelivery = order && order.order_delivery ? order.order_delivery : {};
return `${orderDelivery.warehouse_id}_${orderDelivery.id}_${order.business_key}`;
}));
const receivedObjectIdSet = new Set();
const successUpdates = modules.map(moduleItem => {
const objectId = String(moduleItem && moduleItem.object_id || '').trim();
if (!objectId || !requestedObjectIdSet.has(objectId)) {
throw new Error(`菜鸟平台接口返回 object_id 异常: ${objectId || 'empty'}`);
}
if (receivedObjectIdSet.has(objectId)) {
throw new Error(`菜鸟平台接口返回重复 object_id: ${objectId}`);
}
receivedObjectIdSet.add(objectId);
const [ warehouseId, orderId, businessKey ] = objectId.split('_');
const waybillCode = String(moduleItem && (moduleItem.parent_waybill_code || moduleItem.waybill_code) || '').trim();
if (!waybillCode) {
throw new Error(`菜鸟平台接口返回运单号为空: ${objectId}`);
}
const rawPrintData = moduleItem && Object.prototype.hasOwnProperty.call(moduleItem, 'print_data')
? moduleItem.print_data
: moduleItem && Object.prototype.hasOwnProperty.call(moduleItem, 'printData')
? moduleItem.printData
: null;
const parsedPrintData = this.parsePlatformPrintData(rawPrintData, '菜鸟', objectId);
const persistedPrintData = this.stringifyPlatformPrintData(rawPrintData, parsedPrintData);
if (!persistedPrintData) {
throw new Error(`菜鸟平台接口返回 print_data 为空: ${objectId}`);
}
const parsedPrintDataRoot = parsedPrintData && typeof parsedPrintData === 'object' ? parsedPrintData : {};
const printDataContent = parsedPrintDataRoot.data && typeof parsedPrintDataRoot.data === 'object'
? parsedPrintDataRoot.data
: {};
const extraInfo = printDataContent.extraInfo && typeof printDataContent.extraInfo === 'object'
? printDataContent.extraInfo
: {};
const orderExpressVerPatch = this.buildOrderExpressVerPatch([
moduleItem && moduleItem.ver,
parsedPrintDataRoot.ver,
printDataContent.ver,
extraInfo.ver,
]);
const signature = String(
parsedPrintDataRoot.signature
|| printDataContent.signature
|| extraInfo.signature
|| moduleItem && moduleItem.signature
|| ''
).trim() || null;
const encryptPrintInfo = String(
parsedPrintDataRoot.encryptedData
|| parsedPrintDataRoot.key
|| printDataContent.encryptedData
|| printDataContent.encryptWaybillCode
|| extraInfo.encryptWaybillCode
|| extraInfo.key
|| moduleItem && (moduleItem.encrypt_waybill_code || moduleItem.encryptprintinfo)
|| ''
).trim() || null;
return {
warehouse_id: Number(warehouseId) || 0,
order_id: Number(orderId) || 0,
business_key: Number(businessKey) || 0,
waybill_code: waybillCode,
orderExpressValues: {
waybill_code: waybillCode,
printinfo: persistedPrintData,
signature,
encryptprintinfo: encryptPrintInfo,
...orderExpressVerPatch,
create_at: new Date(),
delivery_order_code: orderDataMap.get(`${orderId}_${businessKey}`)?.delivery_order_code || null,
source_order_codes: orderDataMap.get(`${orderId}_${businessKey}`)?.source_order_codes || null,
store_id: orderDataMap.get(`${orderId}_${businessKey}`)?.store_id || null,
logistics_code: listByWarehousePlatformCode.sys_express_code || '',
logistics_interface_id: listByWarehousePlatformCode.id || null,
logistics_name: sysExpressName || '',
logistics_interface_name: listByWarehousePlatformCode.name || '',
platform_code: listByWarehousePlatformCode.platform_code || '',
status: 1,
retry_count: 0,
},
orderDeliveryValues: {
post_status: 'fin',
order_flag: '',
},
};
});
await this.persistWaybillSuccessUpdates(successUpdates, normalizedOrders);
// 自动同步回传:快递号分配成功后异步触发订单同步
try {
const orderMetaMap = this.buildWaybillOrderMetaMap(normalizedOrders);
const settlementRelationMap = this.buildWaybillSettlementRelationMap(
successUpdates,
orderMetaMap
);
const settlementEntries = Array.from(settlementRelationMap.entries());
for (const [ key, relation ] of settlementEntries) {
const successCount = Number(relation && relation.success_count) || 0;
if (successCount <= 0) continue;
const [ storeId, warehouseId ] = key.split(':').map(Number);
if (!storeId || !warehouseId) continue;
const contractConfig = await this.service.systems.storeWarehouse.getContractConfig(
warehouseId,
storeId
);
if (
contractConfig
&& contractConfig.policy_config
&& contractConfig.policy_config.auto_sync_back === 1
) {
// 收集本次分配成功的订单ID
const syncedOrderIds = successUpdates
.filter(u => {
const orderId = Number(u.order_id) || 0;
const wid = Number(u.warehouse_id) || 0;
const bk = Number(u.business_key) || 0;
const meta = orderMetaMap.get(`${wid}_${orderId}_${bk}`);
return meta && meta.store_id === storeId && wid === warehouseId;
})
.map(u => Number(u.order_id) || 0)
.filter(Boolean);
if (syncedOrderIds.length > 0) {
// 异步调用,不阻塞主流程
// 显式传仓库上下文:Qimen 创建订单等链路 ctx.user 为空,
// 不传会导致 syncOrderIds 因"缺少仓库上下文"静默失败
this.ctx.service.systemMethods.order.pendingOrder.syncOrderIds({
orderIds: syncedOrderIds,
warehouseId,
}).catch(err => {
this.ctx.logger.error(
`[auto_sync_back] cainiao 自动同步失败: ${err.message}`
);
});
}
}
}
} catch (err) {
this.ctx.logger.error(
`[auto_sync_back] cainiao 自动同步异常: ${err.message}`
);
}
return {
flag: true,
code: 0,
message: '菜鸟平台数据处理成功',
data: responseData,
};
}
/**
* 解析平台返回的打印数据结构。
*
* @param {*} rawPrintData 平台原始打印数据。
* @param {string} platformName 平台名称。
* @param {string} objectId 请求对象标识。
* @return {Object|null} 解析后的打印数据对象。
*/
parsePlatformPrintData(rawPrintData, platformName, objectId) {
if (rawPrintData === null || rawPrintData === undefined || rawPrintData === '') {
return null;
}
if (typeof rawPrintData === 'string') {
try {
return JSON.parse(rawPrintData);
} catch (error) {
throw new Error(`${platformName}平台接口返回 print_data 解析失败: ${objectId}`);
}
}
if (typeof rawPrintData === 'object') {
return rawPrintData;
}
throw new Error(`${platformName}平台接口返回 print_data 结构异常: ${objectId}`);
}
/**
* 将平台打印数据标准化为可落库的字符串。
*
* @param {*} rawPrintData 平台原始打印数据。
* @param {Object|null} parsedPrintData 解析后的打印数据对象。
* @return {string|null} 可落库字符串。
*/
stringifyPlatformPrintData(rawPrintData, parsedPrintData) {
if (typeof rawPrintData === 'string') {
return rawPrintData.trim() || null;
}
const dataToPersist = parsedPrintData !== undefined ? parsedPrintData : rawPrintData;
if (dataToPersist === null || dataToPersist === undefined || dataToPersist === '') {
return null;
}
if (typeof dataToPersist === 'object') {
return JSON.stringify(dataToPersist);
}
return String(dataToPersist).trim() || null;
}
/**
* 构建订单与货主仓库关系映射。
*
* @param {Array} orders 订单列表。
* @return {Map<string, {store_id: number, warehouse_id: number}>} 订单元数据映射。
*/
buildWaybillOrderMetaMap(orders = []) {
const orderMetaMap = new Map();
for (const order of Array.isArray(orders) ? orders : []) {
const orderDelivery = order && order.order_delivery ? order.order_delivery : {};
const warehouseId = Number(orderDelivery && orderDelivery.warehouse_id) || 0;
const orderId = Number(orderDelivery && orderDelivery.id) || 0;
const businessKey = Number(order && order.business_key) || 0;
if (!warehouseId || !orderId || !businessKey) {
continue;
}
orderMetaMap.set(`${warehouseId}_${orderId}_${businessKey}`, {
store_id: Number(orderDelivery && orderDelivery.store_id) || 0,
warehouse_id: warehouseId,
});
}
return orderMetaMap;
}
/**
* 按货主仓库聚合成功获取面单的扣减数量。
*
* @param {Array} successUpdates 成功回写项。
* @param {Map<string, {store_id: number, warehouse_id: number}>} orderMetaMap 订单元数据映射。
* @return {Map<string, {store_id: number, warehouse_id: number, success_count: number}>} 聚合结果。
*/
buildWaybillSettlementRelationMap(successUpdates = [], orderMetaMap = new Map()) {
const settlementRelationMap = new Map();
for (const item of Array.isArray(successUpdates) ? successUpdates : []) {
const relationMeta = orderMetaMap.get(`${item.warehouse_id}_${item.order_id}_${item.business_key}`);
if (!relationMeta || !relationMeta.store_id || !relationMeta.warehouse_id) {
continue;
}
const relationKey = `${relationMeta.store_id}:${relationMeta.warehouse_id}`;
const currentRelation = settlementRelationMap.get(relationKey) || {
store_id: relationMeta.store_id,
warehouse_id: relationMeta.warehouse_id,
success_count: 0,
};
currentRelation.success_count += 1;
settlementRelationMap.set(relationKey, currentRelation);
}
return settlementRelationMap;
}
/**
* 事务内按 store:warehouse 扣减打印余量并写扣减流水。
*
* 必须在结算事务内最先执行:先锁 wms_store_warehouse,再更新 wms_order_express,
* 与 createWaybillCode 回写事务(先锁 store_warehouse 后锁 order_express)保持
* 一致加锁顺序,消除两类事务间的 AB-BA 死锁。
*
* @param {Map<string, {store_id: number, warehouse_id: number, success_count: number}>} settlementRelationMap 结算关系聚合。
* @param {Object} storeWarehouseModel 签约关系模型。
* @param {Object} transaction Sequelize 事务。
* @return {Promise<void>} 无返回值。
*/
async lockAndDeductWaybillSettlement(settlementRelationMap = new Map(), storeWarehouseModel, transaction) {
if (!storeWarehouseModel
|| typeof storeWarehouseModel.findAll !== 'function'
|| !settlementRelationMap
|| settlementRelationMap.size === 0) {
return;
}
const { Op } = this.app.Sequelize;
const relationList = Array.from(settlementRelationMap.values());
const relationRows = await storeWarehouseModel.findAll({
attributes: [ 'id', 'store_id', 'warehouse_id', 'print_quantity', 'print_quantity_locked' ],
where: {
[Op.or]: relationList.map(item => ({
store_id: item.store_id,
warehouse_id: item.warehouse_id,
})),
},
raw: true,
transaction,
lock: transaction.LOCK.UPDATE,
});
const relationRowMap = new Map();
for (const row of Array.isArray(relationRows) ? relationRows : []) {
const relationKey = `${Number(row && row.store_id) || 0}:${Number(row && row.warehouse_id) || 0}`;
if (relationKey !== '0:0') {
relationRowMap.set(relationKey, row);
}
}
for (const item of relationList) {
const relationKey = `${item.store_id}:${item.warehouse_id}`;
const row = relationRowMap.get(relationKey);
if (!row) {
continue;
}
const currentPrintQuantity = Number(row.print_quantity || 0);
const currentLockedQuantity = Math.max(0, Number(row.print_quantity_locked || 0));
const successCount = Number(item.success_count || 0);
if (successCount <= 0) {
continue;
}
const printDecrement = successCount;
const lockedDecrement = Math.min(currentLockedQuantity, printDecrement);
const nextPrintQuantity = currentPrintQuantity - printDecrement;
const nextLockedQuantity = Math.max(0, currentLockedQuantity - lockedDecrement);
await storeWarehouseModel.update({
print_quantity: nextPrintQuantity,
print_quantity_locked: nextLockedQuantity,
}, {
where: {
id: row.id,
},
transaction,
});
await this.ctx.model.StoreWarehousePrintQuantityLog.create({
contract_id: Number(row.id || 0),
store_id: Number(row.store_id || 0),
warehouse_id: Number(row.warehouse_id || 0),
change_type: 'order_deduct',
business_type: 'order_express',
business_id: null,
change_quantity: -printDecrement,
balance_before: Math.max(0, currentPrintQuantity),
balance_after: Math.max(0, nextPrintQuantity),
reason: '获取快递号成功扣减',
operator_id: null,
created_by: null,
}, {
transaction,
});
}
}
/**
* 回写成功获取的面单结果,并扣减打印余量与写入操作日志。
*
* @param {Array} successUpdates 成功回写项。
* @param {Array} orders 请求订单列表。
* @return {Promise<void>} 无返回值。
*/
async persistWaybillSuccessUpdates(successUpdates = [], orders = []) {
const normalizedSuccessUpdates = Array.isArray(successUpdates) ? successUpdates : [];
if (normalizedSuccessUpdates.length === 0) {
return;
}
const orderMetaMap = this.buildWaybillOrderMetaMap(orders);
const settlementRelationMap = this.buildWaybillSettlementRelationMap(normalizedSuccessUpdates, orderMetaMap);
const storeWarehouseModel = this.ctx.model && this.ctx.model.StoreWarehouse;
if (typeof this.ctx.model.transaction === 'function') {
await this.ctx.model.transaction(async transaction => {
// 统一加锁顺序:先锁 store_warehouse 再更新 order_express,
// 与 createWaybillCode 回写事务一致,避免 AB-BA 死锁
await this.lockAndDeductWaybillSettlement(settlementRelationMap, storeWarehouseModel, transaction);
for (const item of normalizedSuccessUpdates) {
if (!item.warehouse_id || !item.order_id || !item.business_key) {
throw new Error('平台接口返回 object_id 无法解析');
}
await this.ctx.model.OrderExpress.update(this.dropEmptyOrderExpressFields(item.orderExpressValues), {
where: {
order_id: item.order_id,
business_key: item.business_key,
warehouse_id: item.warehouse_id,
},
transaction,
});
const orderModel = await this.service.systems.express.getWaybillAsyncOrderDeliveryModel(item.warehouse_id);
if (item.orderDeliveryValues && orderModel && typeof orderModel.update === 'function') {
await orderModel.update(item.orderDeliveryValues, {
where: {
id: item.order_id,
},
transaction,
});
}
}
});
}
const operationLogService = this.service && this.service.systems && this.service.systems.operationLog;
const operator = this.getOrderLogOperator();
const logPayloads = normalizedSuccessUpdates
.filter(item => item.warehouse_id && item.order_id)
.map(item => ({
businessType: 'order',
businessId: `${item.order_id}`,
operationCode: 'WAYBILL',
operator,
extras: {
message: `订单${item.order_id}获取快递单成功,单号:${item.waybill_code}`,
warehouseId: item.warehouse_id,
externalLogType: 'API',
},
}));
if (operationLogService && typeof operationLogService.createOperationLogs === 'function' && logPayloads.length > 0) {
await operationLogService.createOperationLogs(logPayloads);
}
}
/**
* 规范化拼多多接口要求的扩展字段字符串。
*
* @param {*} value 扩展字段原始值。
* @return {string} 规范化后的字符串。
*/
normalizePddExtData(value) {
if (value === null || value === undefined || value === '') {
return '';
}
if (typeof value === 'string') {
return value.trim();
}
if (typeof value === 'object') {
return JSON.stringify(value);
}
return String(value);
}
/**
* 拼多多数据处理接口。
*
* @param {Object} [data={}] 平台业务入参。
* @return {Promise<never>} 当前暂未实现,直接抛出异常。
*/
async pdd(data = {}) {
const {
listByWarehousePlatformCode = {},
orders = [],
} = data && typeof data === 'object' ? data : {};
const normalizedOrders = Array.isArray(orders) ? orders : [];
const normalizedExtData = this.normalizePddExtData(listByWarehousePlatformCode.ext_data);
const ExpressList = await this.service.systems.express.loadExpressList();
const sysExpressName = (ExpressList.find(item => item.code === listByWarehousePlatformCode.sys_express_code) || {}).name || '';
const orderDataMap = new Map();
for (const order_tmp of normalizedOrders) {
const od = order_tmp && order_tmp.order_delivery;
if (!od) continue;
orderDataMap.set(`${od.id}_${order_tmp.business_key}`, {
delivery_order_code: od.delivery_order_code || '',
source_order_codes: od.source_order_codes || '',
store_id: od.store_id || 0,
});
}
console.log('拼多多平台接口入参', data);
const tradeOrderList = normalizedOrders.map(
order_tmp => {
return {
logistics_services: normalizedExtData,
object_id: `${order_tmp.order_delivery.warehouse_id}_${order_tmp.order_delivery.id}_${order_tmp.business_key}`,
order_info: {
order_channels_type: 'PDD',
trade_order_list: [ `${order_tmp.order_delivery.warehouse_id}_${order_tmp.order_delivery.id}_${order_tmp.business_key}` ],
},
package_info: {
items: (order_tmp.order_delivery && order_tmp.order_delivery.orderItems || []).map(item => ({
name: item.item_name || '商品',
count: item.plan_qty,
})) || [],
id: `${order_tmp.order_delivery.warehouse_id}_${order_tmp.order_delivery.id}_${order_tmp.business_key}`,
total_packages_count: order_tmp.business_key || 1,
},
recipient: {
address: {
country: '中国',
city: order_tmp.order_delivery && order_tmp.order_delivery.city || '',
province: order_tmp.order_delivery && order_tmp.order_delivery.province || '',
district: order_tmp.order_delivery && order_tmp.order_delivery.area || '',
town: order_tmp.order_delivery && order_tmp.order_delivery.town || null,
detail: order_tmp.order_delivery && order_tmp.order_delivery.detail_address || '',
},
moblie: order_tmp.order_delivery && (order_tmp.order_delivery.mobile || order_tmp.order_delivery.tel) || '',
name: order_tmp.order_delivery && order_tmp.order_delivery.name || '',
phone: order_tmp.order_delivery && (order_tmp.order_delivery.mobile || order_tmp.order_delivery.tel) || '',
},
template_url: listByWarehousePlatformCode.template_url || '',
user_id: listByWarehousePlatformCode.shop.owner_id || 0,
};
}
);
// 构建pdd接口入参
const pddPayload = {
// 这里根据实际需要构建接口入参
type: 'pdd.waybill.get',
accessToken: listByWarehousePlatformCode.token,
param_waybill_cloud_print_apply_new_request: {
need_encrypt: true,
sender: {
address: {
country: '中国',
city: listByWarehousePlatformCode.city_name,
province: listByWarehousePlatformCode.province_name,
district: listByWarehousePlatformCode.district_name,
town: listByWarehousePlatformCode.town_name || null,
detail: listByWarehousePlatformCode.address,
},
moblie: listByWarehousePlatformCode.sender_tel,
name: listByWarehousePlatformCode.sender_name,
phone: listByWarehousePlatformCode.sender_tel,
},
trade_order_info_dtos: tradeOrderList,
wp_code: listByWarehousePlatformCode && listByWarehousePlatformCode.express
? (listByWarehousePlatformCode.express.PDD || '')
: '',
},
};
console.log('拼多多平台接口构建的请求参数', JSON.stringify(pddPayload, null, 2));
await this.app.setCacheAsync('Pddquery', JSON.stringify(pddPayload), 3600);
// 这里写一个调用pdd_client的入参示例
//
//
//
const pddClient = new PddClient(this.ctx);
const {
type,
accessToken,
dataType,
timestamp,
...requestParams
} = pddPayload;
const pddConfig = (this.ctx && this.ctx.app && this.ctx.app.config && this.ctx.app.config.pdd) || {};
const configClientId = pddConfig.client_id || pddConfig.clientId;
const configClientSecret = pddConfig.client_secret || pddConfig.clientSecret;
console.log('拼多多签名凭据来源', {
clientId: configClientId || '(missing app.config.pdd.client_id)',
hasClientSecret: Boolean(configClientSecret),
source: 'app.config.pdd',
});
const builtRequest = pddClient.buildRequest({
type,
accessToken,
dataType,
timestamp,
clientId: configClientId,
clientSecret: configClientSecret,
bizParams: requestParams,
});
console.log('拼多多平台接口请求参数', JSON.stringify({
baseUrl: DEFAULT_PDD_ROUTER_URL,
requestBody: builtRequest.requestBody,
signText: builtRequest.signText,
sortedPairs: builtRequest.sortedPairs,
}, null, 2));
try {
const response = await this.ctx.curl(DEFAULT_PDD_ROUTER_URL, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
dataType: String(pddPayload.dataType || 'JSON').toLowerCase() === 'xml' ? 'text' : 'json',
data: builtRequest.requestBody,
});
await this.app.setCacheAsync('Pddresult', JSON.stringify(response), 3600);
const responseData = response && Object.prototype.hasOwnProperty.call(response, 'data')
? response.data
: response;
console.log('拼多多平台接口返回参数', JSON.stringify(responseData, null, 2));
const errorResponse = responseData && responseData.error_response;
if (errorResponse) {
const errorMessage = String(errorResponse.sub_msg || errorResponse.error_msg || '拼多多平台接口调用失败').trim();
throw new Error(errorMessage);
}
const modules = responseData
&& responseData.pdd_waybill_get_response
&& Array.isArray(responseData.pdd_waybill_get_response.modules)
? responseData.pdd_waybill_get_response.modules
: [];
if (modules.length === 0) {
throw new Error('拼多多平台接口返回数据为空');
}
if (modules.length !== normalizedOrders.length) {
throw new Error(`拼多多平台接口返回数量异常: 请求 ${normalizedOrders.length} 条, 返回 ${modules.length} 条`);
}
const requestedObjectIdSet = new Set(normalizedOrders.map(order => `${order.order_delivery.warehouse_id}_${order.order_delivery.id}_${order.business_key}`));
const successUpdates = modules.map(moduleItem => {
const objectId = String(moduleItem && moduleItem.object_id || '').trim();
if (!objectId || !requestedObjectIdSet.has(objectId)) {
throw new Error(`拼多多平台接口返回 object_id 异常: ${objectId || 'empty'}`);
}
const [ warehouseId, orderId, businessKey ] = objectId.split('_');
const waybillCode = String(moduleItem && (moduleItem.parent_waybill_code || moduleItem.waybill_code) || '').trim();
if (!waybillCode) {
throw new Error(`拼多多平台接口返回运单号为空: ${objectId}`);
}
let parsedPrintData = null;
if (moduleItem && moduleItem.print_data) {
try {
parsedPrintData = JSON.parse(moduleItem.print_data);
} catch (parseError) {
throw new Error(`拼多多平台接口返回 print_data 解析失败: ${objectId}`);
}
}
return {
warehouse_id: Number(warehouseId) || 0,
order_id: Number(orderId) || 0,
business_key: Number(businessKey) || 0,
waybill_code: waybillCode,
orderExpressValues: {
waybill_code: waybillCode,
signature: (parsedPrintData && parsedPrintData.signature) || String(moduleItem && moduleItem.signature || '').trim() || null,
encryptprintinfo: (parsedPrintData && parsedPrintData.encryptedData) || null,
...this.buildOrderExpressVerPatch([
moduleItem && moduleItem.ver,
parsedPrintData && parsedPrintData.ver,
parsedPrintData && parsedPrintData.data && parsedPrintData.data.ver,
]),
create_at: new Date(),
delivery_order_code: orderDataMap.get(`${orderId}_${businessKey}`)?.delivery_order_code || null,
source_order_codes: orderDataMap.get(`${orderId}_${businessKey}`)?.source_order_codes || null,
store_id: orderDataMap.get(`${orderId}_${businessKey}`)?.store_id || null,
logistics_code: listByWarehousePlatformCode.sys_express_code || '',
logistics_interface_id: listByWarehousePlatformCode.id || null,
logistics_name: sysExpressName || '',
logistics_interface_name: listByWarehousePlatformCode.name || '',
platform_code: listByWarehousePlatformCode.platform_code || '',
status: 1,
retry_count: 0,
},
orderDeliveryValues: {
post_status: 'fin',
order_flag: '',
},
};
});
const orderMetaMap = new Map();
for (const order of normalizedOrders) {
const orderDelivery = order && order.order_delivery;
const warehouseId = Number(orderDelivery && orderDelivery.warehouse_id) || 0;
const orderId = Number(orderDelivery && orderDelivery.id) || 0;
const businessKey = Number(order && order.business_key) || 0;
if (!warehouseId || !orderId || !businessKey) {
continue;
}
orderMetaMap.set(`${warehouseId}_${orderId}_${businessKey}`, {
store_id: Number(orderDelivery && orderDelivery.store_id) || 0,
warehouse_id: warehouseId,
});
}
const settlementRelationMap = new Map();
for (const item of successUpdates) {
const relationMeta = orderMetaMap.get(`${item.warehouse_id}_${item.order_id}_${item.business_key}`);
if (!relationMeta || !relationMeta.store_id || !relationMeta.warehouse_id) {
continue;
}
const relationKey = `${relationMeta.store_id}:${relationMeta.warehouse_id}`;
const currentRelation = settlementRelationMap.get(relationKey) || {
store_id: relationMeta.store_id,
warehouse_id: relationMeta.warehouse_id,
success_count: 0,
};
currentRelation.success_count += 1;
settlementRelationMap.set(relationKey, currentRelation);
}
const storeWarehouseModel = this.ctx.model && this.ctx.model.StoreWarehouse;
if (typeof this.ctx.model.transaction === 'function' && successUpdates.length > 0) {
await this.ctx.model.transaction(async transaction => {
// 统一加锁顺序:先锁 store_warehouse 再更新 order_express,
// 与 createWaybillCode 回写事务一致,避免 AB-BA 死锁
await this.lockAndDeductWaybillSettlement(settlementRelationMap, storeWarehouseModel, transaction);
for (const item of successUpdates) {
if (!item.warehouse_id || !item.order_id || !item.business_key) {
throw new Error('拼多多平台接口返回 object_id 无法解析');
}
await this.ctx.model.OrderExpress.update(item.orderExpressValues, {
where: {
order_id: item.order_id,
business_key: item.business_key,
warehouse_id: item.warehouse_id,
},
transaction,
});
const orderModel = await this.service.systems.express.getWaybillAsyncOrderDeliveryModel(item.warehouse_id);
if (item.orderDeliveryValues && orderModel && typeof orderModel.update === 'function') {
await orderModel.update(item.orderDeliveryValues, {
where: {
id: item.order_id,
},
transaction,
});
}
}
});
}
const operationLogService = this.service && this.service.systems && this.service.systems.operationLog;
const operator = this.getOrderLogOperator();
const logPayloads = successUpdates
.filter(item => item.warehouse_id && item.order_id)
.map(item => ({
businessType: 'order',
businessId: `${item.order_id}`,
operationCode: 'WAYBILL',
operator,
extras: {
message: `订单${item.order_id}获取快递单成功,单号:${item.waybill_code}`,
warehouseId: item.warehouse_id,
externalLogType: 'API',
},
}));
if (operationLogService && typeof operationLogService.createOperationLogs === 'function' && logPayloads.length > 0) {
await operationLogService.createOperationLogs(logPayloads);
}
// 自动同步回传:快递号分配成功后异步触发订单同步
try {
const settlementEntries = Array.from(settlementRelationMap.entries());
for (const [ key, relation ] of settlementEntries) {
const successCount = Number(relation && relation.success_count) || 0;
if (successCount <= 0) continue;
const [ storeId, warehouseId ] = key.split(':').map(Number);
if (!storeId || !warehouseId) continue;
const contractConfig = await this.service.systems.storeWarehouse.getContractConfig(
warehouseId,
storeId
);
if (
contractConfig
&& contractConfig.policy_config
&& contractConfig.policy_config.auto_sync_back === 1
) {
// 收集本次分配成功的订单ID
const syncedOrderIds = successUpdates
.filter(u => {
const orderId = Number(u.order_id) || 0;
const wid = Number(u.warehouse_id) || 0;
const bk = Number(u.business_key) || 0;
const meta = orderMetaMap.get(`${wid}_${orderId}_${bk}`);
return meta && meta.store_id === storeId && wid === warehouseId;
})
.map(u => Number(u.order_id) || 0)
.filter(Boolean);
if (syncedOrderIds.length > 0) {
// 异步调用,不阻塞主流程
// 显式传仓库上下文:Qimen 创建订单等链路 ctx.user 为空,
// 不传会导致 syncOrderIds 因"缺少仓库上下文"静默失败
this.ctx.service.systemMethods.order.pendingOrder.syncOrderIds({
orderIds: syncedOrderIds,
warehouseId,
}).catch(err => {
this.ctx.logger.error(
`[auto_sync_back] pdd 自动同步失败: ${err.message}`
);
});
}
}
}
} catch (err) {
this.ctx.logger.error(
`[auto_sync_back] pdd 自动同步异常: ${err.message}`
);
}
return {
flag: true,
code: 0,
message: '拼多多平台数据处理成功',
data: responseData,
};
} catch (error) {
console.log('拼多多平台接口返回异常', error && error.message ? error.message : `${error}`);
throw error;
}
}
/**
* 规范化 OMS 取号订单项。
*
* 兼容两种入参形态:
* - 队列/流水线风格:`{ order_id, business_key, order_delivery: {...} }`
* - 展平风格:直接把订单字段放在数组项上
*
* @param {Array<Object>} orders 订单列表。
* @return {Array<Object>} 规范化后的订单项。
*/
normalizeOmsWaybillOrders(orders = []) {
const normalized = [];
for (const item of normalizeArray(orders)) {
if (!item || typeof item !== 'object') {
continue;
}
const orderDelivery = item.order_delivery && typeof item.order_delivery === 'object'
? item.order_delivery
: item;
const orderId = Number(orderDelivery.id || orderDelivery.order_id || item.order_id) || 0;
if (!Number.isInteger(orderId) || orderId <= 0) {
continue;
}
const businessKey = Number(item.business_key || item.businessKey) || 1;
const expressCode = String(
orderDelivery.logistics_code
|| orderDelivery.sys_logistics_code
|| orderDelivery.express_code
|| ''
).trim().toUpperCase();
normalized.push({
order_id: orderId,
business_key: businessKey,
delivery_order_code: String(
orderDelivery.delivery_order_code || orderDelivery.deliveryOrderCode || ''
).trim(),
express_code: expressCode,
store_id: Number(orderDelivery.store_id) || 0,
warehouse_id: Number(orderDelivery.warehouse_id) || 0,
source_order_codes: orderDelivery.source_order_codes || null,
from_key: String(orderDelivery.from_key || '').trim(),
// 打印按来源平台(wms_print_platform.platform_code)匹配模板,不能落 'oms'
platform_code: String(
orderDelivery.sys_platform_code || orderDelivery.source_platform_code || ''
).trim().toUpperCase(),
});
}
return normalized;
}
/**
* 加载「系统平台编码 -> 打印平台编码」映射。
*
* 与 `express.js createWaybillCodePipeline` 同源同参(`getPlatformList(true, true)`),
* 保证本地取号与 OMS 回源取号算出的平台码口径一致。
* 映射缺失时返回空 Map,调用方按原值兜底,不影响取号主流程。
*
* @return {Promise<Map<string, string>>} 系统平台编码(大写)到打印平台编码(大写)的映射。
*/
async buildWaybillPrintPlatformCodeMap() {
const platformService = this.service && this.service.systems && this.service.systems.platform;
if (!platformService || typeof platformService.getPlatformList !== 'function') {
this.ctx.logger.warn('[ExpressPlatformService.buildWaybillPrintPlatformCodeMap] platform 服务不可用,平台码不做归一');
return new Map();
}
let platformList = [];
try {
platformList = await platformService.getPlatformList(true, true);
} catch (error) {
this.ctx.logger.warn('[ExpressPlatformService.buildWaybillPrintPlatformCodeMap] 平台列表加载失败,平台码不做归一', {
error: error && error.message ? error.message : `${error}`,
});
return new Map();
}
const printPlatformCodeMap = new Map();
for (const platform of normalizeArray(platformList)) {
const platformCode = String(platform && platform.code || '').trim().toUpperCase();
const printPlatformCode = String(platform && platform.default_express_interface || '').trim().toUpperCase();
if (platformCode && printPlatformCode) {
printPlatformCodeMap.set(platformCode, printPlatformCode);
}
}
return printPlatformCodeMap;
}
/**
* 将平台码归一为打印平台编码。
*
* 落库口径统一为 `wms_print_platform.platform_code`:
* 本地取号取的是 `wms_express_interface.platform_code`(已是打印平台码),
* OMS 回源取号的来源平台码(如 DYXD)必须映射成同一编码后再落库。
*
* @param {string} platformCode 原始平台码。
* @param {Map<string, string>} [printPlatformCodeMap] 平台码映射。
* @return {string} 归一后的平台码;无法归一或为空时返回原值(大写)。
*/
resolveWaybillPrintPlatformCode(platformCode, printPlatformCodeMap = new Map()) {
const normalizedPlatformCode = String(platformCode || '').trim().toUpperCase();
if (!normalizedPlatformCode) {
return '';
}
const mappedPlatformCode = printPlatformCodeMap instanceof Map
? printPlatformCodeMap.get(normalizedPlatformCode)
: '';
return String(mappedPlatformCode || normalizedPlatformCode).trim().toUpperCase();
}
/**
* 就地归一 OMS 取号订单项的平台码。
*
* @param {Array<Object>} items 归一化后的 OMS 取号订单项。
* @param {Map<string, string>} [printPlatformCodeMap] 平台码映射。
* @return {Array<Object>} 归一后的订单项。
*/
applyWaybillPrintPlatformCodes(items = [], printPlatformCodeMap = new Map()) {
for (const item of normalizeArray(items)) {
if (!item || typeof item !== 'object') {
continue;
}
item.platform_code = this.resolveWaybillPrintPlatformCode(item.platform_code, printPlatformCodeMap);
}
return items;
}
/**
* 为 OMS 淘宝(菜鸟)运单回拼 printinfo 整包。
*
* OMS 取号把菜鸟加密面单拆成 `signature` / `encryptprintinfo` / `ver` 平铺返回,
* `printinfo` 恒为空串;而 WMS 菜鸟打印只认 `printinfo` 里的
* `{ encryptedData, signature, ver }`(见 app/lib/printer_data_builder.js 的菜鸟分支)。
* 不回拼会导致打印退化成模板兜底(`_dataFrom='template'`),与菠萝派取号单输出不一致。
*
* 取值原样保留密文前缀(`AES:` / `MD:`),不做解码。
*
* @param {string} platformCode 归一后的平台编码。
* @param {Object} orderExpressValues 待写入的运单字段集合。
* @return {string} 可直接落库的 printinfo JSON;不适用时返回空字符串。
*/
buildOmsCainiaoPrintinfo(platformCode, orderExpressValues = {}) {
const normalizedPlatformCode = String(platformCode || '').trim().toUpperCase();
// CAINIAO 为归一后的打印平台码;TB 为归一失败时的原始码(打印侧同样归一为菜鸟)
if (normalizedPlatformCode !== 'CAINIAO' && normalizedPlatformCode !== 'TB') {
return '';
}
const values = orderExpressValues && typeof orderExpressValues === 'object' ? orderExpressValues : {};
if (String(values.printinfo || '').trim()) {
return '';
}
const encryptedData = String(values.encryptprintinfo || '').trim();
if (!encryptedData) {
return '';
}
const payload = { encryptedData };
const signature = String(values.signature || '').trim();
if (signature) {
payload.signature = signature;
}
const version = String(values.ver || '').trim();
if (version) {
payload.ver = version;
}
return JSON.stringify(payload);
}
/**
* 剔除上游未返回(null/undefined/空串)的运单报文字段。
*
* 命中的字段不做写入,交由数据库保留已有值,避免 OMS 回源取号把本地已落库的报文冲成空。
*
* @param {Object} [values={}] 待写入 `wms_order_express` 的字段集合。
* @return {Object} 剔除空值后的字段集合。
*/
dropEmptyOrderExpressFields(values = {}) {
const source = values && typeof values === 'object' ? values : {};
const sanitized = { ...source };
for (const field of ORDER_EXPRESS_UPSTREAM_OPTIONAL_FIELDS) {
if (!Object.prototype.hasOwnProperty.call(sanitized, field)) {
continue;
}
const value = sanitized[field];
if (value === null || value === undefined || String(value).trim() === '') {
delete sanitized[field];
}
}
return sanitized;
}
/**
* 按货主 + 仓库反查可用于回调 OMS 的 OpenAPI 应用配置。
*
* @param {number} storeId 货主 ID。
* @param {number} warehouseId 仓库 ID。
* @return {Promise<Object|null>} { appKey, selfAppSecret, callbackUrl } 或 null。
*/
async resolveOmsWaybillAppConfig(storeId, warehouseId) {
const orderAsyncService = this.service && this.service.systems && this.service.systems.orderAsync;
if (!orderAsyncService || typeof orderAsyncService.resolveOpenApiAppByStore !== 'function') {
return null;
}
return await orderAsyncService.resolveOpenApiAppByStore(storeId, warehouseId);
}
/**
* 为待取号订单解析回 OMS 用的 appKey。
*
* 优先使用订单 `from_key`(建单时落库的来源应用 appKey,即 api_app.self_app_key),
* 缺失时按「货主 + 仓库」反查授权关系下的启用 ApiApp。
*
* @param {Array<Object>} items 归一化后的订单项(就地写入 app_key)。
* @return {Promise<void>} 无返回值。
*/
async attachOmsWaybillAppKeys(items = []) {
const cache = new Map();
for (const item of normalizeArray(items)) {
if (item.from_key) {
item.app_key = item.from_key;
item.app_key_source = 'order.from_key';
continue;
}
const cacheKey = `${item.store_id}:${item.warehouse_id}`;
if (!cache.has(cacheKey)) {
const appConfig = await this.resolveOmsWaybillAppConfig(item.store_id, item.warehouse_id);
cache.set(cacheKey, String(appConfig && appConfig.appKey || '').trim());
}
item.app_key = cache.get(cacheKey);
item.app_key_source = 'store_warehouse.api_app';
}
}
/**
* 生成稳定的 OMS 幂等 request_id。
*
* 摘要输入采用与菠萝派/菜鸟/拼多多一致的包裹标识
* `warehouse_id(16进制)_order_id(16进制)_business_key`,
* 同批(同一组包裹)在重试时得到相同值,OMS 会直接回放上次响应,
* 避免重复调用打单平台产生重复面单。
*
* @param {number} warehouseId 仓库 ID(订单项缺 warehouse_id 时兜底)。
* @param {Array<Object>} items 本批订单项。
* @return {string} request_id(不超过 OMS 100 字符上限)。
*/
buildOmsWaybillRequestId(warehouseId, items = []) {
const objectIds = normalizeArray(items)
.map(item => {
const warehouseHex = (Number(item.warehouse_id) || Number(warehouseId) || 0).toString(16);
const orderHex = (Number(item.order_id) || 0).toString(16);
const businessKey = Number(item.business_key) || 1;
return `${warehouseHex}_${orderHex}_${businessKey}`;
})
.sort();
return `oms-getwaybill-${crypto.createHash('md5').update(objectIds.join(','), 'utf8').digest('hex')}`;
}
/**
* 生成 OMS 取号报文缓存的键集合。
*
* 除固定 latest 键外,再按 request_id 落一份,便于用日志里的 request_id 直接定位。
*
* @param {string} [requestId=''] 本次取号的 request_id。
* @return {{ request: string, response: string, responseByRequestId: string }} 缓存键集合。
*/
buildOmsWaybillPayloadCacheKeys(requestId = '') {
const normalizedRequestId = String(requestId || '').trim();
return {
request: `${OMS_WAYBILL_PAYLOAD_CACHE_KEY_PREFIX}:request:latest`,
response: `${OMS_WAYBILL_PAYLOAD_CACHE_KEY_PREFIX}:response:latest`,
responseByRequestId: normalizedRequestId
? `${OMS_WAYBILL_PAYLOAD_CACHE_KEY_PREFIX}:response:${normalizedRequestId}`
: '',
};
}
/**
* 按字段名截断报文中的密文/大字段。
*
* 仅改写命中 {@link OMS_WAYBILL_PAYLOAD_HEAVY_FIELDS} 且超长的字符串取值,
* 其余字段(含层级结构)原样保留,确保缓存内容仍能反映真实报文格式。
*
* @param {*} value 报文节点。
* @param {number} [depth=0] 当前递归深度,超过 10 层不再下钻。
* @return {*} 处理后的报文节点。
*/
truncateOmsWaybillPayloadFields(value, depth = 0) {
if (depth > 10 || value === null || typeof value !== 'object') {
return value;
}
if (Array.isArray(value)) {
return value.map(item => this.truncateOmsWaybillPayloadFields(item, depth + 1));
}
const truncated = {};
for (const [ key, item ] of Object.entries(value)) {
const isHeavyField = OMS_WAYBILL_PAYLOAD_HEAVY_FIELDS.includes(String(key).toLowerCase());
if (isHeavyField
&& typeof item === 'string'
&& item.length > OMS_WAYBILL_PAYLOAD_HEAVY_FIELD_KEEP_CHARS) {
truncated[key] = `${item.slice(0, OMS_WAYBILL_PAYLOAD_HEAVY_FIELD_KEEP_CHARS)}...(truncated,total=${item.length})`;
continue;
}
truncated[key] = this.truncateOmsWaybillPayloadFields(item, depth + 1);
}
return truncated;
}
/**
* 缓存 OMS 回源取号的请求与返回报文。
*
* OMS 返回的报文格式是与 OMS 对齐的唯一依据,落缓存后可直接用
* `script/redis-cache.ps1 -Action get -Key <key>` 取回核对,不再依赖日志留存。
* 缓存失败只告警,绝不影响取号结果。
*
* 缓存键(TTL 见 {@link OMS_WAYBILL_PAYLOAD_CACHE_TTL}):
* - `oms:waybill:request:latest`:最近一次请求体
* - `oms:waybill:response:latest`:最近一次完整快照(元信息 + 请求 + 返回报文)
* - `oms:waybill:response:<request_id>`:按 request_id 归档的同一份快照
*
* @param {Object} [payload={}] 快照数据。
* @param {string} [payload.request_id] 本次取号 request_id。
* @param {string} [payload.app_key] 目标 OMS 应用 appKey。
* @param {number} [payload.warehouse_id] 仓库 ID。
* @param {number} [payload.store_id] 货主 ID。
* @param {number} [payload.order_count] 本次批次订单数。
* @param {Array<string>} [payload.delivery_order_codes] 本次批次发货单号。
* @param {Object} [payload.transport] 传输层结果(success/retry_count/error)。
* @param {Object} [payload.request] 实际下发的请求体。
* @param {*} [payload.response] OMS 原始返回报文。
* @return {Promise<Object|null>} 缓存键与字节数;未缓存时返回 null。
*/
async cacheOmsWaybillPayload(payload = {}) {
const app = this.ctx && this.ctx.app;
const cacheKeys = this.buildOmsWaybillPayloadCacheKeys(payload.request_id);
if (!app || typeof app.setCacheAsync !== 'function') {
return null;
}
const snapshot = {
cached_at: new Date().toISOString(),
request_id: String(payload.request_id || ''),
app_key: String(payload.app_key || ''),
event: OMS_WAYBILL_EVENT,
warehouse_id: Number(payload.warehouse_id) || 0,
store_id: Number(payload.store_id) || 0,
order_count: Number(payload.order_count) || 0,
delivery_order_codes: normalizeArray(payload.delivery_order_codes),
transport: payload.transport || {},
request: payload.request === undefined ? null : payload.request,
response: payload.response === undefined ? null : payload.response,
payload_truncated: false,
};
let payloadBytes = Buffer.byteLength(JSON.stringify(snapshot), 'utf8');
if (payloadBytes > OMS_WAYBILL_PAYLOAD_CACHE_MAX_BYTES) {
snapshot.request = this.truncateOmsWaybillPayloadFields(snapshot.request);
snapshot.response = this.truncateOmsWaybillPayloadFields(snapshot.response);
snapshot.payload_truncated = true;
payloadBytes = Buffer.byteLength(JSON.stringify(snapshot), 'utf8');
}
if (payloadBytes > OMS_WAYBILL_PAYLOAD_CACHE_MAX_BYTES) {
// 脱敏后仍超限:响应只留元信息,避免把 Redis 打爆
snapshot.response = `<omitted: ${Buffer.byteLength(JSON.stringify(payload.response === undefined ? null : payload.response), 'utf8')} bytes,超过报文缓存上限>`;
payloadBytes = Buffer.byteLength(JSON.stringify(snapshot), 'utf8');
}
try {
await app.setCacheAsync(cacheKeys.request, snapshot.request, OMS_WAYBILL_PAYLOAD_CACHE_TTL);
await app.setCacheAsync(cacheKeys.response, snapshot, OMS_WAYBILL_PAYLOAD_CACHE_TTL);
if (cacheKeys.responseByRequestId) {
await app.setCacheAsync(cacheKeys.responseByRequestId, snapshot, OMS_WAYBILL_PAYLOAD_CACHE_TTL);
}
} catch (error) {
this.ctx.logger.warn('[ExpressPlatformService.oms] OMS 取号报文缓存写入失败', {
requestId: snapshot.request_id,
error: error && error.message ? error.message : `${error}`,
});
return null;
}
this.ctx.logger.info('[ExpressPlatformService.oms] OMS 取号报文已缓存', {
requestId: snapshot.request_id,
cacheKey: cacheKeys.response,
requestIdCacheKey: cacheKeys.responseByRequestId,
ttlSeconds: OMS_WAYBILL_PAYLOAD_CACHE_TTL,
payloadBytes,
truncated: snapshot.payload_truncated,
});
return {
...cacheKeys,
payloadBytes,
};
}
/**
* 判断 OMS 逐单失败原因是否值得重试。
*
* @param {string} message OMS 返回的失败原因。
* @return {boolean} 可重试返回 true。
*/
isRetryableOmsWaybillMessage(message) {
const text = String(message || '').trim();
if (!text) {
return false;
}
return !OMS_WAYBILL_NON_RETRYABLE_KEYWORDS.some(keyword => text.includes(keyword));
}
/**
* 为回 OMS 取号的订单补齐 order_express 占位行。
*
* 这类订单被本地取号流水线整体跳过(不建占位行),若不补齐,
* 取号成功后的 update 会因无匹配行而丢失运单号。
*
* @param {Array<Object>} items 本次取号成功的订单项。
* @param {number} warehouseId 仓库 ID。
* @return {Promise<void>} 无返回值。
*/
async ensureOmsWaybillOrderExpressRows(items = [], warehouseId = 0) {
const orderExpressModel = this.ctx.model && this.ctx.model.OrderExpress;
const normalizedItems = normalizeArray(items).filter(item => item.order_id);
if (!orderExpressModel
|| typeof orderExpressModel.findAll !== 'function'
|| typeof orderExpressModel.bulkCreate !== 'function'
|| normalizedItems.length === 0) {
return;
}
const { Op } = this.app.Sequelize;
const existingRows = await orderExpressModel.findAll({
where: {
order_id: {
[Op.in]: normalizedItems.map(item => item.order_id),
},
},
attributes: [ 'order_id', 'business_key' ],
raw: true,
});
const existingKeySet = new Set(
normalizeArray(existingRows).map(row => `${Number(row.order_id)}:${Number(row.business_key) || 1}`)
);
const rowsToCreate = normalizedItems
.filter(item => !existingKeySet.has(`${item.order_id}:${item.business_key}`))
.map(item => ({
order_id: item.order_id,
business_key: item.business_key,
status: 0,
retry_count: 0,
warehouse_id: item.warehouse_id || warehouseId,
store_id: item.store_id || null,
logistics_code: item.express_code || '',
delivery_order_code: item.delivery_order_code || null,
source_order_codes: item.source_order_codes || null,
}));
if (rowsToCreate.length === 0) {
return;
}
await orderExpressModel.bulkCreate(rowsToCreate, { ignoreDuplicates: true });
}
/**
* OMS 回源取号(deliveryorder.getwaybill)。
*
* 处理 need_oms_waybill=1 的订单:不调本地快递平台,改由 OMS 侧的
* 外部打单账号取号,回传运单号后写入 order_express 并把订单置为已分配快递。
*
* 约定:
* - 单批最多 100 单(OMS 硬上限),超出自动切分;
* - request_id 由订单集合推导,重试复用同一值以命中 OMS 幂等;
* - 有失败时抛错,`error.retryable` 标记是否值得重试,由队列消费侧决定状态。
*
* @param {Object} data 业务数据骨架(orders / warehouse_id / store_id)。
* @return {Promise<Object>} 处理结果。
*/
async oms(data = {}) {
const source = data && typeof data === 'object' ? data : {};
const warehouseIdHint = Number(source.warehouse_id || source.warehouseId) || 0;
const storeIdHint = Number(source.store_id || source.storeId) || 0;
const rawOrders = normalizeArray(source.orders);
const items = this.normalizeOmsWaybillOrders(rawOrders);
if (items.length === 0) {
return {
flag: 'success',
code: 0,
message: '没有需要回 OMS 取号的订单',
data: { total: 0, success: 0, failed: 0, results: [] },
};
}
// 平台码统一归一为打印平台码,与本地取号落库口径保持一致(避免把 DYXD 这类来源平台码写进 order_express)
const printPlatformCodeMap = await this.buildWaybillPrintPlatformCodeMap();
this.applyWaybillPrintPlatformCodes(items, printPlatformCodeMap);
const startedAt = Date.now();
const callbackService = this.service && this.service.openapi && this.service.openapi.callback;
const ExpressList = await this.service.systems.express.loadExpressList();
const aggregatedResults = [];
const failedMessages = [];
const successUpdates = [];
const successItems = [];
let retryable = false;
let successCount = 0;
await this.attachOmsWaybillAppKeys(items);
// 按 appKey 分组后再按 100 切分:不同 OMS 应用/仓库不能混在同一批
const appKeyGroupMap = new Map();
for (const item of items) {
const groupKey = String(item.app_key || '').trim();
if (!appKeyGroupMap.has(groupKey)) {
appKeyGroupMap.set(groupKey, []);
}
appKeyGroupMap.get(groupKey).push(item);
}
const batches = [];
for (const [ groupAppKey, groupItems ] of appKeyGroupMap.entries()) {
for (let offset = 0; offset < groupItems.length; offset += OMS_WAYBILL_MAX_BATCH_SIZE) {
batches.push({
appKey: groupAppKey,
orders: groupItems.slice(offset, offset + OMS_WAYBILL_MAX_BATCH_SIZE),
});
}
}
for (const { appKey, orders: batch } of batches) {
if (!appKey) {
for (const item of batch) {
failedMessages.push(
`${item.delivery_order_code || item.order_id}: 订单缺少来源应用 appKey,且货主 ${item.store_id} 仓库 ${item.warehouse_id} 未配置可用的 OpenAPI 应用`
);
}
continue;
}
const warehouseId = Number(batch[0].warehouse_id) || warehouseIdHint;
if (!callbackService || typeof callbackService.sendByAppKey !== 'function') {
throw new Error('OpenAPI 回调服务不可用,无法回 OMS 取号');
}
const requestId = this.buildOmsWaybillRequestId(warehouseId, batch);
const callbackRequest = {
orders: batch.map(item => ({
deliveryOrderCode: item.delivery_order_code,
expressCode: item.express_code,
// 包裹序号(0 基):不传时 OMS 按单号尾部 _N 推导,主单子单会撞成同一个包裹
packageIndex: Math.max((Number(item.business_key) || 1) - 1, 0),
})),
request_id: requestId,
};
const callbackResult = await callbackService.sendByAppKey({
appKey,
event: OMS_WAYBILL_EVENT,
request: callbackRequest,
});
// 无论成功失败都缓存请求/返回报文:OMS 返回格式是与 OMS 对齐的唯一依据
await this.cacheOmsWaybillPayload({
request_id: requestId,
app_key: appKey,
warehouse_id: warehouseId,
store_id: Number(batch[0].store_id) || storeIdHint,
order_count: batch.length,
delivery_order_codes: batch.map(item => item.delivery_order_code).filter(Boolean),
transport: {
success: Boolean(callbackResult && callbackResult.success),
retry_count: Number(callbackResult && callbackResult.retryCount) || 0,
error: callbackResult && callbackResult.error ? String(callbackResult.error) : null,
},
request: callbackRequest,
response: callbackResult ? callbackResult.response : null,
});
if (!callbackResult || callbackResult.success !== true) {
const transportError = new Error(
`OMS 取号请求失败: ${callbackResult && callbackResult.error ? callbackResult.error : '未知错误'}`
);
transportError.retryable = true;
throw transportError;
}
const responseBody = callbackResult.response && typeof callbackResult.response === 'object'
? callbackResult.response
: {};
const responseCode = Number(responseBody.code) || 0;
const responseFlag = String(responseBody.flag || '').trim().toLowerCase();
if (responseFlag !== 'success' || responseCode !== 1) {
const responseMessage = String(responseBody.message || 'OMS 取号返回失败').trim();
const businessError = new Error(`OMS 取号返回失败(code=${responseCode}): ${responseMessage}`);
businessError.retryable = responseCode === 409 || responseCode >= 500;
throw businessError;
}
const responseResults = normalizeArray(responseBody.data && responseBody.data.results);
if (responseResults.length !== batch.length) {
const countError = new Error(
`OMS 取号返回数量异常: 请求 ${batch.length} 条,返回 ${responseResults.length} 条`
);
countError.retryable = true;
throw countError;
}
for (let index = 0; index < batch.length; index++) {
const item = batch[index];
const row = responseResults[index] || {};
const isSuccess = row.success === true;
const waybillCode = String(row.waybill_code || '').trim();
const rowMessage = String(row.message || '').trim();
aggregatedResults.push({
delivery_order_code: item.delivery_order_code,
success: isSuccess,
message: rowMessage || (isSuccess ? 'ok' : 'OMS 未返回失败原因'),
waybill_code: waybillCode,
});
if (!isSuccess) {
failedMessages.push(`${item.delivery_order_code || item.order_id}: ${rowMessage || '取号失败'}`);
if (this.isRetryableOmsWaybillMessage(rowMessage)) {
retryable = true;
}
continue;
}
if (!waybillCode) {
failedMessages.push(`${item.delivery_order_code || item.order_id}: OMS 返回成功但运单号为空`);
retryable = true;
continue;
}
// 回显的包裹序号必须与请求一致,否则运单号可能被落到错误的包裹行
const expectedPackageIndex = Math.max((Number(item.business_key) || 1) - 1, 0);
const responsePackageIndex = Number(row.package_index);
if (typeof row.package_index !== 'undefined'
&& row.package_index !== null
&& row.package_index !== ''
&& Number.isInteger(responsePackageIndex)
&& responsePackageIndex !== expectedPackageIndex) {
failedMessages.push(
`${item.delivery_order_code || item.order_id}: OMS 返回包裹序号不一致(期望 ${expectedPackageIndex},返回 ${responsePackageIndex})`
);
retryable = true;
continue;
}
const expressCode = String(row.express_code || item.express_code || '').trim().toUpperCase();
const expressName = (ExpressList.find(entry => entry.code === expressCode) || {}).name || '';
// 平台码先归一为打印平台码再落库:item.platform_code 已在入口归一,
// OMS 回传的 platform_code 同样要过一遍映射,禁止落 'oms' 或来源平台码。
const responsePlatformCode = this.resolveWaybillPrintPlatformCode(row.platform_code, printPlatformCodeMap);
const platformCode = String(item.platform_code || responsePlatformCode || '').trim().toUpperCase();
// 打印定位字段:print_history_id 用于打印前回 OMS 换新 params,
// cai_niao_auth_info_id 用于打印时按店铺(授权网点)分组,一组只换一次 params
const printHistoryId = String(
row.print_history_id
|| (Array.isArray(row.print_history_ids) && row.print_history_ids[0] && row.print_history_ids[0].id)
|| ''
).trim();
const caiNiaoAuthInfoId = Number(row.cai_niao_auth_info_id) || 0;
// 面单打印数据与签名:OMS 原样透传,打印时必须原样下发(不要解码 base64/URL 编码);
// 上游未返回的报文字段不写库,避免把已有有效值冲成空。
const orderExpressValues = this.dropEmptyOrderExpressFields({
waybill_code: waybillCode,
status: 1,
retry_count: 0,
create_at: new Date(),
delivery_order_code: item.delivery_order_code || null,
source_order_codes: item.source_order_codes || null,
store_id: item.store_id || null,
logistics_code: expressCode,
logistics_name: expressName,
printinfo: String(row.printinfo || '') || null,
signature: String(row.signature || '') || null,
// 快手口径的加密密钥由 encryptprintinfo 承载;OMS 新版另给 key 字段,作为兜底
encryptprintinfo: String(
row.encryptprintinfo
|| (platformCode === 'KS' ? row.key : '')
|| ''
) || null,
ver: String(row.ver || '') || null,
});
if (platformCode) {
orderExpressValues.platform_code = platformCode;
}
if (printHistoryId) {
orderExpressValues.print_history_id = printHistoryId;
}
if (caiNiaoAuthInfoId > 0) {
orderExpressValues.cai_niao_auth_info_id = caiNiaoAuthInfoId;
}
// 菜鸟(淘宝)打印只认 printinfo 整包:OMS 恒回空串、把密文拆成平铺字段,
// 这里按菜鸟规范回拼,保证与菠萝派取号落库结构一致
const omsCainiaoPrintinfo = this.buildOmsCainiaoPrintinfo(platformCode, orderExpressValues);
if (omsCainiaoPrintinfo) {
orderExpressValues.printinfo = omsCainiaoPrintinfo;
}
successCount += 1;
successItems.push(item);
successUpdates.push({
warehouse_id: item.warehouse_id || warehouseId,
order_id: item.order_id,
business_key: item.business_key,
waybill_code: waybillCode,
orderExpressValues,
orderDeliveryValues: {
post_status: 'fin',
order_flag: '',
},
});
}
}
if (successUpdates.length > 0) {
const successWarehouseId = Number(successUpdates[0].warehouse_id) || warehouseIdHint;
await this.ensureOmsWaybillOrderExpressRows(successItems, successWarehouseId);
await this.persistWaybillSuccessUpdates(successUpdates, rawOrders);
}
this.ctx.logger.info('[ExpressPlatformService.oms] 回 OMS 取号完成', {
warehouseId: warehouseIdHint,
storeId: storeIdHint,
total: items.length,
success: successCount,
failed: failedMessages.length,
retryable,
durationMs: Date.now() - startedAt,
firstFailure: failedMessages[0] || '',
});
if (failedMessages.length > 0) {
const failureError = new Error(failedMessages.join('; '));
failureError.retryable = retryable;
throw failureError;
}
return {
flag: 'success',
code: 0,
message: `回 OMS 取号成功 ${successCount} 单`,
data: {
total: items.length,
success: successCount,
failed: 0,
results: aggregatedResults,
},
};
}
}
// 静态挂载 Uint64 工具:供回包解析(SPH object_Id 反解)等场景复用
ExpressPlatformService.toUint64 = toUint64;
ExpressPlatformService.fromUint64 = fromUint64;
module.exports = ExpressPlatformService;