- dgj: 抽取 contents[0].key;快手单 printinfo 取 encryptedData、encryptprintinfo 取逐单密钥(对齐菠萝派口径) - waybillGet: deliveryorder.getwaybill 响应新增 key 字段并透传给 WMS - 探测脚本输出 encryptprintinfo/key 长度;补充单测 - 更新 WMS-OMS 取号对接文档的快手字段说明 Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
710 lines
30 KiB
JavaScript
710 lines
30 KiB
JavaScript
'use strict';
|
||
|
||
const orderCallback = require('./orderCallback');
|
||
const { ORDER_STATUS } = require('./orderStatus');
|
||
const { getShopBasic } = require('./externalPrintConfig');
|
||
const { platformNameOf } = require('./platformCode');
|
||
|
||
/** 单号候选字段(与 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',
|
||
];
|
||
|
||
/** 包裹序号候选字段(WMS 拆单/多包裹时显式指定,0 基,优先生效) */
|
||
const PACKAGE_INDEX_PATHS = [
|
||
'packageIndex',
|
||
'package_index',
|
||
'packageNo',
|
||
'package_no',
|
||
'waybillIndex',
|
||
'waybill_index',
|
||
];
|
||
|
||
/** 包裹序号候选字段(WMS 侧的 business_key,1 基,会转成 0 基) */
|
||
const BUSINESS_KEY_PATHS = [
|
||
'businessKey',
|
||
'business_key',
|
||
];
|
||
|
||
/** 单次批量上限(避免一次回调过大、平台侧限流) */
|
||
const MAX_BATCH = 100;
|
||
|
||
/**
|
||
* 并发处理数(平台取号是网络请求,适度并发缩短总耗时)
|
||
*
|
||
* 店管家按服务商维度限流(实测 600 QPS),并发越大突发越猛、越容易被判 `isv.request-limited`;
|
||
* 单进程另有全局请求间隔(`DGJ_REQUEST_INTERVAL_MS`)兜底,这里默认压到 2。
|
||
* 可用 `WAYBILL_CONCURRENCY` 调整。
|
||
*/
|
||
const CONCURRENCY = Math.max(1, Number(process.env.WAYBILL_CONCURRENCY || 2) || 2);
|
||
|
||
/** 取消 / 作废 / 归档等不可取号的状态 */
|
||
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);
|
||
}
|
||
|
||
/**
|
||
* 从发货单号尾部取包裹/子单序号(0 基)
|
||
*
|
||
* 店管家订单的 OMS 单号形如 `dgj-<系统编号>_1`、`_2`…,尾部数字即该单在拆单后的序号(1 基)。
|
||
* 打单平台按 `<LogicOrderId>_<序号0基>` 分配运单号,所以这里统一转成 0 基再下发;
|
||
* 非店管家单号(其它平台/手工单)或没有序号时一律按第 1 个包裹(0)处理。
|
||
* @param {string} code 发货单号
|
||
* @return {number} 包裹序号(0 基)
|
||
*/
|
||
function resolvePackageIndex(code) {
|
||
const text = String(code || '').trim();
|
||
if (!/^dgj-/i.test(text)) return 0;
|
||
const matched = text.match(/_(\d+)$/);
|
||
if (!matched) return 0;
|
||
const seq = Number(matched[1]);
|
||
return Number.isFinite(seq) && seq > 0 ? seq - 1 : 0;
|
||
}
|
||
|
||
/**
|
||
* 取 WMS 报文里显式指定的包裹序号(0 基,拆单/多包裹时用)
|
||
*
|
||
* 优先读 `packageIndex`(0 基);没有时读 WMS 原生的 `businessKey`(1 基,转 0 基)。
|
||
* WMS 侧同一个 OMS 单号拆成多个包裹时,`deliveryOrderCode` 不变、只有 `business_key` 变,
|
||
* 所以必须由报文带过来,否则各包裹都会落到序号 0、拿回同一个运单号。
|
||
* @param {Object} item 订单项
|
||
* @return {number|null} 包裹序号;未指定返回 null
|
||
*/
|
||
function pickPackageIndex(item) {
|
||
const raw = orderCallback.pickFirst(item || {}, PACKAGE_INDEX_PATHS);
|
||
if (raw !== undefined && raw !== null && raw !== '') {
|
||
const value = Number(raw);
|
||
return Number.isFinite(value) && value >= 0 ? Math.floor(value) : null;
|
||
}
|
||
const businessKey = orderCallback.pickFirst(item || {}, BUSINESS_KEY_PATHS);
|
||
if (businessKey !== undefined && businessKey !== null && businessKey !== '') {
|
||
const value = Number(businessKey);
|
||
return Number.isFinite(value) && value > 0 ? Math.floor(value) - 1 : null;
|
||
}
|
||
return null;
|
||
}
|
||
|
||
/**
|
||
* 递归提取平台返回的运单号(兼容字符串 / 数组 / 常见字段名)
|
||
* @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 };
|
||
}
|
||
|
||
/**
|
||
* 把平台返回的原始错误拼成一句可读提示(回给 WMS,同时写进取号记录)
|
||
*
|
||
* 平台(店管家)失败时通常只回一个 `ErrorCode`(如 2),真实原因在 `Data.ErrorMsg` / `Data.BranchName` 里,
|
||
* WMS 侧只能看到我们给出的文案,所以这里把可读字段一并带上,便于直接定位
|
||
* (不包含任何收件人信息)。
|
||
* @param {Error|Object} err 平台异常(可带 rawResponse)
|
||
* @return {string} 失败原因
|
||
*/
|
||
function describePlatformFailure(err) {
|
||
const message = String((err && err.message) || '取号失败');
|
||
const raw = err && err.rawResponse;
|
||
if (!raw || typeof raw !== 'object') return message;
|
||
|
||
const parts = [];
|
||
const push = (label, value) => {
|
||
const text = String(value == null ? '' : value).trim();
|
||
if (!text || text === 'null' || text === 'undefined') return;
|
||
if (message.includes(text) || parts.some(item => item.endsWith(`:${text}`))) return;
|
||
parts.push(`${label}:${text}`);
|
||
};
|
||
|
||
push('平台错误码', raw.ErrorCode);
|
||
push('平台提示', raw.Message);
|
||
const data = Array.isArray(raw.Data) ? raw.Data[0] : raw.Data;
|
||
if (data && typeof data === 'object') {
|
||
push('平台说明', data.ErrorMsg || data.Message);
|
||
push('网点', data.BranchName);
|
||
}
|
||
if (!parts.length) return message;
|
||
return `${message}(${parts.join(',')})`.slice(0, 500);
|
||
}
|
||
|
||
/**
|
||
* 组装「未绑定到快递接口」的简短提示
|
||
*
|
||
* 两个分支:
|
||
* 1. 快递编码在「系统快递公司」和「自定义快递编码」里都不存在 → 提示去新增编码;
|
||
* 2. 编码存在但该账号该平台没绑定 → `平台SPH(视频号)快递STO(申通)在账号xxx下未绑定到快递接口,请到 OMS 店铺管理→外部打单平台→快递接口 绑定`
|
||
* 平台/快递优先显示中文名,查不到名称时只显示编码。
|
||
* @param {Object} ctx egg context
|
||
* @param {Object} params 参数
|
||
* @param {Object} params.account 打单账号(含 platform)
|
||
* @param {string} params.platformCode 订单来源平台编码
|
||
* @param {string} params.expressCode WMS 传入的快递编码
|
||
* @param {number} params.principalId 主体ID
|
||
* @return {Promise<string>} 提示信息
|
||
*/
|
||
async function buildTemplateMissingMessage(ctx, { account, platformCode, expressCode, principalId }) {
|
||
const platformLabel = labelWithName(platformCode, platformNameOf(platformCode));
|
||
const { name: expressName, exists: expressExists, disabled: expressDisabled } = await findExpressCode(ctx, expressCode, principalId);
|
||
const expressLabel = labelWithName(expressCode, expressName);
|
||
const accountText = account.account ? `账号${account.account}` : `账号#${account.id}`;
|
||
// WMS 侧日志/页面会截断长文案,这里把「真正原因」放最前面,操作指引放后面
|
||
const guide = 'OMS 店铺管理→外部打单平台→快递接口';
|
||
|
||
// 快递编码在系统字典与自定义字典里都没有:先让运营把编码建出来(否则绑定页也选不到它)
|
||
if (!expressExists) {
|
||
if (expressDisabled) {
|
||
return `快递编码${expressCode}已停用,请到 OMS 系统管理→自定义快递编码 启用后再重试`;
|
||
}
|
||
return `快递编码${expressCode}不存在(系统快递编码与自定义快递编码均无此编码),请到 OMS 系统管理→自定义快递编码 新增后再重试`;
|
||
}
|
||
|
||
let rows = [];
|
||
try {
|
||
rows = await ctx.model.ExternalPrintExpressInterface.findAll({
|
||
where: { principal_id: principalId, account_id: account.id, platform_code: platformCode, status: 1 },
|
||
attributes: [ 'id', 'express_company_code', 'custom_code' ],
|
||
limit: 50,
|
||
});
|
||
} catch (err) {
|
||
return `平台${platformLabel}快递${expressLabel}(${accountText})未绑定到快递接口:请到 ${guide} 绑定`;
|
||
}
|
||
|
||
// 该平台一条模板都没有:不是绑定漏了,而是店管家侧没有这个平台的电子面单模板
|
||
if (!rows.length) {
|
||
return `平台${platformLabel}暂无面单模板(${accountText}):请到 ${guide} 点「从平台同步数据」,再为快递${expressLabel}绑定`;
|
||
}
|
||
|
||
// 同一编码被多个模板绑定 → resolveByCode 视为未命中
|
||
const duplicated = rows.filter(row => String(row.custom_code || '').trim() === expressCode);
|
||
if (duplicated.length > 1) {
|
||
return `平台${platformLabel}快递${expressLabel}(${accountText})绑定了 ${duplicated.length} 个快递接口:请到 ${guide} 只保留一个后重试`;
|
||
}
|
||
|
||
const codeKey = String(expressCode).trim().toUpperCase();
|
||
const hasSameCompany = rows.some(row => String(row.express_company_code || '').trim().toUpperCase() === codeKey);
|
||
if (!hasSameCompany) {
|
||
return `平台${platformLabel}没有快递${expressLabel}的面单模板(${accountText}):请到 ${guide} 点「从平台同步数据」,再为该快递绑定`;
|
||
}
|
||
return `平台${platformLabel}快递${expressLabel}(${accountText})未绑定到快递接口:请到 ${guide} 选择对应模板绑定`;
|
||
}
|
||
|
||
/**
|
||
* 编码 + 中文名(有名称时 `STO(申通)`,没有名称只返回编码)
|
||
* @param {string} code 编码
|
||
* @param {string} [name] 中文名
|
||
* @return {string} 展示文本
|
||
*/
|
||
function labelWithName(code, name) {
|
||
const text = String(name || '').trim();
|
||
return text && text !== code ? `${code}(${text})` : String(code);
|
||
}
|
||
|
||
/**
|
||
* 查快递编码:先查自定义快递编码字典(全局),再查系统快递公司字典
|
||
* @param {Object} ctx egg context
|
||
* @param {string} expressCode 快递编码
|
||
* @param {number} principalId 主体ID(自定义编码为全局字典,仅保留签名兼容)
|
||
* @return {Promise<{name: string, exists: boolean, disabled: boolean}>} 中文名(查不到为空串)、是否存在、是否已停用
|
||
*/
|
||
async function findExpressCode(ctx, expressCode, principalId) { // eslint-disable-line no-unused-vars
|
||
const code = String(expressCode || '').trim();
|
||
if (!code) return { name: '', exists: false, disabled: false };
|
||
try {
|
||
// 自定义字典:不过滤状态,便于区分「不存在」与「已停用」
|
||
const custom = await ctx.model.CustomExpressCode.findOne({
|
||
where: { code },
|
||
attributes: [ 'name', 'status' ],
|
||
});
|
||
if (custom) {
|
||
return {
|
||
name: custom.name || '',
|
||
exists: Number(custom.status) === 1,
|
||
disabled: Number(custom.status) !== 1,
|
||
};
|
||
}
|
||
} catch (err) {
|
||
// 字典缺失时继续走系统字典
|
||
}
|
||
try {
|
||
const system = await ctx.model.ExpressCompany.findOne({ where: { code }, attributes: [ 'name', 'status' ] });
|
||
if (system) {
|
||
return {
|
||
name: system.name || '',
|
||
exists: Number(system.status) === 1,
|
||
disabled: Number(system.status) !== 1,
|
||
};
|
||
}
|
||
} catch (err) {
|
||
return { name: '', exists: false, disabled: false };
|
||
}
|
||
return { name: '', exists: false, disabled: false };
|
||
}
|
||
|
||
/**
|
||
* 读取完整打单账号实例(含 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;
|
||
}
|
||
|
||
/**
|
||
* 取号留痕:把本次取号拿到的平台原始返回(含 printinfo / signature)写入 waybill_fetch_records
|
||
*
|
||
* 只在「已定位到打单账号」之后调用(真正接触平台的单才留痕,避免报文类失败刷表);
|
||
* 写入失败只告警,绝不影响取号结果。
|
||
* @param {Object} ctx egg context
|
||
* @param {Object} meta 本次取号的上下文(主体/仓库/单号/编码/账号/模板)
|
||
* @param {Object} result 逐单结果
|
||
* @param {Object} [extra] 平台返回的补充数据
|
||
* @param {string} [extra.raw] 平台原始返回
|
||
* @param {string} [extra.printinfo] 面单打印数据
|
||
* @param {string} [extra.signature] 面单签名
|
||
* @param {Array<Object>} [extra.print_history_ids] 打印记录(平台 PrintHistoryIds:id/pid/waybill_code/batch_index)
|
||
* @param {string} [extra.dbname] 实际命中的打单平台分区
|
||
* @return {Promise<void>} 无返回值
|
||
*/
|
||
async function saveRecord(ctx, meta, result, extra = {}) {
|
||
if (!meta || !meta.accountId) return;
|
||
const raw = extra.raw;
|
||
try {
|
||
await ctx.model.WaybillFetchRecord.create({
|
||
principal_id: meta.principalId,
|
||
warehouse_id: meta.warehouseId || null,
|
||
request_id: meta.requestId || '',
|
||
delivery_order_code: meta.code,
|
||
express_code: meta.expressCode || '',
|
||
platform_code: meta.platformCode || '',
|
||
account_id: meta.accountId || null,
|
||
template_id: meta.templateId || '',
|
||
status: result && result.success ? 1 : 0,
|
||
waybill_source: (result && result.waybill_source) || '',
|
||
waybill_code: (result && result.waybill_code) || '',
|
||
waybill_codes: result && result.waybill_codes ? JSON.stringify(result.waybill_codes) : '',
|
||
printinfo: extra.printinfo || '',
|
||
signature: extra.signature || '',
|
||
print_history_ids: Array.isArray(extra.print_history_ids) ? JSON.stringify(extra.print_history_ids) : '',
|
||
// 店铺唯一标识 + 分区:WMS 重取打印数据(params 只有 10 分钟有效期)时按「它 + 运单号」定位
|
||
cai_niao_auth_info_id: meta.caiNiaoAuthInfoId == null ? null : Number(meta.caiNiaoAuthInfoId),
|
||
dbname: extra.dbname || '',
|
||
platform_host: extra.platform_host || '',
|
||
raw_response: raw ? JSON.stringify(raw) : '',
|
||
error_message: result && result.success ? '' : (result && result.message) || '',
|
||
});
|
||
} catch (err) {
|
||
ctx.logger.warn('[waybill.get] 写取号记录失败 %s:%s', meta.code, err.message);
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 处理单个订单取号
|
||
* @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 批内缓存(账号实例等)
|
||
* @param {string} [params.requestId] 调用方 request_id(留痕用)
|
||
* @return {Promise<Object>} 结果项
|
||
*/
|
||
async function processItem(ctx, { principalId, warehouseId, item, memo, requestId }) {
|
||
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)');
|
||
|
||
// 留痕上下文:处理过程中逐步补齐(平台编码 / 打单账号 / 模板)
|
||
const meta = { principalId, warehouseId, requestId, code, expressCode, platformCode: '', accountId: null, templateId: null };
|
||
const detail = { raw: null, printinfo: '', signature: '', encryptprintinfo: '', key: '', ver: '', print_history_ids: [] };
|
||
const result = await callPlatform(ctx, { principalId, warehouseId, code, expressCode, item, memo, meta, detail });
|
||
await saveRecord(ctx, meta, result, detail);
|
||
return result;
|
||
}
|
||
|
||
/**
|
||
* 单订单取号主流程(结果由 processItem 统一留痕)
|
||
* @param {Object} ctx egg context
|
||
* @param {Object} params 参数
|
||
* @param {number} params.principalId 主体ID
|
||
* @param {number} params.warehouseId 仓库ID
|
||
* @param {string} params.code 发货单号
|
||
* @param {string} params.expressCode 快递编码
|
||
* @param {Object} params.item 订单项(可带 packageIndex 指定包裹序号)
|
||
* @param {Map} params.memo 批内缓存
|
||
* @param {Object} params.meta 留痕上下文(会被补齐)
|
||
* @param {Object} params.detail 平台返回数据(raw / printinfo / signature)
|
||
* @return {Promise<Object>} 结果项
|
||
*/
|
||
async function callPlatform(ctx, { principalId, warehouseId, code, expressCode, item, memo, meta, detail }) {
|
||
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 (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 (status === 4) return fail(code, '订单已完成,取号失败');
|
||
}
|
||
|
||
// 平台信息必须回读订单(订单来自哪个平台)
|
||
const platformCode = String(order.source_platform_code || '').trim();
|
||
if (!platformCode) return fail(code, '订单缺少来源平台,无法匹配快递接口');
|
||
meta.platformCode = platformCode;
|
||
|
||
// 打单账号:订单店铺 → 外部打单账号(跨打单平台无法取号)
|
||
// 店铺与账号平台配置走缓存,避免一批 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, '外部打单账号或平台配置不存在:请到「外部打单平台」检查该账号是否被删除、是否已关联平台');
|
||
}
|
||
meta.accountId = account.id;
|
||
|
||
// 按「账号 + 订单平台 + WMS 传入的快递编码」定位唯一模板
|
||
const template = await ctx.service.externalPrintExpressInterface.resolveByCode(
|
||
account.id,
|
||
{ platformCode, expressCode },
|
||
principalId
|
||
);
|
||
if (!template) {
|
||
return fail(code, await buildTemplateMissingMessage(ctx, {
|
||
account,
|
||
platformCode,
|
||
expressCode,
|
||
principalId,
|
||
}));
|
||
}
|
||
|
||
const platformService = ctx.service.externalPrintOrder.createPlatformService(account);
|
||
if (!platformService.needFetchWaybillNo) {
|
||
return fail(code, `打单平台「${account.platform.name}」未开启回平台取号:请在平台配置中开启 fetch_waybill_no 后重试`);
|
||
}
|
||
meta.templateId = String(template.template_id || (template.raw && template.raw.Id) || '');
|
||
// 菜鸟授权网点ID:随取号结果回给 WMS(同平台不同网点取号用的授权不同)
|
||
const caiNiaoAuthInfoId = template.cai_niao_auth_info_id == null ? null : Number(template.cai_niao_auth_info_id);
|
||
// 留痕用:店铺唯一标识(WMS 重取打印数据时按它 + 运单号定位)
|
||
meta.caiNiaoAuthInfoId = caiNiaoAuthInfoId;
|
||
|
||
const orderPlain = order.get ? order.get({ plain: true }) : { ...order };
|
||
// 1688 分销单被换算成抖音小店/淘宝后,取号域名仍要按原始平台(否则回读订单行查错域名)
|
||
const extendProps = orderPlain.extend_props && typeof orderPlain.extend_props === 'object' ? orderPlain.extend_props : {};
|
||
// 包裹序号:报文显式指定优先(拆单场景),否则按单号尾部 `_N` 推导
|
||
const explicitIndex = pickPackageIndex(item);
|
||
const packageIndex = explicitIndex === null ? resolvePackageIndex(code) : explicitIndex;
|
||
const fetched = await platformService.fetchWaybillNo(orderPlain, {
|
||
template: template.get ? template.get({ plain: true }) : template,
|
||
expressCode,
|
||
platformCode,
|
||
originalPlatformCode: extendProps.original_platform_code || '',
|
||
packageIndex,
|
||
});
|
||
const waybill = normalizeWaybill(fetched);
|
||
if (!waybill.waybill_code) return fail(code, '平台未返回运单号');
|
||
|
||
// 面单打印数据原样保留:既要透传给 WMS,也要落取号记录备查
|
||
detail.raw = fetched && fetched.raw ? fetched.raw : null;
|
||
// 打印记录ID(平台 PrintHistoryIds):仅本地留痕,不进 WMS 响应契约
|
||
detail.print_history_ids = Array.isArray(fetched && fetched.print_history_ids) ? fetched.print_history_ids : [];
|
||
// 实际命中的打单平台分区(重取打印数据时要用同一个 dbname)
|
||
detail.dbname = String((fetched && fetched.dbname) || '');
|
||
detail.platform_host = String((fetched && fetched.host) || '');
|
||
detail.printinfo = String((fetched && fetched.printinfo) || '');
|
||
detail.signature = String((fetched && fetched.signature) || '');
|
||
detail.encryptprintinfo = String((fetched && fetched.encryptprintinfo) || '');
|
||
detail.key = String((fetched && fetched.key) || '');
|
||
detail.ver = String((fetched && fetched.ver) || '');
|
||
|
||
// 取号结果只回给调用方(WMS 自行落单),不写回 OMS 订单表:
|
||
// 现阶段取号与订单表不做关联,需要重测时无需清理订单上的运单号
|
||
const previousCode = String((fetched && fetched.previous_code) || '').trim();
|
||
const message = previousCode && previousCode === waybill.waybill_code
|
||
? `已取号:本次调用平台取号,但平台仍返回原运单号 ${previousCode}(平台按「${orderPlain.parent_order_no || orderPlain.order_no}_${packageIndex}」复用该包裹的运单号)`
|
||
: 'ok';
|
||
ctx.logger.info('[waybill.get] 取号成功', {
|
||
code,
|
||
expressCode,
|
||
platformCode,
|
||
waybillCode: waybill.waybill_code,
|
||
printinfoLength: detail.printinfo.length,
|
||
keyLength: detail.key.length,
|
||
});
|
||
return {
|
||
delivery_order_code: code,
|
||
success: true,
|
||
message,
|
||
// 运单号来源:现阶段一律为 express_print(本次向打单平台取号,不再复用平台已有运单号)
|
||
waybill_source: 'express_print',
|
||
express_code: expressCode,
|
||
platform_code: platformCode,
|
||
waybill_code: waybill.waybill_code,
|
||
waybill_codes: waybill.waybill_codes,
|
||
// 本次取号对应的包裹序号(0 基):平台按 <LogicOrderId>_<序号> 分配/复用运单号
|
||
package_index: packageIndex,
|
||
// 菜鸟授权网点ID(模板绑定的授权网点,平台 CaiNiaoAuthInfoId)
|
||
cai_niao_auth_info_id: caiNiaoAuthInfoId,
|
||
// 面单打印数据:平台原样返回,WMS 落 order_express 后打印时直接使用
|
||
printinfo: detail.printinfo,
|
||
signature: detail.signature,
|
||
// 打印记录ID(平台 PrintHistoryIds):WMS 自行落库;重取打印数据时可直接用 printHistoryIds 直传
|
||
print_history_ids: Array.isArray(detail.print_history_ids) ? detail.print_history_ids : [],
|
||
print_history_id: (Array.isArray(detail.print_history_ids) && detail.print_history_ids[0]
|
||
? String(detail.print_history_ids[0].id || '')
|
||
: ''),
|
||
// 需要加密打印的平台(如菜鸟系)才有值,店管家视频号自定义模板一般为空
|
||
encryptprintinfo: detail.encryptprintinfo,
|
||
// 快手逐单加密密钥(base64,约 172 字符):WMS 快手打印模板的 key 参数,其余平台为空串
|
||
key: detail.key,
|
||
ver: detail.ver,
|
||
};
|
||
} catch (err) {
|
||
ctx.logger.warn('[waybill.get] 取号失败 %s:%s', code, err.message);
|
||
// 平台异常时保留原始返回,便于在取号记录里看到平台到底回了什么
|
||
if (err && err.rawResponse) detail.raw = err.rawResponse;
|
||
// 回给 WMS 的错误信息带上平台的可读原因(ErrorCode / ErrorMsg / 网点),方便对方直接定位
|
||
return fail(code, describePlatformFailure(err));
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 批量取号(method = deliveryorder.getwaybill)
|
||
*
|
||
* WMS 发起取号时携带快递编码,OMS 回读订单信息(平台 / 店铺 / 打单账号)后按
|
||
* 「账号 + 平台 + 编码」定位快递接口并调用平台取号;逐单返回成功/失败,不影响其它订单。
|
||
* 订单已取消 / 已作废 / 已归档 / 已配送时返回该单取号失败。
|
||
* **取号结果不回写订单表**(现阶段取号与订单表不做关联,由 WMS 自行落单);
|
||
* 每次取号的平台原始返回(含 printinfo / signature)写入 waybill_fetch_records 留痕。
|
||
* @param {Object} ctx egg context
|
||
* @param {Object} payload 调用上下文
|
||
* @param {number} payload.principalId 主体ID
|
||
* @param {number} payload.warehouseId app_key 定位到的仓库ID
|
||
* @param {Object} payload.data 回调报文
|
||
* @param {string} [payload.requestId] 调用方 request_id(写入取号记录,便于按批排查)
|
||
* @return {Promise<{ok: boolean, message: string, data?: Object}>} 批量结果
|
||
*/
|
||
async function getWaybills(ctx, { principalId, warehouseId, data, requestId }) {
|
||
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,
|
||
requestId,
|
||
}));
|
||
const success = results.filter(row => row.success).length;
|
||
return {
|
||
ok: true,
|
||
message: 'ok',
|
||
// 有订单没取到号时不锁定 request_id:调用方用同一 request_id 重试会整批重跑,
|
||
// 已取到号的单会复用打单平台订单上的运单号(不重复消耗面单),只补真正失败的单
|
||
replayable: success === results.length,
|
||
data: {
|
||
total: results.length,
|
||
success,
|
||
failed: results.length - success,
|
||
results,
|
||
},
|
||
};
|
||
}
|
||
|
||
module.exports = {
|
||
getWaybills,
|
||
extractItems,
|
||
pickExpressCode,
|
||
pickPackageIndex,
|
||
resolvePackageIndex,
|
||
normalizeWaybill,
|
||
};
|