From b629b59d4b2ce3e1d35f9eda85c2eddd4d33913e Mon Sep 17 00:00:00 2001 From: liufumingren Date: Wed, 20 May 2026 04:55:16 +0800 Subject: [PATCH] fix(print): callback sync order print_status by order_ids --- app/service/systemMethods/print.js | 1211 ++++++++++++++++- .../service/systemMethods/print.send.test.js | 808 ++++++++++- 2 files changed, 1963 insertions(+), 56 deletions(-) diff --git a/app/service/systemMethods/print.js b/app/service/systemMethods/print.js index d4cc9d8..0913e72 100644 --- a/app/service/systemMethods/print.js +++ b/app/service/systemMethods/print.js @@ -1,5 +1,6 @@ 'use strict'; +const { randomBytes } = require('node:crypto'); // 打印相关 Service const MainService = require('../main'); const { @@ -82,6 +83,554 @@ class PrintService extends MainService { 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: 'unknown', + sent_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); + } + + /** + * 从打印记录 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 !== 'unknown' + || !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。 @@ -147,14 +696,13 @@ class PrintService extends MainService { if (type !== 'express') { // 生成打印编号并记录到数据库 try { - printRecord = await ctx.model.PrintRecord.create({ + printRecord = await ctx.model.PrintRecord.create(this.buildPendingPrintRecordPayload({ warehouse_id: warehouseId, computer_id: computerId, printer, type, data: { template, data }, - status: 'pending', - }); + })); this.ctx.logger.info('[print.send] PrintRecord 创建成功', { warehouseId, type, @@ -391,61 +939,45 @@ class PrintService extends MainService { }); 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, + requestCode, printStation: expressPrintStation.data, payloadBuilder, idGenerator, - printRecordId: printRecord.id, + expressRecordFields: expressRecordFields.data, platformComponents: platformComponentsResult.data, + type, + template, + 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, + printId: expressSendResult.printId || 0, reason: expressSendResult.error, }); - return this.fail(expressSendResult.error, { code: 504, printId: printRecord.id }); + return this.fail(expressSendResult.error, { + code: 504, + printId: expressSendResult.printId || 0, + printIds: Array.isArray(expressSendResult.printIds) ? expressSendResult.printIds : [], + }); } - await printRecord.update({ status: 'sent' }); this.ctx.logger.info('[print.send] 最终返回 success', { warehouseId, type, - printId: printRecord.id, + 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 : [], }); - return this.success('发送打印任务成功', { code: 200, printId: printRecord.id }); } default: this.ctx.logger.error('[print.send] 最终返回 failure', { @@ -488,7 +1020,7 @@ class PrintService extends MainService { } // 发送成功后更新打印记录状态 if (res.status === 'success') { - await printRecord.update({ status: 'sent' }); + await printRecord.update(this.buildSentPrintRecordUpdatePayload()); this.ctx.logger.info('[print.send] 最终返回 success', { warehouseId, type, @@ -496,7 +1028,9 @@ class PrintService extends MainService { }); return this.success('发送打印任务成功', { code: 200, printId: printRecord.id }); } - await printRecord.update({ status: 'failed', error_message: res.error }); + await printRecord.update(this.buildSendFailedPrintRecordUpdatePayload({ + errorMessage: res.error || '打印服务返回失败', + })); this.ctx.logger.error('[print.send] 最终返回 failure', { warehouseId, type, @@ -506,6 +1040,175 @@ class PrintService extends MainService { 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 校验参数。 @@ -639,6 +1342,114 @@ class PrintService extends MainService { 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); + } + + /** + * 在打印发送成功后批量锁定订单。 + * + * 仅将 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', + }, { + where: { + id: orderIds, + print_lock_status: 'none', + }, + }); + + 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 查询参数。 @@ -789,18 +1600,25 @@ class PrintService extends MainService { * @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 {number|string} payload.printRecordId 打印记录 ID。 - * @param {Object} payload.platformComponents 平台到打印组件映射。 - * @return {Promise<{success:boolean,error?:string}>} 发送结果。 + * @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 expressOrderIds = this.collectOrderIdsFromWaveGroups(waveGroups); + const generatedTaskCodes = []; + const createdPrintRecordIds = []; for (const waveGroup of waveGroups) { const platforms = Array.isArray(waveGroup && waveGroup.platforms) ? waveGroup.platforms : []; for (const platformGroup of platforms) { @@ -813,8 +1631,20 @@ class PrintService extends MainService { platform: platformGroup && platformGroup.platform ? platformGroup.platform : '', sysLogisticsCode: platformGroup && platformGroup.sys_logistics_code ? platformGroup.sys_logistics_code : '', ordersCount: orders.length, - printRecordId: normalizedPayload.printRecordId, }; + 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(); @@ -837,6 +1667,8 @@ class PrintService extends MainService { return { success: false, error: `平台 ${platformCode} 未配置打印组件`, + printId: createdPrintRecordIds[0] || 0, + printIds: createdPrintRecordIds, }; } @@ -857,6 +1689,8 @@ class PrintService extends MainService { return { success: false, error: printerNameResult.error, + printId: createdPrintRecordIds[0] || 0, + printIds: createdPrintRecordIds, }; } @@ -874,6 +1708,8 @@ class PrintService extends MainService { 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, @@ -881,6 +1717,7 @@ class PrintService extends MainService { batchOrdersCount: batchOrders.length, }; let requestPayload; + let currentTaskCode = ''; try { requestPayload = normalizedPayload.payloadBuilder.buildPayload({ platform: platformGroup && platformGroup.platform, @@ -892,6 +1729,13 @@ class PrintService extends MainService { 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, @@ -914,15 +1758,63 @@ class PrintService extends MainService { 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: printerNameResult.data, + printer: currentPrinterName, component, type: 'express', + order_ids: batchOrderIds, data: requestPayload, - printId: normalizedPayload.printRecordId, + printId: currentPrintRecord.id, }; const sendStartAt = Date.now(); let sendResult; @@ -936,12 +1828,17 @@ class PrintService extends MainService { const sendDurationMs = Date.now() - sendStartAt; 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}`, @@ -949,18 +1846,25 @@ class PrintService extends MainService { return { success: false, error: error && error.message ? error.message : '打印服务调用失败', + printId: createdPrintRecordIds[0] || 0, + printIds: createdPrintRecordIds, }; } const sendDurationMs = Date.now() - sendStartAt; if (sendResult.status !== 'success') { 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 || '打印服务返回失败', @@ -976,10 +1880,42 @@ class PrintService extends MainService { 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 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, }; } this.ctx.logger.info('[print.send] 平台快递组发送结束', { ...batchSummary, + printId: currentPrintRecord.id, computerId: normalizedPayload.printStation.computer_id, status: 'success', }); @@ -987,9 +1923,185 @@ class PrintService extends MainService { } } - return { success: true }; + const lockResult = await this.lockOrderDeliveryAfterPrintSentSuccess({ + warehouseId: normalizedPayload.warehouseId, + orderIds: expressOrderIds, + }); + if (!lockResult.success) { + this.ctx.logger.error('[print.send] 打印成功后锁定订单失败', { + warehouseId: normalizedPayload.warehouseId, + orderIdsCount: expressOrderIds.length, + reason: lockResult.errorMessage, + }); + } + + 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; @@ -999,6 +2111,13 @@ class PrintService extends MainService { 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; diff --git a/test/app/service/systemMethods/print.send.test.js b/test/app/service/systemMethods/print.send.test.js index 2e6a424..15ae828 100644 --- a/test/app/service/systemMethods/print.send.test.js +++ b/test/app/service/systemMethods/print.send.test.js @@ -15,12 +15,50 @@ function createContext(options = {}) { const calls = { printRecordCreatePayloads: [], printRecordUpdatePayloads: [], + printRecordStaticUpdatePayloads: [], + printRecordFindOnePayloads: [], + printRecordFindAllPayloads: [], + printTaskMapCreatePayloads: [], + printTaskMapFindOnePayloads: [], + printTaskMapUpdatePayloads: [], sendToComputerPayloads: [], sendOrderMarks: [], redisGetKeys: [], platformFindAllWheres: [], + orderDeliveryLockUpdates: [], }; + const state = { + nextPrintRecordId: 9001, + printRecordsById: { + 9001: { + id: 9001, + print_task_code: String(requestOptions.initialPrintTaskCode || ''), + status: 'pending', + }, + }, + printTaskMapByTaskCode: {}, + }; + + if (Array.isArray(requestOptions.initialPrintRecords)) { + for (const record of requestOptions.initialPrintRecords) { + const recordId = Number(record && record.id ? record.id : 0); + if (!recordId) { + continue; + } + state.printRecordsById[recordId] = { + ...(state.printRecordsById[recordId] || {}), + ...record, + id: recordId, + }; + if (recordId >= state.nextPrintRecordId) { + state.nextPrintRecordId = recordId + 1; + } + } + } + + let duplicateTaskCodeTimes = Number(requestOptions.duplicateTaskCodeTimes || 0); + const platformComponents = requestOptions.platformComponents || { cainiao: '菜鸟', pdd: '拼多多', @@ -76,6 +114,16 @@ function createContext(options = {}) { baseDir: process.cwd(), config: { jwt: {}, + printTaskCodeRetry: { + maxRetries: 5, + baseDelayMs: 0, + jitterMs: 0, + }, + printTaskCodeWritebackRetry: { + maxRetries: 3, + baseDelayMs: 0, + jitterMs: 0, + }, }, Sequelize: {}, redis: { @@ -103,13 +151,122 @@ function createContext(options = {}) { PrintRecord: { async create(payload) { calls.printRecordCreatePayloads.push(payload); + const currentId = state.nextPrintRecordId; + state.nextPrintRecordId += 1; + state.printRecordsById[currentId] = { + id: currentId, + print_task_code: '', + ...payload, + }; return { - id: 9001, + id: currentId, async update(updatePayload) { - calls.printRecordUpdatePayloads.push(updatePayload); + calls.printRecordUpdatePayloads.push({ id: currentId, payload: updatePayload }); + state.printRecordsById[currentId] = { + ...(state.printRecordsById[currentId] || { id: currentId }), + ...updatePayload, + }; }, }; }, + async findOne(query) { + calls.printRecordFindOnePayloads.push(query || {}); + const where = query && query.where ? query.where : {}; + const printRecordId = Number(where.id || 0); + if (!printRecordId || !state.printRecordsById[printRecordId]) { + return null; + } + return { + ...state.printRecordsById[printRecordId], + }; + }, + async findAll(query) { + calls.printRecordFindAllPayloads.push(query || {}); + const where = query && query.where ? query.where : {}; + const idList = Array.isArray(where.id) + ? where.id.map(item => Number(item)).filter(item => Number.isInteger(item) && item > 0) + : []; + const warehouseId = where.warehouse_id; + const records = Object.values(state.printRecordsById).filter(item => { + const currentId = Number(item && item.id ? item.id : 0); + if (idList.length > 0 && !idList.includes(currentId)) { + return false; + } + if (warehouseId !== undefined && warehouseId !== null && item.warehouse_id !== warehouseId) { + return false; + } + return true; + }); + return records.map(item => ({ ...item })); + }, + async update(payload, query) { + calls.printRecordStaticUpdatePayloads.push({ payload, query }); + const where = query && query.where ? query.where : {}; + const printRecordId = Number(where.id || 0); + if (!printRecordId || !state.printRecordsById[printRecordId]) { + return [ 0 ]; + } + state.printRecordsById[printRecordId] = { + ...state.printRecordsById[printRecordId], + ...payload, + }; + return [ 1 ]; + }, + }, + PrintTaskMap: { + async create(payload) { + calls.printTaskMapCreatePayloads.push(payload); + if (duplicateTaskCodeTimes > 0) { + duplicateTaskCodeTimes -= 1; + const duplicateError = new Error('Duplicate entry'); + duplicateError.name = 'SequelizeUniqueConstraintError'; + duplicateError.parent = { code: 'ER_DUP_ENTRY', errno: 1062 }; + throw duplicateError; + } + const taskCode = String(payload && payload.task_code ? payload.task_code : '').trim(); + if (taskCode && state.printTaskMapByTaskCode[taskCode]) { + const duplicateError = new Error('Duplicate entry'); + duplicateError.name = 'SequelizeUniqueConstraintError'; + duplicateError.parent = { code: 'ER_DUP_ENTRY', errno: 1062 }; + throw duplicateError; + } + state.printTaskMapByTaskCode[taskCode] = { + task_code: taskCode, + print_record_id: null, + provider: null, + }; + return { + id: calls.printTaskMapCreatePayloads.length, + }; + }, + async findOne(query) { + calls.printTaskMapFindOnePayloads.push(query || {}); + const where = query && query.where ? query.where : {}; + const taskCode = String(where.task_code || '').trim(); + if (!taskCode || !state.printTaskMapByTaskCode[taskCode]) { + return null; + } + return { + ...state.printTaskMapByTaskCode[taskCode], + }; + }, + async update(payload, query) { + calls.printTaskMapUpdatePayloads.push({ payload, query }); + const taskCode = String(query && query.where && query.where.task_code ? query.where.task_code : '').trim(); + if (!taskCode) { + return [ 0 ]; + } + const current = state.printTaskMapByTaskCode[taskCode] || { + task_code: taskCode, + print_record_id: null, + provider: null, + }; + state.printTaskMapByTaskCode[taskCode] = { + ...current, + ...payload, + }; + return [ 1 ]; + }, }, PrintStations: { async findOne() { @@ -130,6 +287,19 @@ function createContext(options = {}) { })); }, }, + OrderDeliveryFactory: { + async getCurrentModel() { + return { + async update(payload, query) { + calls.orderDeliveryLockUpdates.push({ payload, query }); + const whereIds = Array.isArray(query && query.where && query.where.id) + ? query.where.id + : []; + return [ whereIds.length ]; + }, + }; + }, + }, }, service: { systems: { @@ -142,7 +312,7 @@ function createContext(options = {}) { }, }; - return { ctx, calls }; + return { ctx, calls, state }; } /** @@ -294,16 +464,34 @@ describe('test/app/service/systemMethods/print.send.test.js', () => { assert.equal(result.flag, 'success'); assert.equal(result.code, 200); - assert.equal(calls.printRecordCreatePayloads.length, 1); + assert.equal(result.printId, 9001); + assert.deepEqual(result.printIds, [ 9001, 9002, 9003 ]); + assert.equal(calls.printRecordCreatePayloads.length, 3); assert.equal(calls.printRecordCreatePayloads[0].computer_id, 'PC-STATION-001'); - assert.equal(calls.printRecordCreatePayloads[0].printer, 'PRN-DEFAULT'); + assert.equal(calls.printRecordCreatePayloads[0].printer, 'PRN-STO'); + assert.equal(calls.printRecordCreatePayloads[0].send_status, 'pending'); + assert.equal(calls.printRecordCreatePayloads[0].print_status, 'unknown'); assert.equal(calls.sendToComputerPayloads.length, 3); + assert.equal(calls.printRecordCreatePayloads.length, calls.sendToComputerPayloads.length); + for (let index = 0; index < calls.printRecordCreatePayloads.length; index++) { + const recordPayload = calls.printRecordCreatePayloads[index] || {}; + const sendPayload = calls.sendToComputerPayloads[index] || {}; + const sendData = sendPayload && sendPayload.data && typeof sendPayload.data === 'object' + ? sendPayload.data + : {}; + assert.equal(recordPayload.printer, sendData.printer); + const sendDataWithoutPrintId = { ...sendData }; + delete sendDataWithoutPrintId.printId; + assert.deepEqual(recordPayload.data, sendDataWithoutPrintId); + } assert.deepEqual(calls.sendOrderMarks, [ 'W1-P1', 'W1-P2', 'W2-P1' ]); - assert.equal(calls.printRecordUpdatePayloads.length, 1); - assert.equal(calls.printRecordUpdatePayloads[0].status, 'sent'); + assert.equal(calls.printRecordUpdatePayloads.length, 0); + assert.equal(calls.printRecordStaticUpdatePayloads[0].payload.send_status, 'sent'); + assert.equal(calls.printRecordStaticUpdatePayloads[0].payload.print_status, 'unknown'); + assert.ok(calls.printRecordStaticUpdatePayloads[0].payload.sent_time instanceof Date); }); - it('type=express 默认打印机为空时创建记录应写入稳定占位值', async () => { + it('type=express 默认打印机为空时创建记录应写入实际发送打印机', async () => { const { ctx, calls } = createContext({ printStation: { id: 101, @@ -337,9 +525,18 @@ describe('test/app/service/systemMethods/print.send.test.js', () => { }); assert.equal(result.flag, 'success'); - assert.equal(calls.printRecordCreatePayloads.length, 1); + assert.equal(calls.printRecordCreatePayloads.length, 3); assert.equal(calls.printRecordCreatePayloads[0].computer_id, 'PC-STATION-001'); - assert.equal(calls.printRecordCreatePayloads[0].printer, 'EXPRESS_DYNAMIC_PRINTER'); + const printers = calls.printRecordCreatePayloads.map(item => item.printer); + assert.deepEqual(printers, [ 'PRN-STO', 'PRN-YTO', 'PRN-STO' ]); + for (let index = 0; index < calls.printRecordCreatePayloads.length; index++) { + const recordPayload = calls.printRecordCreatePayloads[index] || {}; + const sendPayload = calls.sendToComputerPayloads[index] || {}; + const sendData = sendPayload && sendPayload.data && typeof sendPayload.data === 'object' + ? sendPayload.data + : {}; + assert.equal(recordPayload.printer, sendData.printer); + } }); it('type=express 应按快递匹配打印机并在未命中时回退默认打印机', async () => { @@ -357,6 +554,7 @@ describe('test/app/service/systemMethods/print.send.test.js', () => { assert.equal(result.flag, 'success'); assert.equal(calls.sendToComputerPayloads.length, 3); + assert.equal(calls.printRecordCreatePayloads.length, 3); const printerNames = calls.sendToComputerPayloads.map(item => item.data.printer); assert.deepEqual(printerNames, [ 'PRN-STO', 'PRN-DEFAULT', 'PRN-STO' ]); }); @@ -377,6 +575,7 @@ describe('test/app/service/systemMethods/print.send.test.js', () => { assert.equal(result.flag, 'success'); const components = calls.sendToComputerPayloads.map(item => item.data.component); assert.deepEqual(components, [ '菜鸟', '拼多多', '抖音' ]); + assert.equal(calls.printRecordCreatePayloads.length, calls.sendToComputerPayloads.length); }); it('type=express 任意组件离线时应整批失败且不发送任务', async () => { @@ -451,6 +650,7 @@ describe('test/app/service/systemMethods/print.send.test.js', () => { assert.equal(result.flag, 'success'); assert.equal(calls.sendToComputerPayloads.length, 1); + assert.equal(calls.printRecordCreatePayloads.length, 1); assert.deepEqual(calls.sendOrderMarks, [ 'ONLY-CAINIAO' ]); assert.equal(calls.platformFindAllWheres.length, 1); assert.deepEqual(calls.platformFindAllWheres[0].code, [ 'cainiao' ]); @@ -505,6 +705,7 @@ describe('test/app/service/systemMethods/print.send.test.js', () => { assert.equal(result.flag, 'success'); assert.equal(calls.sendToComputerPayloads.length, 3); + assert.equal(calls.printRecordCreatePayloads.length, 3); const requestPayloads = calls.sendToComputerPayloads.map(item => item.data.data); const firstDocumentNumbers = requestPayloads.map(item => item.task.firstDocumentNumber); @@ -550,6 +751,232 @@ describe('test/app/service/systemMethods/print.send.test.js', () => { assert.equal(documentIdSet.size, 4); }); + it('type=express 正常生成 task_id 并写入映射表', async () => { + const { ctx, calls } = createContext(); + const service = new PrintService(ctx); + + const result = await service.send({ + type: 'express', + printStationId: 101, + requestCode: 'REQ-TASK-CODE-001', + data: { + waveGroups: createExpressWaveGroups(), + }, + }); + + assert.equal(result.flag, 'success'); + assert.equal(calls.printRecordCreatePayloads.length, 3); + assert.equal(calls.sendToComputerPayloads.length, 3); + assert.equal(calls.printTaskMapCreatePayloads.length, 3); + assert.equal(calls.printTaskMapUpdatePayloads.length, 3); + for (const item of calls.printTaskMapCreatePayloads) { + assert.match(String(item.task_code || ''), /^PRT\d{14}[0-9a-f]{4}[0-9a-f]{8}$/i); + } + assert.equal(calls.printRecordStaticUpdatePayloads.length, 3); + for (const updateItem of calls.printRecordStaticUpdatePayloads) { + assert.equal(typeof updateItem.payload.print_task_code, 'string'); + assert.ok(updateItem.payload.print_task_code.length > 0); + assert.equal(updateItem.payload.print_task_code.includes(','), false); + assert.equal(updateItem.payload.status, 'sent'); + } + }); + + it('type=express 生成冲突时应重试并最终成功', async () => { + const { ctx, calls } = createContext({ + duplicateTaskCodeTimes: 1, + }); + const service = new PrintService(ctx); + + const result = await service.send({ + type: 'express', + printStationId: 101, + requestCode: 'REQ-TASK-CODE-RETRY-001', + data: { + waveGroups: [ createExpressWaveGroups()[0] ], + }, + }); + + assert.equal(result.flag, 'success'); + assert.ok(calls.printTaskMapCreatePayloads.length >= 3); + assert.equal(calls.printTaskMapUpdatePayloads.length, 2); + }); + + it('type=express 发送成功后应锁定订单 print_lock_status=warehouse', async () => { + const { ctx, calls } = createContext(); + const service = new PrintService(ctx); + + const result = await service.send({ + type: 'express', + requestCode: 'REQ-LOCK-ORDER', + printStationId: 101, + data: { + waveGroups: [ + { + wave_id: 1, + wave_no: 'WAVE-1', + platforms: [ + { + platform: 'cainiao', + sys_logistics_code: 'STO', + order_ids: [ 101, 102, 101 ], + orders: [ + { + order_id: 101, + print_data: { + documentID: 'DOC-LOCK-1', + contents: [ + { + marker: 'LOCK-1', + }, + ], + }, + }, + ], + }, + ], + }, + ], + }, + }); + + assert.equal(result.flag, 'success'); + assert.equal(calls.orderDeliveryLockUpdates.length, 1); + assert.equal(calls.orderDeliveryLockUpdates[0].payload.print_lock_status, 'warehouse'); + assert.deepEqual(calls.orderDeliveryLockUpdates[0].query.where.id, [ 101, 102 ]); + assert.equal(calls.orderDeliveryLockUpdates[0].query.where.print_lock_status, 'none'); + }); + + it('type=express provider 成功后应回写 print_record 与 print_task_map,且回写可重入', async () => { + const { ctx, calls, state } = createContext(); + const service = new PrintService(ctx); + + const taskCode = 'PRT2026051923595900aa11bb22cc'; + state.printTaskMapByTaskCode[taskCode] = { + task_code: taskCode, + print_record_id: null, + provider: null, + }; + + await service.bindTaskCodeToPrintRecord({ + printRecordId: 9001, + taskCode, + provider: 'provider-task-1', + }); + await service.bindTaskCodeToPrintRecord({ + printRecordId: 9001, + taskCode, + provider: 'provider-task-1', + }); + + assert.equal(state.printTaskMapByTaskCode[taskCode].print_record_id, 9001); + assert.equal(state.printTaskMapByTaskCode[taskCode].provider, 'provider-task-1'); + assert.equal(state.printRecordsById[9001].print_task_code, taskCode); + assert.equal(state.printRecordsById[9001].status, 'sent'); + assert.equal(state.printRecordsById[9001].send_status, 'sent'); + assert.equal(state.printRecordsById[9001].print_status, 'unknown'); + assert.equal(calls.printRecordStaticUpdatePayloads.length, 1); + assert.equal(calls.printRecordStaticUpdatePayloads[0].payload.print_task_code, taskCode); + }); + + it('type=express 发送失败后应写入 send_failed 与 unknown', async () => { + const { ctx, calls } = createContext({ + sendToComputer: async payload => { + calls.sendToComputerPayloads.push(payload); + return { + status: 'failure', + error: '打印服务不可用', + }; + }, + }); + const service = new PrintService(ctx); + + const result = await service.send({ + type: 'express', + printStationId: 101, + requestCode: 'REQ-EXPRESS-SEND-FAILED-001', + data: { + waveGroups: [ createExpressWaveGroups()[0] ], + }, + }); + + assert.equal(result.flag, 'failure'); + assert.equal(result.code, 504); + assert.equal(calls.printRecordCreatePayloads.length, 1); + assert.equal(calls.printRecordUpdatePayloads.length, 1); + assert.equal(calls.printRecordUpdatePayloads[0].payload.status, 'failed'); + assert.equal(calls.printRecordUpdatePayloads[0].payload.send_status, 'send_failed'); + assert.equal(calls.printRecordUpdatePayloads[0].payload.print_status, 'unknown'); + assert.equal(calls.printRecordUpdatePayloads[0].payload.fail_code, 'SEND_FAILED'); + }); + + it('type=customize 发送成功后应写入 sent 与 unknown', async () => { + const { ctx, calls } = createContext(); + const service = new PrintService(ctx); + + const result = await service.send({ + computerId: 'PC-03', + printer: 'Printer-A', + type: 'customize', + template: { + page_width: 100, + page_height: 60, + template_content: [], + }, + data: { + order_no: 'SO10001', + }, + timestamp: '1710000000', + count: 1, + }); + + assert.equal(result.flag, 'success'); + assert.equal(calls.printRecordCreatePayloads.length, 1); + assert.equal(calls.printRecordCreatePayloads[0].send_status, 'pending'); + assert.equal(calls.printRecordCreatePayloads[0].print_status, 'unknown'); + assert.equal(calls.printRecordUpdatePayloads.length, 1); + assert.equal(calls.printRecordUpdatePayloads[0].payload.status, 'sent'); + assert.equal(calls.printRecordUpdatePayloads[0].payload.send_status, 'sent'); + assert.equal(calls.printRecordUpdatePayloads[0].payload.print_status, 'unknown'); + assert.ok(calls.printRecordUpdatePayloads[0].payload.sent_time instanceof Date); + }); + + it('type=customize 发送失败后应写入 send_failed 与 unknown', async () => { + const { ctx, calls } = createContext({ + sendToComputer: async payload => { + calls.sendToComputerPayloads.push(payload); + return { + status: 'failure', + error: '打印组件未连接', + }; + }, + }); + const service = new PrintService(ctx); + + const result = await service.send({ + computerId: 'PC-04', + printer: 'Printer-B', + type: 'customize', + template: { + page_width: 80, + page_height: 50, + template_content: [], + }, + data: { + order_no: 'SO10004', + }, + timestamp: '1710000003', + count: 1, + }); + + assert.equal(result.flag, 'failure'); + assert.equal(calls.printRecordCreatePayloads.length, 1); + assert.equal(calls.printRecordUpdatePayloads.length, 1); + assert.equal(calls.printRecordUpdatePayloads[0].payload.status, 'failed'); + assert.equal(calls.printRecordUpdatePayloads[0].payload.send_status, 'send_failed'); + assert.equal(calls.printRecordUpdatePayloads[0].payload.print_status, 'unknown'); + assert.equal(calls.printRecordUpdatePayloads[0].payload.fail_code, 'SEND_FAILED'); + }); + it('type=customize 不传 printer 时应返回失败且提示 printer', async () => { const { ctx, calls } = createContext(); const service = new PrintService(ctx); @@ -595,4 +1022,365 @@ describe('test/app/service/systemMethods/print.send.test.js', () => { assert.match(result.message, /template/); assert.equal(calls.sendToComputerPayloads.length, 0); }); + + it('retryFailed 应补打 failed 记录并创建新记录', async () => { + const sourceRecordId = 12001; + const { ctx, calls, state } = createContext({ + initialPrintRecords: [ + { + id: sourceRecordId, + warehouse_id: 100000, + computer_id: 'PC-STATION-001', + printer: 'PRN-STO', + type: 'express', + status: 'failed', + send_status: 'send_failed', + print_status: 'unknown', + data: { + printer: 'PRN-STO', + component: '菜鸟', + type: 'express', + data: { + task: { + taskID: 'OLD_TASK_ID', + documents: [], + }, + }, + }, + request_code: 'REQ-RETRY-001', + wave_id: 11, + wave_no: 'WAVE-11', + platform_code: 'cainiao', + platform_name: '菜鸟平台', + sys_logistics_code: 'STO', + sys_logistics_name: '申通', + }, + ], + sendToComputer: async payload => { + calls.sendToComputerPayloads.push(payload); + return { status: 'success' }; + }, + }); + const service = new PrintService(ctx); + + const result = await service.retryFailed({ + print_ids: [ sourceRecordId ], + }); + + assert.equal(result.flag, 'success'); + assert.equal(result.success_count, 1); + assert.equal(result.failed_count, 0); + assert.equal(result.skipped_count, 0); + assert.equal(result.retried.length, 1); + assert.equal(result.retried[0].source_print_id, sourceRecordId); + assert.equal(result.retried[0].status, 'sent'); + assert.equal(calls.printRecordCreatePayloads.length, 1); + assert.equal(calls.sendToComputerPayloads.length, 1); + assert.equal(calls.printRecordCreatePayloads[0].retry_of_print_id, sourceRecordId); + + const newRecordId = result.retried[0].new_print_id; + const newRecord = state.printRecordsById[newRecordId]; + assert.ok(newRecord); + assert.equal(newRecord.retry_of_print_id, sourceRecordId); + assert.equal(newRecord.status, 'sent'); + assert.equal(newRecord.send_status, 'sent'); + assert.equal(newRecord.print_status, 'unknown'); + assert.notEqual(newRecord.data.data.task.taskID, 'OLD_TASK_ID'); + assert.equal(newRecord.data.data.task.taskID, result.retried[0].task_code); + assert.equal(state.printRecordsById[sourceRecordId].status, 'failed'); + }); + + it('retryFailed 应跳过 sent/printed 记录', async () => { + const sourceRecordId = 12002; + const { ctx, calls } = createContext({ + initialPrintRecords: [ + { + id: sourceRecordId, + warehouse_id: 100000, + computer_id: 'PC-STATION-001', + printer: 'PRN-STO', + type: 'express', + status: 'sent', + send_status: 'sent', + print_status: 'printed', + data: { + printer: 'PRN-STO', + component: '菜鸟', + type: 'express', + data: { + task: { + taskID: 'TASK-SENT-001', + documents: [], + }, + }, + }, + }, + ], + }); + const service = new PrintService(ctx); + + const result = await service.retryFailed({ + print_ids: [ sourceRecordId ], + }); + + assert.equal(result.flag, 'success'); + assert.equal(result.success_count, 0); + assert.equal(result.failed_count, 0); + assert.equal(result.skipped_count, 1); + assert.equal(result.skipped[0].print_id, sourceRecordId); + assert.match(result.skipped[0].reason, /跳过|不允许补打/); + assert.equal(calls.printRecordCreatePayloads.length, 0); + assert.equal(calls.sendToComputerPayloads.length, 0); + }); + + it('retryFailed 部分成功时应返回正确统计', async () => { + const sourceSuccessId = 12003; + const sourceFailId = 12004; + const sourceSkipId = 12005; + const { ctx, calls, state } = createContext({ + initialPrintRecords: [ + { + id: sourceSuccessId, + warehouse_id: 100000, + computer_id: 'PC-STATION-001', + printer: 'PRN-STO', + type: 'express', + status: 'failed', + send_status: 'send_failed', + print_status: 'unknown', + data: { + printer: 'PRN-STO', + component: '菜鸟', + type: 'express', + data: { task: { taskID: 'TASK-OLD-SUCCESS', documents: [] } }, + }, + }, + { + id: sourceFailId, + warehouse_id: 100000, + computer_id: 'PC-STATION-001', + printer: 'PRN-YTO', + type: 'express', + status: 'failed', + send_status: 'send_failed', + print_status: 'unknown', + data: { + printer: 'PRN-YTO', + component: '拼多多', + type: 'express', + data: { task: { taskID: 'TASK-OLD-FAIL', documents: [] } }, + }, + }, + { + id: sourceSkipId, + warehouse_id: 100000, + computer_id: 'PC-STATION-001', + printer: 'PRN-STO', + type: 'express', + status: 'sent', + send_status: 'sent', + print_status: 'unknown', + data: { + printer: 'PRN-STO', + component: '菜鸟', + type: 'express', + data: { task: { taskID: 'TASK-SKIP', documents: [] } }, + }, + }, + ], + sendToComputer: async payload => { + calls.sendToComputerPayloads.push(payload); + if (calls.sendToComputerPayloads.length === 2) { + return { + status: 'failure', + error: '发送失败-模拟', + }; + } + return { status: 'success' }; + }, + }); + const service = new PrintService(ctx); + + const result = await service.retryFailed({ + print_ids: [ sourceSuccessId, sourceFailId, sourceSkipId ], + }); + + assert.equal(result.flag, 'success'); + assert.equal(result.success_count, 1); + assert.equal(result.failed_count, 1); + assert.equal(result.skipped_count, 1); + assert.equal(result.retried.length, 2); + assert.equal(calls.printRecordCreatePayloads.length, 2); + assert.equal(calls.sendToComputerPayloads.length, 2); + assert.equal(state.printRecordsById[sourceSuccessId].status, 'failed'); + assert.equal(state.printRecordsById[sourceFailId].status, 'failed'); + assert.equal(state.printRecordsById[sourceSkipId].status, 'sent'); + const failedRetryItem = result.retried.find(item => item.source_print_id === sourceFailId); + assert.ok(failedRetryItem); + assert.equal(failedRetryItem.status, 'failed'); + }); + + it('handlePrintCallback success 回调应更新为 printed', async () => { + const { ctx, state, calls } = createContext(); + const service = new PrintService(ctx); + + state.printTaskMapByTaskCode.PRT_CALLBACK_001 = { + task_code: 'PRT_CALLBACK_001', + print_record_id: 9001, + provider: null, + }; + state.printRecordsById[9001] = { + id: 9001, + warehouse_id: 100000, + status: 'sent', + send_status: 'sent', + print_status: 'unknown', + print_time: null, + error_message: 'old-error', + fail_code: 'OLD_FAIL', + data: { + order_ids: [ 201, 202, 201 ], + }, + }; + + const result = await service.handlePrintCallback({ + print_task_code: 'PRT_CALLBACK_001', + result: 'success', + callback_time: '2026-05-19 12:00:00', + }); + + assert.equal(result.flag, 'success'); + assert.equal(result.result, 'updated'); + assert.equal(state.printRecordsById[9001].status, 'sent'); + assert.equal(state.printRecordsById[9001].print_status, 'printed'); + assert.equal(state.printRecordsById[9001].error_message, null); + assert.equal(state.printRecordsById[9001].fail_code, null); + assert.ok(state.printRecordsById[9001].print_time instanceof Date); + assert.equal(calls.orderDeliveryLockUpdates.length, 1); + assert.equal(calls.orderDeliveryLockUpdates[0].payload.print_status, 'fin'); + assert.deepEqual(calls.orderDeliveryLockUpdates[0].query.where.id, [ 201, 202 ]); + assert.equal(calls.orderDeliveryLockUpdates[0].query.where.print_status, undefined); + }); + + it('handlePrintCallback failed 回调应更新为 print_failed 并写入 fail_code', async () => { + const { ctx, state, calls } = createContext(); + const service = new PrintService(ctx); + + state.printTaskMapByTaskCode.PRT_CALLBACK_002 = { + task_code: 'PRT_CALLBACK_002', + print_record_id: 9001, + provider: null, + }; + state.printRecordsById[9001] = { + id: 9001, + warehouse_id: 100000, + status: 'sent', + send_status: 'sent', + print_status: 'unknown', + data: JSON.stringify({ + order_ids: [ 301, 302, 301 ], + }), + }; + + const result = await service.handlePrintCallback({ + print_task_code: 'PRT_CALLBACK_002', + result: 'failed', + error_message: '打印机离线', + }); + + assert.equal(result.flag, 'success'); + assert.equal(result.result, 'updated'); + assert.equal(state.printRecordsById[9001].print_status, 'print_failed'); + assert.equal(state.printRecordsById[9001].error_message, '打印机离线'); + assert.equal(state.printRecordsById[9001].fail_code, 'PRINT_CALLBACK_FAILED'); + assert.ok(state.printRecordsById[9001].print_time instanceof Date); + assert.equal(calls.orderDeliveryLockUpdates.length, 1); + assert.equal(calls.orderDeliveryLockUpdates[0].payload.print_status, 'error'); + assert.deepEqual(calls.orderDeliveryLockUpdates[0].query.where.id, [ 301, 302 ]); + assert.equal(calls.orderDeliveryLockUpdates[0].query.where.print_status, 'none'); + }); + + it('handlePrintCallback 重复 success 回调应幂等', async () => { + const { ctx, state } = createContext(); + const service = new PrintService(ctx); + + state.printTaskMapByTaskCode.PRT_CALLBACK_003 = { + task_code: 'PRT_CALLBACK_003', + print_record_id: 9001, + provider: null, + }; + state.printRecordsById[9001] = { + id: 9001, + status: 'sent', + send_status: 'sent', + print_status: 'unknown', + }; + + const firstResult = await service.handlePrintCallback({ + print_task_code: 'PRT_CALLBACK_003', + result: 'success', + }); + const firstPrintTime = state.printRecordsById[9001].print_time; + + const secondResult = await service.handlePrintCallback({ + print_task_code: 'PRT_CALLBACK_003', + result: 'success', + callback_time: '2026-06-01 00:00:00', + }); + + assert.equal(firstResult.flag, 'success'); + assert.equal(secondResult.flag, 'success'); + assert.equal(secondResult.result, 'idempotent'); + assert.equal(state.printRecordsById[9001].print_status, 'printed'); + assert.equal(state.printRecordsById[9001].print_time, firstPrintTime); + }); + + it('handlePrintCallback 已 printed 后收到 failed 应忽略', async () => { + const { ctx, state } = createContext(); + const service = new PrintService(ctx); + + state.printTaskMapByTaskCode.PRT_CALLBACK_004 = { + task_code: 'PRT_CALLBACK_004', + print_record_id: 9001, + provider: null, + }; + const existedPrintTime = new Date('2026-05-19T12:30:00.000Z'); + state.printRecordsById[9001] = { + id: 9001, + status: 'sent', + send_status: 'sent', + print_status: 'printed', + print_time: existedPrintTime, + error_message: null, + fail_code: null, + }; + + const result = await service.handlePrintCallback({ + print_task_code: 'PRT_CALLBACK_004', + result: 'failed', + error_message: '晚到失败回执', + fail_code: 'LATE_FAILED', + }); + + assert.equal(result.flag, 'success'); + assert.equal(result.result, 'ignored'); + assert.equal(state.printRecordsById[9001].print_status, 'printed'); + assert.equal(state.printRecordsById[9001].print_time, existedPrintTime); + assert.equal(state.printRecordsById[9001].error_message, null); + assert.equal(state.printRecordsById[9001].fail_code, null); + }); + + it('handlePrintCallback task_code 不存在时应返回失败结果', async () => { + const { ctx } = createContext(); + const service = new PrintService(ctx); + + const result = await service.handlePrintCallback({ + print_task_code: 'PRT_NOT_FOUND_001', + result: 'success', + }); + + assert.equal(result.flag, 'failure'); + assert.equal(result.code, 404); + assert.equal(result.result, 'not_found'); + }); });