feat: support Shopify PDF waybill printing

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
This commit is contained in:
liufumingren 2026-11-25 00:19:34 +08:00
parent 1e1c13f38c
commit e9d081ed4e
9 changed files with 312 additions and 32 deletions

1
.gitignore vendored
View File

@ -11,6 +11,7 @@ coverage/
typings/ typings/
tmp/* tmp/*
test/* test/*
!test/print_shopify_pdf.unit.test.js
npm-debug.log* npm-debug.log*
yarn-debug.log* yarn-debug.log*

View File

@ -67,6 +67,11 @@ const PLATFORM_MAP = Object.freeze({
aliases: [ 'xhs', 'xiaohongshu', 'red' ], aliases: [ 'xhs', 'xiaohongshu', 'red' ],
template_file: 'xhs.json', template_file: 'xhs.json',
}), }),
shopify: Object.freeze({
name: '本机组件',
aliases: [ 'shopify' ],
template_file: 'shopify.json',
}),
}); });
const PRIVATE_PAYLOAD_FIELDS = Object.freeze([ const PRIVATE_PAYLOAD_FIELDS = Object.freeze([

View File

@ -130,6 +130,11 @@ module.exports = app => {
allowNull: true, allowNull: true,
comment: '菜鸟授权网点ID(OMS 取号返回,打印按店铺分组用)', comment: '菜鸟授权网点ID(OMS 取号返回,打印按店铺分组用)',
}, },
pdf_base64: {
type: TEXT('long'),
allowNull: true,
comment: 'PDF面单 base64(部分PDF面单渠道取号返回,直接存储)',
},
warehouse_id: { warehouse_id: {
type: BIGINT(20).UNSIGNED, type: BIGINT(20).UNSIGNED,
allowNull: true, allowNull: true,

View File

@ -282,6 +282,81 @@ class PrintService extends MainService {
return lowerPlatformCode; return lowerPlatformCode;
} }
isShopifyPdfPlatform(platformCode) {
return String(platformCode || '').trim().toLowerCase() === 'shopify';
}
buildShopifyPdfPayload(payload = {}) {
const normalizedPayload = payload && typeof payload === 'object' ? payload : {};
const orders = Array.isArray(normalizedPayload.orders) ? normalizedPayload.orders : [];
const orderIds = Array.isArray(normalizedPayload.orderIds) ? normalizedPayload.orderIds : [];
const platformGroup = normalizedPayload.platformGroup && typeof normalizedPayload.platformGroup === 'object'
? normalizedPayload.platformGroup
: {};
const waveGroup = normalizedPayload.waveGroup && typeof normalizedPayload.waveGroup === 'object'
? normalizedPayload.waveGroup
: {};
const printerName = String(normalizedPayload.printerName || '').trim();
const printId = String(normalizedPayload.printId || '').trim();
const pdfOrders = orders.map((order, index) => {
if (!order || typeof order !== 'object' || Array.isArray(order)) {
throw new Error(`第 ${index + 1} 个 Shopify 面单数据无效`);
}
let contents = order.contents;
if (typeof contents === 'string') {
try {
contents = JSON.parse(contents);
} catch (error) {
throw new Error(`Shopify 面单 contents 格式无效: ${error.message}`);
}
}
const contentRows = Array.isArray(contents)
? contents
: (contents && typeof contents === 'object' && Array.isArray(contents.contents)
? contents.contents
: (contents && typeof contents === 'object' && Array.isArray(contents.documents)
? contents.documents
: []));
const pdfBase64 = String(
order.pdf_base64
|| (contentRows.find(item => item && typeof item.pdf_base64 === 'string') || {}).pdf_base64
|| ''
).trim();
const documentId = order.order_id
|| order.orderId
|| order.id
|| orderIds[index]
|| order.documentID
|| order.document_id;
if (!pdfBase64) {
throw new Error(`Shopify 面单 ${documentId || index + 1} 缺少 pdf_base64`);
}
return {
order_id: documentId === undefined || documentId === null ? null : String(documentId),
pdf_base64: pdfBase64,
};
});
return {
printer: printerName,
printId,
payload: [{
wave_id: waveGroup.wave_id === undefined ? null : waveGroup.wave_id,
wave_no: waveGroup.wave_no || null,
platforms: [{
platform: platformGroup.platform || 'SHOPIFY',
platform_name: platformGroup.platform_name || null,
order_ids: orderIds,
printer: printerName,
orders: pdfOrders,
}],
}],
};
}
/** /**
* 从打印记录 data 中提取订单ID列表。 * 从打印记录 data 中提取订单ID列表。
* 兼容 data 为对象或 JSON 字符串,无法识别时返回空数组。 * 兼容 data 为对象或 JSON 字符串,无法识别时返回空数组。
@ -927,7 +1002,10 @@ class PrintService extends MainService {
} }
const platformCodes = this.collectExpressPlatformCodes(data.waveGroups); const platformCodes = this.collectExpressPlatformCodes(data.waveGroups);
const platformComponentsResult = await this.loadExpressPlatformComponents({ platformCodes }); const componentPlatformCodes = platformCodes.filter(platformCode => !this.isShopifyPdfPlatform(platformCode));
const platformComponentsResult = platformCodes.length > 0 && componentPlatformCodes.length === 0
? { success: true, data: {} }
: await this.loadExpressPlatformComponents({ platformCodes: componentPlatformCodes });
if (!platformComponentsResult.success) { if (!platformComponentsResult.success) {
this.ctx.logger.error('[print.send] 最终返回 failure', { this.ctx.logger.error('[print.send] 最终返回 failure', {
warehouseId, warehouseId,
@ -2274,11 +2352,12 @@ class PrintService extends MainService {
this.ctx.logger.info('[print.send] 平台快递组发送开始', groupSummary); this.ctx.logger.info('[print.send] 平台快递组发送开始', groupSummary);
const platformCode = String(platformGroup && platformGroup.platform ? platformGroup.platform : '').trim(); const platformCode = String(platformGroup && platformGroup.platform ? platformGroup.platform : '').trim();
const isShopifyPdf = this.isShopifyPdfPlatform(platformCode);
const component = String( const component = String(
normalizedPayload.platformComponents normalizedPayload.platformComponents
&& normalizedPayload.platformComponents[platformCode] && normalizedPayload.platformComponents[platformCode]
? normalizedPayload.platformComponents[platformCode] ? normalizedPayload.platformComponents[platformCode]
: '' : (isShopifyPdf ? 'PDF' : '')
).trim(); ).trim();
if (!component) { if (!component) {
this.ctx.logger.error('[print.send] 平台快递组发送失败-打印组件缺失', { this.ctx.logger.error('[print.send] 平台快递组发送失败-打印组件缺失', {
@ -2358,17 +2437,30 @@ class PrintService extends MainService {
let requestPayload; let requestPayload;
let currentTaskCode = ''; let currentTaskCode = '';
try { try {
requestPayload = normalizedPayload.payloadBuilder.buildPayload({ if (isShopifyPdf) {
platform: platformGroup && platformGroup.platform, requestPayload = this.buildShopifyPdfPayload({
printerName: printerNameResult.data, waveGroup,
orders: batchOrders, platformGroup,
idGenerator: normalizedPayload.idGenerator, orders: batchOrders,
}); orderIds: batchOrderIds,
if (isKuaishouPlatform && requestPayload && requestPayload.task && typeof requestPayload.task === 'object' && !Array.isArray(requestPayload.task)) { printerName: currentPrinterName,
requestPayload.task.firstDocumentNumber = batchIndex * 10 + 1; });
requestPayload.task.totalDocumentCount = totalDocumentCount; } else {
requestPayload = normalizedPayload.payloadBuilder.buildPayload({
platform: platformGroup && platformGroup.platform,
printerName: printerNameResult.data,
orders: batchOrders,
idGenerator: normalizedPayload.idGenerator,
});
if (isKuaishouPlatform && requestPayload && requestPayload.task && typeof requestPayload.task === 'object' && !Array.isArray(requestPayload.task)) {
requestPayload.task.firstDocumentNumber = batchIndex * 10 + 1;
requestPayload.task.totalDocumentCount = totalDocumentCount;
}
} }
currentTaskCode = await this.reserveUniquePrintTaskCode(); currentTaskCode = await this.reserveUniquePrintTaskCode();
if (isShopifyPdf) {
requestPayload.printId = currentTaskCode;
}
if (requestPayload.task && typeof requestPayload.task === 'object' && !Array.isArray(requestPayload.task)) { if (requestPayload.task && typeof requestPayload.task === 'object' && !Array.isArray(requestPayload.task)) {
requestPayload.task.taskID = currentTaskCode; requestPayload.task.taskID = currentTaskCode;
} }
@ -2381,7 +2473,7 @@ class PrintService extends MainService {
...batchSummary, ...batchSummary,
platform: platformGroup && platformGroup.platform ? platformGroup.platform : '', platform: platformGroup && platformGroup.platform ? platformGroup.platform : '',
ordersCount: batchOrders.length, ordersCount: batchOrders.length,
documentCount: payloadSummary.documentCount, documentCount: isShopifyPdf ? batchOrders.length : payloadSummary.documentCount,
}); });
} catch (error) { } catch (error) {
this.ctx.logger.error('[print.send] 组装 payload 失败', { this.ctx.logger.error('[print.send] 组装 payload 失败', {
@ -2417,13 +2509,21 @@ class PrintService extends MainService {
platform_name: platformName, platform_name: platformName,
sys_logistics_code: sysLogisticsCode, sys_logistics_code: sysLogisticsCode,
sys_logistics_name: sysLogisticsName, sys_logistics_name: sysLogisticsName,
data: { data: isShopifyPdf
printer: currentPrinterName, ? {
component, ...requestPayload,
type: 'express', component,
order_ids: batchOrderIds, type: 'express',
data: requestPayload, order_ids: batchOrderIds,
}, print_method: 'printer.printPdf',
}
: {
printer: currentPrinterName,
component,
type: 'express',
order_ids: batchOrderIds,
data: requestPayload,
},
})); }));
createdPrintRecordIds.push(currentPrintRecord.id); createdPrintRecordIds.push(currentPrintRecord.id);
this.ctx.logger.info('[print.send] PrintRecord 创建成功', { this.ctx.logger.info('[print.send] PrintRecord 创建成功', {
@ -2448,14 +2548,21 @@ class PrintService extends MainService {
}; };
} }
const printData = { const printData = isShopifyPdf
printer: currentPrinterName, ? {
component, ...requestPayload,
type: 'express', component,
order_ids: batchOrderIds, type: 'express',
data: requestPayload, order_ids: batchOrderIds,
printId: currentPrintRecord.id, }
}; : {
printer: currentPrinterName,
component,
type: 'express',
order_ids: batchOrderIds,
data: requestPayload,
printId: currentPrintRecord.id,
};
const sendStartAt = Date.now(); const sendStartAt = Date.now();
let sendResult; let sendResult;
try { try {
@ -2463,6 +2570,7 @@ class PrintService extends MainService {
warehouse: normalizedPayload.warehouseId, warehouse: normalizedPayload.warehouseId,
computerId: normalizedPayload.printStation.computer_id, computerId: normalizedPayload.printStation.computer_id,
data: printData, data: printData,
printMethod: isShopifyPdf ? 'printer.printPdf' : 'printer.print',
}); });
} catch (error) { } catch (error) {
const sendDurationMs = Date.now() - sendStartAt; const sendDurationMs = Date.now() - sendStartAt;

View File

@ -54,6 +54,7 @@ const ORDER_EXPRESS_UPSTREAM_OPTIONAL_FIELDS = Object.freeze([
'encryptprintinfo', 'encryptprintinfo',
'encryptedtoken', 'encryptedtoken',
'ver', 'ver',
'pdf_base64',
]); ]);
/** OMS 取号请求/返回报文缓存 TTL(秒):覆盖一个工作日,便于事后核对报文格式。 */ /** OMS 取号请求/返回报文缓存 TTL(秒):覆盖一个工作日,便于事后核对报文格式。 */
@ -72,6 +73,7 @@ const OMS_WAYBILL_PAYLOAD_HEAVY_FIELDS = Object.freeze([
'encryptprintinfo', 'encryptprintinfo',
'encryptedtoken', 'encryptedtoken',
'signature', 'signature',
'pdf_base64',
]); ]);
/** 大字段脱敏后保留的字符数(用于人工核对字段内容前缀)。 */ /** 大字段脱敏后保留的字符数(用于人工核对字段内容前缀)。 */
@ -1613,6 +1615,7 @@ class ExpressPlatformService extends MainService {
orderExpressValues: { orderExpressValues: {
waybill_code: waybillCode, waybill_code: waybillCode,
printinfo: item.printinfo, printinfo: item.printinfo,
pdf_base64: String(item.pdf_base64 || '').trim() || null,
signature: item.signature, signature: item.signature,
encryptprintinfo: item.encryptprintinfo, encryptprintinfo: item.encryptprintinfo,
encryptedtoken: item.encryptedtoken, encryptedtoken: item.encryptedtoken,
@ -3690,6 +3693,7 @@ class ExpressPlatformService extends MainService {
|| '' || ''
) || null, ) || null,
ver: String(row.ver || '') || null, ver: String(row.ver || '') || null,
pdf_base64: String(row.pdf_base64 || '') || null,
}); });
if (platformCode) { if (platformCode) {
orderExpressValues.platform_code = platformCode; orderExpressValues.platform_code = platformCode;

View File

@ -1319,6 +1319,7 @@ class OrderPrintSystemService extends OrderBaseService {
'ver', 'ver',
'print_history_id', 'print_history_id',
'cai_niao_auth_info_id', 'cai_niao_auth_info_id',
'pdf_base64',
], ],
where: { where: {
waybill_code: { waybill_code: {
@ -2056,6 +2057,7 @@ class OrderPrintSystemService extends OrderBaseService {
'ver', 'ver',
'print_history_id', 'print_history_id',
'cai_niao_auth_info_id', 'cai_niao_auth_info_id',
'pdf_base64',
], ],
where: { where: {
order_id: { order_id: {
@ -2424,6 +2426,16 @@ ${waveFilterSql}
return PrinterDataBuilder.normalizePlatformAlias(platformCode).platform === 'douyin'; return PrinterDataBuilder.normalizePlatformAlias(platformCode).platform === 'douyin';
} }
/**
* 判断平台编码是否为 Shopify(PDF 面单,直接透传 pdf_base64)。
*
* @param {string} platformCode 平台编码。
* @return {boolean} 是否为 Shopify 平台。
*/
isShopifyPlatformCode(platformCode = '') {
return PrinterDataBuilder.normalizePlatformAlias(platformCode).platform === 'shopify';
}
/** /**
* 收集菜鸟编码映射可能命中的快递编码候选项。 * 收集菜鸟编码映射可能命中的快递编码候选项。
* *
@ -3621,6 +3633,10 @@ ${waveFilterSql}
* @return {Object} 模板样例对象。 * @return {Object} 模板样例对象。
*/ */
loadTemplateSampleByPlatform(platformCode, cache) { loadTemplateSampleByPlatform(platformCode, cache) {
if (this.isShopifyPlatformCode(platformCode)) {
return {};
}
const normalized = PrinterDataBuilder.normalizePlatformAlias(platformCode); const normalized = PrinterDataBuilder.normalizePlatformAlias(platformCode);
const cacheKey = normalized.meta && normalized.meta.template_file const cacheKey = normalized.meta && normalized.meta.template_file
? normalized.meta.template_file ? normalized.meta.template_file
@ -3737,9 +3753,16 @@ ${waveFilterSql}
customAreaBaseUrl: this.ctx.app.config.customAreaBaseUrl || '', customAreaBaseUrl: this.ctx.app.config.customAreaBaseUrl || '',
}, },
}); });
const printData = this.extractSinglePlatformPrintData(printPayload); let printData = this.extractSinglePlatformPrintData(printPayload);
// 子面单场景:同一运单号可能对应多个 business_key,注入 business_key 到返回文档中供调用方区分 if (this.isShopifyPlatformCode(platformCode)) {
if (printData && typeof printData === 'object' && !Array.isArray(printData)) { // Shopify PDF 放入前端可提取的 document.contents 结构中,不套平台模板骨架
const pdfBase64 = String(orderExpress.pdf_base64 || '').trim();
printData = {
documentID: documentId,
contents: pdfBase64 ? [{ pdf_base64: pdfBase64 }] : [],
};
} else if (printData && typeof printData === 'object' && !Array.isArray(printData)) {
// 子面单场景:同一运单号可能对应多个 business_key,注入 business_key 到返回文档中供调用方区分
const expressBusinessKey = Number(orderExpress.business_key || 1); const expressBusinessKey = Number(orderExpress.business_key || 1);
if (expressBusinessKey > 1) { if (expressBusinessKey > 1) {
printData.business_key = expressBusinessKey; printData.business_key = expressBusinessKey;

View File

@ -4,7 +4,11 @@ const Service = require('egg').Service;
class PrintService extends Service { class PrintService extends Service {
// 发送信息到打印电脑 // 发送信息到打印电脑
async sendToComputer({ warehouse, computerId, data }) { async sendToComputer({ warehouse, computerId, data, printMethod = 'printer.print' }) {
if (![ 'printer.print', 'printer.printPdf' ].includes(printMethod)) {
throw new Error(`不支持的打印方法: ${printMethod}`);
}
// 发送指令更新打印机状态 // 发送指令更新打印机状态
const printServiceUrl = this.ctx.app.config.printService.url; const printServiceUrl = this.ctx.app.config.printService.url;
// 先获取redis中打印机列表 // 先获取redis中打印机列表
@ -51,7 +55,7 @@ class PrintService extends Service {
const res = await this.ctx.curl(`${printServiceUrl}/sendToRoom`, { const res = await this.ctx.curl(`${printServiceUrl}/sendToRoom`, {
method: 'POST', method: 'POST',
contentType: 'json', contentType: 'json',
data: { warehouse, computerId, method: 'printer.print', data }, data: { warehouse, computerId, method: printMethod, data },
dataType: 'json', dataType: 'json',
}); });
return res.data; return res.data;

View File

@ -0,0 +1,47 @@
'use strict';
/**
* 为运单表新增 PDF 面单 base64 字段。
*
* - `pdf_base64`:部分 PDF 面单渠道取号返回的面单 PDF base64,直接落库。
*/
module.exports = {
/**
* 执行迁移:新增 pdf_base64(幂等)。
*
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
* @param {import('sequelize')} Sequelize Sequelize 实例。
* @return {Promise<void>} 无返回值。
*/
async up(queryInterface, Sequelize) {
const tableName = 'wms_order_express';
const columns = await queryInterface.describeTable(tableName);
if (columns.pdf_base64) {
return;
}
// 拿不到元数据锁时快速失败:MDL 排队会把后续所有读写一起堵住,
// 30 秒内拿不到锁就报错退出(可安全重试),避免拖垮生产可用性
await queryInterface.sequelize.query('SET SESSION lock_wait_timeout = 30');
await queryInterface.sequelize.query(
`ALTER TABLE \`${tableName}\` ADD COLUMN \`pdf_base64\` ${Sequelize.TEXT('long')} NULL DEFAULT NULL COMMENT 'PDF面单 base64(部分PDF面单渠道取号返回,直接存储)' AFTER \`cai_niao_auth_info_id\``
);
},
/**
* 回滚迁移:删除新增字段(幂等)。
*
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
* @return {Promise<void>} 无返回值。
*/
async down(queryInterface) {
const tableName = 'wms_order_express';
const columns = await queryInterface.describeTable(tableName);
if (columns.pdf_base64) {
await queryInterface.removeColumn(tableName, 'pdf_base64');
}
},
};

View File

@ -0,0 +1,83 @@
'use strict';
const assert = require('assert');
const PrintService = require('../app/service/systemMethods/print');
const PrintClientService = require('../app/service/systems/print');
describe('Shopify PDF print payload', () => {
const service = Object.create(PrintService.prototype);
it('recognizes Shopify platform codes without case sensitivity', () => {
assert.strictEqual(service.isShopifyPdfPlatform('SHOPIFY'), true);
assert.strictEqual(service.isShopifyPdfPlatform('shopify'), true);
assert.strictEqual(service.isShopifyPdfPlatform('amazon'), false);
});
it('converts contents pdf_base64 into the printPdf payload shape', () => {
const result = service.buildShopifyPdfPayload({
waveGroup: { wave_id: 12, wave_no: 'W-12' },
platformGroup: { platform: 'SHOPIFY', platform_name: 'Shopify' },
orders: [{
documentID: 'WAYBILL-1',
contents: [{ pdf_base64: 'JVBERi0xLjQ=' }],
}],
orderIds: [ 321 ],
printerName: 'Label Printer',
printId: 'task-12',
});
assert.deepStrictEqual(result.payload[0].platforms[0].orders, [{
order_id: '321',
pdf_base64: 'JVBERi0xLjQ=',
}]);
assert.strictEqual(result.printer, 'Label Printer');
assert.strictEqual(result.printId, 'task-12');
});
it('rejects Shopify orders without PDF data', () => {
assert.throws(
() => service.buildShopifyPdfPayload({
orders: [{ documentID: 'WAYBILL-1', contents: [] }],
}),
/缺少 pdf_base64/
);
});
it('sends PDF jobs through the printPdf method', async () => {
const calls = [];
const redisValues = {};
const printerRedis = {
get: async key => redisValues[key] || null,
set: async (key, value) => {
redisValues[key] = value;
},
};
const client = Object.create(PrintClientService.prototype);
client.ctx = {
app: {
config: { printService: { url: 'http://print-service' } },
redis: { get: () => printerRedis },
},
curl: async (url, options) => {
calls.push(options.data.method);
if (options.data.method === 'printer.getWindowsPrinters') {
await printerRedis.set('printer:2:printerList', JSON.stringify({
updatedAt: Date.now() + 1,
data: [{ name: 'Label Printer', workOffline: 'FALSE' }],
}));
}
return { data: { status: 'success' } };
},
};
client.app = client.ctx.app;
await client.sendToComputer({
warehouse: '1',
computerId: '2',
data: { printer: 'Label Printer' },
printMethod: 'printer.printPdf',
});
assert.deepStrictEqual(calls, [ 'printer.getWindowsPrinters', 'printer.printPdf' ]);
});
});