'use strict'; // 打印相关 Service const MainService = require('../main'); const { ExpressPrintPayloadBuilder, RequestScopedPrintIdGenerator, } = require('../../lib/express_print_payload_builder'); /** * 打印 Service * 参考 indexService 初始化方式,后续可扩展具体业务函数 */ class PrintService extends MainService { constructor(ctx) { super(ctx); // 初始化免登录、免权限、免日志、免认证等配置 const _noNeedLogin = ''; const _noNeedRight = '*'; const _noNeedLog = ''; const _noNeedAuth = '*'; this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); this.defaultComponents = [ { name: '抖音', port: '13888' }, { name: '拼多多', port: '5000' }, { name: '快手', port: '16888/ks/printer' }, { name: '京东', port: '9113' }, { name: '菜鸟', port: '13528' }, { name: '视频号', port: '12705' }, { name: '小红书', port: '10818' }, { name: 'LODOP', port: '8000' }, ]; } /** * 构建 print.send 入参摘要,避免打印超大对象。 * @param {Object} payload 原始入参。 * @return {Object} 安全摘要信息。 */ buildPrintSendInputSummary(payload = {}) { const normalizedPayload = payload && typeof payload === 'object' ? payload : {}; const data = normalizedPayload.data && typeof normalizedPayload.data === 'object' ? normalizedPayload.data : {}; const waveGroups = Array.isArray(data.waveGroups) ? data.waveGroups : []; const firstWavePlatforms = Array.isArray(waveGroups[0] && waveGroups[0].platforms) ? waveGroups[0].platforms : []; const firstPlatformOrders = Array.isArray(firstWavePlatforms[0] && firstWavePlatforms[0].orders) ? firstWavePlatforms[0].orders : []; return { type: normalizedPayload.type || '', printer: normalizedPayload.printer || '', computerId: normalizedPayload.computerId || '', printStationId: normalizedPayload.printStationId || '', hasTemplate: Boolean(normalizedPayload.template), requestCode: normalizedPayload.requestCode ? String(normalizedPayload.requestCode) : '', waveGroupsCount: waveGroups.length, firstWavePlatformsCount: firstWavePlatforms.length, firstGroupOrdersCount: firstPlatformOrders.length, dataKeys: Object.keys(data).slice(0, 20), }; } /** * 统计快递 payload 摘要,避免输出完整文档对象。 * @param {Object} payload 快递发送 payload。 * @return {{documentCount:number}} 文档数量摘要。 */ summarizeExpressPayload(payload = {}) { const normalizedPayload = payload && typeof payload === 'object' ? payload : {}; let documentCount = 0; if (normalizedPayload.task && Array.isArray(normalizedPayload.task.documents)) { documentCount = normalizedPayload.task.documents.length; } else if (Array.isArray(normalizedPayload.documents)) { documentCount = normalizedPayload.documents.length; } else if (Array.isArray(normalizedPayload.document_list)) { documentCount = normalizedPayload.document_list.length; } else if (Array.isArray(normalizedPayload.data)) { documentCount = normalizedPayload.data.length; } else if (normalizedPayload.document || normalizedPayload.print_data) { documentCount = 1; } return { documentCount }; } /** * 发送打印任务到打印电脑。 * 仅在 type=customize 时要求 printer、template、page_width、page_height、template_content。 * @param {Object} _data 打印请求参数 * @param {string} [_data.printer] 打印机名称(type=customize 必填,type=express 忽略) * @param {string} _data.type 打印类型,支持 customize/express * @param {Object} [_data.template] 打印模板对象(customize 必填) * @param {Object} _data.data 打印业务数据(express 场景要求 data.waveGroups) * @param {string|number} [_data.printStationId] 打印台 ID(express 必填) * @param {string} [_data.requestCode] 请求参数码(express 必填,用于本次请求内 ID 唯一化) * @param {string} [_data.computerId] 打印电脑 ID(customize 必填,express 忽略) * @param {string} [_data.timestamp] 业务时间戳(express 忽略) * @param {number} [_data.count] 打印份数(express 忽略) * @return {Promise} 统一返回结构 */ async send(_data) { const { ctx } = this; const warehouseId = ctx.user.store_id; const { printer, type, template, data, computerId, timestamp, count, printStationId, requestCode, } = _data; this.ctx.logger.info('[print.send] 入参接收', { warehouseId, inputSummary: this.buildPrintSendInputSummary(_data), }); this.ctx.logger.info('[print.send] 分支判定', { warehouseId, type, isExpress: type === 'express', isCustomize: type === 'customize', }); if (type === 'express') { const expressValidationResult = this.validateExpressSendInput({ data, printStationId, requestCode }); if (expressValidationResult) { this.ctx.logger.warn('[print.send] express 参数校验失败', { warehouseId, printStationId, requestCode: requestCode ? String(requestCode) : '', waveGroupsCount: Array.isArray(data && data.waveGroups) ? data.waveGroups.length : 0, }); this.ctx.logger.error('[print.send] 最终返回 failure', { warehouseId, type, reason: 'express 参数校验失败', }); return expressValidationResult; } this.ctx.logger.info('[print.send] express 参数校验通过', { warehouseId, printStationId, waveGroupsCount: Array.isArray(data && data.waveGroups) ? data.waveGroups.length : 0, }); } let printRecord = null; if (type !== 'express') { // 生成打印编号并记录到数据库 try { printRecord = await ctx.model.PrintRecord.create({ warehouse_id: warehouseId, computer_id: computerId, printer, type, data: { template, data }, status: 'pending', }); this.ctx.logger.info('[print.send] PrintRecord 创建成功', { warehouseId, type, printId: printRecord.id, computerId, printer, }); } catch (error) { this.ctx.logger.error('[print.send] PrintRecord 创建失败', { warehouseId, type, computerId, printer, error: error && error.message ? error.message : `${error}`, stack: error && error.stack ? error.stack : '', }); throw error; } } // 处理后的数据 let processedData = {}; switch (type) { case 'customize': { if (printer === undefined || printer === null || printer === '') { this.ctx.logger.warn('[print.send] customize 参数校验失败-printer 为空', { warehouseId, type, }); this.ctx.logger.error('[print.send] 最终返回 failure', { warehouseId, type, reason: 'printer 参数不能为空', }); return this.fail('type=customize 时 printer 参数不能为空', { code: 400 }); } if (!template || typeof template !== 'object' || Array.isArray(template)) { this.ctx.logger.warn('[print.send] customize 参数校验失败-template 非对象', { warehouseId, type, }); this.ctx.logger.error('[print.send] 最终返回 failure', { warehouseId, type, reason: 'template 参数不合法', }); return this.fail('type=customize 时 template 参数不能为空', { code: 400 }); } const { page_width, page_height, template_content } = template; if (page_width === undefined || page_width === null || page_width === '') { this.ctx.logger.warn('[print.send] customize 参数校验失败-page_width 为空', { warehouseId, type, }); this.ctx.logger.error('[print.send] 最终返回 failure', { warehouseId, type, reason: 'page_width 参数不能为空', }); return this.fail('type=customize 时 page_width 参数不能为空', { code: 400 }); } if (page_height === undefined || page_height === null || page_height === '') { this.ctx.logger.warn('[print.send] customize 参数校验失败-page_height 为空', { warehouseId, type, }); this.ctx.logger.error('[print.send] 最终返回 failure', { warehouseId, type, reason: 'page_height 参数不能为空', }); return this.fail('type=customize 时 page_height 参数不能为空', { code: 400 }); } if (!Array.isArray(template_content)) { this.ctx.logger.warn('[print.send] customize 参数校验失败-template_content 非数组', { warehouseId, type, }); this.ctx.logger.error('[print.send] 最终返回 failure', { warehouseId, type, reason: 'template_content 参数不合法', }); return this.fail('type=customize 时 template_content 必须是数组', { code: 400 }); } let htm = ``; for (const item of template_content) { let content = item.content; for (const key in data) { if (String(item.field_code) === key) { content = data[key]; } } switch (item.type) { case 'text': htm += `
${content}
`; break; case 'image': htm += ``; break; case 'barcode': htm += `
`; break; case 'qrcode': { let toUrl = `https://ye4s.wms.gztbyc.com/to/${content}`; // 转换成urlencode toUrl = encodeURIComponent(toUrl); const url = `https://ye4s.wms.gztbyc.com/qrcode/build?text=${toUrl}`; htm += `
`; break; } case 'line': htm += `
`; break; case 'rectangle': htm += `
`; break; case 'table': { let tableHtml = ``; for (let i = 0; i < item.rows; i++) { tableHtml += ''; for (let j = 0; j < item.columns; j++) { const content = item.content[i] && item.content[i][j] ? item.content[i][j] : ''; tableHtml += ``; } tableHtml += ''; } tableHtml += '
${content}
'; htm += tableHtml; break; } default: break; } } htm += ''; processedData = { pageWidth: page_width, pageHeight: page_height, htm, lodopkey: [ '', '13528A153BAEE3A0254B9507DCDE2839', 'EDE92F75B6A3D917F65910', 'D60BC84D7CF2DE18156A6F88987304CB6D8' ], }; this.ctx.logger.info('[print.send] customize payload 组装完成', { warehouseId, type, pageWidth: page_width, pageHeight: page_height, templateItemCount: template_content.length, }); break; } case 'express': { const expressPrintStation = await this.loadExpressPrintStation({ printStationId, warehouseId }); if (!expressPrintStation.success) { this.ctx.logger.error('[print.send] 最终返回 failure', { warehouseId, type, reason: expressPrintStation.error, }); return this.fail(expressPrintStation.error, { code: 400 }); } const expressRecordFields = this.buildExpressPrintRecordFields(expressPrintStation.data); if (!expressRecordFields.success) { this.ctx.logger.error('[print.send] 最终返回 failure', { warehouseId, type, reason: expressRecordFields.error, }); return this.fail(expressRecordFields.error, { code: 400 }); } const platformCodes = this.collectExpressPlatformCodes(data.waveGroups); const platformComponentsResult = await this.loadExpressPlatformComponents({ platformCodes }); if (!platformComponentsResult.success) { this.ctx.logger.error('[print.send] 最终返回 failure', { warehouseId, type, reason: platformComponentsResult.error, }); return this.fail(platformComponentsResult.error, { code: 400 }); } const componentOnlineResult = await this.validateExpressComponentsOnline({ computerId: expressRecordFields.data.computer_id, platformComponents: platformComponentsResult.data, }); if (!componentOnlineResult.success) { this.ctx.logger.error('[print.send] 最终返回 failure', { warehouseId, type, reason: componentOnlineResult.error, }); return this.fail(componentOnlineResult.error, { code: 400 }); } try { printRecord = await ctx.model.PrintRecord.create({ warehouse_id: warehouseId, computer_id: expressRecordFields.data.computer_id, printer: expressRecordFields.data.printer, type, data: { template, data }, status: 'pending', }); this.ctx.logger.info('[print.send] PrintRecord 创建成功', { warehouseId, type, printId: printRecord.id, computerId: expressRecordFields.data.computer_id, printer: expressRecordFields.data.printer, }); } catch (error) { this.ctx.logger.error('[print.send] PrintRecord 创建失败', { warehouseId, type, computerId: expressRecordFields.data.computer_id, printer: expressRecordFields.data.printer, error: error && error.message ? error.message : `${error}`, stack: error && error.stack ? error.stack : '', }); throw error; } const payloadBuilder = new ExpressPrintPayloadBuilder({ baseDir: this.app.baseDir }); const idGenerator = new RequestScopedPrintIdGenerator(requestCode); const expressSendResult = await this.sendExpressWaveGroups({ warehouseId, waveGroups: data.waveGroups, printStation: expressPrintStation.data, payloadBuilder, idGenerator, printRecordId: printRecord.id, platformComponents: platformComponentsResult.data, }); if (!expressSendResult.success) { await printRecord.update({ status: 'failed', error_message: expressSendResult.error }); this.ctx.logger.error('[print.send] 最终返回 failure', { warehouseId, type, printId: printRecord.id, reason: expressSendResult.error, }); return this.fail(expressSendResult.error, { code: 504, printId: printRecord.id }); } await printRecord.update({ status: 'sent' }); this.ctx.logger.info('[print.send] 最终返回 success', { warehouseId, type, printId: printRecord.id, }); return this.success('发送打印任务成功', { code: 200, printId: printRecord.id }); } default: this.ctx.logger.error('[print.send] 最终返回 failure', { warehouseId, type, reason: '不支持的打印类型', }); return this.fail('不支持的打印类型', 1001); } const printData = { printer, type, template, data: processedData, timestamp, count, printId: printRecord.id, }; const sendStartAt = Date.now(); const res = await this.service.systems.print.index.sendToComputer({ warehouse: warehouseId, computerId, data: printData }); const sendDurationMs = Date.now() - sendStartAt; if (res.status === 'success') { this.ctx.logger.info('[print.send] sendToComputer 调用成功', { warehouseId, type, printId: printRecord.id, computerId, durationMs: sendDurationMs, }); } else { this.ctx.logger.error('[print.send] sendToComputer 调用失败', { warehouseId, type, printId: printRecord.id, computerId, durationMs: sendDurationMs, error: res && res.error ? res.error : '打印服务返回失败', }); } // 发送成功后更新打印记录状态 if (res.status === 'success') { await printRecord.update({ status: 'sent' }); this.ctx.logger.info('[print.send] 最终返回 success', { warehouseId, type, printId: printRecord.id, }); return this.success('发送打印任务成功', { code: 200, printId: printRecord.id }); } await printRecord.update({ status: 'failed', error_message: res.error }); this.ctx.logger.error('[print.send] 最终返回 failure', { warehouseId, type, printId: printRecord.id, reason: res.error || '打印服务返回失败', }); return this.fail(res.error, { code: 504, printId: printRecord.id }); } /** * 校验快递打印请求的必要参数。 * @param {Object} payload 校验参数。 * @param {Object} payload.data 请求 data。 * @param {number|string} payload.printStationId 打印台 ID。 * @param {string} payload.requestCode 请求参数码。 * @return {Object|null} 失败时返回 fail 响应,成功返回 null。 */ validateExpressSendInput(payload = {}) { const requestData = payload && typeof payload === 'object' ? payload : {}; const waveGroups = Array.isArray(requestData.data && requestData.data.waveGroups) ? requestData.data.waveGroups : []; if (waveGroups.length === 0) { this.ctx.logger.warn('[print.send] express 参数校验失败-data.waveGroups 为空', { printStationId: requestData.printStationId || '', requestCode: requestData.requestCode ? String(requestData.requestCode) : '', }); return this.fail('type=express 时 data.waveGroups 必须是非空数组', { code: 400 }); } const normalizedPrintStationId = String(requestData.printStationId || '').trim(); if (!normalizedPrintStationId) { this.ctx.logger.warn('[print.send] express 参数校验失败-printStationId 为空', { requestCode: requestData.requestCode ? String(requestData.requestCode) : '', waveGroupsCount: waveGroups.length, }); return this.fail('type=express 时 printStationId 参数不能为空', { code: 400 }); } const normalizedRequestCode = String(requestData.requestCode || '').trim(); if (!normalizedRequestCode) { this.ctx.logger.warn('[print.send] express 参数校验失败-requestCode 为空', { printStationId: normalizedPrintStationId, waveGroupsCount: waveGroups.length, }); return this.fail('type=express 时 requestCode 参数不能为空', { code: 400 }); } return null; } /** * 查询并校验快递打印台。 * @param {Object} payload 查询参数。 * @param {number|string} payload.printStationId 打印台 ID。 * @param {number|string} payload.warehouseId 仓库 ID。 * @return {Promise<{success:boolean,data?:Object,error?:string}>} 查询结果。 */ async loadExpressPrintStation(payload = {}) { const { ctx } = this; const normalizedPayload = payload && typeof payload === 'object' ? payload : {}; const printStation = await ctx.model.PrintStations.findOne({ where: { id: normalizedPayload.printStationId, warehouse_id: normalizedPayload.warehouseId, deleted: 0, }, raw: true, }); if (!printStation) { this.ctx.logger.warn('[print.send] 打印台查询失败', { printStationId: normalizedPayload.printStationId, warehouseId: normalizedPayload.warehouseId, }); return { success: false, error: '打印台不存在', }; } this.ctx.logger.info('[print.send] 打印台查询成功', { printStationId: printStation.id, warehouseId: normalizedPayload.warehouseId, computerId: printStation.computer_id || '', defaultPrinterName: printStation.default_printer_name || '', }); return { success: true, data: printStation, }; } /** * 组装快递打印记录的必填字段,避免写入 null。 * @param {Object} printStation 打印台配置。 * @return {{success:boolean,data?:{computer_id:string,printer:string},error?:string}} 组装结果。 */ buildExpressPrintRecordFields(printStation = {}) { const normalizedStation = printStation && typeof printStation === 'object' ? printStation : {}; const computerId = String(normalizedStation.computer_id || '').trim(); if (!computerId) { return { success: false, error: '打印台未配置打印电脑', }; } const defaultPrinterName = String(normalizedStation.default_printer_name || '').trim(); return { success: true, data: { computer_id: computerId, printer: defaultPrinterName || 'EXPRESS_DYNAMIC_PRINTER', }, }; } /** * 收集 express 请求中涉及的平台编码列表。 * @param {Array} waveGroups 波次分组数据。 * @return {Array} 去重后的平台编码列表。 */ collectExpressPlatformCodes(waveGroups = []) { const normalizedWaveGroups = Array.isArray(waveGroups) ? waveGroups : []; const platformCodeSet = new Set(); for (const waveGroup of normalizedWaveGroups) { const platforms = Array.isArray(waveGroup && waveGroup.platforms) ? waveGroup.platforms : []; for (const platformGroup of platforms) { const orders = Array.isArray(platformGroup && platformGroup.orders) ? platformGroup.orders : []; if (orders.length === 0) { continue; } const platformCode = String(platformGroup && platformGroup.platform ? platformGroup.platform : '').trim(); if (platformCode) { platformCodeSet.add(platformCode); } } } return Array.from(platformCodeSet); } /** * 加载并校验 express 请求涉及平台的打印组件配置。 * @param {Object} payload 查询参数。 * @param {Array} payload.platformCodes 平台编码列表。 * @return {Promise<{success:boolean,data?:Object,error?:string}>} 查询与校验结果。 */ async loadExpressPlatformComponents(payload = {}) { const normalizedPayload = payload && typeof payload === 'object' ? payload : {}; const platformCodes = Array.isArray(normalizedPayload.platformCodes) ? normalizedPayload.platformCodes.filter(item => String(item || '').trim()) : []; if (platformCodes.length === 0) { return { success: false, error: 'type=express 时未识别到有效平台编码', }; } const platformRows = await this.ctx.model.Platform.findAll({ attributes: [ 'code', 'component' ], where: { code: platformCodes, }, raw: true, }); const platformComponentMap = {}; for (const row of platformRows) { const platformCode = String(row && row.code ? row.code : '').trim(); if (!platformCode) { continue; } platformComponentMap[platformCode] = String(row && row.component ? row.component : '').trim(); } for (const platformCode of platformCodes) { const component = String(platformComponentMap[platformCode] || '').trim(); if (!component) { return { success: false, error: `平台 ${platformCode} 未配置打印组件`, }; } } return { success: true, data: platformComponentMap, }; } /** * 校验 express 请求涉及组件是否全部在线。 * @param {Object} payload 校验参数。 * @param {string} payload.computerId 打印电脑 ID。 * @param {Object} payload.platformComponents 平台到组件映射。 * @return {Promise<{success:boolean,error?:string}>} 校验结果。 */ async validateExpressComponentsOnline(payload = {}) { const normalizedPayload = payload && typeof payload === 'object' ? payload : {}; const computerId = String(normalizedPayload.computerId || '').trim(); const platformComponents = normalizedPayload.platformComponents && typeof normalizedPayload.platformComponents === 'object' ? normalizedPayload.platformComponents : {}; if (!computerId) { return { success: false, error: '打印台未配置打印电脑', }; } const redisPrinter = this.app.redis.get('printer'); const entries = Object.entries(platformComponents); for (const entry of entries) { const platformCode = String(entry[0] || '').trim(); const component = String(entry[1] || '').trim(); const statusKey = `printer:${computerId}:name:${component}:status`; const componentStatus = await redisPrinter.get(statusKey); if (componentStatus !== 'connected') { return { success: false, error: `平台 ${platformCode} 打印组件 ${component} 未在线`, }; } } return { success: true }; } /** * 根据平台快递编码解析打印机名称。 * @param {Object} payload 解析参数。 * @param {Object} payload.printStation 打印台配置。 * @param {string} payload.sysLogisticsCode 系统快递编码。 * @return {{success:boolean,data?:string,error?:string}} 解析结果。 */ resolveExpressPrinterName(payload = {}) { const normalizedPayload = payload && typeof payload === 'object' ? payload : {}; const printStation = normalizedPayload.printStation && typeof normalizedPayload.printStation === 'object' ? normalizedPayload.printStation : {}; let subjectConfig = printStation.subject_config; if (typeof subjectConfig === 'string') { try { subjectConfig = JSON.parse(subjectConfig); } catch (error) { subjectConfig = {}; } } if (!subjectConfig || typeof subjectConfig !== 'object' || Array.isArray(subjectConfig)) { subjectConfig = {}; } const expressBindPrinter = Array.isArray(subjectConfig.express_bind_printer) ? subjectConfig.express_bind_printer : []; const sysLogisticsCode = String(normalizedPayload.sysLogisticsCode || '').trim(); const matchedPrinter = expressBindPrinter.find(item => { const sourceItem = item && typeof item === 'object' ? item : {}; return String(sourceItem.express_code || '').trim() === sysLogisticsCode; }); const printerName = String( matchedPrinter && matchedPrinter.printer_name ? matchedPrinter.printer_name : (printStation.default_printer_name || '') ).trim(); if (!printerName) { return { success: false, error: '打印台未配置默认打印机', }; } this.ctx.logger.info('[print.send] resolveExpressPrinterName 成功', { sysLogisticsCode, printerName, matched: Boolean(matchedPrinter), matchSource: matchedPrinter ? '命中快递绑定' : '回退默认打印机', }); return { success: true, data: printerName, }; } /** * 串行发送快递打印任务(波次 -> 平台快递组)。 * @param {Object} payload 发送参数。 * @param {number|string} payload.warehouseId 仓库 ID。 * @param {Array} payload.waveGroups 波次分组。 * @param {Object} payload.printStation 打印台配置。 * @param {Object} payload.payloadBuilder 快递模板组装器。 * @param {Object} payload.idGenerator 本次请求 ID 生成器。 * @param {number|string} payload.printRecordId 打印记录 ID。 * @param {Object} payload.platformComponents 平台到打印组件映射。 * @return {Promise<{success:boolean,error?:string}>} 发送结果。 */ async sendExpressWaveGroups(payload = {}) { const normalizedPayload = payload && typeof payload === 'object' ? payload : {}; const waveGroups = Array.isArray(normalizedPayload.waveGroups) ? normalizedPayload.waveGroups : []; for (const waveGroup of waveGroups) { const platforms = Array.isArray(waveGroup && waveGroup.platforms) ? waveGroup.platforms : []; for (const platformGroup of platforms) { const orders = Array.isArray(platformGroup && platformGroup.orders) ? platformGroup.orders : []; if (orders.length === 0) { continue; } const groupSummary = { waveNo: waveGroup && waveGroup.wave_no ? waveGroup.wave_no : '', platform: platformGroup && platformGroup.platform ? platformGroup.platform : '', sysLogisticsCode: platformGroup && platformGroup.sys_logistics_code ? platformGroup.sys_logistics_code : '', ordersCount: orders.length, printRecordId: normalizedPayload.printRecordId, }; this.ctx.logger.info('[print.send] 平台快递组发送开始', groupSummary); const platformCode = String(platformGroup && platformGroup.platform ? platformGroup.platform : '').trim(); const component = String( normalizedPayload.platformComponents && normalizedPayload.platformComponents[platformCode] ? normalizedPayload.platformComponents[platformCode] : '' ).trim(); if (!component) { this.ctx.logger.error('[print.send] 平台快递组发送失败-打印组件缺失', { ...groupSummary, reason: `平台 ${platformCode} 未配置打印组件`, }); this.ctx.logger.error('[print.send] 平台快递组发送结束', { ...groupSummary, status: 'failure', reason: `平台 ${platformCode} 未配置打印组件`, }); return { success: false, error: `平台 ${platformCode} 未配置打印组件`, }; } const printerNameResult = this.resolveExpressPrinterName({ printStation: normalizedPayload.printStation, sysLogisticsCode: platformGroup && platformGroup.sys_logistics_code, }); if (!printerNameResult.success) { this.ctx.logger.error('[print.send] 平台快递组发送失败-打印机解析失败', { ...groupSummary, reason: printerNameResult.error, }); this.ctx.logger.error('[print.send] 平台快递组发送结束', { ...groupSummary, status: 'failure', reason: printerNameResult.error, }); return { success: false, error: printerNameResult.error, }; } const normalizedPlatformCode = String(platformGroup && platformGroup.platform ? platformGroup.platform : '').trim().toLowerCase(); const isKuaishouPlatform = normalizedPlatformCode === 'kuaishou' || normalizedPlatformCode === 'ks'; const orderBatches = []; if (isKuaishouPlatform) { for (let index = 0; index < orders.length; index += 10) { orderBatches.push(orders.slice(index, index + 10)); } } else { orderBatches.push(orders); } const totalDocumentCount = orders.length; for (let batchIndex = 0; batchIndex < orderBatches.length; batchIndex++) { const batchOrders = orderBatches[batchIndex]; const batchSummary = { ...groupSummary, batchIndex: batchIndex + 1, batchCount: orderBatches.length, batchOrdersCount: batchOrders.length, }; let requestPayload; 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; } const payloadSummary = this.summarizeExpressPayload(requestPayload); this.ctx.logger.info('[print.send] 组装 payload 成功', { ...batchSummary, platform: platformGroup && platformGroup.platform ? platformGroup.platform : '', ordersCount: batchOrders.length, documentCount: payloadSummary.documentCount, }); } catch (error) { this.ctx.logger.error('[print.send] 组装 payload 失败', { ...batchSummary, platform: platformGroup && platformGroup.platform ? platformGroup.platform : '', ordersCount: batchOrders.length, reason: error && error.message ? error.message : '快递打印任务组装失败', }); this.ctx.logger.error('[print.send] 平台快递组发送结束', { ...batchSummary, status: 'failure', reason: error && error.message ? error.message : '快递打印任务组装失败', }); return { success: false, error: error && error.message ? error.message : '快递打印任务组装失败', }; } const printData = { printer: printerNameResult.data, component, type: 'express', data: requestPayload, printId: normalizedPayload.printRecordId, }; const sendStartAt = Date.now(); let sendResult; try { sendResult = await this.service.systems.print.index.sendToComputer({ warehouse: normalizedPayload.warehouseId, computerId: normalizedPayload.printStation.computer_id, data: printData, }); } catch (error) { const sendDurationMs = Date.now() - sendStartAt; this.ctx.logger.error('[print.send] sendToComputer 调用失败', { ...batchSummary, computerId: normalizedPayload.printStation.computer_id, durationMs: sendDurationMs, reason: error && error.message ? error.message : `${error}`, }); this.ctx.logger.error('[print.send] 平台快递组发送结束', { ...batchSummary, computerId: normalizedPayload.printStation.computer_id, status: 'failure', reason: error && error.message ? error.message : `${error}`, }); return { success: false, error: error && error.message ? error.message : '打印服务调用失败', }; } const sendDurationMs = Date.now() - sendStartAt; if (sendResult.status !== 'success') { this.ctx.logger.error('[print.send] sendToComputer 调用失败', { ...batchSummary, computerId: normalizedPayload.printStation.computer_id, durationMs: sendDurationMs, reason: sendResult.error || '打印服务返回失败', }); this.ctx.logger.error('[print.send] 平台快递组发送结束', { ...batchSummary, computerId: normalizedPayload.printStation.computer_id, status: 'failure', reason: sendResult.error || '打印服务返回失败', }); } else { this.ctx.logger.info('[print.send] sendToComputer 调用成功', { ...batchSummary, computerId: normalizedPayload.printStation.computer_id, durationMs: sendDurationMs, }); } if (sendResult.status !== 'success') { return { success: false, error: sendResult.error || '打印服务返回失败', }; } this.ctx.logger.info('[print.send] 平台快递组发送结束', { ...batchSummary, computerId: normalizedPayload.printStation.computer_id, status: 'success', }); } } } return { success: true }; } async getPrintResult(data) { const { ctx } = this; const warehouseId = ctx.user.store_id; const { printId } = data; if (!printId) return this.fail('参数错误', 1001); const record = await ctx.model.PrintRecord.findOne({ where: { id: printId, warehouse_id: warehouseId }, raw: true }); if (!record) return this.fail('打印记录不存在', 1002); return this.success('success', { ...record, code: 0 }); } async getPrintRecordItem(data) { const { ctx } = this; const warehouseId = ctx.user.store_id; const { id } = data; if (!id) return this.fail('参数错误', 1001); const item = await ctx.model.PrintRecord.findOne({ where: { id, warehouse_id: warehouseId }, raw: true }); if (!item) return this.fail('打印记录不存在', 1002); return this.success('success', { ...item, code: 0 }); } /** * 1. 查询打印台列表 * @param {Object} data { page, pageSize, where } */ async getList(data) { const { ctx } = this; const warehouse_id = ctx.user.store_id; const requestData = data && typeof data === 'object' ? data : {}; const { whereValue } = this.prepareWhereContext(requestData); const { page = 1, pageSize = 20 } = requestData; // 字段过滤 const filter = {}; [ 'id', 'name', 'computer_id', 'custom_barcode' ].forEach(key => { const value = whereValue[key]; if (value !== undefined && value !== null && value !== '') filter[key] = value; }); filter.warehouse_id = warehouse_id; filter.deleted = 0; // 查询总数 const total = await ctx.model.PrintStations.count({ where: filter }); // 查询分页数据 const list = await ctx.model.PrintStations.findAll({ where: filter, offset: (page - 1) * pageSize, limit: pageSize, order: [[ 'create_at', 'DESC' ]], raw: true, }); const computers = list.map(item => { const computer = { id: item.computer_id, is_online: 0, components: this.defaultComponents.map(component => ({ name: component.name, is_online: 0, })), }; return computer; }); // 动态属性处理(如 is_online、components) for (let i = 0; i < computers.length; i++) { const key = `warehouse:${warehouse_id}:printer:${computers[i].id}`; const computerInfo = await this.app.redis.get('printer').get(key); if (computerInfo) { computers[i].is_online = 1; computers[i].components = await Promise.all(computers[i].components.map(async component => { const componentKey = `printer:${computers[i].id}:name:${component.name}:status`; const componentInfo = await this.app.redis.get('printer').get(componentKey); if (componentInfo && componentInfo === 'connected') { component.is_online = 1; } return component; })); } } for (const item of list) { const computer = computers.find(c => c.id === item.computer_id); item.is_online = computer ? computer.is_online : 0; item.components = computer ? computer.components : this.defaultComponents.map(component => ({ name: component.name, is_online: 0, })); } const result = { code: 200, data: { list, pagination: { hasNext: page * pageSize < total, hasPrevious: page > 1, page, pageSize, total, totalPages: Math.ceil(total / pageSize), }, queryInfo: { conditions: this.ctx.where || {}, hasBarcodeSearch: false, sortField: 'id', sortOrder: 'DESC', }, summary: { total_available: total, total_items: pageSize, total_locked: 0, total_quantity: 0, }, }, }; return this.success('success', result); } /** * 2. 获取单个打印台 * @param {Object} data { id } * @return {Promise} 返回打印台详情(不包含 warehouse_id) */ async getItem(data) { const { ctx } = this; const { id } = data; if (!id) return this.fail('参数错误', 1001); const item = await ctx.model.PrintStations.findOne({ where: { id }, raw: true }); if (!item) return this.fail('打印台不存在', 1002); const rest = { ...item }; delete rest.warehouse_id; return this.success('success', { ...rest, code: 0 }); } /** * 3. 添加打印台 * @param {Object} data { id, name, computer_id, custom_barcode } * @return {Promise} 返回新增结果。 */ async add(data) { const { ctx } = this; const warehouse_id = ctx.user.store_id; const { name, computer_id, custom_barcode, subject_config } = data; if (!name || !computer_id) return this.fail('参数错误', 1001); const createPayload = { warehouse_id, name, computer_id, custom_barcode, creator_id: ctx.user?.employees_id || '', creator_name: ctx.user?.employees_name || '', default_printer_name: data.default_printer_name || '', create_at: new Date(), update_at: new Date(), deleted: 0, }; if (Object.prototype.hasOwnProperty.call(data, 'subject_config')) { try { createPayload.subject_config = ctx.model.PrintStations.normalizeSubjectConfig(subject_config); } catch (error) { return this.fail(error.message, 1001); } } const newItem = await ctx.model.PrintStations.create(createPayload); return this.success('添加打印台成功', { data: newItem, code: 0 }); } async hasName(data) { const { ctx } = this; const warehouse_id = ctx.user.store_id; const { name, id } = data; if (!name) return this.fail('参数错误', 1001); const item = await ctx.model.PrintStations.findOne({ where: { name, warehouse_id, id: { [ctx.model.Sequelize.Op.ne]: id } }, raw: true }); return this.success('success', { exists: !!item, code: 0 }); } /** * 3. 修改打印台 * @param {Object} data { id, name, computer_id, custom_barcode } * @return {Promise} 返回更新结果。 */ async updateItem(data) { const { ctx } = this; const { id, name, computer_id, custom_barcode, subject_config } = data; if (!id) return this.fail('参数错误', 1001); const item = await ctx.model.PrintStations.findOne({ where: { id } }); if (!item) return this.fail('打印台不存在', 1002); // 只更新允许字段 if (name !== undefined) item.name = name; if (computer_id !== undefined) item.computer_id = computer_id; if (custom_barcode !== undefined) item.custom_barcode = custom_barcode; if (Object.prototype.hasOwnProperty.call(data, 'subject_config')) { try { item.subject_config = ctx.model.PrintStations.normalizeSubjectConfig(subject_config); } catch (error) { return this.fail(error.message, 1001); } } await item.save(); return this.success('success', { data: null, code: 0 }); } /** * 4. 删除打印台 * @param {Object} data { ids } */ async del(data) { const { ctx } = this; const { ids } = data; if (!Array.isArray(ids) || ids.length === 0) return this.fail('参数错误', 1001); // 软删除 await ctx.model.PrintStations.update({ deleted: 1 }, { where: { id: ids } }); // TODO: 检查 result 是否成功 return this.success('success', { data: null, code: 0 }); } /** * 5. 获取打印电脑列表 */ async getComputer() { const { ctx } = this; // TODO: 打印电脑状态需根据实际业务实现 const warehouseId = ctx.user.store_id; const list = await ctx.model.PrintComputer.findAll({ raw: true, where: { status: 1, warehouse_id: warehouseId } }); return this.success('success', { data: list, code: 0 }); } /** * 7. 获取打印电脑的所有打印机 * @param {Object} data { id } */ async getComputerPrinter(data) { const { id } = data; if (!id) return this.fail('参数错误', 1001); const printerListResult = await this.app.redis.get('printer').get(`printer:${id}:printerList`); const printerList = JSON.parse(printerListResult); let printers = []; if (!printerList || !printerList.data || printerList.data.length === 0) { printers = []; } else { printers = printerList.data; } return this.success('success', { data: printers, code: 0 }); } /** * 8. 保存打印台的默认打印机与快递绑定打印机配置。 * @param {Object} data 请求参数。 * @param {string} data.defaultPrinter 默认打印机名称,必填。 * @param {Array} data.express 快递绑定数组,必填。 * @param {number|string} data.print_station_id 打印台 ID,必填。 * @return {Promise} 保存结果。 */ async savePrinters(data) { const { ctx } = this; const { defaultPrinter, express, print_station_id } = data; if (!defaultPrinter || !Array.isArray(express) || !print_station_id) return this.fail('参数错误', { code: 1001 }); const item = await ctx.model.PrintStations.findOne({ where: { id: print_station_id, deleted: 0, }, }); if (!item) return this.fail('打印台不存在', { code: 1002 }); const expressBindPrinter = express.map(expressItem => { const sourceItem = expressItem && typeof expressItem === 'object' ? expressItem : {}; return { printer_name: sourceItem.printer_name || sourceItem.name || defaultPrinter, express_code: sourceItem.express_code || sourceItem.express_id, }; }); const rawSubjectConfig = item.subject_config && typeof item.subject_config === 'object' && !Array.isArray(item.subject_config) ? item.subject_config : {}; const mergedSubjectConfig = { ...rawSubjectConfig, express_bind_printer: expressBindPrinter, }; try { item.subject_config = ctx.model.PrintStations.normalizeSubjectConfig(mergedSubjectConfig); } catch (error) { return this.fail(error.message, { code: 1001 }); } item.default_printer_name = defaultPrinter; item.update_at = new Date(); await item.save(); return this.success('success', { data: null, code: 0 }); } } module.exports = PrintService;