test-delayed-simple.js 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186
  1. // 简单测试延迟打印任务流程
  2. const { DataSource } = require('typeorm');
  3. async function testDelayedPrintSimple() {
  4. console.log('=== 简单测试延迟打印任务流程 ===\n');
  5. // 创建数据源
  6. const dataSource = new DataSource({
  7. type: 'postgres',
  8. host: '127.0.0.1',
  9. port: 5432,
  10. username: 'postgres',
  11. password: '',
  12. database: 'postgres',
  13. synchronize: false,
  14. logging: false
  15. });
  16. try {
  17. await dataSource.initialize();
  18. console.log('✅ 数据库连接成功\n');
  19. const tenantId = 1;
  20. const testPrinterSn = 'TEST' + Math.floor(Math.random() * 1000);
  21. const testOrderId = Math.floor(Math.random() * 10000) + 10000;
  22. // 1. 确保打印机存在
  23. console.log('1. 创建测试打印机记录...');
  24. await dataSource.query(`
  25. INSERT INTO feie_printer_mt (tenant_id, printer_sn, printer_key, printer_name, printer_status, printer_type, is_default, created_at, updated_at)
  26. VALUES ($1, $2, $3, $4, $5, $6, $7, NOW(), NOW())
  27. ON CONFLICT (tenant_id, printer_sn) DO NOTHING
  28. `, [tenantId, testPrinterSn, 'test-key', '测试打印机', 'ACTIVE', '58mm', 0]);
  29. console.log('✅ 测试打印机记录已创建\n');
  30. // 2. 创建延迟打印任务
  31. console.log('2. 创建延迟打印任务...');
  32. const taskId = `FEIE_${Date.now()}_${Math.floor(Math.random() * 10000)}`;
  33. const delaySeconds = 5;
  34. const scheduledAt = new Date(Date.now() + delaySeconds * 1000);
  35. await dataSource.query(`
  36. INSERT INTO feie_print_task_mt
  37. (tenant_id, task_id, order_id, printer_sn, content, print_type, print_status, scheduled_at, retry_count, max_retries, created_at, updated_at)
  38. VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, NOW(), NOW())
  39. `, [
  40. tenantId,
  41. taskId,
  42. testOrderId,
  43. testPrinterSn,
  44. `测试延迟打印内容\n订单号: ${testOrderId}\n时间: ${new Date().toLocaleString()}`,
  45. 'RECEIPT',
  46. 'DELAYED',
  47. scheduledAt,
  48. 0,
  49. 3
  50. ]);
  51. console.log(`✅ 延迟打印任务创建成功`);
  52. console.log(` 任务ID: ${taskId}`);
  53. console.log(` 订单ID: ${testOrderId}`);
  54. console.log(` 打印机SN: ${testPrinterSn}`);
  55. console.log(` 延迟秒数: ${delaySeconds}`);
  56. console.log(` 计划时间: ${scheduledAt}\n`);
  57. // 3. 查询任务
  58. console.log('3. 查询任务状态...');
  59. const tasks = await dataSource.query(
  60. 'SELECT * FROM feie_print_task_mt WHERE tenant_id = $1 AND task_id = $2',
  61. [tenantId, taskId]
  62. );
  63. if (tasks.length > 0) {
  64. const task = tasks[0];
  65. console.log(`✅ 任务查询成功`);
  66. console.log(` 任务状态: ${task.print_status}`);
  67. console.log(` 计划时间: ${task.scheduled_at}`);
  68. console.log(` 创建时间: ${task.created_at}\n`);
  69. }
  70. // 4. 模拟调度器处理(查询待处理任务)
  71. console.log('4. 模拟调度器查询待处理任务...');
  72. console.log(`等待 ${delaySeconds + 2} 秒让任务到达执行时间...`);
  73. await new Promise(resolve => setTimeout(resolve, (delaySeconds + 2) * 1000));
  74. const pendingTasks = await dataSource.query(`
  75. SELECT * FROM feie_print_task_mt
  76. WHERE tenant_id = $1
  77. AND (print_status = 'DELAYED' OR print_status = 'PENDING')
  78. AND scheduled_at <= NOW()
  79. ORDER BY scheduled_at ASC
  80. `, [tenantId]);
  81. console.log(`找到 ${pendingTasks.length} 个待处理任务`);
  82. if (pendingTasks.length > 0) {
  83. const pendingTask = pendingTasks[0];
  84. console.log(` 任务ID: ${pendingTask.task_id}`);
  85. console.log(` 状态: ${pendingTask.print_status}`);
  86. console.log(` 计划时间: ${pendingTask.scheduled_at}`);
  87. console.log(` 当前时间: ${new Date()}`);
  88. console.log(` 是否已到执行时间: ${new Date() >= new Date(pendingTask.scheduled_at) ? '是' : '否'}\n`);
  89. }
  90. // 5. 模拟执行打印(更新状态)
  91. console.log('5. 模拟执行打印任务...');
  92. if (pendingTasks.length > 0) {
  93. await dataSource.query(`
  94. UPDATE feie_print_task_mt
  95. SET print_status = 'PRINTING', updated_at = NOW()
  96. WHERE tenant_id = $1 AND task_id = $2
  97. `, [tenantId, taskId]);
  98. console.log('✅ 任务状态更新为PRINTING');
  99. // 模拟打印失败(测试环境)
  100. await new Promise(resolve => setTimeout(resolve, 1000));
  101. await dataSource.query(`
  102. UPDATE feie_print_task_mt
  103. SET print_status = 'PENDING',
  104. error_message = $3,
  105. retry_count = retry_count + 1,
  106. updated_at = NOW()
  107. WHERE tenant_id = $1 AND task_id = $2
  108. `, [tenantId, taskId, '飞鹅API测试环境失败']);
  109. console.log('✅ 模拟打印失败,任务进入重试状态');
  110. console.log(` 错误信息: 飞鹅API测试环境失败`);
  111. console.log(` 重试次数: 1/3\n`);
  112. }
  113. // 6. 查询最终状态
  114. console.log('6. 查询最终任务状态...');
  115. const finalTasks = await dataSource.query(
  116. 'SELECT * FROM feie_print_task_mt WHERE tenant_id = $1 AND task_id = $2',
  117. [tenantId, taskId]
  118. );
  119. if (finalTasks.length > 0) {
  120. const finalTask = finalTasks[0];
  121. console.log(`最终任务状态:`);
  122. console.log(` 任务ID: ${finalTask.task_id}`);
  123. console.log(` 状态: ${finalTask.print_status}`);
  124. console.log(` 错误信息: ${finalTask.error_message || '无'}`);
  125. console.log(` 重试次数: ${finalTask.retry_count}/${finalTask.max_retries}`);
  126. console.log(` 创建时间: ${finalTask.created_at}`);
  127. console.log(` 更新时间: ${finalTask.updated_at}\n`);
  128. }
  129. // 7. 清理测试数据
  130. console.log('7. 清理测试数据...');
  131. await dataSource.query(
  132. 'DELETE FROM feie_print_task_mt WHERE tenant_id = $1 AND task_id = $2',
  133. [tenantId, taskId]
  134. );
  135. console.log('✅ 测试数据已清理');
  136. console.log('\n🎉 === 测试完成 ===');
  137. console.log('测试流程验证:');
  138. console.log('1. ✅ 数据库连接正常');
  139. console.log('2. ✅ 打印机记录创建正常');
  140. console.log('3. ✅ 延迟打印任务创建正常');
  141. console.log('4. ✅ 任务状态查询正常');
  142. console.log('5. ✅ 调度器查询逻辑正常');
  143. console.log('6. ✅ 任务状态更新正常');
  144. console.log('7. ✅ 数据清理正常');
  145. } catch (error) {
  146. console.error('\n❌ 测试失败:', error);
  147. console.error('错误堆栈:', error.stack);
  148. } finally {
  149. try {
  150. await dataSource.destroy();
  151. console.log('\n🔌 数据库连接已关闭');
  152. } catch (error) {
  153. console.error('关闭数据库连接失败:', error);
  154. }
  155. }
  156. }
  157. // 运行测试
  158. testDelayedPrintSimple().catch(error => {
  159. console.error('测试脚本执行失败:', error);
  160. process.exit(1);
  161. });