feat(waybill): 新增 deliveryorder.getprintdata,打印前按运单号换新 params

店管家面单打印数据(params)只有 10 分钟有效期,取号返回的 printinfo 存着不能用,
WMS 真正打印前必须换新的。新增对外方法:

  method = deliveryorder.getprintdata
  入参:{ caiNiaoAuthInfoIds: [6838859], waybillCodes: ["770357408441408"] }
       也支持直传 { printHistoryIds: ["10000078656212"] }(命中即跳过查库)
  出参:{ total, success, failed, expires_in: 600, results: [...] }
       每单含 print_data / printer_config / document(documentID = 运单号)

实现:
- app/lib/waybillPrintData.js:按「店铺标识 + 运单号」查 waybill_fetch_records 定位打印记录,
  同账号同分区合并成一次 PrintHistory/LoadPrintData(只读,不消耗面单)
- 取号记录补 platform_host(实际命中的订单域名):1688 分销单在 fxali、真实抖音单在 fxdd,
  用被换算过的 source_platform_code 推域名会打错
- waybillGet 落 platform_host;迁移 20261107050000 加列

实测(只读):运单号 770357408441408 → 新 params 7888 字符,documentID 770357408441408,
printer 默认打印机;不存在的运单号返回「未找到该运单号的取号记录」。

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
This commit is contained in:
liufumingren 2026-11-07 06:38:34 +08:00
parent 9252763aba
commit 09587bc3e7
9 changed files with 496 additions and 3 deletions

View File

@ -15,6 +15,7 @@
|---|---|---|---|
| 订单推送 `deliveryorder.create` + `need_oms_waybill` | ✅ 已完成 | ✅ 已识别 | OMS 按平台配置自动下发,WMS 已能把这类订单分流到 `waiting_oms` |
| 取号入站方法 `deliveryorder.getwaybill` | ✅ 已完成 | ❌ 未接通 | OMS 可批量回取号并逐单返回结果 |
| 打印前换新 params `deliveryorder.getprintdata` | ✅ 已完成 | ❌ 未接通 | 平台打印数据只有 10 分钟有效期,打印前按「店铺标识 + 运单号」换新的(只读,不消耗面单) |
| WMS 侧「oms 取号平台」实现 | — | ❌ 缺失 | `express_platform.js` 只有 `polyapi / cainiao / pdd` |
| WMS 侧消费 `waiting_oms` | — | ❌ 缺失 | 目前 `waiting_oms` 是终态,不会被再次处理 |
| 店管家(dgj)真实取号调用 | ✅ 已实现(默认开启) | — | `dgj.fetchWaybillNo()` 已按旧系统流程实现,平台无运单号时会真实取号(消耗面单);可用 `DGJ_WAYBILL_ENABLE=0` 临时关闭 |
@ -367,6 +368,42 @@ SELECT * FROM waybill_fetch_records WHERE request_id = 'oms-getwaybill-xxx' ORDE
> ⚠️ `printinfo` 是整张面单的打印数据(单张常见几十到几百 KB),批量取号时响应会明显变大:
> 建议一次批量不超过 20 单,或让 WMS 逐单/小批取号,避免响应体过大拖慢回调。
#### 4.7.1 ⚠️ `printinfo` 只有 10 分钟有效期 → 打印前必须换新的
店管家面团单打印数据(params)**有效期只有 10 分钟**,取号时拿到的 `printinfo` 不能存着以后慢慢用。
WMS 真正要打印时,调 `deliveryorder.getprintdata` 换一份新的(OMS 内部走 `PrintHistory/LoadPrintData`,**只读、不消耗面单**)。
| 项 | 说明 |
|---|---|
| 方法 | `deliveryorder.getprintdata` |
| 入参(推荐) | `{ "caiNiaoAuthInfoIds": [ 6838859 ], "waybillCodes": [ "770357408441408" ] }` |
| 入参(可选直传) | `{ "printHistoryIds": [ "10000078656212" ] }`(命中即跳过按运单号查库) |
| 出参 | `{ total, success, failed, expires_in, results: [ … ] }`,`expires_in` 固定 600 秒 |
| 单条结果 | `waybill_code, success, message, print_history_id, template_id, cai_niao_auth_info_id, dbname, print_data, printer_config, document` |
`caiNiaoAuthInfoId` 就是取号响应里的 `cai_niao_auth_info_id`(**每个店铺唯一**),WMS 落库时把它和运单号一起存下来即可;
OMS 用它 + 运单号定位到那次取号的打印记录(`waybill_fetch_records`,已建 `principal_id + cai_niao_auth_info_id + waybill_code` 索引)。
返回用法:
- `print_data`:平台原样返回的 params 字符串,直接交给打印服务
- `printer_config` / `document`:拆好的结构。**同店铺多张面单共用一个 `printer_config`**,
把各自的 `document`(含 `documentID` = 运单号、`contents[].params`)拼进同一个 `PrintDataList.task.documents`
就是一次多张打印任务 —— 不要拿 A 单的 `document` 去打 B 单,`documentID`/params 是逐张面单的
- 建议 WMS 按「店铺(caiNiaoAuthInfoId)分组、一批运单号一次调用」换 params,10 分钟内打完
**注意**:`printHistoryId` 由 OMS 保存,**不需要** WMS 再存一份(每张面单一条、重打/换号会新增,存两份必然不一致)。
单条失败原因:`未找到该运单号的取号记录(可能不是通过 OMS 取的号)` /
`取号记录里没有该运单号的打印记录ID(PrintHistoryIds),无法换新的打印数据`。
```sql
-- 打印前换 params 时 OMS 内部按这条定位(同一个运单号多次取号取最新一条)
SELECT id, delivery_order_code, print_history_ids, cai_niao_auth_info_id, dbname, platform_host
FROM waybill_fetch_records
WHERE principal_id = ? AND status = 1 AND waybill_code = ?
ORDER BY id DESC LIMIT 1;
```
---
## 5. 推送侧:`need_oms_waybill`
@ -679,7 +716,8 @@ curl -X POST '<上面打印的 URL>' -H 'Content-Type: application/json' -d '<
| `backend/database/migrations/20261104010000-*.js` | `custom_express_codes` 表 |
| `backend/database/migrations/20261104020000-*.js` | `openapi_request_idempotency` 表 |
| `backend/database/migrations/20261104040000-*.js` | `waybill_fetch_records` 表(取号平台原始返回留痕) |
| `backend/app/model/waybillFetchRecord.js` | 取号记录模型(`printinfo` / `signature` / `raw_response`) |
| `backend/app/model/waybillFetchRecord.js` | 取号记录模型(`printinfo` / `signature` / `print_history_ids` / `cai_niao_auth_info_id` / `dbname` / `platform_host` / `raw_response`) |
| `backend/app/lib/waybillPrintData.js` | `deliveryorder.getprintdata` 实现(按运单号+店铺标识定位打印记录 → `PrintHistory/LoadPrintData` 换新 params) |
### WMS(`D:\wms`)

View File

@ -3,6 +3,7 @@
const { nowTimestamp } = require('./apiResponse');
const orderCallback = require('./orderCallback');
const waybillGet = require('./waybillGet');
const waybillPrintData = require('./waybillPrintData');
/**
* 对外通用回调接口的方法注册表。
@ -144,6 +145,32 @@ const METHODS = {
requestId,
}),
/**
* 重新获取面单打印数据(method = deliveryorder.getprintdata)
*
* 店管家面单打印数据(params)只有 10 分钟有效期,WMS 真正打印前必须换新的:
* 报「店铺标识(CaiNiaoAuthInfoId)+ 运单号」,OMS 查取号记录得到该运单号的打印记录ID,
* 再回平台 `PrintHistory/LoadPrintData` 取新数据(只读,不消耗面单)。
*
* 报文示例:
* { "caiNiaoAuthInfoIds": [ 6838859 ], "waybillCodes": [ "770357408441408" ] }
* { "printHistoryIds": [ "10000078656212" ] } // 直传打印记录ID,命中即跳过查库
* 返回 data:{ total, success, failed, expires_in, results: [ { waybill_code, success, print_data, printer_config, document, ... } ] }
* @param {Object} ctx egg context
* @param {Object} payload 调用上下文
* @param {Object} payload.api 按 app_key 定位到的接口配置
* @param {Object} payload.warehouse 接口配置关联的仓库
* @param {Object} payload.body 报文
* @param {string} [payload.requestId] 调用方 request_id(日志用)
* @return {Promise<Object>} { ok, message, data }
*/
'deliveryorder.getprintdata': (ctx, { api, warehouse, body, requestId }) => waybillPrintData.getPrintData(ctx, {
principalId: api.principal_id,
warehouseId: warehouse.id,
data: body,
requestId,
}),
/**
* 出库单确认(method = stockout.confirm):WMS 出库完成(非订单出库单,CK 组 / wms_order_stockout)
* 写回明细「已出数量」,扣减系统库存并置「已完成(4)」(幂等,明细以仓库侧为准)

View File

@ -2377,6 +2377,8 @@ class DgjService extends PrintPlatformService {
print_history_ids: extractPrintHistoryIds(printed),
// 实际命中的分区库名:重取打印数据(PrintHistory/LoadPrintData)要带上同一个 dbname
dbname,
// 实际命中的订单域名:重取打印数据要发到同一个域名
host,
// 面单打印数据:原样透传(WMS 打印端直接塞进 task.printInfo)
printinfo: firstPrintInfo(items, printed, waybillCodes[0]),
signature: contents.signature,

View File

@ -445,6 +445,7 @@ async function saveRecord(ctx, meta, result, extra = {}) {
// 店铺唯一标识 + 分区: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) || '',
});
@ -582,6 +583,7 @@ async function callPlatform(ctx, { principalId, warehouseId, code, expressCode,
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) || '');

View File

@ -0,0 +1,333 @@
'use strict';
/**
* 打印数据(params)有效期:店管家面团单打印数据只有 10 分钟有效,
* 这里按保守口径回给调用方,便于 WMS 判断是否需要重新拉取。
*/
const PRINT_DATA_TTL_SECONDS = 600;
/** 单次最多换取的运单号数量(一次打印任务的面单张数不会太多) */
const MAX_BATCH = 200;
/**
* 拆掉报文外层的 request / deliveryOrders 包装,取真正的入参对象
* @param {Object} data 原始报文
* @return {Object} 入参对象
*/
function unwrapBody(data) {
if (!data || typeof data !== 'object') return {};
if (data.request && typeof data.request === 'object' && !Array.isArray(data.request)) return data.request;
return data;
}
/**
* 归一化成非空字符串数组(兼容单值、逗号分隔、数组)
* @param {*} value 原始值
* @return {string[]} 去重后的字符串数组
*/
function toStringList(value) {
const raw = Array.isArray(value) ? value : [ value ];
const out = [];
for (const item of raw) {
if (item == null) continue;
for (const part of String(item).split(',')) {
const text = part.trim();
if (text) out.push(text);
}
}
return [ ...new Set(out) ];
}
/**
* 解析取号记录里的打印记录(`print_history_ids` 存的是 JSON 字符串)
* @param {string|Array} value 打印记录
* @return {Array<Object>} 打印记录数组
*/
function parsePrintHistoryIds(value) {
if (Array.isArray(value)) return value;
if (typeof value !== 'string' || !value.trim()) return [];
try {
const parsed = JSON.parse(value);
return Array.isArray(parsed) ? parsed : [];
} catch {
return [];
}
}
/**
* 从一条取号记录里挑出与运单号对应的打印记录
*
* 一个取号请求可能取到多张面单(多包裹),`print_history_ids` 与 `waybill_codes` 按顺序对应;
* 优先按 `waybill_code` 精确匹配,匹配不到时(历史数据缺该字段)退回按位取。
* @param {Object} record 取号记录(Sequelize 实例或 plain object)
* @param {string} waybillCode 运单号
* @param {string[]} [preferredIds] 调用方直传的打印记录ID(命中则优先用)
* @return {Object|null} 打印记录 { id, pid, waybill_code, batch_index }
*/
function pickPrintHistory(record, waybillCode, preferredIds = []) {
const list = parsePrintHistoryIds(record && record.print_history_ids);
if (!list.length) return null;
if (preferredIds.length) {
const hit = list.find(item => item && preferredIds.includes(String(item.id)));
if (hit) return hit;
}
const matched = list.find(item => item && String(item.waybill_code || '') === waybillCode);
if (matched) return matched;
const codes = parsePrintHistoryIds(record && record.waybill_codes);
const index = codes.findIndex(code => String(code) === waybillCode);
return index >= 0 ? list[index] || null : null;
}
/**
* 解析平台返回的打印数据(params),取出打印机配置与面单 document
*
* `Data[].PrintDataJson` 是字符串,里面还有一层 `printDataJson`,形如
* `{ PrinterConfig, PrintDataList: { task: { documents: [ { documentID, contents } ] } } }`。
* 同店铺的 PrinterConfig / templateURL 相同,多张面单只需把各自 documents 拼成一个 task。
* @param {string} printData 平台返回的 PrintDataJson
* @return {{printer_config: Object|null, document: Object|null, documents: Array}} 解析结果
*/
function parsePrintData(printData) {
const empty = { printer_config: null, document: null, documents: [] };
if (typeof printData !== 'string' || !printData.trim()) return empty;
try {
const outer = JSON.parse(printData);
const inner = outer && outer.printDataJson ? JSON.parse(outer.printDataJson) : outer;
const documents = inner && inner.PrintDataList && inner.PrintDataList.task && inner.PrintDataList.task.documents;
const list = Array.isArray(documents) ? documents : [];
return {
printer_config: (inner && inner.PrinterConfig) || null,
document: list[0] || null,
documents: list,
};
} catch {
return empty;
}
}
/**
* 取(并缓存)打单账号的完整实例:一次批量请求通常只涉及 1~2 个账号
* @param {Object} ctx egg context
* @param {Map} memo 批内缓存
* @param {Object} params 参数
* @param {number} params.accountId 打单账号ID
* @param {number} params.principalId 主体ID
* @return {Promise<Object|null>} { account, service }
*/
async function loadAccount(ctx, memo, { accountId, principalId }) {
const key = `${principalId}:${accountId}`;
if (memo.has(key)) return memo.get(key);
const account = await ctx.model.ExternalPrintAccount.findByPk(accountId, {
include: [{ model: ctx.model.ExternalPrintPlatform, as: 'platform' }],
});
if (!account || !account.platform || (account.principal_id && Number(account.principal_id) !== Number(principalId))) {
memo.set(key, null);
return null;
}
const service = ctx.service.externalPrintOrder.createPlatformService(account);
const entry = { account, service };
memo.set(key, entry);
return entry;
}
/**
* 按运单号(或打印记录ID)重新拉取面单打印数据
*
* 背景:取号返回的打印数据只有 10 分钟有效期,WMS 真正打印前必须换新的。
* 定位口径:WMS 传「店铺标识(CaiNiaoAuthInfoId)+ 运单号」,OMS 查取号记录得到该运单号的
* 打印记录ID,再回平台 `PrintHistory/LoadPrintData` 换新的 params。
* 也支持直传 `printHistoryIds`(命中即跳过按运单号的匹配)。
* @param {Object} ctx egg context
* @param {Object} params 参数
* @param {number} params.principalId 主体ID(来自 app_key)
* @param {number} [params.warehouseId] 仓库ID(来自 app_key,仅用于日志)
* @param {Object} params.data 报文
* @param {string} [params.requestId] 调用方 request_id(日志用)
* @return {Promise<Object>} { ok, message, data }
*/
async function getPrintData(ctx, { principalId, warehouseId, data, requestId }) {
const Op = ctx.app.Sequelize.Op;
const body = unwrapBody(data);
ctx.logger.info('[waybill.printdata] 换取打印数据 principal=%s warehouse=%s requestId=%s', principalId, warehouseId || '-', requestId || '-');
const waybillCodes = toStringList(
body.waybillCodes || body.waybillCode || body.mailNos || body.mailNo || body.expressCodes
);
const historyIds = toStringList(body.printHistoryIds || body.printHistoryId);
const shopIds = toStringList(body.caiNiaoAuthInfoIds || body.caiNiaoAuthInfoId || body.authInfoIds)
.map(value => Number(value))
.filter(value => Number.isFinite(value) && value > 0);
if (!waybillCodes.length && !historyIds.length) {
return { ok: false, message: '缺少运单号(waybillCodes)或打印记录ID(printHistoryIds)' };
}
if (waybillCodes.length > MAX_BATCH) {
return { ok: false, message: `单次最多换取 ${MAX_BATCH} 个运单号的打印数据` };
}
const where = { principal_id: principalId, status: 1 };
if (shopIds.length) where.cai_niao_auth_info_id = { [Op.in]: shopIds };
if (waybillCodes.length) where.waybill_code = { [Op.in]: waybillCodes };
const records = await ctx.model.WaybillFetchRecord.findAll({
where,
order: [[ 'id', 'DESC' ]],
});
// 运单号 → 取号记录(同号可能被多次取号,取最新一条)
const byWaybill = new Map();
for (const record of records) {
const code = String(record.waybill_code || '');
if (!code || byWaybill.has(code)) continue;
if (shopIds.length && !shopIds.includes(Number(record.cai_niao_auth_info_id))) continue;
byWaybill.set(code, record);
}
const results = [];
const memo = new Map();
const groups = new Map(); // `${accountId}|${host}|${dbname}` → { accountId, host, dbname, items: [] }
for (const code of waybillCodes) {
const record = byWaybill.get(code);
if (!record) {
results.push({ waybill_code: code, success: false, message: '未找到该运单号的取号记录(可能不是通过 OMS 取的号)' });
continue;
}
const history = pickPrintHistory(record, code, historyIds);
if (!history) {
results.push({
waybill_code: code,
success: false,
message: '取号记录里没有该运单号的打印记录ID(PrintHistoryIds),无法换新的打印数据',
});
continue;
}
const key = `${record.account_id}|${record.platform_host || ''}|${record.dbname || ''}`;
if (!groups.has(key)) {
groups.set(key, {
accountId: Number(record.account_id),
host: String(record.platform_host || ''),
dbname: String(record.dbname || ''),
items: [],
});
}
groups.get(key).items.push({ waybillCode: code, record, history });
}
// 直传 printHistoryIds 但没有对应运单号的情况:按记录里的运单号补齐
if (historyIds.length) {
for (const record of records) {
const list = parsePrintHistoryIds(record.print_history_ids)
.filter(item => item && historyIds.includes(String(item.id)));
for (const history of list) {
const code = String(history.waybill_code || record.waybill_code || '');
if (!code || results.some(row => row.waybill_code === code)) continue;
if (waybillCodes.length && !waybillCodes.includes(code)) continue;
const key = `${record.account_id}|${record.platform_host || ''}|${record.dbname || ''}`;
if (!groups.has(key)) {
groups.set(key, {
accountId: Number(record.account_id),
host: String(record.platform_host || ''),
dbname: String(record.dbname || ''),
items: [],
});
}
groups.get(key).items.push({ waybillCode: code, record, history });
}
}
}
for (const group of groups.values()) {
const found = await fetchGroup(ctx, { principalId, memo, group });
results.push(...found);
}
const success = results.filter(row => row.success).length;
return {
ok: true,
message: 'ok',
data: {
total: results.length,
success,
failed: results.length - success,
// params 只有 10 分钟有效期,调用方需要在这个时间内打印
expires_in: PRINT_DATA_TTL_SECONDS,
results,
},
};
}
/**
* 按「账号 + 域名 + 分区」分组拉取打印数据(同店铺一次请求取多张)
* @param {Object} ctx egg context
* @param {Object} params 参数
* @param {number} params.principalId 主体ID
* @param {Map} params.memo 批内账号缓存
* @param {Object} params.group 分组 { accountId, host, dbname, items }
* @return {Promise<Array<Object>>} 逐运单号结果
*/
async function fetchGroup(ctx, { principalId, memo, group }) {
const { accountId, host, dbname, items } = group;
const fallback = message => items.map(item => ({
waybill_code: item.waybillCode,
success: false,
message,
}));
const entry = await loadAccount(ctx, memo, { accountId, principalId });
if (!entry) return fallback('打单账号不存在或不属于该主体');
const { service } = entry;
if (typeof service.loadPrintData !== 'function') return fallback('当前打单平台不支持重新获取打印数据');
let traceId = '';
try {
const info = await service.getUserInfo();
traceId = (info.data && info.data.TraceId) || '';
} catch {
traceId = '';
}
let list = [];
try {
list = await service.loadPrintData(host, {
traceId,
dbname,
printHistoryIds: items.map(item => item.history.id),
});
} catch (err) {
ctx.logger.warn('[waybill.printdata] 换打印数据失败 host=%s dbname=%s:%s', host, dbname, err.message);
return fallback(`读取打印数据失败:${err.message}`);
}
const byHistoryId = new Map(list.map(item => [ String(item.print_history_id), item ]));
return items.map(item => {
const row = byHistoryId.get(String(item.history.id));
if (!row) {
return { waybill_code: item.waybillCode, success: false, message: '平台未返回该运单号的打印数据' };
}
const parsed = parsePrintData(row.print_data);
return {
waybill_code: item.waybillCode,
success: true,
message: 'ok',
print_history_id: row.print_history_id,
template_id: row.template_id,
cai_niao_auth_info_id: item.record.cai_niao_auth_info_id == null ? null : Number(item.record.cai_niao_auth_info_id),
dbname: item.record.dbname || '',
expires_in: PRINT_DATA_TTL_SECONDS,
// 新的打印数据(平台原样返回的 params 字符串)
print_data: row.print_data,
// 拆好的结构:同店铺多张面单共用一个 printer_config,documents 拼起来即可
printer_config: parsed.printer_config,
document: parsed.document,
};
});
}
module.exports = {
getPrintData,
// 供单测/脚本复用
unwrapBody,
toStringList,
parsePrintHistoryIds,
pickPrintHistory,
parsePrintData,
};

View File

@ -37,6 +37,7 @@ module.exports = app => {
comment: '菜鸟授权网点ID(=店铺唯一标识,重取打印数据时按它+运单号定位)',
},
dbname: { type: STRING(100), comment: '实际命中的打单平台分区(重取打印数据要带同一个 dbname)' },
platform_host: { type: STRING(100), comment: '实际命中的订单域名(重取打印数据要发到同一个域名)' },
raw_response: { type: TEXT('medium'), comment: '平台原始返回(JSON)' },
error_message: { type: TEXT, comment: '失败原因' },
created_at: { type: DATE, comment: '创建时间' },

View File

@ -0,0 +1,23 @@
'use strict';
/**
* 取号记录补「订单域名」:`platform_host`。
*
* `PrintHistory/LoadPrintData` 与取号一样必须发到**订单所在的域名**(1688 分销单在 `fxali`、
* 真实抖音单在 `fxdd`),而 `source_platform_code` 可能已被平台换算改写(1688 → DYXD),
* 用它推域名会打错。因此取号时把实际命中的域名一起落库,重取打印数据时直接复用。
*/
module.exports = {
async up(queryInterface, Sequelize) {
await queryInterface.addColumn('waybill_fetch_records', 'platform_host', {
type: Sequelize.STRING(100),
allowNull: true,
comment: '实际命中的订单域名(重取打印数据要发到同一个域名)',
after: 'dbname',
});
},
async down(queryInterface) {
await queryInterface.removeColumn('waybill_fetch_records', 'platform_host');
},
};

View File

@ -0,0 +1,63 @@
'use strict';
const { assert } = require('egg-mock/bootstrap');
const printData = require('../../../app/lib/waybillPrintData');
describe('waybillPrintData 打印数据换取', () => {
const record = {
waybill_code: '770357408441408',
waybill_codes: JSON.stringify([ '770357408441408', '770357408441409' ]),
print_history_ids: JSON.stringify([
{ id: '10000078656212', pid: 'p1', waybill_code: '770357408441408', batch_index: 1 },
{ id: '10000078656213', pid: 'p2', waybill_code: '770357408441409', batch_index: 2 },
]),
};
it('入参归一化:单值/数组/逗号分隔都接受并去重', () => {
assert.deepStrictEqual(printData.toStringList('a, b'), [ 'a', 'b' ]);
assert.deepStrictEqual(printData.toStringList([ 'a', 'a' ]), [ 'a' ]);
assert.deepStrictEqual(printData.toStringList(null), []);
});
it('按运单号挑出对应的打印记录(多包裹不能串号)', () => {
const first = printData.pickPrintHistory(record, '770357408441408');
const second = printData.pickPrintHistory(record, '770357408441409');
console.log('打印记录:', first && first.id, second && second.id);
assert.strictEqual(first.id, '10000078656212');
assert.strictEqual(second.id, '10000078656213');
});
it('直传的打印记录ID命中时优先使用', () => {
const hit = printData.pickPrintHistory(record, '770357408441408', [ '10000078656213' ]);
assert.strictEqual(hit.id, '10000078656213');
});
it('历史数据缺 waybill_code 时按顺序兜底,找不到返回 null', () => {
const legacy = {
waybill_codes: JSON.stringify([ 'A', 'B' ]),
print_history_ids: JSON.stringify([{ id: '1' }, { id: '2' }]),
};
assert.strictEqual(printData.pickPrintHistory(legacy, 'B').id, '2');
assert.strictEqual(printData.pickPrintHistory(legacy, 'C'), null);
assert.strictEqual(printData.pickPrintHistory({}, 'A'), null);
});
it('解析平台返回的 params:拿到打印机配置与面单 document', () => {
const params = JSON.stringify({
id: null,
sendContent: '[1];\n',
printDataJson: JSON.stringify({
PrinterConfig: { cmd: 'setPrinterConfig', printer: { name: '默认打印机' } },
PrintDataList: {
cmd: 'print',
task: { printer: '默认打印机', documents: [{ documentID: '770357408441408', contents: [{ templateURL: 'https://x/t.xml' }] }] },
},
}),
});
const parsed = printData.parsePrintData(params);
console.log('documentID:', parsed.document.documentID, '| printer:', parsed.printer_config.printer.name);
assert.strictEqual(parsed.document.documentID, '770357408441408');
assert.strictEqual(parsed.printer_config.printer.name, '默认打印机');
assert.deepStrictEqual(printData.parsePrintData('not-json'), { printer_config: null, document: null, documents: [] });
});
});

View File

@ -271,8 +271,12 @@ WaybillCodeCreateDate='2026-11-04 08:20:37'
- **打印数据(params)只有 10 分钟有效期**:取号返回的 `printinfo` 不能长期保存着用,WMS 真正打印前必须重新拉一次
`POST /PrintHistory/LoadPrintData?token=&dbname=<取号命中的分区>`,表单 `printHistoryIds[]=<Id>&IsCustomerOrder=false&FxPageType=1`;
响应 `Data[0].PrintDataJson` 就是新的 params(实测 7888 字符,`id/sendContent/printDataJson`)。
因此取号记录里同时落了 `dbname` 与 `cai_niao_auth_info_id`(= 店铺唯一标识),
后续按「店铺标识 + 运单号」即可定位到该运单号对应的打印记录,再回平台换新数据。
因此取号记录里同时落了 `dbname`、`platform_host`(实际命中的域名)与 `cai_niao_auth_info_id`(= 店铺唯一标识),
后续按「店铺标识 + 运单号」即可定位到该运单号对应的打印记录,再回平台换新数据;
对外方法见 `deliveryorder.getprintdata`(`WMS-OMS-取号对接.md` §4.7.1)。
- **params 是逐张面单的**:`printDataJson.PrintDataList.task.documents[].documentID` = 运单号,
`contents[].params` 是该张面单的内容;同店铺可共用的只有 `PrinterConfig` 与 `templateURL`,
**不能拿 A 单的 document 去打 B 单**(会把收件人/面单号搞错)。
- 因此 OMS「按 `LastWaybillCode` 复用」是错的判断;是否重复取号由 **OMS 幂等表(request_id)** 决定,
而**同一个包裹重复取号拿回同号**是平台行为,不是 bug。