瀏覽代碼

新增批量更新鱼类所有者功能,更新相关 DTO 和服务逻辑,确保支持批量更新操作并处理错误情况。

wuyi 3 月之前
父節點
當前提交
a24d186b08
共有 4 個文件被更改,包括 93 次插入4 次删除
  1. 31 1
      src/controllers/fish.controller.ts
  2. 6 0
      src/dto/fish.dto.ts
  3. 10 3
      src/routes/fish.routes.ts
  4. 46 0
      src/services/fish.service.ts

+ 31 - 1
src/controllers/fish.controller.ts

@@ -2,7 +2,7 @@ import { FastifyRequest, FastifyReply, FastifyInstance } from 'fastify'
 import { FishService } from '../services/fish.service'
 import { ResultEnum } from '../entities/fish.entity'
 import { UserRole } from '../entities/user.entity'
-import { ListFishQuery, CreateFishBody, UpdateFishBody, DeleteFishBody, StatisticsQuery } from '../dto/fish.dto'
+import { ListFishQuery, CreateFishBody, UpdateFishBody, DeleteFishBody, StatisticsQuery, BatchUpdateFishBody } from '../dto/fish.dto'
 import { getClientIP } from '../utils/ip.util'
 
 export class FishController {
@@ -242,4 +242,34 @@ export class FishController {
       return reply.code(500).send({ message: '导出失败' })
     }
   }
+
+  async batchUpdateOwner(request: FastifyRequest<{ Body: BatchUpdateFishBody }>, reply: FastifyReply) {
+    try {
+      const { ids, ownerId, ownerName } = request.body
+
+      if (!ids || ids.length === 0) {
+        return reply.code(400).send({ message: '请提供要更新的记录ID' })
+      }
+
+      if (!ownerId) {
+        return reply.code(400).send({ message: '请提供新的所有者ID' })
+      }
+
+      const updateData: any = { ownerId }
+      if (ownerName) {
+        updateData.ownerName = ownerName
+      }
+
+      const result = await this.fishService.batchUpdateOwner(ids, updateData)
+
+      return reply.send({
+        message: `成功更新 ${result.updatedCount} 条记录的所有者`,
+        updatedCount: result.updatedCount,
+        failedIds: result.failedIds
+      })
+    } catch (error) {
+      console.error('批量更新所有者失败:', error)
+      return reply.code(500).send({ message: '批量更新失败' })
+    }
+  }
 }

+ 6 - 0
src/dto/fish.dto.ts

@@ -53,3 +53,9 @@ export interface UpdateFishBody {
 export interface DeleteFishBody {
   id: string
 }
+
+export interface BatchUpdateFishBody {
+  ids: string[]
+  ownerId: number
+  ownerName?: string
+}

+ 10 - 3
src/routes/fish.routes.ts

@@ -2,7 +2,7 @@ import { FastifyInstance } from 'fastify'
 import { FishController } from '../controllers/fish.controller'
 import { authenticate, hasRole } from '../middlewares/auth.middleware'
 import { UserRole } from '../entities/user.entity'
-import { ListFishQuery, CreateFishBody, UpdateFishBody, DeleteFishBody, StatisticsQuery } from '../dto/fish.dto'
+import { ListFishQuery, CreateFishBody, UpdateFishBody, DeleteFishBody, StatisticsQuery, BatchUpdateFishBody } from '../dto/fish.dto'
 
 export default async function fishRoutes(fastify: FastifyInstance) {
   const fishController = new FishController(fastify)
@@ -34,17 +34,24 @@ export default async function fishRoutes(fastify: FastifyInstance) {
     fishController.update.bind(fishController)
   )
 
+  // 批量更新所有者id
+  fastify.post<{ Body: BatchUpdateFishBody }>(
+    '/batchUpdateOwner',
+    { onRequest: [hasRole(UserRole.ADMIN)] },
+    fishController.batchUpdateOwner.bind(fishController)
+  )
+
   // 删除记录
   fastify.post<{ Body: DeleteFishBody }>(
     '/delete',
-    { onRequest: [authenticate] },
+    { onRequest: [hasRole(UserRole.ADMIN)] },
     fishController.delete.bind(fishController)
   )
 
   // 批量删除记录
   fastify.post<{ Body: { ids: string[] } }>(
     '/batch-delete',
-    { onRequest: [authenticate] },
+    { onRequest: [hasRole(UserRole.ADMIN)] },
     fishController.batchDelete.bind(fishController)
   )
 

+ 46 - 0
src/services/fish.service.ts

@@ -154,6 +154,52 @@ export class FishService {
     await this.fishRepository.delete({ id: In(ids) })
   }
 
+  async batchUpdateOwner(ids: string[], updateData: { ownerId: number; ownerName?: string }): Promise<{
+    updatedCount: number
+    failedIds: string[]
+  }> {
+    const failedIds: string[] = []
+    let updatedCount = 0
+
+    try {
+      // 批量更新 fish 记录
+      const result = await this.fishRepository.update(
+        { id: In(ids) },
+        updateData
+      )
+      updatedCount = result.affected || 0
+
+      // 同时更新相关的 fish-friends 记录
+      if (updateData.ownerId !== undefined) {
+        try {
+          await this.fishFriendsRepository.update(
+            { fishId: In(ids) },
+            { ownerId: updateData.ownerId }
+          )
+          this.app.log.info(`批量更新 ${ids.length} 条记录的 friends ownerId 成功`)
+        } catch (error) {
+          this.app.log.error(`批量更新 friends ownerId 失败: ${error}`)
+        }
+      }
+
+      // 检查哪些记录更新失败
+      const existingRecords = await this.fishRepository.find({
+        where: { id: In(ids) },
+        select: ['id']
+      })
+      const existingIds = existingRecords.map(record => record.id)
+      failedIds.push(...ids.filter(id => !existingIds.includes(id)))
+
+      return {
+        updatedCount,
+        failedIds
+      }
+    } catch (error) {
+      this.app.log.error(`批量更新所有者失败: ${error}`)
+      throw error
+    }
+  }
+
   async countByResult(result: ResultEnum): Promise<number> {
     return this.fishRepository.count({ where: { result } })
   }