'use strict'; const fs = require('node:fs'); const path = require('node:path'); const PrinterDataBuilder = require('./printer_data_builder'); const TEMPLATE_CACHE = new Map(); /** * 判断是否为普通对象。 * @param {any} value 待判断值。 * @return {boolean} 判断结果。 */ function isPlainObject(value) { return value !== null && typeof value === 'object' && !Array.isArray(value); } /** * 以 JSON 方式做深拷贝,避免污染模板缓存对象。 * @param {Object} source 原对象。 * @return {Object} 深拷贝结果。 */ function deepClone(source) { return JSON.parse(JSON.stringify(source)); } /** * 请求内 ID 生成器。 */ class RequestScopedPrintIdGenerator { /** * @param {string} requestCode 前端请求参数码。 */ constructor(requestCode) { this.requestCode = String(requestCode || '').trim(); this.sequence = 0; } /** * 生成请求 ID。 * @return {string} 唯一请求 ID。 */ nextRequestId() { return this.next('request'); } /** * 生成任务 ID。 * @return {string} 唯一任务 ID。 */ nextTaskId() { return this.next('task'); } /** * 生成文档 ID。 * @return {string} 唯一文档 ID。 */ nextDocumentId() { return this.next('document'); } /** * 生成带前缀的递增 ID。 * @param {string} prefix ID 前缀。 * @return {string} 生成结果。 */ next(prefix) { this.sequence += 1; return `${this.requestCode}_${prefix}_${this.sequence}`; } } /** * 快递打印请求组装器。 */ class ExpressPrintPayloadBuilder { /** * @param {Object} options 初始化参数。 * @param {string} options.baseDir 项目根目录。 */ constructor(options = {}) { const requestOptions = isPlainObject(options) ? options : {}; this.baseDir = String(requestOptions.baseDir || process.cwd()); this.templateDir = path.join(this.baseDir, 'printer_data_template'); } /** * 组装平台快递打印 payload。 * @param {Object} options 组装参数。 * @param {string} options.platform 平台编码。 * @param {string} options.printerName 打印机名称。 * @param {Array} options.orders 外部传入的订单打印数据数组。 * @param {RequestScopedPrintIdGenerator} options.idGenerator 请求内 ID 生成器。 * @return {Object} 可直接发送给打印服务的 payload。 */ buildPayload(options = {}) { const requestOptions = isPlainObject(options) ? options : {}; const platform = String(requestOptions.platform || '').trim(); const normalizedPlatform = this.normalizePlatform(platform); if (!platform) { throw new Error('快递打印缺少平台标识'); } const idGenerator = requestOptions.idGenerator; if (!idGenerator || typeof idGenerator.nextRequestId !== 'function') { throw new Error('快递打印缺少请求 ID 生成器'); } const printerName = String(requestOptions.printerName || '').trim(); if (!printerName) { throw new Error('快递打印缺少打印机名称'); } const orders = Array.isArray(requestOptions.orders) ? requestOptions.orders : []; if (orders.length === 0) { throw new Error('快递打印缺少订单数据'); } const payload = this.loadTemplate(platform); const requestId = idGenerator.nextRequestId(); this.applyRequestId(payload, requestId); payload.printer = printerName; if (Array.isArray(payload.taskList)) { payload.taskList.forEach(item => { if (isPlainObject(item)) { item.printer = printerName; } }); } if (normalizedPlatform === 'sph') { payload.taskList = this.buildTaskListFromOrders(orders, idGenerator); } else { if (!isPlainObject(payload.task)) { payload.task = {}; } payload.task.taskID = idGenerator.nextTaskId(); payload.task.printer = printerName; payload.task.documents = this.buildDocumentsFromOrders(orders, idGenerator); } if (normalizedPlatform === 'jd') { this.mergeJdParametersContents(payload, printerName); } return payload; } /** * 将京东平台模板参数中的 contents 替换为订单实际内容。 * @param {Object} payload 打印请求 payload。 * @param {string} printerName 打印机名称。 */ mergeJdParametersContents(payload, printerName) { if (!isPlainObject(payload.parameters)) { payload.parameters = {}; } payload.parameters.printName = printerName; const documents = Array.isArray(payload.task && payload.task.documents) ? payload.task.documents : []; payload.parameters.contents = documents.map(document => { if (!isPlainObject(document) || !Array.isArray(document.contents) || !document.contents[0]) { return {}; } return deepClone(document.contents[0]); }); } /** * 将 orders 映射为 SPH taskList 项。 * SPH 的 task item 结构(taskID / printInfo / customInfo / extendData 等)与通用 document 结构不兼容, * 因此需要独立的构建方法,但处理模式与 buildDocumentsFromOrders 一致: * 遍历 orders → deepClone → 分配唯一 ID → 放入数组。 * * @param {Array} orders 订单数组,每个元素直接是 SPH task item 对象。 * @param {RequestScopedPrintIdGenerator} idGenerator 请求内 ID 生成器。 * @return {Array} taskList 数组。 */ buildTaskListFromOrders(orders, idGenerator) { const taskList = []; for (const order of orders) { if (order && typeof order === 'object' && !Array.isArray(order)) { const taskItem = deepClone(order); taskItem.taskID = idGenerator.nextTaskId(); taskList.push(taskItem); } } return taskList; } /** * 将 orders 映射为 documents。 * @param {Array} orders 订单数组。 * @param {RequestScopedPrintIdGenerator} idGenerator 请求内 ID 生成器。 * @return {Array} documents 数组。 */ buildDocumentsFromOrders(orders, idGenerator) { return orders.map((order, index) => { const sourceDocument = this.resolveOrderDocument(order, index); const document = deepClone(sourceDocument); if (!Array.isArray(document.contents)) { document.contents = []; } document.documentID = idGenerator.nextDocumentId(); return document; }); } /** * 解析单个订单对应的 document。 * @param {Object} order 订单对象。 * @param {number} index 订单索引。 * @return {Object} document 对象。 */ resolveOrderDocument(order, index) { if (!isPlainObject(order)) { throw new Error(`orders[${index}] 必须是对象`); } const printData = isPlainObject(order.print_data) ? order.print_data : order; if (!isPlainObject(printData)) { throw new Error(`orders[${index}] 缺少 print_data`); } const hasDocumentShape = Object.prototype.hasOwnProperty.call(printData, 'documentID') || Array.isArray(printData.contents); if (!hasDocumentShape) { throw new Error(`orders[${index}] 的 print_data 不是有效 document 结构`); } return printData; } /** * 写入请求 ID,兼容 requestID / requetID 两种字段。 * @param {Object} payload 请求 payload。 * @param {string} requestId 请求 ID。 */ applyRequestId(payload, requestId) { const hasRequestId = Object.prototype.hasOwnProperty.call(payload, 'requestID'); const hasRequetId = Object.prototype.hasOwnProperty.call(payload, 'requetID'); if (hasRequestId) { payload.requestID = requestId; } if (hasRequetId) { payload.requetID = requestId; } if (!hasRequestId && !hasRequetId) { payload.requestID = requestId; } } /** * 加载并缓存平台模板,然后返回深拷贝对象。 * @param {string} platform 平台编码。 * @return {Object} 模板拷贝。 */ loadTemplate(platform) { const normalizedPlatform = this.normalizePlatform(platform); const templatePath = path.join(this.templateDir, `${normalizedPlatform}.json`); if (!TEMPLATE_CACHE.has(templatePath)) { let templateContent = ''; try { templateContent = fs.readFileSync(templatePath, 'utf8'); } catch (error) { throw new Error(`未找到平台模板: ${normalizedPlatform}.json`); } let templateData; try { templateData = JSON.parse(templateContent); } catch (error) { throw new Error(`平台模板 JSON 解析失败: ${normalizedPlatform}.json`); } TEMPLATE_CACHE.set(templatePath, templateData); } return deepClone(TEMPLATE_CACHE.get(templatePath)); } /** * 规范化平台编码。 * @param {string} platform 平台编码或别名。 * @return {string} 规范化平台编码。 */ normalizePlatform(platform) { const normalized = PrinterDataBuilder.normalizePlatformAlias(platform); if (normalized && normalized.platform) { return normalized.platform; } return String(platform || '').trim().toLowerCase(); } } module.exports = { ExpressPrintPayloadBuilder, RequestScopedPrintIdGenerator, };