OcrChannelController.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339
  1. import { HttpContextContract } from '@ioc:Adonis/Core/HttpContext'
  2. import PaginationService from 'App/Services/PaginationService'
  3. import OcrChannel from 'App/Models/OcrChannel'
  4. import { schema } from '@ioc:Adonis/Core/Validator'
  5. import { DateTime } from 'luxon'
  6. import Database from '@ioc:Adonis/Lucid/Database'
  7. import User, { UserRoles } from 'App/Models/User'
  8. import UserService from 'App/Services/UserService'
  9. import * as console from 'node:console'
  10. export default class OcrChannelController {
  11. private paginationService = new PaginationService(OcrChannel)
  12. public async index({ request, response, auth }: HttpContextContract) {
  13. try {
  14. const { page = 1, size = 20, id, deviceId, channel } = request.qs()
  15. const user = auth.user
  16. const role = user?.$attributes?.role
  17. if (!role) {
  18. return response.forbidden({
  19. error: 'Forbidden',
  20. message: 'Unauthorized access'
  21. })
  22. }
  23. let userChannel: string | undefined
  24. if (role === UserRoles.Api) {
  25. userChannel = user!.username
  26. } else if (['admin', 'operator'].includes(role)) {
  27. const apiUsers = await UserService.findReferredUsers(user!.id)
  28. const allowedChannels = apiUsers.map((user) => user.username as string)
  29. // 如果请求中指定了channel,检查是否在允许的channel列表中
  30. if (channel) {
  31. if (!allowedChannels.includes(channel)) {
  32. return response.ok({
  33. data: [],
  34. meta: {
  35. total: 0,
  36. per_page: Number(size),
  37. current_page: Number(page),
  38. last_page: 0,
  39. first_page: 1,
  40. first_page_url: '/?page=1',
  41. last_page_url: '/?page=0',
  42. next_page_url: null,
  43. previous_page_url: null
  44. }
  45. })
  46. }
  47. userChannel = channel
  48. } else {
  49. userChannel = allowedChannels.join(',')
  50. }
  51. } else {
  52. return response.forbidden({
  53. error: 'Forbidden',
  54. message: 'You are not authorized to access this resource'
  55. })
  56. }
  57. // 构建查询条件
  58. const query = OcrChannel.query()
  59. if (id) {
  60. query.where('id', id)
  61. }
  62. if (deviceId) {
  63. query.whereIn('name', function (builder) {
  64. builder.select('channel').from('ocr_devices').where('id', deviceId)
  65. })
  66. }
  67. if (userChannel) {
  68. query.whereIn('name', userChannel.split(','))
  69. }
  70. // 执行分页查询
  71. const result = await query.orderBy('created_at', 'desc').paginate(page, size)
  72. return response.ok(result)
  73. } catch (error) {
  74. return response.internalServerError({
  75. message: '获取OCR渠道列表时发生错误',
  76. error: error.message
  77. })
  78. }
  79. }
  80. public async store({ request, bouncer }: HttpContextContract) {
  81. await request.validate({
  82. schema: schema.create({
  83. name: schema.string.optional(),
  84. deviceNum: schema.number(),
  85. recordNum: schema.number(),
  86. scanNum: schema.number()
  87. })
  88. })
  89. const ocrChannel = await OcrChannel.create(request.all())
  90. await this.updateChannelStats(ocrChannel)
  91. return ocrChannel
  92. }
  93. public async show({ params, bouncer }: HttpContextContract) {
  94. await bouncer.authorize('admin')
  95. return await OcrChannel.findOrFail(params.id)
  96. }
  97. public async update({ params, request, bouncer }: HttpContextContract) {
  98. await bouncer.authorize('admin')
  99. const ocrChannel = await OcrChannel.findOrFail(params.id)
  100. const data = await request.validate({
  101. schema: schema.create({
  102. name: schema.string.optional(),
  103. deviceNum: schema.number.optional(),
  104. recordNum: schema.number.optional(),
  105. scanNum: schema.number.optional()
  106. })
  107. })
  108. return await ocrChannel.merge(data).save()
  109. }
  110. public async findApiChannel({ auth, response }: HttpContextContract) {
  111. if (!auth.user) {
  112. return response.unauthorized({ message: 'unauthorized' })
  113. }
  114. return await OcrChannel.findBy('name', auth.user.username)
  115. }
  116. public async plusDeviceNum({ request, response }: HttpContextContract) {
  117. try {
  118. const ocrChannel = await OcrChannel.findBy('id', request.param('id'))
  119. if (!ocrChannel) {
  120. return response.notFound({ message: `未找到ID为 ${request.param('id')} 的OCR渠道` })
  121. }
  122. ocrChannel.deviceNum += 1
  123. await ocrChannel.save()
  124. return ocrChannel
  125. } catch (error) {
  126. return response.internalServerError({
  127. message: '更新设备数量时发生错误',
  128. error: error.message
  129. })
  130. }
  131. }
  132. public async plusRecordNum({ request, response }: HttpContextContract) {
  133. try {
  134. const ocrChannel = await OcrChannel.findBy('id', request.param('id'))
  135. if (!ocrChannel) {
  136. return response.notFound({ message: `未找到ID为 ${request.param('id')} 的OCR渠道` })
  137. }
  138. ocrChannel.recordNum += 1
  139. await ocrChannel.save()
  140. return ocrChannel
  141. } catch (error) {
  142. return response.internalServerError({
  143. message: '更新记录数量时发生错误',
  144. error: error.message
  145. })
  146. }
  147. }
  148. public async plusScanNum({ request, response }: HttpContextContract) {
  149. const scanCount = Number(request.param('scanCount'))
  150. if (isNaN(scanCount)) {
  151. return response.badRequest({ message: 'scanCount 参数必须是有效数字' })
  152. }
  153. try {
  154. const ocrChannel = await OcrChannel.findBy('id', request.param('id'))
  155. if (!ocrChannel) {
  156. return response.notFound({
  157. message: `未找到 ID 为 ${request.param('id')} 的 OCR 渠道`
  158. })
  159. }
  160. ocrChannel.scanNum = (Number(ocrChannel.scanNum) || 0) + scanCount
  161. await ocrChannel.save()
  162. return response.ok(ocrChannel)
  163. } catch (error) {
  164. return response.internalServerError({
  165. message: '更新扫描数量时发生错误',
  166. error: error.message
  167. })
  168. }
  169. }
  170. public async getStatistics({ request, response }: HttpContextContract) {
  171. try {
  172. const name = request.input('name')
  173. let query = Database.from('ocr_channels')
  174. if (name) {
  175. query = query.where('name', name)
  176. }
  177. const sevenDaysAgo = DateTime.now().minus({ days: 7 }).startOf('day').toSQL()
  178. const data = await query
  179. .where('created_at', '>=', sevenDaysAgo)
  180. .orderBy('created_at', 'asc')
  181. .select(
  182. 'created_at',
  183. 'device_num as deviceNum',
  184. 'record_num as recordNum',
  185. 'scan_num as scanNum'
  186. )
  187. const result = {
  188. dates: data.map((item) => DateTime.fromISO(item.created_at).toFormat('yyyy-MM-dd')),
  189. deviceNum: data.map((item) => item.deviceNum),
  190. recordNum: data.map((item) => item.recordNum),
  191. scanNum: data.map((item) => item.scanNum)
  192. }
  193. return response.ok(result)
  194. } catch (error) {
  195. return response.internalServerError({
  196. message: '获取统计数据时发生错误',
  197. error: error.message
  198. })
  199. }
  200. }
  201. public async getChannelNames({ auth, response }: HttpContextContract) {
  202. try {
  203. const user = auth.user
  204. const role = user?.$attributes?.role
  205. if (!role) {
  206. return response.forbidden({
  207. error: 'Forbidden',
  208. message: 'Unauthorized access'
  209. })
  210. }
  211. let channel: string = ''
  212. if (['admin', 'operator'].includes(role)) {
  213. const apiUsers = await UserService.findReferredUsers(user!.id)
  214. const allowedChannels = apiUsers.map((user) => user.username as string)
  215. channel = allowedChannels.join(',')
  216. } else {
  217. return response.forbidden({
  218. error: 'Forbidden',
  219. message: 'You are not authorized to access this resource'
  220. })
  221. }
  222. // 获取指定渠道名称
  223. const channels = await OcrChannel.query()
  224. .select('name')
  225. .whereIn('name', channel.split(','))
  226. .orderBy('name', 'asc')
  227. return response.ok({
  228. data: channels.map((channel) => channel.name)
  229. })
  230. } catch (error) {
  231. return response.internalServerError({
  232. message: '获取渠道名称列表时发生错误',
  233. error: error.message
  234. })
  235. }
  236. }
  237. private async updateChannelStats(channel: OcrChannel) {
  238. // 获取设备数量
  239. const deviceCountResult = await Database.from('ocr_devices')
  240. .where('channel', channel.name)
  241. .count('* as total')
  242. // 获取记录数量
  243. const recordCountResult = await Database.from('ocr_records')
  244. .where('channel', channel.name)
  245. .count('* as total')
  246. // 获取扫描数量总和
  247. const scanSumResult = await Database.from('ocr_devices')
  248. .where('channel', channel.name)
  249. .sum('scanned as total')
  250. // 更新渠道数据
  251. channel.deviceNum = parseInt(deviceCountResult[0].total || '0', 10)
  252. channel.recordNum = parseInt(recordCountResult[0].total || '0', 10)
  253. channel.scanNum = parseInt(scanSumResult[0].total || '0', 10)
  254. await channel.save()
  255. return {
  256. id: channel.id,
  257. name: channel.name,
  258. deviceNum: channel.deviceNum,
  259. recordNum: channel.recordNum,
  260. scanNum: channel.scanNum
  261. }
  262. }
  263. public async updateStatistics({ response }: HttpContextContract) {
  264. try {
  265. // 获取所有渠道
  266. const channels = await OcrChannel.all()
  267. const results = await Promise.all(
  268. channels.map((channel) => this.updateChannelStats(channel))
  269. )
  270. return response.ok({
  271. message: '所有渠道统计数据已更新',
  272. data: results
  273. })
  274. } catch (error) {
  275. return response.internalServerError({
  276. message: '更新所有渠道统计数据时发生错误',
  277. error: error.message
  278. })
  279. }
  280. }
  281. public async getChannelOcrLevel({ params, response }: HttpContextContract) {
  282. try {
  283. const { name } = params
  284. if (!name) {
  285. return response.ok({ level: 0 })
  286. }
  287. const ocrChannel = await OcrChannel.findBy('name', name)
  288. if (!ocrChannel) {
  289. return response.ok({ level: 0 })
  290. }
  291. return response.ok({ level: ocrChannel.ocrLevel })
  292. } catch (error) {
  293. return response.ok({ level: 0 })
  294. }
  295. }
  296. }