764 lines
31 KiB
JavaScript
764 lines
31 KiB
JavaScript
'use strict';
|
||
|
||
const MainService = require('../main');
|
||
|
||
/**
|
||
* 快递平台服务类。
|
||
*
|
||
* 当前仅保留平台方法出口,后续接入真实平台实现时再补充具体调用逻辑。
|
||
* 这里的 `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,
|
||
};
|
||
}
|
||
|
||
/**
|
||
* 构建快递平台链路追踪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)}`;
|
||
}
|
||
|
||
/**
|
||
* 菠萝派数据处理接口。
|
||
*
|
||
* @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 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,
|
||
});
|
||
|
||
const order_bizcontent = {
|
||
orders: orders.map(order_tmp => {
|
||
const order = order_tmp.order_delivery;
|
||
return {
|
||
orderno: `${order.warehouse_id}_${order.id}_${order_tmp.business_key}`, // 菠萝派平台要求订单号必须为字符串
|
||
plattradeno: 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 || '',
|
||
numpackage: order.package_count || 1,
|
||
businesstype: 'JH_Normal',
|
||
|
||
businessplat: order.sys_platform_code === 'KS' ? order.sys_platform_code : 'OTHERS',
|
||
paymode: listByWarehousePlatformCode.paymode ?? 1,
|
||
ordertype: listByWarehousePlatformCode.ordertype ?? 'JH_Normal',
|
||
codpaymoney: order.ar_amount ?? null,
|
||
packagemoney: order.item_amount ?? null,
|
||
weight: Number(order.items_weight) || 0,
|
||
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.shop_id || '',
|
||
sys_express_code: listByWarehousePlatformCode.sys_express_code || '',
|
||
platform_code: listByWarehousePlatformCode.platform_code || '',
|
||
cpcode: ExpressList.find(item => item.code === listByWarehousePlatformCode.sys_express_code)[listByWarehousePlatformCode.platform_code] || '',
|
||
logisticsproductname: 'JH_02',
|
||
dmssorting: 0,
|
||
needencrypt: 1,
|
||
ordersource: matchedPlatform.ordersource || '',
|
||
inputsite: listByWarehousePlatformCode.site_code || '',
|
||
sitecode: listByWarehousePlatformCode.site_code || '',
|
||
shipperno: listByWarehousePlatformCode.client_id || '',
|
||
sender: {
|
||
company: listByWarehousePlatformCode.shop_name || '',
|
||
name: listByWarehousePlatformCode.sender_name || '',
|
||
phone: listByWarehousePlatformCode.sender_tel || '',
|
||
mobile: 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.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: matchedPlatform.template_url || '',
|
||
labelformat: listByWarehousePlatformCode.labelformat || '',
|
||
extraInfo: ExpressList.find(item => item.code === listByWarehousePlatformCode.sys_express_code)?.polyapi_extra_info || '',
|
||
};
|
||
}),
|
||
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: result,
|
||
});
|
||
if (result && result.code !== '10000') {
|
||
this.ctx.logger.error('[expressPlatform.polyapi] PolyAPI 返回业务失败', {
|
||
traceId,
|
||
code: result.code,
|
||
message: result.submessage,
|
||
response: result,
|
||
});
|
||
throw new Error(`菠萝派平台接口返回错误信息:${result.submessage},原始错误信息: \`\`\`${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,
|
||
create_at: new Date(),
|
||
logistics_code: listByWarehousePlatformCode.logistics_code || '',
|
||
logistics_interface_id: listByWarehousePlatformCode.id || null,
|
||
logistics_name: listByWarehousePlatformCode.logistics_name || '',
|
||
logistics_interface_name: listByWarehousePlatformCode.name || '',
|
||
platform_code: listByWarehousePlatformCode.platform_code || '',
|
||
status: 1,
|
||
retry_count: 0,
|
||
},
|
||
orderDeliveryValues: {
|
||
post_status: 'fin',
|
||
order_flag: '',
|
||
},
|
||
};
|
||
});
|
||
break;
|
||
case 'DYXD':
|
||
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,
|
||
create_at: new Date(),
|
||
logistics_code: listByWarehousePlatformCode.logistics_code || '',
|
||
logistics_interface_id: listByWarehousePlatformCode.id || null,
|
||
logistics_name: listByWarehousePlatformCode.logistics_name || '',
|
||
logistics_interface_name: listByWarehousePlatformCode.name || '',
|
||
platform_code: listByWarehousePlatformCode.platform_code || '',
|
||
status: 1,
|
||
retry_count: 0,
|
||
},
|
||
orderDeliveryValues: {
|
||
post_status: 'fin',
|
||
order_flag: '',
|
||
},
|
||
};
|
||
});
|
||
break;
|
||
case 'JD':
|
||
case 'XHS':
|
||
case 'SPH':
|
||
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,
|
||
create_at: new Date(),
|
||
logistics_code: listByWarehousePlatformCode.logistics_code || '',
|
||
logistics_interface_id: listByWarehousePlatformCode.id || null,
|
||
logistics_name: listByWarehousePlatformCode.logistics_name || '',
|
||
logistics_interface_name: listByWarehousePlatformCode.name || '',
|
||
platform_code: listByWarehousePlatformCode.platform_code || '',
|
||
status: 1,
|
||
retry_count: 0,
|
||
},
|
||
orderDeliveryValues: {
|
||
post_status: 'fin',
|
||
order_flag: '',
|
||
},
|
||
};
|
||
});
|
||
break;
|
||
default:
|
||
break;
|
||
}
|
||
|
||
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,
|
||
});
|
||
}
|
||
}
|
||
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<never>} 当前暂未实现,直接抛出异常。
|
||
*/
|
||
async cainiao(data = {}) {
|
||
void data;
|
||
throw new Error('菜鸟平台接口未实现');
|
||
}
|
||
|
||
/**
|
||
* 拼多多数据处理接口。
|
||
*
|
||
* @param {Object} [data={}] 平台业务入参。
|
||
* @return {Promise<never>} 当前暂未实现,直接抛出异常。
|
||
*/
|
||
async pdd(data = {}) {
|
||
void data;
|
||
throw new Error('拼多多平台接口未实现');
|
||
}
|
||
}
|
||
|
||
module.exports = ExpressPlatformService;
|