feat(waybill): getprintdata 改走「原单号打印」重签,拿到新鲜的 params
上一版用 PrintHistory/LoadPrintData,实测它只回放那次打印的签名(timestamp = 打印记录 CreateDate,换 FxPageType / IsRePrint / IsRefresh 都不重签),10 分钟后必过期。 实测出真正的重签方式(复用原运单号、不消耗面单): ExpressPrint + PrintMethod=Normal + IsIgnoreWaybillRepeat=true → 返回的运单号与原来一致,params.timestamp = 当前时间。 - dgj.reprintPrintData:原单号打印并解析 documents[].contents[].params - dgj.expressPrint 支持 reprint 选项(Normal + IsIgnoreWaybillRepeat=true) - getprintdata 改为:回读平台订单行 → 原单号打印 → 返回新 params / template_url; 安全闸:若平台返回了新运单号(说明已消耗面单)直接判失败并 error 日志 - 仍逐张串行 + 300ms 间隔限流;参数归一化/定位逻辑不变 实测:请求 07:39:44 → params timestamp 2026-11-07 07:39:45,运单号 770357415909002 未变。 Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
This commit is contained in:
parent
82ebe7e022
commit
3b98a1c3dc
@ -388,13 +388,13 @@ WMS 真正要打印时,调 `deliveryorder.getprintdata` 换一份新的(OMS
|
||||
| 出参 | `{ total, success, failed, expires_in, results: [ … ] }`,`expires_in` 固定 600 秒 |
|
||||
| 单条结果 | `waybill_code, success, message, print_history_id, template_id, cai_niao_auth_info_id, dbname, expires_in, params, params_timestamp, params_expired, template_url` |
|
||||
|
||||
> ⚠️ **重要(实测 2026-11-07)**:店管家 `PrintHistory/LoadPrintData` **只回放那次打印时签发的 params,不会重签**。
|
||||
> 返回里的 `params_timestamp` 等于该打印记录的 `CreateDate`;换 `FxPageType=1/2`、加 `IsRePrint`/`IsRefresh`
|
||||
> 都返回同一个 `timestamp/sign`。所以隔超过 10 分钟再取,`params_expired` 一定为 `true`,
|
||||
> 那串 `access_token=…&sign=…` 发给打印网关会被判过期。
|
||||
> 结论:**「打印前调本接口换新 params」不成立**,只能保证「取号后 10 分钟内打印」。
|
||||
> 超过 10 分钟的重打需要平台重新签发(走 `ExpressPrint` 的「原单号打印」模式,复用已有运单号、不消耗面单),
|
||||
> 该路径待确认后接入;当前本接口会把 `params_expired` 如实返回,请按它决定是否走重打。
|
||||
> ⚠️ **重要(实测 2026-11-07)**:店管家 `PrintHistory/LoadPrintData` **只回放那次打印时签发的 params,不会重签**
|
||||
> (`params_timestamp` 恒等于该打印记录的 `CreateDate`;换 `FxPageType=1/2`、加 `IsRePrint`/`IsRefresh`
|
||||
> 都返回同一个 `timestamp/sign`),所以那串 `access_token=…&sign=…` 10 分钟后必失效。
|
||||
> ✅ 要新鲜签名只能让平台**重新打印**:`ExpressPrint` + `PrintMethod=Normal` + `IsIgnoreWaybillRepeat=true`
|
||||
> —— 实测平台**复用订单已有运单号**(不消耗面单)并重签 params(返回的 `timestamp` = 当前时间)。
|
||||
> OMS 的 `deliveryorder.getprintdata` 已按这条路径实现:回读平台订单行 → 原单号打印 → 返回新 `params`;
|
||||
> 并带安全闸,万一平台返回了新运单号(说明已消耗面单)会直接判失败并告警,不会静默返回。
|
||||
|
||||
`caiNiaoAuthInfoId` 就是取号响应里的 `cai_niao_auth_info_id`(**每个店铺唯一**),WMS 落库时把它和运单号一起存下来即可;
|
||||
OMS 用它 + 运单号定位到那次取号的打印记录(`waybill_fetch_records`,已建 `principal_id + cai_niao_auth_info_id + waybill_code` 索引)。
|
||||
@ -410,7 +410,8 @@ OMS 用它 + 运单号定位到那次取号的打印记录(`waybill_fetch_reco
|
||||
- **限流**:平台该接口有限流,OMS 内部**一次只带一个 `printHistoryId`**、逐张串行并留 300ms 间隔;
|
||||
WMS 侧也建议一张一张调(或小批),10 分钟内打完
|
||||
- **新鲜度**:`params_timestamp` 是平台签发时间,`params_expired` 由 OMS 按 10 分钟算出;
|
||||
取号后 10 分钟内换到的 `params` 可直接打印,超过就一定是历史签名(见上方 ⚠️)
|
||||
本接口走「原单号打印」重签,正常应当 `params_expired=false`。
|
||||
若为 `true` 或 `success=false` 且 message 提到「重打返回了新运单号」,说明平台异常发了新号(已消耗面单),需人工核对
|
||||
|
||||
**注意**:`printHistoryId` 由 OMS 保存,**不需要** WMS 再存一份(每张面单一条、重打/换号会新增,存两份必然不一致)。
|
||||
单条失败原因:`未找到该运单号的取号记录(可能不是通过 OMS 取的号)` /
|
||||
|
||||
@ -2548,9 +2548,10 @@ class DgjService extends PrintPlatformService {
|
||||
* @param {Object} [options.checkData] CheckTemplateAvaliable 返回的 Data(DateNow / DayPrintBatchNumber / Branches)
|
||||
* @param {number} [options.packageCount] 包裹张数(默认 1):>1 时把同一订单行重复 N 份
|
||||
* @param {string} [options.expressCode] 快递编码(仅用于回传 WaybillCodes 时补 ExpressCpCode)
|
||||
* @param {boolean} [options.reprint] 是否「原单号打印」(复用平台已有运单号、不消耗面单;重打时用)
|
||||
* @return {Promise<Object>} 平台响应(Data.WaybillCode[] 含运单号与打印数据)
|
||||
*/
|
||||
async expressPrint(host, { traceId, dbname, templateId, rows, checkData, packageCount = 1, expressCode = '' }) {
|
||||
async expressPrint(host, { traceId, dbname, templateId, rows, checkData, packageCount = 1, expressCode = '', reprint = false }) {
|
||||
const data = checkData || {};
|
||||
const repeat = Number.isFinite(Number(packageCount)) && Number(packageCount) > 1 ? Math.floor(Number(packageCount)) : 1;
|
||||
const currentWaybillCode = (() => {
|
||||
@ -2632,9 +2633,10 @@ class DgjService extends PrintPlatformService {
|
||||
PackageCount: String(repeat),
|
||||
PackageDesc: '',
|
||||
GoodsDesc: '',
|
||||
PrintMethod: 'NewPrint',
|
||||
// 关键:false + NewPrint = 「新单号打印」(每次分配新号);true/Normal 会被平台复用旧号
|
||||
IsIgnoreWaybillRepeat: 'false',
|
||||
// 「原单号打印」(重打):PrintMethod=Normal + IsIgnoreWaybillRepeat=true 让平台复用已有运单号,
|
||||
// 只重新签发打印数据(params 里的签名会刷新),不消耗新面单
|
||||
PrintMethod: reprint ? 'Normal' : 'NewPrint',
|
||||
IsIgnoreWaybillRepeat: reprint ? 'true' : 'false',
|
||||
PrinterName: '默认打印机',
|
||||
IsPreview: 'false',
|
||||
IsContinueForStock: 'false',
|
||||
@ -2659,6 +2661,60 @@ class DgjService extends PrintPlatformService {
|
||||
return res.json;
|
||||
}
|
||||
|
||||
/**
|
||||
* 「原单号打印」重签打印数据(复用已有运单号,**不消耗面单**)
|
||||
*
|
||||
* `PrintHistory/LoadPrintData` 只回放历史签名(实测不会重签,10 分钟后必然过期),
|
||||
* 要新的 `params`(`access_token=…×tamp=…&sign=…`)只能让平台重新打印一次:
|
||||
* `PrintMethod=Normal + IsIgnoreWaybillRepeat=true` → 平台复用该订单已有运单号,只重新签发打印数据。
|
||||
* @param {string} host 平台域名
|
||||
* @param {Object} options 参数
|
||||
* @param {string} options.traceId 登录上下文 traceId
|
||||
* @param {string} options.dbname 分区库名
|
||||
* @param {string} options.templateId 面单模板ID
|
||||
* @param {Object} options.row 平台订单行(findPlatformOrderRow 的返回)
|
||||
* @param {string} [options.expressCode] 快递编码
|
||||
* @return {Promise<{waybill_codes: string[], documents: Array<{documentID: string, params: string, template_url: string}>, raw: Object}>} 重签结果
|
||||
*/
|
||||
async reprintPrintData(host, { traceId = '', dbname = '', templateId, row, expressCode = '' }) {
|
||||
if (!row) throw new Error('原单号打印需要平台订单行');
|
||||
const printed = await this.expressPrint(host, {
|
||||
traceId,
|
||||
dbname,
|
||||
templateId,
|
||||
rows: [ row ],
|
||||
checkData: {},
|
||||
expressCode,
|
||||
reprint: true,
|
||||
});
|
||||
|
||||
const errorItem = (Array.isArray(printed && printed.Data && printed.Data.WaybillCode) ? printed.Data.WaybillCode : [])
|
||||
.find(item => item && (item.IsError === true || Number(item.IsError) === 1));
|
||||
if (errorItem) {
|
||||
const reason = errorItem.ErrMsg || errorItem.ErrorMsg || '平台返回重打失败';
|
||||
throw buildPlatformError(`店管家原单号打印失败:${reason}`, { status: 200, json: printed, text: '' });
|
||||
}
|
||||
|
||||
const documents = [];
|
||||
const docs = printed && printed.Data && printed.Data.PrintDataList && printed.Data.PrintDataList.task &&
|
||||
printed.Data.PrintDataList.task.documents;
|
||||
for (const doc of Array.isArray(docs) ? docs : []) {
|
||||
const contents = Array.isArray(doc && doc.contents) ? doc.contents : [];
|
||||
const content = contents.find(item => item && String(item.params || '').trim()) || contents[0] || {};
|
||||
documents.push({
|
||||
documentID: String((doc && doc.documentID) || ''),
|
||||
params: String(content.params || ''),
|
||||
template_url: String(content.templateURL || ''),
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
waybill_codes: extractWaybillCodes(printed.Data && printed.Data.WaybillCode),
|
||||
documents,
|
||||
raw: printed,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 按打印记录重新拉取面单打印数据(只读,不消耗面单)
|
||||
*
|
||||
|
||||
@ -307,10 +307,23 @@ async function getPrintData(ctx, { principalId, warehouseId, data, requestId })
|
||||
}
|
||||
|
||||
/**
|
||||
* 按「账号 + 域名 + 分区」分组拉取打印数据
|
||||
* 从发货单号里取店管家系统编号(`dgj-10000280844952_2` → `10000280844952`)
|
||||
* @param {string} deliveryOrderCode 发货单号
|
||||
* @return {string} 系统编号
|
||||
*/
|
||||
function pickLogicalOrderId(deliveryOrderCode) {
|
||||
return String(deliveryOrderCode || '')
|
||||
.trim()
|
||||
.replace(/^[^-]+-/, '')
|
||||
.replace(/_\d+$/, '');
|
||||
}
|
||||
|
||||
/**
|
||||
* 按「账号 + 域名 + 分区」分组换取打印数据
|
||||
*
|
||||
* 平台侧对这个接口有限流,**一次只带一个 printHistoryId**,逐个串行请求并在两次之间留间隔,
|
||||
* 避免同店铺多张面单一起打过去被限流/超时。
|
||||
* 用「原单号打印」重签:平台复用订单已有运单号(**不消耗面单**)并重新签发 params。
|
||||
* `PrintHistory/LoadPrintData` 只是历史回放,不能用来换新签名。
|
||||
* 平台侧有限流,逐张串行并在两次之间留间隔。
|
||||
* @param {Object} ctx egg context
|
||||
* @param {Object} params 参数
|
||||
* @param {number} params.principalId 主体ID
|
||||
@ -329,7 +342,9 @@ async function fetchGroup(ctx, { principalId, memo, group }) {
|
||||
const entry = await loadAccount(ctx, memo, { accountId, principalId });
|
||||
if (!entry) return fallback('打单账号不存在或不属于该主体');
|
||||
const { service } = entry;
|
||||
if (typeof service.loadPrintData !== 'function') return fallback('当前打单平台不支持重新获取打印数据');
|
||||
if (typeof service.reprintPrintData !== 'function' || typeof service.findPlatformOrderRow !== 'function') {
|
||||
return fallback('当前打单平台不支持重新打印(原单号打印)');
|
||||
}
|
||||
|
||||
let traceId = '';
|
||||
try {
|
||||
@ -343,46 +358,81 @@ async function fetchGroup(ctx, { principalId, memo, group }) {
|
||||
for (let index = 0; index < items.length; index += 1) {
|
||||
const item = items[index];
|
||||
if (index > 0) await sleep(THROTTLE_MS);
|
||||
const base = {
|
||||
waybill_code: item.waybillCode,
|
||||
print_history_id: item.history.id,
|
||||
template_id: item.record.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 || '',
|
||||
};
|
||||
|
||||
const logicalOrderId = pickLogicalOrderId(item.record.delivery_order_code);
|
||||
if (!logicalOrderId) {
|
||||
results.push({ ...base, success: false, message: '取号记录缺少店管家系统编号,无法重打' });
|
||||
continue;
|
||||
}
|
||||
const templateId = String(item.record.template_id || '').trim();
|
||||
if (!templateId) {
|
||||
results.push({ ...base, success: false, message: '取号记录缺少面单模板ID,无法重打' });
|
||||
continue;
|
||||
}
|
||||
|
||||
let row = null;
|
||||
try {
|
||||
const list = await service.loadPrintData(host, {
|
||||
traceId,
|
||||
dbname,
|
||||
printHistoryIds: [ item.history.id ],
|
||||
});
|
||||
row = list[0] || null;
|
||||
row = await service.findPlatformOrderRow(host, { traceId, dbname, logicalOrderId });
|
||||
} catch (err) {
|
||||
ctx.logger.warn('[waybill.printdata] 换打印数据失败 host=%s dbname=%s id=%s:%s',
|
||||
host, dbname, item.history.id, err.message);
|
||||
results.push({ waybill_code: item.waybillCode, success: false, message: `读取打印数据失败:${err.message}` });
|
||||
results.push({ ...base, success: false, message: `回读平台订单失败:${err.message}` });
|
||||
continue;
|
||||
}
|
||||
if (!row) {
|
||||
results.push({ waybill_code: item.waybillCode, success: false, message: '平台未返回该运单号的打印数据' });
|
||||
results.push({ ...base, success: false, message: `店管家未找到订单:系统编号 ${logicalOrderId}` });
|
||||
continue;
|
||||
}
|
||||
const parsed = parsePrintData(row.print_data);
|
||||
if (!parsed.params) {
|
||||
results.push({ waybill_code: item.waybillCode, success: false, message: '平台的打印数据里没有 params(access_token 串)' });
|
||||
|
||||
let printed = null;
|
||||
try {
|
||||
printed = await service.reprintPrintData(host, {
|
||||
traceId,
|
||||
dbname,
|
||||
templateId,
|
||||
row,
|
||||
expressCode: item.record.express_code || '',
|
||||
});
|
||||
} catch (err) {
|
||||
ctx.logger.warn('[waybill.printdata] 原单号打印失败 host=%s dbname=%s id=%s:%s',
|
||||
host, dbname, logicalOrderId, err.message);
|
||||
results.push({ ...base, success: false, message: `重新打印失败:${err.message}` });
|
||||
continue;
|
||||
}
|
||||
const paramsTimestamp = pickParamsTimestamp(parsed.params);
|
||||
const expired = isParamsExpired(paramsTimestamp);
|
||||
|
||||
// 安全闸:原单号打印不该换号;换号说明平台发了新面单(已消耗),必须暴露出来
|
||||
const codes = Array.isArray(printed.waybill_codes) ? printed.waybill_codes.map(String) : [];
|
||||
if (codes.length && !codes.includes(String(item.waybillCode))) {
|
||||
ctx.logger.error('[waybill.printdata] 重打返回了新运单号,已消耗面单!原号=%s 新号=%s', item.waybillCode, codes.join(','));
|
||||
results.push({
|
||||
...base,
|
||||
success: false,
|
||||
message: `重打返回了新运单号 ${codes.join(',')}(原号 ${item.waybillCode}),已消耗面单,请人工核对`,
|
||||
});
|
||||
continue;
|
||||
}
|
||||
|
||||
const document = (printed.documents || []).find(doc => doc && String(doc.params || '').trim()) || (printed.documents || [])[0];
|
||||
if (!document || !document.params) {
|
||||
results.push({ ...base, success: false, message: '平台重打后没有返回 params(access_token 串)' });
|
||||
continue;
|
||||
}
|
||||
const paramsTimestamp = pickParamsTimestamp(document.params);
|
||||
results.push({
|
||||
waybill_code: item.waybillCode,
|
||||
...base,
|
||||
success: true,
|
||||
message: expired ? `平台返回的是打印记录里的原签名(${paramsTimestamp}),已超过 10 分钟有效期;要新签名需走「原单号打印」` : '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 || '',
|
||||
message: 'ok',
|
||||
expires_in: PRINT_DATA_TTL_SECONDS,
|
||||
// 打印端要的就是这串:access_token=...&app_key=...&method=logistics.getShopKey&...&sign=...
|
||||
params: parsed.params,
|
||||
// 签名时间与是否过期:LoadPrintData 只回放历史签名,不会重签
|
||||
params: document.params,
|
||||
params_timestamp: paramsTimestamp,
|
||||
params_expired: expired,
|
||||
template_url: parsed.template_url,
|
||||
params_expired: isParamsExpired(paramsTimestamp),
|
||||
template_url: document.template_url || '',
|
||||
});
|
||||
}
|
||||
return results;
|
||||
@ -398,4 +448,5 @@ module.exports = {
|
||||
parsePrintData,
|
||||
pickParamsTimestamp,
|
||||
isParamsExpired,
|
||||
pickLogicalOrderId,
|
||||
};
|
||||
|
||||
@ -42,6 +42,22 @@ describe('waybillPrintData 打印数据换取', () => {
|
||||
assert.strictEqual(printData.pickPrintHistory({}, 'A'), null);
|
||||
});
|
||||
|
||||
it('从发货单号解析店管家系统编号(去掉前缀与包裹序号)', () => {
|
||||
assert.strictEqual(printData.pickLogicalOrderId('dgj-10000280844952'), '10000280844952');
|
||||
assert.strictEqual(printData.pickLogicalOrderId('dgj-10000280844952_2'), '10000280844952');
|
||||
assert.strictEqual(printData.pickLogicalOrderId(''), '');
|
||||
});
|
||||
|
||||
it('签名时间与过期判断(平台有效期 10 分钟)', () => {
|
||||
assert.strictEqual(printData.pickParamsTimestamp('a=1×tamp=2026-11-07 06:59:00&v=2'), '2026-11-07 06:59:00');
|
||||
assert.strictEqual(printData.pickParamsTimestamp('a=1'), '');
|
||||
assert.strictEqual(printData.isParamsExpired('2026-11-07 06:59:00'), true);
|
||||
const now = new Date();
|
||||
const pad = n => String(n).padStart(2, '0');
|
||||
const nowText = `${now.getFullYear()}-${pad(now.getMonth() + 1)}-${pad(now.getDate())} ${pad(now.getHours())}:${pad(now.getMinutes())}:${pad(now.getSeconds())}`;
|
||||
assert.strictEqual(printData.isParamsExpired(nowText), false);
|
||||
});
|
||||
|
||||
it('解析平台返回的 params:拿到打印机配置、面单 document 与 access_token 串', () => {
|
||||
const params = JSON.stringify({
|
||||
id: null,
|
||||
|
||||
@ -275,11 +275,12 @@ WaybillCodeCreateDate='2026-11-04 08:20:37'
|
||||
- **打印数据(params)只有 10 分钟有效期**:`contents[].params` 是平台在**打印那一刻**签发的
|
||||
(`access_token=…&method=logistics.getShopKey×tamp=…&sign=…`,`timestamp` = 该打印记录的 `CreateDate`)。
|
||||
⚠️ 实测确认:`POST /PrintHistory/LoadPrintData` **只是回放那次打印的签名,不会重新签发**
|
||||
(换 `FxPageType=1/2`、加 `IsRePrint` / `IsRefresh` 都返回同一个 `timestamp`/`sign`),
|
||||
所以隔一段时间再取一定是过期的 —— 要新签名只能重新走「原单号打印」(`ExpressPrint` 复用已有运单号,不消耗面单),
|
||||
这条待与平台侧确认后接入(见 `WMS-OMS-取号对接.md` §4.7.1 的说明)。
|
||||
(换 `FxPageType=1/2`、加 `IsRePrint` / `IsRefresh` 都返回同一个 `timestamp`/`sign`)。
|
||||
✅ 要新签名只能让平台重新打印:`ExpressPrint` + `PrintMethod=Normal` + `IsIgnoreWaybillRepeat=true`
|
||||
→ 实测**复用订单已有运单号**(不消耗面单)、`params.timestamp` = 当前时间。
|
||||
对照:`PrintMethod=NewPrint`(或 `IsIgnoreWaybillRepeat=false`)会分配新号并消耗面单,重打绝不能用。
|
||||
因此取号记录里同时落了 `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`,
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user