test-delayed-print-full.js 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227
  1. // 完整测试延迟打印任务流程
  2. const { DataSource } = require('typeorm');
  3. const { PrintTaskService } = require('./packages/feie-printer-module-mt/dist/services/print-task.service');
  4. const { DelaySchedulerService } = require('./packages/feie-printer-module-mt/dist/services/delay-scheduler.service');
  5. const { PrintStatus, CancelReason } = require('./packages/feie-printer-module-mt/dist/types/feie.types');
  6. async function testFullDelayedPrintFlow() {
  7. console.log('=== 开始测试完整延迟打印任务流程 ===\n');
  8. // 模拟飞鹅配置
  9. const feieConfig = {
  10. user: 'test@example.com',
  11. ukey: 'test-ukey',
  12. baseUrl: 'https://api.feieyun.cn/Api/Open/',
  13. timeout: 10000,
  14. maxRetries: 3
  15. };
  16. // 创建数据源
  17. const dataSource = new DataSource({
  18. type: 'postgres',
  19. host: '127.0.0.1',
  20. port: 5432,
  21. username: 'postgres',
  22. password: '',
  23. database: 'postgres',
  24. synchronize: false,
  25. logging: false
  26. });
  27. try {
  28. await dataSource.initialize();
  29. console.log('✅ 数据库连接成功\n');
  30. const tenantId = 1; // 测试租户ID
  31. const printTaskService = new PrintTaskService(dataSource, feieConfig);
  32. const delayScheduler = new DelaySchedulerService(dataSource, feieConfig, tenantId);
  33. // 测试1: 创建延迟打印任务
  34. console.log('📝 测试1: 创建延迟打印任务');
  35. const testOrderId = Math.floor(Math.random() * 10000) + 10000;
  36. const testPrinterSn = 'TEST' + Math.floor(Math.random() * 1000);
  37. console.log(`测试订单ID: ${testOrderId}`);
  38. console.log(`测试打印机SN: ${testPrinterSn}`);
  39. // 先确保打印机存在(创建测试打印机记录)
  40. try {
  41. await dataSource.query(`
  42. INSERT INTO feie_printer_mt (tenant_id, printer_sn, printer_key, printer_name, status, created_at, updated_at)
  43. VALUES ($1, $2, $3, $4, $5, NOW(), NOW())
  44. ON CONFLICT (tenant_id, printer_sn) DO NOTHING
  45. `, [tenantId, testPrinterSn, 'test-key', '测试打印机', 'ACTIVE']);
  46. console.log('✅ 测试打印机记录已创建/存在');
  47. } catch (error) {
  48. console.log('ℹ️ 打印机记录可能已存在,继续测试');
  49. }
  50. // 创建延迟5秒的打印任务
  51. console.log('\n🕐 创建延迟5秒的打印任务...');
  52. const delaySeconds = 5;
  53. const task = await printTaskService.createPrintTask(tenantId, {
  54. orderId: testOrderId,
  55. printerSn: testPrinterSn,
  56. content: `测试延迟打印内容\n订单号: ${testOrderId}\n时间: ${new Date().toLocaleString()}\n延迟: ${delaySeconds}秒`,
  57. printType: 'RECEIPT',
  58. delaySeconds: delaySeconds
  59. });
  60. console.log(`✅ 打印任务创建成功`);
  61. console.log(` 任务ID: ${task.taskId}`);
  62. console.log(` 状态: ${task.printStatus}`);
  63. console.log(` 计划时间: ${task.scheduledAt}`);
  64. console.log(` 延迟秒数: ${delaySeconds}`);
  65. // 验证任务状态
  66. if (task.printStatus !== PrintStatus.DELAYED) {
  67. throw new Error(`任务状态应为DELAYED,实际为${task.printStatus}`);
  68. }
  69. // 检查任务是否已插入数据库
  70. const dbTask = await dataSource.query(
  71. 'SELECT * FROM feie_print_task_mt WHERE tenant_id = $1 AND task_id = $2',
  72. [tenantId, task.taskId]
  73. );
  74. if (dbTask.length === 0) {
  75. throw new Error('任务未成功插入数据库');
  76. }
  77. console.log('✅ 任务已成功保存到数据库\n');
  78. // 测试2: 启动延迟调度器
  79. console.log('⏰ 测试2: 启动延迟调度器');
  80. await delayScheduler.start();
  81. console.log('✅ 延迟调度器已启动\n');
  82. // 测试3: 手动触发任务处理(模拟调度器执行)
  83. console.log('🔄 测试3: 手动触发任务处理');
  84. // 等待延迟时间+2秒
  85. console.log(`等待 ${delaySeconds + 2} 秒让任务到达执行时间...`);
  86. await new Promise(resolve => setTimeout(resolve, (delaySeconds + 2) * 1000));
  87. // 手动触发处理
  88. const result = await delayScheduler.triggerManualProcess(tenantId);
  89. console.log(`手动处理结果: ${result.message}`);
  90. if (result.success) {
  91. console.log(`✅ 成功处理 ${result.processedTasks} 个任务`);
  92. } else {
  93. console.log('❌ 手动处理失败');
  94. }
  95. // 检查任务状态变化
  96. console.log('\n📊 检查任务状态变化...');
  97. const updatedTask = await dataSource.query(
  98. 'SELECT * FROM feie_print_task_mt WHERE tenant_id = $1 AND task_id = $2',
  99. [tenantId, task.taskId]
  100. );
  101. if (updatedTask.length > 0) {
  102. const taskData = updatedTask[0];
  103. console.log(`当前任务状态: ${taskData.print_status}`);
  104. console.log(`错误信息: ${taskData.error_message || '无'}`);
  105. console.log(`重试次数: ${taskData.retry_count}`);
  106. // 由于是测试环境,飞鹅API会失败,任务应该进入重试或失败状态
  107. if (taskData.print_status === PrintStatus.PENDING || taskData.print_status === PrintStatus.FAILED) {
  108. console.log('✅ 任务状态变化符合预期(飞鹅API测试环境会失败)');
  109. } else {
  110. console.log(`ℹ️ 任务状态: ${taskData.print_status}`);
  111. }
  112. }
  113. // 测试4: 停止调度器
  114. console.log('\n🛑 测试4: 停止调度器');
  115. await delayScheduler.stop();
  116. console.log('✅ 延迟调度器已停止\n');
  117. // 测试5: 创建立即打印任务(delaySeconds=0)
  118. console.log('⚡ 测试5: 创建立即打印任务(delaySeconds=0)');
  119. const immediateTask = await printTaskService.createPrintTask(tenantId, {
  120. orderId: testOrderId + 1,
  121. printerSn: testPrinterSn,
  122. content: '测试立即打印内容',
  123. printType: 'RECEIPT',
  124. delaySeconds: 0
  125. });
  126. console.log(`✅ 立即打印任务创建成功`);
  127. console.log(` 任务ID: ${immediateTask.taskId}`);
  128. console.log(` 状态: ${immediateTask.printStatus}`);
  129. // 检查立即任务的状态
  130. const immediateTaskDb = await dataSource.query(
  131. 'SELECT * FROM feie_print_task_mt WHERE tenant_id = $1 AND task_id = $2',
  132. [tenantId, immediateTask.taskId]
  133. );
  134. if (immediateTaskDb.length > 0) {
  135. console.log(` 数据库状态: ${immediateTaskDb[0].print_status}`);
  136. }
  137. // 测试6: 取消打印任务
  138. console.log('\n❌ 测试6: 取消打印任务');
  139. // 先创建一个新的延迟任务
  140. const cancelTask = await printTaskService.createPrintTask(tenantId, {
  141. orderId: testOrderId + 2,
  142. printerSn: testPrinterSn,
  143. content: '测试取消的打印内容',
  144. printType: 'RECEIPT',
  145. delaySeconds: 10
  146. });
  147. console.log(`创建用于取消的任务: ${cancelTask.taskId}`);
  148. // 取消任务
  149. const cancelledTask = await printTaskService.cancelPrintTask(
  150. tenantId,
  151. cancelTask.taskId,
  152. CancelReason.MANUAL
  153. );
  154. console.log(`✅ 任务取消成功`);
  155. console.log(` 取消后状态: ${cancelledTask.printStatus}`);
  156. console.log(` 取消原因: ${cancelledTask.cancelReason}`);
  157. if (cancelledTask.printStatus !== PrintStatus.CANCELLED) {
  158. throw new Error(`取消后任务状态应为CANCELLED,实际为${cancelledTask.printStatus}`);
  159. }
  160. // 清理测试数据
  161. console.log('\n🧹 清理测试数据...');
  162. await dataSource.query(
  163. 'DELETE FROM feie_print_task_mt WHERE tenant_id = $1 AND task_id LIKE $2',
  164. [tenantId, 'FEIE_%']
  165. );
  166. console.log('✅ 测试数据已清理');
  167. console.log('\n🎉 === 所有测试完成 ===');
  168. console.log('总结:');
  169. console.log('1. ✅ 延迟打印任务创建成功');
  170. console.log('2. ✅ 延迟调度器启动/停止正常');
  171. console.log('3. ✅ 任务状态管理正常');
  172. console.log('4. ✅ 立即打印任务创建正常');
  173. console.log('5. ✅ 任务取消功能正常');
  174. console.log('6. ✅ 数据库操作正常');
  175. } catch (error) {
  176. console.error('\n❌ 测试失败:', error);
  177. console.error('错误堆栈:', error.stack);
  178. } finally {
  179. try {
  180. await dataSource.destroy();
  181. console.log('\n🔌 数据库连接已关闭');
  182. } catch (error) {
  183. console.error('关闭数据库连接失败:', error);
  184. }
  185. }
  186. }
  187. // 运行测试
  188. testFullDelayedPrintFlow().catch(error => {
  189. console.error('测试脚本执行失败:', error);
  190. process.exit(1);
  191. });