'use strict'; const assert = require('node:assert/strict'); const PrintService = require('../../../../app/service/systemMethods/print'); /** * 构建 print.send 测试上下文。 * @param {Object} [options] 可选项。 * @param {Object} [options.printStation] 打印台数据。 * @param {Function} [options.sendToComputer] 发送函数桩。 * @return {{ctx: Object, calls: Object}} 包含模拟上下文与调用记录。 */ function createContext(options = {}) { const requestOptions = options && typeof options === 'object' ? options : {}; const calls = { printRecordCreatePayloads: [], printRecordUpdatePayloads: [], printRecordStaticUpdatePayloads: [], printRecordFindOnePayloads: [], printRecordFindAllPayloads: [], printTaskMapCreatePayloads: [], printTaskMapFindOnePayloads: [], printTaskMapUpdatePayloads: [], sendToComputerPayloads: [], sendOrderMarks: [], redisGetKeys: [], platformFindAllWheres: [], orderDeliveryLockUpdates: [], operationLogCreatePayloads: [], }; 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: '拼多多', douyin: '抖音', }; const printStation = requestOptions.printStation || { id: 101, warehouse_id: 100000, deleted: 0, computer_id: 'PC-STATION-001', default_printer_name: 'PRN-DEFAULT', subject_config: { express_bind_printer: [ { express_code: 'STO', printer_name: 'PRN-STO', }, ], }, }; const sendToComputer = requestOptions.sendToComputer || (async payload => { calls.sendToComputerPayloads.push(payload); const marker = payload && payload.data && payload.data.data && payload.data.data.task && Array.isArray(payload.data.data.task.documents) && payload.data.data.task.documents[0] && Array.isArray(payload.data.data.task.documents[0].contents) && payload.data.data.task.documents[0].contents[0] ? payload.data.data.task.documents[0].contents[0].marker : ''; calls.sendOrderMarks.push(marker); return { status: 'success', }; }); const defaultComponentStatusMap = { 'printer:PC-STATION-001:name:菜鸟:status': 'connected', 'printer:PC-STATION-001:name:拼多多:status': 'connected', 'printer:PC-STATION-001:name:抖音:status': 'connected', }; const componentStatusMap = { ...defaultComponentStatusMap, ...(requestOptions.componentStatuses || {}), }; const ctx = { app: { baseDir: process.cwd(), config: { jwt: {}, printTaskCodeRetry: { maxRetries: 5, baseDelayMs: 0, jitterMs: 0, }, printTaskCodeWritebackRetry: { maxRetries: 3, baseDelayMs: 0, jitterMs: 0, }, }, Sequelize: {}, redis: { get() { return { async get(key) { calls.redisGetKeys.push(key); return Object.prototype.hasOwnProperty.call(componentStatusMap, key) ? componentStatusMap[key] : null; }, }; }, }, }, logger: { info() {}, warn() {}, error() {}, }, user: { store_id: 100000, }, model: { 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: currentId, async update(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() { return printStation; }, }, PrintPlatform: { async findAll(query) { calls.platformFindAllWheres.push(query && query.where ? query.where : {}); const codeList = query && query.where && Array.isArray(query.where.platform_code) ? query.where.platform_code : []; return codeList.map(platformCode => ({ platform_code: platformCode, platform_name: Object.prototype.hasOwnProperty.call(platformComponents, platformCode) ? platformComponents[platformCode] : '', })); }, }, 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: { print: { index: { sendToComputer, }, }, operationLog: { async createOperationLogs(payloads) { calls.operationLogCreatePayloads.push(payloads); return payloads.map(() => true); }, }, }, }, }; return { ctx, calls, state }; } /** * 构建 express 场景的 waveGroups。 * @return {Array} waveGroups。 */ function createExpressWaveGroups() { return [ { wave_id: 1, wave_no: 'WAVE-1', platforms: [ { platform: 'cainiao', sys_logistics_code: 'STO', orders: [ { print_data: { documentID: 'DOC-OLD-1', contents: [ { marker: 'W1-P1', }, ], }, }, { print_data: { documentID: 'DOC-OLD-2', contents: [ { marker: 'W1-P1-2', }, ], }, }, ], }, { platform: 'pdd', sys_logistics_code: 'YTO', orders: [ { print_data: { documentID: 'DOC-OLD-3', contents: [ { marker: 'W1-P2', }, ], }, }, ], }, ], }, { wave_id: 2, wave_no: 'WAVE-2', platforms: [ { platform: 'douyin', sys_logistics_code: 'STO', orders: [ { print_data: { documentID: 'DOC-OLD-4', contents: [ { marker: 'W2-P1', }, ], }, }, ], }, ], }, ]; } /** * 构建快手平台的 express 场景波次数据。 * @param {number} orderCount 订单数量。 * @return {Array} waveGroups。 */ function createKuaishouWaveGroups(orderCount) { const normalizedOrderCount = Number(orderCount) || 0; const orders = []; for (let index = 0; index < normalizedOrderCount; index++) { const current = index + 1; orders.push({ print_data: { documentID: `DOC-KS-${current}`, contents: [ { marker: `KS-${current}`, }, ], }, }); } return [ { wave_id: 1, wave_no: 'WAVE-KS-1', platforms: [ { platform: 'kuaishou', sys_logistics_code: 'STO', orders, }, ], }, ]; } describe('test/app/service/systemMethods/print.send.test.js', () => { it('type=express 缺失 printStationId 时应返回失败', async () => { const { ctx, calls } = createContext(); const service = new PrintService(ctx); const result = await service.send({ type: 'express', requestCode: 'REQ-MISSING-STATION', data: { waveGroups: createExpressWaveGroups(), }, }); assert.equal(result.flag, 'failure'); assert.equal(result.code, 400); assert.match(result.message, /printStationId/); assert.equal(calls.sendToComputerPayloads.length, 0); }); it('type=express 使用 waveGroups 串行发送并保持 success 返回风格', async () => { const { ctx, calls } = createContext(); const service = new PrintService(ctx); const result = await service.send({ type: 'express', printStationId: 101, requestCode: 'REQ-SEQ-001', data: { waveGroups: createExpressWaveGroups(), }, }); assert.equal(result.flag, 'success'); assert.equal(result.code, 200); 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-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, 0); assert.equal(calls.printRecordStaticUpdatePayloads[0].payload.send_status, 'sent'); assert.equal(calls.printRecordStaticUpdatePayloads[0].payload.print_status, 'printed'); assert.ok(calls.printRecordStaticUpdatePayloads[0].payload.sent_time instanceof Date); }); it('type=express 默认打印机为空时创建记录应写入实际发送打印机', async () => { const { ctx, calls } = createContext({ printStation: { id: 101, warehouse_id: 100000, deleted: 0, computer_id: 'PC-STATION-001', default_printer_name: '', subject_config: { express_bind_printer: [ { express_code: 'STO', printer_name: 'PRN-STO', }, { express_code: 'YTO', printer_name: 'PRN-YTO', }, ], }, }, }); const service = new PrintService(ctx); const result = await service.send({ type: 'express', printStationId: 101, requestCode: 'REQ-RECORD-PLACEHOLDER-001', data: { waveGroups: createExpressWaveGroups(), }, }); assert.equal(result.flag, 'success'); assert.equal(calls.printRecordCreatePayloads.length, 3); assert.equal(calls.printRecordCreatePayloads[0].computer_id, 'PC-STATION-001'); 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 () => { const { ctx, calls } = createContext(); const service = new PrintService(ctx); const result = await service.send({ type: 'express', printStationId: 101, requestCode: 'REQ-PRINTER-001', data: { waveGroups: createExpressWaveGroups(), }, }); 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' ]); }); it('type=express 发送成功时 payload 应带 component 字段', async () => { const { ctx, calls } = createContext(); const service = new PrintService(ctx); const result = await service.send({ type: 'express', printStationId: 101, requestCode: 'REQ-COMPONENT-OK-001', data: { waveGroups: createExpressWaveGroups(), }, }); 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 () => { const { ctx, calls } = createContext({ componentStatuses: { 'printer:PC-STATION-001:name:拼多多:status': 'disconnected', }, }); const service = new PrintService(ctx); const result = await service.send({ type: 'express', printStationId: 101, requestCode: 'REQ-COMPONENT-OFFLINE-001', data: { waveGroups: createExpressWaveGroups(), }, }); assert.equal(result.flag, 'failure'); assert.equal(result.code, 400); assert.match(result.message, /未在线/); assert.equal(calls.printRecordCreatePayloads.length, 0); assert.equal(calls.sendToComputerPayloads.length, 0); }); it('type=express 某平台 orders 为空且组件离线时不应影响整批发送', async () => { const { ctx, calls } = createContext({ componentStatuses: { 'printer:PC-STATION-001:name:拼多多:status': 'disconnected', }, }); const service = new PrintService(ctx); const waveGroups = [ { wave_id: 1, wave_no: 'WAVE-EMPTY-PLATFORM-1', platforms: [ { platform: 'cainiao', sys_logistics_code: 'STO', orders: [ { print_data: { documentID: 'DOC-ONLY-1', contents: [ { marker: 'ONLY-CAINIAO', }, ], }, }, ], }, { platform: 'pdd', sys_logistics_code: 'YTO', orders: [], }, ], }, ]; const result = await service.send({ type: 'express', printStationId: 101, requestCode: 'REQ-EMPTY-PLATFORM-OFFLINE-001', data: { waveGroups, }, }); 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].platform_code, [ 'cainiao' ]); assert.deepEqual(calls.redisGetKeys, [ 'printer:PC-STATION-001:name:菜鸟:status' ]); }); it('type=express 平台 component 为空时应失败且不发送任务', async () => { const { ctx, calls } = createContext({ platformComponents: { cainiao: '菜鸟', pdd: '', douyin: '抖音', }, }); const service = new PrintService(ctx); const result = await service.send({ type: 'express', printStationId: 101, requestCode: 'REQ-COMPONENT-EMPTY-001', data: { waveGroups: createExpressWaveGroups(), }, }); assert.equal(result.flag, 'failure'); assert.equal(result.code, 400); assert.match(result.message, /未配置打印组件/); assert.equal(calls.printRecordCreatePayloads.length, 0); assert.equal(calls.sendToComputerPayloads.length, 0); }); it('type=express 快手平台应按10单分批发送并注入文档位置信息', async () => { const { ctx, calls } = createContext({ platformComponents: { kuaishou: '快手', }, componentStatuses: { 'printer:PC-STATION-001:name:快手:status': 'connected', }, }); const service = new PrintService(ctx); const result = await service.send({ type: 'express', printStationId: 101, requestCode: 'REQ-KS-BATCH-001', data: { waveGroups: createKuaishouWaveGroups(21), }, }); 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); const totalDocumentCounts = requestPayloads.map(item => item.task.totalDocumentCount); const documentCounts = requestPayloads.map(item => item.task.documents.length); assert.deepEqual(firstDocumentNumbers, [ 1, 11, 21 ]); assert.deepEqual(totalDocumentCounts, [ 21, 21, 21 ]); assert.deepEqual(documentCounts, [ 10, 10, 1 ]); }); it('type=express 同一次请求内 requestId/taskID/documentID 应唯一', async () => { const { ctx, calls } = createContext(); const service = new PrintService(ctx); const result = await service.send({ type: 'express', printStationId: 101, requestCode: 'REQ-UNIQ-001', data: { waveGroups: createExpressWaveGroups(), }, }); assert.equal(result.flag, 'success'); const requestIdSet = new Set(); const taskIdSet = new Set(); const documentIdSet = new Set(); for (const callPayload of calls.sendToComputerPayloads) { const requestPayload = callPayload.data.data; const requestId = requestPayload.requestID || requestPayload.requetID; requestIdSet.add(requestId); taskIdSet.add(requestPayload.task.taskID); const documents = Array.isArray(requestPayload.task.documents) ? requestPayload.task.documents : []; for (const document of documents) { documentIdSet.add(document.documentID); } } assert.equal(requestIdSet.size, calls.sendToComputerPayloads.length); assert.equal(taskIdSet.size, calls.sendToComputerPayloads.length); 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, 2); const lockUpdate = calls.orderDeliveryLockUpdates.find(item => item && item.payload && item.payload.print_lock_status === 'warehouse'); assert.ok(lockUpdate); assert.deepEqual(lockUpdate.query.where.id, [ 101, 102 ]); assert.equal(lockUpdate.query.where.print_lock_status, 'none'); const printStatusUpdate = calls.orderDeliveryLockUpdates.find(item => item && item.payload && item.payload.print_status === 'fin'); assert.ok(printStatusUpdate); assert.deepEqual(printStatusUpdate.query.where.id, [ 101, 102 ]); assert.equal(calls.operationLogCreatePayloads.length, 1); assert.equal(calls.operationLogCreatePayloads[0].length, 2); assert.equal(calls.operationLogCreatePayloads[0][0].businessType, 'order'); assert.equal(calls.operationLogCreatePayloads[0][0].operationCode, 'ORDER_PRINT'); assert.match(calls.operationLogCreatePayloads[0][0].extras.message, /批次发送结束成功/); }); it('type=express 批次失败且有订单ID时应写失败订单操作日志', 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', requestCode: 'REQ-LOG-FAIL-ORDER', printStationId: 101, data: { waveGroups: [ { wave_id: 1, wave_no: 'WAVE-LOG-FAIL-1', platforms: [ { platform: 'cainiao', sys_logistics_code: 'STO', order_ids: [ 501, 502 ], orders: [ { order_id: 501, print_data: { documentID: 'DOC-LOG-FAIL-1', contents: [ { marker: 'LOG-FAIL-1', }, ], }, }, ], }, ], }, ], }, }); assert.equal(result.flag, 'failure'); assert.equal(result.code, 504); assert.equal(calls.operationLogCreatePayloads.length, 1); assert.equal(calls.operationLogCreatePayloads[0].length, 2); assert.equal(calls.operationLogCreatePayloads[0][0].businessId, 501); assert.equal(calls.operationLogCreatePayloads[0][1].businessId, 502); assert.match(calls.operationLogCreatePayloads[0][0].extras.message, /批次发送失败/); assert.match(calls.operationLogCreatePayloads[0][0].extras.message, /模拟发送失败/); }); it('type=express 前批次成功后批次失败时应保持成功批次 print_status 回写', async () => { let sendCount = 0; const { ctx, calls } = createContext({ sendToComputer: async payload => { calls.sendToComputerPayloads.push(payload); sendCount += 1; if (sendCount === 2) { return { status: 'failure', error: '第二批次发送失败', }; } return { status: 'success', }; }, }); const service = new PrintService(ctx); const result = await service.send({ type: 'express', requestCode: 'REQ-PARTIAL-SUCCESS-THEN-FAIL', printStationId: 101, data: { waveGroups: [ { wave_id: 1, wave_no: 'WAVE-PARTIAL-1', platforms: [ { platform: 'cainiao', sys_logistics_code: 'STO', order_ids: [ 201, 202 ], orders: [ { order_id: 201, print_data: { documentID: 'DOC-PARTIAL-1', contents: [ { marker: 'PARTIAL-1', }, ], }, }, ], }, { platform: 'pdd', sys_logistics_code: 'YTO', order_ids: [ 301 ], orders: [ { order_id: 301, print_data: { documentID: 'DOC-PARTIAL-2', contents: [ { marker: 'PARTIAL-2', }, ], }, }, ], }, ], }, ], }, }); assert.equal(result.flag, 'failure'); assert.equal(result.code, 504); assert.equal(calls.sendToComputerPayloads.length, 2); const successfulBatchPrintStatusUpdate = calls.orderDeliveryLockUpdates.find(item => ( item && item.payload && item.payload.print_status === 'fin' && item.query && item.query.where && Array.isArray(item.query.where.id) && item.query.where.id.length === 2 && item.query.where.id.includes(201) && item.query.where.id.includes(202) )); assert.ok(successfulBatchPrintStatusUpdate); }); 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, 'printed'); 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, 'printed'); 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); const result = await service.send({ computerId: 'PC-03', type: 'customize', template: { page_width: 100, page_height: 60, template_content: [], }, data: { order_no: 'SO10003', }, timestamp: '1710000002', count: 1, }); assert.equal(result.flag, 'failure'); assert.equal(result.code, 400); assert.match(result.message, /printer/); assert.equal(calls.sendToComputerPayloads.length, 0); }); it('type=customize 不传 template 时应返回失败且提示 template', async () => { const { ctx, calls } = createContext(); const service = new PrintService(ctx); const result = await service.send({ computerId: 'PC-02', printer: 'Printer-B', type: 'customize', data: { order_no: 'SO10002', }, timestamp: '1710000001', count: 1, }); assert.equal(result.flag, 'failure'); assert.equal(result.code, 400); assert.match(result.message, /template/); assert.equal(calls.sendToComputerPayloads.length, 0); }); 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'); }); });