WMS_MAIN/app/service/systems/express_platform.js
liufumingren 5ce689d771 1
Co-authored-by: Copilot <copilot@github.com>
2026-04-30 19:20:31 +08:00

581 lines
24 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 {
/**
* 菠萝派数据处理接口。
*
* @param {Object} [data={}] 平台业务入参。
* @return {Promise<never>} 当前暂未实现,直接抛出异常。
*/
async polyapi(data = {}) {
const { matchedPlatform, listByWarehousePlatformCode, orders } = data;
const ExpressList = await this.service.systems.express.loadExpressList();
console.log('matchedPlatform', JSON.stringify(matchedPlatform));
console.log('接收到菠萝派快递接口入参:', JSON.stringify(listByWarehousePlatformCode));
console.log('接收到菠萝派平台数据处理请求,入参:', JSON.stringify(orders));
console.log('ExpressList', JSON.stringify(ExpressList));
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) {
const allocatedWaybillRows = await orderExpressModel.findAll({
attributes: [ 'order_id', 'business_key', 'waybill_code' ],
where: {
order_id: {
[Op.in]: orderIdList,
},
},
order: [[ 'id', 'ASC' ]],
raw: true,
});
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 = {
};
const Dictionary_result = await this.service.systems.poloApi.request('Differ.JH.LogisticsPlatFeatures', Dictionary_bizcontent, matchedPlatform, listByWarehousePlatformCode.token);
console.log('==================\n菠萝派平台字典接口返回结果', JSON.stringify(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,
};
// 调用菠萝派平台接口进行数据处理
console.log('==================\n业务数据', JSON.stringify(order_bizcontent), '\n=========================\n');
const result = await this.service.systems.poloApi.request('Differ.JH.Logistics.PostOrder', order_bizcontent, matchedPlatform, listByWarehousePlatformCode.token);
console.log('==================\n菠萝派平台接口返回结果', JSON.stringify(result));
if (result && result.code !== '10000') {
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':
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) {
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,
});
}
}
});
for (const item of successUpdates) {
const warehouseId = Number(item.warehouse_id) || 0;
const orderId = Number(item.order_id) || 0;
if (!warehouseId || !orderId) {
continue;
}
await this.service.systems.operationLog.createOperationLog({
businessType: 'order',
businessId: `${orderId}`,
operationCode: 'WAYBILL',
operatorId: this.ctx.user ? this.ctx.user.id : 'system',
operatorName: this.ctx.user ? this.ctx.user.employees_name : '系统',
externalLogType: 'API',
operator: {
id: this.ctx.user ? this.ctx.user.employees_id : '0',
name: this.ctx.user ? this.ctx.user.employees_name : '系统',
},
extras: {
message: `订单${orderId}获取快递单成功,单号:${item.waybill_code}`,
warehouseId,
},
});
}
}
}
return {
flag: true,
code: 0,
message: '菠萝派平台数据处理成功',
data: result,
};
// throw new Error('菠萝派平台接口未实现');
}
/**
* 菜鸟数据处理接口。
*
* @param {Object} [data={}] 平台业务入参。
* @return {Promise<never>} 当前暂未实现,直接抛出异常。
*/
async cainiao(data = {}) {
void data;
console.log('接收到菜鸟平台数据处理请求,入参:', JSON.stringify(data));
throw new Error('菜鸟平台接口未实现');
}
/**
* 拼多多数据处理接口。
*
* @param {Object} [data={}] 平台业务入参。
* @return {Promise<never>} 当前暂未实现,直接抛出异常。
*/
async pdd(data = {}) {
void data;
console.log('接收到拼多多平台数据处理请求,入参:', JSON.stringify(data));
throw new Error('拼多多平台接口未实现');
}
}
module.exports = ExpressPlatformService;