From ecd2d37c7087b82a0d3e888e98a0fef141a0f296 Mon Sep 17 00:00:00 2001 From: huang <1724659546@qq.com> Date: Mon, 10 Nov 2025 22:23:31 +0800 Subject: [PATCH] =?UTF-8?q?uint/uint64=E5=85=A8=E9=83=A8=E6=94=B9=E4=B8=BA?= =?UTF-8?q?uint32?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- design/exceeding-threshold-alarm/index.md | 3 +- docs/docs.go | 16 +- docs/swagger.json | 16 +- docs/swagger.yaml | 8 +- .../alarm/threshold_alarm_controller.go | 4 +- internal/app/controller/auth_utils.go | 2 +- .../controller/device/device_controller.go | 20 +-- .../management/controller_helpers.go | 22 +-- .../management/pig_batch_controller.go | 28 +-- .../management/pig_batch_health_controller.go | 12 +- .../management/pig_batch_trade_controller.go | 4 +- .../pig_batch_transfer_controller.go | 8 +- .../management/pig_farm_controller.go | 14 +- .../app/controller/plan/plan_controller.go | 20 +-- .../app/controller/user/user_controller.go | 4 +- internal/app/dto/alarm_dto.go | 24 +-- internal/app/dto/device_dto.go | 18 +- internal/app/dto/monitor_converter.go | 6 +- internal/app/dto/monitor_dto.go | 164 +++++++++--------- internal/app/dto/notification_dto.go | 6 +- internal/app/dto/pig_batch_dto.go | 42 ++--- internal/app/dto/pig_farm_dto.go | 12 +- internal/app/dto/plan_dto.go | 22 +-- internal/app/dto/user_dto.go | 6 +- internal/app/service/device_service.go | 40 ++--- internal/app/service/monitor_service.go | 2 +- internal/app/service/pig_batch_service.go | 72 ++++---- internal/app/service/pig_farm_service.go | 36 ++-- internal/app/service/plan_service.go | 20 +-- .../app/service/threshold_alarm_service.go | 22 +-- internal/app/service/user_service.go | 4 +- internal/app/webhook/chirp_stack.go | 2 +- internal/core/data_initializer.go | 2 +- internal/domain/alarm/alarm_service.go | 12 +- internal/domain/device/device_service.go | 2 +- .../domain/device/general_device_service.go | 4 +- internal/domain/notify/notify.go | 18 +- internal/domain/pig/pen_transfer_manager.go | 24 +-- internal/domain/pig/pig_batch_service.go | 42 ++--- .../domain/pig/pig_batch_service_method.go | 14 +- .../pig/pig_batch_service_pen_transfer.go | 19 +- .../domain/pig/pig_batch_service_pig_sick.go | 12 +- .../domain/pig/pig_batch_service_pig_trade.go | 4 +- internal/domain/pig/pig_sick_manager.go | 4 +- .../domain/plan/analysis_plan_task_manager.go | 22 +-- .../domain/plan/plan_execution_manager.go | 24 +-- internal/domain/plan/plan_service.go | 20 +-- internal/domain/plan/task.go | 4 +- .../domain/task/alarm_notification_task.go | 6 +- .../domain/task/area_threshold_check_task.go | 10 +- internal/domain/task/delay_task.go | 4 +- .../task/device_threshold_check_task.go | 6 +- internal/domain/task/full_collection_task.go | 6 +- .../domain/task/release_feed_weight_task.go | 10 +- internal/infra/config/config.go | 14 +- internal/infra/models/alarm.go | 18 +- internal/infra/models/device.go | 11 +- internal/infra/models/device_template.go | 3 +- internal/infra/models/execution.go | 16 +- internal/infra/models/farm_asset.go | 12 +- internal/infra/models/feed.go | 30 ++-- internal/infra/models/medication.go | 11 +- internal/infra/models/models.go | 20 ++- internal/infra/models/notify.go | 6 +- internal/infra/models/pig_batch.go | 22 ++- internal/infra/models/pig_sick.go | 10 +- internal/infra/models/pig_trade.go | 14 +- internal/infra/models/pig_transfer.go | 10 +- internal/infra/models/plan.go | 24 +-- internal/infra/models/schedule.go | 6 +- internal/infra/models/sensor_data.go | 4 +- internal/infra/models/user.go | 4 +- internal/infra/repository/alarm_repository.go | 36 ++-- .../repository/area_controller_repository.go | 12 +- .../device_command_log_repository.go | 2 +- .../infra/repository/device_repository.go | 35 ++-- .../repository/device_template_repository.go | 12 +- .../repository/execution_log_repository.go | 48 ++--- .../repository/medication_log_repository.go | 6 +- .../repository/notification_repository.go | 2 +- .../pending_collection_repository.go | 2 +- .../repository/pending_task_repository.go | 24 +-- .../repository/pig_batch_log_repository.go | 12 +- .../infra/repository/pig_batch_repository.go | 24 +-- .../infra/repository/pig_farm_repository.go | 12 +- .../infra/repository/pig_pen_repository.go | 20 +-- .../infra/repository/pig_sick_repository.go | 10 +- .../infra/repository/pig_trade_repository.go | 8 +- .../repository/pig_transfer_log_repository.go | 10 +- internal/infra/repository/plan_repository.go | 70 ++++---- .../repository/raw_material_repository.go | 12 +- .../repository/sensor_data_repository.go | 6 +- .../repository/user_action_log_repository.go | 2 +- internal/infra/repository/user_repository.go | 4 +- .../lora_mesh_uart_passthrough_transport.go | 2 +- internal/infra/utils/token/token_service.go | 6 +- 96 files changed, 775 insertions(+), 785 deletions(-) diff --git a/design/exceeding-threshold-alarm/index.md b/design/exceeding-threshold-alarm/index.md index 3bd49d3..d93188d 100644 --- a/design/exceeding-threshold-alarm/index.md +++ b/design/exceeding-threshold-alarm/index.md @@ -145,4 +145,5 @@ 13. 实现根据区域ID或设备ID清空对应阈值告警任务 14. 设备和区域主控删除时清除对应区域阈值告警或设备阈值告警任务 15. 将所有Regional更改为Area -16. float64全部改float32 \ No newline at end of file +16. float64全部改float32 +17. uint/uint64全部改为uint32 \ No newline at end of file diff --git a/docs/docs.go b/docs/docs.go index 61485a4..8884ef9 100644 --- a/docs/docs.go +++ b/docs/docs.go @@ -1665,7 +1665,6 @@ const docTemplate = `{ }, { "enum": [ - 7, -1, 0, 1, @@ -1675,12 +1674,12 @@ const docTemplate = `{ 5, -1, 5, - 6 + 6, + 7 ], "type": "integer", "format": "int32", "x-enum-varnames": [ - "_numLevels", "DebugLevel", "InfoLevel", "WarnLevel", @@ -1690,7 +1689,8 @@ const docTemplate = `{ "FatalLevel", "_minLevel", "_maxLevel", - "InvalidLevel" + "InvalidLevel", + "_numLevels" ], "name": "level", "in": "query" @@ -7981,7 +7981,6 @@ const docTemplate = `{ "type": "integer", "format": "int32", "enum": [ - 7, -1, 0, 1, @@ -7991,10 +7990,10 @@ const docTemplate = `{ 5, -1, 5, - 6 + 6, + 7 ], "x-enum-varnames": [ - "_numLevels", "DebugLevel", "InfoLevel", "WarnLevel", @@ -8004,7 +8003,8 @@ const docTemplate = `{ "FatalLevel", "_minLevel", "_maxLevel", - "InvalidLevel" + "InvalidLevel", + "_numLevels" ] } }, diff --git a/docs/swagger.json b/docs/swagger.json index dfa71b7..aadfac4 100644 --- a/docs/swagger.json +++ b/docs/swagger.json @@ -1657,7 +1657,6 @@ }, { "enum": [ - 7, -1, 0, 1, @@ -1667,12 +1666,12 @@ 5, -1, 5, - 6 + 6, + 7 ], "type": "integer", "format": "int32", "x-enum-varnames": [ - "_numLevels", "DebugLevel", "InfoLevel", "WarnLevel", @@ -1682,7 +1681,8 @@ "FatalLevel", "_minLevel", "_maxLevel", - "InvalidLevel" + "InvalidLevel", + "_numLevels" ], "name": "level", "in": "query" @@ -7973,7 +7973,6 @@ "type": "integer", "format": "int32", "enum": [ - 7, -1, 0, 1, @@ -7983,10 +7982,10 @@ 5, -1, 5, - 6 + 6, + 7 ], "x-enum-varnames": [ - "_numLevels", "DebugLevel", "InfoLevel", "WarnLevel", @@ -7996,7 +7995,8 @@ "FatalLevel", "_minLevel", "_maxLevel", - "InvalidLevel" + "InvalidLevel", + "_numLevels" ] } }, diff --git a/docs/swagger.yaml b/docs/swagger.yaml index 0230576..10e5f77 100644 --- a/docs/swagger.yaml +++ b/docs/swagger.yaml @@ -2230,7 +2230,6 @@ definitions: - PlanTypeFilterSystem zapcore.Level: enum: - - 7 - -1 - 0 - 1 @@ -2241,10 +2240,10 @@ definitions: - -1 - 5 - 6 + - 7 format: int32 type: integer x-enum-varnames: - - _numLevels - DebugLevel - InfoLevel - WarnLevel @@ -2255,6 +2254,7 @@ definitions: - _minLevel - _maxLevel - InvalidLevel + - _numLevels info: contact: email: divano@example.com @@ -3248,7 +3248,6 @@ paths: name: end_time type: string - enum: - - 7 - -1 - 0 - 1 @@ -3259,12 +3258,12 @@ paths: - -1 - 5 - 6 + - 7 format: int32 in: query name: level type: integer x-enum-varnames: - - _numLevels - DebugLevel - InfoLevel - WarnLevel @@ -3275,6 +3274,7 @@ paths: - _minLevel - _maxLevel - InvalidLevel + - _numLevels - enum: - 邮件 - 企业微信 diff --git a/internal/app/controller/alarm/threshold_alarm_controller.go b/internal/app/controller/alarm/threshold_alarm_controller.go index fed4768..6e69afd 100644 --- a/internal/app/controller/alarm/threshold_alarm_controller.go +++ b/internal/app/controller/alarm/threshold_alarm_controller.go @@ -61,7 +61,7 @@ func (t *ThresholdAlarmController) SnoozeThresholdAlarm(ctx echo.Context) error return controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, "无效的请求体: "+err.Error(), actionType, "请求体绑定失败", req) } - if err := t.thresholdAlarmService.SnoozeThresholdAlarm(reqCtx, uint(alarmID), req.DurationMinutes); err != nil { + if err := t.thresholdAlarmService.SnoozeThresholdAlarm(reqCtx, uint32(alarmID), req.DurationMinutes); err != nil { if errors.Is(err, gorm.ErrRecordNotFound) { logger.Warnf("%s: 告警不存在, ID: %d", actionType, alarmID) return controller.SendErrorWithAudit(ctx, controller.CodeNotFound, "告警未找到", actionType, "告警不存在", alarmID) @@ -96,7 +96,7 @@ func (t *ThresholdAlarmController) CancelSnoozeThresholdAlarm(ctx echo.Context) return controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, "无效的告警ID: "+alarmIDStr, actionType, "无效的告警ID", alarmIDStr) } - if err := t.thresholdAlarmService.CancelSnoozeThresholdAlarm(reqCtx, uint(alarmID)); err != nil { + if err := t.thresholdAlarmService.CancelSnoozeThresholdAlarm(reqCtx, uint32(alarmID)); err != nil { if errors.Is(err, gorm.ErrRecordNotFound) { logger.Warnf("%s: 告警不存在, ID: %d", actionType, alarmID) return controller.SendErrorWithAudit(ctx, controller.CodeNotFound, "告警未找到", actionType, "告警不存在", alarmID) diff --git a/internal/app/controller/auth_utils.go b/internal/app/controller/auth_utils.go index 25d28b8..2b0fe81 100644 --- a/internal/app/controller/auth_utils.go +++ b/internal/app/controller/auth_utils.go @@ -17,7 +17,7 @@ var ( // GetOperatorIDFromContext 从 echo.Context 中提取操作者ID。 // 假设操作者ID是由 AuthMiddleware 存储到 context 中的 *models.User 对象的 ID 字段。 -func GetOperatorIDFromContext(c echo.Context) (uint, error) { +func GetOperatorIDFromContext(c echo.Context) (uint32, error) { userVal := c.Get(models.ContextUserKey.String()) if userVal == nil { return 0, ErrUserNotFoundInContext diff --git a/internal/app/controller/device/device_controller.go b/internal/app/controller/device/device_controller.go index 451b22b..448fecc 100644 --- a/internal/app/controller/device/device_controller.go +++ b/internal/app/controller/device/device_controller.go @@ -84,7 +84,7 @@ func (c *Controller) GetDevice(ctx echo.Context) error { return controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, "无效的ID: "+deviceID, actionType, "无效的ID", deviceID) } - resp, err := c.deviceService.GetDevice(reqCtx, uint(id)) + resp, err := c.deviceService.GetDevice(reqCtx, uint32(id)) if err != nil { if errors.Is(err, gorm.ErrRecordNotFound) { logger.Warnf("%s: 设备不存在, ID: %s", actionType, deviceID) @@ -149,7 +149,7 @@ func (c *Controller) UpdateDevice(ctx echo.Context) error { return controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, "无效的ID: "+deviceID, actionType, "无效的ID", deviceID) } - resp, err := c.deviceService.UpdateDevice(reqCtx, uint(id), &req) + resp, err := c.deviceService.UpdateDevice(reqCtx, uint32(id), &req) if err != nil { if errors.Is(err, gorm.ErrRecordNotFound) { logger.Warnf("%s: 设备不存在, ID: %s", actionType, deviceID) @@ -184,7 +184,7 @@ func (c *Controller) DeleteDevice(ctx echo.Context) error { return controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, "无效的ID: "+deviceID, actionType, "无效的ID", deviceID) } - if err := c.deviceService.DeleteDevice(reqCtx, uint(id)); err != nil { + if err := c.deviceService.DeleteDevice(reqCtx, uint32(id)); err != nil { switch { case errors.Is(err, gorm.ErrRecordNotFound): logger.Warnf("%s: 设备不存在, ID: %s", actionType, deviceID) @@ -232,7 +232,7 @@ func (c *Controller) ManualControl(ctx echo.Context) error { return controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, "无效的ID: "+deviceID, actionType, "无效的ID", deviceID) } - if err := c.deviceService.ManualControl(reqCtx, uint(id), &req); err != nil { + if err := c.deviceService.ManualControl(reqCtx, uint32(id), &req); err != nil { if errors.Is(err, gorm.ErrRecordNotFound) { logger.Warnf("%s: 设备不存在, ID: %s", actionType, deviceID) return controller.SendErrorWithAudit(ctx, controller.CodeNotFound, "设备未找到", actionType, "设备不存在", deviceID) @@ -297,7 +297,7 @@ func (c *Controller) GetAreaController(ctx echo.Context) error { return controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, "无效的ID: "+acID, actionType, "无效的ID", acID) } - resp, err := c.deviceService.GetAreaController(reqCtx, uint(id)) + resp, err := c.deviceService.GetAreaController(reqCtx, uint32(id)) if err != nil { if errors.Is(err, gorm.ErrRecordNotFound) { logger.Warnf("%s: 区域主控不存在, ID: %s", actionType, acID) @@ -361,7 +361,7 @@ func (c *Controller) UpdateAreaController(ctx echo.Context) error { return controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, "无效的ID: "+acID, actionType, "无效的ID", acID) } - resp, err := c.deviceService.UpdateAreaController(reqCtx, uint(id), &req) + resp, err := c.deviceService.UpdateAreaController(reqCtx, uint32(id), &req) if err != nil { if errors.Is(err, gorm.ErrRecordNotFound) { logger.Warnf("%s: 区域主控不存在, ID: %s", actionType, acID) @@ -396,7 +396,7 @@ func (c *Controller) DeleteAreaController(ctx echo.Context) error { return controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, "无效的ID: "+acID, actionType, "无效的ID", acID) } - if err := c.deviceService.DeleteAreaController(reqCtx, uint(id)); err != nil { + if err := c.deviceService.DeleteAreaController(reqCtx, uint32(id)); err != nil { switch { case errors.Is(err, gorm.ErrRecordNotFound): logger.Warnf("%s: 区域主控不存在, ID: %s", actionType, acID) @@ -467,7 +467,7 @@ func (c *Controller) GetDeviceTemplate(ctx echo.Context) error { return controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, "无效的ID: "+dtID, actionType, "无效的ID", dtID) } - resp, err := c.deviceService.GetDeviceTemplate(reqCtx, uint(id)) + resp, err := c.deviceService.GetDeviceTemplate(reqCtx, uint32(id)) if err != nil { if errors.Is(err, gorm.ErrRecordNotFound) { logger.Warnf("%s: 设备模板不存在, ID: %s", actionType, dtID) @@ -532,7 +532,7 @@ func (c *Controller) UpdateDeviceTemplate(ctx echo.Context) error { return controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, "无效的ID: "+dtID, actionType, "无效的ID", dtID) } - resp, err := c.deviceService.UpdateDeviceTemplate(reqCtx, uint(id), &req) + resp, err := c.deviceService.UpdateDeviceTemplate(reqCtx, uint32(id), &req) if err != nil { if errors.Is(err, gorm.ErrRecordNotFound) { logger.Warnf("%s: 设备模板不存在, ID: %s", actionType, dtID) @@ -567,7 +567,7 @@ func (c *Controller) DeleteDeviceTemplate(ctx echo.Context) error { return controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, "无效的ID: "+dtID, actionType, "无效的ID", dtID) } - if err := c.deviceService.DeleteDeviceTemplate(reqCtx, uint(id)); err != nil { + if err := c.deviceService.DeleteDeviceTemplate(reqCtx, uint32(id)); err != nil { switch { case errors.Is(err, gorm.ErrRecordNotFound): logger.Warnf("%s: 设备模板不存在, ID: %s", actionType, dtID) diff --git a/internal/app/controller/management/controller_helpers.go b/internal/app/controller/management/controller_helpers.go index 8e68435..08345ee 100644 --- a/internal/app/controller/management/controller_helpers.go +++ b/internal/app/controller/management/controller_helpers.go @@ -15,7 +15,7 @@ import ( // mapAndSendError 统一映射服务层错误并发送响应。 // 这个函数将服务层返回的错误转换为控制器层应返回的HTTP状态码和审计信息。 -func mapAndSendError(reqContext context.Context, c *PigBatchController, ctx echo.Context, action string, err error, id uint) error { +func mapAndSendError(reqContext context.Context, c *PigBatchController, ctx echo.Context, action string, err error, id uint32) error { if errors.Is(err, service.ErrPigBatchNotFound) || errors.Is(err, service.ErrPenNotFound) || errors.Is(err, service.ErrPenNotAssociatedWithBatch) { @@ -34,7 +34,7 @@ func mapAndSendError(reqContext context.Context, c *PigBatchController, ctx echo } // idExtractorFunc 定义了一个函数类型,用于从echo.Context中提取主ID。 -type idExtractorFunc func(ctx echo.Context) (uint, error) +type idExtractorFunc func(ctx echo.Context) (uint32, error) // extractOperatorAndPrimaryID 封装了从echo.Context中提取操作员ID和主ID的通用逻辑。 // 它负责处理ID提取过程中的错误,并发送相应的HTTP响应。 @@ -48,15 +48,15 @@ type idExtractorFunc func(ctx echo.Context) (uint, error) // // 返回值: // -// operatorID: uint - 提取到的操作员ID。 -// primaryID: uint - 提取到的主ID。 +// operatorID: uint32 - 提取到的操作员ID。 +// primaryID: uint32 - 提取到的主ID。 // err: error - 如果ID提取失败或发送错误响应,则返回错误。 func extractOperatorAndPrimaryID( c *PigBatchController, ctx echo.Context, action string, idExtractor idExtractorFunc, -) (operatorID uint, primaryID uint, err error) { +) (operatorID uint32, primaryID uint32, err error) { // 1. 获取操作员ID operatorID, err = controller.GetOperatorIDFromContext(ctx) if err != nil { @@ -78,7 +78,7 @@ func extractOperatorAndPrimaryID( if err != nil { return 0, 0, controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, "无效的ID格式", action, "ID格式错误", idParam) } - primaryID = uint(parsedID) + primaryID = uint32(parsedID) } } @@ -93,7 +93,7 @@ func handleAPIRequest[Req any]( ctx echo.Context, action string, reqDTO Req, - serviceExecutor func(ctx echo.Context, operatorID uint, primaryID uint, req Req) error, + serviceExecutor func(ctx echo.Context, operatorID uint32, primaryID uint32, req Req) error, successMsg string, idExtractor idExtractorFunc, ) error { @@ -124,7 +124,7 @@ func handleNoBodyAPIRequest( c *PigBatchController, ctx echo.Context, action string, - serviceExecutor func(ctx echo.Context, operatorID uint, primaryID uint) error, + serviceExecutor func(ctx echo.Context, operatorID uint32, primaryID uint32) error, successMsg string, idExtractor idExtractorFunc, ) error { @@ -151,7 +151,7 @@ func handleAPIRequestWithResponse[Req any, Resp any]( ctx echo.Context, action string, reqDTO Req, - serviceExecutor func(ctx echo.Context, operatorID uint, primaryID uint, req Req) (Resp, error), // serviceExecutor现在返回Resp + serviceExecutor func(ctx echo.Context, operatorID uint32, primaryID uint32, req Req) (Resp, error), // serviceExecutor现在返回Resp successMsg string, idExtractor idExtractorFunc, ) error { @@ -182,7 +182,7 @@ func handleNoBodyAPIRequestWithResponse[Resp any]( c *PigBatchController, ctx echo.Context, action string, - serviceExecutor func(ctx echo.Context, operatorID uint, primaryID uint) (Resp, error), // serviceExecutor现在返回Resp + serviceExecutor func(ctx echo.Context, operatorID uint32, primaryID uint32) (Resp, error), // serviceExecutor现在返回Resp successMsg string, idExtractor idExtractorFunc, ) error { @@ -209,7 +209,7 @@ func handleQueryAPIRequestWithResponse[Query any, Resp any]( ctx echo.Context, action string, queryDTO Query, - serviceExecutor func(ctx echo.Context, operatorID uint, query Query) (Resp, error), // serviceExecutor现在接收queryDTO + serviceExecutor func(ctx echo.Context, operatorID uint32, query Query) (Resp, error), // serviceExecutor现在接收queryDTO successMsg string, ) error { // 1. 绑定查询参数 diff --git a/internal/app/controller/management/pig_batch_controller.go b/internal/app/controller/management/pig_batch_controller.go index 6a82809..a0dd7e9 100644 --- a/internal/app/controller/management/pig_batch_controller.go +++ b/internal/app/controller/management/pig_batch_controller.go @@ -43,7 +43,7 @@ func (c *PigBatchController) CreatePigBatch(ctx echo.Context) error { return handleAPIRequestWithResponse( reqCtx, c, ctx, action, &req, - func(ctx echo.Context, operatorID uint, primaryID uint, req *dto.PigBatchCreateDTO) (*dto.PigBatchResponseDTO, error) { + func(ctx echo.Context, operatorID uint32, primaryID uint32, req *dto.PigBatchCreateDTO) (*dto.PigBatchResponseDTO, error) { // 对于创建操作,primaryID通常不从路径中获取,而是由服务层生成 return c.service.CreatePigBatch(reqCtx, operatorID, req) }, @@ -68,7 +68,7 @@ func (c *PigBatchController) GetPigBatch(ctx echo.Context) error { return handleNoBodyAPIRequestWithResponse( reqCtx, c, ctx, action, - func(ctx echo.Context, operatorID uint, primaryID uint) (*dto.PigBatchResponseDTO, error) { + func(ctx echo.Context, operatorID uint32, primaryID uint32) (*dto.PigBatchResponseDTO, error) { return c.service.GetPigBatch(reqCtx, primaryID) }, "获取成功", @@ -95,7 +95,7 @@ func (c *PigBatchController) UpdatePigBatch(ctx echo.Context) error { return handleAPIRequestWithResponse( reqCtx, c, ctx, action, &req, - func(ctx echo.Context, operatorID uint, primaryID uint, req *dto.PigBatchUpdateDTO) (*dto.PigBatchResponseDTO, error) { + func(ctx echo.Context, operatorID uint32, primaryID uint32, req *dto.PigBatchUpdateDTO) (*dto.PigBatchResponseDTO, error) { return c.service.UpdatePigBatch(reqCtx, primaryID, req) }, "更新成功", @@ -119,7 +119,7 @@ func (c *PigBatchController) DeletePigBatch(ctx echo.Context) error { return handleNoBodyAPIRequest( reqCtx, c, ctx, action, - func(ctx echo.Context, operatorID uint, primaryID uint) error { + func(ctx echo.Context, operatorID uint32, primaryID uint32) error { return c.service.DeletePigBatch(reqCtx, primaryID) }, "删除成功", @@ -144,7 +144,7 @@ func (c *PigBatchController) ListPigBatches(ctx echo.Context) error { return handleQueryAPIRequestWithResponse( reqCtx, c, ctx, action, &query, - func(ctx echo.Context, operatorID uint, query *dto.PigBatchQueryDTO) ([]*dto.PigBatchResponseDTO, error) { + func(ctx echo.Context, operatorID uint32, query *dto.PigBatchQueryDTO) ([]*dto.PigBatchResponseDTO, error) { return c.service.ListPigBatches(reqCtx, query.IsActive) }, "获取成功", @@ -170,7 +170,7 @@ func (c *PigBatchController) AssignEmptyPensToBatch(ctx echo.Context) error { return handleAPIRequest( reqCtx, c, ctx, action, &req, - func(ctx echo.Context, operatorID uint, primaryID uint, req *dto.AssignEmptyPensToBatchRequest) error { + func(ctx echo.Context, operatorID uint32, primaryID uint32, req *dto.AssignEmptyPensToBatchRequest) error { return c.service.AssignEmptyPensToBatch(reqCtx, primaryID, req.PenIDs, operatorID) }, "分配成功", @@ -197,18 +197,18 @@ func (c *PigBatchController) ReclassifyPenToNewBatch(ctx echo.Context) error { return handleAPIRequest( reqCtx, c, ctx, action, &req, - func(ctx echo.Context, operatorID uint, primaryID uint, req *dto.ReclassifyPenToNewBatchRequest) error { + func(ctx echo.Context, operatorID uint32, primaryID uint32, req *dto.ReclassifyPenToNewBatchRequest) error { // primaryID 在这里是 fromBatchID return c.service.ReclassifyPenToNewBatch(reqCtx, primaryID, req.ToBatchID, req.PenID, operatorID, req.Remarks) }, "划拨成功", - func(ctx echo.Context) (uint, error) { // 自定义ID提取器,从 ":fromBatchID" 路径参数提取 + func(ctx echo.Context) (uint32, error) { // 自定义ID提取器,从 ":fromBatchID" 路径参数提取 idParam := ctx.Param("fromBatchID") parsedID, err := strconv.ParseUint(idParam, 10, 32) if err != nil { return 0, err } - return uint(parsedID), nil + return uint32(parsedID), nil }, ) } @@ -230,23 +230,23 @@ func (c *PigBatchController) RemoveEmptyPenFromBatch(ctx echo.Context) error { return handleNoBodyAPIRequest( reqCtx, c, ctx, action, - func(ctx echo.Context, operatorID uint, primaryID uint) error { + func(ctx echo.Context, operatorID uint32, primaryID uint32) error { // primaryID 在这里是 batchID penIDParam := ctx.Param("penID") parsedPenID, err := strconv.ParseUint(penIDParam, 10, 32) if err != nil { return err // 返回错误,因为 penID 格式无效 } - return c.service.RemoveEmptyPenFromBatch(reqCtx, primaryID, uint(parsedPenID)) + return c.service.RemoveEmptyPenFromBatch(reqCtx, primaryID, uint32(parsedPenID)) }, "移除成功", - func(ctx echo.Context) (uint, error) { // 自定义ID提取器,从 ":batchID" 路径参数提取 + func(ctx echo.Context) (uint32, error) { // 自定义ID提取器,从 ":batchID" 路径参数提取 idParam := ctx.Param("batchID") parsedID, err := strconv.ParseUint(idParam, 10, 32) if err != nil { return 0, err } - return uint(parsedID), nil + return uint32(parsedID), nil }, ) } @@ -270,7 +270,7 @@ func (c *PigBatchController) MovePigsIntoPen(ctx echo.Context) error { return handleAPIRequest( reqCtx, c, ctx, action, &req, - func(ctx echo.Context, operatorID uint, primaryID uint, req *dto.MovePigsIntoPenRequest) error { + func(ctx echo.Context, operatorID uint32, primaryID uint32, req *dto.MovePigsIntoPenRequest) error { return c.service.MovePigsIntoPen(reqCtx, primaryID, req.ToPenID, req.Quantity, operatorID, req.Remarks) }, "移入成功", diff --git a/internal/app/controller/management/pig_batch_health_controller.go b/internal/app/controller/management/pig_batch_health_controller.go index cd82e8b..905af89 100644 --- a/internal/app/controller/management/pig_batch_health_controller.go +++ b/internal/app/controller/management/pig_batch_health_controller.go @@ -26,7 +26,7 @@ func (c *PigBatchController) RecordSickPigs(ctx echo.Context) error { return handleAPIRequest( reqCtx, c, ctx, action, &req, - func(ctx echo.Context, operatorID uint, primaryID uint, req *dto.RecordSickPigsRequest) error { + func(ctx echo.Context, operatorID uint32, primaryID uint32, req *dto.RecordSickPigsRequest) error { return c.service.RecordSickPigs(reqCtx, operatorID, primaryID, req.PenID, req.Quantity, req.TreatmentLocation, req.HappenedAt, req.Remarks) }, "记录成功", @@ -53,7 +53,7 @@ func (c *PigBatchController) RecordSickPigRecovery(ctx echo.Context) error { return handleAPIRequest( reqCtx, c, ctx, action, &req, - func(ctx echo.Context, operatorID uint, primaryID uint, req *dto.RecordSickPigRecoveryRequest) error { + func(ctx echo.Context, operatorID uint32, primaryID uint32, req *dto.RecordSickPigRecoveryRequest) error { return c.service.RecordSickPigRecovery(reqCtx, operatorID, primaryID, req.PenID, req.Quantity, req.TreatmentLocation, req.HappenedAt, req.Remarks) }, "记录成功", @@ -80,7 +80,7 @@ func (c *PigBatchController) RecordSickPigDeath(ctx echo.Context) error { return handleAPIRequest( reqCtx, c, ctx, action, &req, - func(ctx echo.Context, operatorID uint, primaryID uint, req *dto.RecordSickPigDeathRequest) error { + func(ctx echo.Context, operatorID uint32, primaryID uint32, req *dto.RecordSickPigDeathRequest) error { return c.service.RecordSickPigDeath(reqCtx, operatorID, primaryID, req.PenID, req.Quantity, req.TreatmentLocation, req.HappenedAt, req.Remarks) }, "记录成功", @@ -107,7 +107,7 @@ func (c *PigBatchController) RecordSickPigCull(ctx echo.Context) error { return handleAPIRequest( reqCtx, c, ctx, action, &req, - func(ctx echo.Context, operatorID uint, primaryID uint, req *dto.RecordSickPigCullRequest) error { + func(ctx echo.Context, operatorID uint32, primaryID uint32, req *dto.RecordSickPigCullRequest) error { return c.service.RecordSickPigCull(reqCtx, operatorID, primaryID, req.PenID, req.Quantity, req.TreatmentLocation, req.HappenedAt, req.Remarks) }, "记录成功", @@ -134,7 +134,7 @@ func (c *PigBatchController) RecordDeath(ctx echo.Context) error { return handleAPIRequest( reqCtx, c, ctx, action, &req, - func(ctx echo.Context, operatorID uint, primaryID uint, req *dto.RecordDeathRequest) error { + func(ctx echo.Context, operatorID uint32, primaryID uint32, req *dto.RecordDeathRequest) error { return c.service.RecordDeath(reqCtx, operatorID, primaryID, req.PenID, req.Quantity, req.HappenedAt, req.Remarks) }, "记录成功", @@ -161,7 +161,7 @@ func (c *PigBatchController) RecordCull(ctx echo.Context) error { return handleAPIRequest( reqCtx, c, ctx, action, &req, - func(ctx echo.Context, operatorID uint, primaryID uint, req *dto.RecordCullRequest) error { + func(ctx echo.Context, operatorID uint32, primaryID uint32, req *dto.RecordCullRequest) error { return c.service.RecordCull(reqCtx, operatorID, primaryID, req.PenID, req.Quantity, req.HappenedAt, req.Remarks) }, "记录成功", diff --git a/internal/app/controller/management/pig_batch_trade_controller.go b/internal/app/controller/management/pig_batch_trade_controller.go index 6380c40..e33602d 100644 --- a/internal/app/controller/management/pig_batch_trade_controller.go +++ b/internal/app/controller/management/pig_batch_trade_controller.go @@ -25,7 +25,7 @@ func (c *PigBatchController) SellPigs(ctx echo.Context) error { return handleAPIRequest( reqCtx, c, ctx, action, &req, - func(ctx echo.Context, operatorID uint, primaryID uint, req *dto.SellPigsRequest) error { + func(ctx echo.Context, operatorID uint32, primaryID uint32, req *dto.SellPigsRequest) error { return c.service.SellPigs(reqCtx, primaryID, req.PenID, req.Quantity, req.UnitPrice, req.TotalPrice, req.TraderName, req.TradeDate, req.Remarks, operatorID) }, "卖猪成功", @@ -51,7 +51,7 @@ func (c *PigBatchController) BuyPigs(ctx echo.Context) error { return handleAPIRequest( reqCtx, c, ctx, action, &req, - func(ctx echo.Context, operatorID uint, primaryID uint, req *dto.BuyPigsRequest) error { + func(ctx echo.Context, operatorID uint32, primaryID uint32, req *dto.BuyPigsRequest) error { return c.service.BuyPigs(reqCtx, primaryID, req.PenID, req.Quantity, req.UnitPrice, req.TotalPrice, req.TraderName, req.TradeDate, req.Remarks, operatorID) }, "买猪成功", diff --git a/internal/app/controller/management/pig_batch_transfer_controller.go b/internal/app/controller/management/pig_batch_transfer_controller.go index 1d8c7b4..0bb478a 100644 --- a/internal/app/controller/management/pig_batch_transfer_controller.go +++ b/internal/app/controller/management/pig_batch_transfer_controller.go @@ -28,18 +28,18 @@ func (c *PigBatchController) TransferPigsAcrossBatches(ctx echo.Context) error { return handleAPIRequest( reqCtx, c, ctx, action, &req, - func(ctx echo.Context, operatorID uint, primaryID uint, req *dto.TransferPigsAcrossBatchesRequest) error { + func(ctx echo.Context, operatorID uint32, primaryID uint32, req *dto.TransferPigsAcrossBatchesRequest) error { // primaryID 在这里是 sourceBatchID return c.service.TransferPigsAcrossBatches(reqCtx, primaryID, req.DestBatchID, req.FromPenID, req.ToPenID, req.Quantity, operatorID, req.Remarks) }, "调栏成功", - func(ctx echo.Context) (uint, error) { // 自定义ID提取器,从 ":sourceBatchID" 路径参数提取 + func(ctx echo.Context) (uint32, error) { // 自定义ID提取器,从 ":sourceBatchID" 路径参数提取 idParam := ctx.Param("sourceBatchID") parsedID, err := strconv.ParseUint(idParam, 10, 32) if err != nil { return 0, err } - return uint(parsedID), nil + return uint32(parsedID), nil }, ) } @@ -63,7 +63,7 @@ func (c *PigBatchController) TransferPigsWithinBatch(ctx echo.Context) error { return handleAPIRequest( reqCtx, c, ctx, action, &req, - func(ctx echo.Context, operatorID uint, primaryID uint, req *dto.TransferPigsWithinBatchRequest) error { + func(ctx echo.Context, operatorID uint32, primaryID uint32, req *dto.TransferPigsWithinBatchRequest) error { // primaryID 在这里是 batchID return c.service.TransferPigsWithinBatch(reqCtx, primaryID, req.FromPenID, req.ToPenID, req.Quantity, operatorID, req.Remarks) }, diff --git a/internal/app/controller/management/pig_farm_controller.go b/internal/app/controller/management/pig_farm_controller.go index 0a6733c..69dd7c7 100644 --- a/internal/app/controller/management/pig_farm_controller.go +++ b/internal/app/controller/management/pig_farm_controller.go @@ -76,7 +76,7 @@ func (c *PigFarmController) GetPigHouse(ctx echo.Context) error { return controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, "无效的ID格式", action, "ID格式错误", ctx.Param("id")) } - house, err := c.service.GetPigHouseByID(reqCtx, uint(id)) + house, err := c.service.GetPigHouseByID(reqCtx, uint32(id)) if err != nil { if errors.Is(err, service.ErrHouseNotFound) { return controller.SendErrorWithAudit(ctx, controller.CodeNotFound, "猪舍不存在", action, "猪舍不存在", id) @@ -132,7 +132,7 @@ func (c *PigFarmController) UpdatePigHouse(ctx echo.Context) error { return controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, "无效的请求体", action, "请求体绑定失败", req) } - house, err := c.service.UpdatePigHouse(reqCtx, uint(id), req.Name, req.Description) + house, err := c.service.UpdatePigHouse(reqCtx, uint32(id), req.Name, req.Description) if err != nil { if errors.Is(err, service.ErrHouseNotFound) { return controller.SendErrorWithAudit(ctx, controller.CodeNotFound, "猪舍不存在", action, "猪舍不存在", id) @@ -161,7 +161,7 @@ func (c *PigFarmController) DeletePigHouse(ctx echo.Context) error { return controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, "无效的ID格式", action, "ID格式错误", ctx.Param("id")) } - if err := c.service.DeletePigHouse(reqCtx, uint(id)); err != nil { + if err := c.service.DeletePigHouse(reqCtx, uint32(id)); err != nil { if errors.Is(err, service.ErrHouseNotFound) { return controller.SendErrorWithAudit(ctx, controller.CodeNotFound, "猪舍不存在", action, "猪舍不存在", id) } @@ -226,7 +226,7 @@ func (c *PigFarmController) GetPen(ctx echo.Context) error { return controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, "无效的ID格式", action, "ID格式错误", ctx.Param("id")) } - pen, err := c.service.GetPenByID(reqCtx, uint(id)) + pen, err := c.service.GetPenByID(reqCtx, uint32(id)) if err != nil { if errors.Is(err, service.ErrPenNotFound) { return controller.SendErrorWithAudit(ctx, controller.CodeNotFound, "猪栏不存在", action, "猪栏不存在", id) @@ -282,7 +282,7 @@ func (c *PigFarmController) UpdatePen(ctx echo.Context) error { return controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, "无效的请求体", action, "请求体绑定失败", req) } - pen, err := c.service.UpdatePen(reqCtx, uint(id), req.PenNumber, req.HouseID, req.Capacity, req.Status) + pen, err := c.service.UpdatePen(reqCtx, uint32(id), req.PenNumber, req.HouseID, req.Capacity, req.Status) if err != nil { if errors.Is(err, service.ErrPenNotFound) { return controller.SendErrorWithAudit(ctx, controller.CodeNotFound, "猪栏不存在", action, "猪栏不存在", id) @@ -312,7 +312,7 @@ func (c *PigFarmController) DeletePen(ctx echo.Context) error { return controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, "无效的ID格式", action, "ID格式错误", ctx.Param("id")) } - if err := c.service.DeletePen(reqCtx, uint(id)); err != nil { + if err := c.service.DeletePen(reqCtx, uint32(id)); err != nil { if errors.Is(err, service.ErrPenNotFound) { return controller.SendErrorWithAudit(ctx, controller.CodeNotFound, "猪栏不存在", action, "猪栏不存在", id) } @@ -351,7 +351,7 @@ func (c *PigFarmController) UpdatePenStatus(ctx echo.Context) error { return controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, "无效的请求体", action, "请求体绑定失败", req) } - pen, err := c.service.UpdatePenStatus(reqCtx, uint(id), req.Status) + pen, err := c.service.UpdatePenStatus(reqCtx, uint32(id), req.Status) if err != nil { if errors.Is(err, service.ErrPenNotFound) { return controller.SendErrorWithAudit(ctx, controller.CodeNotFound, err.Error(), action, err.Error(), id) diff --git a/internal/app/controller/plan/plan_controller.go b/internal/app/controller/plan/plan_controller.go index 35fa6b5..dfce780 100644 --- a/internal/app/controller/plan/plan_controller.go +++ b/internal/app/controller/plan/plan_controller.go @@ -81,14 +81,14 @@ func (c *Controller) GetPlan(ctx echo.Context) error { const actionType = "获取计划详情" // 1. 从 URL 路径中获取 ID idStr := ctx.Param("id") - id, err := strconv.ParseUint(idStr, 10, 32) + id, err := strconv.ParseUint(idStr, 10, 64) if err != nil { logger.Errorf("%s: 计划ID格式错误: %v, ID: %s", actionType, err, idStr) return controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, "无效的计划ID格式", actionType, "计划ID格式错误", idStr) } // 调用服务层获取计划详情 - resp, err := c.planService.GetPlanByID(reqCtx, uint(id)) + resp, err := c.planService.GetPlanByID(reqCtx, uint32(id)) if err != nil { logger.Errorf("%s: 服务层获取计划详情失败: %v, ID: %d", actionType, err, id) if errors.Is(err, plan.ErrPlanNotFound) { // 修改为 plan.ErrPlanNotFound @@ -147,7 +147,7 @@ func (c *Controller) UpdatePlan(ctx echo.Context) error { const actionType = "更新计划" // 1. 从 URL 路径中获取 ID idStr := ctx.Param("id") - id, err := strconv.ParseUint(idStr, 10, 32) + id, err := strconv.ParseUint(idStr, 10, 64) if err != nil { logger.Errorf("%s: 计划ID格式错误: %v, ID: %s", actionType, err, idStr) return controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, "无效的计划ID格式", actionType, "计划ID格式错误", idStr) @@ -161,7 +161,7 @@ func (c *Controller) UpdatePlan(ctx echo.Context) error { } // 调用服务层更新计划 - resp, err := c.planService.UpdatePlan(reqCtx, uint(id), &req) + resp, err := c.planService.UpdatePlan(reqCtx, uint32(id), &req) if err != nil { logger.Errorf("%s: 服务层更新计划失败: %v, ID: %d", actionType, err, id) if errors.Is(err, plan.ErrPlanNotFound) { // 修改为 plan.ErrPlanNotFound @@ -191,14 +191,14 @@ func (c *Controller) DeletePlan(ctx echo.Context) error { const actionType = "删除计划" // 1. 从 URL 路径中获取 ID idStr := ctx.Param("id") - id, err := strconv.ParseUint(idStr, 10, 32) + id, err := strconv.ParseUint(idStr, 10, 64) if err != nil { logger.Errorf("%s: 计划ID格式错误: %v, ID: %s", actionType, err, idStr) return controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, "无效的计划ID格式", actionType, "计划ID格式错误", idStr) } // 调用服务层删除计划 - err = c.planService.DeletePlan(reqCtx, uint(id)) + err = c.planService.DeletePlan(reqCtx, uint32(id)) if err != nil { logger.Errorf("%s: 服务层删除计划失败: %v, ID: %d", actionType, err, id) if errors.Is(err, plan.ErrPlanNotFound) { // 修改为 plan.ErrPlanNotFound @@ -228,14 +228,14 @@ func (c *Controller) StartPlan(ctx echo.Context) error { const actionType = "启动计划" // 1. 从 URL 路径中获取 ID idStr := ctx.Param("id") - id, err := strconv.ParseUint(idStr, 10, 32) + id, err := strconv.ParseUint(idStr, 10, 64) if err != nil { logger.Errorf("%s: 计划ID格式错误: %v, ID: %s", actionType, err, idStr) return controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, "无效的计划ID格式", actionType, "计划ID格式错误", idStr) } // 调用服务层启动计划 - err = c.planService.StartPlan(reqCtx, uint(id)) + err = c.planService.StartPlan(reqCtx, uint32(id)) if err != nil { logger.Errorf("%s: 服务层启动计划失败: %v, ID: %d", actionType, err, id) if errors.Is(err, plan.ErrPlanNotFound) { // 修改为 plan.ErrPlanNotFound @@ -267,14 +267,14 @@ func (c *Controller) StopPlan(ctx echo.Context) error { const actionType = "停止计划" // 1. 从 URL 路径中获取 ID idStr := ctx.Param("id") - id, err := strconv.ParseUint(idStr, 10, 32) + id, err := strconv.ParseUint(idStr, 10, 64) if err != nil { logger.Errorf("%s: 计划ID格式错误: %v, ID: %s", actionType, err, idStr) return controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, "无效的计划ID格式", actionType, "计划ID格式错误", idStr) } // 调用服务层停止计划 - err = c.planService.StopPlan(reqCtx, uint(id)) + err = c.planService.StopPlan(reqCtx, uint32(id)) if err != nil { logger.Errorf("%s: 服务层停止计划失败: %v, ID: %d", actionType, err, id) if errors.Is(err, plan.ErrPlanNotFound) { // 修改为 plan.ErrPlanNotFound diff --git a/internal/app/controller/user/user_controller.go b/internal/app/controller/user/user_controller.go index 1aa38c3..dada6ad 100644 --- a/internal/app/controller/user/user_controller.go +++ b/internal/app/controller/user/user_controller.go @@ -101,7 +101,7 @@ func (c *Controller) SendTestNotification(ctx echo.Context) error { const actionType = "发送测试通知" // 1. 从 URL 中获取用户 ID - userID, err := strconv.ParseUint(ctx.Param("id"), 10, 32) + userID, err := strconv.ParseUint(ctx.Param("id"), 10, 64) if err != nil { logger.Errorf("%s: 无效的用户ID格式: %v", actionType, err) return controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, "无效的用户ID格式", actionType, "无效的用户ID格式", ctx.Param("id")) @@ -115,7 +115,7 @@ func (c *Controller) SendTestNotification(ctx echo.Context) error { } // 3. 调用服务层 - err = c.userService.SendTestNotification(reqCtx, uint(userID), &req) + err = c.userService.SendTestNotification(reqCtx, uint32(userID), &req) if err != nil { logger.Errorf("%s: 服务层调用失败: %v", actionType, err) return controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "发送测试消息失败: "+err.Error(), actionType, "服务层调用失败", map[string]interface{}{"userID": userID, "type": req.Type}) diff --git a/internal/app/dto/alarm_dto.go b/internal/app/dto/alarm_dto.go index 2fc48ea..b83527a 100644 --- a/internal/app/dto/alarm_dto.go +++ b/internal/app/dto/alarm_dto.go @@ -8,7 +8,7 @@ import ( // SnoozeAlarmRequest 定义了忽略告警的请求体 type SnoozeAlarmRequest struct { - DurationMinutes uint `json:"duration_minutes" validate:"required,min=1"` // 忽略时长,单位分钟 + DurationMinutes uint32 `json:"duration_minutes" validate:"required,min=1"` // 忽略时长,单位分钟 } // ListActiveAlarmRequest 定义了获取活跃告警列表的请求参数 @@ -16,7 +16,7 @@ type ListActiveAlarmRequest struct { Page int `json:"page" query:"page"` PageSize int `json:"page_size" query:"page_size"` SourceType *models.AlarmSourceType `json:"source_type" query:"source_type"` // 按告警来源类型过滤 - SourceID *uint `json:"source_id" query:"source_id"` // 按告警来源ID过滤 + SourceID *uint32 `json:"source_id" query:"source_id"` // 按告警来源ID过滤 Level *models.SeverityLevel `json:"level" query:"level"` // 按告警严重性等级过滤 IsIgnored *bool `json:"is_ignored" query:"is_ignored"` // 按是否被忽略过滤 TriggerTime *time.Time `json:"trigger_time" query:"trigger_time"` // 告警触发时间范围 - 开始时间 @@ -26,11 +26,11 @@ type ListActiveAlarmRequest struct { // ActiveAlarmDTO 是用于API响应的活跃告警结构 type ActiveAlarmDTO struct { - ID uint `json:"id"` + ID uint32 `json:"id"` CreatedAt time.Time `json:"created_at"` UpdatedAt time.Time `json:"updated_at"` SourceType models.AlarmSourceType `json:"source_type"` - SourceID uint `json:"source_id"` + SourceID uint32 `json:"source_id"` AlarmCode models.AlarmCode `json:"alarm_code"` AlarmSummary string `json:"alarm_summary"` Level models.SeverityLevel `json:"level"` @@ -52,7 +52,7 @@ type ListHistoricalAlarmRequest struct { Page int `json:"page" query:"page"` PageSize int `json:"page_size" query:"page_size"` SourceType *models.AlarmSourceType `json:"source_type" query:"source_type"` // 按告警来源类型过滤 - SourceID *uint `json:"source_id" query:"source_id"` // 按告警来源ID过滤 + SourceID *uint32 `json:"source_id" query:"source_id"` // 按告警来源ID过滤 Level *models.SeverityLevel `json:"level" query:"level"` // 按告警严重性等级过滤 TriggerTimeStart *time.Time `json:"trigger_time_start" query:"trigger_time_start"` // 告警触发时间范围 - 开始时间 TriggerTimeEnd *time.Time `json:"trigger_time_end" query:"trigger_time_end"` // 告警触发时间范围 - 结束时间 @@ -63,9 +63,9 @@ type ListHistoricalAlarmRequest struct { // HistoricalAlarmDTO 是用于API响应的历史告警结构 type HistoricalAlarmDTO struct { - ID uint `json:"id"` + ID uint32 `json:"id"` SourceType models.AlarmSourceType `json:"source_type"` - SourceID uint `json:"source_id"` + SourceID uint32 `json:"source_id"` AlarmCode models.AlarmCode `json:"alarm_code"` AlarmSummary string `json:"alarm_summary"` Level models.SeverityLevel `json:"level"` @@ -73,7 +73,7 @@ type HistoricalAlarmDTO struct { TriggerTime time.Time `json:"trigger_time"` ResolveTime time.Time `json:"resolve_time"` ResolveMethod string `json:"resolve_method"` - ResolvedBy *uint `json:"resolved_by"` + ResolvedBy *uint32 `json:"resolved_by"` } // ListHistoricalAlarmResponse 是获取历史告警列表的响应结构 @@ -84,7 +84,7 @@ type ListHistoricalAlarmResponse struct { // CreateDeviceThresholdAlarmDTO 创建设备阈值告警的请求DTO type CreateDeviceThresholdAlarmDTO struct { - DeviceID uint `json:"device_id" binding:"required"` // 设备ID + DeviceID uint32 `json:"device_id" binding:"required"` // 设备ID SensorType models.SensorType `json:"sensor_type" binding:"required"` // 传感器类型 Thresholds float32 `json:"thresholds" binding:"required"` // 阈值 Operator models.Operator `json:"operator" binding:"required"` // 操作符 (使用string类型,与前端交互更通用) @@ -100,7 +100,7 @@ type UpdateDeviceThresholdAlarmDTO struct { // CreateAreaThresholdAlarmDTO 创建区域阈值告警的请求DTO type CreateAreaThresholdAlarmDTO struct { - AreaControllerID uint `json:"area_controller_id" binding:"required"` // 区域主控ID + AreaControllerID uint32 `json:"area_controller_id" binding:"required"` // 区域主控ID SensorType models.SensorType `json:"sensor_type" binding:"required"` // 传感器类型 Thresholds float32 `json:"thresholds" binding:"required"` // 阈值 Operator models.Operator `json:"operator" binding:"required"` // 操作符 @@ -122,7 +122,7 @@ type DeleteDeviceThresholdAlarmDTO struct { // AreaThresholdAlarmDTO 用于表示一个区域阈值告警任务的详细信息 type AreaThresholdAlarmDTO struct { ID int `json:"id"` - AreaControllerID uint `json:"area_controller_id"` + AreaControllerID uint32 `json:"area_controller_id"` SensorType models.SensorType `json:"sensor_type"` Thresholds float32 `json:"thresholds"` Operator models.Operator `json:"operator"` @@ -132,7 +132,7 @@ type AreaThresholdAlarmDTO struct { // DeviceThresholdAlarmDTO 用于表示一个设备阈值告警任务的详细信息 type DeviceThresholdAlarmDTO struct { ID int `json:"id"` - DeviceID uint `json:"device_id"` + DeviceID uint32 `json:"device_id"` SensorType models.SensorType `json:"sensor_type"` Thresholds float32 `json:"thresholds"` Operator models.Operator `json:"operator"` diff --git a/internal/app/dto/device_dto.go b/internal/app/dto/device_dto.go index 4dd4f20..5ac018b 100644 --- a/internal/app/dto/device_dto.go +++ b/internal/app/dto/device_dto.go @@ -5,8 +5,8 @@ import "git.huangwc.com/pig/pig-farm-controller/internal/infra/models" // CreateDeviceRequest 定义了创建设备时需要传入的参数 type CreateDeviceRequest struct { Name string `json:"name" validate:"required"` - DeviceTemplateID uint `json:"device_template_id" validate:"required"` - AreaControllerID uint `json:"area_controller_id" validate:"required"` + DeviceTemplateID uint32 `json:"device_template_id" validate:"required"` + AreaControllerID uint32 `json:"area_controller_id" validate:"required"` Location string `json:"location,omitempty" validate:"omitempty"` Properties map[string]interface{} `json:"properties,omitempty" validate:"omitempty"` } @@ -14,8 +14,8 @@ type CreateDeviceRequest struct { // UpdateDeviceRequest 定义了更新设备时需要传入的参数 type UpdateDeviceRequest struct { Name string `json:"name" validate:"required"` - DeviceTemplateID uint `json:"device_template_id" validate:"required"` - AreaControllerID uint `json:"area_controller_id" validate:"required"` + DeviceTemplateID uint32 `json:"device_template_id" validate:"required"` + AreaControllerID uint32 `json:"area_controller_id" validate:"required"` Location string `json:"location,omitempty" validate:"omitempty"` Properties map[string]interface{} `json:"properties,omitempty" validate:"omitempty"` } @@ -64,11 +64,11 @@ type UpdateDeviceTemplateRequest struct { // DeviceResponse 定义了返回给客户端的单个设备信息的结构 type DeviceResponse struct { - ID uint `json:"id"` + ID uint32 `json:"id"` Name string `json:"name"` - DeviceTemplateID uint `json:"device_template_id"` + DeviceTemplateID uint32 `json:"device_template_id"` DeviceTemplateName string `json:"device_template_name"` - AreaControllerID uint `json:"area_controller_id"` + AreaControllerID uint32 `json:"area_controller_id"` AreaControllerName string `json:"area_controller_name"` Location string `json:"location"` Properties map[string]interface{} `json:"properties"` @@ -78,7 +78,7 @@ type DeviceResponse struct { // AreaControllerResponse 定义了返回给客户端的单个区域主控信息的结构 type AreaControllerResponse struct { - ID uint `json:"id"` + ID uint32 `json:"id"` Name string `json:"name"` NetworkID string `json:"network_id"` Location string `json:"location"` @@ -90,7 +90,7 @@ type AreaControllerResponse struct { // DeviceTemplateResponse 定义了返回给客户端的单个设备模板信息的结构 type DeviceTemplateResponse struct { - ID uint `json:"id"` + ID uint32 `json:"id"` Name string `json:"name"` Manufacturer string `json:"manufacturer"` Description string `json:"description"` diff --git a/internal/app/dto/monitor_converter.go b/internal/app/dto/monitor_converter.go index 84c7ac2..657a4d4 100644 --- a/internal/app/dto/monitor_converter.go +++ b/internal/app/dto/monitor_converter.go @@ -54,7 +54,7 @@ func NewListDeviceCommandLogResponse(data []models.DeviceCommandLog, total int64 // NewListPlanExecutionLogResponse 从模型数据创建列表响应 DTO func NewListPlanExecutionLogResponse(planLogs []models.PlanExecutionLog, plans []models.Plan, total int64, page, pageSize int) *ListPlanExecutionLogResponse { - planId2Name := make(map[uint]string) + planId2Name := make(map[uint32]string) for _, plan := range plans { planId2Name[plan.ID] = string(plan.Name) } @@ -95,7 +95,7 @@ func NewListTaskExecutionLogResponse(data []models.TaskExecutionLog, total int64 PlanExecutionLogID: item.PlanExecutionLogID, TaskID: item.TaskID, Task: TaskDTO{ - ID: uint(item.Task.ID), + ID: uint32(item.Task.ID), Name: item.Task.Name, Description: item.Task.Description, }, @@ -373,7 +373,7 @@ func NewListWeighingRecordResponse(data []models.WeighingRecord, total int64, pa func NewListPigTransferLogResponse(data []models.PigTransferLog, total int64, page, pageSize int) *ListPigTransferLogResponse { dtos := make([]PigTransferLogDTO, len(data)) for i, item := range data { - // 注意:PigTransferLog 的 ID, CreatedAt, UpdatedAt 字段是 gorm.Model 嵌入的 + // 注意:PigTransferLog 的 ID, CreatedAt, UpdatedAt 字段是 Model 嵌入的 dtos[i] = PigTransferLogDTO{ ID: item.ID, CreatedAt: item.CreatedAt, diff --git a/internal/app/dto/monitor_dto.go b/internal/app/dto/monitor_dto.go index 406883e..6fcf4b6 100644 --- a/internal/app/dto/monitor_dto.go +++ b/internal/app/dto/monitor_dto.go @@ -13,7 +13,7 @@ import ( type ListSensorDataRequest struct { Page int `json:"page" query:"page"` PageSize int `json:"page_size" query:"page_size"` - DeviceID *uint `json:"device_id" query:"device_id"` + DeviceID *uint32 `json:"device_id" query:"device_id"` SensorType *string `json:"sensor_type" query:"sensor_type"` StartTime *time.Time `json:"start_time" query:"start_time"` EndTime *time.Time `json:"end_time" query:"end_time"` @@ -23,8 +23,8 @@ type ListSensorDataRequest struct { // SensorDataDTO 是用于API响应的传感器数据结构 type SensorDataDTO struct { Time time.Time `json:"time"` - DeviceID uint `json:"device_id"` - AreaControllerID uint `json:"area_controller_id"` + DeviceID uint32 `json:"device_id"` + AreaControllerID uint32 `json:"area_controller_id"` SensorType models.SensorType `json:"sensor_type"` Data json.RawMessage `json:"data"` } @@ -41,7 +41,7 @@ type ListSensorDataResponse struct { type ListDeviceCommandLogRequest struct { Page int `json:"page" query:"page"` PageSize int `json:"page_size" query:"page_size"` - DeviceID *uint `json:"device_id" query:"device_id"` + DeviceID *uint32 `json:"device_id" query:"device_id"` ReceivedSuccess *bool `json:"received_success" query:"received_success"` StartTime *time.Time `json:"start_time" query:"start_time"` EndTime *time.Time `json:"end_time" query:"end_time"` @@ -51,7 +51,7 @@ type ListDeviceCommandLogRequest struct { // DeviceCommandLogDTO 是用于API响应的设备命令日志结构 type DeviceCommandLogDTO struct { MessageID string `json:"message_id"` - DeviceID uint `json:"device_id"` + DeviceID uint32 `json:"device_id"` SentAt time.Time `json:"sent_at"` AcknowledgedAt *time.Time `json:"acknowledged_at"` ReceivedSuccess bool `json:"received_success"` @@ -69,7 +69,7 @@ type ListDeviceCommandLogResponse struct { type ListPlanExecutionLogRequest struct { Page int `json:"page" query:"page"` PageSize int `json:"page_size" query:"page_size"` - PlanID *uint `json:"plan_id" query:"plan_id"` + PlanID *uint32 `json:"plan_id" query:"plan_id"` Status *string `json:"status" query:"status"` StartTime *time.Time `json:"start_time" query:"start_time"` EndTime *time.Time `json:"end_time" query:"end_time"` @@ -78,10 +78,10 @@ type ListPlanExecutionLogRequest struct { // PlanExecutionLogDTO 是用于API响应的计划执行日志结构 type PlanExecutionLogDTO struct { - ID uint `json:"id"` + ID uint32 `json:"id"` CreatedAt time.Time `json:"created_at"` UpdatedAt time.Time `json:"updated_at"` - PlanID uint `json:"plan_id"` + PlanID uint32 `json:"plan_id"` PlanName string `json:"plan_name"` Status models.ExecutionStatus `json:"status"` StartedAt time.Time `json:"started_at"` @@ -101,7 +101,7 @@ type ListPlanExecutionLogResponse struct { type ListTaskExecutionLogRequest struct { Page int `json:"page" query:"page"` PageSize int `json:"page_size" query:"page_size"` - PlanExecutionLogID *uint `json:"plan_execution_log_id" query:"plan_execution_log_id"` + PlanExecutionLogID *uint32 `json:"plan_execution_log_id" query:"plan_execution_log_id"` TaskID *int `json:"task_id" query:"task_id"` Status *string `json:"status" query:"status"` StartTime *time.Time `json:"start_time" query:"start_time"` @@ -111,17 +111,17 @@ type ListTaskExecutionLogRequest struct { // TaskDTO 是用于API响应的简化版任务结构 type TaskDTO struct { - ID uint `json:"id"` + ID uint32 `json:"id"` Name string `json:"name"` Description string `json:"description"` } // TaskExecutionLogDTO 是用于API响应的任务执行日志结构 type TaskExecutionLogDTO struct { - ID uint `json:"id"` + ID uint32 `json:"id"` CreatedAt time.Time `json:"created_at"` UpdatedAt time.Time `json:"updated_at"` - PlanExecutionLogID uint `json:"plan_execution_log_id"` + PlanExecutionLogID uint32 `json:"plan_execution_log_id"` TaskID int `json:"task_id"` Task TaskDTO `json:"task"` // 嵌套的任务信息 Status models.ExecutionStatus `json:"status"` @@ -142,7 +142,7 @@ type ListTaskExecutionLogResponse struct { type ListPendingCollectionRequest struct { Page int `json:"page" query:"page"` PageSize int `json:"page_size" query:"page_size"` - DeviceID *uint `json:"device_id" query:"device_id"` + DeviceID *uint32 `json:"device_id" query:"device_id"` Status *string `json:"status" query:"status"` StartTime *time.Time `json:"start_time" query:"start_time"` EndTime *time.Time `json:"end_time" query:"end_time"` @@ -152,7 +152,7 @@ type ListPendingCollectionRequest struct { // PendingCollectionDTO 是用于API响应的待采集请求结构 type PendingCollectionDTO struct { CorrelationID string `json:"correlation_id"` - DeviceID uint `json:"device_id"` + DeviceID uint32 `json:"device_id"` CommandMetadata models.UintArray `json:"command_metadata"` Status models.PendingCollectionStatus `json:"status"` FulfilledAt *time.Time `json:"fulfilled_at"` @@ -171,7 +171,7 @@ type ListPendingCollectionResponse struct { type ListUserActionLogRequest struct { Page int `json:"page" query:"page"` PageSize int `json:"page_size" query:"page_size"` - UserID *uint `json:"user_id" query:"user_id"` + UserID *uint32 `json:"user_id" query:"user_id"` Username *string `json:"username" query:"username"` ActionType *string `json:"action_type" query:"action_type"` Status *string `json:"status" query:"status"` @@ -182,9 +182,9 @@ type ListUserActionLogRequest struct { // UserActionLogDTO 是用于API响应的用户操作日志结构 type UserActionLogDTO struct { - ID uint `json:"id"` + ID uint32 `json:"id"` Time time.Time `json:"time"` - UserID uint `json:"user_id"` + UserID uint32 `json:"user_id"` Username string `json:"username"` SourceIP string `json:"source_ip"` ActionType string `json:"action_type"` @@ -208,7 +208,7 @@ type ListUserActionLogResponse struct { type ListRawMaterialPurchaseRequest struct { Page int `json:"page" query:"page"` PageSize int `json:"page_size" query:"page_size"` - RawMaterialID *uint `json:"raw_material_id" query:"raw_material_id"` + RawMaterialID *uint32 `json:"raw_material_id" query:"raw_material_id"` Supplier *string `json:"supplier" query:"supplier"` StartTime *time.Time `json:"start_time" query:"start_time"` EndTime *time.Time `json:"end_time" query:"end_time"` @@ -217,14 +217,14 @@ type ListRawMaterialPurchaseRequest struct { // RawMaterialDTO 是用于API响应的简化版原料结构 type RawMaterialDTO struct { - ID uint `json:"id"` + ID uint32 `json:"id"` Name string `json:"name"` } // RawMaterialPurchaseDTO 是用于API响应的原料采购结构 type RawMaterialPurchaseDTO struct { - ID uint `json:"id"` - RawMaterialID uint `json:"raw_material_id"` + ID uint32 `json:"id"` + RawMaterialID uint32 `json:"raw_material_id"` RawMaterial RawMaterialDTO `json:"raw_material"` Supplier string `json:"supplier"` Amount float32 `json:"amount"` @@ -246,9 +246,9 @@ type ListRawMaterialPurchaseResponse struct { type ListRawMaterialStockLogRequest struct { Page int `json:"page" query:"page"` PageSize int `json:"page_size" query:"page_size"` - RawMaterialID *uint `json:"raw_material_id" query:"raw_material_id"` + RawMaterialID *uint32 `json:"raw_material_id" query:"raw_material_id"` SourceType *string `json:"source_type" query:"source_type"` - SourceID *uint `json:"source_id" query:"source_id"` + SourceID *uint32 `json:"source_id" query:"source_id"` StartTime *time.Time `json:"start_time" query:"start_time"` EndTime *time.Time `json:"end_time" query:"end_time"` OrderBy string `json:"order_by" query:"order_by"` @@ -256,11 +256,11 @@ type ListRawMaterialStockLogRequest struct { // RawMaterialStockLogDTO 是用于API响应的原料库存日志结构 type RawMaterialStockLogDTO struct { - ID uint `json:"id"` - RawMaterialID uint `json:"raw_material_id"` + ID uint32 `json:"id"` + RawMaterialID uint32 `json:"raw_material_id"` ChangeAmount float32 `json:"change_amount"` SourceType models.StockLogSourceType `json:"source_type"` - SourceID uint `json:"source_id"` + SourceID uint32 `json:"source_id"` HappenedAt time.Time `json:"happened_at"` Remarks string `json:"remarks"` } @@ -277,9 +277,9 @@ type ListRawMaterialStockLogResponse struct { type ListFeedUsageRecordRequest struct { Page int `json:"page" query:"page"` PageSize int `json:"page_size" query:"page_size"` - PenID *uint `json:"pen_id" query:"pen_id"` - FeedFormulaID *uint `json:"feed_formula_id" query:"feed_formula_id"` - OperatorID *uint `json:"operator_id" query:"operator_id"` + PenID *uint32 `json:"pen_id" query:"pen_id"` + FeedFormulaID *uint32 `json:"feed_formula_id" query:"feed_formula_id"` + OperatorID *uint32 `json:"operator_id" query:"operator_id"` StartTime *time.Time `json:"start_time" query:"start_time"` EndTime *time.Time `json:"end_time" query:"end_time"` OrderBy string `json:"order_by" query:"order_by"` @@ -287,26 +287,26 @@ type ListFeedUsageRecordRequest struct { // PenDTO 是用于API响应的简化版猪栏结构 type PenDTO struct { - ID uint `json:"id"` + ID uint32 `json:"id"` Name string `json:"name"` } // FeedFormulaDTO 是用于API响应的简化版饲料配方结构 type FeedFormulaDTO struct { - ID uint `json:"id"` + ID uint32 `json:"id"` Name string `json:"name"` } // FeedUsageRecordDTO 是用于API响应的饲料使用记录结构 type FeedUsageRecordDTO struct { - ID uint `json:"id"` - PenID uint `json:"pen_id"` + ID uint32 `json:"id"` + PenID uint32 `json:"pen_id"` Pen PenDTO `json:"pen"` - FeedFormulaID uint `json:"feed_formula_id"` + FeedFormulaID uint32 `json:"feed_formula_id"` FeedFormula FeedFormulaDTO `json:"feed_formula"` Amount float32 `json:"amount"` RecordedAt time.Time `json:"recorded_at"` - OperatorID uint `json:"operator_id"` + OperatorID uint32 `json:"operator_id"` Remarks string `json:"remarks"` } @@ -322,10 +322,10 @@ type ListFeedUsageRecordResponse struct { type ListMedicationLogRequest struct { Page int `json:"page" query:"page"` PageSize int `json:"page_size" query:"page_size"` - PigBatchID *uint `json:"pig_batch_id" query:"pig_batch_id"` - MedicationID *uint `json:"medication_id" query:"medication_id"` + PigBatchID *uint32 `json:"pig_batch_id" query:"pig_batch_id"` + MedicationID *uint32 `json:"medication_id" query:"medication_id"` Reason *string `json:"reason" query:"reason"` - OperatorID *uint `json:"operator_id" query:"operator_id"` + OperatorID *uint32 `json:"operator_id" query:"operator_id"` StartTime *time.Time `json:"start_time" query:"start_time"` EndTime *time.Time `json:"end_time" query:"end_time"` OrderBy string `json:"order_by" query:"order_by"` @@ -333,21 +333,21 @@ type ListMedicationLogRequest struct { // MedicationDTO 是用于API响应的简化版药品结构 type MedicationDTO struct { - ID uint `json:"id"` + ID uint32 `json:"id"` Name string `json:"name"` } // MedicationLogDTO 是用于API响应的用药记录结构 type MedicationLogDTO struct { - ID uint `json:"id"` - PigBatchID uint `json:"pig_batch_id"` - MedicationID uint `json:"medication_id"` + ID uint32 `json:"id"` + PigBatchID uint32 `json:"pig_batch_id"` + MedicationID uint32 `json:"medication_id"` Medication MedicationDTO `json:"medication"` DosageUsed float32 `json:"dosage_used"` TargetCount int `json:"target_count"` Reason models.MedicationReasonType `json:"reason"` Description string `json:"description"` - OperatorID uint `json:"operator_id"` + OperatorID uint32 `json:"operator_id"` HappenedAt time.Time `json:"happened_at"` } @@ -363,9 +363,9 @@ type ListMedicationLogResponse struct { type ListPigBatchLogRequest struct { Page int `json:"page" query:"page"` PageSize int `json:"page_size" query:"page_size"` - PigBatchID *uint `json:"pig_batch_id" query:"pig_batch_id"` + PigBatchID *uint32 `json:"pig_batch_id" query:"pig_batch_id"` ChangeType *string `json:"change_type" query:"change_type"` - OperatorID *uint `json:"operator_id" query:"operator_id"` + OperatorID *uint32 `json:"operator_id" query:"operator_id"` StartTime *time.Time `json:"start_time" query:"start_time"` EndTime *time.Time `json:"end_time" query:"end_time"` OrderBy string `json:"order_by" query:"order_by"` @@ -373,16 +373,16 @@ type ListPigBatchLogRequest struct { // PigBatchLogDTO 是用于API响应的猪批次日志结构 type PigBatchLogDTO struct { - ID uint `json:"id"` + ID uint32 `json:"id"` CreatedAt time.Time `json:"created_at"` UpdatedAt time.Time `json:"updated_at"` - PigBatchID uint `json:"pig_batch_id"` + PigBatchID uint32 `json:"pig_batch_id"` ChangeType models.LogChangeType `json:"change_type"` ChangeCount int `json:"change_count"` Reason string `json:"reason"` BeforeCount int `json:"before_count"` AfterCount int `json:"after_count"` - OperatorID uint `json:"operator_id"` + OperatorID uint32 `json:"operator_id"` HappenedAt time.Time `json:"happened_at"` } @@ -398,7 +398,7 @@ type ListPigBatchLogResponse struct { type ListWeighingBatchRequest struct { Page int `json:"page" query:"page"` PageSize int `json:"page_size" query:"page_size"` - PigBatchID *uint `json:"pig_batch_id" query:"pig_batch_id"` + PigBatchID *uint32 `json:"pig_batch_id" query:"pig_batch_id"` StartTime *time.Time `json:"start_time" query:"start_time"` EndTime *time.Time `json:"end_time" query:"end_time"` OrderBy string `json:"order_by" query:"order_by"` @@ -406,12 +406,12 @@ type ListWeighingBatchRequest struct { // WeighingBatchDTO 是用于API响应的批次称重记录结构 type WeighingBatchDTO struct { - ID uint `json:"id"` + ID uint32 `json:"id"` CreatedAt time.Time `json:"created_at"` UpdatedAt time.Time `json:"updated_at"` WeighingTime time.Time `json:"weighing_time"` Description string `json:"description"` - PigBatchID uint `json:"pig_batch_id"` + PigBatchID uint32 `json:"pig_batch_id"` } // ListWeighingBatchResponse 是获取批次称重记录列表的响应结构 @@ -426,9 +426,9 @@ type ListWeighingBatchResponse struct { type ListWeighingRecordRequest struct { Page int `json:"page" query:"page"` PageSize int `json:"page_size" query:"page_size"` - WeighingBatchID *uint `json:"weighing_batch_id" query:"weighing_batch_id"` - PenID *uint `json:"pen_id" query:"pen_id"` - OperatorID *uint `json:"operator_id" query:"operator_id"` + WeighingBatchID *uint32 `json:"weighing_batch_id" query:"weighing_batch_id"` + PenID *uint32 `json:"pen_id" query:"pen_id"` + OperatorID *uint32 `json:"operator_id" query:"operator_id"` StartTime *time.Time `json:"start_time" query:"start_time"` EndTime *time.Time `json:"end_time" query:"end_time"` OrderBy string `json:"order_by" query:"order_by"` @@ -436,13 +436,13 @@ type ListWeighingRecordRequest struct { // WeighingRecordDTO 是用于API响应的单次称重记录结构 type WeighingRecordDTO struct { - ID uint `json:"id"` + ID uint32 `json:"id"` CreatedAt time.Time `json:"created_at"` UpdatedAt time.Time `json:"updated_at"` Weight float32 `json:"weight"` - WeighingBatchID uint `json:"weighing_batch_id"` - PenID uint `json:"pen_id"` - OperatorID uint `json:"operator_id"` + WeighingBatchID uint32 `json:"weighing_batch_id"` + PenID uint32 `json:"pen_id"` + OperatorID uint32 `json:"operator_id"` Remark string `json:"remark"` WeighingTime time.Time `json:"weighing_time"` } @@ -459,10 +459,10 @@ type ListWeighingRecordResponse struct { type ListPigTransferLogRequest struct { Page int `json:"page" query:"page"` PageSize int `json:"page_size" query:"page_size"` - PigBatchID *uint `json:"pig_batch_id" query:"pig_batch_id"` - PenID *uint `json:"pen_id" query:"pen_id"` + PigBatchID *uint32 `json:"pig_batch_id" query:"pig_batch_id"` + PenID *uint32 `json:"pen_id" query:"pen_id"` TransferType *string `json:"transfer_type" query:"transfer_type"` - OperatorID *uint `json:"operator_id" query:"operator_id"` + OperatorID *uint32 `json:"operator_id" query:"operator_id"` CorrelationID *string `json:"correlation_id" query:"correlation_id"` StartTime *time.Time `json:"start_time" query:"start_time"` EndTime *time.Time `json:"end_time" query:"end_time"` @@ -471,16 +471,16 @@ type ListPigTransferLogRequest struct { // PigTransferLogDTO 是用于API响应的猪只迁移日志结构 type PigTransferLogDTO struct { - ID uint `json:"id"` + ID uint32 `json:"id"` CreatedAt time.Time `json:"created_at"` UpdatedAt time.Time `json:"updated_at"` TransferTime time.Time `json:"transfer_time"` - PigBatchID uint `json:"pig_batch_id"` - PenID uint `json:"pen_id"` + PigBatchID uint32 `json:"pig_batch_id"` + PenID uint32 `json:"pen_id"` Quantity int `json:"quantity"` Type models.PigTransferType `json:"type"` CorrelationID string `json:"correlation_id"` - OperatorID uint `json:"operator_id"` + OperatorID uint32 `json:"operator_id"` Remarks string `json:"remarks"` } @@ -496,11 +496,11 @@ type ListPigTransferLogResponse struct { type ListPigSickLogRequest struct { Page int `json:"page" query:"page"` PageSize int `json:"page_size" query:"page_size"` - PigBatchID *uint `json:"pig_batch_id" query:"pig_batch_id"` - PenID *uint `json:"pen_id" query:"pen_id"` + PigBatchID *uint32 `json:"pig_batch_id" query:"pig_batch_id"` + PenID *uint32 `json:"pen_id" query:"pen_id"` Reason *string `json:"reason" query:"reason"` TreatmentLocation *string `json:"treatment_location" query:"treatment_location"` - OperatorID *uint `json:"operator_id" query:"operator_id"` + OperatorID *uint32 `json:"operator_id" query:"operator_id"` StartTime *time.Time `json:"start_time" query:"start_time"` EndTime *time.Time `json:"end_time" query:"end_time"` OrderBy string `json:"order_by" query:"order_by"` @@ -508,18 +508,18 @@ type ListPigSickLogRequest struct { // PigSickLogDTO 是用于API响应的病猪日志结构 type PigSickLogDTO struct { - ID uint `json:"id"` + ID uint32 `json:"id"` CreatedAt time.Time `json:"created_at"` UpdatedAt time.Time `json:"updated_at"` - PigBatchID uint `json:"pig_batch_id"` - PenID uint `json:"pen_id"` + PigBatchID uint32 `json:"pig_batch_id"` + PenID uint32 `json:"pen_id"` ChangeCount int `json:"change_count"` Reason models.PigBatchSickPigReasonType `json:"reason"` BeforeCount int `json:"before_count"` AfterCount int `json:"after_count"` Remarks string `json:"remarks"` TreatmentLocation models.PigBatchSickPigTreatmentLocation `json:"treatment_location"` - OperatorID uint `json:"operator_id"` + OperatorID uint32 `json:"operator_id"` HappenedAt time.Time `json:"happened_at"` } @@ -535,9 +535,9 @@ type ListPigSickLogResponse struct { type ListPigPurchaseRequest struct { Page int `json:"page" query:"page"` PageSize int `json:"page_size" query:"page_size"` - PigBatchID *uint `json:"pig_batch_id" query:"pig_batch_id"` + PigBatchID *uint32 `json:"pig_batch_id" query:"pig_batch_id"` Supplier *string `json:"supplier" query:"supplier"` - OperatorID *uint `json:"operator_id" query:"operator_id"` + OperatorID *uint32 `json:"operator_id" query:"operator_id"` StartTime *time.Time `json:"start_time" query:"start_time"` EndTime *time.Time `json:"end_time" query:"end_time"` OrderBy string `json:"order_by" query:"order_by"` @@ -545,17 +545,17 @@ type ListPigPurchaseRequest struct { // PigPurchaseDTO 是用于API响应的猪只采购记录结构 type PigPurchaseDTO struct { - ID uint `json:"id"` + ID uint32 `json:"id"` CreatedAt time.Time `json:"created_at"` UpdatedAt time.Time `json:"updated_at"` - PigBatchID uint `json:"pig_batch_id"` + PigBatchID uint32 `json:"pig_batch_id"` PurchaseDate time.Time `json:"purchase_date"` Supplier string `json:"supplier"` Quantity int `json:"quantity"` UnitPrice float32 `json:"unit_price"` TotalPrice float32 `json:"total_price"` Remarks string `json:"remarks"` - OperatorID uint `json:"operator_id"` + OperatorID uint32 `json:"operator_id"` } // ListPigPurchaseResponse 是获取猪只采购记录列表的响应结构 @@ -570,9 +570,9 @@ type ListPigPurchaseResponse struct { type ListPigSaleRequest struct { Page int `json:"page" query:"page"` PageSize int `json:"page_size" query:"page_size"` - PigBatchID *uint `json:"pig_batch_id" query:"pig_batch_id"` + PigBatchID *uint32 `json:"pig_batch_id" query:"pig_batch_id"` Buyer *string `json:"buyer" query:"buyer"` - OperatorID *uint `json:"operator_id" query:"operator_id"` + OperatorID *uint32 `json:"operator_id" query:"operator_id"` StartTime *time.Time `json:"start_time" query:"start_time"` EndTime *time.Time `json:"end_time" query:"end_time"` OrderBy string `json:"order_by" query:"order_by"` @@ -580,17 +580,17 @@ type ListPigSaleRequest struct { // PigSaleDTO 是用于API响应的猪只销售记录结构 type PigSaleDTO struct { - ID uint `json:"id"` + ID uint32 `json:"id"` CreatedAt time.Time `json:"created_at"` UpdatedAt time.Time `json:"updated_at"` - PigBatchID uint `json:"pig_batch_id"` + PigBatchID uint32 `json:"pig_batch_id"` SaleDate time.Time `json:"sale_date"` Buyer string `json:"buyer"` Quantity int `json:"quantity"` UnitPrice float32 `json:"unit_price"` TotalPrice float32 `json:"total_price"` Remarks string `json:"remarks"` - OperatorID uint `json:"operator_id"` + OperatorID uint32 `json:"operator_id"` } // ListPigSaleResponse 是获取猪只销售记录列表的响应结构 diff --git a/internal/app/dto/notification_dto.go b/internal/app/dto/notification_dto.go index f0d32ac..15d2b48 100644 --- a/internal/app/dto/notification_dto.go +++ b/internal/app/dto/notification_dto.go @@ -18,7 +18,7 @@ type SendTestNotificationRequest struct { type ListNotificationRequest struct { Page int `json:"page" query:"page"` PageSize int `json:"page_size" query:"page_size"` - UserID *uint `json:"user_id" query:"user_id"` + UserID *uint32 `json:"user_id" query:"user_id"` NotifierType *models.NotifierType `json:"notifier_type" query:"notifier_type"` Status *models.NotificationStatus `json:"status" query:"status"` Level *zapcore.Level `json:"level" query:"level"` @@ -29,11 +29,11 @@ type ListNotificationRequest struct { // NotificationDTO 是用于API响应的通知结构 type NotificationDTO struct { - ID uint `json:"id"` + ID uint32 `json:"id"` CreatedAt time.Time `json:"created_at"` UpdatedAt time.Time `json:"updated_at"` NotifierType models.NotifierType `json:"notifier_type"` - UserID uint `json:"user_id"` + UserID uint32 `json:"user_id"` Title string `json:"title"` Message string `json:"message"` Level models.SeverityLevel `json:"level"` diff --git a/internal/app/dto/pig_batch_dto.go b/internal/app/dto/pig_batch_dto.go index 0b23c92..2f3fbab 100644 --- a/internal/app/dto/pig_batch_dto.go +++ b/internal/app/dto/pig_batch_dto.go @@ -32,7 +32,7 @@ type PigBatchQueryDTO struct { // PigBatchResponseDTO 定义了猪批次信息的响应结构 type PigBatchResponseDTO struct { - ID uint `json:"id"` // 批次ID + ID uint32 `json:"id"` // 批次ID BatchNumber string `json:"batch_number"` // 批次编号 OriginType models.PigBatchOriginType `json:"origin_type"` // 批次来源 StartDate time.Time `json:"start_date"` // 批次开始日期 @@ -48,31 +48,31 @@ type PigBatchResponseDTO struct { // AssignEmptyPensToBatchRequest 用于为猪批次分配空栏的请求体 type AssignEmptyPensToBatchRequest struct { - PenIDs []uint `json:"pen_ids" validate:"required,min=1,dive" example:"1,2,3"` // 待分配的猪栏ID列表 + PenIDs []uint32 `json:"pen_ids" validate:"required,min=1,dive" example:"1,2,3"` // 待分配的猪栏ID列表 } // ReclassifyPenToNewBatchRequest 用于将猪栏划拨到新批次的请求体 type ReclassifyPenToNewBatchRequest struct { - ToBatchID uint `json:"to_batch_id" validate:"required"` // 目标猪批次ID - PenID uint `json:"pen_id" validate:"required"` // 待划拨的猪栏ID + ToBatchID uint32 `json:"to_batch_id" validate:"required"` // 目标猪批次ID + PenID uint32 `json:"pen_id" validate:"required"` // 待划拨的猪栏ID Remarks string `json:"remarks"` // 备注 } // RemoveEmptyPenFromBatchRequest 用于从猪批次移除空栏的请求体 type RemoveEmptyPenFromBatchRequest struct { - PenID uint `json:"pen_id" validate:"required"` // 待移除的猪栏ID + PenID uint32 `json:"pen_id" validate:"required"` // 待移除的猪栏ID } // MovePigsIntoPenRequest 用于将猪只从“虚拟库存”移入指定猪栏的请求体 type MovePigsIntoPenRequest struct { - ToPenID uint `json:"to_pen_id" validate:"required"` // 目标猪栏ID + ToPenID uint32 `json:"to_pen_id" validate:"required"` // 目标猪栏ID Quantity int `json:"quantity" validate:"required,min=1"` // 移入猪只数量 Remarks string `json:"remarks"` // 备注 } // SellPigsRequest 用于处理卖猪的请求体 type SellPigsRequest struct { - PenID uint `json:"pen_id" validate:"required"` // 猪栏ID + PenID uint32 `json:"pen_id" validate:"required"` // 猪栏ID Quantity int `json:"quantity" validate:"required,min=1"` // 卖出猪只数量 UnitPrice float32 `json:"unit_price" validate:"required,min=0"` // 单价 TotalPrice float32 `json:"total_price" validate:"required,min=0"` // 总价 @@ -83,7 +83,7 @@ type SellPigsRequest struct { // BuyPigsRequest 用于处理买猪的请求体 type BuyPigsRequest struct { - PenID uint `json:"pen_id" validate:"required"` // 猪栏ID + PenID uint32 `json:"pen_id" validate:"required"` // 猪栏ID Quantity int `json:"quantity" validate:"required,min=1"` // 买入猪只数量 UnitPrice float32 `json:"unit_price" validate:"required,min=0"` // 单价 TotalPrice float32 `json:"total_price" validate:"required,min=0"` // 总价 @@ -94,24 +94,24 @@ type BuyPigsRequest struct { // TransferPigsAcrossBatchesRequest 用于跨猪群调栏的请求体 type TransferPigsAcrossBatchesRequest struct { - DestBatchID uint `json:"dest_batch_id" validate:"required"` // 目标猪批次ID - FromPenID uint `json:"from_pen_id" validate:"required"` // 源猪栏ID - ToPenID uint `json:"to_pen_id" validate:"required"` // 目标猪栏ID - Quantity uint `json:"quantity" validate:"required,min=1"` // 调栏猪只数量 + DestBatchID uint32 `json:"dest_batch_id" validate:"required"` // 目标猪批次ID + FromPenID uint32 `json:"from_pen_id" validate:"required"` // 源猪栏ID + ToPenID uint32 `json:"to_pen_id" validate:"required"` // 目标猪栏ID + Quantity uint32 `json:"quantity" validate:"required,min=1"` // 调栏猪只数量 Remarks string `json:"remarks"` // 备注 } // TransferPigsWithinBatchRequest 用于群内调栏的请求体 type TransferPigsWithinBatchRequest struct { - FromPenID uint `json:"from_pen_id" validate:"required"` // 源猪栏ID - ToPenID uint `json:"to_pen_id" validate:"required"` // 目标猪栏ID - Quantity uint `json:"quantity" validate:"required,min=1"` // 调栏猪只数量 + FromPenID uint32 `json:"from_pen_id" validate:"required"` // 源猪栏ID + ToPenID uint32 `json:"to_pen_id" validate:"required"` // 目标猪栏ID + Quantity uint32 `json:"quantity" validate:"required,min=1"` // 调栏猪只数量 Remarks string `json:"remarks"` // 备注 } // RecordSickPigsRequest 用于记录新增病猪事件的请求体 type RecordSickPigsRequest struct { - PenID uint `json:"pen_id" validate:"required"` // 猪栏ID + PenID uint32 `json:"pen_id" validate:"required"` // 猪栏ID Quantity int `json:"quantity" validate:"required,min=1"` // 病猪数量 TreatmentLocation models.PigBatchSickPigTreatmentLocation `json:"treatment_location" validate:"required"` // 治疗地点 HappenedAt time.Time `json:"happened_at" validate:"required"` // 发生时间 @@ -120,7 +120,7 @@ type RecordSickPigsRequest struct { // RecordSickPigRecoveryRequest 用于记录病猪康复事件的请求体 type RecordSickPigRecoveryRequest struct { - PenID uint `json:"pen_id" validate:"required"` // 猪栏ID + PenID uint32 `json:"pen_id" validate:"required"` // 猪栏ID Quantity int `json:"quantity" validate:"required,min=1"` // 康复猪数量 TreatmentLocation models.PigBatchSickPigTreatmentLocation `json:"treatment_location" validate:"required"` // 治疗地点 HappenedAt time.Time `json:"happened_at" validate:"required"` // 发生时间 @@ -129,7 +129,7 @@ type RecordSickPigRecoveryRequest struct { // RecordSickPigDeathRequest 用于记录病猪死亡事件的请求体 type RecordSickPigDeathRequest struct { - PenID uint `json:"pen_id" validate:"required"` // 猪栏ID + PenID uint32 `json:"pen_id" validate:"required"` // 猪栏ID Quantity int `json:"quantity" validate:"required,min=1"` // 死亡猪数量 TreatmentLocation models.PigBatchSickPigTreatmentLocation `json:"treatment_location" validate:"required"` // 治疗地点 HappenedAt time.Time `json:"happened_at" validate:"required"` // 发生时间 @@ -138,7 +138,7 @@ type RecordSickPigDeathRequest struct { // RecordSickPigCullRequest 用于记录病猪淘汰事件的请求体 type RecordSickPigCullRequest struct { - PenID uint `json:"pen_id" validate:"required"` // 猪栏ID + PenID uint32 `json:"pen_id" validate:"required"` // 猪栏ID Quantity int `json:"quantity" validate:"required,min=1"` // 淘汰猪数量 TreatmentLocation models.PigBatchSickPigTreatmentLocation `json:"treatment_location" validate:"required"` // 治疗地点 HappenedAt time.Time `json:"happened_at" validate:"required"` // 发生时间 @@ -147,7 +147,7 @@ type RecordSickPigCullRequest struct { // RecordDeathRequest 用于记录正常猪只死亡事件的请求体 type RecordDeathRequest struct { - PenID uint `json:"pen_id" validate:"required"` // 猪栏ID + PenID uint32 `json:"pen_id" validate:"required"` // 猪栏ID Quantity int `json:"quantity" validate:"required,min=1"` // 死亡猪数量 HappenedAt time.Time `json:"happened_at" validate:"required"` // 发生时间 Remarks string `json:"remarks"` // 备注 @@ -155,7 +155,7 @@ type RecordDeathRequest struct { // RecordCullRequest 用于记录正常猪只淘汰事件的请求体 type RecordCullRequest struct { - PenID uint `json:"pen_id" validate:"required"` // 猪栏ID + PenID uint32 `json:"pen_id" validate:"required"` // 猪栏ID Quantity int `json:"quantity" validate:"required,min=1"` // 淘汰猪数量 HappenedAt time.Time `json:"happened_at" validate:"required"` // 发生时间 Remarks string `json:"remarks"` // 备注 diff --git a/internal/app/dto/pig_farm_dto.go b/internal/app/dto/pig_farm_dto.go index fd789bc..913e374 100644 --- a/internal/app/dto/pig_farm_dto.go +++ b/internal/app/dto/pig_farm_dto.go @@ -4,19 +4,19 @@ import "git.huangwc.com/pig/pig-farm-controller/internal/infra/models" // PigHouseResponse 定义了猪舍信息的响应结构 type PigHouseResponse struct { - ID uint `json:"id"` + ID uint32 `json:"id"` Name string `json:"name"` Description string `json:"description"` } // PenResponse 定义了猪栏信息的响应结构 type PenResponse struct { - ID uint `json:"id"` + ID uint32 `json:"id"` PenNumber string `json:"pen_number"` - HouseID uint `json:"house_id"` + HouseID uint32 `json:"house_id"` Capacity int `json:"capacity"` Status models.PenStatus `json:"status"` - PigBatchID *uint `json:"pig_batch_id,omitempty"` + PigBatchID *uint32 `json:"pig_batch_id,omitempty"` CurrentPigCount int `json:"current_pig_count"` } @@ -35,14 +35,14 @@ type UpdatePigHouseRequest struct { // CreatePenRequest 定义了创建猪栏的请求结构 type CreatePenRequest struct { PenNumber string `json:"pen_number" validate:"required"` - HouseID uint `json:"house_id" validate:"required"` + HouseID uint32 `json:"house_id" validate:"required"` Capacity int `json:"capacity" validate:"required"` } // UpdatePenRequest 定义了更新猪栏的请求结构 type UpdatePenRequest struct { PenNumber string `json:"pen_number" validate:"required"` - HouseID uint `json:"house_id" validate:"required"` + HouseID uint32 `json:"house_id" validate:"required"` Capacity int `json:"capacity" validate:"required"` Status models.PenStatus `json:"status" validate:"required,oneof=空闲 使用中 病猪栏 康复栏 清洗消毒 维修中"` // 添加oneof校验 } diff --git a/internal/app/dto/plan_dto.go b/internal/app/dto/plan_dto.go index 51b82f1..b46efdb 100644 --- a/internal/app/dto/plan_dto.go +++ b/internal/app/dto/plan_dto.go @@ -17,22 +17,22 @@ type CreatePlanRequest struct { Name string `json:"name" validate:"required" example:"猪舍温度控制计划"` Description string `json:"description" example:"根据温度自动调节风扇和加热器"` ExecutionType models.PlanExecutionType `json:"execution_type" validate:"required" example:"自动"` - ExecuteNum uint `json:"execute_num,omitempty" validate:"omitempty,min=0" example:"10"` + ExecuteNum uint32 `json:"execute_num,omitempty" validate:"omitempty,min=0" example:"10"` CronExpression string `json:"cron_expression" validate:"omitempty,cron" example:"0 0 6 * * *"` - SubPlanIDs []uint `json:"sub_plan_ids,omitempty" validate:"omitempty,dive"` + SubPlanIDs []uint32 `json:"sub_plan_ids,omitempty" validate:"omitempty,dive"` Tasks []TaskRequest `json:"tasks,omitempty" validate:"omitempty,dive"` } // PlanResponse 定义计划详情响应的结构体 type PlanResponse struct { - ID uint `json:"id" example:"1"` + ID uint32 `json:"id" example:"1"` Name string `json:"name" example:"猪舍温度控制计划"` Description string `json:"description" example:"根据温度自动调节风扇和加热器"` PlanType models.PlanType `json:"plan_type" example:"自定义任务"` ExecutionType models.PlanExecutionType `json:"execution_type" example:"自动"` Status models.PlanStatus `json:"status" example:"已启用"` - ExecuteNum uint `json:"execute_num" example:"10"` - ExecuteCount uint `json:"execute_count" example:"0"` + ExecuteNum uint32 `json:"execute_num" example:"10"` + ExecuteCount uint32 `json:"execute_count" example:"0"` CronExpression string `json:"cron_expression" example:"0 0 6 * * *"` ContentType models.PlanContentType `json:"content_type" example:"任务"` SubPlans []SubPlanResponse `json:"sub_plans,omitempty"` @@ -50,17 +50,17 @@ type UpdatePlanRequest struct { Name string `json:"name" example:"猪舍温度控制计划V2"` Description string `json:"description" example:"更新后的描述"` ExecutionType models.PlanExecutionType `json:"execution_type" validate:"required" example:"自动"` - ExecuteNum uint `json:"execute_num,omitempty" validate:"omitempty,min=0" example:"10"` + ExecuteNum uint32 `json:"execute_num,omitempty" validate:"omitempty,min=0" example:"10"` CronExpression string `json:"cron_expression" validate:"omitempty,cron" example:"0 0 6 * * *"` - SubPlanIDs []uint `json:"sub_plan_ids,omitempty" validate:"omitempty,dive"` + SubPlanIDs []uint32 `json:"sub_plan_ids,omitempty" validate:"omitempty,dive"` Tasks []TaskRequest `json:"tasks,omitempty" validate:"omitempty,dive"` } // SubPlanResponse 定义子计划响应结构体 type SubPlanResponse struct { - ID uint `json:"id" example:"1"` - ParentPlanID uint `json:"parent_plan_id" example:"1"` - ChildPlanID uint `json:"child_plan_id" example:"2"` + ID uint32 `json:"id" example:"1"` + ParentPlanID uint32 `json:"parent_plan_id" example:"1"` + ChildPlanID uint32 `json:"child_plan_id" example:"2"` ExecutionOrder int `json:"execution_order" example:"1"` ChildPlan *PlanResponse `json:"child_plan,omitempty"` } @@ -77,7 +77,7 @@ type TaskRequest struct { // TaskResponse 定义任务响应结构体 type TaskResponse struct { ID int `json:"id" example:"1"` - PlanID uint `json:"plan_id" example:"1"` + PlanID uint32 `json:"plan_id" example:"1"` Name string `json:"name" example:"打开风扇"` Description string `json:"description" example:"打开1号风扇"` ExecutionOrder int `json:"execution_order" example:"1"` diff --git a/internal/app/dto/user_dto.go b/internal/app/dto/user_dto.go index 1a758c7..17700f2 100644 --- a/internal/app/dto/user_dto.go +++ b/internal/app/dto/user_dto.go @@ -16,19 +16,19 @@ type LoginRequest struct { // CreateUserResponse 定义创建用户成功响应的结构体 type CreateUserResponse struct { Username string `json:"username" example:"newuser"` - ID uint `json:"id" example:"1"` + ID uint32 `json:"id" example:"1"` } // LoginResponse 定义登录成功响应的结构体 type LoginResponse struct { Username string `json:"username" example:"testuser"` - ID uint `json:"id" example:"1"` + ID uint32 `json:"id" example:"1"` Token string `json:"token" example:"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."` } // HistoryResponse 定义单条操作历史的响应结构体 type HistoryResponse struct { - UserID uint `json:"user_id" example:"101"` + UserID uint32 `json:"user_id" example:"101"` Username string `json:"username" example:"testuser"` ActionType string `json:"action_type" example:"更新设备"` Description string `json:"description" example:"设备更新成功"` diff --git a/internal/app/service/device_service.go b/internal/app/service/device_service.go index 4a471c9..89cc49c 100644 --- a/internal/app/service/device_service.go +++ b/internal/app/service/device_service.go @@ -28,23 +28,23 @@ var ( // DeviceService 定义了应用层的设备服务接口,用于协调设备相关的业务逻辑。 type DeviceService interface { CreateDevice(ctx context.Context, req *dto.CreateDeviceRequest) (*dto.DeviceResponse, error) - GetDevice(ctx context.Context, id uint) (*dto.DeviceResponse, error) + GetDevice(ctx context.Context, id uint32) (*dto.DeviceResponse, error) ListDevices(ctx context.Context) ([]*dto.DeviceResponse, error) - UpdateDevice(ctx context.Context, id uint, req *dto.UpdateDeviceRequest) (*dto.DeviceResponse, error) - DeleteDevice(ctx context.Context, id uint) error - ManualControl(ctx context.Context, id uint, req *dto.ManualControlDeviceRequest) error + UpdateDevice(ctx context.Context, id uint32, req *dto.UpdateDeviceRequest) (*dto.DeviceResponse, error) + DeleteDevice(ctx context.Context, id uint32) error + ManualControl(ctx context.Context, id uint32, req *dto.ManualControlDeviceRequest) error CreateAreaController(ctx context.Context, req *dto.CreateAreaControllerRequest) (*dto.AreaControllerResponse, error) - GetAreaController(ctx context.Context, id uint) (*dto.AreaControllerResponse, error) + GetAreaController(ctx context.Context, id uint32) (*dto.AreaControllerResponse, error) ListAreaControllers(ctx context.Context) ([]*dto.AreaControllerResponse, error) - UpdateAreaController(ctx context.Context, id uint, req *dto.UpdateAreaControllerRequest) (*dto.AreaControllerResponse, error) - DeleteAreaController(ctx context.Context, id uint) error + UpdateAreaController(ctx context.Context, id uint32, req *dto.UpdateAreaControllerRequest) (*dto.AreaControllerResponse, error) + DeleteAreaController(ctx context.Context, id uint32) error CreateDeviceTemplate(ctx context.Context, req *dto.CreateDeviceTemplateRequest) (*dto.DeviceTemplateResponse, error) - GetDeviceTemplate(ctx context.Context, id uint) (*dto.DeviceTemplateResponse, error) + GetDeviceTemplate(ctx context.Context, id uint32) (*dto.DeviceTemplateResponse, error) ListDeviceTemplates(ctx context.Context) ([]*dto.DeviceTemplateResponse, error) - UpdateDeviceTemplate(ctx context.Context, id uint, req *dto.UpdateDeviceTemplateRequest) (*dto.DeviceTemplateResponse, error) - DeleteDeviceTemplate(ctx context.Context, id uint) error + UpdateDeviceTemplate(ctx context.Context, id uint32, req *dto.UpdateDeviceTemplateRequest) (*dto.DeviceTemplateResponse, error) + DeleteDeviceTemplate(ctx context.Context, id uint32) error } // deviceService 是 DeviceService 接口的具体实现。 @@ -109,7 +109,7 @@ func (s *deviceService) CreateDevice(ctx context.Context, req *dto.CreateDeviceR return dto.NewDeviceResponse(createdDevice) } -func (s *deviceService) GetDevice(ctx context.Context, id uint) (*dto.DeviceResponse, error) { +func (s *deviceService) GetDevice(ctx context.Context, id uint32) (*dto.DeviceResponse, error) { serviceCtx := logs.AddFuncName(ctx, s.ctx, "GetDevice") device, err := s.deviceRepo.FindByID(serviceCtx, id) if err != nil { @@ -127,7 +127,7 @@ func (s *deviceService) ListDevices(ctx context.Context) ([]*dto.DeviceResponse, return dto.NewListDeviceResponse(devices) } -func (s *deviceService) UpdateDevice(ctx context.Context, id uint, req *dto.UpdateDeviceRequest) (*dto.DeviceResponse, error) { +func (s *deviceService) UpdateDevice(ctx context.Context, id uint32, req *dto.UpdateDeviceRequest) (*dto.DeviceResponse, error) { serviceCtx := logs.AddFuncName(ctx, s.ctx, "UpdateDevice") existingDevice, err := s.deviceRepo.FindByID(serviceCtx, id) if err != nil { @@ -161,7 +161,7 @@ func (s *deviceService) UpdateDevice(ctx context.Context, id uint, req *dto.Upda return dto.NewDeviceResponse(updatedDevice) } -func (s *deviceService) DeleteDevice(ctx context.Context, id uint) error { +func (s *deviceService) DeleteDevice(ctx context.Context, id uint32) error { serviceCtx := logs.AddFuncName(ctx, s.ctx, "DeleteDevice") // 检查设备是否存在 @@ -191,7 +191,7 @@ func (s *deviceService) DeleteDevice(ctx context.Context, id uint) error { return s.deviceRepo.Delete(serviceCtx, id) } -func (s *deviceService) ManualControl(ctx context.Context, id uint, req *dto.ManualControlDeviceRequest) error { +func (s *deviceService) ManualControl(ctx context.Context, id uint32, req *dto.ManualControlDeviceRequest) error { serviceCtx := logs.AddFuncName(ctx, s.ctx, "ManualControl") dev, err := s.deviceRepo.FindByID(serviceCtx, id) if err != nil { @@ -241,7 +241,7 @@ func (s *deviceService) CreateAreaController(ctx context.Context, req *dto.Creat return dto.NewAreaControllerResponse(ac) } -func (s *deviceService) GetAreaController(ctx context.Context, id uint) (*dto.AreaControllerResponse, error) { +func (s *deviceService) GetAreaController(ctx context.Context, id uint32) (*dto.AreaControllerResponse, error) { serviceCtx := logs.AddFuncName(ctx, s.ctx, "GetAreaController") ac, err := s.areaControllerRepo.FindByID(serviceCtx, id) if err != nil { @@ -259,7 +259,7 @@ func (s *deviceService) ListAreaControllers(ctx context.Context) ([]*dto.AreaCon return dto.NewListAreaControllerResponse(acs) } -func (s *deviceService) UpdateAreaController(ctx context.Context, id uint, req *dto.UpdateAreaControllerRequest) (*dto.AreaControllerResponse, error) { +func (s *deviceService) UpdateAreaController(ctx context.Context, id uint32, req *dto.UpdateAreaControllerRequest) (*dto.AreaControllerResponse, error) { serviceCtx := logs.AddFuncName(ctx, s.ctx, "UpdateAreaController") existingAC, err := s.areaControllerRepo.FindByID(serviceCtx, id) if err != nil { @@ -287,7 +287,7 @@ func (s *deviceService) UpdateAreaController(ctx context.Context, id uint, req * return dto.NewAreaControllerResponse(existingAC) } -func (s *deviceService) DeleteAreaController(ctx context.Context, id uint) error { +func (s *deviceService) DeleteAreaController(ctx context.Context, id uint32) error { serviceCtx := logs.AddFuncName(ctx, s.ctx, "DeleteAreaController") // 1. 检查是否存在 @@ -349,7 +349,7 @@ func (s *deviceService) CreateDeviceTemplate(ctx context.Context, req *dto.Creat return dto.NewDeviceTemplateResponse(deviceTemplate) } -func (s *deviceService) GetDeviceTemplate(ctx context.Context, id uint) (*dto.DeviceTemplateResponse, error) { +func (s *deviceService) GetDeviceTemplate(ctx context.Context, id uint32) (*dto.DeviceTemplateResponse, error) { serviceCtx := logs.AddFuncName(ctx, s.ctx, "GetDeviceTemplate") deviceTemplate, err := s.deviceTemplateRepo.FindByID(serviceCtx, id) if err != nil { @@ -367,7 +367,7 @@ func (s *deviceService) ListDeviceTemplates(ctx context.Context) ([]*dto.DeviceT return dto.NewListDeviceTemplateResponse(deviceTemplates) } -func (s *deviceService) UpdateDeviceTemplate(ctx context.Context, id uint, req *dto.UpdateDeviceTemplateRequest) (*dto.DeviceTemplateResponse, error) { +func (s *deviceService) UpdateDeviceTemplate(ctx context.Context, id uint32, req *dto.UpdateDeviceTemplateRequest) (*dto.DeviceTemplateResponse, error) { serviceCtx := logs.AddFuncName(ctx, s.ctx, "UpdateDeviceTemplate") existingDeviceTemplate, err := s.deviceTemplateRepo.FindByID(serviceCtx, id) if err != nil { @@ -402,7 +402,7 @@ func (s *deviceService) UpdateDeviceTemplate(ctx context.Context, id uint, req * return dto.NewDeviceTemplateResponse(existingDeviceTemplate) } -func (s *deviceService) DeleteDeviceTemplate(ctx context.Context, id uint) error { +func (s *deviceService) DeleteDeviceTemplate(ctx context.Context, id uint32) error { serviceCtx := logs.AddFuncName(ctx, s.ctx, "DeleteDeviceTemplate") // 1. 检查是否存在 diff --git a/internal/app/service/monitor_service.go b/internal/app/service/monitor_service.go index ea3bbab..64be63e 100644 --- a/internal/app/service/monitor_service.go +++ b/internal/app/service/monitor_service.go @@ -147,7 +147,7 @@ func (s *monitorService) ListPlanExecutionLogs(ctx context.Context, req *dto.Lis return nil, err } - planIds := make([]uint, 0, len(planLogs)) + planIds := make([]uint32, 0, len(planLogs)) for _, datum := range planLogs { has := false for _, id := range planIds { diff --git a/internal/app/service/pig_batch_service.go b/internal/app/service/pig_batch_service.go index b0ca12c..8702bbf 100644 --- a/internal/app/service/pig_batch_service.go +++ b/internal/app/service/pig_batch_service.go @@ -12,35 +12,35 @@ import ( // PigBatchService 接口定义保持不变,继续作为应用层对外的契约。 type PigBatchService interface { - CreatePigBatch(ctx context.Context, operatorID uint, dto *dto.PigBatchCreateDTO) (*dto.PigBatchResponseDTO, error) - GetPigBatch(ctx context.Context, id uint) (*dto.PigBatchResponseDTO, error) - UpdatePigBatch(ctx context.Context, id uint, dto *dto.PigBatchUpdateDTO) (*dto.PigBatchResponseDTO, error) - DeletePigBatch(ctx context.Context, id uint) error + CreatePigBatch(ctx context.Context, operatorID uint32, dto *dto.PigBatchCreateDTO) (*dto.PigBatchResponseDTO, error) + GetPigBatch(ctx context.Context, id uint32) (*dto.PigBatchResponseDTO, error) + UpdatePigBatch(ctx context.Context, id uint32, dto *dto.PigBatchUpdateDTO) (*dto.PigBatchResponseDTO, error) + DeletePigBatch(ctx context.Context, id uint32) error ListPigBatches(ctx context.Context, isActive *bool) ([]*dto.PigBatchResponseDTO, error) // Pig Pen Management - AssignEmptyPensToBatch(ctx context.Context, batchID uint, penIDs []uint, operatorID uint) error - ReclassifyPenToNewBatch(ctx context.Context, fromBatchID uint, toBatchID uint, penID uint, operatorID uint, remarks string) error - RemoveEmptyPenFromBatch(ctx context.Context, batchID uint, penID uint) error - MovePigsIntoPen(ctx context.Context, batchID uint, toPenID uint, quantity int, operatorID uint, remarks string) error + AssignEmptyPensToBatch(ctx context.Context, batchID uint32, penIDs []uint32, operatorID uint32) error + ReclassifyPenToNewBatch(ctx context.Context, fromBatchID uint32, toBatchID uint32, penID uint32, operatorID uint32, remarks string) error + RemoveEmptyPenFromBatch(ctx context.Context, batchID uint32, penID uint32) error + MovePigsIntoPen(ctx context.Context, batchID uint32, toPenID uint32, quantity int, operatorID uint32, remarks string) error // Trade Sub-service - SellPigs(ctx context.Context, batchID uint, penID uint, quantity int, unitPrice float32, tatalPrice float32, traderName string, tradeDate time.Time, remarks string, operatorID uint) error - BuyPigs(ctx context.Context, batchID uint, penID uint, quantity int, unitPrice float32, tatalPrice float32, traderName string, tradeDate time.Time, remarks string, operatorID uint) error + SellPigs(ctx context.Context, batchID uint32, penID uint32, quantity int, unitPrice float32, tatalPrice float32, traderName string, tradeDate time.Time, remarks string, operatorID uint32) error + BuyPigs(ctx context.Context, batchID uint32, penID uint32, quantity int, unitPrice float32, tatalPrice float32, traderName string, tradeDate time.Time, remarks string, operatorID uint32) error // Transfer Sub-service - TransferPigsAcrossBatches(ctx context.Context, sourceBatchID uint, destBatchID uint, fromPenID uint, toPenID uint, quantity uint, operatorID uint, remarks string) error - TransferPigsWithinBatch(ctx context.Context, batchID uint, fromPenID uint, toPenID uint, quantity uint, operatorID uint, remarks string) error + TransferPigsAcrossBatches(ctx context.Context, sourceBatchID uint32, destBatchID uint32, fromPenID uint32, toPenID uint32, quantity uint32, operatorID uint32, remarks string) error + TransferPigsWithinBatch(ctx context.Context, batchID uint32, fromPenID uint32, toPenID uint32, quantity uint32, operatorID uint32, remarks string) error // Sick Pig Management - RecordSickPigs(ctx context.Context, operatorID uint, batchID uint, penID uint, quantity int, treatmentLocation models.PigBatchSickPigTreatmentLocation, happenedAt time.Time, remarks string) error - RecordSickPigRecovery(ctx context.Context, operatorID uint, batchID uint, penID uint, quantity int, treatmentLocation models.PigBatchSickPigTreatmentLocation, happenedAt time.Time, remarks string) error - RecordSickPigDeath(ctx context.Context, operatorID uint, batchID uint, penID uint, quantity int, treatmentLocation models.PigBatchSickPigTreatmentLocation, happenedAt time.Time, remarks string) error - RecordSickPigCull(ctx context.Context, operatorID uint, batchID uint, penID uint, quantity int, treatmentLocation models.PigBatchSickPigTreatmentLocation, happenedAt time.Time, remarks string) error + RecordSickPigs(ctx context.Context, operatorID uint32, batchID uint32, penID uint32, quantity int, treatmentLocation models.PigBatchSickPigTreatmentLocation, happenedAt time.Time, remarks string) error + RecordSickPigRecovery(ctx context.Context, operatorID uint32, batchID uint32, penID uint32, quantity int, treatmentLocation models.PigBatchSickPigTreatmentLocation, happenedAt time.Time, remarks string) error + RecordSickPigDeath(ctx context.Context, operatorID uint32, batchID uint32, penID uint32, quantity int, treatmentLocation models.PigBatchSickPigTreatmentLocation, happenedAt time.Time, remarks string) error + RecordSickPigCull(ctx context.Context, operatorID uint32, batchID uint32, penID uint32, quantity int, treatmentLocation models.PigBatchSickPigTreatmentLocation, happenedAt time.Time, remarks string) error // Normal Pig Management - RecordDeath(ctx context.Context, operatorID uint, batchID uint, penID uint, quantity int, happenedAt time.Time, remarks string) error - RecordCull(ctx context.Context, operatorID uint, batchID uint, penID uint, quantity int, happenedAt time.Time, remarks string) error + RecordDeath(ctx context.Context, operatorID uint32, batchID uint32, penID uint32, quantity int, happenedAt time.Time, remarks string) error + RecordCull(ctx context.Context, operatorID uint32, batchID uint32, penID uint32, quantity int, happenedAt time.Time, remarks string) error } // pigBatchService 的实现现在依赖于领域服务接口。 @@ -79,7 +79,7 @@ func (s *pigBatchService) toPigBatchResponseDTO(batch *models.PigBatch, currentT } // CreatePigBatch 现在将请求委托给领域服务处理。 -func (s *pigBatchService) CreatePigBatch(ctx context.Context, operatorID uint, dto *dto.PigBatchCreateDTO) (*dto.PigBatchResponseDTO, error) { +func (s *pigBatchService) CreatePigBatch(ctx context.Context, operatorID uint32, dto *dto.PigBatchCreateDTO) (*dto.PigBatchResponseDTO, error) { serviceCtx, logger := logs.Trace(ctx, s.ctx, "CreatePigBatch") // 1. DTO -> 领域模型 batch := &models.PigBatch{ @@ -102,7 +102,7 @@ func (s *pigBatchService) CreatePigBatch(ctx context.Context, operatorID uint, d } // GetPigBatch 从领域服务获取数据并转换为DTO,同时处理错误转换。 -func (s *pigBatchService) GetPigBatch(ctx context.Context, id uint) (*dto.PigBatchResponseDTO, error) { +func (s *pigBatchService) GetPigBatch(ctx context.Context, id uint32) (*dto.PigBatchResponseDTO, error) { serviceCtx, logger := logs.Trace(ctx, s.ctx, "GetPigBatch") batch, err := s.domainService.GetPigBatch(serviceCtx, id) if err != nil { @@ -123,7 +123,7 @@ func (s *pigBatchService) GetPigBatch(ctx context.Context, id uint) (*dto.PigBat } // UpdatePigBatch 协调获取、更新和保存的流程,并处理错误转换。 -func (s *pigBatchService) UpdatePigBatch(ctx context.Context, id uint, dto *dto.PigBatchUpdateDTO) (*dto.PigBatchResponseDTO, error) { +func (s *pigBatchService) UpdatePigBatch(ctx context.Context, id uint32, dto *dto.PigBatchUpdateDTO) (*dto.PigBatchResponseDTO, error) { serviceCtx, logger := logs.Trace(ctx, s.ctx, "UpdatePigBatch") // 1. 先获取最新的领域模型 existingBatch, err := s.domainService.GetPigBatch(serviceCtx, id) @@ -176,7 +176,7 @@ func (s *pigBatchService) UpdatePigBatch(ctx context.Context, id uint, dto *dto. } // DeletePigBatch 将删除操作委托给领域服务,并转换领域错误为应用层错误。 -func (s *pigBatchService) DeletePigBatch(ctx context.Context, id uint) error { +func (s *pigBatchService) DeletePigBatch(ctx context.Context, id uint32) error { serviceCtx, logger := logs.Trace(ctx, s.ctx, "DeletePigBatch") err := s.domainService.DeletePigBatch(serviceCtx, id) if err != nil { @@ -214,7 +214,7 @@ func (s *pigBatchService) ListPigBatches(ctx context.Context, isActive *bool) ([ } // AssignEmptyPensToBatch 委托给领域服务 -func (s *pigBatchService) AssignEmptyPensToBatch(ctx context.Context, batchID uint, penIDs []uint, operatorID uint) error { +func (s *pigBatchService) AssignEmptyPensToBatch(ctx context.Context, batchID uint32, penIDs []uint32, operatorID uint32) error { serviceCtx, logger := logs.Trace(ctx, s.ctx, "AssignEmptyPensToBatch") err := s.domainService.AssignEmptyPensToBatch(serviceCtx, batchID, penIDs, operatorID) if err != nil { @@ -225,7 +225,7 @@ func (s *pigBatchService) AssignEmptyPensToBatch(ctx context.Context, batchID ui } // ReclassifyPenToNewBatch 委托给领域服务 -func (s *pigBatchService) ReclassifyPenToNewBatch(ctx context.Context, fromBatchID uint, toBatchID uint, penID uint, operatorID uint, remarks string) error { +func (s *pigBatchService) ReclassifyPenToNewBatch(ctx context.Context, fromBatchID uint32, toBatchID uint32, penID uint32, operatorID uint32, remarks string) error { serviceCtx, logger := logs.Trace(ctx, s.ctx, "ReclassifyPenToNewBatch") err := s.domainService.ReclassifyPenToNewBatch(serviceCtx, fromBatchID, toBatchID, penID, operatorID, remarks) if err != nil { @@ -236,7 +236,7 @@ func (s *pigBatchService) ReclassifyPenToNewBatch(ctx context.Context, fromBatch } // RemoveEmptyPenFromBatch 委托给领域服务 -func (s *pigBatchService) RemoveEmptyPenFromBatch(ctx context.Context, batchID uint, penID uint) error { +func (s *pigBatchService) RemoveEmptyPenFromBatch(ctx context.Context, batchID uint32, penID uint32) error { serviceCtx, logger := logs.Trace(ctx, s.ctx, "RemoveEmptyPenFromBatch") err := s.domainService.RemoveEmptyPenFromBatch(serviceCtx, batchID, penID) if err != nil { @@ -247,7 +247,7 @@ func (s *pigBatchService) RemoveEmptyPenFromBatch(ctx context.Context, batchID u } // MovePigsIntoPen 委托给领域服务 -func (s *pigBatchService) MovePigsIntoPen(ctx context.Context, batchID uint, toPenID uint, quantity int, operatorID uint, remarks string) error { +func (s *pigBatchService) MovePigsIntoPen(ctx context.Context, batchID uint32, toPenID uint32, quantity int, operatorID uint32, remarks string) error { serviceCtx, logger := logs.Trace(ctx, s.ctx, "MovePigsIntoPen") err := s.domainService.MovePigsIntoPen(serviceCtx, batchID, toPenID, quantity, operatorID, remarks) if err != nil { @@ -258,7 +258,7 @@ func (s *pigBatchService) MovePigsIntoPen(ctx context.Context, batchID uint, toP } // SellPigs 委托给领域服务 -func (s *pigBatchService) SellPigs(ctx context.Context, batchID uint, penID uint, quantity int, unitPrice float32, tatalPrice float32, traderName string, tradeDate time.Time, remarks string, operatorID uint) error { +func (s *pigBatchService) SellPigs(ctx context.Context, batchID uint32, penID uint32, quantity int, unitPrice float32, tatalPrice float32, traderName string, tradeDate time.Time, remarks string, operatorID uint32) error { serviceCtx, logger := logs.Trace(ctx, s.ctx, "SellPigs") err := s.domainService.SellPigs(serviceCtx, batchID, penID, quantity, unitPrice, tatalPrice, traderName, tradeDate, remarks, operatorID) if err != nil { @@ -269,7 +269,7 @@ func (s *pigBatchService) SellPigs(ctx context.Context, batchID uint, penID uint } // BuyPigs 委托给领域服务 -func (s *pigBatchService) BuyPigs(ctx context.Context, batchID uint, penID uint, quantity int, unitPrice float32, tatalPrice float32, traderName string, tradeDate time.Time, remarks string, operatorID uint) error { +func (s *pigBatchService) BuyPigs(ctx context.Context, batchID uint32, penID uint32, quantity int, unitPrice float32, tatalPrice float32, traderName string, tradeDate time.Time, remarks string, operatorID uint32) error { serviceCtx, logger := logs.Trace(ctx, s.ctx, "BuyPigs") err := s.domainService.BuyPigs(serviceCtx, batchID, penID, quantity, unitPrice, tatalPrice, traderName, tradeDate, remarks, operatorID) if err != nil { @@ -280,7 +280,7 @@ func (s *pigBatchService) BuyPigs(ctx context.Context, batchID uint, penID uint, } // TransferPigsAcrossBatches 委托给领域服务 -func (s *pigBatchService) TransferPigsAcrossBatches(ctx context.Context, sourceBatchID uint, destBatchID uint, fromPenID uint, toPenID uint, quantity uint, operatorID uint, remarks string) error { +func (s *pigBatchService) TransferPigsAcrossBatches(ctx context.Context, sourceBatchID uint32, destBatchID uint32, fromPenID uint32, toPenID uint32, quantity uint32, operatorID uint32, remarks string) error { serviceCtx, logger := logs.Trace(ctx, s.ctx, "TransferPigsAcrossBatches") err := s.domainService.TransferPigsAcrossBatches(serviceCtx, sourceBatchID, destBatchID, fromPenID, toPenID, quantity, operatorID, remarks) if err != nil { @@ -291,7 +291,7 @@ func (s *pigBatchService) TransferPigsAcrossBatches(ctx context.Context, sourceB } // TransferPigsWithinBatch 委托给领域服务 -func (s *pigBatchService) TransferPigsWithinBatch(ctx context.Context, batchID uint, fromPenID uint, toPenID uint, quantity uint, operatorID uint, remarks string) error { +func (s *pigBatchService) TransferPigsWithinBatch(ctx context.Context, batchID uint32, fromPenID uint32, toPenID uint32, quantity uint32, operatorID uint32, remarks string) error { serviceCtx, logger := logs.Trace(ctx, s.ctx, "TransferPigsWithinBatch") err := s.domainService.TransferPigsWithinBatch(serviceCtx, batchID, fromPenID, toPenID, quantity, operatorID, remarks) if err != nil { @@ -302,7 +302,7 @@ func (s *pigBatchService) TransferPigsWithinBatch(ctx context.Context, batchID u } // RecordSickPigs 委托给领域服务 -func (s *pigBatchService) RecordSickPigs(ctx context.Context, operatorID uint, batchID uint, penID uint, quantity int, treatmentLocation models.PigBatchSickPigTreatmentLocation, happenedAt time.Time, remarks string) error { +func (s *pigBatchService) RecordSickPigs(ctx context.Context, operatorID uint32, batchID uint32, penID uint32, quantity int, treatmentLocation models.PigBatchSickPigTreatmentLocation, happenedAt time.Time, remarks string) error { serviceCtx, logger := logs.Trace(ctx, s.ctx, "RecordSickPigs") err := s.domainService.RecordSickPigs(serviceCtx, operatorID, batchID, penID, quantity, treatmentLocation, happenedAt, remarks) if err != nil { @@ -313,7 +313,7 @@ func (s *pigBatchService) RecordSickPigs(ctx context.Context, operatorID uint, b } // RecordSickPigRecovery 委托给领域服务 -func (s *pigBatchService) RecordSickPigRecovery(ctx context.Context, operatorID uint, batchID uint, penID uint, quantity int, treatmentLocation models.PigBatchSickPigTreatmentLocation, happenedAt time.Time, remarks string) error { +func (s *pigBatchService) RecordSickPigRecovery(ctx context.Context, operatorID uint32, batchID uint32, penID uint32, quantity int, treatmentLocation models.PigBatchSickPigTreatmentLocation, happenedAt time.Time, remarks string) error { serviceCtx, logger := logs.Trace(ctx, s.ctx, "RecordSickPigRecovery") err := s.domainService.RecordSickPigRecovery(serviceCtx, operatorID, batchID, penID, quantity, treatmentLocation, happenedAt, remarks) if err != nil { @@ -324,7 +324,7 @@ func (s *pigBatchService) RecordSickPigRecovery(ctx context.Context, operatorID } // RecordSickPigDeath 委托给领域服务 -func (s *pigBatchService) RecordSickPigDeath(ctx context.Context, operatorID uint, batchID uint, penID uint, quantity int, treatmentLocation models.PigBatchSickPigTreatmentLocation, happenedAt time.Time, remarks string) error { +func (s *pigBatchService) RecordSickPigDeath(ctx context.Context, operatorID uint32, batchID uint32, penID uint32, quantity int, treatmentLocation models.PigBatchSickPigTreatmentLocation, happenedAt time.Time, remarks string) error { serviceCtx, logger := logs.Trace(ctx, s.ctx, "RecordSickPigDeath") err := s.domainService.RecordSickPigDeath(serviceCtx, operatorID, batchID, penID, quantity, treatmentLocation, happenedAt, remarks) if err != nil { @@ -335,7 +335,7 @@ func (s *pigBatchService) RecordSickPigDeath(ctx context.Context, operatorID uin } // RecordSickPigCull 委托给领域服务 -func (s *pigBatchService) RecordSickPigCull(ctx context.Context, operatorID uint, batchID uint, penID uint, quantity int, treatmentLocation models.PigBatchSickPigTreatmentLocation, happenedAt time.Time, remarks string) error { +func (s *pigBatchService) RecordSickPigCull(ctx context.Context, operatorID uint32, batchID uint32, penID uint32, quantity int, treatmentLocation models.PigBatchSickPigTreatmentLocation, happenedAt time.Time, remarks string) error { serviceCtx, logger := logs.Trace(ctx, s.ctx, "RecordSickPigCull") err := s.domainService.RecordSickPigCull(serviceCtx, operatorID, batchID, penID, quantity, treatmentLocation, happenedAt, remarks) if err != nil { @@ -346,7 +346,7 @@ func (s *pigBatchService) RecordSickPigCull(ctx context.Context, operatorID uint } // RecordDeath 委托给领域服务 -func (s *pigBatchService) RecordDeath(ctx context.Context, operatorID uint, batchID uint, penID uint, quantity int, happenedAt time.Time, remarks string) error { +func (s *pigBatchService) RecordDeath(ctx context.Context, operatorID uint32, batchID uint32, penID uint32, quantity int, happenedAt time.Time, remarks string) error { serviceCtx, logger := logs.Trace(ctx, s.ctx, "RecordDeath") err := s.domainService.RecordDeath(serviceCtx, operatorID, batchID, penID, quantity, happenedAt, remarks) if err != nil { @@ -357,7 +357,7 @@ func (s *pigBatchService) RecordDeath(ctx context.Context, operatorID uint, batc } // RecordCull 委托给领域服务 -func (s *pigBatchService) RecordCull(ctx context.Context, operatorID uint, batchID uint, penID uint, quantity int, happenedAt time.Time, remarks string) error { +func (s *pigBatchService) RecordCull(ctx context.Context, operatorID uint32, batchID uint32, penID uint32, quantity int, happenedAt time.Time, remarks string) error { serviceCtx, logger := logs.Trace(ctx, s.ctx, "RecordCull") err := s.domainService.RecordCull(serviceCtx, operatorID, batchID, penID, quantity, happenedAt, remarks) if err != nil { diff --git a/internal/app/service/pig_farm_service.go b/internal/app/service/pig_farm_service.go index 4ea98f3..ba85089 100644 --- a/internal/app/service/pig_farm_service.go +++ b/internal/app/service/pig_farm_service.go @@ -18,19 +18,19 @@ import ( type PigFarmService interface { // PigHouse methods CreatePigHouse(ctx context.Context, name, description string) (*dto.PigHouseResponse, error) - GetPigHouseByID(ctx context.Context, id uint) (*dto.PigHouseResponse, error) + GetPigHouseByID(ctx context.Context, id uint32) (*dto.PigHouseResponse, error) ListPigHouses(ctx context.Context) ([]dto.PigHouseResponse, error) - UpdatePigHouse(ctx context.Context, id uint, name, description string) (*dto.PigHouseResponse, error) - DeletePigHouse(ctx context.Context, id uint) error + UpdatePigHouse(ctx context.Context, id uint32, name, description string) (*dto.PigHouseResponse, error) + DeletePigHouse(ctx context.Context, id uint32) error // Pen methods - CreatePen(ctx context.Context, penNumber string, houseID uint, capacity int) (*dto.PenResponse, error) - GetPenByID(ctx context.Context, id uint) (*dto.PenResponse, error) + CreatePen(ctx context.Context, penNumber string, houseID uint32, capacity int) (*dto.PenResponse, error) + GetPenByID(ctx context.Context, id uint32) (*dto.PenResponse, error) ListPens(ctx context.Context) ([]*dto.PenResponse, error) - UpdatePen(ctx context.Context, id uint, penNumber string, houseID uint, capacity int, status models.PenStatus) (*dto.PenResponse, error) - DeletePen(ctx context.Context, id uint) error + UpdatePen(ctx context.Context, id uint32, penNumber string, houseID uint32, capacity int, status models.PenStatus) (*dto.PenResponse, error) + DeletePen(ctx context.Context, id uint32) error // UpdatePenStatus 更新猪栏状态 - UpdatePenStatus(ctx context.Context, id uint, newStatus models.PenStatus) (*dto.PenResponse, error) + UpdatePenStatus(ctx context.Context, id uint32, newStatus models.PenStatus) (*dto.PenResponse, error) } type pigFarmService struct { @@ -79,7 +79,7 @@ func (s *pigFarmService) CreatePigHouse(ctx context.Context, name, description s }, nil } -func (s *pigFarmService) GetPigHouseByID(ctx context.Context, id uint) (*dto.PigHouseResponse, error) { +func (s *pigFarmService) GetPigHouseByID(ctx context.Context, id uint32) (*dto.PigHouseResponse, error) { serviceCtx := logs.AddFuncName(ctx, s.ctx, "GetPigHouseByID") house, err := s.farmRepository.GetPigHouseByID(serviceCtx, id) if err != nil { @@ -109,10 +109,10 @@ func (s *pigFarmService) ListPigHouses(ctx context.Context) ([]dto.PigHouseRespo return resp, nil } -func (s *pigFarmService) UpdatePigHouse(ctx context.Context, id uint, name, description string) (*dto.PigHouseResponse, error) { +func (s *pigFarmService) UpdatePigHouse(ctx context.Context, id uint32, name, description string) (*dto.PigHouseResponse, error) { serviceCtx := logs.AddFuncName(ctx, s.ctx, "UpdatePigHouse") house := &models.PigHouse{ - Model: gorm.Model{ID: id}, + Model: models.Model{ID: id}, Name: name, Description: description, } @@ -135,7 +135,7 @@ func (s *pigFarmService) UpdatePigHouse(ctx context.Context, id uint, name, desc }, nil } -func (s *pigFarmService) DeletePigHouse(ctx context.Context, id uint) error { +func (s *pigFarmService) DeletePigHouse(ctx context.Context, id uint32) error { serviceCtx := logs.AddFuncName(ctx, s.ctx, "DeletePigHouse") // 业务逻辑:检查猪舍是否包含猪栏 penCount, err := s.farmRepository.CountPensInHouse(serviceCtx, id) @@ -159,7 +159,7 @@ func (s *pigFarmService) DeletePigHouse(ctx context.Context, id uint) error { // --- Pen Implementation --- -func (s *pigFarmService) CreatePen(ctx context.Context, penNumber string, houseID uint, capacity int) (*dto.PenResponse, error) { +func (s *pigFarmService) CreatePen(ctx context.Context, penNumber string, houseID uint32, capacity int) (*dto.PenResponse, error) { serviceCtx := logs.AddFuncName(ctx, s.ctx, "CreatePen") // 业务逻辑:验证所属猪舍是否存在 _, err := s.farmRepository.GetPigHouseByID(serviceCtx, houseID) @@ -189,7 +189,7 @@ func (s *pigFarmService) CreatePen(ctx context.Context, penNumber string, houseI }, nil } -func (s *pigFarmService) GetPenByID(ctx context.Context, id uint) (*dto.PenResponse, error) { +func (s *pigFarmService) GetPenByID(ctx context.Context, id uint32) (*dto.PenResponse, error) { serviceCtx, logger := logs.Trace(ctx, s.ctx, "GetPenByID") pen, err := s.penRepository.GetPenByID(serviceCtx, id) if err != nil { @@ -251,7 +251,7 @@ func (s *pigFarmService) ListPens(ctx context.Context) ([]*dto.PenResponse, erro return response, nil } -func (s *pigFarmService) UpdatePen(ctx context.Context, id uint, penNumber string, houseID uint, capacity int, status models.PenStatus) (*dto.PenResponse, error) { +func (s *pigFarmService) UpdatePen(ctx context.Context, id uint32, penNumber string, houseID uint32, capacity int, status models.PenStatus) (*dto.PenResponse, error) { serviceCtx := logs.AddFuncName(ctx, s.ctx, "UpdatePen") // 业务逻辑:验证所属猪舍是否存在 _, err := s.farmRepository.GetPigHouseByID(serviceCtx, houseID) @@ -263,7 +263,7 @@ func (s *pigFarmService) UpdatePen(ctx context.Context, id uint, penNumber strin } pen := &models.Pen{ - Model: gorm.Model{ID: id}, + Model: models.Model{ID: id}, PenNumber: penNumber, HouseID: houseID, Capacity: capacity, @@ -291,7 +291,7 @@ func (s *pigFarmService) UpdatePen(ctx context.Context, id uint, penNumber strin }, nil } -func (s *pigFarmService) DeletePen(ctx context.Context, id uint) error { +func (s *pigFarmService) DeletePen(ctx context.Context, id uint32) error { serviceCtx := logs.AddFuncName(ctx, s.ctx, "DeletePen") // 业务逻辑:检查猪栏是否被活跃批次使用 pen, err := s.penRepository.GetPenByID(serviceCtx, id) @@ -327,7 +327,7 @@ func (s *pigFarmService) DeletePen(ctx context.Context, id uint) error { } // UpdatePenStatus 更新猪栏状态 -func (s *pigFarmService) UpdatePenStatus(ctx context.Context, id uint, newStatus models.PenStatus) (*dto.PenResponse, error) { +func (s *pigFarmService) UpdatePenStatus(ctx context.Context, id uint32, newStatus models.PenStatus) (*dto.PenResponse, error) { serviceCtx, logger := logs.Trace(ctx, s.ctx, "UpdatePenStatus") var updatedPen *models.Pen err := s.uow.ExecuteInTransaction(serviceCtx, func(tx *gorm.DB) error { diff --git a/internal/app/service/plan_service.go b/internal/app/service/plan_service.go index 8601487..3d74823 100644 --- a/internal/app/service/plan_service.go +++ b/internal/app/service/plan_service.go @@ -16,17 +16,17 @@ type PlanService interface { // CreatePlan 创建一个新的计划 CreatePlan(ctx context.Context, req *dto.CreatePlanRequest) (*dto.PlanResponse, error) // GetPlanByID 根据ID获取计划详情 - GetPlanByID(ctx context.Context, id uint) (*dto.PlanResponse, error) + GetPlanByID(ctx context.Context, id uint32) (*dto.PlanResponse, error) // ListPlans 获取计划列表,支持过滤和分页 ListPlans(ctx context.Context, query *dto.ListPlansQuery) (*dto.ListPlansResponse, error) // UpdatePlan 更新计划 - UpdatePlan(ctx context.Context, id uint, req *dto.UpdatePlanRequest) (*dto.PlanResponse, error) + UpdatePlan(ctx context.Context, id uint32, req *dto.UpdatePlanRequest) (*dto.PlanResponse, error) // DeletePlan 删除计划(软删除) - DeletePlan(ctx context.Context, id uint) error + DeletePlan(ctx context.Context, id uint32) error // StartPlan 启动计划 - StartPlan(ctx context.Context, id uint) error + StartPlan(ctx context.Context, id uint32) error // StopPlan 停止计划 - StopPlan(ctx context.Context, id uint) error + StopPlan(ctx context.Context, id uint32) error } // planService 是 PlanService 接口的实现 @@ -77,7 +77,7 @@ func (s *planService) CreatePlan(ctx context.Context, req *dto.CreatePlanRequest } // GetPlanByID 根据ID获取计划详情 -func (s *planService) GetPlanByID(ctx context.Context, id uint) (*dto.PlanResponse, error) { +func (s *planService) GetPlanByID(ctx context.Context, id uint32) (*dto.PlanResponse, error) { serviceCtx, logger := logs.Trace(ctx, s.ctx, "GetPlanByID") const actionType = "应用服务层:获取计划详情" @@ -135,7 +135,7 @@ func (s *planService) ListPlans(ctx context.Context, query *dto.ListPlansQuery) } // UpdatePlan 更新计划 -func (s *planService) UpdatePlan(ctx context.Context, id uint, req *dto.UpdatePlanRequest) (*dto.PlanResponse, error) { +func (s *planService) UpdatePlan(ctx context.Context, id uint32, req *dto.UpdatePlanRequest) (*dto.PlanResponse, error) { serviceCtx, logger := logs.Trace(ctx, s.ctx, "UpdatePlan") const actionType = "应用服务层:更新计划" @@ -166,7 +166,7 @@ func (s *planService) UpdatePlan(ctx context.Context, id uint, req *dto.UpdatePl } // DeletePlan 删除计划(软删除) -func (s *planService) DeletePlan(ctx context.Context, id uint) error { +func (s *planService) DeletePlan(ctx context.Context, id uint32) error { serviceCtx, logger := logs.Trace(ctx, s.ctx, "DeletePlan") const actionType = "应用服务层:删除计划" @@ -182,7 +182,7 @@ func (s *planService) DeletePlan(ctx context.Context, id uint) error { } // StartPlan 启动计划 -func (s *planService) StartPlan(ctx context.Context, id uint) error { +func (s *planService) StartPlan(ctx context.Context, id uint32) error { serviceCtx, logger := logs.Trace(ctx, s.ctx, "StartPlan") const actionType = "应用服务层:启动计划" @@ -198,7 +198,7 @@ func (s *planService) StartPlan(ctx context.Context, id uint) error { } // StopPlan 停止计划 -func (s *planService) StopPlan(ctx context.Context, id uint) error { +func (s *planService) StopPlan(ctx context.Context, id uint32) error { serviceCtx, logger := logs.Trace(ctx, s.ctx, "StopPlan") const actionType = "应用服务层:停止计划" diff --git a/internal/app/service/threshold_alarm_service.go b/internal/app/service/threshold_alarm_service.go index 19a81ac..834a003 100644 --- a/internal/app/service/threshold_alarm_service.go +++ b/internal/app/service/threshold_alarm_service.go @@ -18,9 +18,9 @@ import ( // 该服务负责管理阈值告警任务的配置,并将其与计划进行联动。 type ThresholdAlarmService interface { // SnoozeThresholdAlarm 忽略一个阈值告警,或更新其忽略时间。 - SnoozeThresholdAlarm(ctx context.Context, alarmID uint, durationMinutes uint) error + SnoozeThresholdAlarm(ctx context.Context, alarmID uint32, durationMinutes uint32) error // CancelSnoozeThresholdAlarm 取消对一个阈值告警的忽略状态。 - CancelSnoozeThresholdAlarm(ctx context.Context, alarmID uint) error + CancelSnoozeThresholdAlarm(ctx context.Context, alarmID uint32) error // ListActiveAlarms 批量查询活跃告警。 ListActiveAlarms(ctx context.Context, req *dto.ListActiveAlarmRequest) (*dto.ListActiveAlarmResponse, error) // ListHistoricalAlarms 批量查询历史告警。 @@ -35,7 +35,7 @@ type ThresholdAlarmService interface { // DeleteDeviceThresholdAlarm 删除一个设备阈值告警。 DeleteDeviceThresholdAlarm(ctx context.Context, taskID int, req *dto.DeleteDeviceThresholdAlarmDTO) error // DeleteDeviceThresholdAlarmByDeviceID 实现了根据设备ID删除一个设备下所有设备阈值告警的逻辑。 - DeleteDeviceThresholdAlarmByDeviceID(ctx context.Context, deviceID uint) error + DeleteDeviceThresholdAlarmByDeviceID(ctx context.Context, deviceID uint32) error // CreateAreaThresholdAlarm 创建一个区域阈值告警。 CreateAreaThresholdAlarm(ctx context.Context, req *dto.CreateAreaThresholdAlarmDTO) error @@ -46,7 +46,7 @@ type ThresholdAlarmService interface { // DeleteAreaThresholdAlarm 实现了删除一个区域阈值告警的逻辑。 DeleteAreaThresholdAlarm(ctx context.Context, taskID int) error // DeleteAreaThresholdAlarmByAreaControllerID 实现了根据区域ID删除一个区域下所有区域阈值告警的逻辑。 - DeleteAreaThresholdAlarmByAreaControllerID(ctx context.Context, areaControllerID uint) error + DeleteAreaThresholdAlarmByAreaControllerID(ctx context.Context, areaControllerID uint32) error } // thresholdAlarmService 是 ThresholdAlarmService 接口的具体实现。 @@ -82,13 +82,13 @@ func NewThresholdAlarmService(ctx context.Context, } // SnoozeThresholdAlarm 实现了忽略阈值告警的逻辑。 -func (s *thresholdAlarmService) SnoozeThresholdAlarm(ctx context.Context, alarmID uint, durationMinutes uint) error { +func (s *thresholdAlarmService) SnoozeThresholdAlarm(ctx context.Context, alarmID uint32, durationMinutes uint32) error { serviceCtx := logs.AddFuncName(ctx, s.ctx, "SnoozeThresholdAlarm") return s.alarmService.SnoozeAlarm(serviceCtx, alarmID, time.Duration(durationMinutes)*time.Minute) } // CancelSnoozeThresholdAlarm 实现了取消忽略阈值告警的逻辑。 -func (s *thresholdAlarmService) CancelSnoozeThresholdAlarm(ctx context.Context, alarmID uint) error { +func (s *thresholdAlarmService) CancelSnoozeThresholdAlarm(ctx context.Context, alarmID uint32) error { serviceCtx := logs.AddFuncName(ctx, s.ctx, "CancelSnoozeThresholdAlarm") return s.alarmService.CancelAlarmSnooze(serviceCtx, alarmID) } @@ -169,7 +169,7 @@ func (s *thresholdAlarmService) CreateDeviceThresholdAlarm(ctx context.Context, } case models.TaskTypeAreaCollectorThresholdCheck: // 向区域阈值检查任务过滤列表中添加该设备 params := task.AreaThresholdCheckParams{ - ExcludeDeviceIDs: []uint{}, + ExcludeDeviceIDs: []uint32{}, } err = t.ParseParameters(¶ms) if err != nil { @@ -375,7 +375,7 @@ func (s *thresholdAlarmService) DeleteDeviceThresholdAlarm(ctx context.Context, } // DeleteDeviceThresholdAlarmByDeviceID 实现了根据设备ID删除一个设备下所有设备阈值告警的逻辑。 -func (s *thresholdAlarmService) DeleteDeviceThresholdAlarmByDeviceID(ctx context.Context, deviceID uint) error { +func (s *thresholdAlarmService) DeleteDeviceThresholdAlarmByDeviceID(ctx context.Context, deviceID uint32) error { serviceCtx, logger := logs.Trace(ctx, s.ctx, "DeleteDeviceThresholdAlarmByDeviceID") tasks, err := s.planRepo.ListTasksByDeviceID(serviceCtx, deviceID) if err != nil { @@ -462,13 +462,13 @@ func (s *thresholdAlarmService) CreateAreaThresholdAlarm(ctx context.Context, re if err != nil { return fmt.Errorf("获取区域 %d 下的设备列表失败: %w", req.AreaControllerID, err) } - devicesInAreaMap := make(map[uint]struct{}, len(devicesInArea)) + devicesInAreaMap := make(map[uint32]struct{}, len(devicesInArea)) for _, device := range devicesInArea { devicesInAreaMap[device.ID] = struct{}{} } // 3. 遍历计划,检查存在性并收集需要排除的设备ID - var excludeDeviceIDs []uint + var excludeDeviceIDs []uint32 for _, t := range plan.Tasks { switch t.Type { case models.TaskTypeAreaCollectorThresholdCheck: @@ -631,7 +631,7 @@ func (s *thresholdAlarmService) DeleteAreaThresholdAlarm(ctx context.Context, ta } // DeleteAreaThresholdAlarmByAreaControllerID 实现了根据区域ID删除一个区域下所有区域阈值告警的逻辑。 -func (s *thresholdAlarmService) DeleteAreaThresholdAlarmByAreaControllerID(ctx context.Context, areaControllerID uint) error { +func (s *thresholdAlarmService) DeleteAreaThresholdAlarmByAreaControllerID(ctx context.Context, areaControllerID uint32) error { serviceCtx, logger := logs.Trace(ctx, s.ctx, "DeleteAreaThresholdAlarmByAreaControllerID") // 1. 获取系统健康检查计划 diff --git a/internal/app/service/user_service.go b/internal/app/service/user_service.go index 3efabc8..b9281e9 100644 --- a/internal/app/service/user_service.go +++ b/internal/app/service/user_service.go @@ -18,7 +18,7 @@ import ( type UserService interface { CreateUser(ctx context.Context, req *dto.CreateUserRequest) (*dto.CreateUserResponse, error) Login(ctx context.Context, req *dto.LoginRequest) (*dto.LoginResponse, error) - SendTestNotification(ctx context.Context, userID uint, req *dto.SendTestNotificationRequest) error + SendTestNotification(ctx context.Context, userID uint32, req *dto.SendTestNotificationRequest) error } // userService 实现了 UserService 接口 @@ -103,7 +103,7 @@ func (s *userService) Login(ctx context.Context, req *dto.LoginRequest) (*dto.Lo } // SendTestNotification 发送测试通知 -func (s *userService) SendTestNotification(ctx context.Context, userID uint, req *dto.SendTestNotificationRequest) error { +func (s *userService) SendTestNotification(ctx context.Context, userID uint32, req *dto.SendTestNotificationRequest) error { serviceCtx, logger := logs.Trace(ctx, s.ctx, "SendTestNotification") err := s.notifyService.SendTestMessage(serviceCtx, userID, req.Type) if err != nil { diff --git a/internal/app/webhook/chirp_stack.go b/internal/app/webhook/chirp_stack.go index 8714d47..c3cf005 100644 --- a/internal/app/webhook/chirp_stack.go +++ b/internal/app/webhook/chirp_stack.go @@ -429,7 +429,7 @@ func (c *ChirpStackListener) handleIntegrationEvent(ctx context.Context, event * // sensorDeviceID: 实际产生传感器数据的普通设备的ID // sensorType: 传感器值的类型 (例如 models.SensorTypeTemperature) // data: 具体的传感器数据结构体实例 (例如 models.TemperatureData) -func (c *ChirpStackListener) recordSensorData(ctx context.Context, areaControllerID uint, sensorDeviceID uint, eventTime time.Time, sensorType models.SensorType, data interface{}) { +func (c *ChirpStackListener) recordSensorData(ctx context.Context, areaControllerID uint32, sensorDeviceID uint32, eventTime time.Time, sensorType models.SensorType, data interface{}) { reqCtx, logger := logs.Trace(ctx, c.ctx, "recordSensorData") // 1. 将传入的结构体序列化为 JSON jsonData, err := json.Marshal(data) diff --git a/internal/core/data_initializer.go b/internal/core/data_initializer.go index 9560aac..cfe4894 100644 --- a/internal/core/data_initializer.go +++ b/internal/core/data_initializer.go @@ -293,7 +293,7 @@ func (app *Application) cleanupStaleTasksAndLogs(ctx context.Context) error { } // 2. 收集所有受影响的唯一 PlanID - affectedPlanIDs := make(map[uint]struct{}) + affectedPlanIDs := make(map[uint32]struct{}) for _, log := range incompletePlanLogs { affectedPlanIDs[log.PlanID] = struct{}{} } diff --git a/internal/domain/alarm/alarm_service.go b/internal/domain/alarm/alarm_service.go index 661ba25..a542935 100644 --- a/internal/domain/alarm/alarm_service.go +++ b/internal/domain/alarm/alarm_service.go @@ -21,15 +21,15 @@ type AlarmService interface { // CloseAlarm 关闭一个活跃告警,将其归档到历史记录。 // 如果指定的告警当前不活跃,则不执行任何操作并返回 nil。 - CloseAlarm(ctx context.Context, sourceType models.AlarmSourceType, sourceID uint, alarmCode models.AlarmCode, resolveMethod string, resolvedBy *uint) error + CloseAlarm(ctx context.Context, sourceType models.AlarmSourceType, sourceID uint32, alarmCode models.AlarmCode, resolveMethod string, resolvedBy *uint32) error // SnoozeAlarm 忽略一个活跃告警,或更新其忽略时间。 // 如果告警不存在,将返回错误。 - SnoozeAlarm(ctx context.Context, alarmID uint, duration time.Duration) error + SnoozeAlarm(ctx context.Context, alarmID uint32, duration time.Duration) error // CancelAlarmSnooze 取消对一个告警的忽略状态。 // 如果告警不存在,或本就未被忽略,不执行任何操作并返回 nil。 - CancelAlarmSnooze(ctx context.Context, alarmID uint) error + CancelAlarmSnooze(ctx context.Context, alarmID uint32) error } // alarmService 是 AlarmService 接口的具体实现。 @@ -71,7 +71,7 @@ func (s *alarmService) CreateAlarmIfNotExists(ctx context.Context, newAlarm *mod } // CloseAlarm 实现了关闭告警并将其归档的逻辑。 -func (s *alarmService) CloseAlarm(ctx context.Context, sourceType models.AlarmSourceType, sourceID uint, alarmCode models.AlarmCode, resolveMethod string, resolvedBy *uint) error { +func (s *alarmService) CloseAlarm(ctx context.Context, sourceType models.AlarmSourceType, sourceID uint32, alarmCode models.AlarmCode, resolveMethod string, resolvedBy *uint32) error { serviceCtx, logger := logs.Trace(ctx, s.ctx, "CloseAlarm") // 1. 在事务外进行快速只读检查,避免不必要的事务开销 @@ -133,7 +133,7 @@ func (s *alarmService) CloseAlarm(ctx context.Context, sourceType models.AlarmSo } // SnoozeAlarm 忽略一个活跃告警,或更新其忽略时间。 -func (s *alarmService) SnoozeAlarm(ctx context.Context, alarmID uint, duration time.Duration) error { +func (s *alarmService) SnoozeAlarm(ctx context.Context, alarmID uint32, duration time.Duration) error { serviceCtx, logger := logs.Trace(ctx, s.ctx, "SnoozeAlarm") if duration <= 0 { @@ -156,7 +156,7 @@ func (s *alarmService) SnoozeAlarm(ctx context.Context, alarmID uint, duration t } // CancelAlarmSnooze 取消对一个告警的忽略状态。 -func (s *alarmService) CancelAlarmSnooze(ctx context.Context, alarmID uint) error { +func (s *alarmService) CancelAlarmSnooze(ctx context.Context, alarmID uint32) error { serviceCtx, logger := logs.Trace(ctx, s.ctx, "CancelAlarmSnooze") err := s.alarmRepo.UpdateIgnoreStatus(serviceCtx, alarmID, false, nil) diff --git a/internal/domain/device/device_service.go b/internal/domain/device/device_service.go index bd892dd..db445c0 100644 --- a/internal/domain/device/device_service.go +++ b/internal/domain/device/device_service.go @@ -28,7 +28,7 @@ type Service interface { Switch(ctx context.Context, device *models.Device, action DeviceAction) error // Collect 用于发起对指定区域主控下的多个设备的批量采集请求。 - Collect(ctx context.Context, areaControllerID uint, devicesToCollect []*models.Device) error + Collect(ctx context.Context, areaControllerID uint32, devicesToCollect []*models.Device) error } // 设备操作指令通用结构(最外层) diff --git a/internal/domain/device/general_device_service.go b/internal/domain/device/general_device_service.go index 1a33e1c..4364735 100644 --- a/internal/domain/device/general_device_service.go +++ b/internal/domain/device/general_device_service.go @@ -133,7 +133,7 @@ func (g *GeneralDeviceService) Switch(ctx context.Context, device *models.Device } // Collect 实现了 Service 接口,用于发起对指定区域主控下的多个设备的批量采集请求。 -func (g *GeneralDeviceService) Collect(ctx context.Context, areaControllerID uint, devicesToCollect []*models.Device) error { +func (g *GeneralDeviceService) Collect(ctx context.Context, areaControllerID uint32, devicesToCollect []*models.Device) error { serviceCtx, logger := logs.Trace(ctx, g.ctx, "Collect") if len(devicesToCollect) == 0 { logger.Info("待采集设备列表为空,无需执行采集任务。") @@ -150,7 +150,7 @@ func (g *GeneralDeviceService) Collect(ctx context.Context, areaControllerID uin } // 2. 准备采集任务列表 - var childDeviceIDs []uint + var childDeviceIDs []uint32 var collectTasks []*proto.CollectTask for _, dev := range devicesToCollect { diff --git a/internal/domain/notify/notify.go b/internal/domain/notify/notify.go index 53f1168..0c95842 100644 --- a/internal/domain/notify/notify.go +++ b/internal/domain/notify/notify.go @@ -16,13 +16,13 @@ import ( // Service 定义了通知领域的核心业务逻辑接口 type Service interface { // SendBatchAlarm 向一批用户发送告警通知。它会并发地为每个用户执行带故障转移的发送逻辑。 - SendBatchAlarm(ctx context.Context, userIDs []uint, content notify.AlarmContent) error + SendBatchAlarm(ctx context.Context, userIDs []uint32, content notify.AlarmContent) error // BroadcastAlarm 向所有用户发送告警通知。它会并发地为每个用户执行带故障转移的发送逻辑。 BroadcastAlarm(ctx context.Context, content notify.AlarmContent) error // SendTestMessage 向指定用户发送一条测试消息,用于手动验证特定通知渠道的配置。 - SendTestMessage(ctx context.Context, userID uint, notifierType models.NotifierType) error + SendTestMessage(ctx context.Context, userID uint32, notifierType models.NotifierType) error } // failoverService 是 Service 接口的实现,提供了故障转移功能 @@ -32,7 +32,7 @@ type failoverService struct { notifiers map[models.NotifierType]notify.Notifier primaryNotifier notify.Notifier failureThreshold int - failureCounters *sync.Map // 使用 sync.Map 来安全地并发读写失败计数, key: userID (uint), value: counter (int) + failureCounters *sync.Map // 使用 sync.Map 来安全地并发读写失败计数, key: userID (uint32), value: counter (int) notificationRepo repository.NotificationRepository } @@ -67,7 +67,7 @@ func NewFailoverService( } // SendBatchAlarm 实现了向多个用户并发发送告警的功能 -func (s *failoverService) SendBatchAlarm(ctx context.Context, userIDs []uint, content notify.AlarmContent) error { +func (s *failoverService) SendBatchAlarm(ctx context.Context, userIDs []uint32, content notify.AlarmContent) error { serviceCtx, logger := logs.Trace(ctx, s.ctx, "SendBatchAlarm") var wg sync.WaitGroup var mu sync.Mutex @@ -77,7 +77,7 @@ func (s *failoverService) SendBatchAlarm(ctx context.Context, userIDs []uint, co for _, userID := range userIDs { wg.Add(1) - go func(id uint) { + go func(id uint32) { defer wg.Done() if err := s.sendAlarmToUser(serviceCtx, id, content); err != nil { mu.Lock() @@ -108,7 +108,7 @@ func (s *failoverService) BroadcastAlarm(ctx context.Context, content notify.Ala return fmt.Errorf("广播告警失败:查找所有用户时出错: %w", err) } - var userIDs []uint + var userIDs []uint32 for _, user := range users { userIDs = append(userIDs, user.ID) } @@ -119,7 +119,7 @@ func (s *failoverService) BroadcastAlarm(ctx context.Context, content notify.Ala } // sendAlarmToUser 是为单个用户发送告警的内部方法,包含了完整的故障转移逻辑 -func (s *failoverService) sendAlarmToUser(ctx context.Context, userID uint, content notify.AlarmContent) error { +func (s *failoverService) sendAlarmToUser(ctx context.Context, userID uint32, content notify.AlarmContent) error { serviceCtx, logger := logs.Trace(ctx, s.ctx, "sendAlarmToUser") user, err := s.userRepo.FindByID(serviceCtx, userID) if err != nil { @@ -187,7 +187,7 @@ func (s *failoverService) sendAlarmToUser(ctx context.Context, userID uint, cont } // SendTestMessage 实现了手动发送测试消息的功能 -func (s *failoverService) SendTestMessage(ctx context.Context, userID uint, notifierType models.NotifierType) error { +func (s *failoverService) SendTestMessage(ctx context.Context, userID uint32, notifierType models.NotifierType) error { serviceCtx, logger := logs.Trace(ctx, s.ctx, "SendTestMessage") user, err := s.userRepo.FindByID(serviceCtx, userID) if err != nil { @@ -261,7 +261,7 @@ func getAddressForNotifier(notifierType models.NotifierType, contact models.Cont // err: 如果发送失败,记录的错误信息 func (s *failoverService) recordNotificationAttempt( ctx context.Context, - userID uint, + userID uint32, notifierType models.NotifierType, content notify.AlarmContent, toAddress string, diff --git a/internal/domain/pig/pen_transfer_manager.go b/internal/domain/pig/pen_transfer_manager.go index 6b522a5..266db08 100644 --- a/internal/domain/pig/pen_transfer_manager.go +++ b/internal/domain/pig/pen_transfer_manager.go @@ -19,22 +19,22 @@ type PigPenTransferManager interface { LogTransfer(ctx context.Context, tx *gorm.DB, log *models.PigTransferLog) error // GetPenByID 用于获取猪栏的详细信息,供上层服务进行业务校验。 - GetPenByID(ctx context.Context, tx *gorm.DB, penID uint) (*models.Pen, error) + GetPenByID(ctx context.Context, tx *gorm.DB, penID uint32) (*models.Pen, error) // GetPensByBatchID 获取一个猪群当前关联的所有猪栏。 - GetPensByBatchID(ctx context.Context, tx *gorm.DB, batchID uint) ([]*models.Pen, error) + GetPensByBatchID(ctx context.Context, tx *gorm.DB, batchID uint32) ([]*models.Pen, error) // UpdatePenFields 更新一个猪栏的指定字段。 - UpdatePenFields(ctx context.Context, tx *gorm.DB, penID uint, updates map[string]interface{}) error + UpdatePenFields(ctx context.Context, tx *gorm.DB, penID uint32, updates map[string]interface{}) error // GetCurrentPigsInPen 通过汇总猪只迁移日志,计算给定猪栏中的当前猪只数量。 - GetCurrentPigsInPen(ctx context.Context, tx *gorm.DB, penID uint) (int, error) + GetCurrentPigsInPen(ctx context.Context, tx *gorm.DB, penID uint32) (int, error) // GetTotalPigsInPensForBatchTx 计算指定猪群下所有猪栏的当前总存栏数 - GetTotalPigsInPensForBatchTx(ctx context.Context, tx *gorm.DB, batchID uint) (int, error) + GetTotalPigsInPensForBatchTx(ctx context.Context, tx *gorm.DB, batchID uint32) (int, error) // ReleasePen 将猪栏的猪群归属移除,并将其状态标记为空闲。 - ReleasePen(ctx context.Context, tx *gorm.DB, penID uint) error + ReleasePen(ctx context.Context, tx *gorm.DB, penID uint32) error } // pigPenTransferManager 是 PigPenTransferManager 接口的具体实现。 @@ -63,25 +63,25 @@ func (s *pigPenTransferManager) LogTransfer(ctx context.Context, tx *gorm.DB, lo } // GetPenByID 实现了获取猪栏信息的逻辑。 -func (s *pigPenTransferManager) GetPenByID(ctx context.Context, tx *gorm.DB, penID uint) (*models.Pen, error) { +func (s *pigPenTransferManager) GetPenByID(ctx context.Context, tx *gorm.DB, penID uint32) (*models.Pen, error) { managerCtx := logs.AddFuncName(ctx, s.ctx, "GetPenByID") return s.penRepo.GetPenByIDTx(managerCtx, tx, penID) } // GetPensByBatchID 实现了获取猪群关联猪栏列表的逻辑。 -func (s *pigPenTransferManager) GetPensByBatchID(ctx context.Context, tx *gorm.DB, batchID uint) ([]*models.Pen, error) { +func (s *pigPenTransferManager) GetPensByBatchID(ctx context.Context, tx *gorm.DB, batchID uint32) ([]*models.Pen, error) { managerCtx := logs.AddFuncName(ctx, s.ctx, "GetPensByBatchID") return s.penRepo.GetPensByBatchIDTx(managerCtx, tx, batchID) } // UpdatePenFields 实现了更新猪栏字段的逻辑。 -func (s *pigPenTransferManager) UpdatePenFields(ctx context.Context, tx *gorm.DB, penID uint, updates map[string]interface{}) error { +func (s *pigPenTransferManager) UpdatePenFields(ctx context.Context, tx *gorm.DB, penID uint32, updates map[string]interface{}) error { managerCtx := logs.AddFuncName(ctx, s.ctx, "UpdatePenFields") return s.penRepo.UpdatePenFieldsTx(managerCtx, tx, penID, updates) } // GetCurrentPigsInPen 实现了计算猪栏当前猪只数量的逻辑。 -func (s *pigPenTransferManager) GetCurrentPigsInPen(ctx context.Context, tx *gorm.DB, penID uint) (int, error) { +func (s *pigPenTransferManager) GetCurrentPigsInPen(ctx context.Context, tx *gorm.DB, penID uint32) (int, error) { managerCtx := logs.AddFuncName(ctx, s.ctx, "GetCurrentPigsInPen") // 1. 通过猪栏ID查出所属猪群信息 pen, err := s.penRepo.GetPenByIDTx(managerCtx, tx, penID) @@ -137,7 +137,7 @@ func (s *pigPenTransferManager) GetCurrentPigsInPen(ctx context.Context, tx *gor // GetTotalPigsInPensForBatchTx 计算指定猪群下所有猪栏的当前总存栏数 // 该方法通过遍历猪群下的每个猪栏,并调用 GetCurrentPigsInPen 来累加存栏数。 -func (s *pigPenTransferManager) GetTotalPigsInPensForBatchTx(ctx context.Context, tx *gorm.DB, batchID uint) (int, error) { +func (s *pigPenTransferManager) GetTotalPigsInPensForBatchTx(ctx context.Context, tx *gorm.DB, batchID uint32) (int, error) { managerCtx := logs.AddFuncName(ctx, s.ctx, "GetTotalPigsInPensForBatchTx") // 1. 获取该批次下所有猪栏的列表 pensInBatch, err := s.GetPensByBatchID(managerCtx, tx, batchID) @@ -160,7 +160,7 @@ func (s *pigPenTransferManager) GetTotalPigsInPensForBatchTx(ctx context.Context // ReleasePen 将猪栏的猪群归属移除,并将其状态标记为空闲。 // 此操作通常在猪栏被清空后调用。 -func (s *pigPenTransferManager) ReleasePen(ctx context.Context, tx *gorm.DB, penID uint) error { +func (s *pigPenTransferManager) ReleasePen(ctx context.Context, tx *gorm.DB, penID uint32) error { managerCtx := logs.AddFuncName(ctx, s.ctx, "ReleasePen") // 1. 获取猪栏信息 pen, err := s.penRepo.GetPenByIDTx(managerCtx, tx, penID) diff --git a/internal/domain/pig/pig_batch_service.go b/internal/domain/pig/pig_batch_service.go index f103efc..d4deb40 100644 --- a/internal/domain/pig/pig_batch_service.go +++ b/internal/domain/pig/pig_batch_service.go @@ -38,58 +38,58 @@ var ( // 它抽象了所有与猪批次相关的操作,使得应用层可以依赖于此接口,而不是具体的实现。 type PigBatchService interface { // CreatePigBatch 创建猪批次,并记录初始日志。 - CreatePigBatch(ctx context.Context, operatorID uint, batch *models.PigBatch) (*models.PigBatch, error) + CreatePigBatch(ctx context.Context, operatorID uint32, batch *models.PigBatch) (*models.PigBatch, error) // GetPigBatch 获取单个猪批次。 - GetPigBatch(ctx context.Context, id uint) (*models.PigBatch, error) + GetPigBatch(ctx context.Context, id uint32) (*models.PigBatch, error) // UpdatePigBatch 更新猪批次信息。 UpdatePigBatch(ctx context.Context, batch *models.PigBatch) (*models.PigBatch, error) // DeletePigBatch 删除猪批次,包含业务规则校验。 - DeletePigBatch(ctx context.Context, id uint) error + DeletePigBatch(ctx context.Context, id uint32) error // ListPigBatches 批量查询猪批次。 ListPigBatches(ctx context.Context, isActive *bool) ([]*models.PigBatch, error) // AssignEmptyPensToBatch 为猪群分配空栏 - AssignEmptyPensToBatch(ctx context.Context, batchID uint, penIDs []uint, operatorID uint) error + AssignEmptyPensToBatch(ctx context.Context, batchID uint32, penIDs []uint32, operatorID uint32) error // MovePigsIntoPen 将猪只从“虚拟库存”移入指定猪栏 - MovePigsIntoPen(ctx context.Context, batchID uint, toPenID uint, quantity int, operatorID uint, remarks string) error + MovePigsIntoPen(ctx context.Context, batchID uint32, toPenID uint32, quantity int, operatorID uint32, remarks string) error // ReclassifyPenToNewBatch 连猪带栏,整体划拨到另一个猪群 - ReclassifyPenToNewBatch(ctx context.Context, fromBatchID uint, toBatchID uint, penID uint, operatorID uint, remarks string) error + ReclassifyPenToNewBatch(ctx context.Context, fromBatchID uint32, toBatchID uint32, penID uint32, operatorID uint32, remarks string) error // RemoveEmptyPenFromBatch 将一个猪栏移除出猪群,此方法需要在猪栏为空的情况下执行。 - RemoveEmptyPenFromBatch(ctx context.Context, batchID uint, penID uint) error + RemoveEmptyPenFromBatch(ctx context.Context, batchID uint32, penID uint32) error // GetCurrentPigQuantity 获取指定猪批次的当前猪只数量。 - GetCurrentPigQuantity(ctx context.Context, batchID uint) (int, error) + GetCurrentPigQuantity(ctx context.Context, batchID uint32) (int, error) // GetCurrentPigsInPen 获取指定猪栏的当前存栏量。 - GetCurrentPigsInPen(ctx context.Context, penID uint) (int, error) + GetCurrentPigsInPen(ctx context.Context, penID uint32) (int, error) // GetTotalPigsInPensForBatch 获取指定猪群下所有猪栏的当前总存栏数 - GetTotalPigsInPensForBatch(ctx context.Context, batchID uint) (int, error) + GetTotalPigsInPensForBatch(ctx context.Context, batchID uint32) (int, error) - UpdatePigBatchQuantity(ctx context.Context, operatorID uint, batchID uint, changeType models.LogChangeType, changeAmount int, changeReason string, happenedAt time.Time) error + UpdatePigBatchQuantity(ctx context.Context, operatorID uint32, batchID uint32, changeType models.LogChangeType, changeAmount int, changeReason string, happenedAt time.Time) error // ---交易子服务--- // SellPigs 处理卖猪的业务逻辑。 - SellPigs(ctx context.Context, batchID uint, penID uint, quantity int, unitPrice float32, tatalPrice float32, traderName string, tradeDate time.Time, remarks string, operatorID uint) error + SellPigs(ctx context.Context, batchID uint32, penID uint32, quantity int, unitPrice float32, tatalPrice float32, traderName string, tradeDate time.Time, remarks string, operatorID uint32) error // BuyPigs 处理买猪的业务逻辑。 - BuyPigs(ctx context.Context, batchID uint, penID uint, quantity int, unitPrice float32, tatalPrice float32, traderName string, tradeDate time.Time, remarks string, operatorID uint) error + BuyPigs(ctx context.Context, batchID uint32, penID uint32, quantity int, unitPrice float32, tatalPrice float32, traderName string, tradeDate time.Time, remarks string, operatorID uint32) error // ---调栏子服务 --- - TransferPigsAcrossBatches(ctx context.Context, sourceBatchID uint, destBatchID uint, fromPenID uint, toPenID uint, quantity uint, operatorID uint, remarks string) error - TransferPigsWithinBatch(ctx context.Context, batchID uint, fromPenID uint, toPenID uint, quantity uint, operatorID uint, remarks string) error + TransferPigsAcrossBatches(ctx context.Context, sourceBatchID uint32, destBatchID uint32, fromPenID uint32, toPenID uint32, quantity uint32, operatorID uint32, remarks string) error + TransferPigsWithinBatch(ctx context.Context, batchID uint32, fromPenID uint32, toPenID uint32, quantity uint32, operatorID uint32, remarks string) error // --- 病猪管理相关方法 --- // RecordSickPigs 记录新增病猪事件。 - RecordSickPigs(ctx context.Context, operatorID uint, batchID uint, penID uint, quantity int, treatmentLocation models.PigBatchSickPigTreatmentLocation, happenedAt time.Time, remarks string) error + RecordSickPigs(ctx context.Context, operatorID uint32, batchID uint32, penID uint32, quantity int, treatmentLocation models.PigBatchSickPigTreatmentLocation, happenedAt time.Time, remarks string) error // RecordSickPigRecovery 记录病猪康复事件。 - RecordSickPigRecovery(ctx context.Context, operatorID uint, batchID uint, penID uint, quantity int, treatmentLocation models.PigBatchSickPigTreatmentLocation, happenedAt time.Time, remarks string) error + RecordSickPigRecovery(ctx context.Context, operatorID uint32, batchID uint32, penID uint32, quantity int, treatmentLocation models.PigBatchSickPigTreatmentLocation, happenedAt time.Time, remarks string) error // RecordSickPigDeath 记录病猪死亡事件。 - RecordSickPigDeath(ctx context.Context, operatorID uint, batchID uint, penID uint, quantity int, treatmentLocation models.PigBatchSickPigTreatmentLocation, happenedAt time.Time, remarks string) error + RecordSickPigDeath(ctx context.Context, operatorID uint32, batchID uint32, penID uint32, quantity int, treatmentLocation models.PigBatchSickPigTreatmentLocation, happenedAt time.Time, remarks string) error // RecordSickPigCull 记录病猪淘汰事件。 - RecordSickPigCull(ctx context.Context, operatorID uint, batchID uint, penID uint, quantity int, treatmentLocation models.PigBatchSickPigTreatmentLocation, happenedAt time.Time, remarks string) error + RecordSickPigCull(ctx context.Context, operatorID uint32, batchID uint32, penID uint32, quantity int, treatmentLocation models.PigBatchSickPigTreatmentLocation, happenedAt time.Time, remarks string) error // --- 正常猪只管理相关方法 --- // RecordDeath 记录正常猪只死亡事件。 - RecordDeath(ctx context.Context, operatorID uint, batchID uint, penID uint, quantity int, happenedAt time.Time, remarks string) error + RecordDeath(ctx context.Context, operatorID uint32, batchID uint32, penID uint32, quantity int, happenedAt time.Time, remarks string) error // RecordCull 记录正常猪只淘汰事件。 - RecordCull(ctx context.Context, operatorID uint, batchID uint, penID uint, quantity int, happenedAt time.Time, remarks string) error + RecordCull(ctx context.Context, operatorID uint32, batchID uint32, penID uint32, quantity int, happenedAt time.Time, remarks string) error } // pigBatchService 是 PigBatchService 接口的具体实现。 diff --git a/internal/domain/pig/pig_batch_service_method.go b/internal/domain/pig/pig_batch_service_method.go index 9f070a2..289e3c1 100644 --- a/internal/domain/pig/pig_batch_service_method.go +++ b/internal/domain/pig/pig_batch_service_method.go @@ -15,7 +15,7 @@ import ( // --- 领域服务实现 --- // CreatePigBatch 实现了创建猪批次的逻辑,并同时创建初始批次日志。 -func (s *pigBatchService) CreatePigBatch(ctx context.Context, operatorID uint, batch *models.PigBatch) (*models.PigBatch, error) { +func (s *pigBatchService) CreatePigBatch(ctx context.Context, operatorID uint32, batch *models.PigBatch) (*models.PigBatch, error) { serviceCtx := logs.AddFuncName(ctx, s.ctx, "CreatePigBatch") // 业务规则可以在这里添加,例如检查批次号是否唯一等 @@ -57,7 +57,7 @@ func (s *pigBatchService) CreatePigBatch(ctx context.Context, operatorID uint, b } // GetPigBatch 实现了获取单个猪批次的逻辑。 -func (s *pigBatchService) GetPigBatch(ctx context.Context, id uint) (*models.PigBatch, error) { +func (s *pigBatchService) GetPigBatch(ctx context.Context, id uint32) (*models.PigBatch, error) { serviceCtx := logs.AddFuncName(ctx, s.ctx, "GetPigBatch") batch, err := s.pigBatchRepo.GetPigBatchByID(serviceCtx, id) if err != nil { @@ -84,7 +84,7 @@ func (s *pigBatchService) UpdatePigBatch(ctx context.Context, batch *models.PigB } // DeletePigBatch 实现了删除猪批次的逻辑,并包含业务规则校验。 -func (s *pigBatchService) DeletePigBatch(ctx context.Context, id uint) error { +func (s *pigBatchService) DeletePigBatch(ctx context.Context, id uint32) error { serviceCtx := logs.AddFuncName(ctx, s.ctx, "DeletePigBatch") return s.uow.ExecuteInTransaction(serviceCtx, func(tx *gorm.DB) error { // 1. 获取猪批次信息 @@ -135,7 +135,7 @@ func (s *pigBatchService) ListPigBatches(ctx context.Context, isActive *bool) ([ } // GetCurrentPigQuantity 实现了获取指定猪批次的当前猪只数量的逻辑。 -func (s *pigBatchService) GetCurrentPigQuantity(ctx context.Context, batchID uint) (int, error) { +func (s *pigBatchService) GetCurrentPigQuantity(ctx context.Context, batchID uint32) (int, error) { serviceCtx := logs.AddFuncName(ctx, s.ctx, "GetCurrentPigQuantity") var getErr error var quantity int @@ -150,7 +150,7 @@ func (s *pigBatchService) GetCurrentPigQuantity(ctx context.Context, batchID uin } // getCurrentPigQuantityTx 实现了获取指定猪批次的当前猪只数量的逻辑。 -func (s *pigBatchService) getCurrentPigQuantityTx(ctx context.Context, tx *gorm.DB, batchID uint) (int, error) { +func (s *pigBatchService) getCurrentPigQuantityTx(ctx context.Context, tx *gorm.DB, batchID uint32) (int, error) { serviceCtx := logs.AddFuncName(ctx, s.ctx, "getCurrentPigQuantityTx") // 1. 获取猪批次初始信息 batch, err := s.pigBatchRepo.GetPigBatchByIDTx(serviceCtx, tx, batchID) @@ -175,14 +175,14 @@ func (s *pigBatchService) getCurrentPigQuantityTx(ctx context.Context, tx *gorm. return lastLog.AfterCount, nil } -func (s *pigBatchService) UpdatePigBatchQuantity(ctx context.Context, operatorID uint, batchID uint, changeType models.LogChangeType, changeAmount int, changeReason string, happenedAt time.Time) error { +func (s *pigBatchService) UpdatePigBatchQuantity(ctx context.Context, operatorID uint32, batchID uint32, changeType models.LogChangeType, changeAmount int, changeReason string, happenedAt time.Time) error { serviceCtx := logs.AddFuncName(ctx, s.ctx, "UpdatePigBatchQuantity") return s.uow.ExecuteInTransaction(serviceCtx, func(tx *gorm.DB) error { return s.updatePigBatchQuantityTx(serviceCtx, tx, operatorID, batchID, changeType, changeAmount, changeReason, happenedAt) }) } -func (s *pigBatchService) updatePigBatchQuantityTx(ctx context.Context, tx *gorm.DB, operatorID uint, batchID uint, changeType models.LogChangeType, changeAmount int, changeReason string, happenedAt time.Time) error { +func (s *pigBatchService) updatePigBatchQuantityTx(ctx context.Context, tx *gorm.DB, operatorID uint32, batchID uint32, changeType models.LogChangeType, changeAmount int, changeReason string, happenedAt time.Time) error { serviceCtx := logs.AddFuncName(ctx, s.ctx, "updatePigBatchQuantityTx") lastLog, err := s.pigBatchLogRepo.GetLastLogByBatchIDTx(serviceCtx, tx, batchID) if err != nil { diff --git a/internal/domain/pig/pig_batch_service_pen_transfer.go b/internal/domain/pig/pig_batch_service_pen_transfer.go index e41f06c..292955e 100644 --- a/internal/domain/pig/pig_batch_service_pen_transfer.go +++ b/internal/domain/pig/pig_batch_service_pen_transfer.go @@ -14,7 +14,7 @@ import ( ) // executeTransferAndLog 是一个私有辅助方法,用于封装创建和记录迁移日志的通用逻辑。 -func (s *pigBatchService) executeTransferAndLog(ctx context.Context, tx *gorm.DB, fromBatchID, toBatchID, fromPenID, toPenID uint, quantity int, transferType models.PigTransferType, operatorID uint, remarks string) error { +func (s *pigBatchService) executeTransferAndLog(ctx context.Context, tx *gorm.DB, fromBatchID, toBatchID, fromPenID, toPenID uint32, quantity int, transferType models.PigTransferType, operatorID uint32, remarks string) error { serviceCtx := logs.AddFuncName(ctx, s.ctx, "executeTransferAndLog") // 通用校验:任何调出操作都不能超过源猪栏的当前存栏数 @@ -67,7 +67,7 @@ func (s *pigBatchService) executeTransferAndLog(ctx context.Context, tx *gorm.DB } // TransferPigsWithinBatch 实现了同一个猪群内部的调栏业务。 -func (s *pigBatchService) TransferPigsWithinBatch(ctx context.Context, batchID uint, fromPenID uint, toPenID uint, quantity uint, operatorID uint, remarks string) error { +func (s *pigBatchService) TransferPigsWithinBatch(ctx context.Context, batchID uint32, fromPenID uint32, toPenID uint32, quantity uint32, operatorID uint32, remarks string) error { serviceCtx := logs.AddFuncName(ctx, s.ctx, "TransferPigsWithinBatch") if fromPenID == toPenID { return errors.New("源猪栏和目标猪栏不能相同") @@ -106,7 +106,7 @@ func (s *pigBatchService) TransferPigsWithinBatch(ctx context.Context, batchID u } // TransferPigsAcrossBatches 实现了跨猪群的调栏业务。 -func (s *pigBatchService) TransferPigsAcrossBatches(ctx context.Context, sourceBatchID uint, destBatchID uint, fromPenID uint, toPenID uint, quantity uint, operatorID uint, remarks string) error { +func (s *pigBatchService) TransferPigsAcrossBatches(ctx context.Context, sourceBatchID uint32, destBatchID uint32, fromPenID uint32, toPenID uint32, quantity uint32, operatorID uint32, remarks string) error { serviceCtx := logs.AddFuncName(ctx, s.ctx, "TransferPigsAcrossBatches") if sourceBatchID == destBatchID { return errors.New("源猪群和目标猪群不能相同") @@ -167,7 +167,7 @@ func (s *pigBatchService) TransferPigsAcrossBatches(ctx context.Context, sourceB } // AssignEmptyPensToBatch 为猪群分配空栏 -func (s *pigBatchService) AssignEmptyPensToBatch(ctx context.Context, batchID uint, penIDs []uint, operatorID uint) error { +func (s *pigBatchService) AssignEmptyPensToBatch(ctx context.Context, batchID uint32, penIDs []uint32, operatorID uint32) error { serviceCtx := logs.AddFuncName(ctx, s.ctx, "AssignEmptyPensToBatch") return s.uow.ExecuteInTransaction(serviceCtx, func(tx *gorm.DB) error { // 1. 验证猪批次是否存在且活跃 @@ -204,6 +204,7 @@ func (s *pigBatchService) AssignEmptyPensToBatch(ctx context.Context, batchID ui updates := map[string]interface{}{ "pig_batch_id": &batchID, "status": models.PenStatusOccupied, + "operator_id": operatorID, } if err := s.transferSvc.UpdatePenFields(serviceCtx, tx, penID, updates); err != nil { return fmt.Errorf("分配猪栏 %d 失败: %w", penID, err) @@ -215,7 +216,7 @@ func (s *pigBatchService) AssignEmptyPensToBatch(ctx context.Context, batchID ui } // MovePigsIntoPen 将猪只从“虚拟库存”移入指定猪栏 -func (s *pigBatchService) MovePigsIntoPen(ctx context.Context, batchID uint, toPenID uint, quantity int, operatorID uint, remarks string) error { +func (s *pigBatchService) MovePigsIntoPen(ctx context.Context, batchID uint32, toPenID uint32, quantity int, operatorID uint32, remarks string) error { serviceCtx := logs.AddFuncName(ctx, s.ctx, "MovePigsIntoPen") if quantity <= 0 { return errors.New("迁移数量必须大于零") @@ -287,7 +288,7 @@ func (s *pigBatchService) MovePigsIntoPen(ctx context.Context, batchID uint, toP } // ReclassifyPenToNewBatch 连猪带栏,整体划拨到另一个猪群 -func (s *pigBatchService) ReclassifyPenToNewBatch(ctx context.Context, fromBatchID uint, toBatchID uint, penID uint, operatorID uint, remarks string) error { +func (s *pigBatchService) ReclassifyPenToNewBatch(ctx context.Context, fromBatchID uint32, toBatchID uint32, penID uint32, operatorID uint32, remarks string) error { serviceCtx := logs.AddFuncName(ctx, s.ctx, "ReclassifyPenToNewBatch") if fromBatchID == toBatchID { return errors.New("源猪群和目标猪群不能相同") @@ -392,7 +393,7 @@ func (s *pigBatchService) ReclassifyPenToNewBatch(ctx context.Context, fromBatch }) } -func (s *pigBatchService) RemoveEmptyPenFromBatch(ctx context.Context, batchID uint, penID uint) error { +func (s *pigBatchService) RemoveEmptyPenFromBatch(ctx context.Context, batchID uint32, penID uint32) error { serviceCtx := logs.AddFuncName(ctx, s.ctx, "RemoveEmptyPenFromBatch") return s.uow.ExecuteInTransaction(serviceCtx, func(tx *gorm.DB) error { // 1. 检查猪批次是否存在且活跃 @@ -438,7 +439,7 @@ func (s *pigBatchService) RemoveEmptyPenFromBatch(ctx context.Context, batchID u }) } -func (s *pigBatchService) GetCurrentPigsInPen(ctx context.Context, penID uint) (int, error) { +func (s *pigBatchService) GetCurrentPigsInPen(ctx context.Context, penID uint32) (int, error) { serviceCtx := logs.AddFuncName(ctx, s.ctx, "GetCurrentPigsInPen") var currentPigs int err := s.uow.ExecuteInTransaction(serviceCtx, func(tx *gorm.DB) error { @@ -453,7 +454,7 @@ func (s *pigBatchService) GetCurrentPigsInPen(ctx context.Context, penID uint) ( } // GetTotalPigsInPensForBatch 实现了获取指定猪群下所有猪栏的当前总存栏数的逻辑。 -func (s *pigBatchService) GetTotalPigsInPensForBatch(ctx context.Context, batchID uint) (int, error) { +func (s *pigBatchService) GetTotalPigsInPensForBatch(ctx context.Context, batchID uint32) (int, error) { serviceCtx := logs.AddFuncName(ctx, s.ctx, "GetTotalPigsInPensForBatch") var totalPigs int err := s.uow.ExecuteInTransaction(serviceCtx, func(tx *gorm.DB) error { diff --git a/internal/domain/pig/pig_batch_service_pig_sick.go b/internal/domain/pig/pig_batch_service_pig_sick.go index 2fca6f4..db1a3bf 100644 --- a/internal/domain/pig/pig_batch_service_pig_sick.go +++ b/internal/domain/pig/pig_batch_service_pig_sick.go @@ -13,7 +13,7 @@ import ( ) // RecordSickPigs 记录新增病猪事件。 -func (s *pigBatchService) RecordSickPigs(ctx context.Context, operatorID uint, batchID uint, penID uint, quantity int, treatmentLocation models.PigBatchSickPigTreatmentLocation, happenedAt time.Time, remarks string) error { +func (s *pigBatchService) RecordSickPigs(ctx context.Context, operatorID uint32, batchID uint32, penID uint32, quantity int, treatmentLocation models.PigBatchSickPigTreatmentLocation, happenedAt time.Time, remarks string) error { serviceCtx := logs.AddFuncName(ctx, s.ctx, "RecordSickPigs") if quantity <= 0 { return errors.New("新增病猪数量必须大于0") @@ -89,7 +89,7 @@ func (s *pigBatchService) RecordSickPigs(ctx context.Context, operatorID uint, b } // RecordSickPigRecovery 记录病猪康复事件。 -func (s *pigBatchService) RecordSickPigRecovery(ctx context.Context, operatorID uint, batchID uint, penID uint, quantity int, treatmentLocation models.PigBatchSickPigTreatmentLocation, happenedAt time.Time, remarks string) error { +func (s *pigBatchService) RecordSickPigRecovery(ctx context.Context, operatorID uint32, batchID uint32, penID uint32, quantity int, treatmentLocation models.PigBatchSickPigTreatmentLocation, happenedAt time.Time, remarks string) error { serviceCtx := logs.AddFuncName(ctx, s.ctx, "RecordSickPigRecovery") if quantity <= 0 { return errors.New("康复猪只数量必须大于0") @@ -158,7 +158,7 @@ func (s *pigBatchService) RecordSickPigRecovery(ctx context.Context, operatorID } // RecordSickPigDeath 记录病猪死亡事件。 -func (s *pigBatchService) RecordSickPigDeath(ctx context.Context, operatorID uint, batchID uint, penID uint, quantity int, treatmentLocation models.PigBatchSickPigTreatmentLocation, happenedAt time.Time, remarks string) error { +func (s *pigBatchService) RecordSickPigDeath(ctx context.Context, operatorID uint32, batchID uint32, penID uint32, quantity int, treatmentLocation models.PigBatchSickPigTreatmentLocation, happenedAt time.Time, remarks string) error { serviceCtx := logs.AddFuncName(ctx, s.ctx, "RecordSickPigDeath") if quantity <= 0 { return errors.New("死亡猪只数量必须大于0") @@ -254,7 +254,7 @@ func (s *pigBatchService) RecordSickPigDeath(ctx context.Context, operatorID uin } // RecordSickPigCull 记录病猪淘汰事件。 -func (s *pigBatchService) RecordSickPigCull(ctx context.Context, operatorID uint, batchID uint, penID uint, quantity int, treatmentLocation models.PigBatchSickPigTreatmentLocation, happenedAt time.Time, remarks string) error { +func (s *pigBatchService) RecordSickPigCull(ctx context.Context, operatorID uint32, batchID uint32, penID uint32, quantity int, treatmentLocation models.PigBatchSickPigTreatmentLocation, happenedAt time.Time, remarks string) error { serviceCtx := logs.AddFuncName(ctx, s.ctx, "RecordSickPigCull") if quantity <= 0 { return errors.New("淘汰猪只数量必须大于0") @@ -350,7 +350,7 @@ func (s *pigBatchService) RecordSickPigCull(ctx context.Context, operatorID uint } // RecordDeath 记录正常猪只死亡事件。 -func (s *pigBatchService) RecordDeath(ctx context.Context, operatorID uint, batchID uint, penID uint, quantity int, happenedAt time.Time, remarks string) error { +func (s *pigBatchService) RecordDeath(ctx context.Context, operatorID uint32, batchID uint32, penID uint32, quantity int, happenedAt time.Time, remarks string) error { serviceCtx := logs.AddFuncName(ctx, s.ctx, "RecordDeath") if quantity <= 0 { return errors.New("死亡猪只数量必须大于0") @@ -421,7 +421,7 @@ func (s *pigBatchService) RecordDeath(ctx context.Context, operatorID uint, batc } // RecordCull 记录正常猪只淘汰事件。 -func (s *pigBatchService) RecordCull(ctx context.Context, operatorID uint, batchID uint, penID uint, quantity int, happenedAt time.Time, remarks string) error { +func (s *pigBatchService) RecordCull(ctx context.Context, operatorID uint32, batchID uint32, penID uint32, quantity int, happenedAt time.Time, remarks string) error { serviceCtx := logs.AddFuncName(ctx, s.ctx, "RecordCull") if quantity <= 0 { return errors.New("淘汰猪只数量必须大于0") diff --git a/internal/domain/pig/pig_batch_service_pig_trade.go b/internal/domain/pig/pig_batch_service_pig_trade.go index c6a14b2..0e60283 100644 --- a/internal/domain/pig/pig_batch_service_pig_trade.go +++ b/internal/domain/pig/pig_batch_service_pig_trade.go @@ -13,7 +13,7 @@ import ( ) // SellPigs 处理批量销售猪的业务逻辑。 -func (s *pigBatchService) SellPigs(ctx context.Context, batchID uint, penID uint, quantity int, unitPrice float32, tatalPrice float32, traderName string, tradeDate time.Time, remarks string, operatorID uint) error { +func (s *pigBatchService) SellPigs(ctx context.Context, batchID uint32, penID uint32, quantity int, unitPrice float32, tatalPrice float32, traderName string, tradeDate time.Time, remarks string, operatorID uint32) error { serviceCtx := logs.AddFuncName(ctx, s.ctx, "SellPigs") return s.uow.ExecuteInTransaction(serviceCtx, func(tx *gorm.DB) error { if quantity <= 0 { @@ -85,7 +85,7 @@ func (s *pigBatchService) SellPigs(ctx context.Context, batchID uint, penID uint } // BuyPigs 处理批量购买猪的业务逻辑。 -func (s *pigBatchService) BuyPigs(ctx context.Context, batchID uint, penID uint, quantity int, unitPrice float32, totalPrice float32, traderName string, tradeDate time.Time, remarks string, operatorID uint) error { +func (s *pigBatchService) BuyPigs(ctx context.Context, batchID uint32, penID uint32, quantity int, unitPrice float32, totalPrice float32, traderName string, tradeDate time.Time, remarks string, operatorID uint32) error { serviceCtx := logs.AddFuncName(ctx, s.ctx, "BuyPigs") return s.uow.ExecuteInTransaction(serviceCtx, func(tx *gorm.DB) error { if quantity <= 0 { diff --git a/internal/domain/pig/pig_sick_manager.go b/internal/domain/pig/pig_sick_manager.go index fd93b29..be48017 100644 --- a/internal/domain/pig/pig_sick_manager.go +++ b/internal/domain/pig/pig_sick_manager.go @@ -21,7 +21,7 @@ type SickPigManager interface { ProcessSickPigLog(ctx context.Context, tx *gorm.DB, log *models.PigSickLog) error // GetCurrentSickPigCount 获取指定批次当前患病猪只的总数 - GetCurrentSickPigCount(ctx context.Context, tx *gorm.DB, batchID uint) (int, error) + GetCurrentSickPigCount(ctx context.Context, tx *gorm.DB, batchID uint32) (int, error) } // sickPigManager 是 SickPigManager 接口的具体实现。 @@ -122,7 +122,7 @@ func (s *sickPigManager) ProcessSickPigLog(ctx context.Context, tx *gorm.DB, log return nil } -func (s *sickPigManager) GetCurrentSickPigCount(ctx context.Context, tx *gorm.DB, batchID uint) (int, error) { +func (s *sickPigManager) GetCurrentSickPigCount(ctx context.Context, tx *gorm.DB, batchID uint32) (int, error) { managerCtx := logs.AddFuncName(ctx, s.ctx, "GetCurrentSickPigCount") lastLog, err := s.sickLogRepo.GetLastLogByBatchTx(managerCtx, tx, batchID) if err != nil { diff --git a/internal/domain/plan/analysis_plan_task_manager.go b/internal/domain/plan/analysis_plan_task_manager.go index 05fb741..add3f20 100644 --- a/internal/domain/plan/analysis_plan_task_manager.go +++ b/internal/domain/plan/analysis_plan_task_manager.go @@ -18,10 +18,10 @@ type AnalysisPlanTaskManager interface { Refresh(ctx context.Context) error // CreateOrUpdateTrigger 为给定的 planID 创建其关联的触发任务。 // 如果触发器已存在,会根据计划类型更新其执行时间。 - CreateOrUpdateTrigger(ctx context.Context, planID uint) error + CreateOrUpdateTrigger(ctx context.Context, planID uint32) error // EnsureAnalysisTaskDefinition 确保计划的分析任务定义存在于 tasks 表中。 // 如果不存在,则会自动创建。此方法不涉及待执行队列。 - EnsureAnalysisTaskDefinition(ctx context.Context, planID uint) error + EnsureAnalysisTaskDefinition(ctx context.Context, planID uint32) error } // analysisPlanTaskManagerImpl 负责管理分析计划的触发器任务。 @@ -82,7 +82,7 @@ func (m *analysisPlanTaskManagerImpl) Refresh(ctx context.Context) error { // CreateOrUpdateTrigger 为给定的 planID 创建其关联的触发任务。 // 如果触发器已存在,会根据计划类型更新其执行时间。 -func (m *analysisPlanTaskManagerImpl) CreateOrUpdateTrigger(ctx context.Context, planID uint) error { +func (m *analysisPlanTaskManagerImpl) CreateOrUpdateTrigger(ctx context.Context, planID uint32) error { managerCtx, logger := logs.Trace(ctx, m.ctx, "CreateOrUpdateTrigger") m.mu.Lock() defer m.mu.Unlock() @@ -138,7 +138,7 @@ func (m *analysisPlanTaskManagerImpl) CreateOrUpdateTrigger(ctx context.Context, // EnsureAnalysisTaskDefinition 确保计划的分析任务定义存在于 tasks 表中。 // 如果不存在,则会自动创建。此方法不涉及待执行队列。 -func (m *analysisPlanTaskManagerImpl) EnsureAnalysisTaskDefinition(ctx context.Context, planID uint) error { +func (m *analysisPlanTaskManagerImpl) EnsureAnalysisTaskDefinition(ctx context.Context, planID uint32) error { managerCtx, logger := logs.Trace(ctx, m.ctx, "EnsureAnalysisTaskDefinition") m.mu.Lock() defer m.mu.Unlock() @@ -170,7 +170,7 @@ func (m *analysisPlanTaskManagerImpl) EnsureAnalysisTaskDefinition(ctx context.C // --- 内部私有方法 --- // getRefreshData 从数据库获取刷新所需的所有数据。 -func (m *analysisPlanTaskManagerImpl) getRefreshData(ctx context.Context) (runnablePlans []*models.Plan, invalidPlanIDs []uint, pendingTasks []models.PendingTask, err error) { +func (m *analysisPlanTaskManagerImpl) getRefreshData(ctx context.Context) (runnablePlans []*models.Plan, invalidPlanIDs []uint32, pendingTasks []models.PendingTask, err error) { managerCtx, logger := logs.Trace(ctx, m.ctx, "getRefreshData") runnablePlans, err = m.planRepo.FindRunnablePlans(managerCtx) if err != nil { @@ -183,7 +183,7 @@ func (m *analysisPlanTaskManagerImpl) getRefreshData(ctx context.Context) (runna logger.Errorf("获取失效计划列表失败: %v", err) return } - invalidPlanIDs = make([]uint, len(invalidPlans)) + invalidPlanIDs = make([]uint32, len(invalidPlans)) for i, p := range invalidPlans { invalidPlanIDs[i] = p.ID } @@ -197,19 +197,19 @@ func (m *analysisPlanTaskManagerImpl) getRefreshData(ctx context.Context) (runna } // cleanupInvalidTasks 清理所有与失效计划相关的待执行任务。 -func (m *analysisPlanTaskManagerImpl) cleanupInvalidTasks(ctx context.Context, invalidPlanIDs []uint, allPendingTasks []models.PendingTask) error { +func (m *analysisPlanTaskManagerImpl) cleanupInvalidTasks(ctx context.Context, invalidPlanIDs []uint32, allPendingTasks []models.PendingTask) error { managerCtx, logger := logs.Trace(ctx, m.ctx, "cleanupInvalidTasks") if len(invalidPlanIDs) == 0 { return nil // 没有需要清理的计划 } - invalidPlanIDSet := make(map[uint]struct{}, len(invalidPlanIDs)) + invalidPlanIDSet := make(map[uint32]struct{}, len(invalidPlanIDs)) for _, id := range invalidPlanIDs { invalidPlanIDSet[id] = struct{}{} } - var tasksToDeleteIDs []uint - var logsToCancelIDs []uint + var tasksToDeleteIDs []uint32 + var logsToCancelIDs []uint32 for _, pt := range allPendingTasks { if pt.Task == nil { // 防御性编程,确保 Task 被预加载 @@ -245,7 +245,7 @@ func (m *analysisPlanTaskManagerImpl) cleanupInvalidTasks(ctx context.Context, i func (m *analysisPlanTaskManagerImpl) addOrUpdateTriggers(ctx context.Context, runnablePlans []*models.Plan, allPendingTasks []models.PendingTask) error { managerCtx, logger := logs.Trace(ctx, m.ctx, "addOrUpdateTriggers") // 创建一个映射,存放所有已在队列中的计划触发器 - pendingTriggersMap := make(map[uint]models.PendingTask) + pendingTriggersMap := make(map[uint32]models.PendingTask) for _, pt := range allPendingTasks { if pt.Task != nil && pt.Task.Type == models.TaskPlanAnalysis { pendingTriggersMap[pt.Task.PlanID] = pt diff --git a/internal/domain/plan/plan_execution_manager.go b/internal/domain/plan/plan_execution_manager.go index fc76e4c..8bc9566 100644 --- a/internal/domain/plan/plan_execution_manager.go +++ b/internal/domain/plan/plan_execution_manager.go @@ -25,21 +25,21 @@ type ExecutionManager interface { // ProgressTracker 仅用于在内存中提供计划执行的并发锁 type ProgressTracker struct { mu sync.Mutex - cond *sync.Cond // 用于实现阻塞锁 - runningPlans map[uint]bool // key: planExecutionLogID, value: true (用作内存锁) + cond *sync.Cond // 用于实现阻塞锁 + runningPlans map[uint32]bool // key: planExecutionLogID, value: true (用作内存锁) } // NewProgressTracker 创建一个新的进度跟踪器 func NewProgressTracker() *ProgressTracker { t := &ProgressTracker{ - runningPlans: make(map[uint]bool), + runningPlans: make(map[uint32]bool), } t.cond = sync.NewCond(&t.mu) return t } // TryLock (非阻塞) 尝试锁定一个计划。如果计划未被锁定,则锁定并返回 true。 -func (t *ProgressTracker) TryLock(planLogID uint) bool { +func (t *ProgressTracker) TryLock(planLogID uint32) bool { t.mu.Lock() defer t.mu.Unlock() if t.runningPlans[planLogID] { @@ -50,7 +50,7 @@ func (t *ProgressTracker) TryLock(planLogID uint) bool { } // Lock (阻塞) 获取一个计划的执行锁。如果锁已被占用,则会一直等待直到锁被释放。 -func (t *ProgressTracker) Lock(planLogID uint) { +func (t *ProgressTracker) Lock(planLogID uint32) { t.mu.Lock() // 当计划正在运行时,调用 t.cond.Wait() 会原子地解锁 mu 并挂起当前协程。 // 当被唤醒时,它会重新锁定 mu 并再次检查循环条件。 @@ -63,7 +63,7 @@ func (t *ProgressTracker) Lock(planLogID uint) { } // Unlock 解锁一个计划,并唤醒所有正在等待此锁的协程。 -func (t *ProgressTracker) Unlock(planLogID uint) { +func (t *ProgressTracker) Unlock(planLogID uint32) { t.mu.Lock() defer t.mu.Unlock() delete(t.runningPlans, planLogID) @@ -72,10 +72,10 @@ func (t *ProgressTracker) Unlock(planLogID uint) { } // GetRunningPlanIDs 获取当前所有正在执行的计划ID列表 -func (t *ProgressTracker) GetRunningPlanIDs() []uint { +func (t *ProgressTracker) GetRunningPlanIDs() []uint32 { t.mu.Lock() defer t.mu.Unlock() - ids := make([]uint, 0, len(t.runningPlans)) + ids := make([]uint32, 0, len(t.runningPlans)) for id := range t.runningPlans { ids = append(ids, id) } @@ -214,7 +214,7 @@ func (s *planExecutionManagerImpl) claimAndSubmit(ctx context.Context) { } // handleRequeue 同步地、安全地将一个无法立即执行的任务放回队列。 -func (s *planExecutionManagerImpl) handleRequeue(ctx context.Context, planExecutionLogID uint, taskToRequeue *models.PendingTask) { +func (s *planExecutionManagerImpl) handleRequeue(ctx context.Context, planExecutionLogID uint32, taskToRequeue *models.PendingTask) { managerCtx, logger := logs.Trace(ctx, s.ctx, "handleRequeue") logger.Warnf("计划 %d 正在执行,任务 %d (TaskID: %d) 将等待并重新入队...", planExecutionLogID, taskToRequeue.ID, taskToRequeue.TaskID) @@ -308,7 +308,7 @@ func (s *planExecutionManagerImpl) analysisPlan(ctx context.Context, claimedLog // 创建Plan执行记录 // 从任务的 Parameters 中解析出真实的 PlanID var params struct { - PlanID uint `json:"plan_id"` + PlanID uint32 `json:"plan_id"` } if err := claimedLog.Task.ParseParameters(¶ms); err != nil { logger.Errorf("解析任务参数中的计划ID失败,日志ID: %d, 错误: %v", claimedLog.ID, err) @@ -390,7 +390,7 @@ func (s *planExecutionManagerImpl) updateTaskExecutionLogStatus(ctx context.Cont } // handlePlanTermination 集中处理计划的终止逻辑(失败或取消) -func (s *planExecutionManagerImpl) handlePlanTermination(ctx context.Context, planLogID uint, reason string) { +func (s *planExecutionManagerImpl) handlePlanTermination(ctx context.Context, planLogID uint32, reason string) { managerCtx, logger := logs.Trace(ctx, s.ctx, "handlePlanTermination") // 1. 从待执行队列中删除所有相关的子任务 if err := s.pendingTaskRepo.DeletePendingTasksByPlanLogID(managerCtx, planLogID); err != nil { @@ -434,7 +434,7 @@ func (s *planExecutionManagerImpl) handlePlanTermination(ctx context.Context, pl } // handlePlanCompletion 集中处理计划成功完成后的所有逻辑 -func (s *planExecutionManagerImpl) handlePlanCompletion(ctx context.Context, planLogID uint) { +func (s *planExecutionManagerImpl) handlePlanCompletion(ctx context.Context, planLogID uint32) { managerCtx, logger := logs.Trace(ctx, s.ctx, "handlePlanCompletion") logger.Infof("计划执行 %d 的所有任务已完成,开始处理计划完成逻辑...", planLogID) diff --git a/internal/domain/plan/plan_service.go b/internal/domain/plan/plan_service.go index ea61a9f..48c5cf7 100644 --- a/internal/domain/plan/plan_service.go +++ b/internal/domain/plan/plan_service.go @@ -41,17 +41,17 @@ type Service interface { // CreatePlan 创建一个新的计划 CreatePlan(ctx context.Context, plan *models.Plan) (*models.Plan, error) // GetPlanByID 根据ID获取计划详情 - GetPlanByID(ctx context.Context, id uint) (*models.Plan, error) + GetPlanByID(ctx context.Context, id uint32) (*models.Plan, error) // ListPlans 获取计划列表,支持过滤和分页 ListPlans(ctx context.Context, opts repository.ListPlansOptions, page, pageSize int) ([]models.Plan, int64, error) // UpdatePlan 更新计划, wantPlanType 表示期望被修改的计划是什么类型 UpdatePlan(ctx context.Context, plan *models.Plan, wantPlanType models.PlanType) (*models.Plan, error) // DeletePlan 删除计划(软删除) - DeletePlan(ctx context.Context, id uint) error + DeletePlan(ctx context.Context, id uint32) error // StartPlan 启动计划 - StartPlan(ctx context.Context, id uint) error + StartPlan(ctx context.Context, id uint32) error // StopPlan 停止计划 - StopPlan(ctx context.Context, id uint) error + StopPlan(ctx context.Context, id uint32) error } // planServiceImpl 是 Service 接口的具体实现。 @@ -150,7 +150,7 @@ func (s *planServiceImpl) CreatePlan(ctx context.Context, planToCreate *models.P // 优化:无需查询完整的设备对象,只需构建包含ID的结构体即可建立关联 devices := make([]models.Device, len(deviceIDs)) for i, id := range deviceIDs { - devices[i] = models.Device{Model: gorm.Model{ID: id}} + devices[i] = models.Device{Model: models.Model{ID: id}} } taskModel.Devices = devices } @@ -174,7 +174,7 @@ func (s *planServiceImpl) CreatePlan(ctx context.Context, planToCreate *models.P } // GetPlanByID 根据ID获取计划详情 -func (s *planServiceImpl) GetPlanByID(ctx context.Context, id uint) (*models.Plan, error) { +func (s *planServiceImpl) GetPlanByID(ctx context.Context, id uint32) (*models.Plan, error) { planCtx, logger := logs.Trace(ctx, s.ctx, "GetPlanByID") const actionType = "领域层:获取计划详情" @@ -262,7 +262,7 @@ func (s *planServiceImpl) UpdatePlan(ctx context.Context, planToUpdate *models.P // 优化:无需查询完整的设备对象,只需构建包含ID的结构体即可建立关联 devices := make([]models.Device, len(deviceIDs)) for i, id := range deviceIDs { - devices[i] = models.Device{Model: gorm.Model{ID: id}} + devices[i] = models.Device{Model: models.Model{ID: id}} } taskModel.Devices = devices } @@ -290,7 +290,7 @@ func (s *planServiceImpl) UpdatePlan(ctx context.Context, planToUpdate *models.P } // DeletePlan 删除计划(软删除) -func (s *planServiceImpl) DeletePlan(ctx context.Context, id uint) error { +func (s *planServiceImpl) DeletePlan(ctx context.Context, id uint32) error { planCtx, logger := logs.Trace(ctx, s.ctx, "DeletePlan") const actionType = "领域层:删除计划" @@ -328,7 +328,7 @@ func (s *planServiceImpl) DeletePlan(ctx context.Context, id uint) error { } // StartPlan 启动计划 -func (s *planServiceImpl) StartPlan(ctx context.Context, id uint) error { +func (s *planServiceImpl) StartPlan(ctx context.Context, id uint32) error { planCtx, logger := logs.Trace(ctx, s.ctx, "StartPlan") const actionType = "领域层:启动计划" @@ -383,7 +383,7 @@ func (s *planServiceImpl) StartPlan(ctx context.Context, id uint) error { } // StopPlan 停止计划 -func (s *planServiceImpl) StopPlan(ctx context.Context, id uint) error { +func (s *planServiceImpl) StopPlan(ctx context.Context, id uint32) error { planCtx, logger := logs.Trace(ctx, s.ctx, "StopPlan") const actionType = "领域层:停止计划" diff --git a/internal/domain/plan/task.go b/internal/domain/plan/task.go index ba16106..9b010f4 100644 --- a/internal/domain/plan/task.go +++ b/internal/domain/plan/task.go @@ -25,8 +25,8 @@ type Task interface { // TaskDeviceIDResolver 定义了从任务配置中解析设备ID的方法 type TaskDeviceIDResolver interface { // ResolveDeviceIDs 从任务配置中解析并返回所有关联的设备ID列表 - // 返回值: uint数组,每个字符串代表一个设备ID - ResolveDeviceIDs(ctx context.Context) ([]uint, error) + // 返回值: uint32数组,每个字符串代表一个设备ID + ResolveDeviceIDs(ctx context.Context) ([]uint32, error) } // TaskFactory 是一个工厂接口,用于根据任务执行日志创建任务实例。 diff --git a/internal/domain/task/alarm_notification_task.go b/internal/domain/task/alarm_notification_task.go index 2b03a0d..df7642f 100644 --- a/internal/domain/task/alarm_notification_task.go +++ b/internal/domain/task/alarm_notification_task.go @@ -18,7 +18,7 @@ import ( // 如果用户没有指定某个等级的配置, 则默认为该等级消息只发送一次 type AlarmNotificationTaskParams struct { // NotificationIntervals 告警通知的发送间隔时间,键为告警等级,值为时间间隔(分钟) - NotificationIntervals map[models.SeverityLevel]uint `json:"notification_intervals"` + NotificationIntervals map[models.SeverityLevel]uint32 `json:"notification_intervals"` } // AlarmNotificationTask 告警通知发送任务 @@ -107,9 +107,9 @@ func (t *AlarmNotificationTask) OnFailure(ctx context.Context, executeErr error) } // ResolveDeviceIDs 从任务配置中解析并返回所有关联的设备ID列表 -func (t *AlarmNotificationTask) ResolveDeviceIDs(ctx context.Context) ([]uint, error) { +func (t *AlarmNotificationTask) ResolveDeviceIDs(ctx context.Context) ([]uint32, error) { // 告警通知任务与设备无关 - return []uint{}, nil + return []uint32{}, nil } // parseParameters 解析任务参数 diff --git a/internal/domain/task/area_threshold_check_task.go b/internal/domain/task/area_threshold_check_task.go index 2a2362d..2545796 100644 --- a/internal/domain/task/area_threshold_check_task.go +++ b/internal/domain/task/area_threshold_check_task.go @@ -14,12 +14,12 @@ import ( // AreaThresholdCheckParams 定义了区域阈值检查任务的参数 type AreaThresholdCheckParams struct { - AreaControllerID uint `json:"area_controller_id"` // 区域主控ID + AreaControllerID uint32 `json:"area_controller_id"` // 区域主控ID SensorType models.SensorType `json:"sensor_type"` // 传感器类型 Thresholds float32 `json:"thresholds"` // 阈值 Operator models.Operator `json:"operator"` // 操作符 Level models.SeverityLevel `json:"level"` // 告警级别 - ExcludeDeviceIDs []uint `json:"exclude_device_ids"` // 排除的传感器ID + ExcludeDeviceIDs []uint32 `json:"exclude_device_ids"` // 排除的传感器ID } // AreaThresholdCheckTask 是一个任务,用于检查区域阈值并触发告警, 区域主控下的所有没有独立校验任务的设备都会受到此任务的检查 @@ -62,7 +62,7 @@ func (a *AreaThresholdCheckTask) Execute(ctx context.Context) error { } // 构建忽略设备ID的map,方便快速查找 - ignoredMap := make(map[uint]struct{}) + ignoredMap := make(map[uint32]struct{}) for _, id := range a.params.ExcludeDeviceIDs { ignoredMap[id] = struct{}{} } @@ -112,7 +112,7 @@ func (a *AreaThresholdCheckTask) OnFailure(ctx context.Context, executeErr error logger.Errorf("区域阈值检测任务执行失败, 任务ID: %v: 执行失败: %v", a.taskLog.TaskID, executeErr) } -func (a *AreaThresholdCheckTask) ResolveDeviceIDs(ctx context.Context) ([]uint, error) { +func (a *AreaThresholdCheckTask) ResolveDeviceIDs(ctx context.Context) ([]uint32, error) { taskCtx := logs.AddFuncName(ctx, a.ctx, "ResolveDeviceIDs") if err := a.parseParameters(taskCtx); err != nil { return nil, err @@ -156,7 +156,7 @@ func (a *AreaThresholdCheckTask) parseParameters(ctx context.Context) error { params.Level = models.WarnLevel } if params.ExcludeDeviceIDs == nil { - params.ExcludeDeviceIDs = []uint{} + params.ExcludeDeviceIDs = []uint32{} } a.params = params diff --git a/internal/domain/task/delay_task.go b/internal/domain/task/delay_task.go index 916fb77..24bcd9a 100644 --- a/internal/domain/task/delay_task.go +++ b/internal/domain/task/delay_task.go @@ -70,6 +70,6 @@ func (d *DelayTask) OnFailure(ctx context.Context, executeErr error) { logger.Errorf("任务 %v: 执行失败: %v", d.executionTask.TaskID, executeErr) } -func (d *DelayTask) ResolveDeviceIDs(ctx context.Context) ([]uint, error) { - return []uint{}, nil +func (d *DelayTask) ResolveDeviceIDs(ctx context.Context) ([]uint32, error) { + return []uint32{}, nil } diff --git a/internal/domain/task/device_threshold_check_task.go b/internal/domain/task/device_threshold_check_task.go index 3616118..d351650 100644 --- a/internal/domain/task/device_threshold_check_task.go +++ b/internal/domain/task/device_threshold_check_task.go @@ -14,7 +14,7 @@ import ( ) type DeviceThresholdCheckParams struct { - DeviceID uint `json:"device_id"` // 设备ID + DeviceID uint32 `json:"device_id"` // 设备ID SensorType models.SensorType `json:"sensor_type"` // 传感器类型 Thresholds float32 `json:"thresholds"` // 阈值 Operator models.Operator `json:"operator"` // 操作符 @@ -188,10 +188,10 @@ func (d *DeviceThresholdCheckTask) OnFailure(ctx context.Context, executeErr err logger.Errorf("设备阈值检测任务执行失败, 任务ID: %v: 执行失败: %v", d.taskLog.TaskID, executeErr) } -func (d *DeviceThresholdCheckTask) ResolveDeviceIDs(ctx context.Context) ([]uint, error) { +func (d *DeviceThresholdCheckTask) ResolveDeviceIDs(ctx context.Context) ([]uint32, error) { taskCtx := logs.AddFuncName(ctx, d.ctx, "ResolveDeviceIDs") if err := d.parseParameters(taskCtx); err != nil { return nil, err } - return []uint{d.params.DeviceID}, nil + return []uint32{d.params.DeviceID}, nil } diff --git a/internal/domain/task/full_collection_task.go b/internal/domain/task/full_collection_task.go index b963500..9f94d7d 100644 --- a/internal/domain/task/full_collection_task.go +++ b/internal/domain/task/full_collection_task.go @@ -49,7 +49,7 @@ func (t *FullCollectionTask) Execute(ctx context.Context) error { return nil } - sensorsByController := make(map[uint][]*models.Device) + sensorsByController := make(map[uint32][]*models.Device) for _, sensor := range sensors { sensorsByController[sensor.AreaControllerID] = append(sensorsByController[sensor.AreaControllerID], sensor) } @@ -97,7 +97,7 @@ func (t *FullCollectionTask) OnFailure(ctx context.Context, executeErr error) { } // ResolveDeviceIDs 获取当前任务需要使用的设备ID列表 -func (t *FullCollectionTask) ResolveDeviceIDs(ctx context.Context) ([]uint, error) { +func (t *FullCollectionTask) ResolveDeviceIDs(ctx context.Context) ([]uint32, error) { // 全量采集任务不和任何设备绑定, 每轮采集都会重新获取全量传感器 - return []uint{}, nil + return []uint32{}, nil } diff --git a/internal/domain/task/release_feed_weight_task.go b/internal/domain/task/release_feed_weight_task.go index 7b90038..ad58d2e 100644 --- a/internal/domain/task/release_feed_weight_task.go +++ b/internal/domain/task/release_feed_weight_task.go @@ -16,8 +16,8 @@ import ( // ReleaseFeedWeightTaskParams 定义了 ReleaseFeedWeightTask 的参数结构 type ReleaseFeedWeightTaskParams struct { ReleaseWeight float32 `json:"release_weight"` // 需要释放的重量 - FeedPortDeviceID uint `json:"feed_port_device_id"` // 下料口ID - MixingTankDeviceID uint `json:"mixing_tank_device_id"` // 称重传感器ID + FeedPortDeviceID uint32 `json:"feed_port_device_id"` // 下料口ID + MixingTankDeviceID uint32 `json:"mixing_tank_device_id"` // 称重传感器ID } // ReleaseFeedWeightTask 是一个控制下料口释放指定重量的任务 @@ -30,7 +30,7 @@ type ReleaseFeedWeightTask struct { feedPortDevice *models.Device releaseWeight float32 - mixingTankDeviceID uint + mixingTankDeviceID uint32 feedPort device.Service @@ -178,10 +178,10 @@ func (r *ReleaseFeedWeightTask) OnFailure(ctx context.Context, executeErr error) logger.Errorf("善后处理完成, 日志ID:%v", r.claimedLog.ID) } -func (r *ReleaseFeedWeightTask) ResolveDeviceIDs(ctx context.Context) ([]uint, error) { +func (r *ReleaseFeedWeightTask) ResolveDeviceIDs(ctx context.Context) ([]uint32, error) { taskCtx := logs.AddFuncName(ctx, r.ctx, "ResolveDeviceIDs") if err := r.parseParameters(taskCtx); err != nil { return nil, err } - return []uint{r.feedPortDevice.ID, r.mixingTankDeviceID}, nil + return []uint32{r.feedPortDevice.ID, r.mixingTankDeviceID}, nil } diff --git a/internal/infra/config/config.go b/internal/infra/config/config.go index 7700d44..b592074 100644 --- a/internal/infra/config/config.go +++ b/internal/infra/config/config.go @@ -209,19 +209,19 @@ type CollectionConfig struct { type NotificationIntervalsConfig struct { // DebugIntervalMinutes Debug级别告警的通知间隔(分钟) - DebugIntervalMinutes uint `yaml:"debug"` + DebugIntervalMinutes uint32 `yaml:"debug"` // InfoIntervalMinutes Info级别告警的通知间隔(分钟) - InfoIntervalMinutes uint `yaml:"info"` + InfoIntervalMinutes uint32 `yaml:"info"` // WarnIntervalMinutes Warn级别告警的通知间隔(分钟) - WarnIntervalMinutes uint `yaml:"warn"` + WarnIntervalMinutes uint32 `yaml:"warn"` // ErrorIntervalMinutes Error级别告警的通知间隔(分钟) - ErrorIntervalMinutes uint `yaml:"error"` + ErrorIntervalMinutes uint32 `yaml:"error"` // DPanicIntervalMinutes DPanic级别告警的通知间隔(分钟) - DPanicIntervalMinutes uint `yaml:"dpanic"` + DPanicIntervalMinutes uint32 `yaml:"dpanic"` // PanicIntervalMinutes Panic级别告警的通知间隔(分钟) - PanicIntervalMinutes uint `yaml:"panic"` + PanicIntervalMinutes uint32 `yaml:"panic"` // FatalIntervalMinutes Fatal级别告警的通知间隔(分钟) - FatalIntervalMinutes uint `yaml:"fatal"` + FatalIntervalMinutes uint32 `yaml:"fatal"` } // AlarmNotificationConfig 告警通知配置 diff --git a/internal/infra/models/alarm.go b/internal/infra/models/alarm.go index 8306faa..4cd02a1 100644 --- a/internal/infra/models/alarm.go +++ b/internal/infra/models/alarm.go @@ -2,8 +2,6 @@ package models import ( "time" - - "gorm.io/gorm" ) // AlarmSourceType 定义了告警的来源类型 @@ -46,13 +44,13 @@ const ( ) // ActiveAlarm 活跃告警 -// 活跃告警会被更新(如忽略状态),因此保留 gorm.Model 以包含所有标准字段。 +// 活跃告警会被更新(如忽略状态),因此保留 Model 以包含所有标准字段。 type ActiveAlarm struct { - gorm.Model + Model SourceType AlarmSourceType `gorm:"type:varchar(50);not null;index:idx_alarm_uniqueness;comment:告警来源类型" json:"source_type"` // SourceID 告警来源ID,其具体含义取决于 SourceType 字段 (例如:设备ID, 区域主控ID, 猪栏ID)。 - SourceID uint `gorm:"not null;index:idx_alarm_uniqueness;comment:告警来源ID" json:"source_id"` + SourceID uint32 `gorm:"not null;index:idx_alarm_uniqueness;comment:告警来源ID" json:"source_id"` // AlarmCode 是一个机器可读的、标准化的告警类型标识。 // 它与 SourceType 和 SourceID 共同构成一个活跃告警的唯一标识。 @@ -79,15 +77,15 @@ func (ActiveAlarm) TableName() string { } // HistoricalAlarm 历史告警 -// 历史告警是不可变归档数据,我们移除 gorm.Model,并手动定义字段。 +// 历史告警是不可变归档数据,我们移除 Model,并手动定义字段。 // ID 和 TriggerTime 共同构成联合主键,以满足 TimescaleDB 超表的要求。 type HistoricalAlarm struct { // 手动定义主键,ID 仍然自增 - ID uint `gorm:"primaryKey;autoIncrement;comment:主键ID" json:"id"` + ID uint32 `gorm:"primaryKey;autoIncrement;comment:主键ID" json:"id"` SourceType AlarmSourceType `gorm:"type:varchar(50);not null;index;comment:告警来源类型" json:"source_type"` // SourceID 告警来源ID,其具体含义取决于 SourceType 字段 (例如:设备ID, 区域主控ID, 猪栏ID)。 - SourceID uint `gorm:"not null;index;comment:告警来源ID" json:"source_id"` + SourceID uint32 `gorm:"not null;index;comment:告警来源ID" json:"source_id"` // AlarmCode 是一个机器可读的、标准化的告警类型标识。 AlarmCode AlarmCode `gorm:"type:varchar(100);not null;index;comment:告警代码" json:"alarm_code"` @@ -99,8 +97,8 @@ type HistoricalAlarm struct { ResolveTime time.Time `gorm:"not null;comment:告警解决时间" json:"resolve_time"` ResolveMethod string `gorm:"comment:告警解决方式" json:"resolve_method"` - // ResolvedBy 使用指针类型 *uint 来表示可为空解决人, 当字段为空时表示系统自动解决的 - ResolvedBy *uint `gorm:"comment:告警解决人" json:"resolved_by"` + // ResolvedBy 使用指针类型 *uint32 来表示可为空解决人, 当字段为空时表示系统自动解决的 + ResolvedBy *uint32 `gorm:"comment:告警解决人" json:"resolved_by"` } // TableName 指定 HistoricalAlarm 结构体对应的数据库表名 diff --git a/internal/infra/models/device.go b/internal/infra/models/device.go index 3b15bab..aa2af91 100644 --- a/internal/infra/models/device.go +++ b/internal/infra/models/device.go @@ -6,7 +6,6 @@ import ( "strings" "gorm.io/datatypes" - "gorm.io/gorm" ) // --- Properties 结构体定义 --- @@ -19,7 +18,7 @@ type Bus485Properties struct { // AreaController 是一个LoRa转总线(如485)的通信网关 type AreaController struct { - gorm.Model + Model // Name 是主控的业务名称,例如 "1号猪舍主控" Name string `gorm:"not null;unique" json:"name"` @@ -53,20 +52,20 @@ func (AreaController) TableName() string { // Device 代表系统中的所有普通设备 type Device struct { - // gorm.Model 内嵌了标准模型字段 (ID, CreatedAt, UpdatedAt, DeletedAt) - gorm.Model + // Model 内嵌了标准模型字段 (ID, CreatedAt, UpdatedAt, DeletedAt) + Model // Name 是设备的业务名称,应清晰可读,例如 "1号猪舍温度传感器" Name string `gorm:"not null" json:"name"` // DeviceTemplateID 是设备模板的外键 - DeviceTemplateID uint `gorm:"not null;index" json:"device_template_id"` + DeviceTemplateID uint32 `gorm:"not null;index" json:"device_template_id"` // DeviceTemplate 是设备的模板,包含了设备的通用信息 DeviceTemplate DeviceTemplate `json:"device_template"` // AreaControllerID 是区域主控的外键 - AreaControllerID uint `gorm:"not null;index" json:"area_controller_id"` + AreaControllerID uint32 `gorm:"not null;index" json:"area_controller_id"` // AreaController 是设备所属的区域主控 AreaController AreaController `json:"area_controller"` diff --git a/internal/infra/models/device_template.go b/internal/infra/models/device_template.go index a8f2c7e..0f5cb6d 100644 --- a/internal/infra/models/device_template.go +++ b/internal/infra/models/device_template.go @@ -6,7 +6,6 @@ import ( "fmt" "gorm.io/datatypes" - "gorm.io/gorm" ) // ModbusFunctionCode 定义Modbus功能码的枚举类型 @@ -106,7 +105,7 @@ func (sc *SensorCommands) SelfCheck() error { // DeviceTemplate 代表一种物理设备的类型。 type DeviceTemplate struct { - gorm.Model + Model // Name 是此模板的唯一名称, 例如 "FanModel-XYZ-2000" 或 "TempSensor-T1" Name string `gorm:"not null;unique" json:"name"` diff --git a/internal/infra/models/execution.go b/internal/infra/models/execution.go index e8804d2..fc69e13 100644 --- a/internal/infra/models/execution.go +++ b/internal/infra/models/execution.go @@ -27,12 +27,12 @@ const ( // PlanExecutionLog 记录整个计划的一次执行历史 type PlanExecutionLog struct { - ID uint `gorm:"primaryKey"` + ID uint32 `gorm:"primaryKey"` CreatedAt time.Time `gorm:"primaryKey"` // 作为联合主键方便只查询热点数据 UpdatedAt time.Time DeletedAt gorm.DeletedAt `gorm:"index"` - PlanID uint `gorm:"index"` + PlanID uint32 `gorm:"index"` Status ExecutionStatus StartedAt time.Time EndedAt time.Time @@ -46,12 +46,12 @@ func (PlanExecutionLog) TableName() string { // TaskExecutionLog 记录单个任务的一次执行历史 type TaskExecutionLog struct { - ID uint `gorm:"primaryKey"` + ID uint32 `gorm:"primaryKey"` CreatedAt time.Time `gorm:"primaryKey"` // 作为联合主键方便只查询热点数据 UpdatedAt time.Time DeletedAt gorm.DeletedAt `gorm:"index"` - PlanExecutionLogID uint `gorm:"index"` // 关联到某次计划执行 + PlanExecutionLogID uint32 `gorm:"index"` // 关联到某次计划执行 // TaskID 使用 int 类型以容纳特殊的负数ID,代表系统任务 TaskID int `gorm:"index"` @@ -106,7 +106,7 @@ type DeviceCommandLog struct { // DeviceID 是接收此下行任务的设备的ID。 // 对于 LoRaWAN,这通常是区域主控设备的ID。 - DeviceID uint `gorm:"not null;index" json:"device_id"` + DeviceID uint32 `gorm:"not null;index" json:"device_id"` // SentAt 记录下行任务最初发送的时间。 SentAt time.Time `gorm:"primaryKey" json:"sent_at"` @@ -133,7 +133,7 @@ type PendingCollection struct { // DeviceID 是接收此任务的设备ID // 对于 LoRaWAN,这通常是区域主控设备的ID。 - DeviceID uint `gorm:"index"` + DeviceID uint32 `gorm:"index"` // CommandMetadata 存储了此次采集任务对应的设备ID列表,顺序与设备响应值的顺序一致。 CommandMetadata UintArray `gorm:"type:bigint[]"` @@ -183,13 +183,13 @@ func (a AuditContextKey) String() string { // UserActionLog 记录用户的操作历史,用于审计 type UserActionLog struct { // 用 ID 和 Time 组成复合主键, 防止高并发时时间重复 - ID uint `gorm:"primaryKey"` + ID uint32 `gorm:"primaryKey"` // Time 是操作发生的时间,作为主键和超表的时间分区键 Time time.Time `gorm:"primaryKey" json:"time"` // --- Who (谁) --- - UserID uint `gorm:"not null" json:"user_id,omitempty"` + UserID uint32 `gorm:"not null" json:"user_id,omitempty"` Username string `json:"username,omitempty"` // 操作发生时用户名的快照 // --- Where (何地) --- diff --git a/internal/infra/models/farm_asset.go b/internal/infra/models/farm_asset.go index 7d5731c..c4723b0 100644 --- a/internal/infra/models/farm_asset.go +++ b/internal/infra/models/farm_asset.go @@ -1,16 +1,12 @@ package models -import ( - "gorm.io/gorm" -) - /* 猪场固定资产相关模型 */ // PigHouse 定义了猪舍,是猪栏的集合 type PigHouse struct { - gorm.Model + Model Name string `gorm:"size:100;not null;unique;comment:猪舍名称, 如 '育肥舍A栋'"` Description string `gorm:"size:255;comment:描述信息"` Pens []Pen `gorm:"foreignKey:HouseID"` // 一个猪舍包含多个猪栏 @@ -30,10 +26,10 @@ const ( // Pen 是猪栏的物理实体模型, 是所有空间相关数据的“锚点” type Pen struct { - gorm.Model + Model PenNumber string `gorm:"not null;comment:猪栏的唯一编号, 如 A-01"` - HouseID uint `gorm:"index;comment:所属猪舍ID"` - PigBatchID *uint `gorm:"index;comment:关联的猪批次ID"` + HouseID uint32 `gorm:"index;comment:所属猪舍ID"` + PigBatchID *uint32 `gorm:"index;comment:关联的猪批次ID"` Capacity int `gorm:"not null;comment:设计容量 (头)"` Status PenStatus `gorm:"not null;index;comment:猪栏当前状态"` } diff --git a/internal/infra/models/feed.go b/internal/infra/models/feed.go index b1414dc..472ba2d 100644 --- a/internal/infra/models/feed.go +++ b/internal/infra/models/feed.go @@ -2,8 +2,6 @@ package models import ( "time" - - "gorm.io/gorm" ) /* @@ -13,7 +11,7 @@ import ( // RawMaterial 代表饲料的原料。 // 建议:所有重量单位统一存储 (例如, 全部使用 'g'),便于计算和避免转换错误。 type RawMaterial struct { - gorm.Model + Model Name string `gorm:"size:100;unique;not null;comment:原料名称"` Description string `gorm:"size:255;comment:描述"` Quantity float32 `gorm:"not null;comment:库存总量, 单位: g"` @@ -25,8 +23,8 @@ func (RawMaterial) TableName() string { // RawMaterialPurchase 记录了原料的每一次采购。 type RawMaterialPurchase struct { - gorm.Model - RawMaterialID uint `gorm:"not null;index;comment:关联的原料ID"` + Model + RawMaterialID uint32 `gorm:"not null;index;comment:关联的原料ID"` RawMaterial RawMaterial `gorm:"foreignKey:RawMaterialID"` Supplier string `gorm:"size:100;comment:供应商"` Amount float32 `gorm:"not null;comment:采购数量, 单位: g"` @@ -54,11 +52,11 @@ const ( // RawMaterialStockLog 记录了原料库存的所有变动,提供了完整的追溯链。 type RawMaterialStockLog struct { - gorm.Model - RawMaterialID uint `gorm:"not null;index;comment:关联的原料ID"` + Model + RawMaterialID uint32 `gorm:"not null;index;comment:关联的原料ID"` ChangeAmount float32 `gorm:"not null;comment:变动数量, 正数为入库, 负数为出库"` SourceType StockLogSourceType `gorm:"size:50;not null;index;comment:库存变动来源类型"` - SourceID uint `gorm:"not null;index;comment:来源记录的ID (如 RawMaterialPurchase.ID 或 FeedUsageRecord.ID)"` + SourceID uint32 `gorm:"not null;index;comment:来源记录的ID (如 RawMaterialPurchase.ID 或 FeedUsageRecord.ID)"` HappenedAt time.Time `gorm:"primaryKey;comment:业务发生时间"` Remarks string `gorm:"comment:备注, 如主动领取的理由等"` } @@ -70,7 +68,7 @@ func (RawMaterialStockLog) TableName() string { // FeedFormula 代表饲料配方。 // 对于没有配方的外购饲料,可以将其视为一种特殊的 RawMaterial, 并为其创建一个仅包含它自己的 FeedFormula。 type FeedFormula struct { - gorm.Model + Model Name string `gorm:"size:100;unique;not null;comment:配方名称"` Description string `gorm:"size:255;comment:描述"` Components []FeedFormulaComponent `gorm:"foreignKey:FeedFormulaID"` @@ -82,9 +80,9 @@ func (FeedFormula) TableName() string { // FeedFormulaComponent 代表配方中的一种原料及其占比。 type FeedFormulaComponent struct { - gorm.Model - FeedFormulaID uint `gorm:"not null;index;comment:外键到 FeedFormula"` - RawMaterialID uint `gorm:"not null;index;comment:外键到 RawMaterial"` + Model + FeedFormulaID uint32 `gorm:"not null;index;comment:外键到 FeedFormula"` + RawMaterialID uint32 `gorm:"not null;index;comment:外键到 RawMaterial"` RawMaterial RawMaterial `gorm:"foreignKey:RawMaterialID"` Percentage float32 `gorm:"not null;comment:该原料在配方中的百分比 (0-1.0)"` } @@ -97,14 +95,14 @@ func (FeedFormulaComponent) TableName() string { // 应用层逻辑:当一条使用记录被创建时,应根据其使用的 FeedFormula, // 计算出每种 RawMaterial 的消耗量,并在 RawMaterialStockLog 中创建对应的出库记录。 type FeedUsageRecord struct { - gorm.Model - PenID uint `gorm:"not null;index;comment:关联的猪栏ID"` + Model + PenID uint32 `gorm:"not null;index;comment:关联的猪栏ID"` Pen Pen `gorm:"foreignKey:PenID"` - FeedFormulaID uint `gorm:"not null;index;comment:使用的饲料配方ID"` + FeedFormulaID uint32 `gorm:"not null;index;comment:使用的饲料配方ID"` FeedFormula FeedFormula `gorm:"foreignKey:FeedFormulaID"` Amount float32 `gorm:"not null;comment:使用数量, 单位: g"` RecordedAt time.Time `gorm:"primaryKey;comment:记录时间"` - OperatorID uint `gorm:"not null;comment:操作员"` + OperatorID uint32 `gorm:"not null;comment:操作员"` Remarks string `gorm:"comment:备注, 如 '例行喂料, 弱猪补料' 等"` } diff --git a/internal/infra/models/medication.go b/internal/infra/models/medication.go index c1bd710..052fb60 100644 --- a/internal/infra/models/medication.go +++ b/internal/infra/models/medication.go @@ -4,7 +4,6 @@ import ( "time" "gorm.io/datatypes" - "gorm.io/gorm" ) /* @@ -57,7 +56,7 @@ type PowderInstructions struct { // Medication 定义了兽药/疫苗的基本信息模型 type Medication struct { - gorm.Model + Model Name string `gorm:"size:100;not null;comment:药品名称" json:"name"` Type MedicationType `gorm:"size:20;not null;comment:兽药类型 (粉剂, 针剂, 疫苗)" json:"type"` Category MedicationCategory `gorm:"size:30;not null;comment:兽药种类 (四环素类, 磺胺类等)" json:"category"` @@ -82,15 +81,15 @@ const ( // MedicationLog 记录了对整个猪批次的用药情况 type MedicationLog struct { - gorm.Model - PigBatchID uint `gorm:"not null;index;comment:关联的猪批次ID"` - MedicationID uint `gorm:"not null;index;comment:关联的药品ID"` + Model + PigBatchID uint32 `gorm:"not null;index;comment:关联的猪批次ID"` + MedicationID uint32 `gorm:"not null;index;comment:关联的药品ID"` Medication Medication `gorm:"foreignKey:MedicationID"` // 预加载药品信息 DosageUsed float32 `gorm:"not null;comment:使用的总剂量 (单位由药品决定,如g或ml)"` TargetCount int `gorm:"not null;comment:用药对象数量"` Reason MedicationReasonType `gorm:"size:20;not null;comment:用药原因"` Description string `gorm:"size:255;comment:具体描述,如'治疗呼吸道病'"` - OperatorID uint `gorm:"comment:操作员ID"` + OperatorID uint32 `gorm:"comment:操作员ID"` HappenedAt time.Time `gorm:"primaryKey;comment:用药时间"` } diff --git a/internal/infra/models/models.go b/internal/infra/models/models.go index 9fbb914..fa35ec0 100644 --- a/internal/infra/models/models.go +++ b/internal/infra/models/models.go @@ -6,10 +6,20 @@ import ( "fmt" "strconv" "strings" + "time" "go.uber.org/zap/zapcore" + "gorm.io/gorm" ) +// Model 用于代替gorm.Model, 使用uint32以节约空间 +type Model struct { + ID uint32 `gorm:"primarykey"` + CreatedAt time.Time + UpdatedAt time.Time + DeletedAt gorm.DeletedAt `gorm:"index"` +} + // GetAllModels 返回一个包含所有数据库模型实例的切片。 // 这个函数用于在数据库初始化时自动迁移所有的表结构。 func GetAllModels() []interface{} { @@ -72,10 +82,10 @@ func GetAllModels() []interface{} { } } -// UintArray 是一个自定义类型,代表 uint 的切片。 +// UintArray 是一个自定义类型,代表 uint32 的切片。 // 它实现了 gorm.Scanner 和 driver.Valuer 接口, // 以便能与数据库的 bigint[] 类型进行原生映射。 -type UintArray []uint +type UintArray []uint32 // Value 实现了 driver.Valuer 接口。 // 它告诉 GORM 如何将 UintArray ([]) 转换为数据库能够理解的格式。 @@ -117,19 +127,19 @@ func (a *UintArray) Scan(src interface{}) error { // 去掉花括号 srcStr = strings.Trim(srcStr, "{}") if srcStr == "" { - *a = []uint{} + *a = []uint32{} return nil } // 按逗号分割 parts := strings.Split(srcStr, ",") - arr := make([]uint, len(parts)) + arr := make([]uint32, len(parts)) for i, p := range parts { val, err := strconv.ParseUint(p, 10, 64) if err != nil { return fmt.Errorf("解析 UintArray 元素失败: %w", err) } - arr[i] = uint(val) + arr[i] = uint32(val) } *a = arr diff --git a/internal/infra/models/notify.go b/internal/infra/models/notify.go index d63b5cf..2602267 100644 --- a/internal/infra/models/notify.go +++ b/internal/infra/models/notify.go @@ -2,8 +2,6 @@ package models import ( "time" - - "gorm.io/gorm" ) // NotifierType 定义了通知器的类型。 @@ -31,12 +29,12 @@ const ( // Notification 表示已发送或尝试发送的通知记录。 type Notification struct { - gorm.Model + Model // NotifierType 通知器类型 (例如:"邮件", "企业微信", "飞书", "日志") NotifierType NotifierType `gorm:"type:varchar(20);not null;index" json:"notifier_type"` // UserID 接收通知的用户ID,用于追溯通知记录到特定用户 - UserID uint `gorm:"index" json:"user_id"` // 增加 UserID 字段,并添加索引 + UserID uint32 `gorm:"index" json:"user_id"` // 增加 UserID 字段,并添加索引 // Title 通知标题 Title string `gorm:"type:varchar(255);not null" json:"title"` // Message 通知内容 diff --git a/internal/infra/models/pig_batch.go b/internal/infra/models/pig_batch.go index 37187c9..ee9ca0d 100644 --- a/internal/infra/models/pig_batch.go +++ b/internal/infra/models/pig_batch.go @@ -2,8 +2,6 @@ package models import ( "time" - - "gorm.io/gorm" ) /* @@ -32,7 +30,7 @@ const ( // PigBatch 是猪批次的核心模型,代表了一群被共同管理的猪 type PigBatch struct { - gorm.Model + Model BatchNumber string `gorm:"size:50;not null;uniqueIndex;comment:批次编号,如 2024-W25-A01"` OriginType PigBatchOriginType `gorm:"size:20;not null;comment:批次来源 (自繁, 外购)"` StartDate time.Time `gorm:"not null;comment:批次开始日期 (如转入日或购买日)"` @@ -65,14 +63,14 @@ const ( // PigBatchLog 记录了猪批次数量或状态的每一次变更 type PigBatchLog struct { - gorm.Model - PigBatchID uint `gorm:"not null;index;comment:关联的猪批次ID"` + Model + PigBatchID uint32 `gorm:"not null;index;comment:关联的猪批次ID"` ChangeType LogChangeType `gorm:"size:20;not null;comment:变更类型"` ChangeCount int `gorm:"not null;comment:数量变化,负数表示减少"` Reason string `gorm:"size:255;comment:变更原因描述"` BeforeCount int `gorm:"not null;comment:变更前总数"` AfterCount int `gorm:"not null;comment:变更后总数"` - OperatorID uint `gorm:"comment:操作员ID"` + OperatorID uint32 `gorm:"comment:操作员ID"` HappenedAt time.Time `gorm:"primaryKey;comment:事件发生时间"` } @@ -82,10 +80,10 @@ func (PigBatchLog) TableName() string { // WeighingBatch 记录了一次批次称重的信息 type WeighingBatch struct { - gorm.Model + Model WeighingTime time.Time `gorm:"primaryKey;comment:称重时间"` Description string `gorm:"size:255;comment:批次称重描述"` - PigBatchID uint `gorm:"not null;index;comment:关联的猪批次ID"` + PigBatchID uint32 `gorm:"not null;index;comment:关联的猪批次ID"` } func (WeighingBatch) TableName() string { @@ -94,11 +92,11 @@ func (WeighingBatch) TableName() string { // WeighingRecord 记录了单次称重信息 type WeighingRecord struct { - gorm.Model + Model Weight float32 `gorm:"not null;comment:单只猪重量 (kg)"` - WeighingBatchID uint `gorm:"not null;index;comment:关联的批次称重ID"` - PenID uint `gorm:"not null;index;comment:所在猪圈ID"` - OperatorID uint `gorm:"not null;comment:操作员ID"` + WeighingBatchID uint32 `gorm:"not null;index;comment:关联的批次称重ID"` + PenID uint32 `gorm:"not null;index;comment:所在猪圈ID"` + OperatorID uint32 `gorm:"not null;comment:操作员ID"` Remark string `gorm:"size:255;comment:备注"` WeighingTime time.Time `gorm:"primaryKey;comment:称重时间"` } diff --git a/internal/infra/models/pig_sick.go b/internal/infra/models/pig_sick.go index caf21a9..be85b19 100644 --- a/internal/infra/models/pig_sick.go +++ b/internal/infra/models/pig_sick.go @@ -2,8 +2,6 @@ package models import ( "time" - - "gorm.io/gorm" ) // PigBatchSickPigTreatmentLocation 定义了病猪治疗地点 @@ -29,16 +27,16 @@ const ( // PigSickLog 记录了猪批次中病猪数量的变化日志 type PigSickLog struct { - gorm.Model - PigBatchID uint `gorm:"primaryKey;comment:关联的猪批次ID"` - PenID uint `gorm:"not null;index;comment:所在猪圈ID"` + Model + PigBatchID uint32 `gorm:"primaryKey;comment:关联的猪批次ID"` + PenID uint32 `gorm:"not null;index;comment:所在猪圈ID"` ChangeCount int `gorm:"not null;comment:变化数量, 正数表示新增, 负数表示移除"` Reason PigBatchSickPigReasonType `gorm:"size:20;not null;comment:变化原因 (如: 患病, 康复, 死亡, 转入, 转出, 其他)"` BeforeCount int `gorm:"comment:变化前的数量"` AfterCount int `gorm:"comment:变化后的数量"` Remarks string `gorm:"size:255;comment:备注"` TreatmentLocation PigBatchSickPigTreatmentLocation `gorm:"size:50;comment:治疗地点"` - OperatorID uint `gorm:"comment:操作员ID"` + OperatorID uint32 `gorm:"comment:操作员ID"` HappenedAt time.Time `gorm:"primaryKey;comment:事件发生时间"` } diff --git a/internal/infra/models/pig_trade.go b/internal/infra/models/pig_trade.go index e46a716..4893c98 100644 --- a/internal/infra/models/pig_trade.go +++ b/internal/infra/models/pig_trade.go @@ -2,21 +2,19 @@ package models import ( "time" - - "gorm.io/gorm" ) // PigPurchase 记录了猪只采购信息 type PigPurchase struct { - gorm.Model - PigBatchID uint `gorm:"not null;index;comment:关联的猪批次ID"` + Model + PigBatchID uint32 `gorm:"not null;index;comment:关联的猪批次ID"` PurchaseDate time.Time `gorm:"primaryKey;comment:采购日期"` Supplier string `gorm:"comment:供应商"` Quantity int `gorm:"not null;comment:采购数量"` UnitPrice float32 `gorm:"not null;comment:单价"` TotalPrice float32 `gorm:"not null;comment:总价"` Remarks string `gorm:"size:255;comment:备注"` - OperatorID uint `gorm:"comment:操作员ID"` + OperatorID uint32 `gorm:"comment:操作员ID"` } func (PigPurchase) TableName() string { @@ -25,15 +23,15 @@ func (PigPurchase) TableName() string { // PigSale 记录了猪只销售信息 type PigSale struct { - gorm.Model - PigBatchID uint `gorm:"not null;index;comment:关联的猪批次ID"` + Model + PigBatchID uint32 `gorm:"not null;index;comment:关联的猪批次ID"` SaleDate time.Time `gorm:"primaryKey;comment:销售日期"` Buyer string `gorm:"comment:购买方"` Quantity int `gorm:"not null;comment:销售数量"` UnitPrice float32 `gorm:"not null;comment:单价"` TotalPrice float32 `gorm:"not null;comment:总价"` Remarks string `gorm:"size:255;comment:备注"` - OperatorID uint `gorm:"comment:操作员ID"` + OperatorID uint32 `gorm:"comment:操作员ID"` } func (PigSale) TableName() string { diff --git a/internal/infra/models/pig_transfer.go b/internal/infra/models/pig_transfer.go index 3fc3a04..0af3059 100644 --- a/internal/infra/models/pig_transfer.go +++ b/internal/infra/models/pig_transfer.go @@ -2,8 +2,6 @@ package models import ( "time" - - "gorm.io/gorm" ) // PigTransferType 定义了猪只迁移的类型 @@ -23,14 +21,14 @@ const ( // PigTransferLog 记录了每一次猪只数量在猪栏间的变动事件。 // 它作为事件溯源的基础,用于推算任意时间点猪栏的猪只数量。 type PigTransferLog struct { - gorm.Model + Model TransferTime time.Time `gorm:"primaryKey;comment:迁移发生时间" json:"transfer_time"` // 迁移发生时间,作为联合主键 - PigBatchID uint `gorm:"primaryKey;comment:关联的猪群ID" json:"pig_batch_id"` // 关联的猪群ID,作为联合主键 - PenID uint `gorm:"primaryKey;comment:发生变动的猪栏ID" json:"pen_id"` // 发生变动的猪栏ID,作为联合主键 + PigBatchID uint32 `gorm:"primaryKey;comment:关联的猪群ID" json:"pig_batch_id"` // 关联的猪群ID,作为联合主键 + PenID uint32 `gorm:"primaryKey;comment:发生变动的猪栏ID" json:"pen_id"` // 发生变动的猪栏ID,作为联合主键 Quantity int `gorm:"not null;comment:变动数量(正数表示增加,负数表示减少)" json:"quantity"` // 变动数量(正数表示增加,负数减少) Type PigTransferType `gorm:"not null;comment:变动类型" json:"type"` // 变动类型,使用枚举类型 CorrelationID string `gorm:"comment:用于关联一次完整操作(如一次调栏会产生两条日志)" json:"correlation_id"` // 用于关联一次完整操作 - OperatorID uint `gorm:"not null;comment:操作员ID" json:"operator_id"` // 操作员ID + OperatorID uint32 `gorm:"not null;comment:操作员ID" json:"operator_id"` // 操作员ID Remarks string `gorm:"comment:备注" json:"remarks"` } diff --git a/internal/infra/models/plan.go b/internal/infra/models/plan.go index 86efc6d..7827980 100644 --- a/internal/infra/models/plan.go +++ b/internal/infra/models/plan.go @@ -74,15 +74,15 @@ const ( // Plan 代表系统中的一个计划,可以包含子计划或任务 type Plan struct { - gorm.Model + Model Name PlanName `gorm:"not null" json:"name"` Description string `json:"description"` PlanType PlanType `gorm:"not null;index" json:"plan_type"` // 任务类型, 包括系统任务和用户自定义任务 ExecutionType PlanExecutionType `gorm:"not null;index" json:"execution_type"` Status PlanStatus `gorm:"default:'已禁用';index" json:"status"` // 计划是否被启动 - ExecuteNum uint `gorm:"default:0" json:"execute_num"` // 计划预期执行次数 - ExecuteCount uint `gorm:"default:0" json:"execute_count"` // 执行计数器 + ExecuteNum uint32 `gorm:"default:0" json:"execute_num"` // 计划预期执行次数 + ExecuteCount uint32 `gorm:"default:0" json:"execute_count"` // 执行计数器 // 针对 PlanExecutionTypeAutomatic,使用 Cron 表达式定义调度规则 CronExpression string `json:"cron_expression"` @@ -163,12 +163,12 @@ func (p *Plan) ReorderSteps() { // SubPlan 代表作为另一个计划一部分的子计划,具有执行顺序 type SubPlan struct { - gorm.Model + Model - ParentPlanID uint `gorm:"not null;index" json:"parent_plan_id"` // 父计划的ID - ChildPlanID uint `gorm:"not null;index" json:"child_plan_id"` // 子计划的ID (它本身也是一个 Plan) - ExecutionOrder int `gorm:"not null" json:"execution_order"` // 在父计划中的执行顺序 - ChildPlan *Plan `gorm:"-" json:"child_plan"` // 完整子计划数据,仅内存中 + ParentPlanID uint32 `gorm:"not null;index" json:"parent_plan_id"` // 父计划的ID + ChildPlanID uint32 `gorm:"not null;index" json:"child_plan_id"` // 子计划的ID (它本身也是一个 Plan) + ExecutionOrder int `gorm:"not null" json:"execution_order"` // 在父计划中的执行顺序 + ChildPlan *Plan `gorm:"-" json:"child_plan"` // 完整子计划数据,仅内存中 } // TableName 自定义 GORM 使用的数据库表名 @@ -184,7 +184,7 @@ type Task struct { UpdatedAt time.Time DeletedAt gorm.DeletedAt `gorm:"index"` // 保持软删除功能 - PlanID uint `gorm:"not null;index" json:"plan_id"` // 此任务所属计划的ID + PlanID uint32 `gorm:"not null;index" json:"plan_id"` // 此任务所属计划的ID Name string `gorm:"not null" json:"name"` Description string `json:"description"` ExecutionOrder int `gorm:"not null" json:"execution_order"` // 在计划中的执行顺序 @@ -229,9 +229,9 @@ func (t *Task) SaveParameters(v interface{}) error { // DeviceTask 是设备和任务之间的关联模型,表示一个设备可以执行多个任务,一个任务可以被多个设备执行。 type DeviceTask struct { - gorm.Model - DeviceID uint `gorm:"not null;index"` // 设备ID - TaskID uint `gorm:"not null;index"` // 任务ID + Model + DeviceID uint32 `gorm:"not null;index"` // 设备ID + TaskID uint32 `gorm:"not null;index"` // 任务ID // 可选:如果需要存储关联的额外信息,可以在这里添加字段,例如: // Configuration datatypes.JSON `json:"configuration"` // 任务在特定设备上的配置 diff --git a/internal/infra/models/schedule.go b/internal/infra/models/schedule.go index 12a6384..98f06fc 100644 --- a/internal/infra/models/schedule.go +++ b/internal/infra/models/schedule.go @@ -7,8 +7,8 @@ import ( // PendingTask 是一个待执行任务队列, 里面会储存待执行的Task以及这个Task什么时候执行 // 它是一个纯粹的工作队列,任务被认领后即被删除。 type PendingTask struct { - // 手动填充必须字段以实现硬删除,不内嵌 gorm.Model - ID uint `gorm:"primarykey"` + // 手动填充必须字段以实现硬删除,不内嵌 Model + ID uint32 `gorm:"primarykey"` CreatedAt time.Time UpdatedAt time.Time @@ -21,7 +21,7 @@ type PendingTask struct { Task *Task `gorm:"foreignKey:TaskID"` ExecuteAt time.Time `gorm:"index"` // 任务执行时间 - TaskExecutionLogID uint `gorm:"unique;not null;index"` // 对应的执行历史记录ID + TaskExecutionLogID uint32 `gorm:"unique;not null;index"` // 对应的执行历史记录ID // 通过 TaskExecutionLogID 关联到唯一的 TaskExecutionLog 记录 // ON DELETE CASCADE 确保如果日志被删除,这个待办任务也会被自动清理 diff --git a/internal/infra/models/sensor_data.go b/internal/infra/models/sensor_data.go index a04481a..8165bcc 100644 --- a/internal/infra/models/sensor_data.go +++ b/internal/infra/models/sensor_data.go @@ -55,10 +55,10 @@ type SensorData struct { Time time.Time `gorm:"primaryKey" json:"time"` // DeviceID 是传感器的唯一标识符,作为复合主键的另一部分。 - DeviceID uint `gorm:"primaryKey" json:"device_id"` + DeviceID uint32 `gorm:"primaryKey" json:"device_id"` // AreaControllerID 是上报此数据的区域主控的ID。 - AreaControllerID uint `json:"area_controller_id"` + AreaControllerID uint32 `json:"area_controller_id"` // SensorType 是传感数据的类型 SensorType SensorType `gorm:"not null;index" json:"sensor_type"` diff --git a/internal/infra/models/user.go b/internal/infra/models/user.go index 6212136..2d66ca7 100644 --- a/internal/infra/models/user.go +++ b/internal/infra/models/user.go @@ -38,9 +38,9 @@ func (ci ContactInfo) Value() (driver.Value, error) { // User 代表系统中的用户模型 type User struct { - // gorm.Model 内嵌了 ID, CreatedAt, UpdatedAt, 和 DeletedAt + // Model 内嵌了 ID, CreatedAt, UpdatedAt, 和 DeletedAt // DeletedAt 字段的存在自动为 GORM 开启了软删除模式 - gorm.Model + Model // Username 是用户的登录名,应该是唯一的 // 修正了 gorm 标签的拼写错误 (移除了 gorm 后面的冒号) diff --git a/internal/infra/repository/alarm_repository.go b/internal/infra/repository/alarm_repository.go index f513778..7eea0be 100644 --- a/internal/infra/repository/alarm_repository.go +++ b/internal/infra/repository/alarm_repository.go @@ -15,7 +15,7 @@ import ( // ActiveAlarmListOptions 定义了查询活跃告警列表时的可选参数 type ActiveAlarmListOptions struct { SourceType *models.AlarmSourceType // 按告警来源类型过滤 - SourceID *uint // 按告警来源ID过滤 + SourceID *uint32 // 按告警来源ID过滤 Level *models.SeverityLevel // 按告警严重性等级过滤 IsIgnored *bool // 按是否被忽略过滤 TriggerTime *time.Time // 告警触发时间范围 - 开始时间 @@ -26,7 +26,7 @@ type ActiveAlarmListOptions struct { // HistoricalAlarmListOptions 定义了查询历史告警列表时的可选参数 type HistoricalAlarmListOptions struct { SourceType *models.AlarmSourceType // 按告警来源类型过滤 - SourceID *uint // 按告警来源ID过滤 + SourceID *uint32 // 按告警来源ID过滤 Level *models.SeverityLevel // 按告警严重性等级过滤 TriggerTimeStart *time.Time // 告警触发时间范围 - 开始时间 TriggerTimeEnd *time.Time // 告警触发时间范围 - 结束时间 @@ -41,19 +41,19 @@ type AlarmRepository interface { CreateActiveAlarm(ctx context.Context, alarm *models.ActiveAlarm) error // IsAlarmActiveInUse 检查具有相同来源和告警代码的告警当前是否处于活跃表中 - IsAlarmActiveInUse(ctx context.Context, sourceType models.AlarmSourceType, sourceID uint, alarmCode models.AlarmCode) (bool, error) + IsAlarmActiveInUse(ctx context.Context, sourceType models.AlarmSourceType, sourceID uint32, alarmCode models.AlarmCode) (bool, error) // GetActiveAlarmByUniqueFieldsTx 在指定事务中根据唯一业务键获取一个活跃告警 - GetActiveAlarmByUniqueFieldsTx(ctx context.Context, tx *gorm.DB, sourceType models.AlarmSourceType, sourceID uint, alarmCode models.AlarmCode) (*models.ActiveAlarm, error) + GetActiveAlarmByUniqueFieldsTx(ctx context.Context, tx *gorm.DB, sourceType models.AlarmSourceType, sourceID uint32, alarmCode models.AlarmCode) (*models.ActiveAlarm, error) // CreateHistoricalAlarmTx 在指定事务中创建一条历史告警记录 CreateHistoricalAlarmTx(ctx context.Context, tx *gorm.DB, alarm *models.HistoricalAlarm) error // DeleteActiveAlarmTx 在指定事务中根据主键 ID 删除一个活跃告警 - DeleteActiveAlarmTx(ctx context.Context, tx *gorm.DB, id uint) error + DeleteActiveAlarmTx(ctx context.Context, tx *gorm.DB, id uint32) error // UpdateIgnoreStatus 更新指定告警的忽略状态 - UpdateIgnoreStatus(ctx context.Context, id uint, isIgnored bool, ignoredUntil *time.Time) error + UpdateIgnoreStatus(ctx context.Context, id uint32, isIgnored bool, ignoredUntil *time.Time) error // ListActiveAlarms 支持分页和过滤的活跃告警列表查询。 // 返回活跃告警列表、总记录数和错误。 @@ -67,16 +67,16 @@ type AlarmRepository interface { // lastNotifiedAt: 传入具体的发送时间。 // isIgnored: 告警新的忽略状态。 // ignoredUntil: 告警新的忽略截止时间 (nil 表示没有忽略截止时间/已取消忽略)。 - UpdateAlarmNotificationStatus(ctx context.Context, alarmID uint, lastNotifiedAt time.Time, isIgnored bool, ignoredUntil *time.Time) error + UpdateAlarmNotificationStatus(ctx context.Context, alarmID uint32, lastNotifiedAt time.Time, isIgnored bool, ignoredUntil *time.Time) error // <-- 下列两个方法是为了性能做出的架构妥协, 业务逻辑入侵仓库层带来的收益远大于通过业务层进行数据筛选 --> // ListAlarmsForNotification 查询满足发送告警消息条件的活跃告警列表。 // 返回活跃告警列表和错误。 // intervalByLevel: key=SeverityLevel, value=interval_in_minutes - ListAlarmsForNotification(ctx context.Context, intervalByLevel map[models.SeverityLevel]uint) ([]models.ActiveAlarm, error) + ListAlarmsForNotification(ctx context.Context, intervalByLevel map[models.SeverityLevel]uint32) ([]models.ActiveAlarm, error) // 查询满足发送告警消息条件的记录总数 - CountAlarmsForNotification(ctx context.Context, intervalByLevel map[models.SeverityLevel]uint) (int64, error) + CountAlarmsForNotification(ctx context.Context, intervalByLevel map[models.SeverityLevel]uint32) (int64, error) } // gormAlarmRepository 是 AlarmRepository 的 GORM 实现。 @@ -100,7 +100,7 @@ func (r *gormAlarmRepository) CreateActiveAlarm(ctx context.Context, alarm *mode } // IsAlarmActiveInUse 检查具有相同来源和告警代码的告警当前是否处于活跃表中 -func (r *gormAlarmRepository) IsAlarmActiveInUse(ctx context.Context, sourceType models.AlarmSourceType, sourceID uint, alarmCode models.AlarmCode) (bool, error) { +func (r *gormAlarmRepository) IsAlarmActiveInUse(ctx context.Context, sourceType models.AlarmSourceType, sourceID uint32, alarmCode models.AlarmCode) (bool, error) { repoCtx := logs.AddFuncName(ctx, r.ctx, "IsAlarmActiveInUse") var count int64 err := r.db.WithContext(repoCtx).Model(&models.ActiveAlarm{}). @@ -113,7 +113,7 @@ func (r *gormAlarmRepository) IsAlarmActiveInUse(ctx context.Context, sourceType } // GetActiveAlarmByUniqueFieldsTx 在指定事务中根据唯一业务键获取一个活跃告警 -func (r *gormAlarmRepository) GetActiveAlarmByUniqueFieldsTx(ctx context.Context, tx *gorm.DB, sourceType models.AlarmSourceType, sourceID uint, alarmCode models.AlarmCode) (*models.ActiveAlarm, error) { +func (r *gormAlarmRepository) GetActiveAlarmByUniqueFieldsTx(ctx context.Context, tx *gorm.DB, sourceType models.AlarmSourceType, sourceID uint32, alarmCode models.AlarmCode) (*models.ActiveAlarm, error) { repoCtx := logs.AddFuncName(ctx, r.ctx, "GetActiveAlarmByUniqueFieldsTx") var alarm models.ActiveAlarm err := tx.WithContext(repoCtx). @@ -129,14 +129,14 @@ func (r *gormAlarmRepository) CreateHistoricalAlarmTx(ctx context.Context, tx *g } // DeleteActiveAlarmTx 在指定事务中根据主键 ID 删除一个活跃告警 -func (r *gormAlarmRepository) DeleteActiveAlarmTx(ctx context.Context, tx *gorm.DB, id uint) error { +func (r *gormAlarmRepository) DeleteActiveAlarmTx(ctx context.Context, tx *gorm.DB, id uint32) error { repoCtx := logs.AddFuncName(ctx, r.ctx, "DeleteActiveAlarmTx") // 使用 Unscoped() 确保执行物理删除,而不是软删除 return tx.WithContext(repoCtx).Unscoped().Delete(&models.ActiveAlarm{}, id).Error } // UpdateIgnoreStatus 更新指定告警的忽略状态 -func (r *gormAlarmRepository) UpdateIgnoreStatus(ctx context.Context, id uint, isIgnored bool, ignoredUntil *time.Time) error { +func (r *gormAlarmRepository) UpdateIgnoreStatus(ctx context.Context, id uint32, isIgnored bool, ignoredUntil *time.Time) error { repoCtx := logs.AddFuncName(ctx, r.ctx, "UpdateIgnoreStatus") updates := map[string]interface{}{ "is_ignored": isIgnored, @@ -266,7 +266,7 @@ func (r *gormAlarmRepository) ListHistoricalAlarms(ctx context.Context, opts His return results, total, err } -func (r *gormAlarmRepository) UpdateAlarmNotificationStatus(ctx context.Context, alarmID uint, lastNotifiedAt time.Time, isIgnored bool, ignoredUntil *time.Time) error { +func (r *gormAlarmRepository) UpdateAlarmNotificationStatus(ctx context.Context, alarmID uint32, lastNotifiedAt time.Time, isIgnored bool, ignoredUntil *time.Time) error { repoCtx := logs.AddFuncName(ctx, r.ctx, "UpdateAlarmNotificationStatus") // 1. 内部安全地构造 map,将强类型参数转换为 GORM 需要的格式 @@ -290,7 +290,7 @@ func (r *gormAlarmRepository) UpdateAlarmNotificationStatus(ctx context.Context, } // CountAlarmsForNotification 查询满足发送告警消息条件的记录总数 -func (r *gormAlarmRepository) CountAlarmsForNotification(ctx context.Context, intervalByLevel map[models.SeverityLevel]uint) (int64, error) { +func (r *gormAlarmRepository) CountAlarmsForNotification(ctx context.Context, intervalByLevel map[models.SeverityLevel]uint32) (int64, error) { repoCtx := logs.AddFuncName(ctx, r.ctx, "CountAlarmsForNotification") var total int64 @@ -311,7 +311,7 @@ func (r *gormAlarmRepository) CountAlarmsForNotification(ctx context.Context, in } // ListAlarmsForNotification 查询满足发送告警消息条件的活跃告警列表 -func (r *gormAlarmRepository) ListAlarmsForNotification(ctx context.Context, intervalByLevel map[models.SeverityLevel]uint) ([]models.ActiveAlarm, error) { +func (r *gormAlarmRepository) ListAlarmsForNotification(ctx context.Context, intervalByLevel map[models.SeverityLevel]uint32) ([]models.ActiveAlarm, error) { repoCtx := logs.AddFuncName(ctx, r.ctx, "ListAlarmsForNotification") var results []models.ActiveAlarm @@ -332,7 +332,7 @@ func (r *gormAlarmRepository) ListAlarmsForNotification(ctx context.Context, int } // buildNotificationBaseQuery 负责组合 Group A 和 Group B 的逻辑 -func (r *gormAlarmRepository) buildNotificationBaseQuery(tx *gorm.DB, intervalByLevel map[models.SeverityLevel]uint) *gorm.DB { +func (r *gormAlarmRepository) buildNotificationBaseQuery(tx *gorm.DB, intervalByLevel map[models.SeverityLevel]uint32) *gorm.DB { // 1. 获取所有配置的 Level 列表 configuredLevels := make([]models.SeverityLevel, 0, len(intervalByLevel)) @@ -392,7 +392,7 @@ func (r *gormAlarmRepository) buildGroupAClause(tx *gorm.DB, configuredLevels [] // buildGroupBClause 构造 Group B 的 WHERE 语句和参数列表。 // 针对 Level 存在配置的告警,使用“间隔发送”逻辑。 -func (r *gormAlarmRepository) buildGroupBClause(tx *gorm.DB, intervalByLevel map[models.SeverityLevel]uint, configuredLevels []models.SeverityLevel) *gorm.DB { +func (r *gormAlarmRepository) buildGroupBClause(tx *gorm.DB, intervalByLevel map[models.SeverityLevel]uint32, configuredLevels []models.SeverityLevel) *gorm.DB { now := time.Now() // B.1. 构造 Level IN 子句 diff --git a/internal/infra/repository/area_controller_repository.go b/internal/infra/repository/area_controller_repository.go index 0a0e0bf..d9ed656 100644 --- a/internal/infra/repository/area_controller_repository.go +++ b/internal/infra/repository/area_controller_repository.go @@ -13,14 +13,14 @@ import ( // AreaControllerRepository 定义了对 AreaController 模型的数据库操作接口 type AreaControllerRepository interface { - FindByID(ctx context.Context, id uint) (*models.AreaController, error) + FindByID(ctx context.Context, id uint32) (*models.AreaController, error) FindByNetworkID(ctx context.Context, networkID string) (*models.AreaController, error) Create(ctx context.Context, ac *models.AreaController) error ListAll(ctx context.Context) ([]*models.AreaController, error) Update(ctx context.Context, ac *models.AreaController) error - Delete(ctx context.Context, id uint) error + Delete(ctx context.Context, id uint32) error // IsAreaControllerUsedByTasks 检查区域主控是否被特定任务类型使用,可以忽略指定任务类型 - IsAreaControllerUsedByTasks(ctx context.Context, areaControllerID uint, ignoredTaskTypes []models.TaskType) (bool, error) + IsAreaControllerUsedByTasks(ctx context.Context, areaControllerID uint32, ignoredTaskTypes []models.TaskType) (bool, error) } // gormAreaControllerRepository 是 AreaControllerRepository 的 GORM 实现。 @@ -60,7 +60,7 @@ func (r *gormAreaControllerRepository) Update(ctx context.Context, ac *models.Ar } // Delete 删除一个 AreaController 记录。 -func (r *gormAreaControllerRepository) Delete(ctx context.Context, id uint) error { +func (r *gormAreaControllerRepository) Delete(ctx context.Context, id uint32) error { repoCtx := logs.AddFuncName(ctx, r.ctx, "Delete") if err := r.db.WithContext(repoCtx).Delete(&models.AreaController{}, id).Error; err != nil { return fmt.Errorf("删除区域主控失败: %w", err) @@ -69,7 +69,7 @@ func (r *gormAreaControllerRepository) Delete(ctx context.Context, id uint) erro } // FindByID 通过 ID 查找一个 AreaController。 -func (r *gormAreaControllerRepository) FindByID(ctx context.Context, id uint) (*models.AreaController, error) { +func (r *gormAreaControllerRepository) FindByID(ctx context.Context, id uint32) (*models.AreaController, error) { repoCtx := logs.AddFuncName(ctx, r.ctx, "FindByID") var areaController models.AreaController if err := r.db.WithContext(repoCtx).First(&areaController, id).Error; err != nil { @@ -89,7 +89,7 @@ func (r *gormAreaControllerRepository) FindByNetworkID(ctx context.Context, netw } // IsAreaControllerUsedByTasks 检查区域主控是否被特定任务类型使用,可以忽略指定任务类型 -func (r *gormAreaControllerRepository) IsAreaControllerUsedByTasks(ctx context.Context, areaControllerID uint, ignoredTaskTypes []models.TaskType) (bool, error) { +func (r *gormAreaControllerRepository) IsAreaControllerUsedByTasks(ctx context.Context, areaControllerID uint32, ignoredTaskTypes []models.TaskType) (bool, error) { repoCtx, logger := logs.Trace(ctx, r.ctx, "IsAreaControllerUsedByTasks") // 将 ignoredTaskTypes 转换为 map,以便高效查找 diff --git a/internal/infra/repository/device_command_log_repository.go b/internal/infra/repository/device_command_log_repository.go index b4bc0bb..e974dfd 100644 --- a/internal/infra/repository/device_command_log_repository.go +++ b/internal/infra/repository/device_command_log_repository.go @@ -12,7 +12,7 @@ import ( // DeviceCommandLogListOptions 定义了查询设备命令日志时的可选参数 type DeviceCommandLogListOptions struct { - DeviceID *uint + DeviceID *uint32 ReceivedSuccess *bool StartTime *time.Time // 基于 sent_at 字段 EndTime *time.Time // 基于 sent_at 字段 diff --git a/internal/infra/repository/device_repository.go b/internal/infra/repository/device_repository.go index e19b974..72b01d6 100644 --- a/internal/infra/repository/device_repository.go +++ b/internal/infra/repository/device_repository.go @@ -18,7 +18,7 @@ type DeviceRepository interface { Create(ctx context.Context, device *models.Device) error // FindByID 根据主键 ID 查找设备 - FindByID(ctx context.Context, id uint) (*models.Device, error) + FindByID(ctx context.Context, id uint32) (*models.Device, error) // FindByIDString 根据字符串形式的主键 ID 查找设备 FindByIDString(ctx context.Context, id string) (*models.Device, error) @@ -30,28 +30,28 @@ type DeviceRepository interface { ListAllSensors(ctx context.Context) ([]*models.Device, error) // ListByAreaControllerID 根据区域主控 ID 列出所有子设备 - ListByAreaControllerID(ctx context.Context, areaControllerID uint) ([]*models.Device, error) + ListByAreaControllerID(ctx context.Context, areaControllerID uint32) ([]*models.Device, error) // FindByDeviceTemplateID 根据设备模板ID查找所有使用该模板的设备 - FindByDeviceTemplateID(ctx context.Context, deviceTemplateID uint) ([]*models.Device, error) + FindByDeviceTemplateID(ctx context.Context, deviceTemplateID uint32) ([]*models.Device, error) // Update 更新一个已有的设备信息 Update(ctx context.Context, device *models.Device) error // Delete 根据主键 ID 删除一个设备 - Delete(ctx context.Context, id uint) error + Delete(ctx context.Context, id uint32) error // FindByAreaControllerAndPhysicalAddress 根据区域主控ID和物理地址(总线号、总线地址)查找设备 - FindByAreaControllerAndPhysicalAddress(ctx context.Context, areaControllerID uint, busNumber int, busAddress int) (*models.Device, error) + FindByAreaControllerAndPhysicalAddress(ctx context.Context, areaControllerID uint32, busNumber int, busAddress int) (*models.Device, error) // GetDevicesByIDsTx 在指定事务中根据ID列表获取设备 - GetDevicesByIDsTx(ctx context.Context, tx *gorm.DB, ids []uint) ([]models.Device, error) + GetDevicesByIDsTx(ctx context.Context, tx *gorm.DB, ids []uint32) ([]models.Device, error) // IsDeviceInUse 检查设备是否被任何任务使用,可以忽略指定任务类型 - IsDeviceInUse(ctx context.Context, deviceID uint, ignoredTaskTypes []models.TaskType) (bool, error) + IsDeviceInUse(ctx context.Context, deviceID uint32, ignoredTaskTypes []models.TaskType) (bool, error) // IsAreaControllerInUse 检查区域主控是否被任何设备使用 - IsAreaControllerInUse(ctx context.Context, areaControllerID uint) (bool, error) + IsAreaControllerInUse(ctx context.Context, areaControllerID uint32) (bool, error) } // gormDeviceRepository 是 DeviceRepository 的 GORM 实现 @@ -73,7 +73,7 @@ func (r *gormDeviceRepository) Create(ctx context.Context, device *models.Device } // FindByID 根据 ID 查找设备 -func (r *gormDeviceRepository) FindByID(ctx context.Context, id uint) (*models.Device, error) { +func (r *gormDeviceRepository) FindByID(ctx context.Context, id uint32) (*models.Device, error) { repoCtx := logs.AddFuncName(ctx, r.ctx, "FindByID") var device models.Device if err := r.db.WithContext(repoCtx).Preload("AreaController").Preload("DeviceTemplate").First(&device, id).Error; err != nil { @@ -83,7 +83,7 @@ func (r *gormDeviceRepository) FindByID(ctx context.Context, id uint) (*models.D } // GetDevicesByIDsTx 在指定事务中根据ID列表获取设备 -func (r *gormDeviceRepository) GetDevicesByIDsTx(ctx context.Context, tx *gorm.DB, ids []uint) ([]models.Device, error) { +func (r *gormDeviceRepository) GetDevicesByIDsTx(ctx context.Context, tx *gorm.DB, ids []uint32) ([]models.Device, error) { repoCtx := logs.AddFuncName(ctx, r.ctx, "GetDevicesByIDsTx") var devices []models.Device if len(ids) == 0 { @@ -98,14 +98,13 @@ func (r *gormDeviceRepository) GetDevicesByIDsTx(ctx context.Context, tx *gorm.D // FindByIDString 根据字符串形式的主键 ID 查找设备 func (r *gormDeviceRepository) FindByIDString(ctx context.Context, id string) (*models.Device, error) { repoCtx := logs.AddFuncName(ctx, r.ctx, "FindByIDString") - // 将字符串ID转换为uint64 idInt, err := strconv.ParseUint(id, 10, 64) if err != nil { // 如果转换失败,说明ID格式不正确,返回一个明确的错误 return nil, fmt.Errorf("无效的设备ID格式: %w", err) } // 调用已有的 FindByID 方法 - return r.FindByID(repoCtx, uint(idInt)) + return r.FindByID(repoCtx, uint32(idInt)) } // ListAll 获取所有设备的列表 @@ -133,7 +132,7 @@ func (r *gormDeviceRepository) ListAllSensors(ctx context.Context) ([]*models.De } // ListByAreaControllerID 根据区域主控 ID 列出所有子设备 -func (r *gormDeviceRepository) ListByAreaControllerID(ctx context.Context, areaControllerID uint) ([]*models.Device, error) { +func (r *gormDeviceRepository) ListByAreaControllerID(ctx context.Context, areaControllerID uint32) ([]*models.Device, error) { repoCtx := logs.AddFuncName(ctx, r.ctx, "ListByAreaControllerID") var devices []*models.Device err := r.db.WithContext(repoCtx).Preload("AreaController").Preload("DeviceTemplate").Where("area_controller_id = ?", areaControllerID).Find(&devices).Error @@ -144,7 +143,7 @@ func (r *gormDeviceRepository) ListByAreaControllerID(ctx context.Context, areaC } // FindByDeviceTemplateID 根据设备模板ID查找所有使用该模板的设备 -func (r *gormDeviceRepository) FindByDeviceTemplateID(ctx context.Context, deviceTemplateID uint) ([]*models.Device, error) { +func (r *gormDeviceRepository) FindByDeviceTemplateID(ctx context.Context, deviceTemplateID uint32) ([]*models.Device, error) { repoCtx := logs.AddFuncName(ctx, r.ctx, "FindByDeviceTemplateID") var devices []*models.Device err := r.db.WithContext(repoCtx).Where("device_template_id = ?", deviceTemplateID).Find(&devices).Error @@ -163,13 +162,13 @@ func (r *gormDeviceRepository) Update(ctx context.Context, device *models.Device // Delete 根据 ID 删除一个设备 // GORM 使用软删除,记录不会从数据库中物理移除,而是设置 DeletedAt 字段。 -func (r *gormDeviceRepository) Delete(ctx context.Context, id uint) error { +func (r *gormDeviceRepository) Delete(ctx context.Context, id uint32) error { repoCtx := logs.AddFuncName(ctx, r.ctx, "Delete") return r.db.WithContext(repoCtx).Delete(&models.Device{}, id).Error } // FindByAreaControllerAndPhysicalAddress 根据区域主控ID和物理地址(总线号、总线地址)查找设备 -func (r *gormDeviceRepository) FindByAreaControllerAndPhysicalAddress(ctx context.Context, areaControllerID uint, busNumber int, busAddress int) (*models.Device, error) { +func (r *gormDeviceRepository) FindByAreaControllerAndPhysicalAddress(ctx context.Context, areaControllerID uint32, busNumber int, busAddress int) (*models.Device, error) { repoCtx := logs.AddFuncName(ctx, r.ctx, "FindByAreaControllerAndPhysicalAddress") var device models.Device err := r.db.WithContext(repoCtx).Preload("AreaController").Preload("DeviceTemplate"). @@ -185,7 +184,7 @@ func (r *gormDeviceRepository) FindByAreaControllerAndPhysicalAddress(ctx contex } // IsDeviceInUse 检查设备是否被任何任务使用,可以忽略指定任务类型 -func (r *gormDeviceRepository) IsDeviceInUse(ctx context.Context, deviceID uint, ignoredTaskTypes []models.TaskType) (bool, error) { +func (r *gormDeviceRepository) IsDeviceInUse(ctx context.Context, deviceID uint32, ignoredTaskTypes []models.TaskType) (bool, error) { repoCtx := logs.AddFuncName(ctx, r.ctx, "IsDeviceInUse") var count int64 @@ -207,7 +206,7 @@ func (r *gormDeviceRepository) IsDeviceInUse(ctx context.Context, deviceID uint, } // IsAreaControllerInUse 检查区域主控是否被任何设备使用 -func (r *gormDeviceRepository) IsAreaControllerInUse(ctx context.Context, areaControllerID uint) (bool, error) { +func (r *gormDeviceRepository) IsAreaControllerInUse(ctx context.Context, areaControllerID uint32) (bool, error) { repoCtx := logs.AddFuncName(ctx, r.ctx, "IsAreaControllerInUse") var count int64 if err := r.db.WithContext(repoCtx).Model(&models.Device{}).Where("area_controller_id = ?", areaControllerID).Count(&count).Error; err != nil { diff --git a/internal/infra/repository/device_template_repository.go b/internal/infra/repository/device_template_repository.go index dd9c0b1..22d3fa3 100644 --- a/internal/infra/repository/device_template_repository.go +++ b/internal/infra/repository/device_template_repository.go @@ -14,12 +14,12 @@ import ( // DeviceTemplateRepository 定义了设备模板数据访问的接口 type DeviceTemplateRepository interface { Create(ctx context.Context, deviceTemplate *models.DeviceTemplate) error - FindByID(ctx context.Context, id uint) (*models.DeviceTemplate, error) + FindByID(ctx context.Context, id uint32) (*models.DeviceTemplate, error) FindByName(ctx context.Context, name string) (*models.DeviceTemplate, error) ListAll(ctx context.Context) ([]*models.DeviceTemplate, error) Update(ctx context.Context, deviceTemplate *models.DeviceTemplate) error - Delete(ctx context.Context, id uint) error - IsInUse(ctx context.Context, id uint) (bool, error) + Delete(ctx context.Context, id uint32) error + IsInUse(ctx context.Context, id uint32) (bool, error) } // gormDeviceTemplateRepository 是 DeviceTemplateRepository 的 GORM 实现 @@ -40,7 +40,7 @@ func (r *gormDeviceTemplateRepository) Create(ctx context.Context, deviceTemplat } // FindByID 根据ID查找设备模板 -func (r *gormDeviceTemplateRepository) FindByID(ctx context.Context, id uint) (*models.DeviceTemplate, error) { +func (r *gormDeviceTemplateRepository) FindByID(ctx context.Context, id uint32) (*models.DeviceTemplate, error) { repoCtx := logs.AddFuncName(ctx, r.ctx, "FindByID") var deviceTemplate models.DeviceTemplate if err := r.db.WithContext(repoCtx).First(&deviceTemplate, id).Error; err != nil { @@ -82,7 +82,7 @@ func (r *gormDeviceTemplateRepository) Update(ctx context.Context, deviceTemplat } // IsInUse 检查设备模板是否正在被设备使用 -func (r *gormDeviceTemplateRepository) IsInUse(ctx context.Context, id uint) (bool, error) { +func (r *gormDeviceTemplateRepository) IsInUse(ctx context.Context, id uint32) (bool, error) { repoCtx := logs.AddFuncName(ctx, r.ctx, "IsInUse") var count int64 if err := r.db.WithContext(repoCtx).Model(&models.Device{}).Where("device_template_id = ?", id).Count(&count).Error; err != nil { @@ -92,7 +92,7 @@ func (r *gormDeviceTemplateRepository) IsInUse(ctx context.Context, id uint) (bo } // Delete 软删除数据库中的设备模板 -func (r *gormDeviceTemplateRepository) Delete(ctx context.Context, id uint) error { +func (r *gormDeviceTemplateRepository) Delete(ctx context.Context, id uint32) error { repoCtx := logs.AddFuncName(ctx, r.ctx, "Delete") if err := r.db.WithContext(repoCtx).Delete(&models.DeviceTemplate{}, id).Error; err != nil { return fmt.Errorf("删除设备模板失败: %w", err) diff --git a/internal/infra/repository/execution_log_repository.go b/internal/infra/repository/execution_log_repository.go index bd4a1fb..9d58856 100644 --- a/internal/infra/repository/execution_log_repository.go +++ b/internal/infra/repository/execution_log_repository.go @@ -13,7 +13,7 @@ import ( // PlanExecutionLogListOptions 定义了查询计划执行日志时的可选参数 type PlanExecutionLogListOptions struct { - PlanID *uint + PlanID *uint32 Status *models.ExecutionStatus StartTime *time.Time // 基于 created_at 字段 EndTime *time.Time // 基于 created_at 字段 @@ -22,7 +22,7 @@ type PlanExecutionLogListOptions struct { // TaskExecutionLogListOptions 定义了查询任务执行日志时的可选参数 type TaskExecutionLogListOptions struct { - PlanExecutionLogID *uint + PlanExecutionLogID *uint32 TaskID *int Status *models.ExecutionStatus StartTime *time.Time // 基于 created_at 字段 @@ -33,26 +33,26 @@ type TaskExecutionLogListOptions struct { // ExecutionLogRepository 定义了与执行日志交互的接口。 type ExecutionLogRepository interface { // --- Existing methods --- - UpdateTaskExecutionLogStatusByIDs(ctx context.Context, logIDs []uint, status models.ExecutionStatus) error - UpdateTaskExecutionLogStatus(ctx context.Context, logID uint, status models.ExecutionStatus) error + UpdateTaskExecutionLogStatusByIDs(ctx context.Context, logIDs []uint32, status models.ExecutionStatus) error + UpdateTaskExecutionLogStatus(ctx context.Context, logID uint32, status models.ExecutionStatus) error CreateTaskExecutionLog(ctx context.Context, log *models.TaskExecutionLog) error CreatePlanExecutionLog(ctx context.Context, log *models.PlanExecutionLog) error UpdatePlanExecutionLog(ctx context.Context, log *models.PlanExecutionLog) error CreateTaskExecutionLogsInBatch(ctx context.Context, logs []*models.TaskExecutionLog) error UpdateTaskExecutionLog(ctx context.Context, log *models.TaskExecutionLog) error - FindTaskExecutionLogByID(ctx context.Context, id uint) (*models.TaskExecutionLog, error) + FindTaskExecutionLogByID(ctx context.Context, id uint32) (*models.TaskExecutionLog, error) // UpdatePlanExecutionLogStatus 更新计划执行日志的状态 - UpdatePlanExecutionLogStatus(ctx context.Context, logID uint, status models.ExecutionStatus) error + UpdatePlanExecutionLogStatus(ctx context.Context, logID uint32, status models.ExecutionStatus) error // UpdatePlanExecutionLogsStatusByIDs 批量更新计划执行日志的状态 - UpdatePlanExecutionLogsStatusByIDs(ctx context.Context, logIDs []uint, status models.ExecutionStatus) error + UpdatePlanExecutionLogsStatusByIDs(ctx context.Context, logIDs []uint32, status models.ExecutionStatus) error // FindIncompletePlanExecutionLogs 查找所有未完成的计划执行日志 FindIncompletePlanExecutionLogs(ctx context.Context) ([]models.PlanExecutionLog, error) // FindInProgressPlanExecutionLogByPlanID 根据 PlanID 查找正在进行的计划执行日志 - FindInProgressPlanExecutionLogByPlanID(ctx context.Context, planID uint) (*models.PlanExecutionLog, error) + FindInProgressPlanExecutionLogByPlanID(ctx context.Context, planID uint32) (*models.PlanExecutionLog, error) // FindIncompleteTaskExecutionLogsByPlanLogID 根据计划日志ID查找所有未完成的任务日志 - FindIncompleteTaskExecutionLogsByPlanLogID(ctx context.Context, planLogID uint) ([]models.TaskExecutionLog, error) + FindIncompleteTaskExecutionLogsByPlanLogID(ctx context.Context, planLogID uint32) ([]models.TaskExecutionLog, error) // FailAllIncompletePlanExecutionLogs 将所有状态为 ExecutionStatusStarted 和 ExecutionStatusWaiting 的计划状态都修改为 ExecutionStatusFailed FailAllIncompletePlanExecutionLogs(ctx context.Context) error @@ -60,16 +60,16 @@ type ExecutionLogRepository interface { CancelAllIncompleteTaskExecutionLogs(ctx context.Context) error // FindPlanExecutionLogByID 根据ID查找计划执行日志 - FindPlanExecutionLogByID(ctx context.Context, id uint) (*models.PlanExecutionLog, error) + FindPlanExecutionLogByID(ctx context.Context, id uint32) (*models.PlanExecutionLog, error) // CountIncompleteTasksByPlanLogID 计算一个计划执行中未完成的任务数量 - CountIncompleteTasksByPlanLogID(ctx context.Context, planLogID uint) (int64, error) + CountIncompleteTasksByPlanLogID(ctx context.Context, planLogID uint32) (int64, error) // FailPlanExecution 将指定的计划执行标记为失败 - FailPlanExecution(ctx context.Context, planLogID uint, errorMessage string) error + FailPlanExecution(ctx context.Context, planLogID uint32, errorMessage string) error // CancelIncompleteTasksByPlanLogID 取消一个计划执行中的所有未完成任务 - CancelIncompleteTasksByPlanLogID(ctx context.Context, planLogID uint, reason string) error + CancelIncompleteTasksByPlanLogID(ctx context.Context, planLogID uint32, reason string) error // --- New methods --- ListPlanExecutionLogs(ctx context.Context, opts PlanExecutionLogListOptions, page, pageSize int) ([]models.PlanExecutionLog, int64, error) @@ -175,7 +175,7 @@ func (r *gormExecutionLogRepository) ListTaskExecutionLogs(ctx context.Context, // --- Existing method implementations --- -func (r *gormExecutionLogRepository) UpdateTaskExecutionLogStatusByIDs(ctx context.Context, logIDs []uint, status models.ExecutionStatus) error { +func (r *gormExecutionLogRepository) UpdateTaskExecutionLogStatusByIDs(ctx context.Context, logIDs []uint32, status models.ExecutionStatus) error { repoCtx := logs.AddFuncName(ctx, r.ctx, "UpdateTaskExecutionLogStatusByIDs") if len(logIDs) == 0 { return nil @@ -183,7 +183,7 @@ func (r *gormExecutionLogRepository) UpdateTaskExecutionLogStatusByIDs(ctx conte return r.db.WithContext(repoCtx).Model(&models.TaskExecutionLog{}).Where("id IN ?", logIDs).Update("status", status).Error } -func (r *gormExecutionLogRepository) UpdateTaskExecutionLogStatus(ctx context.Context, logID uint, status models.ExecutionStatus) error { +func (r *gormExecutionLogRepository) UpdateTaskExecutionLogStatus(ctx context.Context, logID uint32, status models.ExecutionStatus) error { repoCtx := logs.AddFuncName(ctx, r.ctx, "UpdateTaskExecutionLogStatus") return r.db.WithContext(repoCtx).Model(&models.TaskExecutionLog{}).Where("id = ?", logID).Update("status", status).Error } @@ -228,7 +228,7 @@ func (r *gormExecutionLogRepository) UpdateTaskExecutionLog(ctx context.Context, // FindTaskExecutionLogByID 根据 ID 查找单个任务执行日志。 // 它会预加载关联的 Task 信息。 -func (r *gormExecutionLogRepository) FindTaskExecutionLogByID(ctx context.Context, id uint) (*models.TaskExecutionLog, error) { +func (r *gormExecutionLogRepository) FindTaskExecutionLogByID(ctx context.Context, id uint32) (*models.TaskExecutionLog, error) { repoCtx := logs.AddFuncName(ctx, r.ctx, "FindTaskExecutionLogByID") var log models.TaskExecutionLog // 使用 Preload("Task") 来确保关联的任务信息被一并加载 @@ -240,13 +240,13 @@ func (r *gormExecutionLogRepository) FindTaskExecutionLogByID(ctx context.Contex } // UpdatePlanExecutionLogStatus 更新计划执行日志的状态 -func (r *gormExecutionLogRepository) UpdatePlanExecutionLogStatus(ctx context.Context, logID uint, status models.ExecutionStatus) error { +func (r *gormExecutionLogRepository) UpdatePlanExecutionLogStatus(ctx context.Context, logID uint32, status models.ExecutionStatus) error { repoCtx := logs.AddFuncName(ctx, r.ctx, "UpdatePlanExecutionLogStatus") return r.db.WithContext(repoCtx).Model(&models.PlanExecutionLog{}).Where("id = ?", logID).Update("status", status).Error } // UpdatePlanExecutionLogsStatusByIDs 批量更新计划执行日志的状态 -func (r *gormExecutionLogRepository) UpdatePlanExecutionLogsStatusByIDs(ctx context.Context, logIDs []uint, status models.ExecutionStatus) error { +func (r *gormExecutionLogRepository) UpdatePlanExecutionLogsStatusByIDs(ctx context.Context, logIDs []uint32, status models.ExecutionStatus) error { repoCtx := logs.AddFuncName(ctx, r.ctx, "UpdatePlanExecutionLogsStatusByIDs") if len(logIDs) == 0 { return nil @@ -263,7 +263,7 @@ func (r *gormExecutionLogRepository) FindIncompletePlanExecutionLogs(ctx context } // FindInProgressPlanExecutionLogByPlanID 根据 PlanID 查找正在进行的计划执行日志 -func (r *gormExecutionLogRepository) FindInProgressPlanExecutionLogByPlanID(ctx context.Context, planID uint) (*models.PlanExecutionLog, error) { +func (r *gormExecutionLogRepository) FindInProgressPlanExecutionLogByPlanID(ctx context.Context, planID uint32) (*models.PlanExecutionLog, error) { repoCtx := logs.AddFuncName(ctx, r.ctx, "FindInProgressPlanExecutionLogByPlanID") var log models.PlanExecutionLog err := r.db.WithContext(repoCtx).Where("plan_id = ? AND status = ?", planID, models.ExecutionStatusStarted).First(&log).Error @@ -279,7 +279,7 @@ func (r *gormExecutionLogRepository) FindInProgressPlanExecutionLogByPlanID(ctx } // FindIncompleteTaskExecutionLogsByPlanLogID 根据计划日志ID查找所有未完成的任务日志 -func (r *gormExecutionLogRepository) FindIncompleteTaskExecutionLogsByPlanLogID(ctx context.Context, planLogID uint) ([]models.TaskExecutionLog, error) { +func (r *gormExecutionLogRepository) FindIncompleteTaskExecutionLogsByPlanLogID(ctx context.Context, planLogID uint32) ([]models.TaskExecutionLog, error) { repoCtx := logs.AddFuncName(ctx, r.ctx, "FindIncompleteTaskExecutionLogsByPlanLogID") var logs []models.TaskExecutionLog err := r.db.WithContext(repoCtx).Where("plan_execution_log_id = ? AND (status = ? OR status = ?)", @@ -304,7 +304,7 @@ func (r *gormExecutionLogRepository) CancelAllIncompleteTaskExecutionLogs(ctx co } // FindPlanExecutionLogByID 根据ID查找计划执行日志 -func (r *gormExecutionLogRepository) FindPlanExecutionLogByID(ctx context.Context, id uint) (*models.PlanExecutionLog, error) { +func (r *gormExecutionLogRepository) FindPlanExecutionLogByID(ctx context.Context, id uint32) (*models.PlanExecutionLog, error) { repoCtx := logs.AddFuncName(ctx, r.ctx, "FindPlanExecutionLogByID") var log models.PlanExecutionLog err := r.db.WithContext(repoCtx).First(&log, id).Error @@ -315,7 +315,7 @@ func (r *gormExecutionLogRepository) FindPlanExecutionLogByID(ctx context.Contex } // CountIncompleteTasksByPlanLogID 计算一个计划执行中未完成的任务数量 -func (r *gormExecutionLogRepository) CountIncompleteTasksByPlanLogID(ctx context.Context, planLogID uint) (int64, error) { +func (r *gormExecutionLogRepository) CountIncompleteTasksByPlanLogID(ctx context.Context, planLogID uint32) (int64, error) { repoCtx := logs.AddFuncName(ctx, r.ctx, "CountIncompleteTasksByPlanLogID") var count int64 err := r.db.WithContext(repoCtx).Model(&models.TaskExecutionLog{}). @@ -326,7 +326,7 @@ func (r *gormExecutionLogRepository) CountIncompleteTasksByPlanLogID(ctx context } // FailPlanExecution 将指定的计划执行标记为失败 -func (r *gormExecutionLogRepository) FailPlanExecution(ctx context.Context, planLogID uint, errorMessage string) error { +func (r *gormExecutionLogRepository) FailPlanExecution(ctx context.Context, planLogID uint32, errorMessage string) error { repoCtx := logs.AddFuncName(ctx, r.ctx, "FailPlanExecution") return r.db.WithContext(repoCtx).Model(&models.PlanExecutionLog{}). Where("id = ?", planLogID). @@ -338,7 +338,7 @@ func (r *gormExecutionLogRepository) FailPlanExecution(ctx context.Context, plan } // CancelIncompleteTasksByPlanLogID 取消一个计划执行中的所有未完成任务 -func (r *gormExecutionLogRepository) CancelIncompleteTasksByPlanLogID(ctx context.Context, planLogID uint, reason string) error { +func (r *gormExecutionLogRepository) CancelIncompleteTasksByPlanLogID(ctx context.Context, planLogID uint32, reason string) error { repoCtx := logs.AddFuncName(ctx, r.ctx, "CancelIncompleteTasksByPlanLogID") return r.db.WithContext(repoCtx).Model(&models.TaskExecutionLog{}). Where("plan_execution_log_id = ? AND status IN (?, ?)", diff --git a/internal/infra/repository/medication_log_repository.go b/internal/infra/repository/medication_log_repository.go index 6db863d..ac99400 100644 --- a/internal/infra/repository/medication_log_repository.go +++ b/internal/infra/repository/medication_log_repository.go @@ -12,10 +12,10 @@ import ( // MedicationLogListOptions 定义了查询用药记录时的可选参数 type MedicationLogListOptions struct { - PigBatchID *uint - MedicationID *uint + PigBatchID *uint32 + MedicationID *uint32 Reason *models.MedicationReasonType - OperatorID *uint + OperatorID *uint32 StartTime *time.Time EndTime *time.Time OrderBy string // 例如 "happened_at desc" diff --git a/internal/infra/repository/notification_repository.go b/internal/infra/repository/notification_repository.go index 10798fc..3f27a57 100644 --- a/internal/infra/repository/notification_repository.go +++ b/internal/infra/repository/notification_repository.go @@ -13,7 +13,7 @@ import ( // NotificationListOptions 定义了查询通知列表时的可选参数 type NotificationListOptions struct { - UserID *uint // 按用户ID过滤 + UserID *uint32 // 按用户ID过滤 NotifierType *models.NotifierType // 按通知器类型过滤 Status *models.NotificationStatus // 按通知状态过滤 (例如:"success", "failed") Level *zapcore.Level // 按通知等级过滤 (例如:"info", "warning", "error") diff --git a/internal/infra/repository/pending_collection_repository.go b/internal/infra/repository/pending_collection_repository.go index 77ab3ad..55360e8 100644 --- a/internal/infra/repository/pending_collection_repository.go +++ b/internal/infra/repository/pending_collection_repository.go @@ -12,7 +12,7 @@ import ( // PendingCollectionListOptions 定义了查询待采集请求时的可选参数 type PendingCollectionListOptions struct { - DeviceID *uint + DeviceID *uint32 Status *models.PendingCollectionStatus StartTime *time.Time // 基于 created_at 字段 EndTime *time.Time // 基于 created_at 字段 diff --git a/internal/infra/repository/pending_task_repository.go b/internal/infra/repository/pending_task_repository.go index 06824df..25f7d7e 100644 --- a/internal/infra/repository/pending_task_repository.go +++ b/internal/infra/repository/pending_task_repository.go @@ -16,27 +16,27 @@ import ( // PendingTaskRepository 定义了与待执行任务队列交互的接口。 type PendingTaskRepository interface { FindAllPendingTasks(ctx context.Context) ([]models.PendingTask, error) - FindPendingTriggerByPlanID(ctx context.Context, planID uint) (*models.PendingTask, error) - DeletePendingTasksByIDs(ctx context.Context, ids []uint) error + FindPendingTriggerByPlanID(ctx context.Context, planID uint32) (*models.PendingTask, error) + DeletePendingTasksByIDs(ctx context.Context, ids []uint32) error CreatePendingTask(ctx context.Context, task *models.PendingTask) error CreatePendingTasksInBatch(ctx context.Context, tasks []*models.PendingTask) error // UpdatePendingTaskExecuteAt 更新指定待执行任务的执行时间 - UpdatePendingTaskExecuteAt(ctx context.Context, id uint, executeAt time.Time) error + UpdatePendingTaskExecuteAt(ctx context.Context, id uint32, executeAt time.Time) error // ClearAllPendingTasks 清空所有待执行任务 ClearAllPendingTasks(ctx context.Context) error // ClaimNextAvailableTask 原子地认领下一个可用的任务。 // 它会同时返回被认领任务对应的日志对象,以及被删除的待办任务对象的内存副本。 - ClaimNextAvailableTask(ctx context.Context, excludePlanIDs []uint) (*models.TaskExecutionLog, *models.PendingTask, error) + ClaimNextAvailableTask(ctx context.Context, excludePlanIDs []uint32) (*models.TaskExecutionLog, *models.PendingTask, error) // RequeueTask 安全地将一个任务重新放回队列。 RequeueTask(ctx context.Context, originalPendingTask *models.PendingTask) error // FindPendingTasksByTaskLogIDs 根据 TaskExecutionLogID 列表查找对应的待执行任务 - FindPendingTasksByTaskLogIDs(ctx context.Context, taskLogIDs []uint) ([]models.PendingTask, error) + FindPendingTasksByTaskLogIDs(ctx context.Context, taskLogIDs []uint32) ([]models.PendingTask, error) // DeletePendingTasksByPlanLogID 删除与指定计划执行日志ID相关的所有待执行任务 - DeletePendingTasksByPlanLogID(ctx context.Context, planLogID uint) error + DeletePendingTasksByPlanLogID(ctx context.Context, planLogID uint32) error } // gormPendingTaskRepository 是使用 GORM 的具体实现。 @@ -59,7 +59,7 @@ func (r *gormPendingTaskRepository) FindAllPendingTasks(ctx context.Context) ([] return tasks, err } -func (r *gormPendingTaskRepository) FindPendingTriggerByPlanID(ctx context.Context, planID uint) (*models.PendingTask, error) { +func (r *gormPendingTaskRepository) FindPendingTriggerByPlanID(ctx context.Context, planID uint32) (*models.PendingTask, error) { repoCtx := logs.AddFuncName(ctx, r.ctx, "FindPendingTriggerByPlanID") var pendingTask models.PendingTask // 关键修改:通过 JOIN tasks 表并查询 parameters JSON 字段来查找触发器,而不是依赖 task.plan_id @@ -73,7 +73,7 @@ func (r *gormPendingTaskRepository) FindPendingTriggerByPlanID(ctx context.Conte return &pendingTask, err } -func (r *gormPendingTaskRepository) DeletePendingTasksByIDs(ctx context.Context, ids []uint) error { +func (r *gormPendingTaskRepository) DeletePendingTasksByIDs(ctx context.Context, ids []uint32) error { repoCtx := logs.AddFuncName(ctx, r.ctx, "DeletePendingTasksByIDs") if len(ids) == 0 { return nil @@ -96,7 +96,7 @@ func (r *gormPendingTaskRepository) CreatePendingTasksInBatch(ctx context.Contex } // UpdatePendingTaskExecuteAt 更新指定待执行任务的执行时间 -func (r *gormPendingTaskRepository) UpdatePendingTaskExecuteAt(ctx context.Context, id uint, executeAt time.Time) error { +func (r *gormPendingTaskRepository) UpdatePendingTaskExecuteAt(ctx context.Context, id uint32, executeAt time.Time) error { repoCtx := logs.AddFuncName(ctx, r.ctx, "UpdatePendingTaskExecuteAt") return r.db.WithContext(repoCtx).Model(&models.PendingTask{}).Where("id = ?", id).Update("execute_at", executeAt).Error } @@ -108,7 +108,7 @@ func (r *gormPendingTaskRepository) ClearAllPendingTasks(ctx context.Context) er } // ClaimNextAvailableTask 以原子方式认领下一个可用的任务。 -func (r *gormPendingTaskRepository) ClaimNextAvailableTask(ctx context.Context, excludePlanIDs []uint) (*models.TaskExecutionLog, *models.PendingTask, error) { +func (r *gormPendingTaskRepository) ClaimNextAvailableTask(ctx context.Context, excludePlanIDs []uint32) (*models.TaskExecutionLog, *models.PendingTask, error) { repoCtx := logs.AddFuncName(ctx, r.ctx, "ClaimNextAvailableTask") var log models.TaskExecutionLog var pendingTask models.PendingTask @@ -175,7 +175,7 @@ func (r *gormPendingTaskRepository) RequeueTask(ctx context.Context, originalPen } // FindPendingTasksByTaskLogIDs 根据 TaskExecutionLogID 列表查找对应的待执行任务 -func (r *gormPendingTaskRepository) FindPendingTasksByTaskLogIDs(ctx context.Context, taskLogIDs []uint) ([]models.PendingTask, error) { +func (r *gormPendingTaskRepository) FindPendingTasksByTaskLogIDs(ctx context.Context, taskLogIDs []uint32) ([]models.PendingTask, error) { repoCtx := logs.AddFuncName(ctx, r.ctx, "FindPendingTasksByTaskLogIDs") if len(taskLogIDs) == 0 { return []models.PendingTask{}, nil @@ -186,7 +186,7 @@ func (r *gormPendingTaskRepository) FindPendingTasksByTaskLogIDs(ctx context.Con } // DeletePendingTasksByPlanLogID 删除与指定计划执行日志ID相关的所有待执行任务 -func (r *gormPendingTaskRepository) DeletePendingTasksByPlanLogID(ctx context.Context, planLogID uint) error { +func (r *gormPendingTaskRepository) DeletePendingTasksByPlanLogID(ctx context.Context, planLogID uint32) error { repoCtx := logs.AddFuncName(ctx, r.ctx, "DeletePendingTasksByPlanLogID") // 使用子查询找到所有与 planLogID 相关的 task_execution_log_id subQuery := r.db.WithContext(repoCtx).Model(&models.TaskExecutionLog{}).Select("id").Where("plan_execution_log_id = ?", planLogID) diff --git a/internal/infra/repository/pig_batch_log_repository.go b/internal/infra/repository/pig_batch_log_repository.go index c07b70c..54eaf4a 100644 --- a/internal/infra/repository/pig_batch_log_repository.go +++ b/internal/infra/repository/pig_batch_log_repository.go @@ -12,9 +12,9 @@ import ( // PigBatchLogListOptions 定义了查询猪批次日志时的可选参数 type PigBatchLogListOptions struct { - PigBatchID *uint + PigBatchID *uint32 ChangeType *models.LogChangeType - OperatorID *uint + OperatorID *uint32 StartTime *time.Time // 基于 happened_at 字段 EndTime *time.Time // 基于 happened_at 字段 OrderBy string // 例如 "happened_at asc" @@ -26,10 +26,10 @@ type PigBatchLogRepository interface { CreateTx(ctx context.Context, tx *gorm.DB, log *models.PigBatchLog) error // GetLogsByBatchIDAndDateRangeTx 在指定的事务中,获取指定批次在特定时间范围内的所有日志记录。 - GetLogsByBatchIDAndDateRangeTx(ctx context.Context, tx *gorm.DB, batchID uint, startDate, endDate time.Time) ([]*models.PigBatchLog, error) + GetLogsByBatchIDAndDateRangeTx(ctx context.Context, tx *gorm.DB, batchID uint32, startDate, endDate time.Time) ([]*models.PigBatchLog, error) // GetLastLogByBatchIDTx 在指定的事务中,获取某批次的最后一条日志记录。 - GetLastLogByBatchIDTx(ctx context.Context, tx *gorm.DB, batchID uint) (*models.PigBatchLog, error) + GetLastLogByBatchIDTx(ctx context.Context, tx *gorm.DB, batchID uint32) (*models.PigBatchLog, error) // List 支持分页和过滤的列表查询 List(ctx context.Context, opts PigBatchLogListOptions, page, pageSize int) ([]models.PigBatchLog, int64, error) @@ -53,7 +53,7 @@ func (r *gormPigBatchLogRepository) CreateTx(ctx context.Context, tx *gorm.DB, l } // GetLogsByBatchIDAndDateRangeTx 实现了在指定的事务中,获取指定批次在特定时间范围内的所有日志记录的逻辑。 -func (r *gormPigBatchLogRepository) GetLogsByBatchIDAndDateRangeTx(ctx context.Context, tx *gorm.DB, batchID uint, startDate, endDate time.Time) ([]*models.PigBatchLog, error) { +func (r *gormPigBatchLogRepository) GetLogsByBatchIDAndDateRangeTx(ctx context.Context, tx *gorm.DB, batchID uint32, startDate, endDate time.Time) ([]*models.PigBatchLog, error) { repoCtx := logs.AddFuncName(ctx, r.ctx, "GetLogsByBatchIDAndDateRangeTx") var logs []*models.PigBatchLog err := tx.WithContext(repoCtx).Where("pig_batch_id = ? AND created_at >= ? AND created_at <= ?", batchID, startDate, endDate).Find(&logs).Error @@ -64,7 +64,7 @@ func (r *gormPigBatchLogRepository) GetLogsByBatchIDAndDateRangeTx(ctx context.C } // GetLastLogByBatchIDTx 实现了在指定的事务中,获取某批次的最后一条日志记录的逻辑。 -func (r *gormPigBatchLogRepository) GetLastLogByBatchIDTx(ctx context.Context, tx *gorm.DB, batchID uint) (*models.PigBatchLog, error) { +func (r *gormPigBatchLogRepository) GetLastLogByBatchIDTx(ctx context.Context, tx *gorm.DB, batchID uint32) (*models.PigBatchLog, error) { repoCtx := logs.AddFuncName(ctx, r.ctx, "GetLastLogByBatchIDTx") var log models.PigBatchLog err := tx.WithContext(repoCtx).Where("pig_batch_id = ?", batchID).Order("id DESC").First(&log).Error diff --git a/internal/infra/repository/pig_batch_repository.go b/internal/infra/repository/pig_batch_repository.go index ae37ecd..40c94e0 100644 --- a/internal/infra/repository/pig_batch_repository.go +++ b/internal/infra/repository/pig_batch_repository.go @@ -14,13 +14,13 @@ import ( type PigBatchRepository interface { CreatePigBatch(ctx context.Context, batch *models.PigBatch) (*models.PigBatch, error) CreatePigBatchTx(ctx context.Context, tx *gorm.DB, batch *models.PigBatch) (*models.PigBatch, error) - GetPigBatchByID(ctx context.Context, id uint) (*models.PigBatch, error) - GetPigBatchByIDTx(ctx context.Context, tx *gorm.DB, id uint) (*models.PigBatch, error) + GetPigBatchByID(ctx context.Context, id uint32) (*models.PigBatch, error) + GetPigBatchByIDTx(ctx context.Context, tx *gorm.DB, id uint32) (*models.PigBatch, error) // UpdatePigBatch 更新一个猪批次,返回更新后的批次、受影响的行数和错误 UpdatePigBatch(ctx context.Context, batch *models.PigBatch) (*models.PigBatch, int64, error) // DeletePigBatch 根据ID删除一个猪批次,返回受影响的行数和错误 - DeletePigBatch(ctx context.Context, id uint) (int64, error) - DeletePigBatchTx(ctx context.Context, tx *gorm.DB, id uint) (int64, error) + DeletePigBatch(ctx context.Context, id uint32) (int64, error) + DeletePigBatchTx(ctx context.Context, tx *gorm.DB, id uint32) (int64, error) ListPigBatches(ctx context.Context, isActive *bool) ([]*models.PigBatch, error) // ListWeighingBatches 支持分页和过滤的批次称重列表查询 @@ -32,7 +32,7 @@ type PigBatchRepository interface { // WeighingBatchListOptions 定义了查询批次称重记录时的可选参数 type WeighingBatchListOptions struct { - PigBatchID *uint + PigBatchID *uint32 StartTime *time.Time // 基于 weighing_time 字段 EndTime *time.Time // 基于 weighing_time 字段 OrderBy string // 例如 "weighing_time asc" @@ -40,9 +40,9 @@ type WeighingBatchListOptions struct { // WeighingRecordListOptions 定义了查询单次称重记录时的可选参数 type WeighingRecordListOptions struct { - WeighingBatchID *uint - PenID *uint - OperatorID *uint + WeighingBatchID *uint32 + PenID *uint32 + OperatorID *uint32 StartTime *time.Time // 基于 weighing_time 字段 EndTime *time.Time // 基于 weighing_time 字段 OrderBy string // 例如 "weighing_time asc" @@ -75,7 +75,7 @@ func (r *gormPigBatchRepository) CreatePigBatchTx(ctx context.Context, tx *gorm. } // GetPigBatchByID 根据ID获取单个猪批次 -func (r *gormPigBatchRepository) GetPigBatchByID(ctx context.Context, id uint) (*models.PigBatch, error) { +func (r *gormPigBatchRepository) GetPigBatchByID(ctx context.Context, id uint32) (*models.PigBatch, error) { repoCtx := logs.AddFuncName(ctx, r.ctx, "GetPigBatchByID") return r.GetPigBatchByIDTx(repoCtx, r.db, id) } @@ -92,12 +92,12 @@ func (r *gormPigBatchRepository) UpdatePigBatch(ctx context.Context, batch *mode } // DeletePigBatch 根据ID删除一个猪批次 (GORM 会执行软删除) -func (r *gormPigBatchRepository) DeletePigBatch(ctx context.Context, id uint) (int64, error) { +func (r *gormPigBatchRepository) DeletePigBatch(ctx context.Context, id uint32) (int64, error) { repoCtx := logs.AddFuncName(ctx, r.ctx, "DeletePigBatch") return r.DeletePigBatchTx(repoCtx, r.db, id) } -func (r *gormPigBatchRepository) DeletePigBatchTx(ctx context.Context, tx *gorm.DB, id uint) (int64, error) { +func (r *gormPigBatchRepository) DeletePigBatchTx(ctx context.Context, tx *gorm.DB, id uint32) (int64, error) { repoCtx := logs.AddFuncName(ctx, r.ctx, "DeletePigBatchTx") result := tx.WithContext(repoCtx).Delete(&models.PigBatch{}, id) if result.Error != nil { @@ -130,7 +130,7 @@ func (r *gormPigBatchRepository) ListPigBatches(ctx context.Context, isActive *b } // GetPigBatchByIDTx 在指定的事务中,通过ID获取单个猪批次 -func (r *gormPigBatchRepository) GetPigBatchByIDTx(ctx context.Context, tx *gorm.DB, id uint) (*models.PigBatch, error) { +func (r *gormPigBatchRepository) GetPigBatchByIDTx(ctx context.Context, tx *gorm.DB, id uint32) (*models.PigBatch, error) { repoCtx := logs.AddFuncName(ctx, r.ctx, "GetPigBatchByIDTx") var batch models.PigBatch if err := tx.WithContext(repoCtx).First(&batch, id).Error; err != nil { diff --git a/internal/infra/repository/pig_farm_repository.go b/internal/infra/repository/pig_farm_repository.go index f70c75b..10068c5 100644 --- a/internal/infra/repository/pig_farm_repository.go +++ b/internal/infra/repository/pig_farm_repository.go @@ -13,13 +13,13 @@ import ( type PigFarmRepository interface { // PigHouse methods CreatePigHouse(ctx context.Context, house *models.PigHouse) error - GetPigHouseByID(ctx context.Context, id uint) (*models.PigHouse, error) + GetPigHouseByID(ctx context.Context, id uint32) (*models.PigHouse, error) ListPigHouses(ctx context.Context) ([]models.PigHouse, error) // UpdatePigHouse 更新一个猪舍,返回受影响的行数和错误 UpdatePigHouse(ctx context.Context, house *models.PigHouse) (int64, error) // DeletePigHouse 根据ID删除一个猪舍,返回受影响的行数和错误 - DeletePigHouse(ctx context.Context, id uint) (int64, error) - CountPensInHouse(ctx context.Context, houseID uint) (int64, error) + DeletePigHouse(ctx context.Context, id uint32) (int64, error) + CountPensInHouse(ctx context.Context, houseID uint32) (int64, error) } // gormPigFarmRepository 是 PigFarmRepository 的 GORM 实现 @@ -42,7 +42,7 @@ func (r *gormPigFarmRepository) CreatePigHouse(ctx context.Context, house *model } // GetPigHouseByID 根据ID获取单个猪舍 -func (r *gormPigFarmRepository) GetPigHouseByID(ctx context.Context, id uint) (*models.PigHouse, error) { +func (r *gormPigFarmRepository) GetPigHouseByID(ctx context.Context, id uint32) (*models.PigHouse, error) { repoCtx := logs.AddFuncName(ctx, r.ctx, "GetPigHouseByID") var house models.PigHouse if err := r.db.WithContext(repoCtx).First(&house, id).Error; err != nil { @@ -72,7 +72,7 @@ func (r *gormPigFarmRepository) UpdatePigHouse(ctx context.Context, house *model } // DeletePigHouse 根据ID删除一个猪舍,返回受影响的行数和错误 -func (r *gormPigFarmRepository) DeletePigHouse(ctx context.Context, id uint) (int64, error) { +func (r *gormPigFarmRepository) DeletePigHouse(ctx context.Context, id uint32) (int64, error) { repoCtx := logs.AddFuncName(ctx, r.ctx, "DeletePigHouse") result := r.db.WithContext(repoCtx).Delete(&models.PigHouse{}, id) if result.Error != nil { @@ -82,7 +82,7 @@ func (r *gormPigFarmRepository) DeletePigHouse(ctx context.Context, id uint) (in } // CountPensInHouse 统计猪舍中的猪栏数量 -func (r *gormPigFarmRepository) CountPensInHouse(ctx context.Context, houseID uint) (int64, error) { +func (r *gormPigFarmRepository) CountPensInHouse(ctx context.Context, houseID uint32) (int64, error) { repoCtx := logs.AddFuncName(ctx, r.ctx, "CountPensInHouse") var count int64 err := r.db.WithContext(repoCtx).Model(&models.Pen{}).Where("house_id = ?", houseID).Count(&count).Error diff --git a/internal/infra/repository/pig_pen_repository.go b/internal/infra/repository/pig_pen_repository.go index ac83df9..4ec91e5 100644 --- a/internal/infra/repository/pig_pen_repository.go +++ b/internal/infra/repository/pig_pen_repository.go @@ -13,18 +13,18 @@ import ( type PigPenRepository interface { CreatePen(ctx context.Context, pen *models.Pen) error // GetPenByID 根据ID获取单个猪栏 (非事务性) - GetPenByID(ctx context.Context, id uint) (*models.Pen, error) + GetPenByID(ctx context.Context, id uint32) (*models.Pen, error) // GetPenByIDTx 根据ID获取单个猪栏 (事务性) - GetPenByIDTx(ctx context.Context, tx *gorm.DB, id uint) (*models.Pen, error) + GetPenByIDTx(ctx context.Context, tx *gorm.DB, id uint32) (*models.Pen, error) ListPens(ctx context.Context) ([]models.Pen, error) // UpdatePen 更新一个猪栏,返回受影响的行数和错误 UpdatePen(ctx context.Context, pen *models.Pen) (int64, error) // DeletePen 根据ID删除一个猪栏,返回受影响的行数和错误 - DeletePen(ctx context.Context, id uint) (int64, error) + DeletePen(ctx context.Context, id uint32) (int64, error) // GetPensByBatchIDTx 根据批次ID获取所有关联的猪栏 (事务性) - GetPensByBatchIDTx(ctx context.Context, tx *gorm.DB, batchID uint) ([]*models.Pen, error) + GetPensByBatchIDTx(ctx context.Context, tx *gorm.DB, batchID uint32) ([]*models.Pen, error) // UpdatePenFieldsTx 更新猪栏的指定字段 (事务性) - UpdatePenFieldsTx(ctx context.Context, tx *gorm.DB, penID uint, updates map[string]interface{}) error + UpdatePenFieldsTx(ctx context.Context, tx *gorm.DB, penID uint32, updates map[string]interface{}) error } // gormPigPenRepository 是 PigPenRepository 接口的 GORM 实现。 @@ -45,13 +45,13 @@ func (r *gormPigPenRepository) CreatePen(ctx context.Context, pen *models.Pen) e } // GetPenByID 根据ID获取单个猪栏 (非事务性) -func (r *gormPigPenRepository) GetPenByID(ctx context.Context, id uint) (*models.Pen, error) { +func (r *gormPigPenRepository) GetPenByID(ctx context.Context, id uint32) (*models.Pen, error) { repoCtx := logs.AddFuncName(ctx, r.ctx, "GetPenByID") return r.GetPenByIDTx(repoCtx, r.db, id) // 非Tx方法直接调用Tx方法 } // GetPenByIDTx 在指定的事务中,通过ID获取单个猪栏信息。 -func (r *gormPigPenRepository) GetPenByIDTx(ctx context.Context, tx *gorm.DB, id uint) (*models.Pen, error) { +func (r *gormPigPenRepository) GetPenByIDTx(ctx context.Context, tx *gorm.DB, id uint32) (*models.Pen, error) { repoCtx := logs.AddFuncName(ctx, r.ctx, "GetPenByIDTx") var pen models.Pen if err := tx.WithContext(repoCtx).First(&pen, id).Error; err != nil { @@ -81,7 +81,7 @@ func (r *gormPigPenRepository) UpdatePen(ctx context.Context, pen *models.Pen) ( } // DeletePen 根据ID删除一个猪栏,返回受影响的行数和错误 -func (r *gormPigPenRepository) DeletePen(ctx context.Context, id uint) (int64, error) { +func (r *gormPigPenRepository) DeletePen(ctx context.Context, id uint32) (int64, error) { repoCtx := logs.AddFuncName(ctx, r.ctx, "DeletePen") result := r.db.WithContext(repoCtx).Delete(&models.Pen{}, id) if result.Error != nil { @@ -91,7 +91,7 @@ func (r *gormPigPenRepository) DeletePen(ctx context.Context, id uint) (int64, e } // GetPensByBatchIDTx 在指定的事务中,获取一个猪群当前关联的所有猪栏。 -func (r *gormPigPenRepository) GetPensByBatchIDTx(ctx context.Context, tx *gorm.DB, batchID uint) ([]*models.Pen, error) { +func (r *gormPigPenRepository) GetPensByBatchIDTx(ctx context.Context, tx *gorm.DB, batchID uint32) ([]*models.Pen, error) { repoCtx := logs.AddFuncName(ctx, r.ctx, "GetPensByBatchIDTx") var pens []*models.Pen // 注意:PigBatchID 是指针类型,需要处理 nil 值 @@ -103,7 +103,7 @@ func (r *gormPigPenRepository) GetPensByBatchIDTx(ctx context.Context, tx *gorm. } // UpdatePenFieldsTx 在指定的事务中,更新一个猪栏的指定字段。 -func (r *gormPigPenRepository) UpdatePenFieldsTx(ctx context.Context, tx *gorm.DB, penID uint, updates map[string]interface{}) error { +func (r *gormPigPenRepository) UpdatePenFieldsTx(ctx context.Context, tx *gorm.DB, penID uint32, updates map[string]interface{}) error { repoCtx := logs.AddFuncName(ctx, r.ctx, "UpdatePenFieldsTx") result := tx.WithContext(repoCtx).Model(&models.Pen{}).Where("id = ?", penID).Updates(updates) return result.Error diff --git a/internal/infra/repository/pig_sick_repository.go b/internal/infra/repository/pig_sick_repository.go index 61f63e9..8a8b569 100644 --- a/internal/infra/repository/pig_sick_repository.go +++ b/internal/infra/repository/pig_sick_repository.go @@ -13,11 +13,11 @@ import ( // PigSickLogListOptions 定义了查询病猪日志时的可选参数 type PigSickLogListOptions struct { - PigBatchID *uint - PenID *uint + PigBatchID *uint32 + PenID *uint32 Reason *models.PigBatchSickPigReasonType TreatmentLocation *models.PigBatchSickPigTreatmentLocation - OperatorID *uint + OperatorID *uint32 StartTime *time.Time // 基于 happened_at 字段 EndTime *time.Time // 基于 happened_at 字段 OrderBy string // 例如 "happened_at desc" @@ -30,7 +30,7 @@ type PigSickLogRepository interface { CreatePigSickLogTx(ctx context.Context, tx *gorm.DB, log *models.PigSickLog) error // GetLastLogByBatchTx 在事务中获取指定批次和猪栏的最新一条 PigSickLog 记录 - GetLastLogByBatchTx(ctx context.Context, tx *gorm.DB, batchID uint) (*models.PigSickLog, error) + GetLastLogByBatchTx(ctx context.Context, tx *gorm.DB, batchID uint32) (*models.PigSickLog, error) // ListPigSickLogs 支持分页和过滤的病猪日志列表查询 ListPigSickLogs(ctx context.Context, opts PigSickLogListOptions, page, pageSize int) ([]models.PigSickLog, int64, error) @@ -58,7 +58,7 @@ func (r *gormPigSickLogRepository) CreatePigSickLogTx(ctx context.Context, tx *g } // GetLastLogByBatchTx 在事务中获取指定批次和猪栏的最新一条 PigSickLog 记录 -func (r *gormPigSickLogRepository) GetLastLogByBatchTx(ctx context.Context, tx *gorm.DB, batchID uint) (*models.PigSickLog, error) { +func (r *gormPigSickLogRepository) GetLastLogByBatchTx(ctx context.Context, tx *gorm.DB, batchID uint32) (*models.PigSickLog, error) { repoCtx := logs.AddFuncName(ctx, r.ctx, "GetLastLogByBatchTx") var lastLog models.PigSickLog err := tx.WithContext(repoCtx). diff --git a/internal/infra/repository/pig_trade_repository.go b/internal/infra/repository/pig_trade_repository.go index 3e6cd25..06f85bb 100644 --- a/internal/infra/repository/pig_trade_repository.go +++ b/internal/infra/repository/pig_trade_repository.go @@ -12,9 +12,9 @@ import ( // PigPurchaseListOptions 定义了查询猪只采购记录时的可选参数 type PigPurchaseListOptions struct { - PigBatchID *uint + PigBatchID *uint32 Supplier *string - OperatorID *uint + OperatorID *uint32 StartTime *time.Time // 基于 purchase_date 字段 EndTime *time.Time // 基于 purchase_date 字段 OrderBy string // 例如 "purchase_date desc" @@ -22,9 +22,9 @@ type PigPurchaseListOptions struct { // PigSaleListOptions 定义了查询猪只销售记录时的可选参数 type PigSaleListOptions struct { - PigBatchID *uint + PigBatchID *uint32 Buyer *string - OperatorID *uint + OperatorID *uint32 StartTime *time.Time // 基于 sale_date 字段 EndTime *time.Time // 基于 sale_date 字段 OrderBy string // 例如 "sale_date desc" diff --git a/internal/infra/repository/pig_transfer_log_repository.go b/internal/infra/repository/pig_transfer_log_repository.go index ca0d5e5..2a5fc85 100644 --- a/internal/infra/repository/pig_transfer_log_repository.go +++ b/internal/infra/repository/pig_transfer_log_repository.go @@ -12,10 +12,10 @@ import ( // PigTransferLogListOptions 定义了查询猪只迁移日志时的可选参数 type PigTransferLogListOptions struct { - PigBatchID *uint - PenID *uint + PigBatchID *uint32 + PenID *uint32 TransferType *models.PigTransferType // 迁移类型 - OperatorID *uint + OperatorID *uint32 CorrelationID *string StartTime *time.Time // 基于 transfer_time 字段 EndTime *time.Time // 基于 transfer_time 字段 @@ -28,7 +28,7 @@ type PigTransferLogRepository interface { CreatePigTransferLog(ctx context.Context, tx *gorm.DB, log *models.PigTransferLog) error // GetLogsForPenSince 获取指定猪栏自特定时间点以来的所有迁移日志,按时间倒序排列。 - GetLogsForPenSince(ctx context.Context, tx *gorm.DB, penID uint, since time.Time) ([]*models.PigTransferLog, error) + GetLogsForPenSince(ctx context.Context, tx *gorm.DB, penID uint32, since time.Time) ([]*models.PigTransferLog, error) // ListPigTransferLogs 支持分页和过滤的猪只迁移日志列表查询 ListPigTransferLogs(ctx context.Context, opts PigTransferLogListOptions, page, pageSize int) ([]models.PigTransferLog, int64, error) @@ -52,7 +52,7 @@ func (r *gormPigTransferLogRepository) CreatePigTransferLog(ctx context.Context, } // GetLogsForPenSince 实现了获取猪栏自特定时间点以来所有迁移日志的逻辑。 -func (r *gormPigTransferLogRepository) GetLogsForPenSince(ctx context.Context, tx *gorm.DB, penID uint, since time.Time) ([]*models.PigTransferLog, error) { +func (r *gormPigTransferLogRepository) GetLogsForPenSince(ctx context.Context, tx *gorm.DB, penID uint32, since time.Time) ([]*models.PigTransferLog, error) { repoCtx := logs.AddFuncName(ctx, r.ctx, "GetLogsForPenSince") var logs []*models.PigTransferLog err := tx.WithContext(repoCtx).Where("pen_id = ? AND transfer_time >= ?", penID, since).Order("transfer_time DESC").Find(&logs).Error diff --git a/internal/infra/repository/plan_repository.go b/internal/infra/repository/plan_repository.go index 38fe3f4..9f01f57 100644 --- a/internal/infra/repository/plan_repository.go +++ b/internal/infra/repository/plan_repository.go @@ -44,11 +44,11 @@ type PlanRepository interface { // ListPlans 获取计划列表,支持过滤和分页 ListPlans(ctx context.Context, opts ListPlansOptions, page, pageSize int) ([]models.Plan, int64, error) // GetBasicPlanByID 根据ID获取计划的基本信息,不包含子计划和任务详情 - GetBasicPlanByID(ctx context.Context, id uint) (*models.Plan, error) + GetBasicPlanByID(ctx context.Context, id uint32) (*models.Plan, error) // GetPlanByID 根据ID获取计划,包含子计划和任务详情 - GetPlanByID(ctx context.Context, id uint) (*models.Plan, error) + GetPlanByID(ctx context.Context, id uint32) (*models.Plan, error) // GetPlansByIDs 根据ID列表获取计划,不包含子计划和任务详情 - GetPlansByIDs(ctx context.Context, ids []uint) ([]models.Plan, error) + GetPlansByIDs(ctx context.Context, ids []uint32) ([]models.Plan, error) // GetSystemPlanByName 根据计划名称获取系统计划,包含子计划和任务详情 GetSystemPlanByName(ctx context.Context, planName models.PlanName) (*models.Plan, error) // CreatePlan 创建一个新的计划 @@ -60,35 +60,35 @@ type PlanRepository interface { // UpdatePlan 更新计划的所有字段 UpdatePlan(ctx context.Context, plan *models.Plan) error // UpdatePlanStatus 更新指定计划的状态 - UpdatePlanStatus(ctx context.Context, id uint, status models.PlanStatus) error + UpdatePlanStatus(ctx context.Context, id uint32, status models.PlanStatus) error // UpdateExecuteCount 更新指定计划的执行计数 - UpdateExecuteCount(ctx context.Context, id uint, count uint) error + UpdateExecuteCount(ctx context.Context, id uint32, count uint32) error // DeletePlan 根据ID删除计划,同时删除其关联的任务(非子任务)或子计划关联 - DeletePlan(ctx context.Context, id uint) error + DeletePlan(ctx context.Context, id uint32) error // FlattenPlanTasks 递归展开计划,返回按执行顺序排列的所有任务列表 - FlattenPlanTasks(ctx context.Context, planID uint) ([]models.Task, error) + FlattenPlanTasks(ctx context.Context, planID uint32) ([]models.Task, error) // DeleteTask 根据ID删除任务 DeleteTask(ctx context.Context, id int) error // FindTaskByID 根据ID获取任务的基本信息 FindTaskByID(ctx context.Context, id int) (*models.Task, error) // FindPlanAnalysisTaskByParamsPlanID 根据Parameters中的ParamsPlanID字段值查找TaskPlanAnalysis类型的Task - FindPlanAnalysisTaskByParamsPlanID(ctx context.Context, paramsPlanID uint) (*models.Task, error) + FindPlanAnalysisTaskByParamsPlanID(ctx context.Context, paramsPlanID uint32) (*models.Task, error) // FindRunnablePlans 获取所有应执行的计划 FindRunnablePlans(ctx context.Context) ([]*models.Plan, error) // FindInactivePlans 获取所有已禁用或已停止的计划 FindInactivePlans(ctx context.Context) ([]*models.Plan, error) // FindPlanAnalysisTaskByPlanID 根据 PlanID 找到其关联的 'plan_analysis' 任务 - FindPlanAnalysisTaskByPlanID(ctx context.Context, planID uint) (*models.Task, error) + FindPlanAnalysisTaskByPlanID(ctx context.Context, planID uint32) (*models.Task, error) // CreatePlanAnalysisTask 创建一个 plan_analysis 类型的任务并返回它 CreatePlanAnalysisTask(ctx context.Context, plan *models.Plan) (*models.Task, error) // FindPlansWithPendingTasks 查找所有正在执行的计划 FindPlansWithPendingTasks(ctx context.Context) ([]*models.Plan, error) // StopPlanTransactionally 停止一个计划的执行,包括更新状态、移除待执行任务和更新执行日志 - StopPlanTransactionally(ctx context.Context, planID uint) error + StopPlanTransactionally(ctx context.Context, planID uint32) error // UpdatePlanStateAfterExecution 更新计划执行后的状态(计数和状态) - UpdatePlanStateAfterExecution(ctx context.Context, planID uint, newCount uint, newStatus models.PlanStatus) error + UpdatePlanStateAfterExecution(ctx context.Context, planID uint32, newCount uint32, newStatus models.PlanStatus) error // ListTasksByDeviceID 根据设备ID获取关联任务列表 - ListTasksByDeviceID(ctx context.Context, deviceID uint) ([]*models.Task, error) + ListTasksByDeviceID(ctx context.Context, deviceID uint32) ([]*models.Task, error) } // gormPlanRepository 是 PlanRepository 的 GORM 实现 @@ -140,7 +140,7 @@ func (r *gormPlanRepository) ListPlans(ctx context.Context, opts ListPlansOption } // GetBasicPlanByID 根据ID获取计划的基本信息,不包含子计划和任务详情 -func (r *gormPlanRepository) GetBasicPlanByID(ctx context.Context, id uint) (*models.Plan, error) { +func (r *gormPlanRepository) GetBasicPlanByID(ctx context.Context, id uint32) (*models.Plan, error) { repoCtx := logs.AddFuncName(ctx, r.ctx, "GetBasicPlanByID") var plan models.Plan // GORM 默认不会加载关联,除非使用 Preload,所以直接 First 即可满足要求 @@ -152,7 +152,7 @@ func (r *gormPlanRepository) GetBasicPlanByID(ctx context.Context, id uint) (*mo } // GetPlansByIDs 根据ID列表获取计划,不包含子计划和任务详情 -func (r *gormPlanRepository) GetPlansByIDs(ctx context.Context, ids []uint) ([]models.Plan, error) { +func (r *gormPlanRepository) GetPlansByIDs(ctx context.Context, ids []uint32) ([]models.Plan, error) { repoCtx := logs.AddFuncName(ctx, r.ctx, "GetPlansByIDs") var plans []models.Plan if len(ids) == 0 { @@ -183,7 +183,7 @@ func (r *gormPlanRepository) GetSystemPlanByName(ctx context.Context, planName m } // GetPlanByID 根据ID获取计划,包含子计划和任务详情 -func (r *gormPlanRepository) GetPlanByID(ctx context.Context, id uint) (*models.Plan, error) { +func (r *gormPlanRepository) GetPlanByID(ctx context.Context, id uint32) (*models.Plan, error) { repoCtx := logs.AddFuncName(ctx, r.ctx, "GetPlanByID") var plan models.Plan @@ -254,7 +254,7 @@ func (r *gormPlanRepository) CreatePlanTx(ctx context.Context, tx *gorm.DB, plan // 如果是子计划类型,验证所有子计划是否存在且ID不为0 if plan.ContentType == models.PlanContentTypeSubPlans { - childIDsToValidate := make(map[uint]bool) + childIDsToValidate := make(map[uint32]bool) for _, subPlanLink := range plan.SubPlans { if subPlanLink.ChildPlanID == 0 { return ErrSubPlanIDIsZeroOnCreate @@ -262,7 +262,7 @@ func (r *gormPlanRepository) CreatePlanTx(ctx context.Context, tx *gorm.DB, plan childIDsToValidate[subPlanLink.ChildPlanID] = true } - var ids []uint + var ids []uint32 for id := range childIDsToValidate { ids = append(ids, id) } @@ -334,8 +334,8 @@ func (r *gormPlanRepository) validatePlanTree(ctx context.Context, tx *gorm.DB, } // 2. 递归验证所有子节点,并检测循环引用 - allIDs := make(map[uint]bool) - recursionStack := make(map[uint]bool) + allIDs := make(map[uint32]bool) + recursionStack := make(map[uint32]bool) if err := validateNodeAndDetectCycles(plan, allIDs, recursionStack); err != nil { return err } @@ -346,7 +346,7 @@ func (r *gormPlanRepository) validatePlanTree(ctx context.Context, tx *gorm.DB, } // 4. 一次性数据库存在性校验 - var idsToCheck []uint + var idsToCheck []uint32 for id := range allIDs { idsToCheck = append(idsToCheck, id) } @@ -364,7 +364,7 @@ func (r *gormPlanRepository) validatePlanTree(ctx context.Context, tx *gorm.DB, } // validateNodeAndDetectCycles 递归地验证节点有效性并检测循环引用 -func validateNodeAndDetectCycles(plan *models.Plan, allIDs, recursionStack map[uint]bool) error { +func validateNodeAndDetectCycles(plan *models.Plan, allIDs, recursionStack map[uint32]bool) error { if plan == nil { return nil } @@ -469,7 +469,7 @@ func (r *gormPlanRepository) reconcileSubPlans(ctx context.Context, tx *gorm.DB, return err } - existingLinkMap := make(map[uint]bool) + existingLinkMap := make(map[uint32]bool) for _, link := range existingLinks { existingLinkMap[link.ID] = true } @@ -489,7 +489,7 @@ func (r *gormPlanRepository) reconcileSubPlans(ctx context.Context, tx *gorm.DB, } } - var linksToDelete []uint + var linksToDelete []uint32 for id := range existingLinkMap { linksToDelete = append(linksToDelete, id) } @@ -503,7 +503,7 @@ func (r *gormPlanRepository) reconcileSubPlans(ctx context.Context, tx *gorm.DB, } // DeletePlan 根据ID删除计划,同时删除其关联的任务(非子任务)或子计划关联 -func (r *gormPlanRepository) DeletePlan(ctx context.Context, id uint) error { +func (r *gormPlanRepository) DeletePlan(ctx context.Context, id uint32) error { repoCtx := logs.AddFuncName(ctx, r.ctx, "DeletePlan") return r.db.WithContext(repoCtx).Transaction(func(tx *gorm.DB) error { // 1. 检查该计划是否是其他计划的子计划 @@ -545,7 +545,7 @@ func (r *gormPlanRepository) DeletePlan(ctx context.Context, id uint) error { } // FlattenPlanTasks 递归展开计划,返回按执行顺序排列的所有任务列表 -func (r *gormPlanRepository) FlattenPlanTasks(ctx context.Context, planID uint) ([]models.Task, error) { +func (r *gormPlanRepository) FlattenPlanTasks(ctx context.Context, planID uint32) ([]models.Task, error) { repoCtx := logs.AddFuncName(ctx, r.ctx, "FlattenPlanTasks") plan, err := r.GetPlanByID(repoCtx, planID) if err != nil { @@ -645,7 +645,7 @@ func (r *gormPlanRepository) deleteTasksTx(ctx context.Context, tx *gorm.DB, ids } // FindPlanAnalysisTaskByParamsPlanID 根据Parameters中的ParamsPlanID字段值查找TaskPlanAnalysis类型的Task -func (r *gormPlanRepository) FindPlanAnalysisTaskByParamsPlanID(ctx context.Context, paramsPlanID uint) (*models.Task, error) { +func (r *gormPlanRepository) FindPlanAnalysisTaskByParamsPlanID(ctx context.Context, paramsPlanID uint32) (*models.Task, error) { repoCtx := logs.AddFuncName(ctx, r.ctx, "FindPlanAnalysisTaskByParamsPlanID") return r.findPlanAnalysisTask(repoCtx, r.db, paramsPlanID) } @@ -722,7 +722,7 @@ func (r *gormPlanRepository) FindInactivePlans(ctx context.Context) ([]*models.P // findPlanAnalysisTask 是一个内部使用的、更高效的查找方法 // 关键修改:通过查询 parameters JSON 字段来查找 -func (r *gormPlanRepository) findPlanAnalysisTask(ctx context.Context, tx *gorm.DB, planID uint) (*models.Task, error) { +func (r *gormPlanRepository) findPlanAnalysisTask(ctx context.Context, tx *gorm.DB, planID uint32) (*models.Task, error) { repoCtx := logs.AddFuncName(ctx, r.ctx, "findPlanAnalysisTask") var task models.Task err := tx.WithContext(repoCtx).Where("type = ? AND parameters->>'plan_id' = ?", models.TaskPlanAnalysis, fmt.Sprintf("%d", planID)).First(&task).Error @@ -734,7 +734,7 @@ func (r *gormPlanRepository) findPlanAnalysisTask(ctx context.Context, tx *gorm. // FindPlanAnalysisTaskByPlanID 是暴露给外部的公共方法 // 关键修改:通过查询 parameters JSON 字段来查找 -func (r *gormPlanRepository) FindPlanAnalysisTaskByPlanID(ctx context.Context, planID uint) (*models.Task, error) { +func (r *gormPlanRepository) FindPlanAnalysisTaskByPlanID(ctx context.Context, planID uint32) (*models.Task, error) { repoCtx := logs.AddFuncName(ctx, r.ctx, "FindPlanAnalysisTaskByPlanID") return r.findPlanAnalysisTask(repoCtx, r.db, planID) } @@ -769,7 +769,7 @@ func (r *gormPlanRepository) FindPlansWithPendingTasks(ctx context.Context) ([]* } // StopPlanTransactionally 停止一个计划的执行,包括更新状态、移除待执行任务和更新执行日志。 -func (r *gormPlanRepository) StopPlanTransactionally(ctx context.Context, planID uint) error { +func (r *gormPlanRepository) StopPlanTransactionally(ctx context.Context, planID uint32) error { repoCtx := logs.AddFuncName(ctx, r.ctx, "StopPlanTransactionally") return r.db.WithContext(repoCtx).Transaction(func(tx *gorm.DB) error { // 使用事务创建新的仓库实例,确保所有操作都在同一个事务中 @@ -800,7 +800,7 @@ func (r *gormPlanRepository) StopPlanTransactionally(ctx context.Context, planID } if len(taskLogs) > 0 { - var taskLogIDs []uint + var taskLogIDs []uint32 for _, tl := range taskLogs { taskLogIDs = append(taskLogIDs, tl.ID) } @@ -817,7 +817,7 @@ func (r *gormPlanRepository) StopPlanTransactionally(ctx context.Context, planID } if len(pendingTasks) > 0 { - var pendingTaskIDs []uint + var pendingTaskIDs []uint32 for _, pt := range pendingTasks { pendingTaskIDs = append(pendingTaskIDs, pt.ID) } @@ -837,7 +837,7 @@ func (r *gormPlanRepository) StopPlanTransactionally(ctx context.Context, planID } // UpdatePlanStatus 更新指定计划的状态 -func (r *gormPlanRepository) UpdatePlanStatus(ctx context.Context, id uint, status models.PlanStatus) error { +func (r *gormPlanRepository) UpdatePlanStatus(ctx context.Context, id uint32, status models.PlanStatus) error { repoCtx := logs.AddFuncName(ctx, r.ctx, "UpdatePlanStatus") result := r.db.WithContext(repoCtx).Model(&models.Plan{}).Where("id = ?", id).Update("status", status) if result.Error != nil { @@ -849,7 +849,7 @@ func (r *gormPlanRepository) UpdatePlanStatus(ctx context.Context, id uint, stat return nil } -func (r *gormPlanRepository) UpdatePlanStateAfterExecution(ctx context.Context, planID uint, newCount uint, newStatus models.PlanStatus) error { +func (r *gormPlanRepository) UpdatePlanStateAfterExecution(ctx context.Context, planID uint32, newCount uint32, newStatus models.PlanStatus) error { repoCtx := logs.AddFuncName(ctx, r.ctx, "UpdatePlanStateAfterExecution") return r.db.WithContext(repoCtx).Model(&models.Plan{}).Where("id = ?", planID).Updates(map[string]interface{}{ "execute_count": newCount, @@ -858,7 +858,7 @@ func (r *gormPlanRepository) UpdatePlanStateAfterExecution(ctx context.Context, } // UpdateExecuteCount 更新指定计划的执行计数 -func (r *gormPlanRepository) UpdateExecuteCount(ctx context.Context, id uint, count uint) error { +func (r *gormPlanRepository) UpdateExecuteCount(ctx context.Context, id uint32, count uint32) error { repoCtx := logs.AddFuncName(ctx, r.ctx, "UpdateExecuteCount") result := r.db.WithContext(repoCtx).Model(&models.Plan{}).Where("id = ?", id).Update("execute_count", count) if result.Error != nil { @@ -881,7 +881,7 @@ func (r *gormPlanRepository) FindTaskByID(ctx context.Context, id int) (*models. return &task, nil } -func (r *gormPlanRepository) ListTasksByDeviceID(ctx context.Context, deviceID uint) ([]*models.Task, error) { +func (r *gormPlanRepository) ListTasksByDeviceID(ctx context.Context, deviceID uint32) ([]*models.Task, error) { repoCtx := logs.AddFuncName(ctx, r.ctx, "ListTasksByDeviceID") tasks := []*models.Task{} // 使用 Joins 方法来连接 tasks 表和 device_tasks 关联表, diff --git a/internal/infra/repository/raw_material_repository.go b/internal/infra/repository/raw_material_repository.go index ba6a757..2795167 100644 --- a/internal/infra/repository/raw_material_repository.go +++ b/internal/infra/repository/raw_material_repository.go @@ -12,7 +12,7 @@ import ( // RawMaterialPurchaseListOptions 定义了查询原料采购记录时的可选参数 type RawMaterialPurchaseListOptions struct { - RawMaterialID *uint + RawMaterialID *uint32 Supplier *string StartTime *time.Time // 基于 purchase_date 字段 EndTime *time.Time // 基于 purchase_date 字段 @@ -21,9 +21,9 @@ type RawMaterialPurchaseListOptions struct { // RawMaterialStockLogListOptions 定义了查询原料库存日志时的可选参数 type RawMaterialStockLogListOptions struct { - RawMaterialID *uint + RawMaterialID *uint32 SourceType *models.StockLogSourceType - SourceID *uint + SourceID *uint32 StartTime *time.Time // 基于 happened_at 字段 EndTime *time.Time // 基于 happened_at 字段 OrderBy string // 例如 "happened_at asc" @@ -31,9 +31,9 @@ type RawMaterialStockLogListOptions struct { // FeedUsageRecordListOptions 定义了查询饲料使用记录时的可选参数 type FeedUsageRecordListOptions struct { - PenID *uint - FeedFormulaID *uint - OperatorID *uint + PenID *uint32 + FeedFormulaID *uint32 + OperatorID *uint32 StartTime *time.Time // 基于 recorded_at 字段 EndTime *time.Time // 基于 recorded_at 字段 OrderBy string // 例如 "recorded_at asc" diff --git a/internal/infra/repository/sensor_data_repository.go b/internal/infra/repository/sensor_data_repository.go index 70c8810..88f1aea 100644 --- a/internal/infra/repository/sensor_data_repository.go +++ b/internal/infra/repository/sensor_data_repository.go @@ -12,7 +12,7 @@ import ( // SensorDataListOptions 定义了查询传感器数据列表时的可选参数 type SensorDataListOptions struct { - DeviceID *uint + DeviceID *uint32 SensorType *models.SensorType StartTime *time.Time EndTime *time.Time @@ -22,7 +22,7 @@ type SensorDataListOptions struct { // SensorDataRepository 定义了与传感器数据相关的数据库操作接口。 type SensorDataRepository interface { Create(ctx context.Context, sensorData *models.SensorData) error - GetLatestSensorDataByDeviceIDAndSensorType(ctx context.Context, deviceID uint, sensorType models.SensorType) (*models.SensorData, error) + GetLatestSensorDataByDeviceIDAndSensorType(ctx context.Context, deviceID uint32, sensorType models.SensorType) (*models.SensorData, error) // List 支持分页和过滤的列表查询 List(ctx context.Context, opts SensorDataListOptions, page, pageSize int) ([]models.SensorData, int64, error) } @@ -45,7 +45,7 @@ func (r *gormSensorDataRepository) Create(ctx context.Context, sensorData *model } // GetLatestSensorDataByDeviceIDAndSensorType 根据设备ID和传感器类型查询最新的传感器数据。 -func (r *gormSensorDataRepository) GetLatestSensorDataByDeviceIDAndSensorType(ctx context.Context, deviceID uint, sensorType models.SensorType) (*models.SensorData, error) { +func (r *gormSensorDataRepository) GetLatestSensorDataByDeviceIDAndSensorType(ctx context.Context, deviceID uint32, sensorType models.SensorType) (*models.SensorData, error) { repoCtx := logs.AddFuncName(ctx, r.ctx, "GetLatestSensorDataByDeviceIDAndSensorType") var sensorData models.SensorData // 增加一个时间范围来缩小查询范围, 从而加快查找速度, 当使用时序数据库时时间范围可以让数据库忽略时间靠前的分片 diff --git a/internal/infra/repository/user_action_log_repository.go b/internal/infra/repository/user_action_log_repository.go index e0102e9..fcd4f32 100644 --- a/internal/infra/repository/user_action_log_repository.go +++ b/internal/infra/repository/user_action_log_repository.go @@ -12,7 +12,7 @@ import ( // UserActionLogListOptions 定义了查询用户操作日志时的可选参数 type UserActionLogListOptions struct { - UserID *uint + UserID *uint32 Username *string ActionType *string Status *models.AuditStatus diff --git a/internal/infra/repository/user_repository.go b/internal/infra/repository/user_repository.go index 97b8bb2..66f6c87 100644 --- a/internal/infra/repository/user_repository.go +++ b/internal/infra/repository/user_repository.go @@ -15,7 +15,7 @@ import ( type UserRepository interface { Create(ctx context.Context, user *models.User) error FindByUsername(ctx context.Context, username string) (*models.User, error) - FindByID(ctx context.Context, id uint) (*models.User, error) + FindByID(ctx context.Context, id uint32) (*models.User, error) FindUserForLogin(ctx context.Context, identifier string) (*models.User, error) FindAll(ctx context.Context) ([]*models.User, error) } @@ -66,7 +66,7 @@ func (r *gormUserRepository) FindUserForLogin(ctx context.Context, identifier st } // FindByID 根据 ID 查找用户 -func (r *gormUserRepository) FindByID(ctx context.Context, id uint) (*models.User, error) { +func (r *gormUserRepository) FindByID(ctx context.Context, id uint32) (*models.User, error) { repoCtx := logs.AddFuncName(ctx, r.ctx, "FindByID") var user models.User if err := r.db.WithContext(repoCtx).First(&user, id).Error; err != nil { diff --git a/internal/infra/transport/lora/lora_mesh_uart_passthrough_transport.go b/internal/infra/transport/lora/lora_mesh_uart_passthrough_transport.go index c719246..a302e48 100644 --- a/internal/infra/transport/lora/lora_mesh_uart_passthrough_transport.go +++ b/internal/infra/transport/lora/lora_mesh_uart_passthrough_transport.go @@ -502,7 +502,7 @@ func (t *LoRaMeshUartPassthroughTransport) handleUpstreamMessage(ctx context.Con } // recordSensorData 是一个通用方法,用于将传感器数据存入数据库。 -func (t *LoRaMeshUartPassthroughTransport) recordSensorData(ctx context.Context, areaControllerID uint, sensorDeviceID uint, eventTime time.Time, sensorType models.SensorType, data interface{}) { +func (t *LoRaMeshUartPassthroughTransport) recordSensorData(ctx context.Context, areaControllerID uint32, sensorDeviceID uint32, eventTime time.Time, sensorType models.SensorType, data interface{}) { loraCtx, logger := logs.Trace(ctx, t.ctx, "recordSensorData") jsonData, err := json.Marshal(data) diff --git a/internal/infra/utils/token/token_service.go b/internal/infra/utils/token/token_service.go index 69dcbcc..8311e2e 100644 --- a/internal/infra/utils/token/token_service.go +++ b/internal/infra/utils/token/token_service.go @@ -9,13 +9,13 @@ import ( // Claims 定义了 JWT 的声明结构 type Claims struct { - UserID uint `json:"user_id"` + UserID uint32 `json:"user_id"` jwt.RegisteredClaims } // Generator 定义了 token 操作的接口 type Generator interface { - GenerateToken(userID uint) (string, error) + GenerateToken(userID uint32) (string, error) ParseToken(tokenString string) (*Claims, error) } @@ -30,7 +30,7 @@ func NewTokenGenerator(secret []byte) Generator { } // GenerateToken 生成一个新的 JWT token -func (s *tokenGenerator) GenerateToken(userID uint) (string, error) { +func (s *tokenGenerator) GenerateToken(userID uint32) (string, error) { nowTime := time.Now() expireTime := nowTime.Add(24 * time.Hour) // Token 有效期为 24 小时