PrintRecordService.ts 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225
  1. import {DbStorage} from "./DbStorage";
  2. import {logger} from 'ee-core/log';
  3. class PrintRecordService {
  4. private static tableName: String = 'print_record'
  5. constructor() {
  6. this.createTable()
  7. }
  8. /**
  9. * 创建打印记录表
  10. * @private
  11. */
  12. private createTable() {
  13. if (!DbStorage.checkTableExists(PrintRecordService.tableName)) {
  14. const sql = `CREATE TABLE IF NOT EXISTS ${PrintRecordService.tableName} (
  15. id INTEGER PRIMARY KEY AUTOINCREMENT,
  16. jobId VARCHAR(128),
  17. printerName VARCHAR(200),
  18. printHtml TEXT,
  19. printStatus VARCHAR(32),
  20. failureReason TEXT,
  21. createdAt TEXT DEFAULT (datetime('now', 'localtime'))
  22. )`
  23. DbStorage.getDb().exec(sql)
  24. }
  25. }
  26. public add(record: AddPrintRecord): PrintRecord {
  27. const uuId = crypto.randomUUID().replace(/-/g, '')
  28. const sql = `INSERT INTO ${PrintRecordService.tableName} (jobId,printerName,printHtml,printStatus,failureReason) VALUES (@jobId,@printerName, @printHtml,@printStatus,@failureReason)`
  29. const insert = DbStorage.getDb().prepare(sql)
  30. insert.run({jobId: uuId, ...record})
  31. return this.getByUuId(uuId)
  32. }
  33. public getByUuId(uuId: String): PrintRecord {
  34. const sql = `SELECT * FROM ${PrintRecordService.tableName} WHERE job_id = ?`
  35. const select = DbStorage.getDb().prepare(sql)
  36. return select.get(uuId) as PrintRecord
  37. }
  38. /**
  39. * 分页查询打印记录
  40. * @param query {@link PageQuery}
  41. */
  42. public getPage(query: PageQuery): Promise<Page> {
  43. return new Promise((resolve, _) => {
  44. this.validatePaginationParams(query)
  45. logger.info('【PrintRecordService#getPage】打印记录分页查询参数:', query)
  46. // 计算偏移量
  47. const offset = (query.page - 1) * query.size;
  48. const { whereSql, queryParams } = this.buildWhereClause(query);
  49. // 查询数据
  50. const dataQuery = `
  51. SELECT * FROM ${PrintRecordService.tableName}
  52. ${whereSql}
  53. ORDER BY createdAt DESC
  54. LIMIT ? OFFSET ?
  55. `;
  56. // 查询总数
  57. const countQuery = `
  58. SELECT COUNT(1) as total FROM ${PrintRecordService.tableName}
  59. ${whereSql}
  60. `;
  61. try {
  62. const db = DbStorage.getDb();
  63. const selectPage = db.prepare(dataQuery)
  64. const dataRows = selectPage.all(...queryParams, query.size, offset)
  65. const totalQuery = db.prepare(countQuery)
  66. const result = totalQuery.get(...queryParams);
  67. // @ts-ignore
  68. const total = result?.total ?? 0;
  69. const totalPages = Math.ceil((total as number) / query.size);
  70. resolve({
  71. total: total as number,
  72. page: query.page,
  73. size: query.size,
  74. totalPages: totalPages,
  75. data: dataRows as PrintRecord[]
  76. })
  77. }catch (e) {
  78. logger.error('【PrintRecordService#getPage】打印记录数据库查询失败:', e)
  79. resolve({
  80. total: 0,
  81. page: query.page,
  82. size: query.size,
  83. totalPages: 0,
  84. data: []
  85. })
  86. }
  87. })
  88. }
  89. private buildWhereClause(query: PageQuery): { whereSql: string; queryParams: any[] } {
  90. const whereClauses: string[] = [];
  91. const queryParams: any[] = [];
  92. if (query.startDate) {
  93. whereClauses.push('createdAt >= ?');
  94. queryParams.push(query.startDate);
  95. }
  96. if (query.endDate) {
  97. whereClauses.push('createdAt <= ?');
  98. queryParams.push(query.endDate);
  99. }
  100. const whereSql = whereClauses.length > 0
  101. ? `WHERE ${whereClauses.join(' AND ')}`
  102. : '';
  103. return { whereSql, queryParams };
  104. }
  105. private validatePaginationParams(params: PageQuery): void {
  106. // 校验页码和每页数量
  107. if (params.page < 1 || !Number.isInteger(params.page)) {
  108. throw new Error('页码必须为正整数');
  109. }
  110. if (params.size < 1 || !Number.isInteger(params.size)) {
  111. throw new Error('每页数量必须为正整数');
  112. }
  113. if (params.startDate) {
  114. const startDate = new Date(params.startDate)
  115. if (isNaN(startDate.getTime())) {
  116. throw new Error('开始时间格式错误');
  117. }
  118. params.startDate = startDate.toISOString()
  119. }
  120. if (params.endDate) {
  121. const endDate = new Date(params.endDate)
  122. if (isNaN(endDate.getTime())) {
  123. throw new Error('结束时间格式错误');
  124. }
  125. params.endDate = endDate.toISOString()
  126. }
  127. if (params.startDate && params.endDate) {
  128. if (params.startDate > params.endDate) {
  129. throw new Error('开始时间不能大于结束时间');
  130. }
  131. }
  132. }
  133. }
  134. interface PrintRecord {
  135. id: number
  136. /**
  137. * 作业ID
  138. */
  139. jobId: string
  140. /**
  141. * 打印机名称
  142. */
  143. printerName: string
  144. /**
  145. * 打印HTML
  146. */
  147. printHtml: string
  148. /**
  149. * 打印状态
  150. */
  151. printStatus: string
  152. /**
  153. * 打印失败原因
  154. */
  155. failureReason: string
  156. /**
  157. * 创建时间
  158. */
  159. createdAt: string
  160. }
  161. interface Page {
  162. total: number
  163. page: number
  164. size: number
  165. totalPages: number,
  166. data: Array<PrintRecord>
  167. }
  168. interface PageQuery {
  169. page: number
  170. size: number
  171. startDate: string,
  172. endDate: string
  173. }
  174. interface AddPrintRecord {
  175. /**
  176. * 打印机名称
  177. */
  178. printerName: string
  179. /**
  180. * 打印HTML
  181. */
  182. printHtml: string
  183. /**
  184. * 打印状态
  185. */
  186. printStatus: string
  187. /**
  188. * 打印失败原因
  189. */
  190. failureReason: string
  191. }
  192. PrintRecordService.toString = () => '[class PrintRecordService]'
  193. const printRecordService = new PrintRecordService()
  194. export {
  195. PrintRecordService,
  196. printRecordService,
  197. }
  198. export type {
  199. PrintRecord,
  200. Page,
  201. PageQuery,
  202. AddPrintRecord
  203. }