print-task.service.test.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375
  1. import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
  2. import { DataSource, Repository } from 'typeorm';
  3. import { PrintTaskService } from '../../src/services/print-task.service';
  4. import { FeiePrintTaskMt } from '../../src/entities/feie-print-task.mt.entity';
  5. import { FeiePrinterMt } from '../../src/entities/feie-printer.mt.entity';
  6. import type { FeieApiConfig, CreatePrintTaskDto } from '../../src/types/feie.types';
  7. // Mock dependencies
  8. vi.mock('../../src/services/feie-api.service', () => {
  9. return {
  10. FeieApiService: vi.fn().mockImplementation(() => ({
  11. printReceipt: vi.fn().mockResolvedValue({ ret: 0, msg: 'success', data: '123456' }),
  12. queryOrderStatus: vi.fn().mockResolvedValue({ ret: 0, data: '已打印' })
  13. }))
  14. };
  15. });
  16. vi.mock('../../src/services/printer.service', () => {
  17. return {
  18. PrinterService: vi.fn().mockImplementation(() => ({}))
  19. };
  20. });
  21. vi.mock('@d8d/shared-crud', () => {
  22. return {
  23. GenericCrudService: vi.fn().mockImplementation(() => ({
  24. create: vi.fn(),
  25. findOne: vi.fn(),
  26. findMany: vi.fn(),
  27. update: vi.fn(),
  28. delete: vi.fn(),
  29. repository: {
  30. findAndCount: vi.fn()
  31. }
  32. }))
  33. };
  34. });
  35. describe('PrintTaskService', () => {
  36. let printTaskService: PrintTaskService;
  37. let mockDataSource: DataSource;
  38. let mockPrinterRepository: Repository<FeiePrinterMt>;
  39. const mockFeieConfig: FeieApiConfig = {
  40. baseUrl: 'http://api.feieyun.cn/Api/Open/',
  41. user: 'test_user',
  42. ukey: 'test_ukey'
  43. };
  44. beforeEach(() => {
  45. vi.clearAllMocks();
  46. vi.useFakeTimers();
  47. mockPrinterRepository = {
  48. findOne: vi.fn()
  49. } as unknown as Repository<FeiePrinterMt>;
  50. mockDataSource = {
  51. getRepository: vi.fn().mockReturnValue(mockPrinterRepository)
  52. } as unknown as DataSource;
  53. printTaskService = new PrintTaskService(mockDataSource, mockFeieConfig);
  54. });
  55. afterEach(() => {
  56. vi.useRealTimers();
  57. });
  58. describe('createPrintTask', () => {
  59. it('应该成功创建立即打印任务', async () => {
  60. const tenantId = 1;
  61. const taskDto: CreatePrintTaskDto = {
  62. printerSn: 'TEST123456',
  63. content: '测试打印内容',
  64. printType: 'RECEIPT',
  65. delaySeconds: 0
  66. };
  67. const mockPrinter: Partial<FeiePrinterMt> = {
  68. id: 1,
  69. tenantId,
  70. printerSn: taskDto.printerSn,
  71. printerStatus: 'ACTIVE'
  72. };
  73. const mockTask: Partial<FeiePrintTaskMt> = {
  74. id: 1,
  75. tenantId,
  76. taskId: 'FEIE_123456789_1234',
  77. printerSn: taskDto.printerSn,
  78. content: taskDto.content,
  79. printType: taskDto.printType,
  80. printStatus: 'PENDING'
  81. };
  82. // Mock dependencies
  83. vi.mocked(mockPrinterRepository.findOne).mockResolvedValue(mockPrinter as FeiePrinterMt);
  84. (printTaskService as any).create = vi.fn().mockResolvedValue(mockTask);
  85. (printTaskService as any).executePrintTask = vi.fn().mockResolvedValue(mockTask);
  86. const result = await printTaskService.createPrintTask(tenantId, taskDto);
  87. expect(result).toEqual(mockTask);
  88. expect(mockPrinterRepository.findOne).toHaveBeenCalledWith({
  89. where: { tenantId, printerSn: taskDto.printerSn }
  90. });
  91. expect((printTaskService as any).executePrintTask).toHaveBeenCalledWith(tenantId, mockTask.taskId);
  92. });
  93. it('应该成功创建延迟打印任务', async () => {
  94. const tenantId = 1;
  95. const taskDto: CreatePrintTaskDto = {
  96. printerSn: 'TEST123456',
  97. content: '测试打印内容',
  98. printType: 'RECEIPT',
  99. delaySeconds: 120 // 2分钟延迟
  100. };
  101. const mockPrinter: Partial<FeiePrinterMt> = {
  102. id: 1,
  103. tenantId,
  104. printerSn: taskDto.printerSn,
  105. printerStatus: 'ACTIVE'
  106. };
  107. const mockTask: Partial<FeiePrintTaskMt> = {
  108. id: 1,
  109. tenantId,
  110. taskId: 'FEIE_123456789_1234',
  111. printerSn: taskDto.printerSn,
  112. content: taskDto.content,
  113. printType: taskDto.printType,
  114. printStatus: 'DELAYED',
  115. scheduledAt: new Date(Date.now() + 120000)
  116. };
  117. // Mock dependencies
  118. vi.mocked(mockPrinterRepository.findOne).mockResolvedValue(mockPrinter as FeiePrinterMt);
  119. (printTaskService as any).create = vi.fn().mockResolvedValue(mockTask);
  120. const result = await printTaskService.createPrintTask(tenantId, taskDto);
  121. expect(result).toEqual(mockTask);
  122. expect(result.printStatus).toBe('DELAYED');
  123. expect(result.scheduledAt).toBeInstanceOf(Date);
  124. expect((printTaskService as any).executePrintTask).not.toHaveBeenCalled();
  125. });
  126. it('应该在打印机不存在时抛出错误', async () => {
  127. const tenantId = 1;
  128. const taskDto: CreatePrintTaskDto = {
  129. printerSn: 'NONEXISTENT',
  130. content: '测试打印内容',
  131. printType: 'RECEIPT'
  132. };
  133. // Mock printer not found
  134. vi.mocked(mockPrinterRepository.findOne).mockResolvedValue(null);
  135. await expect(printTaskService.createPrintTask(tenantId, taskDto))
  136. .rejects
  137. .toThrow('打印机不存在');
  138. });
  139. });
  140. describe('executePrintTask', () => {
  141. it('应该成功执行打印任务', async () => {
  142. const tenantId = 1;
  143. const taskId = 'FEIE_123456789_1234';
  144. const mockTask: Partial<FeiePrintTaskMt> = {
  145. id: 1,
  146. tenantId,
  147. taskId,
  148. printerSn: 'TEST123456',
  149. content: '测试内容',
  150. printType: 'RECEIPT',
  151. printStatus: 'PENDING',
  152. retryCount: 0,
  153. maxRetries: 3
  154. };
  155. const updatedTask: Partial<FeiePrintTaskMt> = {
  156. ...mockTask,
  157. printStatus: 'SUCCESS',
  158. printedAt: new Date()
  159. };
  160. // Mock dependencies
  161. (printTaskService as any).findOne = vi.fn().mockResolvedValue(mockTask);
  162. (printTaskService as any).update = vi.fn().mockResolvedValue(updatedTask);
  163. const result = await printTaskService.executePrintTask(tenantId, taskId);
  164. expect(result).toEqual(updatedTask);
  165. expect((printTaskService as any).update).toHaveBeenCalledWith(mockTask.id, {
  166. printStatus: 'PRINTING',
  167. errorMessage: null
  168. });
  169. });
  170. it('应该在任务已取消时抛出错误', async () => {
  171. const tenantId = 1;
  172. const taskId = 'FEIE_123456789_1234';
  173. const mockTask: Partial<FeiePrintTaskMt> = {
  174. id: 1,
  175. tenantId,
  176. taskId,
  177. printStatus: 'CANCELLED'
  178. };
  179. // Mock dependencies
  180. (printTaskService as any).findOne = vi.fn().mockResolvedValue(mockTask);
  181. await expect(printTaskService.executePrintTask(tenantId, taskId))
  182. .rejects
  183. .toThrow('打印任务已取消');
  184. });
  185. it('应该在任务已完成时抛出错误', async () => {
  186. const tenantId = 1;
  187. const taskId = 'FEIE_123456789_1234';
  188. const mockTask: Partial<FeiePrintTaskMt> = {
  189. id: 1,
  190. tenantId,
  191. taskId,
  192. printStatus: 'SUCCESS'
  193. };
  194. // Mock dependencies
  195. (printTaskService as any).findOne = vi.fn().mockResolvedValue(mockTask);
  196. await expect(printTaskService.executePrintTask(tenantId, taskId))
  197. .rejects
  198. .toThrow('打印任务已完成');
  199. });
  200. it('应该在打印失败时重试', async () => {
  201. const tenantId = 1;
  202. const taskId = 'FEIE_123456789_1234';
  203. const mockTask: Partial<FeiePrintTaskMt> = {
  204. id: 1,
  205. tenantId,
  206. taskId,
  207. printerSn: 'TEST123456',
  208. content: '测试内容',
  209. printType: 'RECEIPT',
  210. printStatus: 'PENDING',
  211. retryCount: 0,
  212. maxRetries: 3
  213. };
  214. // Mock dependencies
  215. (printTaskService as any).findOne = vi.fn().mockResolvedValue(mockTask);
  216. (printTaskService as any).update = vi.fn().mockImplementation(async (id, data) => ({
  217. ...mockTask,
  218. ...data
  219. }));
  220. // Mock printReceipt to throw error
  221. const mockFeieApiService = {
  222. printReceipt: vi.fn().mockRejectedValue(new Error('打印失败'))
  223. };
  224. (printTaskService as any).feieApiService = mockFeieApiService;
  225. await expect(printTaskService.executePrintTask(tenantId, taskId))
  226. .rejects
  227. .toThrow('打印失败');
  228. // Check that retry was scheduled
  229. expect(setTimeout).toHaveBeenCalledWith(expect.any(Function), 5000);
  230. });
  231. });
  232. describe('cancelPrintTask', () => {
  233. it('应该成功取消打印任务', async () => {
  234. const tenantId = 1;
  235. const taskId = 'FEIE_123456789_1234';
  236. const mockTask: Partial<FeiePrintTaskMt> = {
  237. id: 1,
  238. tenantId,
  239. taskId,
  240. printStatus: 'PENDING'
  241. };
  242. const updatedTask: Partial<FeiePrintTaskMt> = {
  243. ...mockTask,
  244. printStatus: 'CANCELLED',
  245. cancelledAt: new Date(),
  246. cancelReason: 'MANUAL'
  247. };
  248. // Mock dependencies
  249. (printTaskService as any).findOne = vi.fn().mockResolvedValue(mockTask);
  250. (printTaskService as any).update = vi.fn().mockResolvedValue(updatedTask);
  251. const result = await printTaskService.cancelPrintTask(tenantId, taskId);
  252. expect(result).toEqual(updatedTask);
  253. });
  254. it('应该在任务已完成时抛出错误', async () => {
  255. const tenantId = 1;
  256. const taskId = 'FEIE_123456789_1234';
  257. const mockTask: Partial<FeiePrintTaskMt> = {
  258. id: 1,
  259. tenantId,
  260. taskId,
  261. printStatus: 'SUCCESS'
  262. };
  263. // Mock dependencies
  264. (printTaskService as any).findOne = vi.fn().mockResolvedValue(mockTask);
  265. await expect(printTaskService.cancelPrintTask(tenantId, taskId))
  266. .rejects
  267. .toThrow('打印任务状态为SUCCESS,无法取消');
  268. });
  269. });
  270. describe('retryPrintTask', () => {
  271. it('应该成功重试失败的打印任务', async () => {
  272. const tenantId = 1;
  273. const taskId = 'FEIE_123456789_1234';
  274. const mockTask: Partial<FeiePrintTaskMt> = {
  275. id: 1,
  276. tenantId,
  277. taskId,
  278. printStatus: 'FAILED',
  279. errorMessage: '之前的错误'
  280. };
  281. const updatedTask: Partial<FeiePrintTaskMt> = {
  282. ...mockTask,
  283. printStatus: 'PENDING',
  284. errorMessage: null,
  285. retryCount: 0
  286. };
  287. // Mock dependencies
  288. (printTaskService as any).findOne = vi.fn().mockResolvedValue(mockTask);
  289. (printTaskService as any).update = vi.fn().mockResolvedValue(updatedTask);
  290. (printTaskService as any).executePrintTask = vi.fn().mockResolvedValue(updatedTask);
  291. const result = await printTaskService.retryPrintTask(tenantId, taskId);
  292. expect(result).toEqual(updatedTask);
  293. expect((printTaskService as any).executePrintTask).toHaveBeenCalledWith(tenantId, taskId);
  294. });
  295. it('应该在任务不是失败状态时抛出错误', async () => {
  296. const tenantId = 1;
  297. const taskId = 'FEIE_123456789_1234';
  298. const mockTask: Partial<FeiePrintTaskMt> = {
  299. id: 1,
  300. tenantId,
  301. taskId,
  302. printStatus: 'PENDING'
  303. };
  304. // Mock dependencies
  305. (printTaskService as any).findOne = vi.fn().mockResolvedValue(mockTask);
  306. await expect(printTaskService.retryPrintTask(tenantId, taskId))
  307. .rejects
  308. .toThrow('只有失败的打印任务可以重试');
  309. });
  310. });
  311. });