- 外部打单平台快递接口:按账号同步平台模板、绑定快递编码、查看模板明细;打开列表只读库,仅「从平台同步数据」时拉取 - 系统管理新增自定义快递编码字典,订单改快递 / 物流下拉合并系统与自定义编码,推送奇门沿用订单上的编码 - 新增 OpenAPI deliveryorder.getwaybill:WMS 批量回取号(单次≤100、并发4、逐单结果),快递编码只取 WMS 报文,取消/作废/归档返回失败,已取号直接复用 - 新增 openapi_request_idempotency 请求级幂等:request_id 回放、报文摘要校验、30 分钟 stale 接管、7 天定时清理 - 外部打单平台订单按平台 fetch_waybill_no 下发 need_oms_waybill,推送时实时判定并回写单据 - 店铺、打单账号平台配置与「平台+编码→模板」绑定走 Redis 缓存,绑定/账号变更主动失效,避免批量推送与取号逐单查库 Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
372 lines
13 KiB
JavaScript
372 lines
13 KiB
JavaScript
'use strict';
|
||
|
||
const orderCallback = require('./orderCallback');
|
||
const { ORDER_STATUS } = require('./orderStatus');
|
||
const { getShopBasic } = require('./externalPrintConfig');
|
||
|
||
/** 单号候选字段(与 deliveryorder.confirm 同口径,支持嵌套) */
|
||
const CODE_PATHS = [
|
||
'deliveryOrderCode',
|
||
'deliveryOrder.deliveryOrderCode',
|
||
'outBizCode',
|
||
'deliveryOrder.outBizCode',
|
||
'orderCode',
|
||
'order.orderCode',
|
||
];
|
||
|
||
/** WMS 传入的快递编码候选字段(不回读订单上的 logistics_code) */
|
||
const EXPRESS_CODE_PATHS = [
|
||
'expressCode',
|
||
'express_code',
|
||
'logisticsCode',
|
||
'logistics_code',
|
||
'express.code',
|
||
];
|
||
|
||
/** 平台返回的运单号候选字段 */
|
||
const WAYBILL_KEYS = [
|
||
'waybillCode',
|
||
'waybill_code',
|
||
'mailNo',
|
||
'mail_no',
|
||
'logisticCode',
|
||
'logistic_code',
|
||
'LogisticCode',
|
||
'WaybillCode',
|
||
'expressCode',
|
||
'express_code',
|
||
];
|
||
|
||
/** 单次批量上限(避免一次回调过大、平台侧限流) */
|
||
const MAX_BATCH = 100;
|
||
|
||
/** 并发处理数(平台取号是网络请求,适度并发缩短总耗时) */
|
||
const CONCURRENCY = 4;
|
||
|
||
/** 取消 / 作废 / 归档等不可取号的状态 */
|
||
const BLOCKED_STATUS_LABELS = {
|
||
[ORDER_STATUS.CANCELED]: '订单已取消,取号失败',
|
||
[ORDER_STATUS.VOID]: '订单已作废,取号失败',
|
||
[ORDER_STATUS.HISTORY]: '订单已归档,取号失败',
|
||
};
|
||
|
||
/**
|
||
* 兼容 `{ request: {...} }` / `{ data: {...} }` 包装(与 orderCallback.unwrapPayload 同口径)
|
||
* @param {Object} body 原始报文
|
||
* @return {Object} 归一化报文
|
||
*/
|
||
function unwrapBody(body) {
|
||
const source = body && typeof body === 'object' && !Array.isArray(body) ? body : {};
|
||
const inner = [ source.request, source.data ].find(v => v && typeof v === 'object' && !Array.isArray(v));
|
||
return inner ? { ...source, ...inner } : source;
|
||
}
|
||
|
||
/**
|
||
* 从报文中提取批量订单项
|
||
*
|
||
* 兼容:`orders: []`、`deliveryOrders: []`、`deliveryOrders.deliveryOrder: []`、
|
||
* `list: []`,以及只传单个对象的场景。
|
||
* @param {Object} body 归一化后的报文
|
||
* @return {Array} 订单项数组
|
||
*/
|
||
function extractItems(body) {
|
||
const source = body || {};
|
||
const candidates = [ source.orders, source.deliveryOrders, source.list, source.items ];
|
||
for (const candidate of candidates) {
|
||
if (Array.isArray(candidate)) return candidate;
|
||
if (candidate && typeof candidate === 'object') {
|
||
for (const key of [ 'orders', 'deliveryOrder', 'list', 'items' ]) {
|
||
if (Array.isArray(candidate[key])) return candidate[key];
|
||
}
|
||
}
|
||
}
|
||
|
||
// 单对象写法:本身就是一个订单项
|
||
if (source.deliveryOrderCode || source.outBizCode || source.orderCode) return [ source ];
|
||
if (source.deliveryOrder && typeof source.deliveryOrder === 'object' && !Array.isArray(source.deliveryOrder)) {
|
||
return [ source ];
|
||
}
|
||
return [];
|
||
}
|
||
|
||
/**
|
||
* 取 WMS 传入的快递编码(只从报文取,不读订单)
|
||
* @param {Object} item 订单项
|
||
* @return {string} 快递编码
|
||
*/
|
||
function pickExpressCode(item) {
|
||
return orderCallback.pickFirst(item || {}, EXPRESS_CODE_PATHS);
|
||
}
|
||
|
||
/**
|
||
* 递归提取平台返回的运单号(兼容字符串 / 数组 / 常见字段名)
|
||
* @param {*} value 平台返回值
|
||
* @param {Array<string>} out 收集结果
|
||
* @return {void}
|
||
*/
|
||
function collectWaybills(value, out) {
|
||
if (value === undefined || value === null) return;
|
||
if (typeof value === 'string') {
|
||
const text = value.trim();
|
||
if (text) out.push(text);
|
||
return;
|
||
}
|
||
if (Array.isArray(value)) {
|
||
for (const item of value) collectWaybills(item, out);
|
||
return;
|
||
}
|
||
if (typeof value !== 'object') return;
|
||
|
||
for (const key of WAYBILL_KEYS) {
|
||
const hit = value[key];
|
||
if (typeof hit === 'string' && hit.trim()) {
|
||
out.push(hit.trim());
|
||
return;
|
||
}
|
||
}
|
||
for (const key of [ 'waybills', 'waybillCodes', 'expressCodes', 'packages', 'data' ]) {
|
||
if (value[key] !== undefined) collectWaybills(value[key], out);
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 归一化平台取号结果
|
||
* @param {*} result 平台返回
|
||
* @return {{waybill_code: string, waybill_codes: Array<string>}} 运单号
|
||
*/
|
||
function normalizeWaybill(result) {
|
||
const list = [];
|
||
collectWaybills(result, list);
|
||
const unique = [ ...new Set(list) ];
|
||
return { waybill_code: unique[0] || '', waybill_codes: unique };
|
||
}
|
||
|
||
/**
|
||
* 有限并发执行,保持结果顺序
|
||
* @param {Array} items 待处理项
|
||
* @param {number} limit 并发数
|
||
* @param {Function} worker 处理函数
|
||
* @return {Promise<Array>} 结果数组
|
||
*/
|
||
async function mapLimit(items, limit, worker) {
|
||
const results = new Array(items.length);
|
||
let cursor = 0;
|
||
const runners = Array.from({ length: Math.min(limit, items.length) }, async () => {
|
||
while (cursor < items.length) {
|
||
const index = cursor;
|
||
cursor += 1;
|
||
results[index] = await worker(items[index], index);
|
||
}
|
||
});
|
||
await Promise.all(runners);
|
||
return results;
|
||
}
|
||
|
||
/**
|
||
* 失败结果
|
||
* @param {string} code 单号
|
||
* @param {string} message 失败原因
|
||
* @return {Object} 结果项
|
||
*/
|
||
function fail(code, message) {
|
||
return { delivery_order_code: code || '', success: false, message };
|
||
}
|
||
|
||
/**
|
||
* 订单已有运单号时的结果(重试 / 不同 request_id 重复取号都直接复用,避免重复请求平台)
|
||
* @param {string} code 单号
|
||
* @param {string} expressCode WMS 传入的快递编码
|
||
* @param {Object} order 订单
|
||
* @return {Object} 成功结果
|
||
*/
|
||
function existingWaybillResult(code, expressCode, order) {
|
||
return {
|
||
delivery_order_code: code,
|
||
success: true,
|
||
message: '已取号,返回已有运单号',
|
||
express_code: expressCode,
|
||
waybill_code: order.express_code,
|
||
waybill_codes: Array.isArray(order.express_codes) ? order.express_codes : [ order.express_code ],
|
||
};
|
||
}
|
||
|
||
/**
|
||
* 读取完整打单账号实例(含 cookie/token,平台客户端直接使用)
|
||
* 同一批内按账号去重,避免逐单查库;缓存 promise 以合并并发请求
|
||
* @param {Object} ctx egg context
|
||
* @param {Object} memo 批内缓存
|
||
* @param {Number} accountId 外部打单账号ID
|
||
* @param {Number} principalId 主体ID
|
||
* @return {Promise<Object|null>} 账号实例,不存在或跨主体为 null
|
||
*/
|
||
async function loadAccountModel(ctx, memo, accountId, principalId) {
|
||
const key = `account:${principalId}:${accountId}`;
|
||
if (memo.has(key)) return await memo.get(key);
|
||
|
||
const promise = ctx.model.ExternalPrintAccount.findOne({
|
||
where: { id: accountId, principal_id: principalId },
|
||
include: [
|
||
{
|
||
model: ctx.model.ExternalPrintPlatform,
|
||
as: 'platform',
|
||
attributes: [ 'id', 'code', 'name', 'url', 'fetch_waybill_no' ],
|
||
},
|
||
],
|
||
}).catch(err => {
|
||
memo.delete(key);
|
||
throw err;
|
||
});
|
||
memo.set(key, promise);
|
||
return await promise;
|
||
}
|
||
|
||
/**
|
||
* 处理单个订单取号
|
||
* @param {Object} ctx egg context
|
||
* @param {Object} params 参数
|
||
* @param {number} params.principalId 主体ID
|
||
* @param {number} params.warehouseId app_key 定位到的仓库ID
|
||
* @param {Object} params.item 订单项(含单号与快递编码)
|
||
* @param {Map} params.memo 批内缓存(账号实例等)
|
||
* @return {Promise<Object>} 结果项
|
||
*/
|
||
async function processItem(ctx, { principalId, warehouseId, item, memo }) {
|
||
const code = orderCallback.pickFirst(item || {}, CODE_PATHS);
|
||
if (!code) return fail('', '缺少发货单号(deliveryOrderCode / outBizCode)');
|
||
|
||
// 快递编码必须由 WMS 传入;订单上的 logistics_code 不参与取号
|
||
const expressCode = pickExpressCode(item);
|
||
if (!expressCode) return fail(code, '缺少快递编码(expressCode)');
|
||
|
||
try {
|
||
const resolved = await orderCallback.resolveDeliveryBill(ctx, { code, principalId });
|
||
const order = resolved.order;
|
||
if (!order) return fail(code, `未找到发货单:${code}`);
|
||
|
||
// 仓库隔离:历史单据可能没有 warehouse_id,仅在双方都有值时校验
|
||
if (order.warehouse_id && warehouseId && Number(order.warehouse_id) !== Number(warehouseId)) {
|
||
return fail(code, `单据 ${code} 不属于当前 app_key 对应的仓库`);
|
||
}
|
||
|
||
if (resolved.isNewModel) {
|
||
const status = resolved.index.current_status;
|
||
if (BLOCKED_STATUS_LABELS[status]) return fail(code, BLOCKED_STATUS_LABELS[status]);
|
||
// 已有运单号:直接复用(幂等),不再请求平台
|
||
if (order.express_code) return existingWaybillResult(code, expressCode, order);
|
||
if (status === ORDER_STATUS.DELIVERY) return fail(code, '订单已配送但没有运单号');
|
||
} else {
|
||
const status = Number(order.status);
|
||
if (status === 9) return fail(code, BLOCKED_STATUS_LABELS[ORDER_STATUS.CANCELED]);
|
||
if (status === 5) return fail(code, BLOCKED_STATUS_LABELS[ORDER_STATUS.VOID]);
|
||
if (order.express_code) return existingWaybillResult(code, expressCode, order);
|
||
if (status === 4) return fail(code, '订单已完成但没有运单号');
|
||
}
|
||
|
||
// 平台信息必须回读订单(订单来自哪个平台)
|
||
const platformCode = String(order.source_platform_code || '').trim();
|
||
if (!platformCode) return fail(code, '订单缺少来源平台,无法匹配快递接口');
|
||
|
||
// 打单账号:订单店铺 → 外部打单账号(跨打单平台无法取号)
|
||
// 店铺与账号平台配置走缓存,避免一批 100 单反复查同一份配置
|
||
if (!order.shop_id) return fail(code, '订单未关联店铺,无法确定打单账号');
|
||
const shop = await getShopBasic(ctx, order.shop_id, principalId);
|
||
if (!shop || Number(shop.type) !== 2 || !shop.external_print_account_id) {
|
||
return fail(code, '订单未关联外部打单账号,无法取号');
|
||
}
|
||
|
||
const account = await loadAccountModel(ctx, memo, shop.external_print_account_id, principalId);
|
||
if (!account || !account.platform) return fail(code, '外部打单账号或平台配置不存在');
|
||
|
||
// 按「账号 + 订单平台 + WMS 传入的快递编码」定位唯一模板
|
||
const template = await ctx.service.externalPrintExpressInterface.resolveByCode(
|
||
account.id,
|
||
{ platformCode, expressCode },
|
||
principalId
|
||
);
|
||
if (!template) {
|
||
return fail(code, `未找到匹配的快递接口(平台 ${platformCode},编码 ${expressCode})`);
|
||
}
|
||
|
||
const platformService = ctx.service.externalPrintOrder.createPlatformService(account);
|
||
if (!platformService.needFetchWaybillNo) {
|
||
return fail(code, `打单平台「${account.platform.name}」未开启取号`);
|
||
}
|
||
|
||
const orderPlain = order.get ? order.get({ plain: true }) : { ...order };
|
||
const fetched = await platformService.fetchWaybillNo(orderPlain, {
|
||
template: template.get ? template.get({ plain: true }) : template,
|
||
expressCode,
|
||
platformCode,
|
||
});
|
||
const waybill = normalizeWaybill(fetched);
|
||
if (!waybill.waybill_code) return fail(code, '平台未返回运单号');
|
||
|
||
// 回写运单号(不覆盖订单上的物流编码/名称)
|
||
await order.update({
|
||
express_code: waybill.waybill_code,
|
||
express_codes: waybill.waybill_codes,
|
||
});
|
||
|
||
ctx.logger.info('[waybill.get] 取号成功', { code, expressCode, platformCode, waybillCode: waybill.waybill_code });
|
||
return {
|
||
delivery_order_code: code,
|
||
success: true,
|
||
message: 'ok',
|
||
express_code: expressCode,
|
||
platform_code: platformCode,
|
||
waybill_code: waybill.waybill_code,
|
||
waybill_codes: waybill.waybill_codes,
|
||
};
|
||
} catch (err) {
|
||
ctx.logger.warn('[waybill.get] 取号失败 %s:%s', code, err.message);
|
||
return fail(code, err.message || '取号失败');
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 批量取号(method = deliveryorder.getwaybill)
|
||
*
|
||
* WMS 发起取号时携带快递编码,OMS 回读订单信息(平台 / 店铺 / 打单账号)后按
|
||
* 「账号 + 平台 + 编码」定位快递接口并调用平台取号;逐单返回成功/失败,不影响其它订单。
|
||
* 订单已取消 / 已作废 / 已归档时返回该单取号失败。
|
||
* @param {Object} ctx egg context
|
||
* @param {Object} payload 调用上下文
|
||
* @param {number} payload.principalId 主体ID
|
||
* @param {number} payload.warehouseId app_key 定位到的仓库ID
|
||
* @param {Object} payload.data 回调报文
|
||
* @return {Promise<{ok: boolean, message: string, data?: Object}>} 批量结果
|
||
*/
|
||
async function getWaybills(ctx, { principalId, warehouseId, data }) {
|
||
const body = unwrapBody(data);
|
||
const items = extractItems(body);
|
||
if (!items.length) {
|
||
return { ok: false, message: '缺少待取号订单(orders / deliveryOrders)' };
|
||
}
|
||
if (items.length > MAX_BATCH) {
|
||
return { ok: false, message: `单次最多取号 ${MAX_BATCH} 单` };
|
||
}
|
||
|
||
// 同一批内按账号缓存完整账号实例(含 cookie/token,供平台客户端直接使用),
|
||
// 一次批量回调通常只涉及 1 个打单账号,避免逐单重复查库
|
||
const memo = new Map();
|
||
const results = await mapLimit(items, CONCURRENCY, item => processItem(ctx, { principalId, warehouseId, item, memo }));
|
||
const success = results.filter(row => row.success).length;
|
||
return {
|
||
ok: true,
|
||
message: 'ok',
|
||
data: {
|
||
total: results.length,
|
||
success,
|
||
failed: results.length - success,
|
||
results,
|
||
},
|
||
};
|
||
}
|
||
|
||
module.exports = {
|
||
getWaybills,
|
||
extractItems,
|
||
pickExpressCode,
|
||
normalizeWaybill,
|
||
};
|