feat: support Shopify PDF waybill printing
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
This commit is contained in:
parent
1e1c13f38c
commit
e9d081ed4e
1
.gitignore
vendored
1
.gitignore
vendored
@ -11,6 +11,7 @@ coverage/
|
||||
typings/
|
||||
tmp/*
|
||||
test/*
|
||||
!test/print_shopify_pdf.unit.test.js
|
||||
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
|
||||
@ -67,6 +67,11 @@ const PLATFORM_MAP = Object.freeze({
|
||||
aliases: [ 'xhs', 'xiaohongshu', 'red' ],
|
||||
template_file: 'xhs.json',
|
||||
}),
|
||||
shopify: Object.freeze({
|
||||
name: '本机组件',
|
||||
aliases: [ 'shopify' ],
|
||||
template_file: 'shopify.json',
|
||||
}),
|
||||
});
|
||||
|
||||
const PRIVATE_PAYLOAD_FIELDS = Object.freeze([
|
||||
|
||||
@ -130,6 +130,11 @@ module.exports = app => {
|
||||
allowNull: true,
|
||||
comment: '菜鸟授权网点ID(OMS 取号返回,打印按店铺分组用)',
|
||||
},
|
||||
pdf_base64: {
|
||||
type: TEXT('long'),
|
||||
allowNull: true,
|
||||
comment: 'PDF面单 base64(部分PDF面单渠道取号返回,直接存储)',
|
||||
},
|
||||
warehouse_id: {
|
||||
type: BIGINT(20).UNSIGNED,
|
||||
allowNull: true,
|
||||
|
||||
@ -282,6 +282,81 @@ class PrintService extends MainService {
|
||||
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 为对象或 JSON 字符串,无法识别时返回空数组。
|
||||
@ -927,7 +1002,10 @@ class PrintService extends MainService {
|
||||
}
|
||||
|
||||
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) {
|
||||
this.ctx.logger.error('[print.send] 最终返回 failure', {
|
||||
warehouseId,
|
||||
@ -2274,11 +2352,12 @@ class PrintService extends MainService {
|
||||
this.ctx.logger.info('[print.send] 平台快递组发送开始', groupSummary);
|
||||
|
||||
const platformCode = String(platformGroup && platformGroup.platform ? platformGroup.platform : '').trim();
|
||||
const isShopifyPdf = this.isShopifyPdfPlatform(platformCode);
|
||||
const component = String(
|
||||
normalizedPayload.platformComponents
|
||||
&& normalizedPayload.platformComponents[platformCode]
|
||||
? normalizedPayload.platformComponents[platformCode]
|
||||
: ''
|
||||
: (isShopifyPdf ? 'PDF' : '')
|
||||
).trim();
|
||||
if (!component) {
|
||||
this.ctx.logger.error('[print.send] 平台快递组发送失败-打印组件缺失', {
|
||||
@ -2358,17 +2437,30 @@ class PrintService extends MainService {
|
||||
let requestPayload;
|
||||
let currentTaskCode = '';
|
||||
try {
|
||||
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;
|
||||
if (isShopifyPdf) {
|
||||
requestPayload = this.buildShopifyPdfPayload({
|
||||
waveGroup,
|
||||
platformGroup,
|
||||
orders: batchOrders,
|
||||
orderIds: batchOrderIds,
|
||||
printerName: currentPrinterName,
|
||||
});
|
||||
} 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();
|
||||
if (isShopifyPdf) {
|
||||
requestPayload.printId = currentTaskCode;
|
||||
}
|
||||
if (requestPayload.task && typeof requestPayload.task === 'object' && !Array.isArray(requestPayload.task)) {
|
||||
requestPayload.task.taskID = currentTaskCode;
|
||||
}
|
||||
@ -2381,7 +2473,7 @@ class PrintService extends MainService {
|
||||
...batchSummary,
|
||||
platform: platformGroup && platformGroup.platform ? platformGroup.platform : '',
|
||||
ordersCount: batchOrders.length,
|
||||
documentCount: payloadSummary.documentCount,
|
||||
documentCount: isShopifyPdf ? batchOrders.length : payloadSummary.documentCount,
|
||||
});
|
||||
} catch (error) {
|
||||
this.ctx.logger.error('[print.send] 组装 payload 失败', {
|
||||
@ -2417,13 +2509,21 @@ class PrintService extends MainService {
|
||||
platform_name: platformName,
|
||||
sys_logistics_code: sysLogisticsCode,
|
||||
sys_logistics_name: sysLogisticsName,
|
||||
data: {
|
||||
printer: currentPrinterName,
|
||||
component,
|
||||
type: 'express',
|
||||
order_ids: batchOrderIds,
|
||||
data: requestPayload,
|
||||
},
|
||||
data: isShopifyPdf
|
||||
? {
|
||||
...requestPayload,
|
||||
component,
|
||||
type: 'express',
|
||||
order_ids: batchOrderIds,
|
||||
print_method: 'printer.printPdf',
|
||||
}
|
||||
: {
|
||||
printer: currentPrinterName,
|
||||
component,
|
||||
type: 'express',
|
||||
order_ids: batchOrderIds,
|
||||
data: requestPayload,
|
||||
},
|
||||
}));
|
||||
createdPrintRecordIds.push(currentPrintRecord.id);
|
||||
this.ctx.logger.info('[print.send] PrintRecord 创建成功', {
|
||||
@ -2448,14 +2548,21 @@ class PrintService extends MainService {
|
||||
};
|
||||
}
|
||||
|
||||
const printData = {
|
||||
printer: currentPrinterName,
|
||||
component,
|
||||
type: 'express',
|
||||
order_ids: batchOrderIds,
|
||||
data: requestPayload,
|
||||
printId: currentPrintRecord.id,
|
||||
};
|
||||
const printData = isShopifyPdf
|
||||
? {
|
||||
...requestPayload,
|
||||
component,
|
||||
type: 'express',
|
||||
order_ids: batchOrderIds,
|
||||
}
|
||||
: {
|
||||
printer: currentPrinterName,
|
||||
component,
|
||||
type: 'express',
|
||||
order_ids: batchOrderIds,
|
||||
data: requestPayload,
|
||||
printId: currentPrintRecord.id,
|
||||
};
|
||||
const sendStartAt = Date.now();
|
||||
let sendResult;
|
||||
try {
|
||||
@ -2463,6 +2570,7 @@ class PrintService extends MainService {
|
||||
warehouse: normalizedPayload.warehouseId,
|
||||
computerId: normalizedPayload.printStation.computer_id,
|
||||
data: printData,
|
||||
printMethod: isShopifyPdf ? 'printer.printPdf' : 'printer.print',
|
||||
});
|
||||
} catch (error) {
|
||||
const sendDurationMs = Date.now() - sendStartAt;
|
||||
|
||||
@ -54,6 +54,7 @@ const ORDER_EXPRESS_UPSTREAM_OPTIONAL_FIELDS = Object.freeze([
|
||||
'encryptprintinfo',
|
||||
'encryptedtoken',
|
||||
'ver',
|
||||
'pdf_base64',
|
||||
]);
|
||||
|
||||
/** OMS 取号请求/返回报文缓存 TTL(秒):覆盖一个工作日,便于事后核对报文格式。 */
|
||||
@ -72,6 +73,7 @@ const OMS_WAYBILL_PAYLOAD_HEAVY_FIELDS = Object.freeze([
|
||||
'encryptprintinfo',
|
||||
'encryptedtoken',
|
||||
'signature',
|
||||
'pdf_base64',
|
||||
]);
|
||||
|
||||
/** 大字段脱敏后保留的字符数(用于人工核对字段内容前缀)。 */
|
||||
@ -1613,6 +1615,7 @@ class ExpressPlatformService extends MainService {
|
||||
orderExpressValues: {
|
||||
waybill_code: waybillCode,
|
||||
printinfo: item.printinfo,
|
||||
pdf_base64: String(item.pdf_base64 || '').trim() || null,
|
||||
signature: item.signature,
|
||||
encryptprintinfo: item.encryptprintinfo,
|
||||
encryptedtoken: item.encryptedtoken,
|
||||
@ -3690,6 +3693,7 @@ class ExpressPlatformService extends MainService {
|
||||
|| ''
|
||||
) || null,
|
||||
ver: String(row.ver || '') || null,
|
||||
pdf_base64: String(row.pdf_base64 || '') || null,
|
||||
});
|
||||
if (platformCode) {
|
||||
orderExpressValues.platform_code = platformCode;
|
||||
|
||||
@ -1319,6 +1319,7 @@ class OrderPrintSystemService extends OrderBaseService {
|
||||
'ver',
|
||||
'print_history_id',
|
||||
'cai_niao_auth_info_id',
|
||||
'pdf_base64',
|
||||
],
|
||||
where: {
|
||||
waybill_code: {
|
||||
@ -2056,6 +2057,7 @@ class OrderPrintSystemService extends OrderBaseService {
|
||||
'ver',
|
||||
'print_history_id',
|
||||
'cai_niao_auth_info_id',
|
||||
'pdf_base64',
|
||||
],
|
||||
where: {
|
||||
order_id: {
|
||||
@ -2424,6 +2426,16 @@ ${waveFilterSql}
|
||||
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} 模板样例对象。
|
||||
*/
|
||||
loadTemplateSampleByPlatform(platformCode, cache) {
|
||||
if (this.isShopifyPlatformCode(platformCode)) {
|
||||
return {};
|
||||
}
|
||||
|
||||
const normalized = PrinterDataBuilder.normalizePlatformAlias(platformCode);
|
||||
const cacheKey = normalized.meta && normalized.meta.template_file
|
||||
? normalized.meta.template_file
|
||||
@ -3737,9 +3753,16 @@ ${waveFilterSql}
|
||||
customAreaBaseUrl: this.ctx.app.config.customAreaBaseUrl || '',
|
||||
},
|
||||
});
|
||||
const printData = this.extractSinglePlatformPrintData(printPayload);
|
||||
// 子面单场景:同一运单号可能对应多个 business_key,注入 business_key 到返回文档中供调用方区分
|
||||
if (printData && typeof printData === 'object' && !Array.isArray(printData)) {
|
||||
let printData = this.extractSinglePlatformPrintData(printPayload);
|
||||
if (this.isShopifyPlatformCode(platformCode)) {
|
||||
// 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);
|
||||
if (expressBusinessKey > 1) {
|
||||
printData.business_key = expressBusinessKey;
|
||||
|
||||
@ -4,7 +4,11 @@ const Service = require('egg').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;
|
||||
// 先获取redis中打印机列表
|
||||
@ -51,7 +55,7 @@ class PrintService extends Service {
|
||||
const res = await this.ctx.curl(`${printServiceUrl}/sendToRoom`, {
|
||||
method: 'POST',
|
||||
contentType: 'json',
|
||||
data: { warehouse, computerId, method: 'printer.print', data },
|
||||
data: { warehouse, computerId, method: printMethod, data },
|
||||
dataType: 'json',
|
||||
});
|
||||
return res.data;
|
||||
|
||||
@ -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');
|
||||
}
|
||||
},
|
||||
};
|
||||
83
test/print_shopify_pdf.unit.test.js
Normal file
83
test/print_shopify_pdf.unit.test.js
Normal 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' ]);
|
||||
});
|
||||
});
|
||||
Loading…
x
Reference in New Issue
Block a user