'use strict'; const { randomBytes } = require('node:crypto'); // 打印相关 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 = 'notifyLock,notify_lock'; 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 }; } /** * 从快递打印 payload 中提取任务编码。 * @param {Object} payload 快递打印 payload。 * @return {string} 任务编码,提取失败时返回空字符串。 */ extractExpressTaskCodeFromPayload(payload = {}) { const normalizedPayload = payload && typeof payload === 'object' ? payload : {}; const task = normalizedPayload.task && typeof normalizedPayload.task === 'object' ? normalizedPayload.task : {}; return String(task.taskID || '').trim(); } /** * 构建打印记录可持久化的任务编码字段。 * @param {Array} taskCodes 任务编码列表。 * @return {string|null} 可持久化任务编码串,无有效编码时返回 null。 */ buildPrintTaskCodeForRecord(taskCodes = []) { const normalizedTaskCodes = Array.isArray(taskCodes) ? taskCodes.map(taskCode => String(taskCode || '').trim()).filter(Boolean) : []; if (normalizedTaskCodes.length === 0) { return null; } return Array.from(new Set(normalizedTaskCodes)).join(','); } /** * 构建打印记录初始化字段,统一发送状态初始值。 * @param {Object} payload 业务字段。 * @return {Object} 可直接用于创建打印记录的字段。 */ buildPendingPrintRecordPayload(payload = {}) { const normalizedPayload = payload && typeof payload === 'object' ? payload : {}; return { ...normalizedPayload, status: 'pending', send_status: 'pending', print_status: 'unknown', }; } /** * 构建打印记录发送成功后的状态字段。 * @param {Object} [payload] 扩展字段。 * @param {Date|string|null} [payload.sentTime] 发送时间,为空时使用当前时间。 * @return {Object} 可直接用于更新打印记录的字段。 */ buildSentPrintRecordUpdatePayload(payload = {}) { const normalizedPayload = payload && typeof payload === 'object' ? payload : {}; const sentTime = normalizedPayload.sentTime || new Date(); return { status: 'sent', send_status: 'sent', print_status: 'printed', sent_time: sentTime, print_time: sentTime, fail_code: null, error_message: null, }; } /** * 构建打印记录发送失败后的状态字段。 * @param {Object} [payload] 扩展字段。 * @param {string} [payload.errorMessage] 失败信息。 * @param {string} [payload.failCode] 失败编码。 * @return {Object} 可直接用于更新打印记录的字段。 */ buildSendFailedPrintRecordUpdatePayload(payload = {}) { const normalizedPayload = payload && typeof payload === 'object' ? payload : {}; const errorMessage = normalizedPayload.errorMessage ? String(normalizedPayload.errorMessage) : null; const failCode = normalizedPayload.failCode ? String(normalizedPayload.failCode) : 'SEND_FAILED'; return { status: 'failed', send_status: 'send_failed', print_status: 'unknown', fail_code: failCode, error_message: errorMessage, }; } /** * 规范化补打所需的已落库发送数据。 * @param {Object|string} recordData 打印记录 data 字段。 * @return {{success:boolean,data?:Object,error?:string}} 解析结果。 */ normalizeRetrySendPayload(recordData) { let normalizedRecordData = recordData; if (typeof normalizedRecordData === 'string') { try { normalizedRecordData = JSON.parse(normalizedRecordData); } catch (error) { return { success: false, error: '打印记录 data 不是有效 JSON', }; } } if (!normalizedRecordData || typeof normalizedRecordData !== 'object' || Array.isArray(normalizedRecordData)) { return { success: false, error: '打印记录 data 结构不合法', }; } const printer = String(normalizedRecordData.printer || '').trim(); const component = String(normalizedRecordData.component || '').trim(); const type = String(normalizedRecordData.type || '').trim(); const payloadData = normalizedRecordData.data; const orderIds = this.normalizeOrderIds(normalizedRecordData.order_ids); if (!printer || !type || !payloadData || typeof payloadData !== 'object' || Array.isArray(payloadData)) { return { success: false, error: '打印记录 data 缺少 printer/type/data', }; } return { success: true, data: { printer, component, type, order_ids: orderIds, data: JSON.parse(JSON.stringify(payloadData)), }, }; } /** * 规范化订单ID数组,过滤非法值并去重。 * @param {Array} orderIds 原始订单ID数组。 * @return {Array} 规范化后的订单ID数组。 */ normalizeOrderIds(orderIds = []) { if (!Array.isArray(orderIds)) { return []; } return Array.from(new Set(orderIds .map(orderId => Number(orderId || 0)) .filter(orderId => Number.isInteger(orderId) && orderId > 0))); } /** * 从单个平台分组提取订单ID列表。 * 优先读取平台透出的 order_ids,并补充 orders[*].order_id。 * @param {Object} platformGroup 平台分组数据。 * @param {Array} [ordersOverride] 指定订单列表(用于分批场景)。 * @return {Array} 去重后的订单ID列表。 */ collectOrderIdsFromPlatformGroup(platformGroup = {}, ordersOverride = null) { const normalizedPlatformGroup = platformGroup && typeof platformGroup === 'object' ? platformGroup : {}; const orderIdSet = new Set(this.normalizeOrderIds(normalizedPlatformGroup.order_ids)); const orders = Array.isArray(ordersOverride) ? ordersOverride : (Array.isArray(normalizedPlatformGroup.orders) ? normalizedPlatformGroup.orders : []); for (const order of orders) { const normalizedOrderId = Number(order && order.order_id || 0); if (Number.isInteger(normalizedOrderId) && normalizedOrderId > 0) { orderIdSet.add(normalizedOrderId); } } return Array.from(orderIdSet); } /** * 从自定义打印数据中提取订单ID列表。 * 支持 order_ids / orderIds 数组以及单个 order_id / orderId 字段。 * @param {Object} customData 自定义打印数据对象。 * @return {Array} 去重后的订单ID列表。 */ collectOrderIdsFromCustomizeData(customData = {}) { const normalizedData = customData && typeof customData === 'object' ? customData : {}; const orderIdSet = new Set(); // 尝试读取 order_ids 数组 if (Array.isArray(normalizedData.order_ids)) { for (const id of normalizedData.order_ids) { const num = Number(id || 0); if (Number.isInteger(num) && num > 0) { orderIdSet.add(num); } } } // 尝试读取 orderIds 数组 if (Array.isArray(normalizedData.orderIds)) { for (const id of normalizedData.orderIds) { const num = Number(id || 0); if (Number.isInteger(num) && num > 0) { orderIdSet.add(num); } } } // 尝试读取单个 order_id / orderId const singleId = Number(normalizedData.order_id || normalizedData.orderId || 0); if (Number.isInteger(singleId) && singleId > 0) { orderIdSet.add(singleId); } return Array.from(orderIdSet); } /** * 规范化快递打印平台编码,兼容常见别名。 * @param {Object} payload 入参。 * @param {string} payload.platformCode 原始平台编码。 * @param {Object} [payload.payloadBuilder] 快递 payload 组装器。 * @return {string} 规范化平台编码。 */ normalizeExpressPlatformCode(payload = {}) { const normalizedPayload = payload && typeof payload === 'object' ? payload : {}; const platformCode = String(normalizedPayload.platformCode || '').trim(); const payloadBuilder = normalizedPayload.payloadBuilder; if (payloadBuilder && typeof payloadBuilder.normalizePlatform === 'function') { try { const normalizedPlatformCode = String(payloadBuilder.normalizePlatform(platformCode) || '').trim().toLowerCase(); if (normalizedPlatformCode) { return normalizedPlatformCode; } } catch (error) { this.ctx.logger.warn('[print.send] 平台编码归一化失败,回退本地策略', { platformCode, reason: error && error.message ? error.message : `${error}`, }); } } const lowerPlatformCode = platformCode.toLowerCase(); if ([ 'shipinhao', 'wechatvideo' ].includes(lowerPlatformCode)) { return 'sph'; } if (lowerPlatformCode === 'ks') { return 'kuaishou'; } return lowerPlatformCode; } /** * 从打印记录 data 中提取订单ID列表。 * 兼容 data 为对象或 JSON 字符串,无法识别时返回空数组。 * @param {Object|string} printRecordData 打印记录 data 字段。 * @return {Array} 订单ID列表。 */ extractOrderIdsFromPrintRecordData(printRecordData) { let normalizedRecordData = printRecordData; if (typeof normalizedRecordData === 'string') { try { normalizedRecordData = JSON.parse(normalizedRecordData); } catch (error) { return []; } } if (!normalizedRecordData || typeof normalizedRecordData !== 'object' || Array.isArray(normalizedRecordData)) { return []; } return this.normalizeOrderIds(normalizedRecordData.order_ids); } /** * 更新订单主表打印状态。 * 仅在可识别订单ID时更新,failed 场景附加 print_status=none 条件避免覆盖已完成状态。 * @param {Object} payload 更新参数。 * @param {number|string} payload.warehouseId 仓库ID。 * @param {Array} payload.orderIds 订单ID列表。 * @param {'success'|'failed'} payload.result 回执结果。 * @return {Promise<{success:boolean,affectedRows:number,skipped:boolean,errorMessage:string}>} 更新结果。 */ async updateOrderPrintStatusByCallback(payload = {}) { const normalizedPayload = payload && typeof payload === 'object' ? payload : {}; const warehouseId = Number(normalizedPayload.warehouseId || 0); const orderIds = this.normalizeOrderIds(normalizedPayload.orderIds); const callbackResult = String(normalizedPayload.result || '').trim().toLowerCase(); if (!Number.isInteger(warehouseId) || warehouseId <= 0 || orderIds.length === 0) { return { success: true, affectedRows: 0, skipped: true, errorMessage: '', }; } try { const orderDeliveryFactory = this.ctx.model && this.ctx.model.OrderDeliveryFactory; if (!orderDeliveryFactory || typeof orderDeliveryFactory.getCurrentModel !== 'function') { return { success: false, affectedRows: 0, skipped: false, errorMessage: 'OrderDeliveryFactory 不可用', }; } const orderDeliveryModel = await orderDeliveryFactory.getCurrentModel(warehouseId); if (!orderDeliveryModel || typeof orderDeliveryModel.update !== 'function') { return { success: false, affectedRows: 0, skipped: false, errorMessage: 'OrderDeliveryModel 不可用', }; } const updatePayload = callbackResult === 'success' ? { print_status: 'fin' } : { print_status: 'error' }; const where = { id: orderIds, }; if (callbackResult === 'failed') { where.print_status = 'none'; } const updateResult = await orderDeliveryModel.update(updatePayload, { where, }); const affectedRows = Number(Array.isArray(updateResult) ? updateResult[0] : updateResult) || 0; return { success: true, affectedRows: affectedRows > 0 ? affectedRows : 0, skipped: false, errorMessage: '', }; } catch (error) { return { success: false, affectedRows: 0, skipped: false, errorMessage: error && error.message ? error.message : `${error}`, }; } } /** * 判断记录是否满足失败补打条件。 * @param {Object} record 打印记录。 * @param {boolean} force 是否强制补打(最小实现默认不放宽规则)。 * @return {{canRetry:boolean,reason:string}} 判断结果。 */ getRetryEligibility(record = {}, force = false) { const normalizedRecord = record && typeof record === 'object' ? record : {}; const status = String(normalizedRecord.status || '').trim(); const printStatus = String(normalizedRecord.print_status || '').trim(); if (status === 'sent' && [ 'unknown', 'printed' ].includes(printStatus)) { return { canRetry: false, reason: `状态为 sent/${printStatus},按规则跳过`, }; } const canRetry = status === 'failed' || [ 'print_failed', 'timeout' ].includes(printStatus); if (canRetry) { return { canRetry: true, reason: '', }; } const forceTip = force ? '(force 已开启,当前最小实现仍不放宽状态限制)' : ''; return { canRetry: false, reason: `状态不允许补打:status=${status || 'unknown'},print_status=${printStatus || 'unknown'}${forceTip}`, }; } /** * 获取打印任务编码冲突重试配置。 * @return {{maxRetries:number,baseDelayMs:number,jitterMs:number}} 归一化后的重试配置。 */ getPrintTaskCodeRetryConfig() { const retryConfig = this.app && this.app.config && this.app.config.printTaskCodeRetry ? this.app.config.printTaskCodeRetry : {}; const maxRetries = Number.parseInt(retryConfig.maxRetries, 10); const baseDelayMs = Number.parseInt(retryConfig.baseDelayMs, 10); const jitterMs = Number.parseInt(retryConfig.jitterMs, 10); return { maxRetries: Number.isInteger(maxRetries) && maxRetries > 0 ? maxRetries : 5, baseDelayMs: Number.isInteger(baseDelayMs) && baseDelayMs >= 0 ? baseDelayMs : 50, jitterMs: Number.isInteger(jitterMs) && jitterMs >= 0 ? jitterMs : 30, }; } /** * 获取打印任务编码回写重试配置。 * @return {{maxRetries:number,baseDelayMs:number,jitterMs:number}} 归一化后的回写重试配置。 */ getPrintTaskCodeWritebackRetryConfig() { const retryConfig = this.app && this.app.config && this.app.config.printTaskCodeWritebackRetry ? this.app.config.printTaskCodeWritebackRetry : {}; const maxRetries = Number.parseInt(retryConfig.maxRetries, 10); const baseDelayMs = Number.parseInt(retryConfig.baseDelayMs, 10); const jitterMs = Number.parseInt(retryConfig.jitterMs, 10); return { maxRetries: Number.isInteger(maxRetries) && maxRetries > 0 ? maxRetries : 3, baseDelayMs: Number.isInteger(baseDelayMs) && baseDelayMs >= 0 ? baseDelayMs : 50, jitterMs: Number.isInteger(jitterMs) && jitterMs >= 0 ? jitterMs : 30, }; } /** * 生成可排序且高熵的打印任务编码。 * 格式:PRT{yyyyMMddHHmmss}{processIdHex}{random8hex} * @return {string} 打印任务编码。 */ generateAtomicPrintTaskCode() { const now = new Date(); const datePart = [ now.getFullYear(), String(now.getMonth() + 1).padStart(2, '0'), String(now.getDate()).padStart(2, '0'), String(now.getHours()).padStart(2, '0'), String(now.getMinutes()).padStart(2, '0'), String(now.getSeconds()).padStart(2, '0'), ].join(''); const processIdHex = Number(process.pid || 0) .toString(16) .padStart(4, '0') .slice(-4); const randomHex = randomBytes(4).toString('hex'); return `PRT${datePart}${processIdHex}${randomHex}`; } /** * 判断是否为唯一索引冲突错误。 * @param {Error} error 异常对象。 * @return {boolean} 是否为唯一约束冲突。 */ isDuplicateKeyError(error) { if (!error || typeof error !== 'object') { return false; } const errorName = String(error.name || ''); const errorCode = String(error.code || error.parent && error.parent.code || ''); const errno = Number(error.errno || error.parent && error.parent.errno || 0); return errorName === 'SequelizeUniqueConstraintError' || errorCode === 'ER_DUP_ENTRY' || errno === 1062; } /** * 计算指数退避等待时长,并叠加随机抖动。 * @param {number} attempt 当前尝试次数(从 1 开始)。 * @param {number} baseDelayMs 基础等待毫秒。 * @param {number} jitterMs 抖动毫秒上限。 * @return {number} 需要等待的毫秒数。 */ calculateBackoffDelayMs(attempt, baseDelayMs, jitterMs) { const normalizedAttempt = Number.isInteger(attempt) && attempt > 0 ? attempt : 1; const normalizedBase = Number.isFinite(baseDelayMs) && baseDelayMs >= 0 ? baseDelayMs : 0; const normalizedJitter = Number.isFinite(jitterMs) && jitterMs >= 0 ? jitterMs : 0; const backoff = normalizedBase * (2 ** Math.max(0, normalizedAttempt - 1)); const jitter = normalizedJitter > 0 ? Math.floor(Math.random() * (normalizedJitter + 1)) : 0; return backoff + jitter; } /** * 异步等待指定毫秒数。 * @param {number} delayMs 等待毫秒。 * @return {Promise} 无返回值。 */ async sleep(delayMs) { const waitMs = Number.isFinite(delayMs) && delayMs > 0 ? Math.floor(delayMs) : 0; if (waitMs <= 0) { return; } await new Promise(resolve => setTimeout(resolve, waitMs)); } /** * 原子预占打印任务编码:依赖唯一索引插入映射表并处理冲突重试。 * @return {Promise} 预占成功的任务编码。 */ async reserveUniquePrintTaskCode() { const { maxRetries, baseDelayMs, jitterMs } = this.getPrintTaskCodeRetryConfig(); for (let attempt = 1; attempt <= maxRetries; attempt++) { const taskCode = this.generateAtomicPrintTaskCode(); try { await this.ctx.model.PrintTaskMap.create({ task_code: taskCode, print_record_id: null, provider: null, }); return taskCode; } catch (error) { if (!this.isDuplicateKeyError(error)) { throw error; } if (attempt >= maxRetries) { throw new Error(`打印任务编码生成冲突,重试 ${maxRetries} 次后失败`); } const waitMs = this.calculateBackoffDelayMs(attempt, baseDelayMs, jitterMs); this.ctx.logger.warn('[print.send] 打印任务编码冲突,准备重试', { attempt, maxRetries, waitMs, }); await this.sleep(waitMs); } } throw new Error('打印任务编码生成失败'); } /** * 通过事务(若可用)回写打印任务编码映射与打印记录。 * 单条打印记录仅允许绑定一个 task_code,重复回写同 task_code 可重入。 * @param {Object} payload 回写参数。 * @param {number|string} payload.printRecordId 打印记录ID。 * @param {string} payload.taskCode 任务编码。 * @param {string} [payload.provider] provider 返回任务ID。 * @return {Promise} 无返回值。 */ async bindTaskCodeToPrintRecord(payload = {}) { const printRecordId = Number(payload.printRecordId || 0); const taskCode = String(payload.taskCode || '').trim(); const provider = String(payload.provider || '').trim(); if (!printRecordId || !taskCode) { throw new Error('回写任务编码失败:printRecordId 或 taskCode 缺失'); } const runBinding = async transaction => { const mapUpdatePayload = { print_record_id: printRecordId, }; if (provider) { mapUpdatePayload.provider = provider; } await this.ctx.model.PrintTaskMap.update(mapUpdatePayload, { where: { task_code: taskCode }, transaction, }); const lockOption = transaction && transaction.LOCK ? { lock: transaction.LOCK.UPDATE } : {}; const printRecord = await this.ctx.model.PrintRecord.findOne({ where: { id: printRecordId }, transaction, ...lockOption, raw: true, }); if (!printRecord) { throw new Error(`打印记录不存在,id=${printRecordId}`); } const existingTaskCode = String(printRecord.print_task_code || '').trim(); if (existingTaskCode && existingTaskCode !== taskCode) { throw new Error(`打印记录已绑定其他任务编码,id=${printRecordId}`); } const needWriteTaskCode = existingTaskCode !== taskCode; const normalizedStatus = String(printRecord.status || '').trim(); const normalizedSendStatus = String(printRecord.send_status || '').trim(); const normalizedPrintStatus = String(printRecord.print_status || '').trim(); const needUpdateStatus = normalizedStatus !== 'sent' || normalizedSendStatus !== 'sent' || normalizedPrintStatus !== 'printed' || !printRecord.sent_time; if (!needWriteTaskCode && !needUpdateStatus) { return; } const printRecordUpdatePayload = needUpdateStatus ? this.buildSentPrintRecordUpdatePayload({ sentTime: printRecord.sent_time || new Date() }) : {}; if (needWriteTaskCode) { printRecordUpdatePayload.print_task_code = taskCode; } await this.ctx.model.PrintRecord.update(printRecordUpdatePayload, { where: { id: printRecordId }, transaction, }); }; if (this.ctx.model && typeof this.ctx.model.transaction === 'function') { await this.ctx.model.transaction(async transaction => { await runBinding(transaction); }); return; } await runBinding(null); } /** * 回写任务编码并支持失败重试,保证 provider 成功后写回可重试。 * @param {Object} payload 回写参数。 * @param {number|string} payload.printRecordId 打印记录ID。 * @param {string} payload.taskCode 任务编码。 * @param {string} [payload.provider] provider 返回任务ID。 * @return {Promise} 无返回值。 */ async bindTaskCodeToPrintRecordWithRetry(payload = {}) { const { maxRetries, baseDelayMs, jitterMs } = this.getPrintTaskCodeWritebackRetryConfig(); let lastError = null; for (let attempt = 1; attempt <= maxRetries; attempt++) { try { await this.bindTaskCodeToPrintRecord(payload); return; } catch (error) { lastError = error; const errorMessage = error && error.message ? error.message : `${error}`; this.ctx.logger.error('[print.send] 打印任务编码回写失败', { attempt, maxRetries, printRecordId: payload.printRecordId, taskCode: payload.taskCode, error: errorMessage, }); if (attempt >= maxRetries) { break; } const waitMs = this.calculateBackoffDelayMs(attempt, baseDelayMs, jitterMs); await this.sleep(waitMs); } } throw new Error(`打印任务编码回写失败,可重试。原因:${lastError && lastError.message ? lastError.message : `${lastError}`}`); } /** * 发送打印任务到打印电脑。 * 本方法不做打印锁状态校验,不阻止重复打印请求。 * 仅在 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, }); } // 从自定义打印数据中尝试提取关联的配送订单ID,用于后续同步 print_status const customizeOrderIds = type !== 'express' ? this.collectOrderIdsFromCustomizeData(data) : []; let printRecord = null; if (type !== 'express') { // 生成打印编号并记录到数据库 try { const printRecordData = { template, data }; if (customizeOrderIds.length > 0) { printRecordData.order_ids = customizeOrderIds; } printRecord = await ctx.model.PrintRecord.create(this.buildPendingPrintRecordPayload({ warehouse_id: warehouseId, computer_id: computerId, printer, type, data: printRecordData, })); 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++) { let cellContent = item.content[i] && item.content[i][j] ? item.content[i][j] : ''; // 解析单元格字段码为实际数据,与 text 类型保持一致的解析逻辑 for (const key in data) { if (String(cellContent) === key) { cellContent = data[key]; } } tableHtml += ``; } tableHtml += ''; } tableHtml += '
${cellContent}
'; 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 }); } const payloadBuilder = new ExpressPrintPayloadBuilder({ baseDir: this.app.baseDir }); const idGenerator = new RequestScopedPrintIdGenerator(requestCode); const expressSendResult = await this.sendExpressWaveGroups({ warehouseId, waveGroups: data.waveGroups, requestCode, printStation: expressPrintStation.data, payloadBuilder, idGenerator, expressRecordFields: expressRecordFields.data, platformComponents: platformComponentsResult.data, type, template, data, }); if (!expressSendResult.success) { this.ctx.logger.error('[print.send] 最终返回 failure', { warehouseId, type, printId: expressSendResult.printId || 0, reason: expressSendResult.error, }); return this.fail(expressSendResult.error, { code: 504, printId: expressSendResult.printId || 0, printIds: Array.isArray(expressSendResult.printIds) ? expressSendResult.printIds : [], }); } this.ctx.logger.info('[print.send] 最终返回 success', { warehouseId, type, printId: expressSendResult.printId || 0, printIdsCount: Array.isArray(expressSendResult.printIds) ? expressSendResult.printIds.length : 0, }); return this.success('发送打印任务成功', { code: 200, printId: expressSendResult.printId || 0, printIds: Array.isArray(expressSendResult.printIds) ? expressSendResult.printIds : [], }); } 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(this.buildSentPrintRecordUpdatePayload()); // 同步更新关联配送订单的 print_status 为 'fin' if (customizeOrderIds.length > 0) { const updateResult = await this.updateOrderPrintStatusByCallback({ warehouseId, orderIds: customizeOrderIds, result: 'success', }); if (!updateResult.success) { this.ctx.logger.error('[print.send] 同步订单 print_status 失败', { warehouseId, type, orderIdsCount: customizeOrderIds.length, reason: updateResult.errorMessage, }); } } this.ctx.logger.info('[print.send] 最终返回 success', { warehouseId, type, printId: printRecord.id, }); return this.success('发送打印任务成功', { code: 200, printId: printRecord.id }); } await printRecord.update(this.buildSendFailedPrintRecordUpdatePayload({ errorMessage: 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} data 补打参数。 * @param {Array} data.print_ids 需要补打的打印记录 ID 列表。 * @param {boolean} [data.force=false] 是否强制补打(最小实现默认不放宽状态规则)。 * @param {number|string} [data.warehouse_id] 显式指定仓库 ID(用于定时任务等无登录上下文场景)。 * @return {Promise} 统一返回结构。 */ async retryFailed(data = {}) { const { ctx } = this; const requestData = data && typeof data === 'object' ? data : {}; const { print_ids: rawPrintIds, force = false, warehouse_id: rawWarehouseId, } = requestData; const normalizedWarehouseId = Number(rawWarehouseId); const userWarehouseId = Number(ctx.user && ctx.user.store_id); const warehouseId = Number.isInteger(normalizedWarehouseId) && normalizedWarehouseId > 0 ? normalizedWarehouseId : (Number.isInteger(userWarehouseId) && userWarehouseId > 0 ? userWarehouseId : 0); if (!warehouseId) { return this.fail('warehouse_id 参数缺失,且当前上下文无可用仓库信息', { code: 400 }); } if (!Array.isArray(rawPrintIds) || rawPrintIds.length === 0) { return this.fail('print_ids 参数不能为空数组', { code: 400 }); } const printIds = Array.from(new Set(rawPrintIds .map(item => Number(item)) .filter(item => Number.isInteger(item) && item > 0))); if (printIds.length === 0) { return this.fail('print_ids 参数不合法,必须包含正整数 ID', { code: 400 }); } const sourceRecords = await ctx.model.PrintRecord.findAll({ where: { id: printIds, warehouse_id: warehouseId, }, raw: true, }); const sourceRecordMap = new Map(sourceRecords.map(item => [ Number(item.id), item ])); const retried = []; const skipped = []; let successCount = 0; let failedCount = 0; for (const printId of printIds) { const sourceRecord = sourceRecordMap.get(printId); if (!sourceRecord) { skipped.push({ print_id: printId, reason: '记录不存在或不属于当前仓库', }); continue; } const eligibility = this.getRetryEligibility(sourceRecord, Boolean(force)); if (!eligibility.canRetry) { skipped.push({ print_id: printId, reason: eligibility.reason, }); continue; } const payloadResult = this.normalizeRetrySendPayload(sourceRecord.data); if (!payloadResult.success) { skipped.push({ print_id: printId, reason: payloadResult.error, }); continue; } const sendPayload = payloadResult.data; const taskCode = await this.reserveUniquePrintTaskCode(); if (sendPayload.data.task && typeof sendPayload.data.task === 'object' && !Array.isArray(sendPayload.data.task)) { sendPayload.data.task.taskID = taskCode; } const newPrintRecord = await ctx.model.PrintRecord.create(this.buildPendingPrintRecordPayload({ warehouse_id: sourceRecord.warehouse_id, computer_id: sourceRecord.computer_id, printer: sourceRecord.printer, type: sourceRecord.type, request_code: sourceRecord.request_code, wave_id: sourceRecord.wave_id, wave_no: sourceRecord.wave_no, platform_code: sourceRecord.platform_code, platform_name: sourceRecord.platform_name, sys_logistics_code: sourceRecord.sys_logistics_code, sys_logistics_name: sourceRecord.sys_logistics_name, retry_of_print_id: sourceRecord.id, data: sendPayload, })); try { const sendResult = await this.service.systems.print.index.sendToComputer({ warehouse: warehouseId, computerId: sourceRecord.computer_id, data: { ...sendPayload, printId: newPrintRecord.id, }, }); if (sendResult.status !== 'success') { const failedMessage = sendResult.error || '打印服务返回失败'; await newPrintRecord.update(this.buildSendFailedPrintRecordUpdatePayload({ errorMessage: failedMessage, failCode: 'SEND_FAILED', })); retried.push({ source_print_id: sourceRecord.id, new_print_id: newPrintRecord.id, task_code: taskCode, status: 'failed', }); failedCount += 1; continue; } const providerTaskId = String( sendResult && (sendResult.taskId || sendResult.task_id || sendResult.providerTaskId || sendResult.id) ? (sendResult.taskId || sendResult.task_id || sendResult.providerTaskId || sendResult.id) : '' ).trim(); await this.bindTaskCodeToPrintRecordWithRetry({ printRecordId: newPrintRecord.id, taskCode, provider: providerTaskId, }); retried.push({ source_print_id: sourceRecord.id, new_print_id: newPrintRecord.id, task_code: taskCode, status: 'sent', }); successCount += 1; } catch (error) { await newPrintRecord.update(this.buildSendFailedPrintRecordUpdatePayload({ errorMessage: error && error.message ? error.message : `${error}`, failCode: 'SEND_FAILED', })); retried.push({ source_print_id: sourceRecord.id, new_print_id: newPrintRecord.id, task_code: taskCode, status: 'failed', }); failedCount += 1; } } return this.success('失败项补打处理完成', { code: 200, success_count: successCount, failed_count: failedCount, skipped_count: skipped.length, retried, skipped, }); } /** * 校验快递打印请求的必要参数。 * @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); } /** * 从波次平台数据中提取订单ID列表。 * * 优先使用平台分组透出的 order_ids;若缺失则回退读取 orders[*].order_id。 * * @param {Array} waveGroups 波次平台分组。 * @return {Array} 去重后的订单ID列表。 */ collectOrderIdsFromWaveGroups(waveGroups = []) { const normalizedWaveGroups = Array.isArray(waveGroups) ? waveGroups : []; const orderIdSet = new Set(); for (const waveGroup of normalizedWaveGroups) { const platforms = Array.isArray(waveGroup && waveGroup.platforms) ? waveGroup.platforms : []; for (const platformGroup of platforms) { const platformOrderIds = Array.isArray(platformGroup && platformGroup.order_ids) ? platformGroup.order_ids : []; for (const orderId of platformOrderIds) { const normalizedOrderId = Number(orderId || 0); if (Number.isInteger(normalizedOrderId) && normalizedOrderId > 0) { orderIdSet.add(normalizedOrderId); } } const orders = Array.isArray(platformGroup && platformGroup.orders) ? platformGroup.orders : []; for (const order of orders) { const normalizedOrderId = Number(order && order.order_id || 0); if (Number.isInteger(normalizedOrderId) && normalizedOrderId > 0) { orderIdSet.add(normalizedOrderId); } } } } return Array.from(orderIdSet); } /** * 从通知锁定入参中提取订单ID。 * * 优先使用 order_ids/orderIds;为空时回退使用 waveGroups 提取。 * * @param {Object} payload 通知锁定入参。 * @param {Array} [payload.order_ids] 订单ID列表(推荐)。 * @param {Array} [payload.orderIds] 兼容驼峰订单ID列表。 * @param {Array} [payload.waveGroups] 波次分组。 * @param {Object} [payload.data] 兼容 print.send 结构的数据体。 * @return {{orderIds:Array,orderIdsCount:number,waveGroupsCount:number,source:string}} 提取结果。 */ extractOrderIdsFromNotifyLockPayload(payload = {}) { const normalizedPayload = payload && typeof payload === 'object' ? payload : {}; const data = normalizedPayload.data && typeof normalizedPayload.data === 'object' ? normalizedPayload.data : {}; const directOrderIds = this.normalizeOrderIds(Array.isArray(normalizedPayload.order_ids) ? normalizedPayload.order_ids : (Array.isArray(normalizedPayload.orderIds) ? normalizedPayload.orderIds : [])); const waveGroups = Array.isArray(normalizedPayload.waveGroups) ? normalizedPayload.waveGroups : (Array.isArray(data.waveGroups) ? data.waveGroups : []); const waveGroupOrderIds = this.collectOrderIdsFromWaveGroups(waveGroups); const hasDirectOrderIds = directOrderIds.length > 0; const orderIds = hasDirectOrderIds ? directOrderIds : waveGroupOrderIds; return { orderIds, orderIdsCount: orderIds.length, waveGroupsCount: waveGroups.length, source: hasDirectOrderIds ? 'order_ids' : 'waveGroups', }; } /** * 构建 notifyLock 的轻量日志摘要,避免落库超大对象。 * * @param {Object} payload notifyLock 原始入参。 * @param {Object} extracted 已提取摘要信息。 * @param {Array} [extracted.orderIds] 订单ID列表。 * @param {number} [extracted.orderIdsCount] 订单数量。 * @param {number} [extracted.waveGroupsCount] 波次数量。 * @param {string} [extracted.source] 订单来源标识。 * @return {Object} 轻量可落库摘要。 */ buildNotifyLockInputSummary(payload = {}, extracted = {}) { const normalizedPayload = payload && typeof payload === 'object' ? payload : {}; const data = normalizedPayload.data && typeof normalizedPayload.data === 'object' ? normalizedPayload.data : {}; const orderIds = Array.isArray(extracted.orderIds) ? extracted.orderIds : []; const orderIdsCount = Number(extracted.orderIdsCount || orderIds.length || 0); const waveGroupsCount = Number(extracted.waveGroupsCount || 0); const source = String(extracted.source || '').trim(); const requestCode = normalizedPayload.requestCode ? String(normalizedPayload.requestCode).slice(0, 128) : (normalizedPayload.request_code ? String(normalizedPayload.request_code).slice(0, 128) : ''); return { action: 'notifyLock', source, order_ids_count: orderIdsCount, order_ids_sample: orderIds.slice(0, 100), wave_groups_count: waveGroupsCount, request_code: requestCode, payload_keys: Object.keys(normalizedPayload).slice(0, 20), data_keys: Object.keys(data).slice(0, 20), has_data: Object.keys(data).length > 0, }; } /** * 获取打印相关订单操作日志的操作人信息。 * * 取值优先级:ctx.state.user -> ctx.user,字段优先尝试 employees/operator/id 与 name。 * * @return {{id:string|null,name:string}} 操作人信息。 */ getPrintOrderOperationOperator() { const stateUser = this.ctx && this.ctx.state && this.ctx.state.user && typeof this.ctx.state.user === 'object' ? this.ctx.state.user : null; const ctxUser = this.ctx && this.ctx.user && typeof this.ctx.user === 'object' ? this.ctx.user : null; const user = stateUser || ctxUser || {}; const rawOperatorId = user.employees_id ?? user.operator_id ?? user.id; const rawOperatorName = user.employees_name ?? user.operator_name ?? user.real_name ?? user.name; const operatorId = rawOperatorId === undefined || rawOperatorId === null ? null : (String(rawOperatorId).trim() || null); const operatorName = rawOperatorName === undefined || rawOperatorName === null ? 'system' : (String(rawOperatorName).trim() || 'system'); return { id: operatorId, name: operatorName, }; } /** * 按订单ID批量写入打印相关订单操作日志。 * * 日志写入失败不会中断主流程,仅记录 warn/error。 * * @param {Object} payload 写入参数。 * @param {Array} payload.orderIds 订单ID列表。 * @param {string} payload.source 来源标识(如 print.send/print.notifyLock)。 * @param {string} payload.message 日志消息。 * @param {string} [payload.operationCode='ORDER_PRINT'] 操作编码。 * @return {Promise} 无返回值。 */ async writePrintOrderOperationLogsByOrderIds(payload = {}) { const normalizedPayload = payload && typeof payload === 'object' ? payload : {}; const orderIds = this.normalizeOrderIds(normalizedPayload.orderIds); if (orderIds.length === 0) { return; } const source = String(normalizedPayload.source || '').trim() || 'print.send'; const message = String(normalizedPayload.message || '').trim() || `${source} 执行完成`; const operationCode = String(normalizedPayload.operationCode || '').trim() || 'ORDER_PRINT'; const warehouseId = Number(this.ctx && this.ctx.user && this.ctx.user.store_id || 0); const operationLogService = this.ctx && this.ctx.service && this.ctx.service.systems && this.ctx.service.systems.operationLog; if (!operationLogService || typeof operationLogService.createOperationLogs !== 'function') { this.ctx.logger.warn('[print.operationLog] operationLog 批量写入服务不可用,跳过日志写入', { source, orderIdsCount: orderIds.length, }); return; } const operator = this.getPrintOrderOperationOperator(); const payloads = orderIds.map(orderId => ({ businessType: 'order', businessId: orderId, operationCode, operator, extras: { warehouseId, message, }, })); try { const results = await operationLogService.createOperationLogs(payloads); if (!Array.isArray(results)) { return; } for (let index = 0; index < payloads.length; index++) { if (results[index]) { continue; } this.ctx.logger.warn('[print.operationLog] 订单操作日志写入失败,不影响主流程', { source, orderId: payloads[index].businessId, operationCode, }); } } catch (error) { this.ctx.logger.error('[print.operationLog] 批量写入订单操作日志异常,不影响主流程', { source, orderIdsCount: orderIds.length, error: error && error.message ? error.message : `${error}`, }); } } /** * 通知锁定接口:仅执行订单锁定流程,不发送打印任务。 * * @param {Object} data 入参。 * @param {Array} [data.order_ids] 订单ID列表(推荐)。 * @param {Array} [data.orderIds] 兼容驼峰订单ID列表。 * @param {Array} [data.waveGroups] 波次分组(兼容 print.send 轻量版本)。 * @param {Object} [data.data] 兼容 print.send 的 data 包装。 * @return {Promise} 统一 success/fail 返回结构。 */ async notifyLock(data = {}) { const warehouseId = Number(this.ctx && this.ctx.user && this.ctx.user.store_id || 0); const { orderIds, orderIdsCount, waveGroupsCount, source, } = this.extractOrderIdsFromNotifyLockPayload(data); const notifyLockInputSummary = this.buildNotifyLockInputSummary(data, { orderIds, orderIdsCount, waveGroupsCount, source, }); let printRecord = null; try { printRecord = await this.ctx.model.PrintRecord.create(this.buildPendingPrintRecordPayload({ warehouse_id: warehouseId, computer_id: 0, printer: 'notifyLock', type: 'notify_lock', data: notifyLockInputSummary, request_code: notifyLockInputSummary.request_code || null, })); } catch (error) { this.ctx.logger.error('[print.notifyLock] PrintRecord 创建失败', { warehouseId, error: error && error.message ? error.message : `${error}`, stack: error && error.stack ? error.stack : '', }); } if (orderIdsCount === 0) { if (printRecord && typeof printRecord.update === 'function') { try { await printRecord.update(this.buildSendFailedPrintRecordUpdatePayload({ errorMessage: '未提取到有效订单ID,请传入 order_ids 或 waveGroups', failCode: 'NOTIFY_LOCK_INVALID_INPUT', })); } catch (error) { this.ctx.logger.error('[print.notifyLock] PrintRecord 更新失败', { warehouseId, printId: printRecord.id, error: error && error.message ? error.message : `${error}`, stack: error && error.stack ? error.stack : '', }); } } return this.fail('未提取到有效订单ID,请传入 order_ids 或 waveGroups', { code: 400, locked_count: 0, order_ids_count: 0, wave_groups_count: waveGroupsCount, }); } const lockResult = await this.lockOrderDeliveryAfterPrintSentSuccess({ warehouseId, orderIds, }); if (!lockResult.success) { await this.writePrintOrderOperationLogsByOrderIds({ orderIds, source: 'print.notifyLock', message: `通知锁定执行失败,原因=${lockResult.errorMessage || '未知错误'}`, }); if (printRecord && typeof printRecord.update === 'function') { try { await printRecord.update(this.buildSendFailedPrintRecordUpdatePayload({ errorMessage: lockResult.errorMessage || '未知错误', failCode: 'NOTIFY_LOCK_FAILED', })); } catch (error) { this.ctx.logger.error('[print.notifyLock] PrintRecord 更新失败', { warehouseId, printId: printRecord.id, error: error && error.message ? error.message : `${error}`, stack: error && error.stack ? error.stack : '', }); } } return this.fail(`订单锁定失败:${lockResult.errorMessage || '未知错误'}`, { code: 500, locked_count: 0, order_ids_count: orderIdsCount, order_ids: orderIds, }); } if (printRecord && typeof printRecord.update === 'function') { try { await printRecord.update(this.buildSentPrintRecordUpdatePayload()); } catch (error) { this.ctx.logger.error('[print.notifyLock] PrintRecord 更新失败', { warehouseId, printId: printRecord.id, error: error && error.message ? error.message : `${error}`, stack: error && error.stack ? error.stack : '', }); } } await this.writePrintOrderOperationLogsByOrderIds({ orderIds, source: 'print.notifyLock', message: `通知锁定执行成功,locked_count=${lockResult.lockedCount}`, }); return this.success('ok', { code: 0, locked_count: lockResult.lockedCount, order_ids_count: orderIdsCount, order_ids: orderIds, source, }); } /** * notifyLock 的 snake_case 兼容别名。 * * @param {Object} data 入参。 * @return {Promise} 与 notifyLock 一致的返回结构。 */ async notify_lock(data = {}) { return this.notifyLock(data); } /** * 在打印发送成功后批量锁定订单。 * * 仅将 print_lock_status=none 的订单更新为 warehouse,避免覆盖既有锁定状态。 * * @param {Object} payload 锁定参数。 * @param {number|string} payload.warehouseId 仓库ID。 * @param {Array} payload.orderIds 订单ID数组。 * @return {Promise<{success:boolean,lockedCount:number,errorMessage:string}>} 锁定结果。 */ async lockOrderDeliveryAfterPrintSentSuccess(payload = {}) { const normalizedPayload = payload && typeof payload === 'object' ? payload : {}; const warehouseId = Number(normalizedPayload.warehouseId || 0); const orderIds = Array.isArray(normalizedPayload.orderIds) ? Array.from(new Set(normalizedPayload.orderIds .map(orderId => Number(orderId || 0)) .filter(orderId => Number.isInteger(orderId) && orderId > 0))) : []; if (!Number.isInteger(warehouseId) || warehouseId <= 0 || orderIds.length === 0) { return { success: true, lockedCount: 0, errorMessage: '', }; } try { const orderDeliveryFactory = this.ctx.model && this.ctx.model.OrderDeliveryFactory; if (!orderDeliveryFactory || typeof orderDeliveryFactory.getCurrentModel !== 'function') { return { success: false, lockedCount: 0, errorMessage: 'OrderDeliveryFactory 不可用', }; } const orderDeliveryModel = await orderDeliveryFactory.getCurrentModel(warehouseId); if (!orderDeliveryModel || typeof orderDeliveryModel.update !== 'function') { return { success: false, lockedCount: 0, errorMessage: 'OrderDeliveryModel 不可用', }; } const updateResult = await orderDeliveryModel.update({ print_lock_status: 'warehouse', print_status: 'fin', }, { where: { id: orderIds, }, }); const lockedCount = Number(Array.isArray(updateResult) ? updateResult[0] : updateResult) || 0; return { success: true, lockedCount: lockedCount > 0 ? lockedCount : 0, errorMessage: '', }; } catch (error) { return { success: false, lockedCount: 0, errorMessage: error && error.message ? error.message : `${error}`, }; } } /** * 加载并校验 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.PrintPlatform.findAll({ attributes: [ 'platform_code', 'platform_name' ], where: { platform_code: platformCodes, }, raw: true, }); const platformComponentMap = {}; for (const row of platformRows) { const platformCode = String(row && row.platform_code ? row.platform_code : '').trim(); if (!platformCode) { continue; } platformComponentMap[platformCode] = String(row && row.platform_name ? row.platform_name : '').trim(); } console.log('platformComponentMap', platformComponentMap); 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 {string} payload.requestCode 请求参数码。 * @param {Object} payload.printStation 打印台配置。 * @param {Object} payload.payloadBuilder 快递模板组装器。 * @param {Object} payload.idGenerator 本次请求 ID 生成器。 * @param {Object} payload.expressRecordFields 快递打印记录字段。 * @param {Object} payload.platformComponents 平台到打印组件映射。 * @param {string} payload.type 打印类型。 * @param {Object|null} payload.template 模板数据。 * @param {Object} payload.data 业务数据。 * @return {Promise<{success:boolean,error?:string,taskCodes?:Array,printId:number,printIds:Array}>} 发送结果。 */ async sendExpressWaveGroups(payload = {}) { const normalizedPayload = payload && typeof payload === 'object' ? payload : {}; const waveGroups = Array.isArray(normalizedPayload.waveGroups) ? normalizedPayload.waveGroups : []; const generatedTaskCodes = []; const createdPrintRecordIds = []; 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, }; const requestCode = String(normalizedPayload.requestCode || '').trim() || null; const rawWaveId = waveGroup && waveGroup.wave_id; const normalizedWaveId = rawWaveId === null || rawWaveId === undefined || String(rawWaveId).trim() === '' ? null : Number(rawWaveId); const waveId = Number.isFinite(normalizedWaveId) ? normalizedWaveId : null; const waveNo = String(waveGroup && waveGroup.wave_no ? waveGroup.wave_no : '').trim() || null; const platformCodeForRecord = String(platformGroup && platformGroup.platform ? platformGroup.platform : '').trim() || null; const platformName = String(platformGroup && platformGroup.platform_name ? platformGroup.platform_name : '').trim() || null; const sysLogisticsCode = String(platformGroup && platformGroup.sys_logistics_code ? platformGroup.sys_logistics_code : '').trim() || null; const sysLogisticsName = String(platformGroup && platformGroup.sys_logistics_name ? platformGroup.sys_logistics_name : '').trim() || null; 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} 未配置打印组件`, printId: createdPrintRecordIds[0] || 0, printIds: createdPrintRecordIds, }; } 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, printId: createdPrintRecordIds[0] || 0, printIds: createdPrintRecordIds, }; } const normalizedPlatformCode = this.normalizeExpressPlatformCode({ platformCode: platformGroup && platformGroup.platform ? platformGroup.platform : '', payloadBuilder: normalizedPayload.payloadBuilder, }); const isKuaishouPlatform = normalizedPlatformCode === 'kuaishou'; 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 batchOrderIds = this.collectOrderIdsFromPlatformGroup(platformGroup, batchOrders); const currentPrinterName = printerNameResult.data; const batchSummary = { ...groupSummary, batchIndex: batchIndex + 1, batchCount: orderBatches.length, batchOrdersCount: batchOrders.length, }; 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; } currentTaskCode = await this.reserveUniquePrintTaskCode(); if (requestPayload.task && typeof requestPayload.task === 'object' && !Array.isArray(requestPayload.task)) { requestPayload.task.taskID = currentTaskCode; } if (currentTaskCode && !generatedTaskCodes.includes(currentTaskCode)) { generatedTaskCodes.push(currentTaskCode); } 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 : '快递打印任务组装失败', printId: createdPrintRecordIds[0] || 0, printIds: createdPrintRecordIds, }; } let currentPrintRecord; try { currentPrintRecord = await this.ctx.model.PrintRecord.create(this.buildPendingPrintRecordPayload({ warehouse_id: normalizedPayload.warehouseId, computer_id: normalizedPayload.expressRecordFields.computer_id, printer: currentPrinterName, type: normalizedPayload.type, request_code: requestCode, wave_id: waveId, wave_no: waveNo, platform_code: platformCodeForRecord, platform_name: platformName, sys_logistics_code: sysLogisticsCode, sys_logistics_name: sysLogisticsName, data: { printer: currentPrinterName, component, type: 'express', order_ids: batchOrderIds, data: requestPayload, }, })); createdPrintRecordIds.push(currentPrintRecord.id); this.ctx.logger.info('[print.send] PrintRecord 创建成功', { ...batchSummary, printId: currentPrintRecord.id, computerId: normalizedPayload.expressRecordFields.computer_id, printer: currentPrinterName, }); } catch (error) { this.ctx.logger.error('[print.send] PrintRecord 创建失败', { ...batchSummary, computerId: normalizedPayload.expressRecordFields.computer_id, printer: currentPrinterName, error: error && error.message ? error.message : `${error}`, stack: error && error.stack ? error.stack : '', }); return { success: false, error: error && error.message ? error.message : '打印记录创建失败', printId: createdPrintRecordIds[0] || 0, printIds: createdPrintRecordIds, }; } const printData = { printer: currentPrinterName, component, type: 'express', order_ids: batchOrderIds, data: requestPayload, printId: currentPrintRecord.id, }; 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; await this.writePrintOrderOperationLogsByOrderIds({ orderIds: batchOrderIds, source: 'print.send', message: `批次发送失败,原因=${error && error.message ? error.message : `${error}`}`, }); this.ctx.logger.error('[print.send] sendToComputer 调用失败', { ...batchSummary, printId: currentPrintRecord.id, computerId: normalizedPayload.printStation.computer_id, durationMs: sendDurationMs, reason: error && error.message ? error.message : `${error}`, }); await currentPrintRecord.update(this.buildSendFailedPrintRecordUpdatePayload({ errorMessage: error && error.message ? error.message : `${error}`, })); this.ctx.logger.error('[print.send] 平台快递组发送结束', { ...batchSummary, printId: currentPrintRecord.id, computerId: normalizedPayload.printStation.computer_id, status: 'failure', reason: error && error.message ? error.message : `${error}`, }); return { success: false, error: error && error.message ? error.message : '打印服务调用失败', printId: createdPrintRecordIds[0] || 0, printIds: createdPrintRecordIds, }; } const sendDurationMs = Date.now() - sendStartAt; if (sendResult.status !== 'success') { await this.writePrintOrderOperationLogsByOrderIds({ orderIds: batchOrderIds, source: 'print.send', message: `批次发送失败,原因=${sendResult.error || '打印服务返回失败'}`, }); this.ctx.logger.error('[print.send] sendToComputer 调用失败', { ...batchSummary, printId: currentPrintRecord.id, computerId: normalizedPayload.printStation.computer_id, durationMs: sendDurationMs, reason: sendResult.error || '打印服务返回失败', }); await currentPrintRecord.update(this.buildSendFailedPrintRecordUpdatePayload({ errorMessage: sendResult.error || '打印服务返回失败', })); this.ctx.logger.error('[print.send] 平台快递组发送结束', { ...batchSummary, printId: currentPrintRecord.id, 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 || '打印服务返回失败', printId: createdPrintRecordIds[0] || 0, printIds: createdPrintRecordIds, }; } const providerTaskId = String( sendResult && (sendResult.taskId || sendResult.task_id || sendResult.providerTaskId || sendResult.id) ? (sendResult.taskId || sendResult.task_id || sendResult.providerTaskId || sendResult.id) : '' ).trim(); try { await this.bindTaskCodeToPrintRecordWithRetry({ printRecordId: currentPrintRecord.id, taskCode: currentTaskCode, provider: providerTaskId, }); } catch (error) { await this.writePrintOrderOperationLogsByOrderIds({ orderIds: batchOrderIds, source: 'print.send', message: `批次发送失败,原因=${error && error.message ? error.message : `${error}`}`, }); await currentPrintRecord.update(this.buildSendFailedPrintRecordUpdatePayload({ errorMessage: error && error.message ? error.message : `${error}`, })); this.ctx.logger.error('[print.send] 平台快递组发送成功但回写失败', { ...batchSummary, printId: currentPrintRecord.id, taskCode: currentTaskCode, providerTaskId, reason: error && error.message ? error.message : `${error}`, }); return { success: false, error: `打印任务发送成功但回写失败:${error && error.message ? error.message : '未知错误'}`, printId: createdPrintRecordIds[0] || 0, printIds: createdPrintRecordIds, }; } const lockResult = await this.lockOrderDeliveryAfterPrintSentSuccess({ warehouseId: normalizedPayload.warehouseId, orderIds: batchOrderIds, }); if (!lockResult.success) { this.ctx.logger.error('[print.send] 批次发送成功后锁定订单失败', { ...batchSummary, warehouseId: normalizedPayload.warehouseId, orderIdsCount: batchOrderIds.length, reason: lockResult.errorMessage, }); } const orderPrintStatusUpdateResult = await this.updateOrderPrintStatusByCallback({ warehouseId: normalizedPayload.warehouseId, orderIds: batchOrderIds, result: 'success', }); if (!orderPrintStatusUpdateResult.success) { this.ctx.logger.error('[print.send] 批次发送成功后同步订单主表 print_status 失败', { ...batchSummary, warehouseId: normalizedPayload.warehouseId, orderIdsCount: batchOrderIds.length, reason: orderPrintStatusUpdateResult.errorMessage, }); } await this.writePrintOrderOperationLogsByOrderIds({ orderIds: batchOrderIds, source: 'print.send', message: `批次发送结束成功,print_id=${currentPrintRecord.id},order_count=${batchOrderIds.length}`, }); this.ctx.logger.info('[print.send] 平台快递组发送结束', { ...batchSummary, printId: currentPrintRecord.id, computerId: normalizedPayload.printStation.computer_id, status: 'success', }); } } } return { success: true, taskCodes: generatedTaskCodes, printId: createdPrintRecordIds[0] || 0, printIds: createdPrintRecordIds, }; } /** * 解析打印回执时间,解析失败时回退当前时间。 * @param {string|Date|number} callbackTime 回执时间。 * @return {Date} 归一化后的打印时间。 */ parsePrintCallbackTime(callbackTime) { if (callbackTime instanceof Date && !Number.isNaN(callbackTime.getTime())) { return callbackTime; } if (callbackTime === undefined || callbackTime === null || callbackTime === '') { return new Date(); } const parsedDate = new Date(callbackTime); if (Number.isNaN(parsedDate.getTime())) { return new Date(); } return parsedDate; } /** * 处理打印结果回执,按 print_task_code 更新打印记录并保证幂等。 * @param {Object} data 回执参数。 * @param {string} data.print_task_code 打印任务编码。 * @param {string} data.result 回执结果,仅支持 success/failed。 * @param {string} [data.error_message] 失败原因。 * @param {string} [data.fail_code] 失败编码。 * @param {string} [data.printer] 打印机标识。 * @param {string|Date|number} [data.callback_time] 回执时间。 * @return {Promise} 统一回执处理结果。 */ async handlePrintCallback(data = {}) { const requestData = data && typeof data === 'object' ? data : {}; const { print_task_code: printTaskCode, result, error_message: errorMessage, fail_code: failCode, printer, callback_time: callbackTime, } = requestData; const normalizedPrintTaskCode = String(printTaskCode || '').trim(); if (!normalizedPrintTaskCode) { return this.fail('print_task_code 参数不能为空', { code: 400 }); } const normalizedResult = String(result || '').trim().toLowerCase(); if (![ 'success', 'failed' ].includes(normalizedResult)) { return this.fail('result 参数不合法,仅支持 success/failed', { code: 400 }); } const printTaskMap = await this.ctx.model.PrintTaskMap.findOne({ where: { task_code: normalizedPrintTaskCode, }, raw: true, }); if (!printTaskMap || !printTaskMap.print_record_id) { return this.fail('打印任务映射不存在', { code: 404, result: 'not_found', print_task_code: normalizedPrintTaskCode, }); } const printRecordId = Number(printTaskMap.print_record_id || 0); const printRecord = await this.ctx.model.PrintRecord.findOne({ where: { id: printRecordId }, raw: true, }); if (!printRecord) { return this.fail('打印记录不存在', { code: 404, result: 'not_found', print_task_code: normalizedPrintTaskCode, print_record_id: printRecordId, }); } const currentPrintStatus = String(printRecord.print_status || '').trim(); if (normalizedResult === 'success' && currentPrintStatus === 'printed') { return this.success('打印回执已处理', { code: 0, result: 'idempotent', print_task_code: normalizedPrintTaskCode, print_record_id: printRecordId, print_status: 'printed', }); } if (normalizedResult === 'failed' && currentPrintStatus === 'printed') { return this.success('已打印成功,忽略失败回执', { code: 0, result: 'ignored', print_task_code: normalizedPrintTaskCode, print_record_id: printRecordId, print_status: 'printed', }); } const normalizedPrintTime = this.parsePrintCallbackTime(callbackTime); const orderIds = this.extractOrderIdsFromPrintRecordData(printRecord.data); const warehouseId = Number(printRecord.warehouse_id || 0); const updatePayload = normalizedResult === 'success' ? { status: 'sent', print_status: 'printed', error_message: null, fail_code: null, print_time: normalizedPrintTime, } : { print_status: 'print_failed', error_message: errorMessage ? String(errorMessage) : null, fail_code: failCode ? String(failCode) : 'PRINT_CALLBACK_FAILED', print_time: normalizedPrintTime, }; await this.ctx.model.PrintRecord.update(updatePayload, { where: { id: printRecordId }, }); const orderPrintStatusUpdateResult = await this.updateOrderPrintStatusByCallback({ warehouseId, orderIds, result: normalizedResult, }); if (!orderPrintStatusUpdateResult.success) { this.ctx.logger.error('[print.callback] 同步订单主表 print_status 失败', { printTaskCode: normalizedPrintTaskCode, printRecordId, result: normalizedResult, orderIdsCount: orderIds.length, reason: orderPrintStatusUpdateResult.errorMessage, }); } this.ctx.logger.info('[print.callback] 回执处理完成', { printTaskCode: normalizedPrintTaskCode, printRecordId, result: normalizedResult, printer: printer ? String(printer) : '', }); return this.success('打印回执处理成功', { code: 0, result: 'updated', print_task_code: normalizedPrintTaskCode, print_record_id: printRecordId, print_status: updatePayload.print_status, }); } /** * 查询单条打印结果。 * @param {Object} data 入参。 * @param {number|string} data.printId 打印记录ID。 * @return {Promise} 查询结果。 */ 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 }); } /** * 查询单条打印记录详情。 * @param {Object} data 入参。 * @param {number|string} data.id 打印记录ID。 * @return {Promise} 查询结果。 */ 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;