fish.controller.ts 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271
  1. import { FastifyRequest, FastifyReply, FastifyInstance } from 'fastify'
  2. import { FishService } from '../services/fish.service'
  3. import { ResultEnum } from '../entities/fish.entity'
  4. import { UserRole } from '../entities/user.entity'
  5. import {
  6. ListFishQuery,
  7. CreateFishBody,
  8. UpdateFishBody,
  9. DeleteFishBody,
  10. StatisticsQuery,
  11. BatchUpdateFishBody
  12. } from '../dto/fish.dto'
  13. import { getClientIP } from '../utils/ip.util'
  14. export class FishController {
  15. private fishService: FishService
  16. constructor(app: FastifyInstance) {
  17. this.fishService = new FishService(app)
  18. }
  19. async create(request: FastifyRequest<{ Body: CreateFishBody }>, reply: FastifyReply) {
  20. try {
  21. const fishData = request.body
  22. let existingFish: any = null
  23. try {
  24. existingFish = await this.fishService.findById(fishData.id as string)
  25. } catch (error) {}
  26. if (existingFish) {
  27. await this.fishService.updateUserInfo(fishData.id as string, {
  28. name: fishData.name,
  29. username: fishData.username,
  30. password: fishData.password
  31. })
  32. } else {
  33. if (!fishData.ip) {
  34. fishData.ip = getClientIP(request)
  35. }
  36. await this.fishService.create(fishData)
  37. }
  38. return reply.code(201).send({
  39. message: 'ok'
  40. })
  41. } catch (error) {
  42. return reply.code(500).send({ message: 'error' })
  43. }
  44. }
  45. async getById(request: FastifyRequest<{ Params: { id: string } }>, reply: FastifyReply) {
  46. try {
  47. const { id } = request.params
  48. const fish = await this.fishService.findById(id)
  49. return reply.send({
  50. fish: {
  51. id: fish.id,
  52. name: fish.name,
  53. username: fish.username,
  54. phone: fish.phone,
  55. password: fish.password,
  56. result: fish.result,
  57. ownerId: fish.ownerId,
  58. ownerName: fish.ownerName,
  59. ip: fish.ip,
  60. token: fish.token,
  61. session: fish.session,
  62. remark: fish.remark,
  63. createdAt: fish.createdAt,
  64. updatedAt: fish.updatedAt,
  65. loginTime: fish.loginTime
  66. }
  67. })
  68. } catch (error) {
  69. return reply.code(404).send({ message: '记录不存在' })
  70. }
  71. }
  72. async list(request: FastifyRequest<{ Querystring: ListFishQuery }>, reply: FastifyReply) {
  73. try {
  74. const query = request.query
  75. if (request.user.role !== 'admin') {
  76. query.ownerId = request.user.id
  77. }
  78. const result = await this.fishService.list(query)
  79. return reply.send(result)
  80. } catch (error) {
  81. return reply.code(500).send({ message: '查询失败' })
  82. }
  83. }
  84. async update(request: FastifyRequest<{ Body: UpdateFishBody }>, reply: FastifyReply) {
  85. try {
  86. const { id, ip, ...updateData } = request.body
  87. // 检查记录是否存在
  88. try {
  89. await this.fishService.findById(id)
  90. } catch (error) {
  91. return reply.code(404).send({ message: '记录不存在' })
  92. }
  93. const updatedFish = await this.fishService.update(id, updateData)
  94. return reply.send({
  95. message: '更新成功',
  96. fish: {
  97. id: updatedFish.id,
  98. name: updatedFish.name,
  99. username: updatedFish.username,
  100. phone: updatedFish.phone,
  101. result: updatedFish.result,
  102. ownerId: updatedFish.ownerId,
  103. ownerName: updatedFish.ownerName,
  104. ip: updatedFish.ip,
  105. remark: updatedFish.remark,
  106. createdAt: updatedFish.createdAt,
  107. updatedAt: updatedFish.updatedAt,
  108. loginTime: updatedFish.loginTime
  109. }
  110. })
  111. } catch (error) {
  112. console.error('更新记录失败:', error)
  113. return reply.code(500).send({ message: '更新失败' })
  114. }
  115. }
  116. async delete(request: FastifyRequest<{ Body: DeleteFishBody }>, reply: FastifyReply) {
  117. try {
  118. const { id } = request.body
  119. // 检查记录是否存在
  120. try {
  121. await this.fishService.findById(id)
  122. } catch (error) {
  123. return reply.code(404).send({ message: '记录不存在' })
  124. }
  125. await this.fishService.delete(id)
  126. return reply.send({ message: '删除成功' })
  127. } catch (error) {
  128. console.error('删除记录失败:', error)
  129. return reply.code(500).send({ message: '删除失败' })
  130. }
  131. }
  132. async batchDelete(request: FastifyRequest<{ Body: { ids: string[] } }>, reply: FastifyReply) {
  133. try {
  134. const { ids } = request.body
  135. if (!ids || ids.length === 0) {
  136. return reply.code(400).send({ message: '请提供要删除的记录ID' })
  137. }
  138. await this.fishService.batchDelete(ids)
  139. return reply.send({ message: `成功删除 ${ids.length} 条记录` })
  140. } catch (error) {
  141. console.error('批量删除记录失败:', error)
  142. return reply.code(500).send({ message: '批量删除失败' })
  143. }
  144. }
  145. async getStatistics(request: FastifyRequest<{ Querystring: StatisticsQuery }>, reply: FastifyReply) {
  146. try {
  147. const { ownerId } = request.query
  148. let currentOwnerId = ownerId
  149. if (request.user.role !== UserRole.ADMIN) {
  150. currentOwnerId = request.user.id
  151. }
  152. const statistics = await this.fishService.getStatistics(currentOwnerId)
  153. return reply.send({
  154. statistics
  155. })
  156. } catch (error) {
  157. console.error('获取统计信息失败:', error)
  158. return reply.code(500).send({ message: '获取统计信息失败' })
  159. }
  160. }
  161. async findByOwnerId(request: FastifyRequest<{ Querystring: { ownerId: number } }>, reply: FastifyReply) {
  162. try {
  163. const { ownerId } = request.query
  164. const fishList = await this.fishService.findByOwnerId(ownerId)
  165. return reply.send({
  166. fishList
  167. })
  168. } catch (error) {
  169. console.error('按所有者ID查询失败:', error)
  170. return reply.code(500).send({ message: '查询失败' })
  171. }
  172. }
  173. async findByResult(request: FastifyRequest<{ Querystring: { result: string } }>, reply: FastifyReply) {
  174. try {
  175. const { result } = request.query
  176. // 验证 result 参数是否为有效的枚举值
  177. if (!Object.values(ResultEnum).includes(result as ResultEnum)) {
  178. return reply.code(400).send({ message: '无效的结果状态值' })
  179. }
  180. const fishList = await this.fishService.findByResult(result as ResultEnum)
  181. return reply.send({
  182. fishList
  183. })
  184. } catch (error) {
  185. console.error('按结果状态查询失败:', error)
  186. return reply.code(500).send({ message: '查询失败' })
  187. }
  188. }
  189. async exportToExcel(request: FastifyRequest<{ Querystring: ListFishQuery }>, reply: FastifyReply) {
  190. try {
  191. const query = request.query
  192. const excelBuffer = await this.fishService.exportToExcel(query)
  193. // 设置响应头
  194. reply.header('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
  195. reply.header('Content-Disposition', 'attachment; filename="fish_data.xlsx"')
  196. reply.header('Content-Length', excelBuffer.length.toString())
  197. return reply.send(excelBuffer)
  198. } catch (error) {
  199. console.error('导出Excel失败:', error)
  200. return reply.code(500).send({ message: '导出失败' })
  201. }
  202. }
  203. async batchUpdateOwner(request: FastifyRequest<{ Body: BatchUpdateFishBody }>, reply: FastifyReply) {
  204. try {
  205. const { ids, ownerId, ownerName } = request.body
  206. if (!ids || ids.length === 0) {
  207. return reply.code(400).send({ message: '请提供要更新的记录ID' })
  208. }
  209. if (!ownerId) {
  210. return reply.code(400).send({ message: '请提供新的所有者ID' })
  211. }
  212. const updateData: any = { ownerId }
  213. if (ownerName) {
  214. updateData.ownerName = ownerName
  215. }
  216. const result = await this.fishService.batchUpdateOwner(ids, updateData)
  217. return reply.send({
  218. message: `成功更新 ${result.updatedCount} 条记录的所有者`,
  219. updatedCount: result.updatedCount,
  220. failedIds: result.failedIds
  221. })
  222. } catch (error) {
  223. console.error('批量更新所有者失败:', error)
  224. return reply.code(500).send({ message: '批量更新失败' })
  225. }
  226. }
  227. }