WMS_MAIN/app/service/systems/express_platform.js
liufumingren 02b3a5e813 fix(order): 订单同步/运单/库位分配防御性修复
- express: 运单查询补充 pay_no/from_key 字段;step 更新增加 status!=cancel 过滤
- order_async: 同步分发前过滤 sync_status=fin 的已完成订单;修复 Op.ne 引用缺失;强制 SELECT FOR UPDATE 重读;多处更新增加 status!=cancel 守卫
- order_storage_allocation: SN/快递分配失败回写增加 status!=cancel 守卫
- methods: allocateExpressCode 文档更新为异步接口说明
2026-08-02 00:38:34 +08:00

2684 lines
110 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 DEFAULT_PDD_ROUTER_URL = 'https://gw-api.pinduoduo.com/api/router';
const DEFAULT_TB_ROUTER_URL = 'https://eco.taobao.com/router/rest';
/**
* 将任意值标准化为数组。
*
* @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';
/**
* 快递平台服务类。
*
* 当前仅保留平台方法出口,后续接入真实平台实现时再补充具体调用逻辑。
* 这里的 `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 : '',
});
// 清理异常不抛给上游,避免干扰主流程
}
}
/**
* 从 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;
}
/**
* 菠萝派数据处理接口。
*
* @param {Object} [data={}] 平台业务入参。
* @return {Promise<never>} 当前暂未实现,直接抛出异常。
*/
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),
});
const allocatedWaybillRows = await orderExpressModel.findAll({
attributes: [ 'order_id', 'business_key', 'waybill_code' ],
where: {
order_id: {
[Op.in]: orderIdList,
},
},
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}`);
}
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 playload = {
object_Id: `${order.warehouse_id}_${order.id}_${order_tmp.business_key}`, // 菠萝派平台要求订单唯一标识必须为字符串
orderno: `${order.warehouse_id}_${order.id}_${order_tmp.business_key}`, // 菠萝派平台要求订单号必须为字符串
plattradeno: listByWarehousePlatformCode.platform_code === 'DY' && order.from_key == 23060081? order.pay_no : order.source_order_codes || order.delivery_order_code || '',
ismultiplepieces: order.package_count > 1 ? 1 : 0,
logisticno: allocatedWaybillMap.get(`${Number(order.id) || 0}:${Number(order_tmp.business_key) || 0}`) || '',
logistictype: order.logistics_code || '',
providercode: expressListItem[listByWarehousePlatformCode.platform_code] || order.logistics_code || '',
numpackage: order.package_count || 1,
businessType: listByWarehousePlatformCode.product_type,
businessplat: order.sys_platform_code === 'KS' ? order.sys_platform_code : 'OTHERS',
paymode: listByWarehousePlatformCode.paymode ?? 1,
ordertype: listByWarehousePlatformCode.ordertype ?? 'JH_Normal',
ProviderID: listByWarehousePlatformCode.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,
ProductType: listByWarehousePlatformCode.product_type || '',
Sipshopid: listByWarehousePlatformCode.platform_shop_id || '',
oaid: order.oaid || '',
sys_express_code: listByWarehousePlatformCode.sys_express_code || '',
platform_code: listByWarehousePlatformCode.platform_code || '',
cpcode: expressListItem[listByWarehousePlatformCode.platform_code] || '',
logisticsproductname: 'JH_02',
dmssorting: 0,
brandno: listByWarehousePlatformCode.brandno || null,
needencrypt: 1,
ordersource: matchedPlatform.ordersource || '',
inputsite: listByWarehousePlatformCode.site_code || '',
sitecode: listByWarehousePlatformCode.site_code || '',
shipperno: listByWarehousePlatformCode.shipperno || '',
customercode: listByWarehousePlatformCode.shipperno || listByWarehousePlatformCode.client_id || '',
sender: {
company: listByWarehousePlatformCode.shop_name || '',
name: listByWarehousePlatformCode.sender_name || '',
phone: listByWarehousePlatformCode.sender_tel || '',
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: item.item_name || '商品',
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 (Number(matchedPlatform.platid) === 673) {
playload.BizVersion = '2';
playload.brandno = listByWarehousePlatformCode.brandno || '';
}
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,
expresstype: ProductType,
logistictype,
providercode: providercode || cpcode || logistictype || '',
numpackage,
businessplat,
mainsubpaymode: '1',
ordertype,
businessType: businessType || ordertype || 'JH_Normal',
codpaymoney,
ProviderID,
cpcode,
logisticsproductname,
needencrypt,
ordersource,
shipperno,
sitecode,
customername,
goods,
oaid,
customercode: 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 = order.source_order_codes.split(',')[0];
if (!order.extend_props.ewaybill_order_code) {
throw new Error('订单数据错误,参数不全缺失extend_props.ewaybill_order_code,请复制次信息给ERP方反馈');
}
playload.oaid = order.extend_props.ewaybill_order_code||order.oaid||undefined;
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);
if (result && result.code !== '10000') {
const postOrderErrorMessage = String(
result.submessage || result.message || '菠萝派平台接口调用失败'
).trim();
this.ctx.logger.error('[expressPlatform.polyapi] PolyAPI 返回业务失败', {
traceId,
code: result.code,
message: postOrderErrorMessage,
response: result,
});
// 清洗本批次全部订单资源,然后抛出
const allFailedOrders = this.buildFailedOrderCleanupList(orders);
await this.cleanupFailedWaybillOrders(allFailedOrders, `PostOrder业务失败: ${postOrderErrorMessage}`);
throw new Error(`菠萝派平台接口返回错误信息:${postOrderErrorMessage},原始错误信息: \`\`\`${JSON.stringify(result)}\`\`\``);
} else if (result && result.code === '10000') {
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, order_id, business_key ] = String(item.orderno || '').split('_');
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, order_id, business_key ] = String(item.orderno || '').split('_');
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 batchPrintSipshopid = String(listByWarehousePlatformCode.platform_shop_id || '0');
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, order_id, business_key ] = objectId.split('_');
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, order_id, business_key ] = String(item.orderno || '').split('_');
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, order_id, business_key ] = objectIdParts;
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, order_id, business_key ] = String(item.orderno || '').split('_');
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, order_id, business_key ] = String(item.orderno || '').split('_');
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 => {
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,
});
}
}
if (storeWarehouseModel
&& typeof storeWarehouseModel.findAll === 'function'
&& settlementRelationMap.size > 0) {
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,
});
}
}
});
} 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) {
// 异步调用,不阻塞主流程
this.ctx.service.systemMethods.order.pendingOrder.syncOrderIds({
orderIds: syncedOrderIds,
}).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)
: [];
const recipientMobile = orderDelivery && (orderDelivery.mobile || orderDelivery.tel) || '';
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: '物品',
},
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: orderDelivery && orderDelivery.oaid || '',
tid: sourceOrderCodes[0] || '',
},
oaid: orderDelivery && orderDelivery.oaid || '',
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(),
},
};
console.log('cainiaoPayload', JSON.stringify(cainiaoPayload));
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,
},
});
console.log('菜鸟取号返回数据', JSON.stringify(response));
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) {
// 异步调用,不阻塞主流程
this.ctx.service.systemMethods.order.pendingOrder.syncOrderIds({
orderIds: syncedOrderIds,
}).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;
}
/**
* 回写成功获取的面单结果,并扣减打印余量与写入操作日志。
*
* @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 => {
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(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,
});
}
}
if (storeWarehouseModel
&& typeof storeWarehouseModel.findAll === 'function'
&& settlementRelationMap.size > 0) {
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,
});
}
}
});
}
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 && order_tmp.order_delivery.source_order_codes ? order_tmp.order_delivery.source_order_codes.split(',') : [ order_tmp.order_delivery && order_tmp.order_delivery.delivery_order_code || '' ],
},
package_info: {
items: (order_tmp.order_delivery && order_tmp.order_delivery.orderItems || []).map(item => ({
name: item.item_name || '商品',
count: item.plan_qty,
})) || [],
},
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));
// 这里写一个调用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,
});
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 => {
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,
});
}
}
if (storeWarehouseModel
&& typeof storeWarehouseModel.findAll === 'function'
&& settlementRelationMap.size > 0) {
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,
});
}
}
});
}
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) {
// 异步调用,不阻塞主流程
this.ctx.service.systemMethods.order.pendingOrder.syncOrderIds({
orderIds: syncedOrderIds,
}).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;
}
}
}
module.exports = ExpressPlatformService;