| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227 |
- // 完整测试延迟打印任务流程
- const { DataSource } = require('typeorm');
- const { PrintTaskService } = require('./packages/feie-printer-module-mt/dist/services/print-task.service');
- const { DelaySchedulerService } = require('./packages/feie-printer-module-mt/dist/services/delay-scheduler.service');
- const { PrintStatus, CancelReason } = require('./packages/feie-printer-module-mt/dist/types/feie.types');
- async function testFullDelayedPrintFlow() {
- console.log('=== 开始测试完整延迟打印任务流程 ===\n');
- // 模拟飞鹅配置
- const feieConfig = {
- user: 'test@example.com',
- ukey: 'test-ukey',
- baseUrl: 'https://api.feieyun.cn/Api/Open/',
- timeout: 10000,
- maxRetries: 3
- };
- // 创建数据源
- const dataSource = new DataSource({
- type: 'postgres',
- host: '127.0.0.1',
- port: 5432,
- username: 'postgres',
- password: '',
- database: 'postgres',
- synchronize: false,
- logging: false
- });
- try {
- await dataSource.initialize();
- console.log('✅ 数据库连接成功\n');
- const tenantId = 1; // 测试租户ID
- const printTaskService = new PrintTaskService(dataSource, feieConfig);
- const delayScheduler = new DelaySchedulerService(dataSource, feieConfig, tenantId);
- // 测试1: 创建延迟打印任务
- console.log('📝 测试1: 创建延迟打印任务');
- const testOrderId = Math.floor(Math.random() * 10000) + 10000;
- const testPrinterSn = 'TEST' + Math.floor(Math.random() * 1000);
- console.log(`测试订单ID: ${testOrderId}`);
- console.log(`测试打印机SN: ${testPrinterSn}`);
- // 先确保打印机存在(创建测试打印机记录)
- try {
- await dataSource.query(`
- INSERT INTO feie_printer_mt (tenant_id, printer_sn, printer_key, printer_name, status, created_at, updated_at)
- VALUES ($1, $2, $3, $4, $5, NOW(), NOW())
- ON CONFLICT (tenant_id, printer_sn) DO NOTHING
- `, [tenantId, testPrinterSn, 'test-key', '测试打印机', 'ACTIVE']);
- console.log('✅ 测试打印机记录已创建/存在');
- } catch (error) {
- console.log('ℹ️ 打印机记录可能已存在,继续测试');
- }
- // 创建延迟5秒的打印任务
- console.log('\n🕐 创建延迟5秒的打印任务...');
- const delaySeconds = 5;
- const task = await printTaskService.createPrintTask(tenantId, {
- orderId: testOrderId,
- printerSn: testPrinterSn,
- content: `测试延迟打印内容\n订单号: ${testOrderId}\n时间: ${new Date().toLocaleString()}\n延迟: ${delaySeconds}秒`,
- printType: 'RECEIPT',
- delaySeconds: delaySeconds
- });
- console.log(`✅ 打印任务创建成功`);
- console.log(` 任务ID: ${task.taskId}`);
- console.log(` 状态: ${task.printStatus}`);
- console.log(` 计划时间: ${task.scheduledAt}`);
- console.log(` 延迟秒数: ${delaySeconds}`);
- // 验证任务状态
- if (task.printStatus !== PrintStatus.DELAYED) {
- throw new Error(`任务状态应为DELAYED,实际为${task.printStatus}`);
- }
- // 检查任务是否已插入数据库
- const dbTask = await dataSource.query(
- 'SELECT * FROM feie_print_task_mt WHERE tenant_id = $1 AND task_id = $2',
- [tenantId, task.taskId]
- );
- if (dbTask.length === 0) {
- throw new Error('任务未成功插入数据库');
- }
- console.log('✅ 任务已成功保存到数据库\n');
- // 测试2: 启动延迟调度器
- console.log('⏰ 测试2: 启动延迟调度器');
- await delayScheduler.start();
- console.log('✅ 延迟调度器已启动\n');
- // 测试3: 手动触发任务处理(模拟调度器执行)
- console.log('🔄 测试3: 手动触发任务处理');
- // 等待延迟时间+2秒
- console.log(`等待 ${delaySeconds + 2} 秒让任务到达执行时间...`);
- await new Promise(resolve => setTimeout(resolve, (delaySeconds + 2) * 1000));
- // 手动触发处理
- const result = await delayScheduler.triggerManualProcess(tenantId);
- console.log(`手动处理结果: ${result.message}`);
- if (result.success) {
- console.log(`✅ 成功处理 ${result.processedTasks} 个任务`);
- } else {
- console.log('❌ 手动处理失败');
- }
- // 检查任务状态变化
- console.log('\n📊 检查任务状态变化...');
- const updatedTask = await dataSource.query(
- 'SELECT * FROM feie_print_task_mt WHERE tenant_id = $1 AND task_id = $2',
- [tenantId, task.taskId]
- );
- if (updatedTask.length > 0) {
- const taskData = updatedTask[0];
- console.log(`当前任务状态: ${taskData.print_status}`);
- console.log(`错误信息: ${taskData.error_message || '无'}`);
- console.log(`重试次数: ${taskData.retry_count}`);
- // 由于是测试环境,飞鹅API会失败,任务应该进入重试或失败状态
- if (taskData.print_status === PrintStatus.PENDING || taskData.print_status === PrintStatus.FAILED) {
- console.log('✅ 任务状态变化符合预期(飞鹅API测试环境会失败)');
- } else {
- console.log(`ℹ️ 任务状态: ${taskData.print_status}`);
- }
- }
- // 测试4: 停止调度器
- console.log('\n🛑 测试4: 停止调度器');
- await delayScheduler.stop();
- console.log('✅ 延迟调度器已停止\n');
- // 测试5: 创建立即打印任务(delaySeconds=0)
- console.log('⚡ 测试5: 创建立即打印任务(delaySeconds=0)');
- const immediateTask = await printTaskService.createPrintTask(tenantId, {
- orderId: testOrderId + 1,
- printerSn: testPrinterSn,
- content: '测试立即打印内容',
- printType: 'RECEIPT',
- delaySeconds: 0
- });
- console.log(`✅ 立即打印任务创建成功`);
- console.log(` 任务ID: ${immediateTask.taskId}`);
- console.log(` 状态: ${immediateTask.printStatus}`);
- // 检查立即任务的状态
- const immediateTaskDb = await dataSource.query(
- 'SELECT * FROM feie_print_task_mt WHERE tenant_id = $1 AND task_id = $2',
- [tenantId, immediateTask.taskId]
- );
- if (immediateTaskDb.length > 0) {
- console.log(` 数据库状态: ${immediateTaskDb[0].print_status}`);
- }
- // 测试6: 取消打印任务
- console.log('\n❌ 测试6: 取消打印任务');
- // 先创建一个新的延迟任务
- const cancelTask = await printTaskService.createPrintTask(tenantId, {
- orderId: testOrderId + 2,
- printerSn: testPrinterSn,
- content: '测试取消的打印内容',
- printType: 'RECEIPT',
- delaySeconds: 10
- });
- console.log(`创建用于取消的任务: ${cancelTask.taskId}`);
- // 取消任务
- const cancelledTask = await printTaskService.cancelPrintTask(
- tenantId,
- cancelTask.taskId,
- CancelReason.MANUAL
- );
- console.log(`✅ 任务取消成功`);
- console.log(` 取消后状态: ${cancelledTask.printStatus}`);
- console.log(` 取消原因: ${cancelledTask.cancelReason}`);
- if (cancelledTask.printStatus !== PrintStatus.CANCELLED) {
- throw new Error(`取消后任务状态应为CANCELLED,实际为${cancelledTask.printStatus}`);
- }
- // 清理测试数据
- console.log('\n🧹 清理测试数据...');
- await dataSource.query(
- 'DELETE FROM feie_print_task_mt WHERE tenant_id = $1 AND task_id LIKE $2',
- [tenantId, 'FEIE_%']
- );
- console.log('✅ 测试数据已清理');
- console.log('\n🎉 === 所有测试完成 ===');
- console.log('总结:');
- console.log('1. ✅ 延迟打印任务创建成功');
- console.log('2. ✅ 延迟调度器启动/停止正常');
- console.log('3. ✅ 任务状态管理正常');
- console.log('4. ✅ 立即打印任务创建正常');
- console.log('5. ✅ 任务取消功能正常');
- console.log('6. ✅ 数据库操作正常');
- } catch (error) {
- console.error('\n❌ 测试失败:', error);
- console.error('错误堆栈:', error.stack);
- } finally {
- try {
- await dataSource.destroy();
- console.log('\n🔌 数据库连接已关闭');
- } catch (error) {
- console.error('关闭数据库连接失败:', error);
- }
- }
- }
- // 运行测试
- testFullDelayedPrintFlow().catch(error => {
- console.error('测试脚本执行失败:', error);
- process.exit(1);
- });
|