print-task.service.ts 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367
  1. import { GenericCrudService } from '@d8d/shared-crud';
  2. import { DataSource, Repository } from 'typeorm';
  3. import { FeiePrintTaskMt } from '../entities/feie-print-task.mt.entity';
  4. import { FeiePrinterMt } from '../entities/feie-printer.mt.entity';
  5. import { FeieApiService } from './feie-api.service';
  6. import { PrinterService } from './printer.service';
  7. import { FeieApiConfig, CreatePrintTaskDto, PrintStatus, PrintType, CancelReason } from '../types/feie.types';
  8. export class PrintTaskService extends GenericCrudService<FeiePrintTaskMt> {
  9. private feieApiService: FeieApiService;
  10. private printerService: PrinterService;
  11. private printerRepository: Repository<FeiePrinterMt>;
  12. constructor(dataSource: DataSource, feieConfig: FeieApiConfig) {
  13. super(dataSource, FeiePrintTaskMt, {
  14. tenantOptions: { enabled: true, tenantIdField: 'tenantId' }
  15. });
  16. this.feieApiService = new FeieApiService(feieConfig);
  17. this.printerService = new PrinterService(dataSource, feieConfig);
  18. this.printerRepository = dataSource.getRepository(FeiePrinterMt);
  19. }
  20. /**
  21. * 创建打印任务
  22. */
  23. async createPrintTask(tenantId: number, taskDto: CreatePrintTaskDto): Promise<FeiePrintTaskMt> {
  24. // 验证打印机是否存在且可用
  25. const printer = await this.printerRepository.findOne({
  26. where: {
  27. tenantId,
  28. printerSn: taskDto.printerSn
  29. }
  30. });
  31. if (!printer) {
  32. throw new Error('打印机不存在');
  33. }
  34. // 生成任务ID
  35. const taskId = this.generateTaskId();
  36. // 计算计划打印时间
  37. let scheduledAt: Date | null = null;
  38. let printStatus = PrintStatus.PENDING;
  39. if (taskDto.delaySeconds && taskDto.delaySeconds > 0) {
  40. scheduledAt = new Date(Date.now() + taskDto.delaySeconds * 1000);
  41. printStatus = PrintStatus.DELAYED;
  42. }
  43. // 创建打印任务记录
  44. const printTask = await this.create({
  45. tenantId,
  46. taskId,
  47. orderId: taskDto.orderId || null,
  48. printerSn: taskDto.printerSn,
  49. content: taskDto.content,
  50. printType: taskDto.printType,
  51. printStatus,
  52. scheduledAt,
  53. retryCount: 0,
  54. maxRetries: 3
  55. });
  56. // 如果是立即打印,则立即执行
  57. if (!taskDto.delaySeconds || taskDto.delaySeconds <= 0) {
  58. await this.executePrintTask(tenantId, taskId);
  59. }
  60. return printTask;
  61. }
  62. /**
  63. * 执行打印任务
  64. */
  65. async executePrintTask(tenantId: number, taskId: string): Promise<FeiePrintTaskMt> {
  66. const task = await this.findOne({
  67. where: { tenantId, taskId }
  68. });
  69. if (!task) {
  70. throw new Error('打印任务不存在');
  71. }
  72. // 检查任务状态
  73. if (task.printStatus === PrintStatus.CANCELLED) {
  74. throw new Error('打印任务已取消');
  75. }
  76. if (task.printStatus === PrintStatus.SUCCESS) {
  77. throw new Error('打印任务已完成');
  78. }
  79. // 更新状态为打印中
  80. await this.update(task.id, {
  81. printStatus: PrintStatus.PRINTING,
  82. errorMessage: null
  83. });
  84. try {
  85. // 调用飞鹅API打印
  86. const response = await this.feieApiService.printReceipt({
  87. sn: task.printerSn,
  88. content: task.content,
  89. times: 1
  90. });
  91. // 更新任务状态
  92. const updatedTask = await this.update(task.id, {
  93. printStatus: PrintStatus.SUCCESS,
  94. printedAt: new Date(),
  95. errorMessage: null
  96. });
  97. return updatedTask;
  98. } catch (error) {
  99. // 处理打印失败
  100. const errorMessage = error instanceof Error ? error.message : '打印失败';
  101. // 检查是否需要重试
  102. const shouldRetry = task.retryCount < task.maxRetries;
  103. const updateData: Partial<FeiePrintTaskMt> = {
  104. errorMessage,
  105. retryCount: task.retryCount + 1
  106. };
  107. if (shouldRetry) {
  108. updateData.printStatus = PrintStatus.PENDING;
  109. } else {
  110. updateData.printStatus = PrintStatus.FAILED;
  111. }
  112. const updatedTask = await this.update(task.id, updateData);
  113. if (shouldRetry) {
  114. // 安排重试(5秒后)
  115. setTimeout(() => {
  116. this.executePrintTask(tenantId, taskId).catch(console.error);
  117. }, 5000);
  118. }
  119. throw error;
  120. }
  121. }
  122. /**
  123. * 取消打印任务
  124. */
  125. async cancelPrintTask(
  126. tenantId: number,
  127. taskId: string,
  128. reason: CancelReason = CancelReason.MANUAL
  129. ): Promise<FeiePrintTaskMt> {
  130. const task = await this.findOne({
  131. where: { tenantId, taskId }
  132. });
  133. if (!task) {
  134. throw new Error('打印任务不存在');
  135. }
  136. // 检查任务状态是否可以取消
  137. if ([PrintStatus.SUCCESS, PrintStatus.CANCELLED].includes(task.printStatus as PrintStatus)) {
  138. throw new Error(`打印任务状态为${task.printStatus},无法取消`);
  139. }
  140. // 更新任务状态
  141. return this.update(task.id, {
  142. printStatus: PrintStatus.CANCELLED,
  143. cancelledAt: new Date(),
  144. cancelReason: reason
  145. });
  146. }
  147. /**
  148. * 重试打印任务
  149. */
  150. async retryPrintTask(tenantId: number, taskId: string): Promise<FeiePrintTaskMt> {
  151. const task = await this.findOne({
  152. where: { tenantId, taskId }
  153. });
  154. if (!task) {
  155. throw new Error('打印任务不存在');
  156. }
  157. // 检查任务状态是否可以重试
  158. if (task.printStatus !== PrintStatus.FAILED) {
  159. throw new Error('只有失败的打印任务可以重试');
  160. }
  161. // 重置重试计数和错误信息
  162. const updatedTask = await this.update(task.id, {
  163. printStatus: PrintStatus.PENDING,
  164. errorMessage: null,
  165. retryCount: 0
  166. });
  167. // 立即执行重试
  168. await this.executePrintTask(tenantId, taskId);
  169. return updatedTask;
  170. }
  171. /**
  172. * 查询打印任务状态
  173. */
  174. async getPrintTaskStatus(tenantId: number, taskId: string): Promise<any> {
  175. const task = await this.findOne({
  176. where: { tenantId, taskId }
  177. });
  178. if (!task) {
  179. throw new Error('打印任务不存在');
  180. }
  181. // 如果任务已完成,返回本地状态
  182. if (task.printStatus === PrintStatus.SUCCESS || task.printStatus === PrintStatus.CANCELLED) {
  183. return {
  184. taskId: task.taskId,
  185. printStatus: task.printStatus,
  186. printedAt: task.printedAt,
  187. cancelledAt: task.cancelledAt,
  188. cancelReason: task.cancelReason,
  189. errorMessage: task.errorMessage
  190. };
  191. }
  192. // 查询飞鹅API获取最新状态
  193. try {
  194. const response = await this.feieApiService.queryOrderStatus(taskId);
  195. // 根据飞鹅API响应更新本地状态
  196. let newStatus = task.printStatus;
  197. if (response.data === '已打印') {
  198. newStatus = PrintStatus.SUCCESS;
  199. } else if (response.data === '打印失败') {
  200. newStatus = PrintStatus.FAILED;
  201. }
  202. if (newStatus !== task.printStatus) {
  203. const updateData: Partial<FeiePrintTaskMt> = {
  204. printStatus: newStatus
  205. };
  206. if (newStatus === PrintStatus.SUCCESS) {
  207. updateData.printedAt = new Date();
  208. }
  209. await this.update(task.id, updateData);
  210. }
  211. return {
  212. taskId: task.taskId,
  213. printStatus: newStatus,
  214. remoteStatus: response.data,
  215. printedAt: task.printedAt,
  216. errorMessage: task.errorMessage
  217. };
  218. } catch (error) {
  219. // API查询失败,返回本地状态
  220. return {
  221. taskId: task.taskId,
  222. printStatus: task.printStatus,
  223. printedAt: task.printedAt,
  224. errorMessage: task.errorMessage,
  225. apiError: error instanceof Error ? error.message : '查询API失败'
  226. };
  227. }
  228. }
  229. /**
  230. * 获取打印任务列表
  231. */
  232. async getPrintTasks(
  233. tenantId: number,
  234. filters: {
  235. orderId?: number;
  236. printerSn?: string;
  237. printType?: PrintType;
  238. printStatus?: PrintStatus;
  239. startDate?: Date;
  240. endDate?: Date;
  241. } = {},
  242. page: number = 1,
  243. limit: number = 20
  244. ): Promise<{ tasks: FeiePrintTaskMt[]; total: number }> {
  245. const where: any = { tenantId };
  246. if (filters.orderId) {
  247. where.orderId = filters.orderId;
  248. }
  249. if (filters.printerSn) {
  250. where.printerSn = filters.printerSn;
  251. }
  252. if (filters.printType) {
  253. where.printType = filters.printType;
  254. }
  255. if (filters.printStatus) {
  256. where.printStatus = filters.printStatus;
  257. }
  258. if (filters.startDate || filters.endDate) {
  259. where.createdAt = {};
  260. if (filters.startDate) {
  261. where.createdAt.$gte = filters.startDate;
  262. }
  263. if (filters.endDate) {
  264. where.createdAt.$lte = filters.endDate;
  265. }
  266. }
  267. const [tasks, total] = await this.repository.findAndCount({
  268. where,
  269. order: { createdAt: 'DESC' },
  270. skip: (page - 1) * limit,
  271. take: limit
  272. });
  273. return { tasks, total };
  274. }
  275. /**
  276. * 获取待处理的延迟打印任务
  277. */
  278. async getPendingDelayedTasks(tenantId: number): Promise<FeiePrintTaskMt[]> {
  279. return this.findMany({
  280. where: {
  281. tenantId,
  282. printStatus: PrintStatus.DELAYED,
  283. scheduledAt: { $lte: new Date() }
  284. },
  285. order: { scheduledAt: 'ASC' }
  286. });
  287. }
  288. /**
  289. * 处理退款事件,取消相关打印任务
  290. */
  291. async handleRefundEvent(tenantId: number, orderId: number): Promise<void> {
  292. const tasks = await this.findMany({
  293. where: {
  294. tenantId,
  295. orderId,
  296. printStatus: PrintStatus.DELAYED
  297. }
  298. });
  299. for (const task of tasks) {
  300. await this.cancelPrintTask(tenantId, task.taskId, CancelReason.REFUND);
  301. }
  302. }
  303. /**
  304. * 生成任务ID
  305. */
  306. private generateTaskId(): string {
  307. const timestamp = Date.now();
  308. const random = Math.floor(Math.random() * 10000);
  309. return `FEIE_${timestamp}_${random}`;
  310. }
  311. }