uint/uint64全部改为uint32

This commit is contained in:
2025-11-10 22:23:31 +08:00
parent 3e711551e7
commit ecd2d37c70
96 changed files with 775 additions and 785 deletions

View File

@@ -145,4 +145,5 @@
13. 实现根据区域ID或设备ID清空对应阈值告警任务 13. 实现根据区域ID或设备ID清空对应阈值告警任务
14. 设备和区域主控删除时清除对应区域阈值告警或设备阈值告警任务 14. 设备和区域主控删除时清除对应区域阈值告警或设备阈值告警任务
15. 将所有Regional更改为Area 15. 将所有Regional更改为Area
16. float64全部改float32 16. float64全部改float32
17. uint/uint64全部改为uint32

View File

@@ -1665,7 +1665,6 @@ const docTemplate = `{
}, },
{ {
"enum": [ "enum": [
7,
-1, -1,
0, 0,
1, 1,
@@ -1675,12 +1674,12 @@ const docTemplate = `{
5, 5,
-1, -1,
5, 5,
6 6,
7
], ],
"type": "integer", "type": "integer",
"format": "int32", "format": "int32",
"x-enum-varnames": [ "x-enum-varnames": [
"_numLevels",
"DebugLevel", "DebugLevel",
"InfoLevel", "InfoLevel",
"WarnLevel", "WarnLevel",
@@ -1690,7 +1689,8 @@ const docTemplate = `{
"FatalLevel", "FatalLevel",
"_minLevel", "_minLevel",
"_maxLevel", "_maxLevel",
"InvalidLevel" "InvalidLevel",
"_numLevels"
], ],
"name": "level", "name": "level",
"in": "query" "in": "query"
@@ -7981,7 +7981,6 @@ const docTemplate = `{
"type": "integer", "type": "integer",
"format": "int32", "format": "int32",
"enum": [ "enum": [
7,
-1, -1,
0, 0,
1, 1,
@@ -7991,10 +7990,10 @@ const docTemplate = `{
5, 5,
-1, -1,
5, 5,
6 6,
7
], ],
"x-enum-varnames": [ "x-enum-varnames": [
"_numLevels",
"DebugLevel", "DebugLevel",
"InfoLevel", "InfoLevel",
"WarnLevel", "WarnLevel",
@@ -8004,7 +8003,8 @@ const docTemplate = `{
"FatalLevel", "FatalLevel",
"_minLevel", "_minLevel",
"_maxLevel", "_maxLevel",
"InvalidLevel" "InvalidLevel",
"_numLevels"
] ]
} }
}, },

View File

@@ -1657,7 +1657,6 @@
}, },
{ {
"enum": [ "enum": [
7,
-1, -1,
0, 0,
1, 1,
@@ -1667,12 +1666,12 @@
5, 5,
-1, -1,
5, 5,
6 6,
7
], ],
"type": "integer", "type": "integer",
"format": "int32", "format": "int32",
"x-enum-varnames": [ "x-enum-varnames": [
"_numLevels",
"DebugLevel", "DebugLevel",
"InfoLevel", "InfoLevel",
"WarnLevel", "WarnLevel",
@@ -1682,7 +1681,8 @@
"FatalLevel", "FatalLevel",
"_minLevel", "_minLevel",
"_maxLevel", "_maxLevel",
"InvalidLevel" "InvalidLevel",
"_numLevels"
], ],
"name": "level", "name": "level",
"in": "query" "in": "query"
@@ -7973,7 +7973,6 @@
"type": "integer", "type": "integer",
"format": "int32", "format": "int32",
"enum": [ "enum": [
7,
-1, -1,
0, 0,
1, 1,
@@ -7983,10 +7982,10 @@
5, 5,
-1, -1,
5, 5,
6 6,
7
], ],
"x-enum-varnames": [ "x-enum-varnames": [
"_numLevels",
"DebugLevel", "DebugLevel",
"InfoLevel", "InfoLevel",
"WarnLevel", "WarnLevel",
@@ -7996,7 +7995,8 @@
"FatalLevel", "FatalLevel",
"_minLevel", "_minLevel",
"_maxLevel", "_maxLevel",
"InvalidLevel" "InvalidLevel",
"_numLevels"
] ]
} }
}, },

View File

@@ -2230,7 +2230,6 @@ definitions:
- PlanTypeFilterSystem - PlanTypeFilterSystem
zapcore.Level: zapcore.Level:
enum: enum:
- 7
- -1 - -1
- 0 - 0
- 1 - 1
@@ -2241,10 +2240,10 @@ definitions:
- -1 - -1
- 5 - 5
- 6 - 6
- 7
format: int32 format: int32
type: integer type: integer
x-enum-varnames: x-enum-varnames:
- _numLevels
- DebugLevel - DebugLevel
- InfoLevel - InfoLevel
- WarnLevel - WarnLevel
@@ -2255,6 +2254,7 @@ definitions:
- _minLevel - _minLevel
- _maxLevel - _maxLevel
- InvalidLevel - InvalidLevel
- _numLevels
info: info:
contact: contact:
email: divano@example.com email: divano@example.com
@@ -3248,7 +3248,6 @@ paths:
name: end_time name: end_time
type: string type: string
- enum: - enum:
- 7
- -1 - -1
- 0 - 0
- 1 - 1
@@ -3259,12 +3258,12 @@ paths:
- -1 - -1
- 5 - 5
- 6 - 6
- 7
format: int32 format: int32
in: query in: query
name: level name: level
type: integer type: integer
x-enum-varnames: x-enum-varnames:
- _numLevels
- DebugLevel - DebugLevel
- InfoLevel - InfoLevel
- WarnLevel - WarnLevel
@@ -3275,6 +3274,7 @@ paths:
- _minLevel - _minLevel
- _maxLevel - _maxLevel
- InvalidLevel - InvalidLevel
- _numLevels
- enum: - enum:
- 邮件 - 邮件
- 企业微信 - 企业微信

View File

@@ -61,7 +61,7 @@ func (t *ThresholdAlarmController) SnoozeThresholdAlarm(ctx echo.Context) error
return controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, "无效的请求体: "+err.Error(), actionType, "请求体绑定失败", req) 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) { if errors.Is(err, gorm.ErrRecordNotFound) {
logger.Warnf("%s: 告警不存在, ID: %d", actionType, alarmID) logger.Warnf("%s: 告警不存在, ID: %d", actionType, alarmID)
return controller.SendErrorWithAudit(ctx, controller.CodeNotFound, "告警未找到", 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) 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) { if errors.Is(err, gorm.ErrRecordNotFound) {
logger.Warnf("%s: 告警不存在, ID: %d", actionType, alarmID) logger.Warnf("%s: 告警不存在, ID: %d", actionType, alarmID)
return controller.SendErrorWithAudit(ctx, controller.CodeNotFound, "告警未找到", actionType, "告警不存在", alarmID) return controller.SendErrorWithAudit(ctx, controller.CodeNotFound, "告警未找到", actionType, "告警不存在", alarmID)

View File

@@ -17,7 +17,7 @@ var (
// GetOperatorIDFromContext 从 echo.Context 中提取操作者ID。 // GetOperatorIDFromContext 从 echo.Context 中提取操作者ID。
// 假设操作者ID是由 AuthMiddleware 存储到 context 中的 *models.User 对象的 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()) userVal := c.Get(models.ContextUserKey.String())
if userVal == nil { if userVal == nil {
return 0, ErrUserNotFoundInContext return 0, ErrUserNotFoundInContext

View File

@@ -84,7 +84,7 @@ func (c *Controller) GetDevice(ctx echo.Context) error {
return controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, "无效的ID: "+deviceID, actionType, "无效的ID", deviceID) 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 err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) { if errors.Is(err, gorm.ErrRecordNotFound) {
logger.Warnf("%s: 设备不存在, ID: %s", actionType, deviceID) 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) 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 err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) { if errors.Is(err, gorm.ErrRecordNotFound) {
logger.Warnf("%s: 设备不存在, ID: %s", actionType, deviceID) 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) 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 { switch {
case errors.Is(err, gorm.ErrRecordNotFound): case errors.Is(err, gorm.ErrRecordNotFound):
logger.Warnf("%s: 设备不存在, ID: %s", actionType, deviceID) 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) 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) { if errors.Is(err, gorm.ErrRecordNotFound) {
logger.Warnf("%s: 设备不存在, ID: %s", actionType, deviceID) logger.Warnf("%s: 设备不存在, ID: %s", actionType, deviceID)
return controller.SendErrorWithAudit(ctx, controller.CodeNotFound, "设备未找到", 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) 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 err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) { if errors.Is(err, gorm.ErrRecordNotFound) {
logger.Warnf("%s: 区域主控不存在, ID: %s", actionType, acID) 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) 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 err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) { if errors.Is(err, gorm.ErrRecordNotFound) {
logger.Warnf("%s: 区域主控不存在, ID: %s", actionType, acID) 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) 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 { switch {
case errors.Is(err, gorm.ErrRecordNotFound): case errors.Is(err, gorm.ErrRecordNotFound):
logger.Warnf("%s: 区域主控不存在, ID: %s", actionType, acID) 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) 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 err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) { if errors.Is(err, gorm.ErrRecordNotFound) {
logger.Warnf("%s: 设备模板不存在, ID: %s", actionType, dtID) 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) 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 err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) { if errors.Is(err, gorm.ErrRecordNotFound) {
logger.Warnf("%s: 设备模板不存在, ID: %s", actionType, dtID) 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) 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 { switch {
case errors.Is(err, gorm.ErrRecordNotFound): case errors.Is(err, gorm.ErrRecordNotFound):
logger.Warnf("%s: 设备模板不存在, ID: %s", actionType, dtID) logger.Warnf("%s: 设备模板不存在, ID: %s", actionType, dtID)

View File

@@ -15,7 +15,7 @@ import (
// mapAndSendError 统一映射服务层错误并发送响应。 // mapAndSendError 统一映射服务层错误并发送响应。
// 这个函数将服务层返回的错误转换为控制器层应返回的HTTP状态码和审计信息。 // 这个函数将服务层返回的错误转换为控制器层应返回的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) || if errors.Is(err, service.ErrPigBatchNotFound) ||
errors.Is(err, service.ErrPenNotFound) || errors.Is(err, service.ErrPenNotFound) ||
errors.Is(err, service.ErrPenNotAssociatedWithBatch) { errors.Is(err, service.ErrPenNotAssociatedWithBatch) {
@@ -34,7 +34,7 @@ func mapAndSendError(reqContext context.Context, c *PigBatchController, ctx echo
} }
// idExtractorFunc 定义了一个函数类型用于从echo.Context中提取主ID。 // 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的通用逻辑。 // extractOperatorAndPrimaryID 封装了从echo.Context中提取操作员ID和主ID的通用逻辑。
// 它负责处理ID提取过程中的错误并发送相应的HTTP响应。 // 它负责处理ID提取过程中的错误并发送相应的HTTP响应。
@@ -48,15 +48,15 @@ type idExtractorFunc func(ctx echo.Context) (uint, error)
// //
// 返回值: // 返回值:
// //
// operatorID: uint - 提取到的操作员ID。 // operatorID: uint32 - 提取到的操作员ID。
// primaryID: uint - 提取到的主ID。 // primaryID: uint32 - 提取到的主ID。
// err: error - 如果ID提取失败或发送错误响应则返回错误。 // err: error - 如果ID提取失败或发送错误响应则返回错误。
func extractOperatorAndPrimaryID( func extractOperatorAndPrimaryID(
c *PigBatchController, c *PigBatchController,
ctx echo.Context, ctx echo.Context,
action string, action string,
idExtractor idExtractorFunc, idExtractor idExtractorFunc,
) (operatorID uint, primaryID uint, err error) { ) (operatorID uint32, primaryID uint32, err error) {
// 1. 获取操作员ID // 1. 获取操作员ID
operatorID, err = controller.GetOperatorIDFromContext(ctx) operatorID, err = controller.GetOperatorIDFromContext(ctx)
if err != nil { if err != nil {
@@ -78,7 +78,7 @@ func extractOperatorAndPrimaryID(
if err != nil { if err != nil {
return 0, 0, controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, "无效的ID格式", action, "ID格式错误", idParam) 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, ctx echo.Context,
action string, action string,
reqDTO Req, 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, successMsg string,
idExtractor idExtractorFunc, idExtractor idExtractorFunc,
) error { ) error {
@@ -124,7 +124,7 @@ func handleNoBodyAPIRequest(
c *PigBatchController, c *PigBatchController,
ctx echo.Context, ctx echo.Context,
action string, action string,
serviceExecutor func(ctx echo.Context, operatorID uint, primaryID uint) error, serviceExecutor func(ctx echo.Context, operatorID uint32, primaryID uint32) error,
successMsg string, successMsg string,
idExtractor idExtractorFunc, idExtractor idExtractorFunc,
) error { ) error {
@@ -151,7 +151,7 @@ func handleAPIRequestWithResponse[Req any, Resp any](
ctx echo.Context, ctx echo.Context,
action string, action string,
reqDTO Req, 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, successMsg string,
idExtractor idExtractorFunc, idExtractor idExtractorFunc,
) error { ) error {
@@ -182,7 +182,7 @@ func handleNoBodyAPIRequestWithResponse[Resp any](
c *PigBatchController, c *PigBatchController,
ctx echo.Context, ctx echo.Context,
action string, 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, successMsg string,
idExtractor idExtractorFunc, idExtractor idExtractorFunc,
) error { ) error {
@@ -209,7 +209,7 @@ func handleQueryAPIRequestWithResponse[Query any, Resp any](
ctx echo.Context, ctx echo.Context,
action string, action string,
queryDTO Query, 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, successMsg string,
) error { ) error {
// 1. 绑定查询参数 // 1. 绑定查询参数

View File

@@ -43,7 +43,7 @@ func (c *PigBatchController) CreatePigBatch(ctx echo.Context) error {
return handleAPIRequestWithResponse( return handleAPIRequestWithResponse(
reqCtx, c, ctx, action, &req, 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通常不从路径中获取而是由服务层生成 // 对于创建操作primaryID通常不从路径中获取而是由服务层生成
return c.service.CreatePigBatch(reqCtx, operatorID, req) return c.service.CreatePigBatch(reqCtx, operatorID, req)
}, },
@@ -68,7 +68,7 @@ func (c *PigBatchController) GetPigBatch(ctx echo.Context) error {
return handleNoBodyAPIRequestWithResponse( return handleNoBodyAPIRequestWithResponse(
reqCtx, c, ctx, action, 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) return c.service.GetPigBatch(reqCtx, primaryID)
}, },
"获取成功", "获取成功",
@@ -95,7 +95,7 @@ func (c *PigBatchController) UpdatePigBatch(ctx echo.Context) error {
return handleAPIRequestWithResponse( return handleAPIRequestWithResponse(
reqCtx, c, ctx, action, &req, 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) return c.service.UpdatePigBatch(reqCtx, primaryID, req)
}, },
"更新成功", "更新成功",
@@ -119,7 +119,7 @@ func (c *PigBatchController) DeletePigBatch(ctx echo.Context) error {
return handleNoBodyAPIRequest( return handleNoBodyAPIRequest(
reqCtx, c, ctx, action, 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) return c.service.DeletePigBatch(reqCtx, primaryID)
}, },
"删除成功", "删除成功",
@@ -144,7 +144,7 @@ func (c *PigBatchController) ListPigBatches(ctx echo.Context) error {
return handleQueryAPIRequestWithResponse( return handleQueryAPIRequestWithResponse(
reqCtx, c, ctx, action, &query, 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) return c.service.ListPigBatches(reqCtx, query.IsActive)
}, },
"获取成功", "获取成功",
@@ -170,7 +170,7 @@ func (c *PigBatchController) AssignEmptyPensToBatch(ctx echo.Context) error {
return handleAPIRequest( return handleAPIRequest(
reqCtx, c, ctx, action, &req, 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) return c.service.AssignEmptyPensToBatch(reqCtx, primaryID, req.PenIDs, operatorID)
}, },
"分配成功", "分配成功",
@@ -197,18 +197,18 @@ func (c *PigBatchController) ReclassifyPenToNewBatch(ctx echo.Context) error {
return handleAPIRequest( return handleAPIRequest(
reqCtx, c, ctx, action, &req, 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 // primaryID 在这里是 fromBatchID
return c.service.ReclassifyPenToNewBatch(reqCtx, primaryID, req.ToBatchID, req.PenID, operatorID, req.Remarks) 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") idParam := ctx.Param("fromBatchID")
parsedID, err := strconv.ParseUint(idParam, 10, 32) parsedID, err := strconv.ParseUint(idParam, 10, 32)
if err != nil { if err != nil {
return 0, err 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( return handleNoBodyAPIRequest(
reqCtx, c, ctx, action, reqCtx, c, ctx, action,
func(ctx echo.Context, operatorID uint, primaryID uint) error { func(ctx echo.Context, operatorID uint32, primaryID uint32) error {
// primaryID 在这里是 batchID // primaryID 在这里是 batchID
penIDParam := ctx.Param("penID") penIDParam := ctx.Param("penID")
parsedPenID, err := strconv.ParseUint(penIDParam, 10, 32) parsedPenID, err := strconv.ParseUint(penIDParam, 10, 32)
if err != nil { if err != nil {
return err // 返回错误,因为 penID 格式无效 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") idParam := ctx.Param("batchID")
parsedID, err := strconv.ParseUint(idParam, 10, 32) parsedID, err := strconv.ParseUint(idParam, 10, 32)
if err != nil { if err != nil {
return 0, err 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( return handleAPIRequest(
reqCtx, c, ctx, action, &req, 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) return c.service.MovePigsIntoPen(reqCtx, primaryID, req.ToPenID, req.Quantity, operatorID, req.Remarks)
}, },
"移入成功", "移入成功",

View File

@@ -26,7 +26,7 @@ func (c *PigBatchController) RecordSickPigs(ctx echo.Context) error {
return handleAPIRequest( return handleAPIRequest(
reqCtx, c, ctx, action, &req, 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) 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( return handleAPIRequest(
reqCtx, c, ctx, action, &req, 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) 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( return handleAPIRequest(
reqCtx, c, ctx, action, &req, 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) 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( return handleAPIRequest(
reqCtx, c, ctx, action, &req, 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) 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( return handleAPIRequest(
reqCtx, c, ctx, action, &req, 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) 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( return handleAPIRequest(
reqCtx, c, ctx, action, &req, 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) return c.service.RecordCull(reqCtx, operatorID, primaryID, req.PenID, req.Quantity, req.HappenedAt, req.Remarks)
}, },
"记录成功", "记录成功",

View File

@@ -25,7 +25,7 @@ func (c *PigBatchController) SellPigs(ctx echo.Context) error {
return handleAPIRequest( return handleAPIRequest(
reqCtx, c, ctx, action, &req, 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) 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( return handleAPIRequest(
reqCtx, c, ctx, action, &req, 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) return c.service.BuyPigs(reqCtx, primaryID, req.PenID, req.Quantity, req.UnitPrice, req.TotalPrice, req.TraderName, req.TradeDate, req.Remarks, operatorID)
}, },
"买猪成功", "买猪成功",

View File

@@ -28,18 +28,18 @@ func (c *PigBatchController) TransferPigsAcrossBatches(ctx echo.Context) error {
return handleAPIRequest( return handleAPIRequest(
reqCtx, c, ctx, action, &req, 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 // primaryID 在这里是 sourceBatchID
return c.service.TransferPigsAcrossBatches(reqCtx, primaryID, req.DestBatchID, req.FromPenID, req.ToPenID, req.Quantity, operatorID, req.Remarks) 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") idParam := ctx.Param("sourceBatchID")
parsedID, err := strconv.ParseUint(idParam, 10, 32) parsedID, err := strconv.ParseUint(idParam, 10, 32)
if err != nil { if err != nil {
return 0, err 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( return handleAPIRequest(
reqCtx, c, ctx, action, &req, 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 // primaryID 在这里是 batchID
return c.service.TransferPigsWithinBatch(reqCtx, primaryID, req.FromPenID, req.ToPenID, req.Quantity, operatorID, req.Remarks) return c.service.TransferPigsWithinBatch(reqCtx, primaryID, req.FromPenID, req.ToPenID, req.Quantity, operatorID, req.Remarks)
}, },

View File

@@ -76,7 +76,7 @@ func (c *PigFarmController) GetPigHouse(ctx echo.Context) error {
return controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, "无效的ID格式", action, "ID格式错误", ctx.Param("id")) 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 err != nil {
if errors.Is(err, service.ErrHouseNotFound) { if errors.Is(err, service.ErrHouseNotFound) {
return controller.SendErrorWithAudit(ctx, controller.CodeNotFound, "猪舍不存在", action, "猪舍不存在", id) 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) 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 err != nil {
if errors.Is(err, service.ErrHouseNotFound) { if errors.Is(err, service.ErrHouseNotFound) {
return controller.SendErrorWithAudit(ctx, controller.CodeNotFound, "猪舍不存在", action, "猪舍不存在", id) 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")) 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) { if errors.Is(err, service.ErrHouseNotFound) {
return controller.SendErrorWithAudit(ctx, controller.CodeNotFound, "猪舍不存在", action, "猪舍不存在", id) 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")) 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 err != nil {
if errors.Is(err, service.ErrPenNotFound) { if errors.Is(err, service.ErrPenNotFound) {
return controller.SendErrorWithAudit(ctx, controller.CodeNotFound, "猪栏不存在", action, "猪栏不存在", id) 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) 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 err != nil {
if errors.Is(err, service.ErrPenNotFound) { if errors.Is(err, service.ErrPenNotFound) {
return controller.SendErrorWithAudit(ctx, controller.CodeNotFound, "猪栏不存在", action, "猪栏不存在", id) 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")) 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) { if errors.Is(err, service.ErrPenNotFound) {
return controller.SendErrorWithAudit(ctx, controller.CodeNotFound, "猪栏不存在", action, "猪栏不存在", id) 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) 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 err != nil {
if errors.Is(err, service.ErrPenNotFound) { if errors.Is(err, service.ErrPenNotFound) {
return controller.SendErrorWithAudit(ctx, controller.CodeNotFound, err.Error(), action, err.Error(), id) return controller.SendErrorWithAudit(ctx, controller.CodeNotFound, err.Error(), action, err.Error(), id)

View File

@@ -81,14 +81,14 @@ func (c *Controller) GetPlan(ctx echo.Context) error {
const actionType = "获取计划详情" const actionType = "获取计划详情"
// 1. 从 URL 路径中获取 ID // 1. 从 URL 路径中获取 ID
idStr := ctx.Param("id") idStr := ctx.Param("id")
id, err := strconv.ParseUint(idStr, 10, 32) id, err := strconv.ParseUint(idStr, 10, 64)
if err != nil { if err != nil {
logger.Errorf("%s: 计划ID格式错误: %v, ID: %s", actionType, err, idStr) logger.Errorf("%s: 计划ID格式错误: %v, ID: %s", actionType, err, idStr)
return controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, "无效的计划ID格式", actionType, "计划ID格式错误", 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 { if err != nil {
logger.Errorf("%s: 服务层获取计划详情失败: %v, ID: %d", actionType, err, id) logger.Errorf("%s: 服务层获取计划详情失败: %v, ID: %d", actionType, err, id)
if errors.Is(err, plan.ErrPlanNotFound) { // 修改为 plan.ErrPlanNotFound if errors.Is(err, plan.ErrPlanNotFound) { // 修改为 plan.ErrPlanNotFound
@@ -147,7 +147,7 @@ func (c *Controller) UpdatePlan(ctx echo.Context) error {
const actionType = "更新计划" const actionType = "更新计划"
// 1. 从 URL 路径中获取 ID // 1. 从 URL 路径中获取 ID
idStr := ctx.Param("id") idStr := ctx.Param("id")
id, err := strconv.ParseUint(idStr, 10, 32) id, err := strconv.ParseUint(idStr, 10, 64)
if err != nil { if err != nil {
logger.Errorf("%s: 计划ID格式错误: %v, ID: %s", actionType, err, idStr) logger.Errorf("%s: 计划ID格式错误: %v, ID: %s", actionType, err, idStr)
return controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, "无效的计划ID格式", actionType, "计划ID格式错误", 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 { if err != nil {
logger.Errorf("%s: 服务层更新计划失败: %v, ID: %d", actionType, err, id) logger.Errorf("%s: 服务层更新计划失败: %v, ID: %d", actionType, err, id)
if errors.Is(err, plan.ErrPlanNotFound) { // 修改为 plan.ErrPlanNotFound if errors.Is(err, plan.ErrPlanNotFound) { // 修改为 plan.ErrPlanNotFound
@@ -191,14 +191,14 @@ func (c *Controller) DeletePlan(ctx echo.Context) error {
const actionType = "删除计划" const actionType = "删除计划"
// 1. 从 URL 路径中获取 ID // 1. 从 URL 路径中获取 ID
idStr := ctx.Param("id") idStr := ctx.Param("id")
id, err := strconv.ParseUint(idStr, 10, 32) id, err := strconv.ParseUint(idStr, 10, 64)
if err != nil { if err != nil {
logger.Errorf("%s: 计划ID格式错误: %v, ID: %s", actionType, err, idStr) logger.Errorf("%s: 计划ID格式错误: %v, ID: %s", actionType, err, idStr)
return controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, "无效的计划ID格式", actionType, "计划ID格式错误", 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 { if err != nil {
logger.Errorf("%s: 服务层删除计划失败: %v, ID: %d", actionType, err, id) logger.Errorf("%s: 服务层删除计划失败: %v, ID: %d", actionType, err, id)
if errors.Is(err, plan.ErrPlanNotFound) { // 修改为 plan.ErrPlanNotFound if errors.Is(err, plan.ErrPlanNotFound) { // 修改为 plan.ErrPlanNotFound
@@ -228,14 +228,14 @@ func (c *Controller) StartPlan(ctx echo.Context) error {
const actionType = "启动计划" const actionType = "启动计划"
// 1. 从 URL 路径中获取 ID // 1. 从 URL 路径中获取 ID
idStr := ctx.Param("id") idStr := ctx.Param("id")
id, err := strconv.ParseUint(idStr, 10, 32) id, err := strconv.ParseUint(idStr, 10, 64)
if err != nil { if err != nil {
logger.Errorf("%s: 计划ID格式错误: %v, ID: %s", actionType, err, idStr) logger.Errorf("%s: 计划ID格式错误: %v, ID: %s", actionType, err, idStr)
return controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, "无效的计划ID格式", actionType, "计划ID格式错误", 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 { if err != nil {
logger.Errorf("%s: 服务层启动计划失败: %v, ID: %d", actionType, err, id) logger.Errorf("%s: 服务层启动计划失败: %v, ID: %d", actionType, err, id)
if errors.Is(err, plan.ErrPlanNotFound) { // 修改为 plan.ErrPlanNotFound if errors.Is(err, plan.ErrPlanNotFound) { // 修改为 plan.ErrPlanNotFound
@@ -267,14 +267,14 @@ func (c *Controller) StopPlan(ctx echo.Context) error {
const actionType = "停止计划" const actionType = "停止计划"
// 1. 从 URL 路径中获取 ID // 1. 从 URL 路径中获取 ID
idStr := ctx.Param("id") idStr := ctx.Param("id")
id, err := strconv.ParseUint(idStr, 10, 32) id, err := strconv.ParseUint(idStr, 10, 64)
if err != nil { if err != nil {
logger.Errorf("%s: 计划ID格式错误: %v, ID: %s", actionType, err, idStr) logger.Errorf("%s: 计划ID格式错误: %v, ID: %s", actionType, err, idStr)
return controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, "无效的计划ID格式", actionType, "计划ID格式错误", 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 { if err != nil {
logger.Errorf("%s: 服务层停止计划失败: %v, ID: %d", actionType, err, id) logger.Errorf("%s: 服务层停止计划失败: %v, ID: %d", actionType, err, id)
if errors.Is(err, plan.ErrPlanNotFound) { // 修改为 plan.ErrPlanNotFound if errors.Is(err, plan.ErrPlanNotFound) { // 修改为 plan.ErrPlanNotFound

View File

@@ -101,7 +101,7 @@ func (c *Controller) SendTestNotification(ctx echo.Context) error {
const actionType = "发送测试通知" const actionType = "发送测试通知"
// 1. 从 URL 中获取用户 ID // 1. 从 URL 中获取用户 ID
userID, err := strconv.ParseUint(ctx.Param("id"), 10, 32) userID, err := strconv.ParseUint(ctx.Param("id"), 10, 64)
if err != nil { if err != nil {
logger.Errorf("%s: 无效的用户ID格式: %v", actionType, err) logger.Errorf("%s: 无效的用户ID格式: %v", actionType, err)
return controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, "无效的用户ID格式", actionType, "无效的用户ID格式", ctx.Param("id")) 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. 调用服务层 // 3. 调用服务层
err = c.userService.SendTestNotification(reqCtx, uint(userID), &req) err = c.userService.SendTestNotification(reqCtx, uint32(userID), &req)
if err != nil { if err != nil {
logger.Errorf("%s: 服务层调用失败: %v", actionType, err) logger.Errorf("%s: 服务层调用失败: %v", actionType, err)
return controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "发送测试消息失败: "+err.Error(), actionType, "服务层调用失败", map[string]interface{}{"userID": userID, "type": req.Type}) return controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "发送测试消息失败: "+err.Error(), actionType, "服务层调用失败", map[string]interface{}{"userID": userID, "type": req.Type})

View File

@@ -8,7 +8,7 @@ import (
// SnoozeAlarmRequest 定义了忽略告警的请求体 // SnoozeAlarmRequest 定义了忽略告警的请求体
type SnoozeAlarmRequest struct { type SnoozeAlarmRequest struct {
DurationMinutes uint `json:"duration_minutes" validate:"required,min=1"` // 忽略时长,单位分钟 DurationMinutes uint32 `json:"duration_minutes" validate:"required,min=1"` // 忽略时长,单位分钟
} }
// ListActiveAlarmRequest 定义了获取活跃告警列表的请求参数 // ListActiveAlarmRequest 定义了获取活跃告警列表的请求参数
@@ -16,7 +16,7 @@ type ListActiveAlarmRequest struct {
Page int `json:"page" query:"page"` Page int `json:"page" query:"page"`
PageSize int `json:"page_size" query:"page_size"` PageSize int `json:"page_size" query:"page_size"`
SourceType *models.AlarmSourceType `json:"source_type" query:"source_type"` // 按告警来源类型过滤 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"` // 按告警严重性等级过滤 Level *models.SeverityLevel `json:"level" query:"level"` // 按告警严重性等级过滤
IsIgnored *bool `json:"is_ignored" query:"is_ignored"` // 按是否被忽略过滤 IsIgnored *bool `json:"is_ignored" query:"is_ignored"` // 按是否被忽略过滤
TriggerTime *time.Time `json:"trigger_time" query:"trigger_time"` // 告警触发时间范围 - 开始时间 TriggerTime *time.Time `json:"trigger_time" query:"trigger_time"` // 告警触发时间范围 - 开始时间
@@ -26,11 +26,11 @@ type ListActiveAlarmRequest struct {
// ActiveAlarmDTO 是用于API响应的活跃告警结构 // ActiveAlarmDTO 是用于API响应的活跃告警结构
type ActiveAlarmDTO struct { type ActiveAlarmDTO struct {
ID uint `json:"id"` ID uint32 `json:"id"`
CreatedAt time.Time `json:"created_at"` CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"` UpdatedAt time.Time `json:"updated_at"`
SourceType models.AlarmSourceType `json:"source_type"` SourceType models.AlarmSourceType `json:"source_type"`
SourceID uint `json:"source_id"` SourceID uint32 `json:"source_id"`
AlarmCode models.AlarmCode `json:"alarm_code"` AlarmCode models.AlarmCode `json:"alarm_code"`
AlarmSummary string `json:"alarm_summary"` AlarmSummary string `json:"alarm_summary"`
Level models.SeverityLevel `json:"level"` Level models.SeverityLevel `json:"level"`
@@ -52,7 +52,7 @@ type ListHistoricalAlarmRequest struct {
Page int `json:"page" query:"page"` Page int `json:"page" query:"page"`
PageSize int `json:"page_size" query:"page_size"` PageSize int `json:"page_size" query:"page_size"`
SourceType *models.AlarmSourceType `json:"source_type" query:"source_type"` // 按告警来源类型过滤 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"` // 按告警严重性等级过滤 Level *models.SeverityLevel `json:"level" query:"level"` // 按告警严重性等级过滤
TriggerTimeStart *time.Time `json:"trigger_time_start" query:"trigger_time_start"` // 告警触发时间范围 - 开始时间 TriggerTimeStart *time.Time `json:"trigger_time_start" query:"trigger_time_start"` // 告警触发时间范围 - 开始时间
TriggerTimeEnd *time.Time `json:"trigger_time_end" query:"trigger_time_end"` // 告警触发时间范围 - 结束时间 TriggerTimeEnd *time.Time `json:"trigger_time_end" query:"trigger_time_end"` // 告警触发时间范围 - 结束时间
@@ -63,9 +63,9 @@ type ListHistoricalAlarmRequest struct {
// HistoricalAlarmDTO 是用于API响应的历史告警结构 // HistoricalAlarmDTO 是用于API响应的历史告警结构
type HistoricalAlarmDTO struct { type HistoricalAlarmDTO struct {
ID uint `json:"id"` ID uint32 `json:"id"`
SourceType models.AlarmSourceType `json:"source_type"` SourceType models.AlarmSourceType `json:"source_type"`
SourceID uint `json:"source_id"` SourceID uint32 `json:"source_id"`
AlarmCode models.AlarmCode `json:"alarm_code"` AlarmCode models.AlarmCode `json:"alarm_code"`
AlarmSummary string `json:"alarm_summary"` AlarmSummary string `json:"alarm_summary"`
Level models.SeverityLevel `json:"level"` Level models.SeverityLevel `json:"level"`
@@ -73,7 +73,7 @@ type HistoricalAlarmDTO struct {
TriggerTime time.Time `json:"trigger_time"` TriggerTime time.Time `json:"trigger_time"`
ResolveTime time.Time `json:"resolve_time"` ResolveTime time.Time `json:"resolve_time"`
ResolveMethod string `json:"resolve_method"` ResolveMethod string `json:"resolve_method"`
ResolvedBy *uint `json:"resolved_by"` ResolvedBy *uint32 `json:"resolved_by"`
} }
// ListHistoricalAlarmResponse 是获取历史告警列表的响应结构 // ListHistoricalAlarmResponse 是获取历史告警列表的响应结构
@@ -84,7 +84,7 @@ type ListHistoricalAlarmResponse struct {
// CreateDeviceThresholdAlarmDTO 创建设备阈值告警的请求DTO // CreateDeviceThresholdAlarmDTO 创建设备阈值告警的请求DTO
type CreateDeviceThresholdAlarmDTO struct { 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"` // 传感器类型 SensorType models.SensorType `json:"sensor_type" binding:"required"` // 传感器类型
Thresholds float32 `json:"thresholds" binding:"required"` // 阈值 Thresholds float32 `json:"thresholds" binding:"required"` // 阈值
Operator models.Operator `json:"operator" binding:"required"` // 操作符 (使用string类型与前端交互更通用) Operator models.Operator `json:"operator" binding:"required"` // 操作符 (使用string类型与前端交互更通用)
@@ -100,7 +100,7 @@ type UpdateDeviceThresholdAlarmDTO struct {
// CreateAreaThresholdAlarmDTO 创建区域阈值告警的请求DTO // CreateAreaThresholdAlarmDTO 创建区域阈值告警的请求DTO
type CreateAreaThresholdAlarmDTO struct { 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"` // 传感器类型 SensorType models.SensorType `json:"sensor_type" binding:"required"` // 传感器类型
Thresholds float32 `json:"thresholds" binding:"required"` // 阈值 Thresholds float32 `json:"thresholds" binding:"required"` // 阈值
Operator models.Operator `json:"operator" binding:"required"` // 操作符 Operator models.Operator `json:"operator" binding:"required"` // 操作符
@@ -122,7 +122,7 @@ type DeleteDeviceThresholdAlarmDTO struct {
// AreaThresholdAlarmDTO 用于表示一个区域阈值告警任务的详细信息 // AreaThresholdAlarmDTO 用于表示一个区域阈值告警任务的详细信息
type AreaThresholdAlarmDTO struct { type AreaThresholdAlarmDTO struct {
ID int `json:"id"` ID int `json:"id"`
AreaControllerID uint `json:"area_controller_id"` AreaControllerID uint32 `json:"area_controller_id"`
SensorType models.SensorType `json:"sensor_type"` SensorType models.SensorType `json:"sensor_type"`
Thresholds float32 `json:"thresholds"` Thresholds float32 `json:"thresholds"`
Operator models.Operator `json:"operator"` Operator models.Operator `json:"operator"`
@@ -132,7 +132,7 @@ type AreaThresholdAlarmDTO struct {
// DeviceThresholdAlarmDTO 用于表示一个设备阈值告警任务的详细信息 // DeviceThresholdAlarmDTO 用于表示一个设备阈值告警任务的详细信息
type DeviceThresholdAlarmDTO struct { type DeviceThresholdAlarmDTO struct {
ID int `json:"id"` ID int `json:"id"`
DeviceID uint `json:"device_id"` DeviceID uint32 `json:"device_id"`
SensorType models.SensorType `json:"sensor_type"` SensorType models.SensorType `json:"sensor_type"`
Thresholds float32 `json:"thresholds"` Thresholds float32 `json:"thresholds"`
Operator models.Operator `json:"operator"` Operator models.Operator `json:"operator"`

View File

@@ -5,8 +5,8 @@ import "git.huangwc.com/pig/pig-farm-controller/internal/infra/models"
// CreateDeviceRequest 定义了创建设备时需要传入的参数 // CreateDeviceRequest 定义了创建设备时需要传入的参数
type CreateDeviceRequest struct { type CreateDeviceRequest struct {
Name string `json:"name" validate:"required"` Name string `json:"name" validate:"required"`
DeviceTemplateID uint `json:"device_template_id" validate:"required"` DeviceTemplateID uint32 `json:"device_template_id" validate:"required"`
AreaControllerID uint `json:"area_controller_id" validate:"required"` AreaControllerID uint32 `json:"area_controller_id" validate:"required"`
Location string `json:"location,omitempty" validate:"omitempty"` Location string `json:"location,omitempty" validate:"omitempty"`
Properties map[string]interface{} `json:"properties,omitempty" validate:"omitempty"` Properties map[string]interface{} `json:"properties,omitempty" validate:"omitempty"`
} }
@@ -14,8 +14,8 @@ type CreateDeviceRequest struct {
// UpdateDeviceRequest 定义了更新设备时需要传入的参数 // UpdateDeviceRequest 定义了更新设备时需要传入的参数
type UpdateDeviceRequest struct { type UpdateDeviceRequest struct {
Name string `json:"name" validate:"required"` Name string `json:"name" validate:"required"`
DeviceTemplateID uint `json:"device_template_id" validate:"required"` DeviceTemplateID uint32 `json:"device_template_id" validate:"required"`
AreaControllerID uint `json:"area_controller_id" validate:"required"` AreaControllerID uint32 `json:"area_controller_id" validate:"required"`
Location string `json:"location,omitempty" validate:"omitempty"` Location string `json:"location,omitempty" validate:"omitempty"`
Properties map[string]interface{} `json:"properties,omitempty" validate:"omitempty"` Properties map[string]interface{} `json:"properties,omitempty" validate:"omitempty"`
} }
@@ -64,11 +64,11 @@ type UpdateDeviceTemplateRequest struct {
// DeviceResponse 定义了返回给客户端的单个设备信息的结构 // DeviceResponse 定义了返回给客户端的单个设备信息的结构
type DeviceResponse struct { type DeviceResponse struct {
ID uint `json:"id"` ID uint32 `json:"id"`
Name string `json:"name"` Name string `json:"name"`
DeviceTemplateID uint `json:"device_template_id"` DeviceTemplateID uint32 `json:"device_template_id"`
DeviceTemplateName string `json:"device_template_name"` DeviceTemplateName string `json:"device_template_name"`
AreaControllerID uint `json:"area_controller_id"` AreaControllerID uint32 `json:"area_controller_id"`
AreaControllerName string `json:"area_controller_name"` AreaControllerName string `json:"area_controller_name"`
Location string `json:"location"` Location string `json:"location"`
Properties map[string]interface{} `json:"properties"` Properties map[string]interface{} `json:"properties"`
@@ -78,7 +78,7 @@ type DeviceResponse struct {
// AreaControllerResponse 定义了返回给客户端的单个区域主控信息的结构 // AreaControllerResponse 定义了返回给客户端的单个区域主控信息的结构
type AreaControllerResponse struct { type AreaControllerResponse struct {
ID uint `json:"id"` ID uint32 `json:"id"`
Name string `json:"name"` Name string `json:"name"`
NetworkID string `json:"network_id"` NetworkID string `json:"network_id"`
Location string `json:"location"` Location string `json:"location"`
@@ -90,7 +90,7 @@ type AreaControllerResponse struct {
// DeviceTemplateResponse 定义了返回给客户端的单个设备模板信息的结构 // DeviceTemplateResponse 定义了返回给客户端的单个设备模板信息的结构
type DeviceTemplateResponse struct { type DeviceTemplateResponse struct {
ID uint `json:"id"` ID uint32 `json:"id"`
Name string `json:"name"` Name string `json:"name"`
Manufacturer string `json:"manufacturer"` Manufacturer string `json:"manufacturer"`
Description string `json:"description"` Description string `json:"description"`

View File

@@ -54,7 +54,7 @@ func NewListDeviceCommandLogResponse(data []models.DeviceCommandLog, total int64
// NewListPlanExecutionLogResponse 从模型数据创建列表响应 DTO // NewListPlanExecutionLogResponse 从模型数据创建列表响应 DTO
func NewListPlanExecutionLogResponse(planLogs []models.PlanExecutionLog, plans []models.Plan, total int64, page, pageSize int) *ListPlanExecutionLogResponse { 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 { for _, plan := range plans {
planId2Name[plan.ID] = string(plan.Name) planId2Name[plan.ID] = string(plan.Name)
} }
@@ -95,7 +95,7 @@ func NewListTaskExecutionLogResponse(data []models.TaskExecutionLog, total int64
PlanExecutionLogID: item.PlanExecutionLogID, PlanExecutionLogID: item.PlanExecutionLogID,
TaskID: item.TaskID, TaskID: item.TaskID,
Task: TaskDTO{ Task: TaskDTO{
ID: uint(item.Task.ID), ID: uint32(item.Task.ID),
Name: item.Task.Name, Name: item.Task.Name,
Description: item.Task.Description, 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 { func NewListPigTransferLogResponse(data []models.PigTransferLog, total int64, page, pageSize int) *ListPigTransferLogResponse {
dtos := make([]PigTransferLogDTO, len(data)) dtos := make([]PigTransferLogDTO, len(data))
for i, item := range data { for i, item := range data {
// 注意PigTransferLog 的 ID, CreatedAt, UpdatedAt 字段是 gorm.Model 嵌入的 // 注意PigTransferLog 的 ID, CreatedAt, UpdatedAt 字段是 Model 嵌入的
dtos[i] = PigTransferLogDTO{ dtos[i] = PigTransferLogDTO{
ID: item.ID, ID: item.ID,
CreatedAt: item.CreatedAt, CreatedAt: item.CreatedAt,

View File

@@ -13,7 +13,7 @@ import (
type ListSensorDataRequest struct { type ListSensorDataRequest struct {
Page int `json:"page" query:"page"` Page int `json:"page" query:"page"`
PageSize int `json:"page_size" query:"page_size"` 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"` SensorType *string `json:"sensor_type" query:"sensor_type"`
StartTime *time.Time `json:"start_time" query:"start_time"` StartTime *time.Time `json:"start_time" query:"start_time"`
EndTime *time.Time `json:"end_time" query:"end_time"` EndTime *time.Time `json:"end_time" query:"end_time"`
@@ -23,8 +23,8 @@ type ListSensorDataRequest struct {
// SensorDataDTO 是用于API响应的传感器数据结构 // SensorDataDTO 是用于API响应的传感器数据结构
type SensorDataDTO struct { type SensorDataDTO struct {
Time time.Time `json:"time"` Time time.Time `json:"time"`
DeviceID uint `json:"device_id"` DeviceID uint32 `json:"device_id"`
AreaControllerID uint `json:"area_controller_id"` AreaControllerID uint32 `json:"area_controller_id"`
SensorType models.SensorType `json:"sensor_type"` SensorType models.SensorType `json:"sensor_type"`
Data json.RawMessage `json:"data"` Data json.RawMessage `json:"data"`
} }
@@ -41,7 +41,7 @@ type ListSensorDataResponse struct {
type ListDeviceCommandLogRequest struct { type ListDeviceCommandLogRequest struct {
Page int `json:"page" query:"page"` Page int `json:"page" query:"page"`
PageSize int `json:"page_size" query:"page_size"` 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"` ReceivedSuccess *bool `json:"received_success" query:"received_success"`
StartTime *time.Time `json:"start_time" query:"start_time"` StartTime *time.Time `json:"start_time" query:"start_time"`
EndTime *time.Time `json:"end_time" query:"end_time"` EndTime *time.Time `json:"end_time" query:"end_time"`
@@ -51,7 +51,7 @@ type ListDeviceCommandLogRequest struct {
// DeviceCommandLogDTO 是用于API响应的设备命令日志结构 // DeviceCommandLogDTO 是用于API响应的设备命令日志结构
type DeviceCommandLogDTO struct { type DeviceCommandLogDTO struct {
MessageID string `json:"message_id"` MessageID string `json:"message_id"`
DeviceID uint `json:"device_id"` DeviceID uint32 `json:"device_id"`
SentAt time.Time `json:"sent_at"` SentAt time.Time `json:"sent_at"`
AcknowledgedAt *time.Time `json:"acknowledged_at"` AcknowledgedAt *time.Time `json:"acknowledged_at"`
ReceivedSuccess bool `json:"received_success"` ReceivedSuccess bool `json:"received_success"`
@@ -69,7 +69,7 @@ type ListDeviceCommandLogResponse struct {
type ListPlanExecutionLogRequest struct { type ListPlanExecutionLogRequest struct {
Page int `json:"page" query:"page"` Page int `json:"page" query:"page"`
PageSize int `json:"page_size" query:"page_size"` 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"` Status *string `json:"status" query:"status"`
StartTime *time.Time `json:"start_time" query:"start_time"` StartTime *time.Time `json:"start_time" query:"start_time"`
EndTime *time.Time `json:"end_time" query:"end_time"` EndTime *time.Time `json:"end_time" query:"end_time"`
@@ -78,10 +78,10 @@ type ListPlanExecutionLogRequest struct {
// PlanExecutionLogDTO 是用于API响应的计划执行日志结构 // PlanExecutionLogDTO 是用于API响应的计划执行日志结构
type PlanExecutionLogDTO struct { type PlanExecutionLogDTO struct {
ID uint `json:"id"` ID uint32 `json:"id"`
CreatedAt time.Time `json:"created_at"` CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"` UpdatedAt time.Time `json:"updated_at"`
PlanID uint `json:"plan_id"` PlanID uint32 `json:"plan_id"`
PlanName string `json:"plan_name"` PlanName string `json:"plan_name"`
Status models.ExecutionStatus `json:"status"` Status models.ExecutionStatus `json:"status"`
StartedAt time.Time `json:"started_at"` StartedAt time.Time `json:"started_at"`
@@ -101,7 +101,7 @@ type ListPlanExecutionLogResponse struct {
type ListTaskExecutionLogRequest struct { type ListTaskExecutionLogRequest struct {
Page int `json:"page" query:"page"` Page int `json:"page" query:"page"`
PageSize int `json:"page_size" query:"page_size"` 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"` TaskID *int `json:"task_id" query:"task_id"`
Status *string `json:"status" query:"status"` Status *string `json:"status" query:"status"`
StartTime *time.Time `json:"start_time" query:"start_time"` StartTime *time.Time `json:"start_time" query:"start_time"`
@@ -111,17 +111,17 @@ type ListTaskExecutionLogRequest struct {
// TaskDTO 是用于API响应的简化版任务结构 // TaskDTO 是用于API响应的简化版任务结构
type TaskDTO struct { type TaskDTO struct {
ID uint `json:"id"` ID uint32 `json:"id"`
Name string `json:"name"` Name string `json:"name"`
Description string `json:"description"` Description string `json:"description"`
} }
// TaskExecutionLogDTO 是用于API响应的任务执行日志结构 // TaskExecutionLogDTO 是用于API响应的任务执行日志结构
type TaskExecutionLogDTO struct { type TaskExecutionLogDTO struct {
ID uint `json:"id"` ID uint32 `json:"id"`
CreatedAt time.Time `json:"created_at"` CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_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"` TaskID int `json:"task_id"`
Task TaskDTO `json:"task"` // 嵌套的任务信息 Task TaskDTO `json:"task"` // 嵌套的任务信息
Status models.ExecutionStatus `json:"status"` Status models.ExecutionStatus `json:"status"`
@@ -142,7 +142,7 @@ type ListTaskExecutionLogResponse struct {
type ListPendingCollectionRequest struct { type ListPendingCollectionRequest struct {
Page int `json:"page" query:"page"` Page int `json:"page" query:"page"`
PageSize int `json:"page_size" query:"page_size"` 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"` Status *string `json:"status" query:"status"`
StartTime *time.Time `json:"start_time" query:"start_time"` StartTime *time.Time `json:"start_time" query:"start_time"`
EndTime *time.Time `json:"end_time" query:"end_time"` EndTime *time.Time `json:"end_time" query:"end_time"`
@@ -152,7 +152,7 @@ type ListPendingCollectionRequest struct {
// PendingCollectionDTO 是用于API响应的待采集请求结构 // PendingCollectionDTO 是用于API响应的待采集请求结构
type PendingCollectionDTO struct { type PendingCollectionDTO struct {
CorrelationID string `json:"correlation_id"` CorrelationID string `json:"correlation_id"`
DeviceID uint `json:"device_id"` DeviceID uint32 `json:"device_id"`
CommandMetadata models.UintArray `json:"command_metadata"` CommandMetadata models.UintArray `json:"command_metadata"`
Status models.PendingCollectionStatus `json:"status"` Status models.PendingCollectionStatus `json:"status"`
FulfilledAt *time.Time `json:"fulfilled_at"` FulfilledAt *time.Time `json:"fulfilled_at"`
@@ -171,7 +171,7 @@ type ListPendingCollectionResponse struct {
type ListUserActionLogRequest struct { type ListUserActionLogRequest struct {
Page int `json:"page" query:"page"` Page int `json:"page" query:"page"`
PageSize int `json:"page_size" query:"page_size"` 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"` Username *string `json:"username" query:"username"`
ActionType *string `json:"action_type" query:"action_type"` ActionType *string `json:"action_type" query:"action_type"`
Status *string `json:"status" query:"status"` Status *string `json:"status" query:"status"`
@@ -182,9 +182,9 @@ type ListUserActionLogRequest struct {
// UserActionLogDTO 是用于API响应的用户操作日志结构 // UserActionLogDTO 是用于API响应的用户操作日志结构
type UserActionLogDTO struct { type UserActionLogDTO struct {
ID uint `json:"id"` ID uint32 `json:"id"`
Time time.Time `json:"time"` Time time.Time `json:"time"`
UserID uint `json:"user_id"` UserID uint32 `json:"user_id"`
Username string `json:"username"` Username string `json:"username"`
SourceIP string `json:"source_ip"` SourceIP string `json:"source_ip"`
ActionType string `json:"action_type"` ActionType string `json:"action_type"`
@@ -208,7 +208,7 @@ type ListUserActionLogResponse struct {
type ListRawMaterialPurchaseRequest struct { type ListRawMaterialPurchaseRequest struct {
Page int `json:"page" query:"page"` Page int `json:"page" query:"page"`
PageSize int `json:"page_size" query:"page_size"` 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"` Supplier *string `json:"supplier" query:"supplier"`
StartTime *time.Time `json:"start_time" query:"start_time"` StartTime *time.Time `json:"start_time" query:"start_time"`
EndTime *time.Time `json:"end_time" query:"end_time"` EndTime *time.Time `json:"end_time" query:"end_time"`
@@ -217,14 +217,14 @@ type ListRawMaterialPurchaseRequest struct {
// RawMaterialDTO 是用于API响应的简化版原料结构 // RawMaterialDTO 是用于API响应的简化版原料结构
type RawMaterialDTO struct { type RawMaterialDTO struct {
ID uint `json:"id"` ID uint32 `json:"id"`
Name string `json:"name"` Name string `json:"name"`
} }
// RawMaterialPurchaseDTO 是用于API响应的原料采购结构 // RawMaterialPurchaseDTO 是用于API响应的原料采购结构
type RawMaterialPurchaseDTO struct { type RawMaterialPurchaseDTO struct {
ID uint `json:"id"` ID uint32 `json:"id"`
RawMaterialID uint `json:"raw_material_id"` RawMaterialID uint32 `json:"raw_material_id"`
RawMaterial RawMaterialDTO `json:"raw_material"` RawMaterial RawMaterialDTO `json:"raw_material"`
Supplier string `json:"supplier"` Supplier string `json:"supplier"`
Amount float32 `json:"amount"` Amount float32 `json:"amount"`
@@ -246,9 +246,9 @@ type ListRawMaterialPurchaseResponse struct {
type ListRawMaterialStockLogRequest struct { type ListRawMaterialStockLogRequest struct {
Page int `json:"page" query:"page"` Page int `json:"page" query:"page"`
PageSize int `json:"page_size" query:"page_size"` 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"` 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"` StartTime *time.Time `json:"start_time" query:"start_time"`
EndTime *time.Time `json:"end_time" query:"end_time"` EndTime *time.Time `json:"end_time" query:"end_time"`
OrderBy string `json:"order_by" query:"order_by"` OrderBy string `json:"order_by" query:"order_by"`
@@ -256,11 +256,11 @@ type ListRawMaterialStockLogRequest struct {
// RawMaterialStockLogDTO 是用于API响应的原料库存日志结构 // RawMaterialStockLogDTO 是用于API响应的原料库存日志结构
type RawMaterialStockLogDTO struct { type RawMaterialStockLogDTO struct {
ID uint `json:"id"` ID uint32 `json:"id"`
RawMaterialID uint `json:"raw_material_id"` RawMaterialID uint32 `json:"raw_material_id"`
ChangeAmount float32 `json:"change_amount"` ChangeAmount float32 `json:"change_amount"`
SourceType models.StockLogSourceType `json:"source_type"` SourceType models.StockLogSourceType `json:"source_type"`
SourceID uint `json:"source_id"` SourceID uint32 `json:"source_id"`
HappenedAt time.Time `json:"happened_at"` HappenedAt time.Time `json:"happened_at"`
Remarks string `json:"remarks"` Remarks string `json:"remarks"`
} }
@@ -277,9 +277,9 @@ type ListRawMaterialStockLogResponse struct {
type ListFeedUsageRecordRequest struct { type ListFeedUsageRecordRequest struct {
Page int `json:"page" query:"page"` Page int `json:"page" query:"page"`
PageSize int `json:"page_size" query:"page_size"` PageSize int `json:"page_size" query:"page_size"`
PenID *uint `json:"pen_id" query:"pen_id"` PenID *uint32 `json:"pen_id" query:"pen_id"`
FeedFormulaID *uint `json:"feed_formula_id" query:"feed_formula_id"` FeedFormulaID *uint32 `json:"feed_formula_id" query:"feed_formula_id"`
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"` StartTime *time.Time `json:"start_time" query:"start_time"`
EndTime *time.Time `json:"end_time" query:"end_time"` EndTime *time.Time `json:"end_time" query:"end_time"`
OrderBy string `json:"order_by" query:"order_by"` OrderBy string `json:"order_by" query:"order_by"`
@@ -287,26 +287,26 @@ type ListFeedUsageRecordRequest struct {
// PenDTO 是用于API响应的简化版猪栏结构 // PenDTO 是用于API响应的简化版猪栏结构
type PenDTO struct { type PenDTO struct {
ID uint `json:"id"` ID uint32 `json:"id"`
Name string `json:"name"` Name string `json:"name"`
} }
// FeedFormulaDTO 是用于API响应的简化版饲料配方结构 // FeedFormulaDTO 是用于API响应的简化版饲料配方结构
type FeedFormulaDTO struct { type FeedFormulaDTO struct {
ID uint `json:"id"` ID uint32 `json:"id"`
Name string `json:"name"` Name string `json:"name"`
} }
// FeedUsageRecordDTO 是用于API响应的饲料使用记录结构 // FeedUsageRecordDTO 是用于API响应的饲料使用记录结构
type FeedUsageRecordDTO struct { type FeedUsageRecordDTO struct {
ID uint `json:"id"` ID uint32 `json:"id"`
PenID uint `json:"pen_id"` PenID uint32 `json:"pen_id"`
Pen PenDTO `json:"pen"` Pen PenDTO `json:"pen"`
FeedFormulaID uint `json:"feed_formula_id"` FeedFormulaID uint32 `json:"feed_formula_id"`
FeedFormula FeedFormulaDTO `json:"feed_formula"` FeedFormula FeedFormulaDTO `json:"feed_formula"`
Amount float32 `json:"amount"` Amount float32 `json:"amount"`
RecordedAt time.Time `json:"recorded_at"` RecordedAt time.Time `json:"recorded_at"`
OperatorID uint `json:"operator_id"` OperatorID uint32 `json:"operator_id"`
Remarks string `json:"remarks"` Remarks string `json:"remarks"`
} }
@@ -322,10 +322,10 @@ type ListFeedUsageRecordResponse struct {
type ListMedicationLogRequest struct { type ListMedicationLogRequest struct {
Page int `json:"page" query:"page"` Page int `json:"page" query:"page"`
PageSize int `json:"page_size" query:"page_size"` 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"`
MedicationID *uint `json:"medication_id" query:"medication_id"` MedicationID *uint32 `json:"medication_id" query:"medication_id"`
Reason *string `json:"reason" query:"reason"` 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"` StartTime *time.Time `json:"start_time" query:"start_time"`
EndTime *time.Time `json:"end_time" query:"end_time"` EndTime *time.Time `json:"end_time" query:"end_time"`
OrderBy string `json:"order_by" query:"order_by"` OrderBy string `json:"order_by" query:"order_by"`
@@ -333,21 +333,21 @@ type ListMedicationLogRequest struct {
// MedicationDTO 是用于API响应的简化版药品结构 // MedicationDTO 是用于API响应的简化版药品结构
type MedicationDTO struct { type MedicationDTO struct {
ID uint `json:"id"` ID uint32 `json:"id"`
Name string `json:"name"` Name string `json:"name"`
} }
// MedicationLogDTO 是用于API响应的用药记录结构 // MedicationLogDTO 是用于API响应的用药记录结构
type MedicationLogDTO struct { type MedicationLogDTO struct {
ID uint `json:"id"` ID uint32 `json:"id"`
PigBatchID uint `json:"pig_batch_id"` PigBatchID uint32 `json:"pig_batch_id"`
MedicationID uint `json:"medication_id"` MedicationID uint32 `json:"medication_id"`
Medication MedicationDTO `json:"medication"` Medication MedicationDTO `json:"medication"`
DosageUsed float32 `json:"dosage_used"` DosageUsed float32 `json:"dosage_used"`
TargetCount int `json:"target_count"` TargetCount int `json:"target_count"`
Reason models.MedicationReasonType `json:"reason"` Reason models.MedicationReasonType `json:"reason"`
Description string `json:"description"` Description string `json:"description"`
OperatorID uint `json:"operator_id"` OperatorID uint32 `json:"operator_id"`
HappenedAt time.Time `json:"happened_at"` HappenedAt time.Time `json:"happened_at"`
} }
@@ -363,9 +363,9 @@ type ListMedicationLogResponse struct {
type ListPigBatchLogRequest struct { type ListPigBatchLogRequest struct {
Page int `json:"page" query:"page"` Page int `json:"page" query:"page"`
PageSize int `json:"page_size" query:"page_size"` 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"` 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"` StartTime *time.Time `json:"start_time" query:"start_time"`
EndTime *time.Time `json:"end_time" query:"end_time"` EndTime *time.Time `json:"end_time" query:"end_time"`
OrderBy string `json:"order_by" query:"order_by"` OrderBy string `json:"order_by" query:"order_by"`
@@ -373,16 +373,16 @@ type ListPigBatchLogRequest struct {
// PigBatchLogDTO 是用于API响应的猪批次日志结构 // PigBatchLogDTO 是用于API响应的猪批次日志结构
type PigBatchLogDTO struct { type PigBatchLogDTO struct {
ID uint `json:"id"` ID uint32 `json:"id"`
CreatedAt time.Time `json:"created_at"` CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_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"` ChangeType models.LogChangeType `json:"change_type"`
ChangeCount int `json:"change_count"` ChangeCount int `json:"change_count"`
Reason string `json:"reason"` Reason string `json:"reason"`
BeforeCount int `json:"before_count"` BeforeCount int `json:"before_count"`
AfterCount int `json:"after_count"` AfterCount int `json:"after_count"`
OperatorID uint `json:"operator_id"` OperatorID uint32 `json:"operator_id"`
HappenedAt time.Time `json:"happened_at"` HappenedAt time.Time `json:"happened_at"`
} }
@@ -398,7 +398,7 @@ type ListPigBatchLogResponse struct {
type ListWeighingBatchRequest struct { type ListWeighingBatchRequest struct {
Page int `json:"page" query:"page"` Page int `json:"page" query:"page"`
PageSize int `json:"page_size" query:"page_size"` 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"` StartTime *time.Time `json:"start_time" query:"start_time"`
EndTime *time.Time `json:"end_time" query:"end_time"` EndTime *time.Time `json:"end_time" query:"end_time"`
OrderBy string `json:"order_by" query:"order_by"` OrderBy string `json:"order_by" query:"order_by"`
@@ -406,12 +406,12 @@ type ListWeighingBatchRequest struct {
// WeighingBatchDTO 是用于API响应的批次称重记录结构 // WeighingBatchDTO 是用于API响应的批次称重记录结构
type WeighingBatchDTO struct { type WeighingBatchDTO struct {
ID uint `json:"id"` ID uint32 `json:"id"`
CreatedAt time.Time `json:"created_at"` CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"` UpdatedAt time.Time `json:"updated_at"`
WeighingTime time.Time `json:"weighing_time"` WeighingTime time.Time `json:"weighing_time"`
Description string `json:"description"` Description string `json:"description"`
PigBatchID uint `json:"pig_batch_id"` PigBatchID uint32 `json:"pig_batch_id"`
} }
// ListWeighingBatchResponse 是获取批次称重记录列表的响应结构 // ListWeighingBatchResponse 是获取批次称重记录列表的响应结构
@@ -426,9 +426,9 @@ type ListWeighingBatchResponse struct {
type ListWeighingRecordRequest struct { type ListWeighingRecordRequest struct {
Page int `json:"page" query:"page"` Page int `json:"page" query:"page"`
PageSize int `json:"page_size" query:"page_size"` PageSize int `json:"page_size" query:"page_size"`
WeighingBatchID *uint `json:"weighing_batch_id" query:"weighing_batch_id"` WeighingBatchID *uint32 `json:"weighing_batch_id" query:"weighing_batch_id"`
PenID *uint `json:"pen_id" query:"pen_id"` PenID *uint32 `json:"pen_id" query:"pen_id"`
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"` StartTime *time.Time `json:"start_time" query:"start_time"`
EndTime *time.Time `json:"end_time" query:"end_time"` EndTime *time.Time `json:"end_time" query:"end_time"`
OrderBy string `json:"order_by" query:"order_by"` OrderBy string `json:"order_by" query:"order_by"`
@@ -436,13 +436,13 @@ type ListWeighingRecordRequest struct {
// WeighingRecordDTO 是用于API响应的单次称重记录结构 // WeighingRecordDTO 是用于API响应的单次称重记录结构
type WeighingRecordDTO struct { type WeighingRecordDTO struct {
ID uint `json:"id"` ID uint32 `json:"id"`
CreatedAt time.Time `json:"created_at"` CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"` UpdatedAt time.Time `json:"updated_at"`
Weight float32 `json:"weight"` Weight float32 `json:"weight"`
WeighingBatchID uint `json:"weighing_batch_id"` WeighingBatchID uint32 `json:"weighing_batch_id"`
PenID uint `json:"pen_id"` PenID uint32 `json:"pen_id"`
OperatorID uint `json:"operator_id"` OperatorID uint32 `json:"operator_id"`
Remark string `json:"remark"` Remark string `json:"remark"`
WeighingTime time.Time `json:"weighing_time"` WeighingTime time.Time `json:"weighing_time"`
} }
@@ -459,10 +459,10 @@ type ListWeighingRecordResponse struct {
type ListPigTransferLogRequest struct { type ListPigTransferLogRequest struct {
Page int `json:"page" query:"page"` Page int `json:"page" query:"page"`
PageSize int `json:"page_size" query:"page_size"` 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"`
PenID *uint `json:"pen_id" query:"pen_id"` PenID *uint32 `json:"pen_id" query:"pen_id"`
TransferType *string `json:"transfer_type" query:"transfer_type"` 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"` CorrelationID *string `json:"correlation_id" query:"correlation_id"`
StartTime *time.Time `json:"start_time" query:"start_time"` StartTime *time.Time `json:"start_time" query:"start_time"`
EndTime *time.Time `json:"end_time" query:"end_time"` EndTime *time.Time `json:"end_time" query:"end_time"`
@@ -471,16 +471,16 @@ type ListPigTransferLogRequest struct {
// PigTransferLogDTO 是用于API响应的猪只迁移日志结构 // PigTransferLogDTO 是用于API响应的猪只迁移日志结构
type PigTransferLogDTO struct { type PigTransferLogDTO struct {
ID uint `json:"id"` ID uint32 `json:"id"`
CreatedAt time.Time `json:"created_at"` CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"` UpdatedAt time.Time `json:"updated_at"`
TransferTime time.Time `json:"transfer_time"` TransferTime time.Time `json:"transfer_time"`
PigBatchID uint `json:"pig_batch_id"` PigBatchID uint32 `json:"pig_batch_id"`
PenID uint `json:"pen_id"` PenID uint32 `json:"pen_id"`
Quantity int `json:"quantity"` Quantity int `json:"quantity"`
Type models.PigTransferType `json:"type"` Type models.PigTransferType `json:"type"`
CorrelationID string `json:"correlation_id"` CorrelationID string `json:"correlation_id"`
OperatorID uint `json:"operator_id"` OperatorID uint32 `json:"operator_id"`
Remarks string `json:"remarks"` Remarks string `json:"remarks"`
} }
@@ -496,11 +496,11 @@ type ListPigTransferLogResponse struct {
type ListPigSickLogRequest struct { type ListPigSickLogRequest struct {
Page int `json:"page" query:"page"` Page int `json:"page" query:"page"`
PageSize int `json:"page_size" query:"page_size"` 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"`
PenID *uint `json:"pen_id" query:"pen_id"` PenID *uint32 `json:"pen_id" query:"pen_id"`
Reason *string `json:"reason" query:"reason"` Reason *string `json:"reason" query:"reason"`
TreatmentLocation *string `json:"treatment_location" query:"treatment_location"` 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"` StartTime *time.Time `json:"start_time" query:"start_time"`
EndTime *time.Time `json:"end_time" query:"end_time"` EndTime *time.Time `json:"end_time" query:"end_time"`
OrderBy string `json:"order_by" query:"order_by"` OrderBy string `json:"order_by" query:"order_by"`
@@ -508,18 +508,18 @@ type ListPigSickLogRequest struct {
// PigSickLogDTO 是用于API响应的病猪日志结构 // PigSickLogDTO 是用于API响应的病猪日志结构
type PigSickLogDTO struct { type PigSickLogDTO struct {
ID uint `json:"id"` ID uint32 `json:"id"`
CreatedAt time.Time `json:"created_at"` CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"` UpdatedAt time.Time `json:"updated_at"`
PigBatchID uint `json:"pig_batch_id"` PigBatchID uint32 `json:"pig_batch_id"`
PenID uint `json:"pen_id"` PenID uint32 `json:"pen_id"`
ChangeCount int `json:"change_count"` ChangeCount int `json:"change_count"`
Reason models.PigBatchSickPigReasonType `json:"reason"` Reason models.PigBatchSickPigReasonType `json:"reason"`
BeforeCount int `json:"before_count"` BeforeCount int `json:"before_count"`
AfterCount int `json:"after_count"` AfterCount int `json:"after_count"`
Remarks string `json:"remarks"` Remarks string `json:"remarks"`
TreatmentLocation models.PigBatchSickPigTreatmentLocation `json:"treatment_location"` TreatmentLocation models.PigBatchSickPigTreatmentLocation `json:"treatment_location"`
OperatorID uint `json:"operator_id"` OperatorID uint32 `json:"operator_id"`
HappenedAt time.Time `json:"happened_at"` HappenedAt time.Time `json:"happened_at"`
} }
@@ -535,9 +535,9 @@ type ListPigSickLogResponse struct {
type ListPigPurchaseRequest struct { type ListPigPurchaseRequest struct {
Page int `json:"page" query:"page"` Page int `json:"page" query:"page"`
PageSize int `json:"page_size" query:"page_size"` 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"` 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"` StartTime *time.Time `json:"start_time" query:"start_time"`
EndTime *time.Time `json:"end_time" query:"end_time"` EndTime *time.Time `json:"end_time" query:"end_time"`
OrderBy string `json:"order_by" query:"order_by"` OrderBy string `json:"order_by" query:"order_by"`
@@ -545,17 +545,17 @@ type ListPigPurchaseRequest struct {
// PigPurchaseDTO 是用于API响应的猪只采购记录结构 // PigPurchaseDTO 是用于API响应的猪只采购记录结构
type PigPurchaseDTO struct { type PigPurchaseDTO struct {
ID uint `json:"id"` ID uint32 `json:"id"`
CreatedAt time.Time `json:"created_at"` CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_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"` PurchaseDate time.Time `json:"purchase_date"`
Supplier string `json:"supplier"` Supplier string `json:"supplier"`
Quantity int `json:"quantity"` Quantity int `json:"quantity"`
UnitPrice float32 `json:"unit_price"` UnitPrice float32 `json:"unit_price"`
TotalPrice float32 `json:"total_price"` TotalPrice float32 `json:"total_price"`
Remarks string `json:"remarks"` Remarks string `json:"remarks"`
OperatorID uint `json:"operator_id"` OperatorID uint32 `json:"operator_id"`
} }
// ListPigPurchaseResponse 是获取猪只采购记录列表的响应结构 // ListPigPurchaseResponse 是获取猪只采购记录列表的响应结构
@@ -570,9 +570,9 @@ type ListPigPurchaseResponse struct {
type ListPigSaleRequest struct { type ListPigSaleRequest struct {
Page int `json:"page" query:"page"` Page int `json:"page" query:"page"`
PageSize int `json:"page_size" query:"page_size"` 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"` 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"` StartTime *time.Time `json:"start_time" query:"start_time"`
EndTime *time.Time `json:"end_time" query:"end_time"` EndTime *time.Time `json:"end_time" query:"end_time"`
OrderBy string `json:"order_by" query:"order_by"` OrderBy string `json:"order_by" query:"order_by"`
@@ -580,17 +580,17 @@ type ListPigSaleRequest struct {
// PigSaleDTO 是用于API响应的猪只销售记录结构 // PigSaleDTO 是用于API响应的猪只销售记录结构
type PigSaleDTO struct { type PigSaleDTO struct {
ID uint `json:"id"` ID uint32 `json:"id"`
CreatedAt time.Time `json:"created_at"` CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_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"` SaleDate time.Time `json:"sale_date"`
Buyer string `json:"buyer"` Buyer string `json:"buyer"`
Quantity int `json:"quantity"` Quantity int `json:"quantity"`
UnitPrice float32 `json:"unit_price"` UnitPrice float32 `json:"unit_price"`
TotalPrice float32 `json:"total_price"` TotalPrice float32 `json:"total_price"`
Remarks string `json:"remarks"` Remarks string `json:"remarks"`
OperatorID uint `json:"operator_id"` OperatorID uint32 `json:"operator_id"`
} }
// ListPigSaleResponse 是获取猪只销售记录列表的响应结构 // ListPigSaleResponse 是获取猪只销售记录列表的响应结构

View File

@@ -18,7 +18,7 @@ type SendTestNotificationRequest struct {
type ListNotificationRequest struct { type ListNotificationRequest struct {
Page int `json:"page" query:"page"` Page int `json:"page" query:"page"`
PageSize int `json:"page_size" query:"page_size"` 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"` NotifierType *models.NotifierType `json:"notifier_type" query:"notifier_type"`
Status *models.NotificationStatus `json:"status" query:"status"` Status *models.NotificationStatus `json:"status" query:"status"`
Level *zapcore.Level `json:"level" query:"level"` Level *zapcore.Level `json:"level" query:"level"`
@@ -29,11 +29,11 @@ type ListNotificationRequest struct {
// NotificationDTO 是用于API响应的通知结构 // NotificationDTO 是用于API响应的通知结构
type NotificationDTO struct { type NotificationDTO struct {
ID uint `json:"id"` ID uint32 `json:"id"`
CreatedAt time.Time `json:"created_at"` CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"` UpdatedAt time.Time `json:"updated_at"`
NotifierType models.NotifierType `json:"notifier_type"` NotifierType models.NotifierType `json:"notifier_type"`
UserID uint `json:"user_id"` UserID uint32 `json:"user_id"`
Title string `json:"title"` Title string `json:"title"`
Message string `json:"message"` Message string `json:"message"`
Level models.SeverityLevel `json:"level"` Level models.SeverityLevel `json:"level"`

View File

@@ -32,7 +32,7 @@ type PigBatchQueryDTO struct {
// PigBatchResponseDTO 定义了猪批次信息的响应结构 // PigBatchResponseDTO 定义了猪批次信息的响应结构
type PigBatchResponseDTO struct { type PigBatchResponseDTO struct {
ID uint `json:"id"` // 批次ID ID uint32 `json:"id"` // 批次ID
BatchNumber string `json:"batch_number"` // 批次编号 BatchNumber string `json:"batch_number"` // 批次编号
OriginType models.PigBatchOriginType `json:"origin_type"` // 批次来源 OriginType models.PigBatchOriginType `json:"origin_type"` // 批次来源
StartDate time.Time `json:"start_date"` // 批次开始日期 StartDate time.Time `json:"start_date"` // 批次开始日期
@@ -48,31 +48,31 @@ type PigBatchResponseDTO struct {
// AssignEmptyPensToBatchRequest 用于为猪批次分配空栏的请求体 // AssignEmptyPensToBatchRequest 用于为猪批次分配空栏的请求体
type AssignEmptyPensToBatchRequest struct { 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 用于将猪栏划拨到新批次的请求体 // ReclassifyPenToNewBatchRequest 用于将猪栏划拨到新批次的请求体
type ReclassifyPenToNewBatchRequest struct { type ReclassifyPenToNewBatchRequest struct {
ToBatchID uint `json:"to_batch_id" validate:"required"` // 目标猪批次ID ToBatchID uint32 `json:"to_batch_id" validate:"required"` // 目标猪批次ID
PenID uint `json:"pen_id" validate:"required"` // 待划拨的猪栏ID PenID uint32 `json:"pen_id" validate:"required"` // 待划拨的猪栏ID
Remarks string `json:"remarks"` // 备注 Remarks string `json:"remarks"` // 备注
} }
// RemoveEmptyPenFromBatchRequest 用于从猪批次移除空栏的请求体 // RemoveEmptyPenFromBatchRequest 用于从猪批次移除空栏的请求体
type RemoveEmptyPenFromBatchRequest struct { type RemoveEmptyPenFromBatchRequest struct {
PenID uint `json:"pen_id" validate:"required"` // 待移除的猪栏ID PenID uint32 `json:"pen_id" validate:"required"` // 待移除的猪栏ID
} }
// MovePigsIntoPenRequest 用于将猪只从“虚拟库存”移入指定猪栏的请求体 // MovePigsIntoPenRequest 用于将猪只从“虚拟库存”移入指定猪栏的请求体
type MovePigsIntoPenRequest struct { 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"` // 移入猪只数量 Quantity int `json:"quantity" validate:"required,min=1"` // 移入猪只数量
Remarks string `json:"remarks"` // 备注 Remarks string `json:"remarks"` // 备注
} }
// SellPigsRequest 用于处理卖猪的请求体 // SellPigsRequest 用于处理卖猪的请求体
type SellPigsRequest struct { 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"` // 卖出猪只数量 Quantity int `json:"quantity" validate:"required,min=1"` // 卖出猪只数量
UnitPrice float32 `json:"unit_price" validate:"required,min=0"` // 单价 UnitPrice float32 `json:"unit_price" validate:"required,min=0"` // 单价
TotalPrice float32 `json:"total_price" validate:"required,min=0"` // 总价 TotalPrice float32 `json:"total_price" validate:"required,min=0"` // 总价
@@ -83,7 +83,7 @@ type SellPigsRequest struct {
// BuyPigsRequest 用于处理买猪的请求体 // BuyPigsRequest 用于处理买猪的请求体
type BuyPigsRequest struct { 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"` // 买入猪只数量 Quantity int `json:"quantity" validate:"required,min=1"` // 买入猪只数量
UnitPrice float32 `json:"unit_price" validate:"required,min=0"` // 单价 UnitPrice float32 `json:"unit_price" validate:"required,min=0"` // 单价
TotalPrice float32 `json:"total_price" validate:"required,min=0"` // 总价 TotalPrice float32 `json:"total_price" validate:"required,min=0"` // 总价
@@ -94,24 +94,24 @@ type BuyPigsRequest struct {
// TransferPigsAcrossBatchesRequest 用于跨猪群调栏的请求体 // TransferPigsAcrossBatchesRequest 用于跨猪群调栏的请求体
type TransferPigsAcrossBatchesRequest struct { type TransferPigsAcrossBatchesRequest struct {
DestBatchID uint `json:"dest_batch_id" validate:"required"` // 目标猪批次ID DestBatchID uint32 `json:"dest_batch_id" validate:"required"` // 目标猪批次ID
FromPenID uint `json:"from_pen_id" validate:"required"` // 源猪栏ID FromPenID uint32 `json:"from_pen_id" validate:"required"` // 源猪栏ID
ToPenID uint `json:"to_pen_id" validate:"required"` // 目标猪栏ID ToPenID uint32 `json:"to_pen_id" validate:"required"` // 目标猪栏ID
Quantity uint `json:"quantity" validate:"required,min=1"` // 调栏猪只数量 Quantity uint32 `json:"quantity" validate:"required,min=1"` // 调栏猪只数量
Remarks string `json:"remarks"` // 备注 Remarks string `json:"remarks"` // 备注
} }
// TransferPigsWithinBatchRequest 用于群内调栏的请求体 // TransferPigsWithinBatchRequest 用于群内调栏的请求体
type TransferPigsWithinBatchRequest struct { type TransferPigsWithinBatchRequest struct {
FromPenID uint `json:"from_pen_id" validate:"required"` // 源猪栏ID FromPenID uint32 `json:"from_pen_id" validate:"required"` // 源猪栏ID
ToPenID uint `json:"to_pen_id" validate:"required"` // 目标猪栏ID ToPenID uint32 `json:"to_pen_id" validate:"required"` // 目标猪栏ID
Quantity uint `json:"quantity" validate:"required,min=1"` // 调栏猪只数量 Quantity uint32 `json:"quantity" validate:"required,min=1"` // 调栏猪只数量
Remarks string `json:"remarks"` // 备注 Remarks string `json:"remarks"` // 备注
} }
// RecordSickPigsRequest 用于记录新增病猪事件的请求体 // RecordSickPigsRequest 用于记录新增病猪事件的请求体
type RecordSickPigsRequest struct { 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"` // 病猪数量 Quantity int `json:"quantity" validate:"required,min=1"` // 病猪数量
TreatmentLocation models.PigBatchSickPigTreatmentLocation `json:"treatment_location" validate:"required"` // 治疗地点 TreatmentLocation models.PigBatchSickPigTreatmentLocation `json:"treatment_location" validate:"required"` // 治疗地点
HappenedAt time.Time `json:"happened_at" validate:"required"` // 发生时间 HappenedAt time.Time `json:"happened_at" validate:"required"` // 发生时间
@@ -120,7 +120,7 @@ type RecordSickPigsRequest struct {
// RecordSickPigRecoveryRequest 用于记录病猪康复事件的请求体 // RecordSickPigRecoveryRequest 用于记录病猪康复事件的请求体
type RecordSickPigRecoveryRequest struct { 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"` // 康复猪数量 Quantity int `json:"quantity" validate:"required,min=1"` // 康复猪数量
TreatmentLocation models.PigBatchSickPigTreatmentLocation `json:"treatment_location" validate:"required"` // 治疗地点 TreatmentLocation models.PigBatchSickPigTreatmentLocation `json:"treatment_location" validate:"required"` // 治疗地点
HappenedAt time.Time `json:"happened_at" validate:"required"` // 发生时间 HappenedAt time.Time `json:"happened_at" validate:"required"` // 发生时间
@@ -129,7 +129,7 @@ type RecordSickPigRecoveryRequest struct {
// RecordSickPigDeathRequest 用于记录病猪死亡事件的请求体 // RecordSickPigDeathRequest 用于记录病猪死亡事件的请求体
type RecordSickPigDeathRequest struct { 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"` // 死亡猪数量 Quantity int `json:"quantity" validate:"required,min=1"` // 死亡猪数量
TreatmentLocation models.PigBatchSickPigTreatmentLocation `json:"treatment_location" validate:"required"` // 治疗地点 TreatmentLocation models.PigBatchSickPigTreatmentLocation `json:"treatment_location" validate:"required"` // 治疗地点
HappenedAt time.Time `json:"happened_at" validate:"required"` // 发生时间 HappenedAt time.Time `json:"happened_at" validate:"required"` // 发生时间
@@ -138,7 +138,7 @@ type RecordSickPigDeathRequest struct {
// RecordSickPigCullRequest 用于记录病猪淘汰事件的请求体 // RecordSickPigCullRequest 用于记录病猪淘汰事件的请求体
type RecordSickPigCullRequest struct { 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"` // 淘汰猪数量 Quantity int `json:"quantity" validate:"required,min=1"` // 淘汰猪数量
TreatmentLocation models.PigBatchSickPigTreatmentLocation `json:"treatment_location" validate:"required"` // 治疗地点 TreatmentLocation models.PigBatchSickPigTreatmentLocation `json:"treatment_location" validate:"required"` // 治疗地点
HappenedAt time.Time `json:"happened_at" validate:"required"` // 发生时间 HappenedAt time.Time `json:"happened_at" validate:"required"` // 发生时间
@@ -147,7 +147,7 @@ type RecordSickPigCullRequest struct {
// RecordDeathRequest 用于记录正常猪只死亡事件的请求体 // RecordDeathRequest 用于记录正常猪只死亡事件的请求体
type RecordDeathRequest struct { 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"` // 死亡猪数量 Quantity int `json:"quantity" validate:"required,min=1"` // 死亡猪数量
HappenedAt time.Time `json:"happened_at" validate:"required"` // 发生时间 HappenedAt time.Time `json:"happened_at" validate:"required"` // 发生时间
Remarks string `json:"remarks"` // 备注 Remarks string `json:"remarks"` // 备注
@@ -155,7 +155,7 @@ type RecordDeathRequest struct {
// RecordCullRequest 用于记录正常猪只淘汰事件的请求体 // RecordCullRequest 用于记录正常猪只淘汰事件的请求体
type RecordCullRequest struct { 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"` // 淘汰猪数量 Quantity int `json:"quantity" validate:"required,min=1"` // 淘汰猪数量
HappenedAt time.Time `json:"happened_at" validate:"required"` // 发生时间 HappenedAt time.Time `json:"happened_at" validate:"required"` // 发生时间
Remarks string `json:"remarks"` // 备注 Remarks string `json:"remarks"` // 备注

View File

@@ -4,19 +4,19 @@ import "git.huangwc.com/pig/pig-farm-controller/internal/infra/models"
// PigHouseResponse 定义了猪舍信息的响应结构 // PigHouseResponse 定义了猪舍信息的响应结构
type PigHouseResponse struct { type PigHouseResponse struct {
ID uint `json:"id"` ID uint32 `json:"id"`
Name string `json:"name"` Name string `json:"name"`
Description string `json:"description"` Description string `json:"description"`
} }
// PenResponse 定义了猪栏信息的响应结构 // PenResponse 定义了猪栏信息的响应结构
type PenResponse struct { type PenResponse struct {
ID uint `json:"id"` ID uint32 `json:"id"`
PenNumber string `json:"pen_number"` PenNumber string `json:"pen_number"`
HouseID uint `json:"house_id"` HouseID uint32 `json:"house_id"`
Capacity int `json:"capacity"` Capacity int `json:"capacity"`
Status models.PenStatus `json:"status"` 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"` CurrentPigCount int `json:"current_pig_count"`
} }
@@ -35,14 +35,14 @@ type UpdatePigHouseRequest struct {
// CreatePenRequest 定义了创建猪栏的请求结构 // CreatePenRequest 定义了创建猪栏的请求结构
type CreatePenRequest struct { type CreatePenRequest struct {
PenNumber string `json:"pen_number" validate:"required"` 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"` Capacity int `json:"capacity" validate:"required"`
} }
// UpdatePenRequest 定义了更新猪栏的请求结构 // UpdatePenRequest 定义了更新猪栏的请求结构
type UpdatePenRequest struct { type UpdatePenRequest struct {
PenNumber string `json:"pen_number" validate:"required"` 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"` Capacity int `json:"capacity" validate:"required"`
Status models.PenStatus `json:"status" validate:"required,oneof=空闲 使用中 病猪栏 康复栏 清洗消毒 维修中"` // 添加oneof校验 Status models.PenStatus `json:"status" validate:"required,oneof=空闲 使用中 病猪栏 康复栏 清洗消毒 维修中"` // 添加oneof校验
} }

View File

@@ -17,22 +17,22 @@ type CreatePlanRequest struct {
Name string `json:"name" validate:"required" example:"猪舍温度控制计划"` Name string `json:"name" validate:"required" example:"猪舍温度控制计划"`
Description string `json:"description" example:"根据温度自动调节风扇和加热器"` Description string `json:"description" example:"根据温度自动调节风扇和加热器"`
ExecutionType models.PlanExecutionType `json:"execution_type" validate:"required" 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 * * *"` 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"` Tasks []TaskRequest `json:"tasks,omitempty" validate:"omitempty,dive"`
} }
// PlanResponse 定义计划详情响应的结构体 // PlanResponse 定义计划详情响应的结构体
type PlanResponse struct { type PlanResponse struct {
ID uint `json:"id" example:"1"` ID uint32 `json:"id" example:"1"`
Name string `json:"name" example:"猪舍温度控制计划"` Name string `json:"name" example:"猪舍温度控制计划"`
Description string `json:"description" example:"根据温度自动调节风扇和加热器"` Description string `json:"description" example:"根据温度自动调节风扇和加热器"`
PlanType models.PlanType `json:"plan_type" example:"自定义任务"` PlanType models.PlanType `json:"plan_type" example:"自定义任务"`
ExecutionType models.PlanExecutionType `json:"execution_type" example:"自动"` ExecutionType models.PlanExecutionType `json:"execution_type" example:"自动"`
Status models.PlanStatus `json:"status" example:"已启用"` Status models.PlanStatus `json:"status" example:"已启用"`
ExecuteNum uint `json:"execute_num" example:"10"` ExecuteNum uint32 `json:"execute_num" example:"10"`
ExecuteCount uint `json:"execute_count" example:"0"` ExecuteCount uint32 `json:"execute_count" example:"0"`
CronExpression string `json:"cron_expression" example:"0 0 6 * * *"` CronExpression string `json:"cron_expression" example:"0 0 6 * * *"`
ContentType models.PlanContentType `json:"content_type" example:"任务"` ContentType models.PlanContentType `json:"content_type" example:"任务"`
SubPlans []SubPlanResponse `json:"sub_plans,omitempty"` SubPlans []SubPlanResponse `json:"sub_plans,omitempty"`
@@ -50,17 +50,17 @@ type UpdatePlanRequest struct {
Name string `json:"name" example:"猪舍温度控制计划V2"` Name string `json:"name" example:"猪舍温度控制计划V2"`
Description string `json:"description" example:"更新后的描述"` Description string `json:"description" example:"更新后的描述"`
ExecutionType models.PlanExecutionType `json:"execution_type" validate:"required" 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 * * *"` 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"` Tasks []TaskRequest `json:"tasks,omitempty" validate:"omitempty,dive"`
} }
// SubPlanResponse 定义子计划响应结构体 // SubPlanResponse 定义子计划响应结构体
type SubPlanResponse struct { type SubPlanResponse struct {
ID uint `json:"id" example:"1"` ID uint32 `json:"id" example:"1"`
ParentPlanID uint `json:"parent_plan_id" example:"1"` ParentPlanID uint32 `json:"parent_plan_id" example:"1"`
ChildPlanID uint `json:"child_plan_id" example:"2"` ChildPlanID uint32 `json:"child_plan_id" example:"2"`
ExecutionOrder int `json:"execution_order" example:"1"` ExecutionOrder int `json:"execution_order" example:"1"`
ChildPlan *PlanResponse `json:"child_plan,omitempty"` ChildPlan *PlanResponse `json:"child_plan,omitempty"`
} }
@@ -77,7 +77,7 @@ type TaskRequest struct {
// TaskResponse 定义任务响应结构体 // TaskResponse 定义任务响应结构体
type TaskResponse struct { type TaskResponse struct {
ID int `json:"id" example:"1"` 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:"打开风扇"` Name string `json:"name" example:"打开风扇"`
Description string `json:"description" example:"打开1号风扇"` Description string `json:"description" example:"打开1号风扇"`
ExecutionOrder int `json:"execution_order" example:"1"` ExecutionOrder int `json:"execution_order" example:"1"`

View File

@@ -16,19 +16,19 @@ type LoginRequest struct {
// CreateUserResponse 定义创建用户成功响应的结构体 // CreateUserResponse 定义创建用户成功响应的结构体
type CreateUserResponse struct { type CreateUserResponse struct {
Username string `json:"username" example:"newuser"` Username string `json:"username" example:"newuser"`
ID uint `json:"id" example:"1"` ID uint32 `json:"id" example:"1"`
} }
// LoginResponse 定义登录成功响应的结构体 // LoginResponse 定义登录成功响应的结构体
type LoginResponse struct { type LoginResponse struct {
Username string `json:"username" example:"testuser"` Username string `json:"username" example:"testuser"`
ID uint `json:"id" example:"1"` ID uint32 `json:"id" example:"1"`
Token string `json:"token" example:"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."` Token string `json:"token" example:"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."`
} }
// HistoryResponse 定义单条操作历史的响应结构体 // HistoryResponse 定义单条操作历史的响应结构体
type HistoryResponse struct { type HistoryResponse struct {
UserID uint `json:"user_id" example:"101"` UserID uint32 `json:"user_id" example:"101"`
Username string `json:"username" example:"testuser"` Username string `json:"username" example:"testuser"`
ActionType string `json:"action_type" example:"更新设备"` ActionType string `json:"action_type" example:"更新设备"`
Description string `json:"description" example:"设备更新成功"` Description string `json:"description" example:"设备更新成功"`

View File

@@ -28,23 +28,23 @@ var (
// DeviceService 定义了应用层的设备服务接口,用于协调设备相关的业务逻辑。 // DeviceService 定义了应用层的设备服务接口,用于协调设备相关的业务逻辑。
type DeviceService interface { type DeviceService interface {
CreateDevice(ctx context.Context, req *dto.CreateDeviceRequest) (*dto.DeviceResponse, error) 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) ListDevices(ctx context.Context) ([]*dto.DeviceResponse, error)
UpdateDevice(ctx context.Context, id uint, req *dto.UpdateDeviceRequest) (*dto.DeviceResponse, error) UpdateDevice(ctx context.Context, id uint32, req *dto.UpdateDeviceRequest) (*dto.DeviceResponse, error)
DeleteDevice(ctx context.Context, id uint) error DeleteDevice(ctx context.Context, id uint32) error
ManualControl(ctx context.Context, id uint, req *dto.ManualControlDeviceRequest) error ManualControl(ctx context.Context, id uint32, req *dto.ManualControlDeviceRequest) error
CreateAreaController(ctx context.Context, req *dto.CreateAreaControllerRequest) (*dto.AreaControllerResponse, 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) ListAreaControllers(ctx context.Context) ([]*dto.AreaControllerResponse, error)
UpdateAreaController(ctx context.Context, id uint, req *dto.UpdateAreaControllerRequest) (*dto.AreaControllerResponse, error) UpdateAreaController(ctx context.Context, id uint32, req *dto.UpdateAreaControllerRequest) (*dto.AreaControllerResponse, error)
DeleteAreaController(ctx context.Context, id uint) error DeleteAreaController(ctx context.Context, id uint32) error
CreateDeviceTemplate(ctx context.Context, req *dto.CreateDeviceTemplateRequest) (*dto.DeviceTemplateResponse, 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) ListDeviceTemplates(ctx context.Context) ([]*dto.DeviceTemplateResponse, error)
UpdateDeviceTemplate(ctx context.Context, id uint, req *dto.UpdateDeviceTemplateRequest) (*dto.DeviceTemplateResponse, error) UpdateDeviceTemplate(ctx context.Context, id uint32, req *dto.UpdateDeviceTemplateRequest) (*dto.DeviceTemplateResponse, error)
DeleteDeviceTemplate(ctx context.Context, id uint) error DeleteDeviceTemplate(ctx context.Context, id uint32) error
} }
// deviceService 是 DeviceService 接口的具体实现。 // deviceService 是 DeviceService 接口的具体实现。
@@ -109,7 +109,7 @@ func (s *deviceService) CreateDevice(ctx context.Context, req *dto.CreateDeviceR
return dto.NewDeviceResponse(createdDevice) 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") serviceCtx := logs.AddFuncName(ctx, s.ctx, "GetDevice")
device, err := s.deviceRepo.FindByID(serviceCtx, id) device, err := s.deviceRepo.FindByID(serviceCtx, id)
if err != nil { if err != nil {
@@ -127,7 +127,7 @@ func (s *deviceService) ListDevices(ctx context.Context) ([]*dto.DeviceResponse,
return dto.NewListDeviceResponse(devices) 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") serviceCtx := logs.AddFuncName(ctx, s.ctx, "UpdateDevice")
existingDevice, err := s.deviceRepo.FindByID(serviceCtx, id) existingDevice, err := s.deviceRepo.FindByID(serviceCtx, id)
if err != nil { if err != nil {
@@ -161,7 +161,7 @@ func (s *deviceService) UpdateDevice(ctx context.Context, id uint, req *dto.Upda
return dto.NewDeviceResponse(updatedDevice) 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") 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) 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") serviceCtx := logs.AddFuncName(ctx, s.ctx, "ManualControl")
dev, err := s.deviceRepo.FindByID(serviceCtx, id) dev, err := s.deviceRepo.FindByID(serviceCtx, id)
if err != nil { if err != nil {
@@ -241,7 +241,7 @@ func (s *deviceService) CreateAreaController(ctx context.Context, req *dto.Creat
return dto.NewAreaControllerResponse(ac) 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") serviceCtx := logs.AddFuncName(ctx, s.ctx, "GetAreaController")
ac, err := s.areaControllerRepo.FindByID(serviceCtx, id) ac, err := s.areaControllerRepo.FindByID(serviceCtx, id)
if err != nil { if err != nil {
@@ -259,7 +259,7 @@ func (s *deviceService) ListAreaControllers(ctx context.Context) ([]*dto.AreaCon
return dto.NewListAreaControllerResponse(acs) 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") serviceCtx := logs.AddFuncName(ctx, s.ctx, "UpdateAreaController")
existingAC, err := s.areaControllerRepo.FindByID(serviceCtx, id) existingAC, err := s.areaControllerRepo.FindByID(serviceCtx, id)
if err != nil { if err != nil {
@@ -287,7 +287,7 @@ func (s *deviceService) UpdateAreaController(ctx context.Context, id uint, req *
return dto.NewAreaControllerResponse(existingAC) 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") serviceCtx := logs.AddFuncName(ctx, s.ctx, "DeleteAreaController")
// 1. 检查是否存在 // 1. 检查是否存在
@@ -349,7 +349,7 @@ func (s *deviceService) CreateDeviceTemplate(ctx context.Context, req *dto.Creat
return dto.NewDeviceTemplateResponse(deviceTemplate) 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") serviceCtx := logs.AddFuncName(ctx, s.ctx, "GetDeviceTemplate")
deviceTemplate, err := s.deviceTemplateRepo.FindByID(serviceCtx, id) deviceTemplate, err := s.deviceTemplateRepo.FindByID(serviceCtx, id)
if err != nil { if err != nil {
@@ -367,7 +367,7 @@ func (s *deviceService) ListDeviceTemplates(ctx context.Context) ([]*dto.DeviceT
return dto.NewListDeviceTemplateResponse(deviceTemplates) 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") serviceCtx := logs.AddFuncName(ctx, s.ctx, "UpdateDeviceTemplate")
existingDeviceTemplate, err := s.deviceTemplateRepo.FindByID(serviceCtx, id) existingDeviceTemplate, err := s.deviceTemplateRepo.FindByID(serviceCtx, id)
if err != nil { if err != nil {
@@ -402,7 +402,7 @@ func (s *deviceService) UpdateDeviceTemplate(ctx context.Context, id uint, req *
return dto.NewDeviceTemplateResponse(existingDeviceTemplate) 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") serviceCtx := logs.AddFuncName(ctx, s.ctx, "DeleteDeviceTemplate")
// 1. 检查是否存在 // 1. 检查是否存在

View File

@@ -147,7 +147,7 @@ func (s *monitorService) ListPlanExecutionLogs(ctx context.Context, req *dto.Lis
return nil, err return nil, err
} }
planIds := make([]uint, 0, len(planLogs)) planIds := make([]uint32, 0, len(planLogs))
for _, datum := range planLogs { for _, datum := range planLogs {
has := false has := false
for _, id := range planIds { for _, id := range planIds {

View File

@@ -12,35 +12,35 @@ import (
// PigBatchService 接口定义保持不变,继续作为应用层对外的契约。 // PigBatchService 接口定义保持不变,继续作为应用层对外的契约。
type PigBatchService interface { type PigBatchService interface {
CreatePigBatch(ctx context.Context, operatorID uint, dto *dto.PigBatchCreateDTO) (*dto.PigBatchResponseDTO, error) CreatePigBatch(ctx context.Context, operatorID uint32, dto *dto.PigBatchCreateDTO) (*dto.PigBatchResponseDTO, error)
GetPigBatch(ctx context.Context, id uint) (*dto.PigBatchResponseDTO, error) GetPigBatch(ctx context.Context, id uint32) (*dto.PigBatchResponseDTO, error)
UpdatePigBatch(ctx context.Context, id uint, dto *dto.PigBatchUpdateDTO) (*dto.PigBatchResponseDTO, error) UpdatePigBatch(ctx context.Context, id uint32, dto *dto.PigBatchUpdateDTO) (*dto.PigBatchResponseDTO, error)
DeletePigBatch(ctx context.Context, id uint) error DeletePigBatch(ctx context.Context, id uint32) error
ListPigBatches(ctx context.Context, isActive *bool) ([]*dto.PigBatchResponseDTO, error) ListPigBatches(ctx context.Context, isActive *bool) ([]*dto.PigBatchResponseDTO, error)
// Pig Pen Management // Pig Pen Management
AssignEmptyPensToBatch(ctx context.Context, batchID uint, penIDs []uint, operatorID uint) error AssignEmptyPensToBatch(ctx context.Context, batchID uint32, penIDs []uint32, operatorID uint32) error
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(ctx context.Context, batchID uint, penID uint) error RemoveEmptyPenFromBatch(ctx context.Context, batchID uint32, penID uint32) error
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
// Trade Sub-service // 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 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 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
// Transfer Sub-service // Transfer Sub-service
TransferPigsAcrossBatches(ctx context.Context, sourceBatchID uint, destBatchID 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 uint, fromPenID uint, toPenID uint, quantity uint, operatorID uint, remarks string) error TransferPigsWithinBatch(ctx context.Context, batchID uint32, fromPenID uint32, toPenID uint32, quantity uint32, operatorID uint32, remarks string) error
// Sick Pig Management // Sick Pig Management
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(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(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(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
// Normal Pig Management // Normal Pig Management
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(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 的实现现在依赖于领域服务接口。
@@ -79,7 +79,7 @@ func (s *pigBatchService) toPigBatchResponseDTO(batch *models.PigBatch, currentT
} }
// CreatePigBatch 现在将请求委托给领域服务处理。 // 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") serviceCtx, logger := logs.Trace(ctx, s.ctx, "CreatePigBatch")
// 1. DTO -> 领域模型 // 1. DTO -> 领域模型
batch := &models.PigBatch{ batch := &models.PigBatch{
@@ -102,7 +102,7 @@ func (s *pigBatchService) CreatePigBatch(ctx context.Context, operatorID uint, d
} }
// GetPigBatch 从领域服务获取数据并转换为DTO同时处理错误转换。 // 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") serviceCtx, logger := logs.Trace(ctx, s.ctx, "GetPigBatch")
batch, err := s.domainService.GetPigBatch(serviceCtx, id) batch, err := s.domainService.GetPigBatch(serviceCtx, id)
if err != nil { if err != nil {
@@ -123,7 +123,7 @@ func (s *pigBatchService) GetPigBatch(ctx context.Context, id uint) (*dto.PigBat
} }
// UpdatePigBatch 协调获取、更新和保存的流程,并处理错误转换。 // 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") serviceCtx, logger := logs.Trace(ctx, s.ctx, "UpdatePigBatch")
// 1. 先获取最新的领域模型 // 1. 先获取最新的领域模型
existingBatch, err := s.domainService.GetPigBatch(serviceCtx, id) existingBatch, err := s.domainService.GetPigBatch(serviceCtx, id)
@@ -176,7 +176,7 @@ func (s *pigBatchService) UpdatePigBatch(ctx context.Context, id uint, dto *dto.
} }
// DeletePigBatch 将删除操作委托给领域服务,并转换领域错误为应用层错误。 // 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") serviceCtx, logger := logs.Trace(ctx, s.ctx, "DeletePigBatch")
err := s.domainService.DeletePigBatch(serviceCtx, id) err := s.domainService.DeletePigBatch(serviceCtx, id)
if err != nil { if err != nil {
@@ -214,7 +214,7 @@ func (s *pigBatchService) ListPigBatches(ctx context.Context, isActive *bool) ([
} }
// AssignEmptyPensToBatch 委托给领域服务 // 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") serviceCtx, logger := logs.Trace(ctx, s.ctx, "AssignEmptyPensToBatch")
err := s.domainService.AssignEmptyPensToBatch(serviceCtx, batchID, penIDs, operatorID) err := s.domainService.AssignEmptyPensToBatch(serviceCtx, batchID, penIDs, operatorID)
if err != nil { if err != nil {
@@ -225,7 +225,7 @@ func (s *pigBatchService) AssignEmptyPensToBatch(ctx context.Context, batchID ui
} }
// ReclassifyPenToNewBatch 委托给领域服务 // 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") serviceCtx, logger := logs.Trace(ctx, s.ctx, "ReclassifyPenToNewBatch")
err := s.domainService.ReclassifyPenToNewBatch(serviceCtx, fromBatchID, toBatchID, penID, operatorID, remarks) err := s.domainService.ReclassifyPenToNewBatch(serviceCtx, fromBatchID, toBatchID, penID, operatorID, remarks)
if err != nil { if err != nil {
@@ -236,7 +236,7 @@ func (s *pigBatchService) ReclassifyPenToNewBatch(ctx context.Context, fromBatch
} }
// RemoveEmptyPenFromBatch 委托给领域服务 // 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") serviceCtx, logger := logs.Trace(ctx, s.ctx, "RemoveEmptyPenFromBatch")
err := s.domainService.RemoveEmptyPenFromBatch(serviceCtx, batchID, penID) err := s.domainService.RemoveEmptyPenFromBatch(serviceCtx, batchID, penID)
if err != nil { if err != nil {
@@ -247,7 +247,7 @@ func (s *pigBatchService) RemoveEmptyPenFromBatch(ctx context.Context, batchID u
} }
// MovePigsIntoPen 委托给领域服务 // 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") serviceCtx, logger := logs.Trace(ctx, s.ctx, "MovePigsIntoPen")
err := s.domainService.MovePigsIntoPen(serviceCtx, batchID, toPenID, quantity, operatorID, remarks) err := s.domainService.MovePigsIntoPen(serviceCtx, batchID, toPenID, quantity, operatorID, remarks)
if err != nil { if err != nil {
@@ -258,7 +258,7 @@ func (s *pigBatchService) MovePigsIntoPen(ctx context.Context, batchID uint, toP
} }
// SellPigs 委托给领域服务 // 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") serviceCtx, logger := logs.Trace(ctx, s.ctx, "SellPigs")
err := s.domainService.SellPigs(serviceCtx, batchID, penID, quantity, unitPrice, tatalPrice, traderName, tradeDate, remarks, operatorID) err := s.domainService.SellPigs(serviceCtx, batchID, penID, quantity, unitPrice, tatalPrice, traderName, tradeDate, remarks, operatorID)
if err != nil { if err != nil {
@@ -269,7 +269,7 @@ func (s *pigBatchService) SellPigs(ctx context.Context, batchID uint, penID uint
} }
// BuyPigs 委托给领域服务 // 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") serviceCtx, logger := logs.Trace(ctx, s.ctx, "BuyPigs")
err := s.domainService.BuyPigs(serviceCtx, batchID, penID, quantity, unitPrice, tatalPrice, traderName, tradeDate, remarks, operatorID) err := s.domainService.BuyPigs(serviceCtx, batchID, penID, quantity, unitPrice, tatalPrice, traderName, tradeDate, remarks, operatorID)
if err != nil { if err != nil {
@@ -280,7 +280,7 @@ func (s *pigBatchService) BuyPigs(ctx context.Context, batchID uint, penID uint,
} }
// TransferPigsAcrossBatches 委托给领域服务 // 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") serviceCtx, logger := logs.Trace(ctx, s.ctx, "TransferPigsAcrossBatches")
err := s.domainService.TransferPigsAcrossBatches(serviceCtx, sourceBatchID, destBatchID, fromPenID, toPenID, quantity, operatorID, remarks) err := s.domainService.TransferPigsAcrossBatches(serviceCtx, sourceBatchID, destBatchID, fromPenID, toPenID, quantity, operatorID, remarks)
if err != nil { if err != nil {
@@ -291,7 +291,7 @@ func (s *pigBatchService) TransferPigsAcrossBatches(ctx context.Context, sourceB
} }
// TransferPigsWithinBatch 委托给领域服务 // 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") serviceCtx, logger := logs.Trace(ctx, s.ctx, "TransferPigsWithinBatch")
err := s.domainService.TransferPigsWithinBatch(serviceCtx, batchID, fromPenID, toPenID, quantity, operatorID, remarks) err := s.domainService.TransferPigsWithinBatch(serviceCtx, batchID, fromPenID, toPenID, quantity, operatorID, remarks)
if err != nil { if err != nil {
@@ -302,7 +302,7 @@ func (s *pigBatchService) TransferPigsWithinBatch(ctx context.Context, batchID u
} }
// RecordSickPigs 委托给领域服务 // 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") serviceCtx, logger := logs.Trace(ctx, s.ctx, "RecordSickPigs")
err := s.domainService.RecordSickPigs(serviceCtx, operatorID, batchID, penID, quantity, treatmentLocation, happenedAt, remarks) err := s.domainService.RecordSickPigs(serviceCtx, operatorID, batchID, penID, quantity, treatmentLocation, happenedAt, remarks)
if err != nil { if err != nil {
@@ -313,7 +313,7 @@ func (s *pigBatchService) RecordSickPigs(ctx context.Context, operatorID uint, b
} }
// RecordSickPigRecovery 委托给领域服务 // 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") serviceCtx, logger := logs.Trace(ctx, s.ctx, "RecordSickPigRecovery")
err := s.domainService.RecordSickPigRecovery(serviceCtx, operatorID, batchID, penID, quantity, treatmentLocation, happenedAt, remarks) err := s.domainService.RecordSickPigRecovery(serviceCtx, operatorID, batchID, penID, quantity, treatmentLocation, happenedAt, remarks)
if err != nil { if err != nil {
@@ -324,7 +324,7 @@ func (s *pigBatchService) RecordSickPigRecovery(ctx context.Context, operatorID
} }
// RecordSickPigDeath 委托给领域服务 // 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") serviceCtx, logger := logs.Trace(ctx, s.ctx, "RecordSickPigDeath")
err := s.domainService.RecordSickPigDeath(serviceCtx, operatorID, batchID, penID, quantity, treatmentLocation, happenedAt, remarks) err := s.domainService.RecordSickPigDeath(serviceCtx, operatorID, batchID, penID, quantity, treatmentLocation, happenedAt, remarks)
if err != nil { if err != nil {
@@ -335,7 +335,7 @@ func (s *pigBatchService) RecordSickPigDeath(ctx context.Context, operatorID uin
} }
// RecordSickPigCull 委托给领域服务 // 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") serviceCtx, logger := logs.Trace(ctx, s.ctx, "RecordSickPigCull")
err := s.domainService.RecordSickPigCull(serviceCtx, operatorID, batchID, penID, quantity, treatmentLocation, happenedAt, remarks) err := s.domainService.RecordSickPigCull(serviceCtx, operatorID, batchID, penID, quantity, treatmentLocation, happenedAt, remarks)
if err != nil { if err != nil {
@@ -346,7 +346,7 @@ func (s *pigBatchService) RecordSickPigCull(ctx context.Context, operatorID uint
} }
// RecordDeath 委托给领域服务 // 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") serviceCtx, logger := logs.Trace(ctx, s.ctx, "RecordDeath")
err := s.domainService.RecordDeath(serviceCtx, operatorID, batchID, penID, quantity, happenedAt, remarks) err := s.domainService.RecordDeath(serviceCtx, operatorID, batchID, penID, quantity, happenedAt, remarks)
if err != nil { if err != nil {
@@ -357,7 +357,7 @@ func (s *pigBatchService) RecordDeath(ctx context.Context, operatorID uint, batc
} }
// RecordCull 委托给领域服务 // 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") serviceCtx, logger := logs.Trace(ctx, s.ctx, "RecordCull")
err := s.domainService.RecordCull(serviceCtx, operatorID, batchID, penID, quantity, happenedAt, remarks) err := s.domainService.RecordCull(serviceCtx, operatorID, batchID, penID, quantity, happenedAt, remarks)
if err != nil { if err != nil {

View File

@@ -18,19 +18,19 @@ import (
type PigFarmService interface { type PigFarmService interface {
// PigHouse methods // PigHouse methods
CreatePigHouse(ctx context.Context, name, description string) (*dto.PigHouseResponse, error) 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) ListPigHouses(ctx context.Context) ([]dto.PigHouseResponse, error)
UpdatePigHouse(ctx context.Context, id uint, name, description string) (*dto.PigHouseResponse, error) UpdatePigHouse(ctx context.Context, id uint32, name, description string) (*dto.PigHouseResponse, error)
DeletePigHouse(ctx context.Context, id uint) error DeletePigHouse(ctx context.Context, id uint32) error
// Pen methods // Pen methods
CreatePen(ctx context.Context, penNumber string, houseID uint, capacity int) (*dto.PenResponse, error) CreatePen(ctx context.Context, penNumber string, houseID uint32, capacity int) (*dto.PenResponse, error)
GetPenByID(ctx context.Context, id uint) (*dto.PenResponse, error) GetPenByID(ctx context.Context, id uint32) (*dto.PenResponse, error)
ListPens(ctx context.Context) ([]*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) UpdatePen(ctx context.Context, id uint32, penNumber string, houseID uint32, capacity int, status models.PenStatus) (*dto.PenResponse, error)
DeletePen(ctx context.Context, id uint) error DeletePen(ctx context.Context, id uint32) error
// UpdatePenStatus 更新猪栏状态 // 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 { type pigFarmService struct {
@@ -79,7 +79,7 @@ func (s *pigFarmService) CreatePigHouse(ctx context.Context, name, description s
}, nil }, 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") serviceCtx := logs.AddFuncName(ctx, s.ctx, "GetPigHouseByID")
house, err := s.farmRepository.GetPigHouseByID(serviceCtx, id) house, err := s.farmRepository.GetPigHouseByID(serviceCtx, id)
if err != nil { if err != nil {
@@ -109,10 +109,10 @@ func (s *pigFarmService) ListPigHouses(ctx context.Context) ([]dto.PigHouseRespo
return resp, nil 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") serviceCtx := logs.AddFuncName(ctx, s.ctx, "UpdatePigHouse")
house := &models.PigHouse{ house := &models.PigHouse{
Model: gorm.Model{ID: id}, Model: models.Model{ID: id},
Name: name, Name: name,
Description: description, Description: description,
} }
@@ -135,7 +135,7 @@ func (s *pigFarmService) UpdatePigHouse(ctx context.Context, id uint, name, desc
}, nil }, 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") serviceCtx := logs.AddFuncName(ctx, s.ctx, "DeletePigHouse")
// 业务逻辑:检查猪舍是否包含猪栏 // 业务逻辑:检查猪舍是否包含猪栏
penCount, err := s.farmRepository.CountPensInHouse(serviceCtx, id) penCount, err := s.farmRepository.CountPensInHouse(serviceCtx, id)
@@ -159,7 +159,7 @@ func (s *pigFarmService) DeletePigHouse(ctx context.Context, id uint) error {
// --- Pen Implementation --- // --- 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") serviceCtx := logs.AddFuncName(ctx, s.ctx, "CreatePen")
// 业务逻辑:验证所属猪舍是否存在 // 业务逻辑:验证所属猪舍是否存在
_, err := s.farmRepository.GetPigHouseByID(serviceCtx, houseID) _, err := s.farmRepository.GetPigHouseByID(serviceCtx, houseID)
@@ -189,7 +189,7 @@ func (s *pigFarmService) CreatePen(ctx context.Context, penNumber string, houseI
}, nil }, 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") serviceCtx, logger := logs.Trace(ctx, s.ctx, "GetPenByID")
pen, err := s.penRepository.GetPenByID(serviceCtx, id) pen, err := s.penRepository.GetPenByID(serviceCtx, id)
if err != nil { if err != nil {
@@ -251,7 +251,7 @@ func (s *pigFarmService) ListPens(ctx context.Context) ([]*dto.PenResponse, erro
return response, nil 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") serviceCtx := logs.AddFuncName(ctx, s.ctx, "UpdatePen")
// 业务逻辑:验证所属猪舍是否存在 // 业务逻辑:验证所属猪舍是否存在
_, err := s.farmRepository.GetPigHouseByID(serviceCtx, houseID) _, err := s.farmRepository.GetPigHouseByID(serviceCtx, houseID)
@@ -263,7 +263,7 @@ func (s *pigFarmService) UpdatePen(ctx context.Context, id uint, penNumber strin
} }
pen := &models.Pen{ pen := &models.Pen{
Model: gorm.Model{ID: id}, Model: models.Model{ID: id},
PenNumber: penNumber, PenNumber: penNumber,
HouseID: houseID, HouseID: houseID,
Capacity: capacity, Capacity: capacity,
@@ -291,7 +291,7 @@ func (s *pigFarmService) UpdatePen(ctx context.Context, id uint, penNumber strin
}, nil }, 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") serviceCtx := logs.AddFuncName(ctx, s.ctx, "DeletePen")
// 业务逻辑:检查猪栏是否被活跃批次使用 // 业务逻辑:检查猪栏是否被活跃批次使用
pen, err := s.penRepository.GetPenByID(serviceCtx, id) pen, err := s.penRepository.GetPenByID(serviceCtx, id)
@@ -327,7 +327,7 @@ func (s *pigFarmService) DeletePen(ctx context.Context, id uint) error {
} }
// UpdatePenStatus 更新猪栏状态 // 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") serviceCtx, logger := logs.Trace(ctx, s.ctx, "UpdatePenStatus")
var updatedPen *models.Pen var updatedPen *models.Pen
err := s.uow.ExecuteInTransaction(serviceCtx, func(tx *gorm.DB) error { err := s.uow.ExecuteInTransaction(serviceCtx, func(tx *gorm.DB) error {

View File

@@ -16,17 +16,17 @@ type PlanService interface {
// CreatePlan 创建一个新的计划 // CreatePlan 创建一个新的计划
CreatePlan(ctx context.Context, req *dto.CreatePlanRequest) (*dto.PlanResponse, error) CreatePlan(ctx context.Context, req *dto.CreatePlanRequest) (*dto.PlanResponse, error)
// GetPlanByID 根据ID获取计划详情 // GetPlanByID 根据ID获取计划详情
GetPlanByID(ctx context.Context, id uint) (*dto.PlanResponse, error) GetPlanByID(ctx context.Context, id uint32) (*dto.PlanResponse, error)
// ListPlans 获取计划列表,支持过滤和分页 // ListPlans 获取计划列表,支持过滤和分页
ListPlans(ctx context.Context, query *dto.ListPlansQuery) (*dto.ListPlansResponse, error) ListPlans(ctx context.Context, query *dto.ListPlansQuery) (*dto.ListPlansResponse, error)
// UpdatePlan 更新计划 // 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 删除计划(软删除)
DeletePlan(ctx context.Context, id uint) error DeletePlan(ctx context.Context, id uint32) error
// StartPlan 启动计划 // StartPlan 启动计划
StartPlan(ctx context.Context, id uint) error StartPlan(ctx context.Context, id uint32) error
// StopPlan 停止计划 // StopPlan 停止计划
StopPlan(ctx context.Context, id uint) error StopPlan(ctx context.Context, id uint32) error
} }
// planService 是 PlanService 接口的实现 // planService 是 PlanService 接口的实现
@@ -77,7 +77,7 @@ func (s *planService) CreatePlan(ctx context.Context, req *dto.CreatePlanRequest
} }
// GetPlanByID 根据ID获取计划详情 // 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") serviceCtx, logger := logs.Trace(ctx, s.ctx, "GetPlanByID")
const actionType = "应用服务层:获取计划详情" const actionType = "应用服务层:获取计划详情"
@@ -135,7 +135,7 @@ func (s *planService) ListPlans(ctx context.Context, query *dto.ListPlansQuery)
} }
// UpdatePlan 更新计划 // 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") serviceCtx, logger := logs.Trace(ctx, s.ctx, "UpdatePlan")
const actionType = "应用服务层:更新计划" const actionType = "应用服务层:更新计划"
@@ -166,7 +166,7 @@ func (s *planService) UpdatePlan(ctx context.Context, id uint, req *dto.UpdatePl
} }
// DeletePlan 删除计划(软删除) // 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") serviceCtx, logger := logs.Trace(ctx, s.ctx, "DeletePlan")
const actionType = "应用服务层:删除计划" const actionType = "应用服务层:删除计划"
@@ -182,7 +182,7 @@ func (s *planService) DeletePlan(ctx context.Context, id uint) error {
} }
// StartPlan 启动计划 // 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") serviceCtx, logger := logs.Trace(ctx, s.ctx, "StartPlan")
const actionType = "应用服务层:启动计划" const actionType = "应用服务层:启动计划"
@@ -198,7 +198,7 @@ func (s *planService) StartPlan(ctx context.Context, id uint) error {
} }
// StopPlan 停止计划 // 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") serviceCtx, logger := logs.Trace(ctx, s.ctx, "StopPlan")
const actionType = "应用服务层:停止计划" const actionType = "应用服务层:停止计划"

View File

@@ -18,9 +18,9 @@ import (
// 该服务负责管理阈值告警任务的配置,并将其与计划进行联动。 // 该服务负责管理阈值告警任务的配置,并将其与计划进行联动。
type ThresholdAlarmService interface { type ThresholdAlarmService interface {
// SnoozeThresholdAlarm 忽略一个阈值告警,或更新其忽略时间。 // SnoozeThresholdAlarm 忽略一个阈值告警,或更新其忽略时间。
SnoozeThresholdAlarm(ctx context.Context, alarmID uint, durationMinutes uint) error SnoozeThresholdAlarm(ctx context.Context, alarmID uint32, durationMinutes uint32) error
// CancelSnoozeThresholdAlarm 取消对一个阈值告警的忽略状态。 // CancelSnoozeThresholdAlarm 取消对一个阈值告警的忽略状态。
CancelSnoozeThresholdAlarm(ctx context.Context, alarmID uint) error CancelSnoozeThresholdAlarm(ctx context.Context, alarmID uint32) error
// ListActiveAlarms 批量查询活跃告警。 // ListActiveAlarms 批量查询活跃告警。
ListActiveAlarms(ctx context.Context, req *dto.ListActiveAlarmRequest) (*dto.ListActiveAlarmResponse, error) ListActiveAlarms(ctx context.Context, req *dto.ListActiveAlarmRequest) (*dto.ListActiveAlarmResponse, error)
// ListHistoricalAlarms 批量查询历史告警。 // ListHistoricalAlarms 批量查询历史告警。
@@ -35,7 +35,7 @@ type ThresholdAlarmService interface {
// DeleteDeviceThresholdAlarm 删除一个设备阈值告警。 // DeleteDeviceThresholdAlarm 删除一个设备阈值告警。
DeleteDeviceThresholdAlarm(ctx context.Context, taskID int, req *dto.DeleteDeviceThresholdAlarmDTO) error DeleteDeviceThresholdAlarm(ctx context.Context, taskID int, req *dto.DeleteDeviceThresholdAlarmDTO) error
// DeleteDeviceThresholdAlarmByDeviceID 实现了根据设备ID删除一个设备下所有设备阈值告警的逻辑。 // DeleteDeviceThresholdAlarmByDeviceID 实现了根据设备ID删除一个设备下所有设备阈值告警的逻辑。
DeleteDeviceThresholdAlarmByDeviceID(ctx context.Context, deviceID uint) error DeleteDeviceThresholdAlarmByDeviceID(ctx context.Context, deviceID uint32) error
// CreateAreaThresholdAlarm 创建一个区域阈值告警。 // CreateAreaThresholdAlarm 创建一个区域阈值告警。
CreateAreaThresholdAlarm(ctx context.Context, req *dto.CreateAreaThresholdAlarmDTO) error CreateAreaThresholdAlarm(ctx context.Context, req *dto.CreateAreaThresholdAlarmDTO) error
@@ -46,7 +46,7 @@ type ThresholdAlarmService interface {
// DeleteAreaThresholdAlarm 实现了删除一个区域阈值告警的逻辑。 // DeleteAreaThresholdAlarm 实现了删除一个区域阈值告警的逻辑。
DeleteAreaThresholdAlarm(ctx context.Context, taskID int) error DeleteAreaThresholdAlarm(ctx context.Context, taskID int) error
// DeleteAreaThresholdAlarmByAreaControllerID 实现了根据区域ID删除一个区域下所有区域阈值告警的逻辑。 // DeleteAreaThresholdAlarmByAreaControllerID 实现了根据区域ID删除一个区域下所有区域阈值告警的逻辑。
DeleteAreaThresholdAlarmByAreaControllerID(ctx context.Context, areaControllerID uint) error DeleteAreaThresholdAlarmByAreaControllerID(ctx context.Context, areaControllerID uint32) error
} }
// thresholdAlarmService 是 ThresholdAlarmService 接口的具体实现。 // thresholdAlarmService 是 ThresholdAlarmService 接口的具体实现。
@@ -82,13 +82,13 @@ func NewThresholdAlarmService(ctx context.Context,
} }
// SnoozeThresholdAlarm 实现了忽略阈值告警的逻辑。 // 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") serviceCtx := logs.AddFuncName(ctx, s.ctx, "SnoozeThresholdAlarm")
return s.alarmService.SnoozeAlarm(serviceCtx, alarmID, time.Duration(durationMinutes)*time.Minute) return s.alarmService.SnoozeAlarm(serviceCtx, alarmID, time.Duration(durationMinutes)*time.Minute)
} }
// CancelSnoozeThresholdAlarm 实现了取消忽略阈值告警的逻辑。 // 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") serviceCtx := logs.AddFuncName(ctx, s.ctx, "CancelSnoozeThresholdAlarm")
return s.alarmService.CancelAlarmSnooze(serviceCtx, alarmID) return s.alarmService.CancelAlarmSnooze(serviceCtx, alarmID)
} }
@@ -169,7 +169,7 @@ func (s *thresholdAlarmService) CreateDeviceThresholdAlarm(ctx context.Context,
} }
case models.TaskTypeAreaCollectorThresholdCheck: // 向区域阈值检查任务过滤列表中添加该设备 case models.TaskTypeAreaCollectorThresholdCheck: // 向区域阈值检查任务过滤列表中添加该设备
params := task.AreaThresholdCheckParams{ params := task.AreaThresholdCheckParams{
ExcludeDeviceIDs: []uint{}, ExcludeDeviceIDs: []uint32{},
} }
err = t.ParseParameters(&params) err = t.ParseParameters(&params)
if err != nil { if err != nil {
@@ -375,7 +375,7 @@ func (s *thresholdAlarmService) DeleteDeviceThresholdAlarm(ctx context.Context,
} }
// DeleteDeviceThresholdAlarmByDeviceID 实现了根据设备ID删除一个设备下所有设备阈值告警的逻辑。 // 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") serviceCtx, logger := logs.Trace(ctx, s.ctx, "DeleteDeviceThresholdAlarmByDeviceID")
tasks, err := s.planRepo.ListTasksByDeviceID(serviceCtx, deviceID) tasks, err := s.planRepo.ListTasksByDeviceID(serviceCtx, deviceID)
if err != nil { if err != nil {
@@ -462,13 +462,13 @@ func (s *thresholdAlarmService) CreateAreaThresholdAlarm(ctx context.Context, re
if err != nil { if err != nil {
return fmt.Errorf("获取区域 %d 下的设备列表失败: %w", req.AreaControllerID, err) 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 { for _, device := range devicesInArea {
devicesInAreaMap[device.ID] = struct{}{} devicesInAreaMap[device.ID] = struct{}{}
} }
// 3. 遍历计划检查存在性并收集需要排除的设备ID // 3. 遍历计划检查存在性并收集需要排除的设备ID
var excludeDeviceIDs []uint var excludeDeviceIDs []uint32
for _, t := range plan.Tasks { for _, t := range plan.Tasks {
switch t.Type { switch t.Type {
case models.TaskTypeAreaCollectorThresholdCheck: case models.TaskTypeAreaCollectorThresholdCheck:
@@ -631,7 +631,7 @@ func (s *thresholdAlarmService) DeleteAreaThresholdAlarm(ctx context.Context, ta
} }
// DeleteAreaThresholdAlarmByAreaControllerID 实现了根据区域ID删除一个区域下所有区域阈值告警的逻辑。 // 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") serviceCtx, logger := logs.Trace(ctx, s.ctx, "DeleteAreaThresholdAlarmByAreaControllerID")
// 1. 获取系统健康检查计划 // 1. 获取系统健康检查计划

View File

@@ -18,7 +18,7 @@ import (
type UserService interface { type UserService interface {
CreateUser(ctx context.Context, req *dto.CreateUserRequest) (*dto.CreateUserResponse, error) CreateUser(ctx context.Context, req *dto.CreateUserRequest) (*dto.CreateUserResponse, error)
Login(ctx context.Context, req *dto.LoginRequest) (*dto.LoginResponse, 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 接口 // userService 实现了 UserService 接口
@@ -103,7 +103,7 @@ func (s *userService) Login(ctx context.Context, req *dto.LoginRequest) (*dto.Lo
} }
// SendTestNotification 发送测试通知 // 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") serviceCtx, logger := logs.Trace(ctx, s.ctx, "SendTestNotification")
err := s.notifyService.SendTestMessage(serviceCtx, userID, req.Type) err := s.notifyService.SendTestMessage(serviceCtx, userID, req.Type)
if err != nil { if err != nil {

View File

@@ -429,7 +429,7 @@ func (c *ChirpStackListener) handleIntegrationEvent(ctx context.Context, event *
// sensorDeviceID: 实际产生传感器数据的普通设备的ID // sensorDeviceID: 实际产生传感器数据的普通设备的ID
// sensorType: 传感器值的类型 (例如 models.SensorTypeTemperature) // sensorType: 传感器值的类型 (例如 models.SensorTypeTemperature)
// data: 具体的传感器数据结构体实例 (例如 models.TemperatureData) // 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") reqCtx, logger := logs.Trace(ctx, c.ctx, "recordSensorData")
// 1. 将传入的结构体序列化为 JSON // 1. 将传入的结构体序列化为 JSON
jsonData, err := json.Marshal(data) jsonData, err := json.Marshal(data)

View File

@@ -293,7 +293,7 @@ func (app *Application) cleanupStaleTasksAndLogs(ctx context.Context) error {
} }
// 2. 收集所有受影响的唯一 PlanID // 2. 收集所有受影响的唯一 PlanID
affectedPlanIDs := make(map[uint]struct{}) affectedPlanIDs := make(map[uint32]struct{})
for _, log := range incompletePlanLogs { for _, log := range incompletePlanLogs {
affectedPlanIDs[log.PlanID] = struct{}{} affectedPlanIDs[log.PlanID] = struct{}{}
} }

View File

@@ -21,15 +21,15 @@ type AlarmService interface {
// CloseAlarm 关闭一个活跃告警,将其归档到历史记录。 // CloseAlarm 关闭一个活跃告警,将其归档到历史记录。
// 如果指定的告警当前不活跃,则不执行任何操作并返回 nil。 // 如果指定的告警当前不活跃,则不执行任何操作并返回 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 忽略一个活跃告警,或更新其忽略时间。
// 如果告警不存在,将返回错误。 // 如果告警不存在,将返回错误。
SnoozeAlarm(ctx context.Context, alarmID uint, duration time.Duration) error SnoozeAlarm(ctx context.Context, alarmID uint32, duration time.Duration) error
// CancelAlarmSnooze 取消对一个告警的忽略状态。 // CancelAlarmSnooze 取消对一个告警的忽略状态。
// 如果告警不存在,或本就未被忽略,不执行任何操作并返回 nil。 // 如果告警不存在,或本就未被忽略,不执行任何操作并返回 nil。
CancelAlarmSnooze(ctx context.Context, alarmID uint) error CancelAlarmSnooze(ctx context.Context, alarmID uint32) error
} }
// alarmService 是 AlarmService 接口的具体实现。 // alarmService 是 AlarmService 接口的具体实现。
@@ -71,7 +71,7 @@ func (s *alarmService) CreateAlarmIfNotExists(ctx context.Context, newAlarm *mod
} }
// CloseAlarm 实现了关闭告警并将其归档的逻辑。 // 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") serviceCtx, logger := logs.Trace(ctx, s.ctx, "CloseAlarm")
// 1. 在事务外进行快速只读检查,避免不必要的事务开销 // 1. 在事务外进行快速只读检查,避免不必要的事务开销
@@ -133,7 +133,7 @@ func (s *alarmService) CloseAlarm(ctx context.Context, sourceType models.AlarmSo
} }
// SnoozeAlarm 忽略一个活跃告警,或更新其忽略时间。 // 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") serviceCtx, logger := logs.Trace(ctx, s.ctx, "SnoozeAlarm")
if duration <= 0 { if duration <= 0 {
@@ -156,7 +156,7 @@ func (s *alarmService) SnoozeAlarm(ctx context.Context, alarmID uint, duration t
} }
// CancelAlarmSnooze 取消对一个告警的忽略状态。 // 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") serviceCtx, logger := logs.Trace(ctx, s.ctx, "CancelAlarmSnooze")
err := s.alarmRepo.UpdateIgnoreStatus(serviceCtx, alarmID, false, nil) err := s.alarmRepo.UpdateIgnoreStatus(serviceCtx, alarmID, false, nil)

View File

@@ -28,7 +28,7 @@ type Service interface {
Switch(ctx context.Context, device *models.Device, action DeviceAction) error Switch(ctx context.Context, device *models.Device, action DeviceAction) error
// Collect 用于发起对指定区域主控下的多个设备的批量采集请求。 // Collect 用于发起对指定区域主控下的多个设备的批量采集请求。
Collect(ctx context.Context, areaControllerID uint, devicesToCollect []*models.Device) error Collect(ctx context.Context, areaControllerID uint32, devicesToCollect []*models.Device) error
} }
// 设备操作指令通用结构(最外层) // 设备操作指令通用结构(最外层)

View File

@@ -133,7 +133,7 @@ func (g *GeneralDeviceService) Switch(ctx context.Context, device *models.Device
} }
// Collect 实现了 Service 接口,用于发起对指定区域主控下的多个设备的批量采集请求。 // 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") serviceCtx, logger := logs.Trace(ctx, g.ctx, "Collect")
if len(devicesToCollect) == 0 { if len(devicesToCollect) == 0 {
logger.Info("待采集设备列表为空,无需执行采集任务。") logger.Info("待采集设备列表为空,无需执行采集任务。")
@@ -150,7 +150,7 @@ func (g *GeneralDeviceService) Collect(ctx context.Context, areaControllerID uin
} }
// 2. 准备采集任务列表 // 2. 准备采集任务列表
var childDeviceIDs []uint var childDeviceIDs []uint32
var collectTasks []*proto.CollectTask var collectTasks []*proto.CollectTask
for _, dev := range devicesToCollect { for _, dev := range devicesToCollect {

View File

@@ -16,13 +16,13 @@ import (
// Service 定义了通知领域的核心业务逻辑接口 // Service 定义了通知领域的核心业务逻辑接口
type Service interface { type Service interface {
// SendBatchAlarm 向一批用户发送告警通知。它会并发地为每个用户执行带故障转移的发送逻辑。 // SendBatchAlarm 向一批用户发送告警通知。它会并发地为每个用户执行带故障转移的发送逻辑。
SendBatchAlarm(ctx context.Context, userIDs []uint, content notify.AlarmContent) error SendBatchAlarm(ctx context.Context, userIDs []uint32, content notify.AlarmContent) error
// BroadcastAlarm 向所有用户发送告警通知。它会并发地为每个用户执行带故障转移的发送逻辑。 // BroadcastAlarm 向所有用户发送告警通知。它会并发地为每个用户执行带故障转移的发送逻辑。
BroadcastAlarm(ctx context.Context, content notify.AlarmContent) error BroadcastAlarm(ctx context.Context, content notify.AlarmContent) error
// SendTestMessage 向指定用户发送一条测试消息,用于手动验证特定通知渠道的配置。 // SendTestMessage 向指定用户发送一条测试消息,用于手动验证特定通知渠道的配置。
SendTestMessage(ctx context.Context, userID uint, notifierType models.NotifierType) error SendTestMessage(ctx context.Context, userID uint32, notifierType models.NotifierType) error
} }
// failoverService 是 Service 接口的实现,提供了故障转移功能 // failoverService 是 Service 接口的实现,提供了故障转移功能
@@ -32,7 +32,7 @@ type failoverService struct {
notifiers map[models.NotifierType]notify.Notifier notifiers map[models.NotifierType]notify.Notifier
primaryNotifier notify.Notifier primaryNotifier notify.Notifier
failureThreshold int 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 notificationRepo repository.NotificationRepository
} }
@@ -67,7 +67,7 @@ func NewFailoverService(
} }
// SendBatchAlarm 实现了向多个用户并发发送告警的功能 // 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") serviceCtx, logger := logs.Trace(ctx, s.ctx, "SendBatchAlarm")
var wg sync.WaitGroup var wg sync.WaitGroup
var mu sync.Mutex var mu sync.Mutex
@@ -77,7 +77,7 @@ func (s *failoverService) SendBatchAlarm(ctx context.Context, userIDs []uint, co
for _, userID := range userIDs { for _, userID := range userIDs {
wg.Add(1) wg.Add(1)
go func(id uint) { go func(id uint32) {
defer wg.Done() defer wg.Done()
if err := s.sendAlarmToUser(serviceCtx, id, content); err != nil { if err := s.sendAlarmToUser(serviceCtx, id, content); err != nil {
mu.Lock() mu.Lock()
@@ -108,7 +108,7 @@ func (s *failoverService) BroadcastAlarm(ctx context.Context, content notify.Ala
return fmt.Errorf("广播告警失败:查找所有用户时出错: %w", err) return fmt.Errorf("广播告警失败:查找所有用户时出错: %w", err)
} }
var userIDs []uint var userIDs []uint32
for _, user := range users { for _, user := range users {
userIDs = append(userIDs, user.ID) userIDs = append(userIDs, user.ID)
} }
@@ -119,7 +119,7 @@ func (s *failoverService) BroadcastAlarm(ctx context.Context, content notify.Ala
} }
// sendAlarmToUser 是为单个用户发送告警的内部方法,包含了完整的故障转移逻辑 // 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") serviceCtx, logger := logs.Trace(ctx, s.ctx, "sendAlarmToUser")
user, err := s.userRepo.FindByID(serviceCtx, userID) user, err := s.userRepo.FindByID(serviceCtx, userID)
if err != nil { if err != nil {
@@ -187,7 +187,7 @@ func (s *failoverService) sendAlarmToUser(ctx context.Context, userID uint, cont
} }
// SendTestMessage 实现了手动发送测试消息的功能 // 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") serviceCtx, logger := logs.Trace(ctx, s.ctx, "SendTestMessage")
user, err := s.userRepo.FindByID(serviceCtx, userID) user, err := s.userRepo.FindByID(serviceCtx, userID)
if err != nil { if err != nil {
@@ -261,7 +261,7 @@ func getAddressForNotifier(notifierType models.NotifierType, contact models.Cont
// err: 如果发送失败,记录的错误信息 // err: 如果发送失败,记录的错误信息
func (s *failoverService) recordNotificationAttempt( func (s *failoverService) recordNotificationAttempt(
ctx context.Context, ctx context.Context,
userID uint, userID uint32,
notifierType models.NotifierType, notifierType models.NotifierType,
content notify.AlarmContent, content notify.AlarmContent,
toAddress string, toAddress string,

View File

@@ -19,22 +19,22 @@ type PigPenTransferManager interface {
LogTransfer(ctx context.Context, tx *gorm.DB, log *models.PigTransferLog) error LogTransfer(ctx context.Context, tx *gorm.DB, log *models.PigTransferLog) error
// GetPenByID 用于获取猪栏的详细信息,供上层服务进行业务校验。 // 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 获取一个猪群当前关联的所有猪栏。
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 更新一个猪栏的指定字段。
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 通过汇总猪只迁移日志,计算给定猪栏中的当前猪只数量。
GetCurrentPigsInPen(ctx context.Context, tx *gorm.DB, penID uint) (int, error) GetCurrentPigsInPen(ctx context.Context, tx *gorm.DB, penID uint32) (int, error)
// GetTotalPigsInPensForBatchTx 计算指定猪群下所有猪栏的当前总存栏数 // 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 将猪栏的猪群归属移除,并将其状态标记为空闲。
ReleasePen(ctx context.Context, tx *gorm.DB, penID uint) error ReleasePen(ctx context.Context, tx *gorm.DB, penID uint32) error
} }
// pigPenTransferManager 是 PigPenTransferManager 接口的具体实现。 // pigPenTransferManager 是 PigPenTransferManager 接口的具体实现。
@@ -63,25 +63,25 @@ func (s *pigPenTransferManager) LogTransfer(ctx context.Context, tx *gorm.DB, lo
} }
// GetPenByID 实现了获取猪栏信息的逻辑。 // 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") managerCtx := logs.AddFuncName(ctx, s.ctx, "GetPenByID")
return s.penRepo.GetPenByIDTx(managerCtx, tx, penID) return s.penRepo.GetPenByIDTx(managerCtx, tx, penID)
} }
// GetPensByBatchID 实现了获取猪群关联猪栏列表的逻辑。 // 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") managerCtx := logs.AddFuncName(ctx, s.ctx, "GetPensByBatchID")
return s.penRepo.GetPensByBatchIDTx(managerCtx, tx, batchID) return s.penRepo.GetPensByBatchIDTx(managerCtx, tx, batchID)
} }
// UpdatePenFields 实现了更新猪栏字段的逻辑。 // 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") managerCtx := logs.AddFuncName(ctx, s.ctx, "UpdatePenFields")
return s.penRepo.UpdatePenFieldsTx(managerCtx, tx, penID, updates) return s.penRepo.UpdatePenFieldsTx(managerCtx, tx, penID, updates)
} }
// GetCurrentPigsInPen 实现了计算猪栏当前猪只数量的逻辑。 // 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") managerCtx := logs.AddFuncName(ctx, s.ctx, "GetCurrentPigsInPen")
// 1. 通过猪栏ID查出所属猪群信息 // 1. 通过猪栏ID查出所属猪群信息
pen, err := s.penRepo.GetPenByIDTx(managerCtx, tx, penID) pen, err := s.penRepo.GetPenByIDTx(managerCtx, tx, penID)
@@ -137,7 +137,7 @@ func (s *pigPenTransferManager) GetCurrentPigsInPen(ctx context.Context, tx *gor
// GetTotalPigsInPensForBatchTx 计算指定猪群下所有猪栏的当前总存栏数 // GetTotalPigsInPensForBatchTx 计算指定猪群下所有猪栏的当前总存栏数
// 该方法通过遍历猪群下的每个猪栏,并调用 GetCurrentPigsInPen 来累加存栏数。 // 该方法通过遍历猪群下的每个猪栏,并调用 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") managerCtx := logs.AddFuncName(ctx, s.ctx, "GetTotalPigsInPensForBatchTx")
// 1. 获取该批次下所有猪栏的列表 // 1. 获取该批次下所有猪栏的列表
pensInBatch, err := s.GetPensByBatchID(managerCtx, tx, batchID) pensInBatch, err := s.GetPensByBatchID(managerCtx, tx, batchID)
@@ -160,7 +160,7 @@ func (s *pigPenTransferManager) GetTotalPigsInPensForBatchTx(ctx context.Context
// ReleasePen 将猪栏的猪群归属移除,并将其状态标记为空闲。 // 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") managerCtx := logs.AddFuncName(ctx, s.ctx, "ReleasePen")
// 1. 获取猪栏信息 // 1. 获取猪栏信息
pen, err := s.penRepo.GetPenByIDTx(managerCtx, tx, penID) pen, err := s.penRepo.GetPenByIDTx(managerCtx, tx, penID)

View File

@@ -38,58 +38,58 @@ var (
// 它抽象了所有与猪批次相关的操作,使得应用层可以依赖于此接口,而不是具体的实现。 // 它抽象了所有与猪批次相关的操作,使得应用层可以依赖于此接口,而不是具体的实现。
type PigBatchService interface { type PigBatchService interface {
// CreatePigBatch 创建猪批次,并记录初始日志。 // 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 获取单个猪批次。
GetPigBatch(ctx context.Context, id uint) (*models.PigBatch, error) GetPigBatch(ctx context.Context, id uint32) (*models.PigBatch, error)
// UpdatePigBatch 更新猪批次信息。 // UpdatePigBatch 更新猪批次信息。
UpdatePigBatch(ctx context.Context, batch *models.PigBatch) (*models.PigBatch, error) UpdatePigBatch(ctx context.Context, batch *models.PigBatch) (*models.PigBatch, error)
// DeletePigBatch 删除猪批次,包含业务规则校验。 // DeletePigBatch 删除猪批次,包含业务规则校验。
DeletePigBatch(ctx context.Context, id uint) error DeletePigBatch(ctx context.Context, id uint32) error
// ListPigBatches 批量查询猪批次。 // ListPigBatches 批量查询猪批次。
ListPigBatches(ctx context.Context, isActive *bool) ([]*models.PigBatch, error) ListPigBatches(ctx context.Context, isActive *bool) ([]*models.PigBatch, error)
// AssignEmptyPensToBatch 为猪群分配空栏 // 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 将猪只从“虚拟库存”移入指定猪栏
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 连猪带栏,整体划拨到另一个猪群
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 将一个猪栏移除出猪群,此方法需要在猪栏为空的情况下执行。
RemoveEmptyPenFromBatch(ctx context.Context, batchID uint, penID uint) error RemoveEmptyPenFromBatch(ctx context.Context, batchID uint32, penID uint32) error
// GetCurrentPigQuantity 获取指定猪批次的当前猪只数量。 // GetCurrentPigQuantity 获取指定猪批次的当前猪只数量。
GetCurrentPigQuantity(ctx context.Context, batchID uint) (int, error) GetCurrentPigQuantity(ctx context.Context, batchID uint32) (int, error)
// GetCurrentPigsInPen 获取指定猪栏的当前存栏量。 // GetCurrentPigsInPen 获取指定猪栏的当前存栏量。
GetCurrentPigsInPen(ctx context.Context, penID uint) (int, error) GetCurrentPigsInPen(ctx context.Context, penID uint32) (int, error)
// GetTotalPigsInPensForBatch 获取指定猪群下所有猪栏的当前总存栏数 // 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 处理卖猪的业务逻辑。
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 处理买猪的业务逻辑。
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 TransferPigsAcrossBatches(ctx context.Context, sourceBatchID uint32, destBatchID uint32, fromPenID uint32, toPenID uint32, quantity uint32, operatorID uint32, remarks string) error
TransferPigsWithinBatch(ctx context.Context, batchID uint, fromPenID uint, toPenID uint, quantity uint, operatorID uint, remarks string) error TransferPigsWithinBatch(ctx context.Context, batchID uint32, fromPenID uint32, toPenID uint32, quantity uint32, operatorID uint32, remarks string) error
// --- 病猪管理相关方法 --- // --- 病猪管理相关方法 ---
// RecordSickPigs 记录新增病猪事件。 // 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 记录病猪康复事件。
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 记录病猪死亡事件。
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 记录病猪淘汰事件。
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 记录正常猪只死亡事件。
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 记录正常猪只淘汰事件。
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 接口的具体实现。 // pigBatchService 是 PigBatchService 接口的具体实现。

View File

@@ -15,7 +15,7 @@ import (
// --- 领域服务实现 --- // --- 领域服务实现 ---
// CreatePigBatch 实现了创建猪批次的逻辑,并同时创建初始批次日志。 // 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") serviceCtx := logs.AddFuncName(ctx, s.ctx, "CreatePigBatch")
// 业务规则可以在这里添加,例如检查批次号是否唯一等 // 业务规则可以在这里添加,例如检查批次号是否唯一等
@@ -57,7 +57,7 @@ func (s *pigBatchService) CreatePigBatch(ctx context.Context, operatorID uint, b
} }
// GetPigBatch 实现了获取单个猪批次的逻辑。 // 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") serviceCtx := logs.AddFuncName(ctx, s.ctx, "GetPigBatch")
batch, err := s.pigBatchRepo.GetPigBatchByID(serviceCtx, id) batch, err := s.pigBatchRepo.GetPigBatchByID(serviceCtx, id)
if err != nil { if err != nil {
@@ -84,7 +84,7 @@ func (s *pigBatchService) UpdatePigBatch(ctx context.Context, batch *models.PigB
} }
// DeletePigBatch 实现了删除猪批次的逻辑,并包含业务规则校验。 // 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") serviceCtx := logs.AddFuncName(ctx, s.ctx, "DeletePigBatch")
return s.uow.ExecuteInTransaction(serviceCtx, func(tx *gorm.DB) error { return s.uow.ExecuteInTransaction(serviceCtx, func(tx *gorm.DB) error {
// 1. 获取猪批次信息 // 1. 获取猪批次信息
@@ -135,7 +135,7 @@ func (s *pigBatchService) ListPigBatches(ctx context.Context, isActive *bool) ([
} }
// GetCurrentPigQuantity 实现了获取指定猪批次的当前猪只数量的逻辑。 // 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") serviceCtx := logs.AddFuncName(ctx, s.ctx, "GetCurrentPigQuantity")
var getErr error var getErr error
var quantity int var quantity int
@@ -150,7 +150,7 @@ func (s *pigBatchService) GetCurrentPigQuantity(ctx context.Context, batchID uin
} }
// getCurrentPigQuantityTx 实现了获取指定猪批次的当前猪只数量的逻辑。 // 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") serviceCtx := logs.AddFuncName(ctx, s.ctx, "getCurrentPigQuantityTx")
// 1. 获取猪批次初始信息 // 1. 获取猪批次初始信息
batch, err := s.pigBatchRepo.GetPigBatchByIDTx(serviceCtx, tx, batchID) 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 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") serviceCtx := logs.AddFuncName(ctx, s.ctx, "UpdatePigBatchQuantity")
return s.uow.ExecuteInTransaction(serviceCtx, func(tx *gorm.DB) error { return s.uow.ExecuteInTransaction(serviceCtx, func(tx *gorm.DB) error {
return s.updatePigBatchQuantityTx(serviceCtx, tx, operatorID, batchID, changeType, changeAmount, changeReason, happenedAt) 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") serviceCtx := logs.AddFuncName(ctx, s.ctx, "updatePigBatchQuantityTx")
lastLog, err := s.pigBatchLogRepo.GetLastLogByBatchIDTx(serviceCtx, tx, batchID) lastLog, err := s.pigBatchLogRepo.GetLastLogByBatchIDTx(serviceCtx, tx, batchID)
if err != nil { if err != nil {

View File

@@ -14,7 +14,7 @@ import (
) )
// executeTransferAndLog 是一个私有辅助方法,用于封装创建和记录迁移日志的通用逻辑。 // 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") serviceCtx := logs.AddFuncName(ctx, s.ctx, "executeTransferAndLog")
// 通用校验:任何调出操作都不能超过源猪栏的当前存栏数 // 通用校验:任何调出操作都不能超过源猪栏的当前存栏数
@@ -67,7 +67,7 @@ func (s *pigBatchService) executeTransferAndLog(ctx context.Context, tx *gorm.DB
} }
// TransferPigsWithinBatch 实现了同一个猪群内部的调栏业务。 // 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") serviceCtx := logs.AddFuncName(ctx, s.ctx, "TransferPigsWithinBatch")
if fromPenID == toPenID { if fromPenID == toPenID {
return errors.New("源猪栏和目标猪栏不能相同") return errors.New("源猪栏和目标猪栏不能相同")
@@ -106,7 +106,7 @@ func (s *pigBatchService) TransferPigsWithinBatch(ctx context.Context, batchID u
} }
// TransferPigsAcrossBatches 实现了跨猪群的调栏业务。 // 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") serviceCtx := logs.AddFuncName(ctx, s.ctx, "TransferPigsAcrossBatches")
if sourceBatchID == destBatchID { if sourceBatchID == destBatchID {
return errors.New("源猪群和目标猪群不能相同") return errors.New("源猪群和目标猪群不能相同")
@@ -167,7 +167,7 @@ func (s *pigBatchService) TransferPigsAcrossBatches(ctx context.Context, sourceB
} }
// AssignEmptyPensToBatch 为猪群分配空栏 // 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") serviceCtx := logs.AddFuncName(ctx, s.ctx, "AssignEmptyPensToBatch")
return s.uow.ExecuteInTransaction(serviceCtx, func(tx *gorm.DB) error { return s.uow.ExecuteInTransaction(serviceCtx, func(tx *gorm.DB) error {
// 1. 验证猪批次是否存在且活跃 // 1. 验证猪批次是否存在且活跃
@@ -204,6 +204,7 @@ func (s *pigBatchService) AssignEmptyPensToBatch(ctx context.Context, batchID ui
updates := map[string]interface{}{ updates := map[string]interface{}{
"pig_batch_id": &batchID, "pig_batch_id": &batchID,
"status": models.PenStatusOccupied, "status": models.PenStatusOccupied,
"operator_id": operatorID,
} }
if err := s.transferSvc.UpdatePenFields(serviceCtx, tx, penID, updates); err != nil { if err := s.transferSvc.UpdatePenFields(serviceCtx, tx, penID, updates); err != nil {
return fmt.Errorf("分配猪栏 %d 失败: %w", penID, err) return fmt.Errorf("分配猪栏 %d 失败: %w", penID, err)
@@ -215,7 +216,7 @@ func (s *pigBatchService) AssignEmptyPensToBatch(ctx context.Context, batchID ui
} }
// MovePigsIntoPen 将猪只从“虚拟库存”移入指定猪栏 // 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") serviceCtx := logs.AddFuncName(ctx, s.ctx, "MovePigsIntoPen")
if quantity <= 0 { if quantity <= 0 {
return errors.New("迁移数量必须大于零") return errors.New("迁移数量必须大于零")
@@ -287,7 +288,7 @@ func (s *pigBatchService) MovePigsIntoPen(ctx context.Context, batchID uint, toP
} }
// ReclassifyPenToNewBatch 连猪带栏,整体划拨到另一个猪群 // 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") serviceCtx := logs.AddFuncName(ctx, s.ctx, "ReclassifyPenToNewBatch")
if fromBatchID == toBatchID { if fromBatchID == toBatchID {
return errors.New("源猪群和目标猪群不能相同") 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") serviceCtx := logs.AddFuncName(ctx, s.ctx, "RemoveEmptyPenFromBatch")
return s.uow.ExecuteInTransaction(serviceCtx, func(tx *gorm.DB) error { return s.uow.ExecuteInTransaction(serviceCtx, func(tx *gorm.DB) error {
// 1. 检查猪批次是否存在且活跃 // 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") serviceCtx := logs.AddFuncName(ctx, s.ctx, "GetCurrentPigsInPen")
var currentPigs int var currentPigs int
err := s.uow.ExecuteInTransaction(serviceCtx, func(tx *gorm.DB) error { err := s.uow.ExecuteInTransaction(serviceCtx, func(tx *gorm.DB) error {
@@ -453,7 +454,7 @@ func (s *pigBatchService) GetCurrentPigsInPen(ctx context.Context, penID uint) (
} }
// GetTotalPigsInPensForBatch 实现了获取指定猪群下所有猪栏的当前总存栏数的逻辑。 // 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") serviceCtx := logs.AddFuncName(ctx, s.ctx, "GetTotalPigsInPensForBatch")
var totalPigs int var totalPigs int
err := s.uow.ExecuteInTransaction(serviceCtx, func(tx *gorm.DB) error { err := s.uow.ExecuteInTransaction(serviceCtx, func(tx *gorm.DB) error {

View File

@@ -13,7 +13,7 @@ import (
) )
// RecordSickPigs 记录新增病猪事件。 // 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") serviceCtx := logs.AddFuncName(ctx, s.ctx, "RecordSickPigs")
if quantity <= 0 { if quantity <= 0 {
return errors.New("新增病猪数量必须大于0") return errors.New("新增病猪数量必须大于0")
@@ -89,7 +89,7 @@ func (s *pigBatchService) RecordSickPigs(ctx context.Context, operatorID uint, b
} }
// RecordSickPigRecovery 记录病猪康复事件。 // 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") serviceCtx := logs.AddFuncName(ctx, s.ctx, "RecordSickPigRecovery")
if quantity <= 0 { if quantity <= 0 {
return errors.New("康复猪只数量必须大于0") return errors.New("康复猪只数量必须大于0")
@@ -158,7 +158,7 @@ func (s *pigBatchService) RecordSickPigRecovery(ctx context.Context, operatorID
} }
// RecordSickPigDeath 记录病猪死亡事件。 // 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") serviceCtx := logs.AddFuncName(ctx, s.ctx, "RecordSickPigDeath")
if quantity <= 0 { if quantity <= 0 {
return errors.New("死亡猪只数量必须大于0") return errors.New("死亡猪只数量必须大于0")
@@ -254,7 +254,7 @@ func (s *pigBatchService) RecordSickPigDeath(ctx context.Context, operatorID uin
} }
// RecordSickPigCull 记录病猪淘汰事件。 // 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") serviceCtx := logs.AddFuncName(ctx, s.ctx, "RecordSickPigCull")
if quantity <= 0 { if quantity <= 0 {
return errors.New("淘汰猪只数量必须大于0") return errors.New("淘汰猪只数量必须大于0")
@@ -350,7 +350,7 @@ func (s *pigBatchService) RecordSickPigCull(ctx context.Context, operatorID uint
} }
// RecordDeath 记录正常猪只死亡事件。 // 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") serviceCtx := logs.AddFuncName(ctx, s.ctx, "RecordDeath")
if quantity <= 0 { if quantity <= 0 {
return errors.New("死亡猪只数量必须大于0") return errors.New("死亡猪只数量必须大于0")
@@ -421,7 +421,7 @@ func (s *pigBatchService) RecordDeath(ctx context.Context, operatorID uint, batc
} }
// RecordCull 记录正常猪只淘汰事件。 // 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") serviceCtx := logs.AddFuncName(ctx, s.ctx, "RecordCull")
if quantity <= 0 { if quantity <= 0 {
return errors.New("淘汰猪只数量必须大于0") return errors.New("淘汰猪只数量必须大于0")

View File

@@ -13,7 +13,7 @@ import (
) )
// SellPigs 处理批量销售猪的业务逻辑。 // 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") serviceCtx := logs.AddFuncName(ctx, s.ctx, "SellPigs")
return s.uow.ExecuteInTransaction(serviceCtx, func(tx *gorm.DB) error { return s.uow.ExecuteInTransaction(serviceCtx, func(tx *gorm.DB) error {
if quantity <= 0 { if quantity <= 0 {
@@ -85,7 +85,7 @@ func (s *pigBatchService) SellPigs(ctx context.Context, batchID uint, penID uint
} }
// BuyPigs 处理批量购买猪的业务逻辑。 // 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") serviceCtx := logs.AddFuncName(ctx, s.ctx, "BuyPigs")
return s.uow.ExecuteInTransaction(serviceCtx, func(tx *gorm.DB) error { return s.uow.ExecuteInTransaction(serviceCtx, func(tx *gorm.DB) error {
if quantity <= 0 { if quantity <= 0 {

View File

@@ -21,7 +21,7 @@ type SickPigManager interface {
ProcessSickPigLog(ctx context.Context, tx *gorm.DB, log *models.PigSickLog) error ProcessSickPigLog(ctx context.Context, tx *gorm.DB, log *models.PigSickLog) error
// GetCurrentSickPigCount 获取指定批次当前患病猪只的总数 // 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 接口的具体实现。 // sickPigManager 是 SickPigManager 接口的具体实现。
@@ -122,7 +122,7 @@ func (s *sickPigManager) ProcessSickPigLog(ctx context.Context, tx *gorm.DB, log
return nil 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") managerCtx := logs.AddFuncName(ctx, s.ctx, "GetCurrentSickPigCount")
lastLog, err := s.sickLogRepo.GetLastLogByBatchTx(managerCtx, tx, batchID) lastLog, err := s.sickLogRepo.GetLastLogByBatchTx(managerCtx, tx, batchID)
if err != nil { if err != nil {

View File

@@ -18,10 +18,10 @@ type AnalysisPlanTaskManager interface {
Refresh(ctx context.Context) error Refresh(ctx context.Context) error
// CreateOrUpdateTrigger 为给定的 planID 创建其关联的触发任务。 // CreateOrUpdateTrigger 为给定的 planID 创建其关联的触发任务。
// 如果触发器已存在,会根据计划类型更新其执行时间。 // 如果触发器已存在,会根据计划类型更新其执行时间。
CreateOrUpdateTrigger(ctx context.Context, planID uint) error CreateOrUpdateTrigger(ctx context.Context, planID uint32) error
// EnsureAnalysisTaskDefinition 确保计划的分析任务定义存在于 tasks 表中。 // EnsureAnalysisTaskDefinition 确保计划的分析任务定义存在于 tasks 表中。
// 如果不存在,则会自动创建。此方法不涉及待执行队列。 // 如果不存在,则会自动创建。此方法不涉及待执行队列。
EnsureAnalysisTaskDefinition(ctx context.Context, planID uint) error EnsureAnalysisTaskDefinition(ctx context.Context, planID uint32) error
} }
// analysisPlanTaskManagerImpl 负责管理分析计划的触发器任务。 // analysisPlanTaskManagerImpl 负责管理分析计划的触发器任务。
@@ -82,7 +82,7 @@ func (m *analysisPlanTaskManagerImpl) Refresh(ctx context.Context) error {
// CreateOrUpdateTrigger 为给定的 planID 创建其关联的触发任务。 // 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") managerCtx, logger := logs.Trace(ctx, m.ctx, "CreateOrUpdateTrigger")
m.mu.Lock() m.mu.Lock()
defer m.mu.Unlock() defer m.mu.Unlock()
@@ -138,7 +138,7 @@ func (m *analysisPlanTaskManagerImpl) CreateOrUpdateTrigger(ctx context.Context,
// EnsureAnalysisTaskDefinition 确保计划的分析任务定义存在于 tasks 表中。 // 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") managerCtx, logger := logs.Trace(ctx, m.ctx, "EnsureAnalysisTaskDefinition")
m.mu.Lock() m.mu.Lock()
defer m.mu.Unlock() defer m.mu.Unlock()
@@ -170,7 +170,7 @@ func (m *analysisPlanTaskManagerImpl) EnsureAnalysisTaskDefinition(ctx context.C
// --- 内部私有方法 --- // --- 内部私有方法 ---
// getRefreshData 从数据库获取刷新所需的所有数据。 // 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") managerCtx, logger := logs.Trace(ctx, m.ctx, "getRefreshData")
runnablePlans, err = m.planRepo.FindRunnablePlans(managerCtx) runnablePlans, err = m.planRepo.FindRunnablePlans(managerCtx)
if err != nil { if err != nil {
@@ -183,7 +183,7 @@ func (m *analysisPlanTaskManagerImpl) getRefreshData(ctx context.Context) (runna
logger.Errorf("获取失效计划列表失败: %v", err) logger.Errorf("获取失效计划列表失败: %v", err)
return return
} }
invalidPlanIDs = make([]uint, len(invalidPlans)) invalidPlanIDs = make([]uint32, len(invalidPlans))
for i, p := range invalidPlans { for i, p := range invalidPlans {
invalidPlanIDs[i] = p.ID invalidPlanIDs[i] = p.ID
} }
@@ -197,19 +197,19 @@ func (m *analysisPlanTaskManagerImpl) getRefreshData(ctx context.Context) (runna
} }
// cleanupInvalidTasks 清理所有与失效计划相关的待执行任务。 // 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") managerCtx, logger := logs.Trace(ctx, m.ctx, "cleanupInvalidTasks")
if len(invalidPlanIDs) == 0 { if len(invalidPlanIDs) == 0 {
return nil // 没有需要清理的计划 return nil // 没有需要清理的计划
} }
invalidPlanIDSet := make(map[uint]struct{}, len(invalidPlanIDs)) invalidPlanIDSet := make(map[uint32]struct{}, len(invalidPlanIDs))
for _, id := range invalidPlanIDs { for _, id := range invalidPlanIDs {
invalidPlanIDSet[id] = struct{}{} invalidPlanIDSet[id] = struct{}{}
} }
var tasksToDeleteIDs []uint var tasksToDeleteIDs []uint32
var logsToCancelIDs []uint var logsToCancelIDs []uint32
for _, pt := range allPendingTasks { for _, pt := range allPendingTasks {
if pt.Task == nil { // 防御性编程,确保 Task 被预加载 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 { func (m *analysisPlanTaskManagerImpl) addOrUpdateTriggers(ctx context.Context, runnablePlans []*models.Plan, allPendingTasks []models.PendingTask) error {
managerCtx, logger := logs.Trace(ctx, m.ctx, "addOrUpdateTriggers") managerCtx, logger := logs.Trace(ctx, m.ctx, "addOrUpdateTriggers")
// 创建一个映射,存放所有已在队列中的计划触发器 // 创建一个映射,存放所有已在队列中的计划触发器
pendingTriggersMap := make(map[uint]models.PendingTask) pendingTriggersMap := make(map[uint32]models.PendingTask)
for _, pt := range allPendingTasks { for _, pt := range allPendingTasks {
if pt.Task != nil && pt.Task.Type == models.TaskPlanAnalysis { if pt.Task != nil && pt.Task.Type == models.TaskPlanAnalysis {
pendingTriggersMap[pt.Task.PlanID] = pt pendingTriggersMap[pt.Task.PlanID] = pt

View File

@@ -25,21 +25,21 @@ type ExecutionManager interface {
// ProgressTracker 仅用于在内存中提供计划执行的并发锁 // ProgressTracker 仅用于在内存中提供计划执行的并发锁
type ProgressTracker struct { type ProgressTracker struct {
mu sync.Mutex mu sync.Mutex
cond *sync.Cond // 用于实现阻塞锁 cond *sync.Cond // 用于实现阻塞锁
runningPlans map[uint]bool // key: planExecutionLogID, value: true (用作内存锁) runningPlans map[uint32]bool // key: planExecutionLogID, value: true (用作内存锁)
} }
// NewProgressTracker 创建一个新的进度跟踪器 // NewProgressTracker 创建一个新的进度跟踪器
func NewProgressTracker() *ProgressTracker { func NewProgressTracker() *ProgressTracker {
t := &ProgressTracker{ t := &ProgressTracker{
runningPlans: make(map[uint]bool), runningPlans: make(map[uint32]bool),
} }
t.cond = sync.NewCond(&t.mu) t.cond = sync.NewCond(&t.mu)
return t return t
} }
// TryLock (非阻塞) 尝试锁定一个计划。如果计划未被锁定,则锁定并返回 true。 // TryLock (非阻塞) 尝试锁定一个计划。如果计划未被锁定,则锁定并返回 true。
func (t *ProgressTracker) TryLock(planLogID uint) bool { func (t *ProgressTracker) TryLock(planLogID uint32) bool {
t.mu.Lock() t.mu.Lock()
defer t.mu.Unlock() defer t.mu.Unlock()
if t.runningPlans[planLogID] { if t.runningPlans[planLogID] {
@@ -50,7 +50,7 @@ func (t *ProgressTracker) TryLock(planLogID uint) bool {
} }
// Lock (阻塞) 获取一个计划的执行锁。如果锁已被占用,则会一直等待直到锁被释放。 // Lock (阻塞) 获取一个计划的执行锁。如果锁已被占用,则会一直等待直到锁被释放。
func (t *ProgressTracker) Lock(planLogID uint) { func (t *ProgressTracker) Lock(planLogID uint32) {
t.mu.Lock() t.mu.Lock()
// 当计划正在运行时,调用 t.cond.Wait() 会原子地解锁 mu 并挂起当前协程。 // 当计划正在运行时,调用 t.cond.Wait() 会原子地解锁 mu 并挂起当前协程。
// 当被唤醒时,它会重新锁定 mu 并再次检查循环条件。 // 当被唤醒时,它会重新锁定 mu 并再次检查循环条件。
@@ -63,7 +63,7 @@ func (t *ProgressTracker) Lock(planLogID uint) {
} }
// Unlock 解锁一个计划,并唤醒所有正在等待此锁的协程。 // Unlock 解锁一个计划,并唤醒所有正在等待此锁的协程。
func (t *ProgressTracker) Unlock(planLogID uint) { func (t *ProgressTracker) Unlock(planLogID uint32) {
t.mu.Lock() t.mu.Lock()
defer t.mu.Unlock() defer t.mu.Unlock()
delete(t.runningPlans, planLogID) delete(t.runningPlans, planLogID)
@@ -72,10 +72,10 @@ func (t *ProgressTracker) Unlock(planLogID uint) {
} }
// GetRunningPlanIDs 获取当前所有正在执行的计划ID列表 // GetRunningPlanIDs 获取当前所有正在执行的计划ID列表
func (t *ProgressTracker) GetRunningPlanIDs() []uint { func (t *ProgressTracker) GetRunningPlanIDs() []uint32 {
t.mu.Lock() t.mu.Lock()
defer t.mu.Unlock() defer t.mu.Unlock()
ids := make([]uint, 0, len(t.runningPlans)) ids := make([]uint32, 0, len(t.runningPlans))
for id := range t.runningPlans { for id := range t.runningPlans {
ids = append(ids, id) ids = append(ids, id)
} }
@@ -214,7 +214,7 @@ func (s *planExecutionManagerImpl) claimAndSubmit(ctx context.Context) {
} }
// handleRequeue 同步地、安全地将一个无法立即执行的任务放回队列。 // 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") managerCtx, logger := logs.Trace(ctx, s.ctx, "handleRequeue")
logger.Warnf("计划 %d 正在执行,任务 %d (TaskID: %d) 将等待并重新入队...", planExecutionLogID, taskToRequeue.ID, taskToRequeue.TaskID) logger.Warnf("计划 %d 正在执行,任务 %d (TaskID: %d) 将等待并重新入队...", planExecutionLogID, taskToRequeue.ID, taskToRequeue.TaskID)
@@ -308,7 +308,7 @@ func (s *planExecutionManagerImpl) analysisPlan(ctx context.Context, claimedLog
// 创建Plan执行记录 // 创建Plan执行记录
// 从任务的 Parameters 中解析出真实的 PlanID // 从任务的 Parameters 中解析出真实的 PlanID
var params struct { var params struct {
PlanID uint `json:"plan_id"` PlanID uint32 `json:"plan_id"`
} }
if err := claimedLog.Task.ParseParameters(&params); err != nil { if err := claimedLog.Task.ParseParameters(&params); err != nil {
logger.Errorf("解析任务参数中的计划ID失败日志ID: %d, 错误: %v", claimedLog.ID, err) logger.Errorf("解析任务参数中的计划ID失败日志ID: %d, 错误: %v", claimedLog.ID, err)
@@ -390,7 +390,7 @@ func (s *planExecutionManagerImpl) updateTaskExecutionLogStatus(ctx context.Cont
} }
// handlePlanTermination 集中处理计划的终止逻辑(失败或取消) // 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") managerCtx, logger := logs.Trace(ctx, s.ctx, "handlePlanTermination")
// 1. 从待执行队列中删除所有相关的子任务 // 1. 从待执行队列中删除所有相关的子任务
if err := s.pendingTaskRepo.DeletePendingTasksByPlanLogID(managerCtx, planLogID); err != nil { if err := s.pendingTaskRepo.DeletePendingTasksByPlanLogID(managerCtx, planLogID); err != nil {
@@ -434,7 +434,7 @@ func (s *planExecutionManagerImpl) handlePlanTermination(ctx context.Context, pl
} }
// handlePlanCompletion 集中处理计划成功完成后的所有逻辑 // 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") managerCtx, logger := logs.Trace(ctx, s.ctx, "handlePlanCompletion")
logger.Infof("计划执行 %d 的所有任务已完成,开始处理计划完成逻辑...", planLogID) logger.Infof("计划执行 %d 的所有任务已完成,开始处理计划完成逻辑...", planLogID)

View File

@@ -41,17 +41,17 @@ type Service interface {
// CreatePlan 创建一个新的计划 // CreatePlan 创建一个新的计划
CreatePlan(ctx context.Context, plan *models.Plan) (*models.Plan, error) CreatePlan(ctx context.Context, plan *models.Plan) (*models.Plan, error)
// GetPlanByID 根据ID获取计划详情 // GetPlanByID 根据ID获取计划详情
GetPlanByID(ctx context.Context, id uint) (*models.Plan, error) GetPlanByID(ctx context.Context, id uint32) (*models.Plan, error)
// ListPlans 获取计划列表,支持过滤和分页 // ListPlans 获取计划列表,支持过滤和分页
ListPlans(ctx context.Context, opts repository.ListPlansOptions, page, pageSize int) ([]models.Plan, int64, error) ListPlans(ctx context.Context, opts repository.ListPlansOptions, page, pageSize int) ([]models.Plan, int64, error)
// UpdatePlan 更新计划, wantPlanType 表示期望被修改的计划是什么类型 // UpdatePlan 更新计划, wantPlanType 表示期望被修改的计划是什么类型
UpdatePlan(ctx context.Context, plan *models.Plan, wantPlanType models.PlanType) (*models.Plan, error) UpdatePlan(ctx context.Context, plan *models.Plan, wantPlanType models.PlanType) (*models.Plan, error)
// DeletePlan 删除计划(软删除) // DeletePlan 删除计划(软删除)
DeletePlan(ctx context.Context, id uint) error DeletePlan(ctx context.Context, id uint32) error
// StartPlan 启动计划 // StartPlan 启动计划
StartPlan(ctx context.Context, id uint) error StartPlan(ctx context.Context, id uint32) error
// StopPlan 停止计划 // StopPlan 停止计划
StopPlan(ctx context.Context, id uint) error StopPlan(ctx context.Context, id uint32) error
} }
// planServiceImpl 是 Service 接口的具体实现。 // planServiceImpl 是 Service 接口的具体实现。
@@ -150,7 +150,7 @@ func (s *planServiceImpl) CreatePlan(ctx context.Context, planToCreate *models.P
// 优化无需查询完整的设备对象只需构建包含ID的结构体即可建立关联 // 优化无需查询完整的设备对象只需构建包含ID的结构体即可建立关联
devices := make([]models.Device, len(deviceIDs)) devices := make([]models.Device, len(deviceIDs))
for i, id := range 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 taskModel.Devices = devices
} }
@@ -174,7 +174,7 @@ func (s *planServiceImpl) CreatePlan(ctx context.Context, planToCreate *models.P
} }
// GetPlanByID 根据ID获取计划详情 // 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") planCtx, logger := logs.Trace(ctx, s.ctx, "GetPlanByID")
const actionType = "领域层:获取计划详情" const actionType = "领域层:获取计划详情"
@@ -262,7 +262,7 @@ func (s *planServiceImpl) UpdatePlan(ctx context.Context, planToUpdate *models.P
// 优化无需查询完整的设备对象只需构建包含ID的结构体即可建立关联 // 优化无需查询完整的设备对象只需构建包含ID的结构体即可建立关联
devices := make([]models.Device, len(deviceIDs)) devices := make([]models.Device, len(deviceIDs))
for i, id := range 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 taskModel.Devices = devices
} }
@@ -290,7 +290,7 @@ func (s *planServiceImpl) UpdatePlan(ctx context.Context, planToUpdate *models.P
} }
// DeletePlan 删除计划(软删除) // 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") planCtx, logger := logs.Trace(ctx, s.ctx, "DeletePlan")
const actionType = "领域层:删除计划" const actionType = "领域层:删除计划"
@@ -328,7 +328,7 @@ func (s *planServiceImpl) DeletePlan(ctx context.Context, id uint) error {
} }
// StartPlan 启动计划 // 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") planCtx, logger := logs.Trace(ctx, s.ctx, "StartPlan")
const actionType = "领域层:启动计划" const actionType = "领域层:启动计划"
@@ -383,7 +383,7 @@ func (s *planServiceImpl) StartPlan(ctx context.Context, id uint) error {
} }
// StopPlan 停止计划 // 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") planCtx, logger := logs.Trace(ctx, s.ctx, "StopPlan")
const actionType = "领域层:停止计划" const actionType = "领域层:停止计划"

View File

@@ -25,8 +25,8 @@ type Task interface {
// TaskDeviceIDResolver 定义了从任务配置中解析设备ID的方法 // TaskDeviceIDResolver 定义了从任务配置中解析设备ID的方法
type TaskDeviceIDResolver interface { type TaskDeviceIDResolver interface {
// ResolveDeviceIDs 从任务配置中解析并返回所有关联的设备ID列表 // ResolveDeviceIDs 从任务配置中解析并返回所有关联的设备ID列表
// 返回值: uint数组每个字符串代表一个设备ID // 返回值: uint32数组每个字符串代表一个设备ID
ResolveDeviceIDs(ctx context.Context) ([]uint, error) ResolveDeviceIDs(ctx context.Context) ([]uint32, error)
} }
// TaskFactory 是一个工厂接口,用于根据任务执行日志创建任务实例。 // TaskFactory 是一个工厂接口,用于根据任务执行日志创建任务实例。

View File

@@ -18,7 +18,7 @@ import (
// 如果用户没有指定某个等级的配置, 则默认为该等级消息只发送一次 // 如果用户没有指定某个等级的配置, 则默认为该等级消息只发送一次
type AlarmNotificationTaskParams struct { type AlarmNotificationTaskParams struct {
// NotificationIntervals 告警通知的发送间隔时间,键为告警等级,值为时间间隔(分钟) // NotificationIntervals 告警通知的发送间隔时间,键为告警等级,值为时间间隔(分钟)
NotificationIntervals map[models.SeverityLevel]uint `json:"notification_intervals"` NotificationIntervals map[models.SeverityLevel]uint32 `json:"notification_intervals"`
} }
// AlarmNotificationTask 告警通知发送任务 // AlarmNotificationTask 告警通知发送任务
@@ -107,9 +107,9 @@ func (t *AlarmNotificationTask) OnFailure(ctx context.Context, executeErr error)
} }
// ResolveDeviceIDs 从任务配置中解析并返回所有关联的设备ID列表 // 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 解析任务参数 // parseParameters 解析任务参数

View File

@@ -14,12 +14,12 @@ import (
// AreaThresholdCheckParams 定义了区域阈值检查任务的参数 // AreaThresholdCheckParams 定义了区域阈值检查任务的参数
type AreaThresholdCheckParams struct { type AreaThresholdCheckParams struct {
AreaControllerID uint `json:"area_controller_id"` // 区域主控ID AreaControllerID uint32 `json:"area_controller_id"` // 区域主控ID
SensorType models.SensorType `json:"sensor_type"` // 传感器类型 SensorType models.SensorType `json:"sensor_type"` // 传感器类型
Thresholds float32 `json:"thresholds"` // 阈值 Thresholds float32 `json:"thresholds"` // 阈值
Operator models.Operator `json:"operator"` // 操作符 Operator models.Operator `json:"operator"` // 操作符
Level models.SeverityLevel `json:"level"` // 告警级别 Level models.SeverityLevel `json:"level"` // 告警级别
ExcludeDeviceIDs []uint `json:"exclude_device_ids"` // 排除的传感器ID ExcludeDeviceIDs []uint32 `json:"exclude_device_ids"` // 排除的传感器ID
} }
// AreaThresholdCheckTask 是一个任务,用于检查区域阈值并触发告警, 区域主控下的所有没有独立校验任务的设备都会受到此任务的检查 // AreaThresholdCheckTask 是一个任务,用于检查区域阈值并触发告警, 区域主控下的所有没有独立校验任务的设备都会受到此任务的检查
@@ -62,7 +62,7 @@ func (a *AreaThresholdCheckTask) Execute(ctx context.Context) error {
} }
// 构建忽略设备ID的map方便快速查找 // 构建忽略设备ID的map方便快速查找
ignoredMap := make(map[uint]struct{}) ignoredMap := make(map[uint32]struct{})
for _, id := range a.params.ExcludeDeviceIDs { for _, id := range a.params.ExcludeDeviceIDs {
ignoredMap[id] = struct{}{} 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) 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") taskCtx := logs.AddFuncName(ctx, a.ctx, "ResolveDeviceIDs")
if err := a.parseParameters(taskCtx); err != nil { if err := a.parseParameters(taskCtx); err != nil {
return nil, err return nil, err
@@ -156,7 +156,7 @@ func (a *AreaThresholdCheckTask) parseParameters(ctx context.Context) error {
params.Level = models.WarnLevel params.Level = models.WarnLevel
} }
if params.ExcludeDeviceIDs == nil { if params.ExcludeDeviceIDs == nil {
params.ExcludeDeviceIDs = []uint{} params.ExcludeDeviceIDs = []uint32{}
} }
a.params = params a.params = params

View File

@@ -70,6 +70,6 @@ func (d *DelayTask) OnFailure(ctx context.Context, executeErr error) {
logger.Errorf("任务 %v: 执行失败: %v", d.executionTask.TaskID, executeErr) logger.Errorf("任务 %v: 执行失败: %v", d.executionTask.TaskID, executeErr)
} }
func (d *DelayTask) ResolveDeviceIDs(ctx context.Context) ([]uint, error) { func (d *DelayTask) ResolveDeviceIDs(ctx context.Context) ([]uint32, error) {
return []uint{}, nil return []uint32{}, nil
} }

View File

@@ -14,7 +14,7 @@ import (
) )
type DeviceThresholdCheckParams struct { type DeviceThresholdCheckParams struct {
DeviceID uint `json:"device_id"` // 设备ID DeviceID uint32 `json:"device_id"` // 设备ID
SensorType models.SensorType `json:"sensor_type"` // 传感器类型 SensorType models.SensorType `json:"sensor_type"` // 传感器类型
Thresholds float32 `json:"thresholds"` // 阈值 Thresholds float32 `json:"thresholds"` // 阈值
Operator models.Operator `json:"operator"` // 操作符 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) 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") taskCtx := logs.AddFuncName(ctx, d.ctx, "ResolveDeviceIDs")
if err := d.parseParameters(taskCtx); err != nil { if err := d.parseParameters(taskCtx); err != nil {
return nil, err return nil, err
} }
return []uint{d.params.DeviceID}, nil return []uint32{d.params.DeviceID}, nil
} }

View File

@@ -49,7 +49,7 @@ func (t *FullCollectionTask) Execute(ctx context.Context) error {
return nil return nil
} }
sensorsByController := make(map[uint][]*models.Device) sensorsByController := make(map[uint32][]*models.Device)
for _, sensor := range sensors { for _, sensor := range sensors {
sensorsByController[sensor.AreaControllerID] = append(sensorsByController[sensor.AreaControllerID], sensor) sensorsByController[sensor.AreaControllerID] = append(sensorsByController[sensor.AreaControllerID], sensor)
} }
@@ -97,7 +97,7 @@ func (t *FullCollectionTask) OnFailure(ctx context.Context, executeErr error) {
} }
// ResolveDeviceIDs 获取当前任务需要使用的设备ID列表 // 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
} }

View File

@@ -16,8 +16,8 @@ import (
// ReleaseFeedWeightTaskParams 定义了 ReleaseFeedWeightTask 的参数结构 // ReleaseFeedWeightTaskParams 定义了 ReleaseFeedWeightTask 的参数结构
type ReleaseFeedWeightTaskParams struct { type ReleaseFeedWeightTaskParams struct {
ReleaseWeight float32 `json:"release_weight"` // 需要释放的重量 ReleaseWeight float32 `json:"release_weight"` // 需要释放的重量
FeedPortDeviceID uint `json:"feed_port_device_id"` // 下料口ID FeedPortDeviceID uint32 `json:"feed_port_device_id"` // 下料口ID
MixingTankDeviceID uint `json:"mixing_tank_device_id"` // 称重传感器ID MixingTankDeviceID uint32 `json:"mixing_tank_device_id"` // 称重传感器ID
} }
// ReleaseFeedWeightTask 是一个控制下料口释放指定重量的任务 // ReleaseFeedWeightTask 是一个控制下料口释放指定重量的任务
@@ -30,7 +30,7 @@ type ReleaseFeedWeightTask struct {
feedPortDevice *models.Device feedPortDevice *models.Device
releaseWeight float32 releaseWeight float32
mixingTankDeviceID uint mixingTankDeviceID uint32
feedPort device.Service feedPort device.Service
@@ -178,10 +178,10 @@ func (r *ReleaseFeedWeightTask) OnFailure(ctx context.Context, executeErr error)
logger.Errorf("善后处理完成, 日志ID:%v", r.claimedLog.ID) 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") taskCtx := logs.AddFuncName(ctx, r.ctx, "ResolveDeviceIDs")
if err := r.parseParameters(taskCtx); err != nil { if err := r.parseParameters(taskCtx); err != nil {
return nil, err return nil, err
} }
return []uint{r.feedPortDevice.ID, r.mixingTankDeviceID}, nil return []uint32{r.feedPortDevice.ID, r.mixingTankDeviceID}, nil
} }

View File

@@ -209,19 +209,19 @@ type CollectionConfig struct {
type NotificationIntervalsConfig struct { type NotificationIntervalsConfig struct {
// DebugIntervalMinutes Debug级别告警的通知间隔分钟 // DebugIntervalMinutes Debug级别告警的通知间隔分钟
DebugIntervalMinutes uint `yaml:"debug"` DebugIntervalMinutes uint32 `yaml:"debug"`
// InfoIntervalMinutes Info级别告警的通知间隔分钟 // InfoIntervalMinutes Info级别告警的通知间隔分钟
InfoIntervalMinutes uint `yaml:"info"` InfoIntervalMinutes uint32 `yaml:"info"`
// WarnIntervalMinutes Warn级别告警的通知间隔分钟 // WarnIntervalMinutes Warn级别告警的通知间隔分钟
WarnIntervalMinutes uint `yaml:"warn"` WarnIntervalMinutes uint32 `yaml:"warn"`
// ErrorIntervalMinutes Error级别告警的通知间隔分钟 // ErrorIntervalMinutes Error级别告警的通知间隔分钟
ErrorIntervalMinutes uint `yaml:"error"` ErrorIntervalMinutes uint32 `yaml:"error"`
// DPanicIntervalMinutes DPanic级别告警的通知间隔分钟 // DPanicIntervalMinutes DPanic级别告警的通知间隔分钟
DPanicIntervalMinutes uint `yaml:"dpanic"` DPanicIntervalMinutes uint32 `yaml:"dpanic"`
// PanicIntervalMinutes Panic级别告警的通知间隔分钟 // PanicIntervalMinutes Panic级别告警的通知间隔分钟
PanicIntervalMinutes uint `yaml:"panic"` PanicIntervalMinutes uint32 `yaml:"panic"`
// FatalIntervalMinutes Fatal级别告警的通知间隔分钟 // FatalIntervalMinutes Fatal级别告警的通知间隔分钟
FatalIntervalMinutes uint `yaml:"fatal"` FatalIntervalMinutes uint32 `yaml:"fatal"`
} }
// AlarmNotificationConfig 告警通知配置 // AlarmNotificationConfig 告警通知配置

View File

@@ -2,8 +2,6 @@ package models
import ( import (
"time" "time"
"gorm.io/gorm"
) )
// AlarmSourceType 定义了告警的来源类型 // AlarmSourceType 定义了告警的来源类型
@@ -46,13 +44,13 @@ const (
) )
// ActiveAlarm 活跃告警 // ActiveAlarm 活跃告警
// 活跃告警会被更新(如忽略状态),因此保留 gorm.Model 以包含所有标准字段。 // 活跃告警会被更新(如忽略状态),因此保留 Model 以包含所有标准字段。
type ActiveAlarm struct { type ActiveAlarm struct {
gorm.Model Model
SourceType AlarmSourceType `gorm:"type:varchar(50);not null;index:idx_alarm_uniqueness;comment:告警来源类型" json:"source_type"` SourceType AlarmSourceType `gorm:"type:varchar(50);not null;index:idx_alarm_uniqueness;comment:告警来源类型" json:"source_type"`
// SourceID 告警来源ID其具体含义取决于 SourceType 字段 (例如设备ID, 区域主控ID, 猪栏ID)。 // 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 是一个机器可读的、标准化的告警类型标识。 // AlarmCode 是一个机器可读的、标准化的告警类型标识。
// 它与 SourceType 和 SourceID 共同构成一个活跃告警的唯一标识。 // 它与 SourceType 和 SourceID 共同构成一个活跃告警的唯一标识。
@@ -79,15 +77,15 @@ func (ActiveAlarm) TableName() string {
} }
// HistoricalAlarm 历史告警 // HistoricalAlarm 历史告警
// 历史告警是不可变归档数据,我们移除 gorm.Model并手动定义字段。 // 历史告警是不可变归档数据,我们移除 Model并手动定义字段。
// ID 和 TriggerTime 共同构成联合主键,以满足 TimescaleDB 超表的要求。 // ID 和 TriggerTime 共同构成联合主键,以满足 TimescaleDB 超表的要求。
type HistoricalAlarm struct { type HistoricalAlarm struct {
// 手动定义主键ID 仍然自增 // 手动定义主键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"` SourceType AlarmSourceType `gorm:"type:varchar(50);not null;index;comment:告警来源类型" json:"source_type"`
// SourceID 告警来源ID其具体含义取决于 SourceType 字段 (例如设备ID, 区域主控ID, 猪栏ID)。 // 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 AlarmCode `gorm:"type:varchar(100);not null;index;comment:告警代码" json:"alarm_code"` 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"` ResolveTime time.Time `gorm:"not null;comment:告警解决时间" json:"resolve_time"`
ResolveMethod string `gorm:"comment:告警解决方式" json:"resolve_method"` ResolveMethod string `gorm:"comment:告警解决方式" json:"resolve_method"`
// ResolvedBy 使用指针类型 *uint 来表示可为空解决人, 当字段为空时表示系统自动解决的 // ResolvedBy 使用指针类型 *uint32 来表示可为空解决人, 当字段为空时表示系统自动解决的
ResolvedBy *uint `gorm:"comment:告警解决人" json:"resolved_by"` ResolvedBy *uint32 `gorm:"comment:告警解决人" json:"resolved_by"`
} }
// TableName 指定 HistoricalAlarm 结构体对应的数据库表名 // TableName 指定 HistoricalAlarm 结构体对应的数据库表名

View File

@@ -6,7 +6,6 @@ import (
"strings" "strings"
"gorm.io/datatypes" "gorm.io/datatypes"
"gorm.io/gorm"
) )
// --- Properties 结构体定义 --- // --- Properties 结构体定义 ---
@@ -19,7 +18,7 @@ type Bus485Properties struct {
// AreaController 是一个LoRa转总线(如485)的通信网关 // AreaController 是一个LoRa转总线(如485)的通信网关
type AreaController struct { type AreaController struct {
gorm.Model Model
// Name 是主控的业务名称,例如 "1号猪舍主控" // Name 是主控的业务名称,例如 "1号猪舍主控"
Name string `gorm:"not null;unique" json:"name"` Name string `gorm:"not null;unique" json:"name"`
@@ -53,20 +52,20 @@ func (AreaController) TableName() string {
// Device 代表系统中的所有普通设备 // Device 代表系统中的所有普通设备
type Device struct { type Device struct {
// gorm.Model 内嵌了标准模型字段 (ID, CreatedAt, UpdatedAt, DeletedAt) // Model 内嵌了标准模型字段 (ID, CreatedAt, UpdatedAt, DeletedAt)
gorm.Model Model
// Name 是设备的业务名称,应清晰可读,例如 "1号猪舍温度传感器" // Name 是设备的业务名称,应清晰可读,例如 "1号猪舍温度传感器"
Name string `gorm:"not null" json:"name"` Name string `gorm:"not null" json:"name"`
// DeviceTemplateID 是设备模板的外键 // DeviceTemplateID 是设备模板的外键
DeviceTemplateID uint `gorm:"not null;index" json:"device_template_id"` DeviceTemplateID uint32 `gorm:"not null;index" json:"device_template_id"`
// DeviceTemplate 是设备的模板,包含了设备的通用信息 // DeviceTemplate 是设备的模板,包含了设备的通用信息
DeviceTemplate DeviceTemplate `json:"device_template"` DeviceTemplate DeviceTemplate `json:"device_template"`
// AreaControllerID 是区域主控的外键 // AreaControllerID 是区域主控的外键
AreaControllerID uint `gorm:"not null;index" json:"area_controller_id"` AreaControllerID uint32 `gorm:"not null;index" json:"area_controller_id"`
// AreaController 是设备所属的区域主控 // AreaController 是设备所属的区域主控
AreaController AreaController `json:"area_controller"` AreaController AreaController `json:"area_controller"`

View File

@@ -6,7 +6,6 @@ import (
"fmt" "fmt"
"gorm.io/datatypes" "gorm.io/datatypes"
"gorm.io/gorm"
) )
// ModbusFunctionCode 定义Modbus功能码的枚举类型 // ModbusFunctionCode 定义Modbus功能码的枚举类型
@@ -106,7 +105,7 @@ func (sc *SensorCommands) SelfCheck() error {
// DeviceTemplate 代表一种物理设备的类型。 // DeviceTemplate 代表一种物理设备的类型。
type DeviceTemplate struct { type DeviceTemplate struct {
gorm.Model Model
// Name 是此模板的唯一名称, 例如 "FanModel-XYZ-2000" 或 "TempSensor-T1" // Name 是此模板的唯一名称, 例如 "FanModel-XYZ-2000" 或 "TempSensor-T1"
Name string `gorm:"not null;unique" json:"name"` Name string `gorm:"not null;unique" json:"name"`

View File

@@ -27,12 +27,12 @@ const (
// PlanExecutionLog 记录整个计划的一次执行历史 // PlanExecutionLog 记录整个计划的一次执行历史
type PlanExecutionLog struct { type PlanExecutionLog struct {
ID uint `gorm:"primaryKey"` ID uint32 `gorm:"primaryKey"`
CreatedAt time.Time `gorm:"primaryKey"` // 作为联合主键方便只查询热点数据 CreatedAt time.Time `gorm:"primaryKey"` // 作为联合主键方便只查询热点数据
UpdatedAt time.Time UpdatedAt time.Time
DeletedAt gorm.DeletedAt `gorm:"index"` DeletedAt gorm.DeletedAt `gorm:"index"`
PlanID uint `gorm:"index"` PlanID uint32 `gorm:"index"`
Status ExecutionStatus Status ExecutionStatus
StartedAt time.Time StartedAt time.Time
EndedAt time.Time EndedAt time.Time
@@ -46,12 +46,12 @@ func (PlanExecutionLog) TableName() string {
// TaskExecutionLog 记录单个任务的一次执行历史 // TaskExecutionLog 记录单个任务的一次执行历史
type TaskExecutionLog struct { type TaskExecutionLog struct {
ID uint `gorm:"primaryKey"` ID uint32 `gorm:"primaryKey"`
CreatedAt time.Time `gorm:"primaryKey"` // 作为联合主键方便只查询热点数据 CreatedAt time.Time `gorm:"primaryKey"` // 作为联合主键方便只查询热点数据
UpdatedAt time.Time UpdatedAt time.Time
DeletedAt gorm.DeletedAt `gorm:"index"` DeletedAt gorm.DeletedAt `gorm:"index"`
PlanExecutionLogID uint `gorm:"index"` // 关联到某次计划执行 PlanExecutionLogID uint32 `gorm:"index"` // 关联到某次计划执行
// TaskID 使用 int 类型以容纳特殊的负数ID代表系统任务 // TaskID 使用 int 类型以容纳特殊的负数ID代表系统任务
TaskID int `gorm:"index"` TaskID int `gorm:"index"`
@@ -106,7 +106,7 @@ type DeviceCommandLog struct {
// DeviceID 是接收此下行任务的设备的ID。 // DeviceID 是接收此下行任务的设备的ID。
// 对于 LoRaWAN这通常是区域主控设备的ID。 // 对于 LoRaWAN这通常是区域主控设备的ID。
DeviceID uint `gorm:"not null;index" json:"device_id"` DeviceID uint32 `gorm:"not null;index" json:"device_id"`
// SentAt 记录下行任务最初发送的时间。 // SentAt 记录下行任务最初发送的时间。
SentAt time.Time `gorm:"primaryKey" json:"sent_at"` SentAt time.Time `gorm:"primaryKey" json:"sent_at"`
@@ -133,7 +133,7 @@ type PendingCollection struct {
// DeviceID 是接收此任务的设备ID // DeviceID 是接收此任务的设备ID
// 对于 LoRaWAN这通常是区域主控设备的ID。 // 对于 LoRaWAN这通常是区域主控设备的ID。
DeviceID uint `gorm:"index"` DeviceID uint32 `gorm:"index"`
// CommandMetadata 存储了此次采集任务对应的设备ID列表顺序与设备响应值的顺序一致。 // CommandMetadata 存储了此次采集任务对应的设备ID列表顺序与设备响应值的顺序一致。
CommandMetadata UintArray `gorm:"type:bigint[]"` CommandMetadata UintArray `gorm:"type:bigint[]"`
@@ -183,13 +183,13 @@ func (a AuditContextKey) String() string {
// UserActionLog 记录用户的操作历史,用于审计 // UserActionLog 记录用户的操作历史,用于审计
type UserActionLog struct { type UserActionLog struct {
// 用 ID 和 Time 组成复合主键, 防止高并发时时间重复 // 用 ID 和 Time 组成复合主键, 防止高并发时时间重复
ID uint `gorm:"primaryKey"` ID uint32 `gorm:"primaryKey"`
// Time 是操作发生的时间,作为主键和超表的时间分区键 // Time 是操作发生的时间,作为主键和超表的时间分区键
Time time.Time `gorm:"primaryKey" json:"time"` Time time.Time `gorm:"primaryKey" json:"time"`
// --- Who (谁) --- // --- Who (谁) ---
UserID uint `gorm:"not null" json:"user_id,omitempty"` UserID uint32 `gorm:"not null" json:"user_id,omitempty"`
Username string `json:"username,omitempty"` // 操作发生时用户名的快照 Username string `json:"username,omitempty"` // 操作发生时用户名的快照
// --- Where (何地) --- // --- Where (何地) ---

View File

@@ -1,16 +1,12 @@
package models package models
import (
"gorm.io/gorm"
)
/* /*
猪场固定资产相关模型 猪场固定资产相关模型
*/ */
// PigHouse 定义了猪舍,是猪栏的集合 // PigHouse 定义了猪舍,是猪栏的集合
type PigHouse struct { type PigHouse struct {
gorm.Model Model
Name string `gorm:"size:100;not null;unique;comment:猪舍名称, 如 '育肥舍A栋'"` Name string `gorm:"size:100;not null;unique;comment:猪舍名称, 如 '育肥舍A栋'"`
Description string `gorm:"size:255;comment:描述信息"` Description string `gorm:"size:255;comment:描述信息"`
Pens []Pen `gorm:"foreignKey:HouseID"` // 一个猪舍包含多个猪栏 Pens []Pen `gorm:"foreignKey:HouseID"` // 一个猪舍包含多个猪栏
@@ -30,10 +26,10 @@ const (
// Pen 是猪栏的物理实体模型, 是所有空间相关数据的“锚点” // Pen 是猪栏的物理实体模型, 是所有空间相关数据的“锚点”
type Pen struct { type Pen struct {
gorm.Model Model
PenNumber string `gorm:"not null;comment:猪栏的唯一编号, 如 A-01"` PenNumber string `gorm:"not null;comment:猪栏的唯一编号, 如 A-01"`
HouseID uint `gorm:"index;comment:所属猪舍ID"` HouseID uint32 `gorm:"index;comment:所属猪舍ID"`
PigBatchID *uint `gorm:"index;comment:关联的猪批次ID"` PigBatchID *uint32 `gorm:"index;comment:关联的猪批次ID"`
Capacity int `gorm:"not null;comment:设计容量 (头)"` Capacity int `gorm:"not null;comment:设计容量 (头)"`
Status PenStatus `gorm:"not null;index;comment:猪栏当前状态"` Status PenStatus `gorm:"not null;index;comment:猪栏当前状态"`
} }

View File

@@ -2,8 +2,6 @@ package models
import ( import (
"time" "time"
"gorm.io/gorm"
) )
/* /*
@@ -13,7 +11,7 @@ import (
// RawMaterial 代表饲料的原料。 // RawMaterial 代表饲料的原料。
// 建议:所有重量单位统一存储 (例如, 全部使用 'g'),便于计算和避免转换错误。 // 建议:所有重量单位统一存储 (例如, 全部使用 'g'),便于计算和避免转换错误。
type RawMaterial struct { type RawMaterial struct {
gorm.Model Model
Name string `gorm:"size:100;unique;not null;comment:原料名称"` Name string `gorm:"size:100;unique;not null;comment:原料名称"`
Description string `gorm:"size:255;comment:描述"` Description string `gorm:"size:255;comment:描述"`
Quantity float32 `gorm:"not null;comment:库存总量, 单位: g"` Quantity float32 `gorm:"not null;comment:库存总量, 单位: g"`
@@ -25,8 +23,8 @@ func (RawMaterial) TableName() string {
// RawMaterialPurchase 记录了原料的每一次采购。 // RawMaterialPurchase 记录了原料的每一次采购。
type RawMaterialPurchase struct { type RawMaterialPurchase struct {
gorm.Model Model
RawMaterialID uint `gorm:"not null;index;comment:关联的原料ID"` RawMaterialID uint32 `gorm:"not null;index;comment:关联的原料ID"`
RawMaterial RawMaterial `gorm:"foreignKey:RawMaterialID"` RawMaterial RawMaterial `gorm:"foreignKey:RawMaterialID"`
Supplier string `gorm:"size:100;comment:供应商"` Supplier string `gorm:"size:100;comment:供应商"`
Amount float32 `gorm:"not null;comment:采购数量, 单位: g"` Amount float32 `gorm:"not null;comment:采购数量, 单位: g"`
@@ -54,11 +52,11 @@ const (
// RawMaterialStockLog 记录了原料库存的所有变动,提供了完整的追溯链。 // RawMaterialStockLog 记录了原料库存的所有变动,提供了完整的追溯链。
type RawMaterialStockLog struct { type RawMaterialStockLog struct {
gorm.Model Model
RawMaterialID uint `gorm:"not null;index;comment:关联的原料ID"` RawMaterialID uint32 `gorm:"not null;index;comment:关联的原料ID"`
ChangeAmount float32 `gorm:"not null;comment:变动数量, 正数为入库, 负数为出库"` ChangeAmount float32 `gorm:"not null;comment:变动数量, 正数为入库, 负数为出库"`
SourceType StockLogSourceType `gorm:"size:50;not null;index;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:业务发生时间"` HappenedAt time.Time `gorm:"primaryKey;comment:业务发生时间"`
Remarks string `gorm:"comment:备注, 如主动领取的理由等"` Remarks string `gorm:"comment:备注, 如主动领取的理由等"`
} }
@@ -70,7 +68,7 @@ func (RawMaterialStockLog) TableName() string {
// FeedFormula 代表饲料配方。 // FeedFormula 代表饲料配方。
// 对于没有配方的外购饲料,可以将其视为一种特殊的 RawMaterial, 并为其创建一个仅包含它自己的 FeedFormula。 // 对于没有配方的外购饲料,可以将其视为一种特殊的 RawMaterial, 并为其创建一个仅包含它自己的 FeedFormula。
type FeedFormula struct { type FeedFormula struct {
gorm.Model Model
Name string `gorm:"size:100;unique;not null;comment:配方名称"` Name string `gorm:"size:100;unique;not null;comment:配方名称"`
Description string `gorm:"size:255;comment:描述"` Description string `gorm:"size:255;comment:描述"`
Components []FeedFormulaComponent `gorm:"foreignKey:FeedFormulaID"` Components []FeedFormulaComponent `gorm:"foreignKey:FeedFormulaID"`
@@ -82,9 +80,9 @@ func (FeedFormula) TableName() string {
// FeedFormulaComponent 代表配方中的一种原料及其占比。 // FeedFormulaComponent 代表配方中的一种原料及其占比。
type FeedFormulaComponent struct { type FeedFormulaComponent struct {
gorm.Model Model
FeedFormulaID uint `gorm:"not null;index;comment:外键到 FeedFormula"` FeedFormulaID uint32 `gorm:"not null;index;comment:外键到 FeedFormula"`
RawMaterialID uint `gorm:"not null;index;comment:外键到 RawMaterial"` RawMaterialID uint32 `gorm:"not null;index;comment:外键到 RawMaterial"`
RawMaterial RawMaterial `gorm:"foreignKey:RawMaterialID"` RawMaterial RawMaterial `gorm:"foreignKey:RawMaterialID"`
Percentage float32 `gorm:"not null;comment:该原料在配方中的百分比 (0-1.0)"` Percentage float32 `gorm:"not null;comment:该原料在配方中的百分比 (0-1.0)"`
} }
@@ -97,14 +95,14 @@ func (FeedFormulaComponent) TableName() string {
// 应用层逻辑:当一条使用记录被创建时,应根据其使用的 FeedFormula, // 应用层逻辑:当一条使用记录被创建时,应根据其使用的 FeedFormula,
// 计算出每种 RawMaterial 的消耗量,并在 RawMaterialStockLog 中创建对应的出库记录。 // 计算出每种 RawMaterial 的消耗量,并在 RawMaterialStockLog 中创建对应的出库记录。
type FeedUsageRecord struct { type FeedUsageRecord struct {
gorm.Model Model
PenID uint `gorm:"not null;index;comment:关联的猪栏ID"` PenID uint32 `gorm:"not null;index;comment:关联的猪栏ID"`
Pen Pen `gorm:"foreignKey:PenID"` 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"` FeedFormula FeedFormula `gorm:"foreignKey:FeedFormulaID"`
Amount float32 `gorm:"not null;comment:使用数量, 单位: g"` Amount float32 `gorm:"not null;comment:使用数量, 单位: g"`
RecordedAt time.Time `gorm:"primaryKey;comment:记录时间"` RecordedAt time.Time `gorm:"primaryKey;comment:记录时间"`
OperatorID uint `gorm:"not null;comment:操作员"` OperatorID uint32 `gorm:"not null;comment:操作员"`
Remarks string `gorm:"comment:备注, 如 '例行喂料, 弱猪补料' 等"` Remarks string `gorm:"comment:备注, 如 '例行喂料, 弱猪补料' 等"`
} }

View File

@@ -4,7 +4,6 @@ import (
"time" "time"
"gorm.io/datatypes" "gorm.io/datatypes"
"gorm.io/gorm"
) )
/* /*
@@ -57,7 +56,7 @@ type PowderInstructions struct {
// Medication 定义了兽药/疫苗的基本信息模型 // Medication 定义了兽药/疫苗的基本信息模型
type Medication struct { type Medication struct {
gorm.Model Model
Name string `gorm:"size:100;not null;comment:药品名称" json:"name"` Name string `gorm:"size:100;not null;comment:药品名称" json:"name"`
Type MedicationType `gorm:"size:20;not null;comment:兽药类型 (粉剂, 针剂, 疫苗)" json:"type"` Type MedicationType `gorm:"size:20;not null;comment:兽药类型 (粉剂, 针剂, 疫苗)" json:"type"`
Category MedicationCategory `gorm:"size:30;not null;comment:兽药种类 (四环素类, 磺胺类等)" json:"category"` Category MedicationCategory `gorm:"size:30;not null;comment:兽药种类 (四环素类, 磺胺类等)" json:"category"`
@@ -82,15 +81,15 @@ const (
// MedicationLog 记录了对整个猪批次的用药情况 // MedicationLog 记录了对整个猪批次的用药情况
type MedicationLog struct { type MedicationLog struct {
gorm.Model Model
PigBatchID uint `gorm:"not null;index;comment:关联的猪批次ID"` PigBatchID uint32 `gorm:"not null;index;comment:关联的猪批次ID"`
MedicationID uint `gorm:"not null;index;comment:关联的药品ID"` MedicationID uint32 `gorm:"not null;index;comment:关联的药品ID"`
Medication Medication `gorm:"foreignKey:MedicationID"` // 预加载药品信息 Medication Medication `gorm:"foreignKey:MedicationID"` // 预加载药品信息
DosageUsed float32 `gorm:"not null;comment:使用的总剂量 (单位由药品决定,如g或ml)"` DosageUsed float32 `gorm:"not null;comment:使用的总剂量 (单位由药品决定,如g或ml)"`
TargetCount int `gorm:"not null;comment:用药对象数量"` TargetCount int `gorm:"not null;comment:用药对象数量"`
Reason MedicationReasonType `gorm:"size:20;not null;comment:用药原因"` Reason MedicationReasonType `gorm:"size:20;not null;comment:用药原因"`
Description string `gorm:"size:255;comment:具体描述,如'治疗呼吸道病'"` Description string `gorm:"size:255;comment:具体描述,如'治疗呼吸道病'"`
OperatorID uint `gorm:"comment:操作员ID"` OperatorID uint32 `gorm:"comment:操作员ID"`
HappenedAt time.Time `gorm:"primaryKey;comment:用药时间"` HappenedAt time.Time `gorm:"primaryKey;comment:用药时间"`
} }

View File

@@ -6,10 +6,20 @@ import (
"fmt" "fmt"
"strconv" "strconv"
"strings" "strings"
"time"
"go.uber.org/zap/zapcore" "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 返回一个包含所有数据库模型实例的切片。 // GetAllModels 返回一个包含所有数据库模型实例的切片。
// 这个函数用于在数据库初始化时自动迁移所有的表结构。 // 这个函数用于在数据库初始化时自动迁移所有的表结构。
func GetAllModels() []interface{} { func GetAllModels() []interface{} {
@@ -72,10 +82,10 @@ func GetAllModels() []interface{} {
} }
} }
// UintArray 是一个自定义类型,代表 uint 的切片。 // UintArray 是一个自定义类型,代表 uint32 的切片。
// 它实现了 gorm.Scanner 和 driver.Valuer 接口, // 它实现了 gorm.Scanner 和 driver.Valuer 接口,
// 以便能与数据库的 bigint[] 类型进行原生映射。 // 以便能与数据库的 bigint[] 类型进行原生映射。
type UintArray []uint type UintArray []uint32
// Value 实现了 driver.Valuer 接口。 // Value 实现了 driver.Valuer 接口。
// 它告诉 GORM 如何将 UintArray ([]) 转换为数据库能够理解的格式。 // 它告诉 GORM 如何将 UintArray ([]) 转换为数据库能够理解的格式。
@@ -117,19 +127,19 @@ func (a *UintArray) Scan(src interface{}) error {
// 去掉花括号 // 去掉花括号
srcStr = strings.Trim(srcStr, "{}") srcStr = strings.Trim(srcStr, "{}")
if srcStr == "" { if srcStr == "" {
*a = []uint{} *a = []uint32{}
return nil return nil
} }
// 按逗号分割 // 按逗号分割
parts := strings.Split(srcStr, ",") parts := strings.Split(srcStr, ",")
arr := make([]uint, len(parts)) arr := make([]uint32, len(parts))
for i, p := range parts { for i, p := range parts {
val, err := strconv.ParseUint(p, 10, 64) val, err := strconv.ParseUint(p, 10, 64)
if err != nil { if err != nil {
return fmt.Errorf("解析 UintArray 元素失败: %w", err) return fmt.Errorf("解析 UintArray 元素失败: %w", err)
} }
arr[i] = uint(val) arr[i] = uint32(val)
} }
*a = arr *a = arr

View File

@@ -2,8 +2,6 @@ package models
import ( import (
"time" "time"
"gorm.io/gorm"
) )
// NotifierType 定义了通知器的类型。 // NotifierType 定义了通知器的类型。
@@ -31,12 +29,12 @@ const (
// Notification 表示已发送或尝试发送的通知记录。 // Notification 表示已发送或尝试发送的通知记录。
type Notification struct { type Notification struct {
gorm.Model Model
// NotifierType 通知器类型 (例如:"邮件", "企业微信", "飞书", "日志") // NotifierType 通知器类型 (例如:"邮件", "企业微信", "飞书", "日志")
NotifierType NotifierType `gorm:"type:varchar(20);not null;index" json:"notifier_type"` NotifierType NotifierType `gorm:"type:varchar(20);not null;index" json:"notifier_type"`
// UserID 接收通知的用户ID用于追溯通知记录到特定用户 // UserID 接收通知的用户ID用于追溯通知记录到特定用户
UserID uint `gorm:"index" json:"user_id"` // 增加 UserID 字段,并添加索引 UserID uint32 `gorm:"index" json:"user_id"` // 增加 UserID 字段,并添加索引
// Title 通知标题 // Title 通知标题
Title string `gorm:"type:varchar(255);not null" json:"title"` Title string `gorm:"type:varchar(255);not null" json:"title"`
// Message 通知内容 // Message 通知内容

View File

@@ -2,8 +2,6 @@ package models
import ( import (
"time" "time"
"gorm.io/gorm"
) )
/* /*
@@ -32,7 +30,7 @@ const (
// PigBatch 是猪批次的核心模型,代表了一群被共同管理的猪 // PigBatch 是猪批次的核心模型,代表了一群被共同管理的猪
type PigBatch struct { type PigBatch struct {
gorm.Model Model
BatchNumber string `gorm:"size:50;not null;uniqueIndex;comment:批次编号,如 2024-W25-A01"` BatchNumber string `gorm:"size:50;not null;uniqueIndex;comment:批次编号,如 2024-W25-A01"`
OriginType PigBatchOriginType `gorm:"size:20;not null;comment:批次来源 (自繁, 外购)"` OriginType PigBatchOriginType `gorm:"size:20;not null;comment:批次来源 (自繁, 外购)"`
StartDate time.Time `gorm:"not null;comment:批次开始日期 (如转入日或购买日)"` StartDate time.Time `gorm:"not null;comment:批次开始日期 (如转入日或购买日)"`
@@ -65,14 +63,14 @@ const (
// PigBatchLog 记录了猪批次数量或状态的每一次变更 // PigBatchLog 记录了猪批次数量或状态的每一次变更
type PigBatchLog struct { type PigBatchLog struct {
gorm.Model Model
PigBatchID uint `gorm:"not null;index;comment:关联的猪批次ID"` PigBatchID uint32 `gorm:"not null;index;comment:关联的猪批次ID"`
ChangeType LogChangeType `gorm:"size:20;not null;comment:变更类型"` ChangeType LogChangeType `gorm:"size:20;not null;comment:变更类型"`
ChangeCount int `gorm:"not null;comment:数量变化,负数表示减少"` ChangeCount int `gorm:"not null;comment:数量变化,负数表示减少"`
Reason string `gorm:"size:255;comment:变更原因描述"` Reason string `gorm:"size:255;comment:变更原因描述"`
BeforeCount int `gorm:"not null;comment:变更前总数"` BeforeCount int `gorm:"not null;comment:变更前总数"`
AfterCount 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:事件发生时间"` HappenedAt time.Time `gorm:"primaryKey;comment:事件发生时间"`
} }
@@ -82,10 +80,10 @@ func (PigBatchLog) TableName() string {
// WeighingBatch 记录了一次批次称重的信息 // WeighingBatch 记录了一次批次称重的信息
type WeighingBatch struct { type WeighingBatch struct {
gorm.Model Model
WeighingTime time.Time `gorm:"primaryKey;comment:称重时间"` WeighingTime time.Time `gorm:"primaryKey;comment:称重时间"`
Description string `gorm:"size:255;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 { func (WeighingBatch) TableName() string {
@@ -94,11 +92,11 @@ func (WeighingBatch) TableName() string {
// WeighingRecord 记录了单次称重信息 // WeighingRecord 记录了单次称重信息
type WeighingRecord struct { type WeighingRecord struct {
gorm.Model Model
Weight float32 `gorm:"not null;comment:单只猪重量 (kg)"` Weight float32 `gorm:"not null;comment:单只猪重量 (kg)"`
WeighingBatchID uint `gorm:"not null;index;comment:关联的批次称重ID"` WeighingBatchID uint32 `gorm:"not null;index;comment:关联的批次称重ID"`
PenID uint `gorm:"not null;index;comment:所在猪圈ID"` PenID uint32 `gorm:"not null;index;comment:所在猪圈ID"`
OperatorID uint `gorm:"not null;comment:操作员ID"` OperatorID uint32 `gorm:"not null;comment:操作员ID"`
Remark string `gorm:"size:255;comment:备注"` Remark string `gorm:"size:255;comment:备注"`
WeighingTime time.Time `gorm:"primaryKey;comment:称重时间"` WeighingTime time.Time `gorm:"primaryKey;comment:称重时间"`
} }

View File

@@ -2,8 +2,6 @@ package models
import ( import (
"time" "time"
"gorm.io/gorm"
) )
// PigBatchSickPigTreatmentLocation 定义了病猪治疗地点 // PigBatchSickPigTreatmentLocation 定义了病猪治疗地点
@@ -29,16 +27,16 @@ const (
// PigSickLog 记录了猪批次中病猪数量的变化日志 // PigSickLog 记录了猪批次中病猪数量的变化日志
type PigSickLog struct { type PigSickLog struct {
gorm.Model Model
PigBatchID uint `gorm:"primaryKey;comment:关联的猪批次ID"` PigBatchID uint32 `gorm:"primaryKey;comment:关联的猪批次ID"`
PenID uint `gorm:"not null;index;comment:所在猪圈ID"` PenID uint32 `gorm:"not null;index;comment:所在猪圈ID"`
ChangeCount int `gorm:"not null;comment:变化数量, 正数表示新增, 负数表示移除"` ChangeCount int `gorm:"not null;comment:变化数量, 正数表示新增, 负数表示移除"`
Reason PigBatchSickPigReasonType `gorm:"size:20;not null;comment:变化原因 (如: 患病, 康复, 死亡, 转入, 转出, 其他)"` Reason PigBatchSickPigReasonType `gorm:"size:20;not null;comment:变化原因 (如: 患病, 康复, 死亡, 转入, 转出, 其他)"`
BeforeCount int `gorm:"comment:变化前的数量"` BeforeCount int `gorm:"comment:变化前的数量"`
AfterCount int `gorm:"comment:变化后的数量"` AfterCount int `gorm:"comment:变化后的数量"`
Remarks string `gorm:"size:255;comment:备注"` Remarks string `gorm:"size:255;comment:备注"`
TreatmentLocation PigBatchSickPigTreatmentLocation `gorm:"size:50;comment:治疗地点"` TreatmentLocation PigBatchSickPigTreatmentLocation `gorm:"size:50;comment:治疗地点"`
OperatorID uint `gorm:"comment:操作员ID"` OperatorID uint32 `gorm:"comment:操作员ID"`
HappenedAt time.Time `gorm:"primaryKey;comment:事件发生时间"` HappenedAt time.Time `gorm:"primaryKey;comment:事件发生时间"`
} }

View File

@@ -2,21 +2,19 @@ package models
import ( import (
"time" "time"
"gorm.io/gorm"
) )
// PigPurchase 记录了猪只采购信息 // PigPurchase 记录了猪只采购信息
type PigPurchase struct { type PigPurchase struct {
gorm.Model Model
PigBatchID uint `gorm:"not null;index;comment:关联的猪批次ID"` PigBatchID uint32 `gorm:"not null;index;comment:关联的猪批次ID"`
PurchaseDate time.Time `gorm:"primaryKey;comment:采购日期"` PurchaseDate time.Time `gorm:"primaryKey;comment:采购日期"`
Supplier string `gorm:"comment:供应商"` Supplier string `gorm:"comment:供应商"`
Quantity int `gorm:"not null;comment:采购数量"` Quantity int `gorm:"not null;comment:采购数量"`
UnitPrice float32 `gorm:"not null;comment:单价"` UnitPrice float32 `gorm:"not null;comment:单价"`
TotalPrice float32 `gorm:"not null;comment:总价"` TotalPrice float32 `gorm:"not null;comment:总价"`
Remarks string `gorm:"size:255;comment:备注"` Remarks string `gorm:"size:255;comment:备注"`
OperatorID uint `gorm:"comment:操作员ID"` OperatorID uint32 `gorm:"comment:操作员ID"`
} }
func (PigPurchase) TableName() string { func (PigPurchase) TableName() string {
@@ -25,15 +23,15 @@ func (PigPurchase) TableName() string {
// PigSale 记录了猪只销售信息 // PigSale 记录了猪只销售信息
type PigSale struct { type PigSale struct {
gorm.Model Model
PigBatchID uint `gorm:"not null;index;comment:关联的猪批次ID"` PigBatchID uint32 `gorm:"not null;index;comment:关联的猪批次ID"`
SaleDate time.Time `gorm:"primaryKey;comment:销售日期"` SaleDate time.Time `gorm:"primaryKey;comment:销售日期"`
Buyer string `gorm:"comment:购买方"` Buyer string `gorm:"comment:购买方"`
Quantity int `gorm:"not null;comment:销售数量"` Quantity int `gorm:"not null;comment:销售数量"`
UnitPrice float32 `gorm:"not null;comment:单价"` UnitPrice float32 `gorm:"not null;comment:单价"`
TotalPrice float32 `gorm:"not null;comment:总价"` TotalPrice float32 `gorm:"not null;comment:总价"`
Remarks string `gorm:"size:255;comment:备注"` Remarks string `gorm:"size:255;comment:备注"`
OperatorID uint `gorm:"comment:操作员ID"` OperatorID uint32 `gorm:"comment:操作员ID"`
} }
func (PigSale) TableName() string { func (PigSale) TableName() string {

View File

@@ -2,8 +2,6 @@ package models
import ( import (
"time" "time"
"gorm.io/gorm"
) )
// PigTransferType 定义了猪只迁移的类型 // PigTransferType 定义了猪只迁移的类型
@@ -23,14 +21,14 @@ const (
// PigTransferLog 记录了每一次猪只数量在猪栏间的变动事件。 // PigTransferLog 记录了每一次猪只数量在猪栏间的变动事件。
// 它作为事件溯源的基础,用于推算任意时间点猪栏的猪只数量。 // 它作为事件溯源的基础,用于推算任意时间点猪栏的猪只数量。
type PigTransferLog struct { type PigTransferLog struct {
gorm.Model Model
TransferTime time.Time `gorm:"primaryKey;comment:迁移发生时间" json:"transfer_time"` // 迁移发生时间,作为联合主键 TransferTime time.Time `gorm:"primaryKey;comment:迁移发生时间" json:"transfer_time"` // 迁移发生时间,作为联合主键
PigBatchID uint `gorm:"primaryKey;comment:关联的猪群ID" json:"pig_batch_id"` // 关联的猪群ID作为联合主键 PigBatchID uint32 `gorm:"primaryKey;comment:关联的猪群ID" json:"pig_batch_id"` // 关联的猪群ID作为联合主键
PenID uint `gorm:"primaryKey;comment:发生变动的猪栏ID" json:"pen_id"` // 发生变动的猪栏ID作为联合主键 PenID uint32 `gorm:"primaryKey;comment:发生变动的猪栏ID" json:"pen_id"` // 发生变动的猪栏ID作为联合主键
Quantity int `gorm:"not null;comment:变动数量(正数表示增加,负数表示减少)" json:"quantity"` // 变动数量(正数表示增加,负数减少) Quantity int `gorm:"not null;comment:变动数量(正数表示增加,负数表示减少)" json:"quantity"` // 变动数量(正数表示增加,负数减少)
Type PigTransferType `gorm:"not null;comment:变动类型" json:"type"` // 变动类型,使用枚举类型 Type PigTransferType `gorm:"not null;comment:变动类型" json:"type"` // 变动类型,使用枚举类型
CorrelationID string `gorm:"comment:用于关联一次完整操作(如一次调栏会产生两条日志)" json:"correlation_id"` // 用于关联一次完整操作 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"` Remarks string `gorm:"comment:备注" json:"remarks"`
} }

View File

@@ -74,15 +74,15 @@ const (
// Plan 代表系统中的一个计划,可以包含子计划或任务 // Plan 代表系统中的一个计划,可以包含子计划或任务
type Plan struct { type Plan struct {
gorm.Model Model
Name PlanName `gorm:"not null" json:"name"` Name PlanName `gorm:"not null" json:"name"`
Description string `json:"description"` Description string `json:"description"`
PlanType PlanType `gorm:"not null;index" json:"plan_type"` // 任务类型, 包括系统任务和用户自定义任务 PlanType PlanType `gorm:"not null;index" json:"plan_type"` // 任务类型, 包括系统任务和用户自定义任务
ExecutionType PlanExecutionType `gorm:"not null;index" json:"execution_type"` ExecutionType PlanExecutionType `gorm:"not null;index" json:"execution_type"`
Status PlanStatus `gorm:"default:'已禁用';index" json:"status"` // 计划是否被启动 Status PlanStatus `gorm:"default:'已禁用';index" json:"status"` // 计划是否被启动
ExecuteNum uint `gorm:"default:0" json:"execute_num"` // 计划预期执行次数 ExecuteNum uint32 `gorm:"default:0" json:"execute_num"` // 计划预期执行次数
ExecuteCount uint `gorm:"default:0" json:"execute_count"` // 执行计数器 ExecuteCount uint32 `gorm:"default:0" json:"execute_count"` // 执行计数器
// 针对 PlanExecutionTypeAutomatic使用 Cron 表达式定义调度规则 // 针对 PlanExecutionTypeAutomatic使用 Cron 表达式定义调度规则
CronExpression string `json:"cron_expression"` CronExpression string `json:"cron_expression"`
@@ -163,12 +163,12 @@ func (p *Plan) ReorderSteps() {
// SubPlan 代表作为另一个计划一部分的子计划,具有执行顺序 // SubPlan 代表作为另一个计划一部分的子计划,具有执行顺序
type SubPlan struct { type SubPlan struct {
gorm.Model Model
ParentPlanID uint `gorm:"not null;index" json:"parent_plan_id"` // 父计划的ID ParentPlanID uint32 `gorm:"not null;index" json:"parent_plan_id"` // 父计划的ID
ChildPlanID uint `gorm:"not null;index" json:"child_plan_id"` // 子计划的ID (它本身也是一个 Plan) ChildPlanID uint32 `gorm:"not null;index" json:"child_plan_id"` // 子计划的ID (它本身也是一个 Plan)
ExecutionOrder int `gorm:"not null" json:"execution_order"` // 在父计划中的执行顺序 ExecutionOrder int `gorm:"not null" json:"execution_order"` // 在父计划中的执行顺序
ChildPlan *Plan `gorm:"-" json:"child_plan"` // 完整子计划数据,仅内存中 ChildPlan *Plan `gorm:"-" json:"child_plan"` // 完整子计划数据,仅内存中
} }
// TableName 自定义 GORM 使用的数据库表名 // TableName 自定义 GORM 使用的数据库表名
@@ -184,7 +184,7 @@ type Task struct {
UpdatedAt time.Time UpdatedAt time.Time
DeletedAt gorm.DeletedAt `gorm:"index"` // 保持软删除功能 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"` Name string `gorm:"not null" json:"name"`
Description string `json:"description"` Description string `json:"description"`
ExecutionOrder int `gorm:"not null" json:"execution_order"` // 在计划中的执行顺序 ExecutionOrder int `gorm:"not null" json:"execution_order"` // 在计划中的执行顺序
@@ -229,9 +229,9 @@ func (t *Task) SaveParameters(v interface{}) error {
// DeviceTask 是设备和任务之间的关联模型,表示一个设备可以执行多个任务,一个任务可以被多个设备执行。 // DeviceTask 是设备和任务之间的关联模型,表示一个设备可以执行多个任务,一个任务可以被多个设备执行。
type DeviceTask struct { type DeviceTask struct {
gorm.Model Model
DeviceID uint `gorm:"not null;index"` // 设备ID DeviceID uint32 `gorm:"not null;index"` // 设备ID
TaskID uint `gorm:"not null;index"` // 任务ID TaskID uint32 `gorm:"not null;index"` // 任务ID
// 可选:如果需要存储关联的额外信息,可以在这里添加字段,例如: // 可选:如果需要存储关联的额外信息,可以在这里添加字段,例如:
// Configuration datatypes.JSON `json:"configuration"` // 任务在特定设备上的配置 // Configuration datatypes.JSON `json:"configuration"` // 任务在特定设备上的配置

View File

@@ -7,8 +7,8 @@ import (
// PendingTask 是一个待执行任务队列, 里面会储存待执行的Task以及这个Task什么时候执行 // PendingTask 是一个待执行任务队列, 里面会储存待执行的Task以及这个Task什么时候执行
// 它是一个纯粹的工作队列,任务被认领后即被删除。 // 它是一个纯粹的工作队列,任务被认领后即被删除。
type PendingTask struct { type PendingTask struct {
// 手动填充必须字段以实现硬删除,不内嵌 gorm.Model // 手动填充必须字段以实现硬删除,不内嵌 Model
ID uint `gorm:"primarykey"` ID uint32 `gorm:"primarykey"`
CreatedAt time.Time CreatedAt time.Time
UpdatedAt time.Time UpdatedAt time.Time
@@ -21,7 +21,7 @@ type PendingTask struct {
Task *Task `gorm:"foreignKey:TaskID"` Task *Task `gorm:"foreignKey:TaskID"`
ExecuteAt time.Time `gorm:"index"` // 任务执行时间 ExecuteAt time.Time `gorm:"index"` // 任务执行时间
TaskExecutionLogID uint `gorm:"unique;not null;index"` // 对应的执行历史记录ID TaskExecutionLogID uint32 `gorm:"unique;not null;index"` // 对应的执行历史记录ID
// 通过 TaskExecutionLogID 关联到唯一的 TaskExecutionLog 记录 // 通过 TaskExecutionLogID 关联到唯一的 TaskExecutionLog 记录
// ON DELETE CASCADE 确保如果日志被删除,这个待办任务也会被自动清理 // ON DELETE CASCADE 确保如果日志被删除,这个待办任务也会被自动清理

View File

@@ -55,10 +55,10 @@ type SensorData struct {
Time time.Time `gorm:"primaryKey" json:"time"` Time time.Time `gorm:"primaryKey" json:"time"`
// DeviceID 是传感器的唯一标识符,作为复合主键的另一部分。 // DeviceID 是传感器的唯一标识符,作为复合主键的另一部分。
DeviceID uint `gorm:"primaryKey" json:"device_id"` DeviceID uint32 `gorm:"primaryKey" json:"device_id"`
// AreaControllerID 是上报此数据的区域主控的ID。 // AreaControllerID 是上报此数据的区域主控的ID。
AreaControllerID uint `json:"area_controller_id"` AreaControllerID uint32 `json:"area_controller_id"`
// SensorType 是传感数据的类型 // SensorType 是传感数据的类型
SensorType SensorType `gorm:"not null;index" json:"sensor_type"` SensorType SensorType `gorm:"not null;index" json:"sensor_type"`

View File

@@ -38,9 +38,9 @@ func (ci ContactInfo) Value() (driver.Value, error) {
// User 代表系统中的用户模型 // User 代表系统中的用户模型
type User struct { type User struct {
// gorm.Model 内嵌了 ID, CreatedAt, UpdatedAt, 和 DeletedAt // Model 内嵌了 ID, CreatedAt, UpdatedAt, 和 DeletedAt
// DeletedAt 字段的存在自动为 GORM 开启了软删除模式 // DeletedAt 字段的存在自动为 GORM 开启了软删除模式
gorm.Model Model
// Username 是用户的登录名,应该是唯一的 // Username 是用户的登录名,应该是唯一的
// 修正了 gorm 标签的拼写错误 (移除了 gorm 后面的冒号) // 修正了 gorm 标签的拼写错误 (移除了 gorm 后面的冒号)

View File

@@ -15,7 +15,7 @@ import (
// ActiveAlarmListOptions 定义了查询活跃告警列表时的可选参数 // ActiveAlarmListOptions 定义了查询活跃告警列表时的可选参数
type ActiveAlarmListOptions struct { type ActiveAlarmListOptions struct {
SourceType *models.AlarmSourceType // 按告警来源类型过滤 SourceType *models.AlarmSourceType // 按告警来源类型过滤
SourceID *uint // 按告警来源ID过滤 SourceID *uint32 // 按告警来源ID过滤
Level *models.SeverityLevel // 按告警严重性等级过滤 Level *models.SeverityLevel // 按告警严重性等级过滤
IsIgnored *bool // 按是否被忽略过滤 IsIgnored *bool // 按是否被忽略过滤
TriggerTime *time.Time // 告警触发时间范围 - 开始时间 TriggerTime *time.Time // 告警触发时间范围 - 开始时间
@@ -26,7 +26,7 @@ type ActiveAlarmListOptions struct {
// HistoricalAlarmListOptions 定义了查询历史告警列表时的可选参数 // HistoricalAlarmListOptions 定义了查询历史告警列表时的可选参数
type HistoricalAlarmListOptions struct { type HistoricalAlarmListOptions struct {
SourceType *models.AlarmSourceType // 按告警来源类型过滤 SourceType *models.AlarmSourceType // 按告警来源类型过滤
SourceID *uint // 按告警来源ID过滤 SourceID *uint32 // 按告警来源ID过滤
Level *models.SeverityLevel // 按告警严重性等级过滤 Level *models.SeverityLevel // 按告警严重性等级过滤
TriggerTimeStart *time.Time // 告警触发时间范围 - 开始时间 TriggerTimeStart *time.Time // 告警触发时间范围 - 开始时间
TriggerTimeEnd *time.Time // 告警触发时间范围 - 结束时间 TriggerTimeEnd *time.Time // 告警触发时间范围 - 结束时间
@@ -41,19 +41,19 @@ type AlarmRepository interface {
CreateActiveAlarm(ctx context.Context, alarm *models.ActiveAlarm) error CreateActiveAlarm(ctx context.Context, alarm *models.ActiveAlarm) error
// IsAlarmActiveInUse 检查具有相同来源和告警代码的告警当前是否处于活跃表中 // 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 在指定事务中根据唯一业务键获取一个活跃告警
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 在指定事务中创建一条历史告警记录
CreateHistoricalAlarmTx(ctx context.Context, tx *gorm.DB, alarm *models.HistoricalAlarm) error CreateHistoricalAlarmTx(ctx context.Context, tx *gorm.DB, alarm *models.HistoricalAlarm) error
// DeleteActiveAlarmTx 在指定事务中根据主键 ID 删除一个活跃告警 // DeleteActiveAlarmTx 在指定事务中根据主键 ID 删除一个活跃告警
DeleteActiveAlarmTx(ctx context.Context, tx *gorm.DB, id uint) error DeleteActiveAlarmTx(ctx context.Context, tx *gorm.DB, id uint32) error
// UpdateIgnoreStatus 更新指定告警的忽略状态 // 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 支持分页和过滤的活跃告警列表查询。 // ListActiveAlarms 支持分页和过滤的活跃告警列表查询。
// 返回活跃告警列表、总记录数和错误。 // 返回活跃告警列表、总记录数和错误。
@@ -67,16 +67,16 @@ type AlarmRepository interface {
// lastNotifiedAt: 传入具体的发送时间。 // lastNotifiedAt: 传入具体的发送时间。
// isIgnored: 告警新的忽略状态。 // isIgnored: 告警新的忽略状态。
// ignoredUntil: 告警新的忽略截止时间 (nil 表示没有忽略截止时间/已取消忽略)。 // 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 查询满足发送告警消息条件的活跃告警列表。 // ListAlarmsForNotification 查询满足发送告警消息条件的活跃告警列表。
// 返回活跃告警列表和错误。 // 返回活跃告警列表和错误。
// intervalByLevel: key=SeverityLevel, value=interval_in_minutes // 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 实现。 // gormAlarmRepository 是 AlarmRepository 的 GORM 实现。
@@ -100,7 +100,7 @@ func (r *gormAlarmRepository) CreateActiveAlarm(ctx context.Context, alarm *mode
} }
// IsAlarmActiveInUse 检查具有相同来源和告警代码的告警当前是否处于活跃表中 // 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") repoCtx := logs.AddFuncName(ctx, r.ctx, "IsAlarmActiveInUse")
var count int64 var count int64
err := r.db.WithContext(repoCtx).Model(&models.ActiveAlarm{}). err := r.db.WithContext(repoCtx).Model(&models.ActiveAlarm{}).
@@ -113,7 +113,7 @@ func (r *gormAlarmRepository) IsAlarmActiveInUse(ctx context.Context, sourceType
} }
// GetActiveAlarmByUniqueFieldsTx 在指定事务中根据唯一业务键获取一个活跃告警 // 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") repoCtx := logs.AddFuncName(ctx, r.ctx, "GetActiveAlarmByUniqueFieldsTx")
var alarm models.ActiveAlarm var alarm models.ActiveAlarm
err := tx.WithContext(repoCtx). err := tx.WithContext(repoCtx).
@@ -129,14 +129,14 @@ func (r *gormAlarmRepository) CreateHistoricalAlarmTx(ctx context.Context, tx *g
} }
// DeleteActiveAlarmTx 在指定事务中根据主键 ID 删除一个活跃告警 // 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") repoCtx := logs.AddFuncName(ctx, r.ctx, "DeleteActiveAlarmTx")
// 使用 Unscoped() 确保执行物理删除,而不是软删除 // 使用 Unscoped() 确保执行物理删除,而不是软删除
return tx.WithContext(repoCtx).Unscoped().Delete(&models.ActiveAlarm{}, id).Error return tx.WithContext(repoCtx).Unscoped().Delete(&models.ActiveAlarm{}, id).Error
} }
// UpdateIgnoreStatus 更新指定告警的忽略状态 // 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") repoCtx := logs.AddFuncName(ctx, r.ctx, "UpdateIgnoreStatus")
updates := map[string]interface{}{ updates := map[string]interface{}{
"is_ignored": isIgnored, "is_ignored": isIgnored,
@@ -266,7 +266,7 @@ func (r *gormAlarmRepository) ListHistoricalAlarms(ctx context.Context, opts His
return results, total, err 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") repoCtx := logs.AddFuncName(ctx, r.ctx, "UpdateAlarmNotificationStatus")
// 1. 内部安全地构造 map将强类型参数转换为 GORM 需要的格式 // 1. 内部安全地构造 map将强类型参数转换为 GORM 需要的格式
@@ -290,7 +290,7 @@ func (r *gormAlarmRepository) UpdateAlarmNotificationStatus(ctx context.Context,
} }
// CountAlarmsForNotification 查询满足发送告警消息条件的记录总数 // 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") repoCtx := logs.AddFuncName(ctx, r.ctx, "CountAlarmsForNotification")
var total int64 var total int64
@@ -311,7 +311,7 @@ func (r *gormAlarmRepository) CountAlarmsForNotification(ctx context.Context, in
} }
// ListAlarmsForNotification 查询满足发送告警消息条件的活跃告警列表 // 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") repoCtx := logs.AddFuncName(ctx, r.ctx, "ListAlarmsForNotification")
var results []models.ActiveAlarm var results []models.ActiveAlarm
@@ -332,7 +332,7 @@ func (r *gormAlarmRepository) ListAlarmsForNotification(ctx context.Context, int
} }
// buildNotificationBaseQuery 负责组合 Group A 和 Group B 的逻辑 // 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 列表 // 1. 获取所有配置的 Level 列表
configuredLevels := make([]models.SeverityLevel, 0, len(intervalByLevel)) configuredLevels := make([]models.SeverityLevel, 0, len(intervalByLevel))
@@ -392,7 +392,7 @@ func (r *gormAlarmRepository) buildGroupAClause(tx *gorm.DB, configuredLevels []
// buildGroupBClause 构造 Group B 的 WHERE 语句和参数列表。 // buildGroupBClause 构造 Group B 的 WHERE 语句和参数列表。
// 针对 Level 存在配置的告警,使用“间隔发送”逻辑。 // 针对 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() now := time.Now()
// B.1. 构造 Level IN 子句 // B.1. 构造 Level IN 子句

View File

@@ -13,14 +13,14 @@ import (
// AreaControllerRepository 定义了对 AreaController 模型的数据库操作接口 // AreaControllerRepository 定义了对 AreaController 模型的数据库操作接口
type AreaControllerRepository interface { 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) FindByNetworkID(ctx context.Context, networkID string) (*models.AreaController, error)
Create(ctx context.Context, ac *models.AreaController) error Create(ctx context.Context, ac *models.AreaController) error
ListAll(ctx context.Context) ([]*models.AreaController, error) ListAll(ctx context.Context) ([]*models.AreaController, error)
Update(ctx context.Context, ac *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 检查区域主控是否被特定任务类型使用,可以忽略指定任务类型
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 实现。 // gormAreaControllerRepository 是 AreaControllerRepository 的 GORM 实现。
@@ -60,7 +60,7 @@ func (r *gormAreaControllerRepository) Update(ctx context.Context, ac *models.Ar
} }
// Delete 删除一个 AreaController 记录。 // 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") repoCtx := logs.AddFuncName(ctx, r.ctx, "Delete")
if err := r.db.WithContext(repoCtx).Delete(&models.AreaController{}, id).Error; err != nil { if err := r.db.WithContext(repoCtx).Delete(&models.AreaController{}, id).Error; err != nil {
return fmt.Errorf("删除区域主控失败: %w", err) return fmt.Errorf("删除区域主控失败: %w", err)
@@ -69,7 +69,7 @@ func (r *gormAreaControllerRepository) Delete(ctx context.Context, id uint) erro
} }
// FindByID 通过 ID 查找一个 AreaController。 // 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") repoCtx := logs.AddFuncName(ctx, r.ctx, "FindByID")
var areaController models.AreaController var areaController models.AreaController
if err := r.db.WithContext(repoCtx).First(&areaController, id).Error; err != nil { 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 检查区域主控是否被特定任务类型使用,可以忽略指定任务类型 // 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") repoCtx, logger := logs.Trace(ctx, r.ctx, "IsAreaControllerUsedByTasks")
// 将 ignoredTaskTypes 转换为 map以便高效查找 // 将 ignoredTaskTypes 转换为 map以便高效查找

View File

@@ -12,7 +12,7 @@ import (
// DeviceCommandLogListOptions 定义了查询设备命令日志时的可选参数 // DeviceCommandLogListOptions 定义了查询设备命令日志时的可选参数
type DeviceCommandLogListOptions struct { type DeviceCommandLogListOptions struct {
DeviceID *uint DeviceID *uint32
ReceivedSuccess *bool ReceivedSuccess *bool
StartTime *time.Time // 基于 sent_at 字段 StartTime *time.Time // 基于 sent_at 字段
EndTime *time.Time // 基于 sent_at 字段 EndTime *time.Time // 基于 sent_at 字段

View File

@@ -18,7 +18,7 @@ type DeviceRepository interface {
Create(ctx context.Context, device *models.Device) error Create(ctx context.Context, device *models.Device) error
// FindByID 根据主键 ID 查找设备 // FindByID 根据主键 ID 查找设备
FindByID(ctx context.Context, id uint) (*models.Device, error) FindByID(ctx context.Context, id uint32) (*models.Device, error)
// FindByIDString 根据字符串形式的主键 ID 查找设备 // FindByIDString 根据字符串形式的主键 ID 查找设备
FindByIDString(ctx context.Context, id string) (*models.Device, error) FindByIDString(ctx context.Context, id string) (*models.Device, error)
@@ -30,28 +30,28 @@ type DeviceRepository interface {
ListAllSensors(ctx context.Context) ([]*models.Device, error) ListAllSensors(ctx context.Context) ([]*models.Device, error)
// ListByAreaControllerID 根据区域主控 ID 列出所有子设备 // ListByAreaControllerID 根据区域主控 ID 列出所有子设备
ListByAreaControllerID(ctx context.Context, areaControllerID uint) ([]*models.Device, error) ListByAreaControllerID(ctx context.Context, areaControllerID uint32) ([]*models.Device, error)
// FindByDeviceTemplateID 根据设备模板ID查找所有使用该模板的设备 // FindByDeviceTemplateID 根据设备模板ID查找所有使用该模板的设备
FindByDeviceTemplateID(ctx context.Context, deviceTemplateID uint) ([]*models.Device, error) FindByDeviceTemplateID(ctx context.Context, deviceTemplateID uint32) ([]*models.Device, error)
// Update 更新一个已有的设备信息 // Update 更新一个已有的设备信息
Update(ctx context.Context, device *models.Device) error Update(ctx context.Context, device *models.Device) error
// Delete 根据主键 ID 删除一个设备 // Delete 根据主键 ID 删除一个设备
Delete(ctx context.Context, id uint) error Delete(ctx context.Context, id uint32) error
// FindByAreaControllerAndPhysicalAddress 根据区域主控ID和物理地址(总线号、总线地址)查找设备 // 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 在指定事务中根据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 检查设备是否被任何任务使用,可以忽略指定任务类型
IsDeviceInUse(ctx context.Context, deviceID uint, ignoredTaskTypes []models.TaskType) (bool, error) IsDeviceInUse(ctx context.Context, deviceID uint32, ignoredTaskTypes []models.TaskType) (bool, error)
// IsAreaControllerInUse 检查区域主控是否被任何设备使用 // IsAreaControllerInUse 检查区域主控是否被任何设备使用
IsAreaControllerInUse(ctx context.Context, areaControllerID uint) (bool, error) IsAreaControllerInUse(ctx context.Context, areaControllerID uint32) (bool, error)
} }
// gormDeviceRepository 是 DeviceRepository 的 GORM 实现 // gormDeviceRepository 是 DeviceRepository 的 GORM 实现
@@ -73,7 +73,7 @@ func (r *gormDeviceRepository) Create(ctx context.Context, device *models.Device
} }
// FindByID 根据 ID 查找设备 // 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") repoCtx := logs.AddFuncName(ctx, r.ctx, "FindByID")
var device models.Device var device models.Device
if err := r.db.WithContext(repoCtx).Preload("AreaController").Preload("DeviceTemplate").First(&device, id).Error; err != nil { 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列表获取设备 // 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") repoCtx := logs.AddFuncName(ctx, r.ctx, "GetDevicesByIDsTx")
var devices []models.Device var devices []models.Device
if len(ids) == 0 { if len(ids) == 0 {
@@ -98,14 +98,13 @@ func (r *gormDeviceRepository) GetDevicesByIDsTx(ctx context.Context, tx *gorm.D
// FindByIDString 根据字符串形式的主键 ID 查找设备 // FindByIDString 根据字符串形式的主键 ID 查找设备
func (r *gormDeviceRepository) FindByIDString(ctx context.Context, id string) (*models.Device, error) { func (r *gormDeviceRepository) FindByIDString(ctx context.Context, id string) (*models.Device, error) {
repoCtx := logs.AddFuncName(ctx, r.ctx, "FindByIDString") repoCtx := logs.AddFuncName(ctx, r.ctx, "FindByIDString")
// 将字符串ID转换为uint64
idInt, err := strconv.ParseUint(id, 10, 64) idInt, err := strconv.ParseUint(id, 10, 64)
if err != nil { if err != nil {
// 如果转换失败说明ID格式不正确返回一个明确的错误 // 如果转换失败说明ID格式不正确返回一个明确的错误
return nil, fmt.Errorf("无效的设备ID格式: %w", err) return nil, fmt.Errorf("无效的设备ID格式: %w", err)
} }
// 调用已有的 FindByID 方法 // 调用已有的 FindByID 方法
return r.FindByID(repoCtx, uint(idInt)) return r.FindByID(repoCtx, uint32(idInt))
} }
// ListAll 获取所有设备的列表 // ListAll 获取所有设备的列表
@@ -133,7 +132,7 @@ func (r *gormDeviceRepository) ListAllSensors(ctx context.Context) ([]*models.De
} }
// ListByAreaControllerID 根据区域主控 ID 列出所有子设备 // 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") repoCtx := logs.AddFuncName(ctx, r.ctx, "ListByAreaControllerID")
var devices []*models.Device var devices []*models.Device
err := r.db.WithContext(repoCtx).Preload("AreaController").Preload("DeviceTemplate").Where("area_controller_id = ?", areaControllerID).Find(&devices).Error 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查找所有使用该模板的设备 // 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") repoCtx := logs.AddFuncName(ctx, r.ctx, "FindByDeviceTemplateID")
var devices []*models.Device var devices []*models.Device
err := r.db.WithContext(repoCtx).Where("device_template_id = ?", deviceTemplateID).Find(&devices).Error 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 删除一个设备 // Delete 根据 ID 删除一个设备
// GORM 使用软删除,记录不会从数据库中物理移除,而是设置 DeletedAt 字段。 // 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") repoCtx := logs.AddFuncName(ctx, r.ctx, "Delete")
return r.db.WithContext(repoCtx).Delete(&models.Device{}, id).Error return r.db.WithContext(repoCtx).Delete(&models.Device{}, id).Error
} }
// FindByAreaControllerAndPhysicalAddress 根据区域主控ID和物理地址(总线号、总线地址)查找设备 // 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") repoCtx := logs.AddFuncName(ctx, r.ctx, "FindByAreaControllerAndPhysicalAddress")
var device models.Device var device models.Device
err := r.db.WithContext(repoCtx).Preload("AreaController").Preload("DeviceTemplate"). err := r.db.WithContext(repoCtx).Preload("AreaController").Preload("DeviceTemplate").
@@ -185,7 +184,7 @@ func (r *gormDeviceRepository) FindByAreaControllerAndPhysicalAddress(ctx contex
} }
// IsDeviceInUse 检查设备是否被任何任务使用,可以忽略指定任务类型 // 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") repoCtx := logs.AddFuncName(ctx, r.ctx, "IsDeviceInUse")
var count int64 var count int64
@@ -207,7 +206,7 @@ func (r *gormDeviceRepository) IsDeviceInUse(ctx context.Context, deviceID uint,
} }
// IsAreaControllerInUse 检查区域主控是否被任何设备使用 // 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") repoCtx := logs.AddFuncName(ctx, r.ctx, "IsAreaControllerInUse")
var count int64 var count int64
if err := r.db.WithContext(repoCtx).Model(&models.Device{}).Where("area_controller_id = ?", areaControllerID).Count(&count).Error; err != nil { if err := r.db.WithContext(repoCtx).Model(&models.Device{}).Where("area_controller_id = ?", areaControllerID).Count(&count).Error; err != nil {

View File

@@ -14,12 +14,12 @@ import (
// DeviceTemplateRepository 定义了设备模板数据访问的接口 // DeviceTemplateRepository 定义了设备模板数据访问的接口
type DeviceTemplateRepository interface { type DeviceTemplateRepository interface {
Create(ctx context.Context, deviceTemplate *models.DeviceTemplate) error 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) FindByName(ctx context.Context, name string) (*models.DeviceTemplate, error)
ListAll(ctx context.Context) ([]*models.DeviceTemplate, error) ListAll(ctx context.Context) ([]*models.DeviceTemplate, error)
Update(ctx context.Context, deviceTemplate *models.DeviceTemplate) error Update(ctx context.Context, deviceTemplate *models.DeviceTemplate) error
Delete(ctx context.Context, id uint) error Delete(ctx context.Context, id uint32) error
IsInUse(ctx context.Context, id uint) (bool, error) IsInUse(ctx context.Context, id uint32) (bool, error)
} }
// gormDeviceTemplateRepository 是 DeviceTemplateRepository 的 GORM 实现 // gormDeviceTemplateRepository 是 DeviceTemplateRepository 的 GORM 实现
@@ -40,7 +40,7 @@ func (r *gormDeviceTemplateRepository) Create(ctx context.Context, deviceTemplat
} }
// FindByID 根据ID查找设备模板 // 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") repoCtx := logs.AddFuncName(ctx, r.ctx, "FindByID")
var deviceTemplate models.DeviceTemplate var deviceTemplate models.DeviceTemplate
if err := r.db.WithContext(repoCtx).First(&deviceTemplate, id).Error; err != nil { 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 检查设备模板是否正在被设备使用 // 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") repoCtx := logs.AddFuncName(ctx, r.ctx, "IsInUse")
var count int64 var count int64
if err := r.db.WithContext(repoCtx).Model(&models.Device{}).Where("device_template_id = ?", id).Count(&count).Error; err != nil { 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 软删除数据库中的设备模板 // 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") repoCtx := logs.AddFuncName(ctx, r.ctx, "Delete")
if err := r.db.WithContext(repoCtx).Delete(&models.DeviceTemplate{}, id).Error; err != nil { if err := r.db.WithContext(repoCtx).Delete(&models.DeviceTemplate{}, id).Error; err != nil {
return fmt.Errorf("删除设备模板失败: %w", err) return fmt.Errorf("删除设备模板失败: %w", err)

View File

@@ -13,7 +13,7 @@ import (
// PlanExecutionLogListOptions 定义了查询计划执行日志时的可选参数 // PlanExecutionLogListOptions 定义了查询计划执行日志时的可选参数
type PlanExecutionLogListOptions struct { type PlanExecutionLogListOptions struct {
PlanID *uint PlanID *uint32
Status *models.ExecutionStatus Status *models.ExecutionStatus
StartTime *time.Time // 基于 created_at 字段 StartTime *time.Time // 基于 created_at 字段
EndTime *time.Time // 基于 created_at 字段 EndTime *time.Time // 基于 created_at 字段
@@ -22,7 +22,7 @@ type PlanExecutionLogListOptions struct {
// TaskExecutionLogListOptions 定义了查询任务执行日志时的可选参数 // TaskExecutionLogListOptions 定义了查询任务执行日志时的可选参数
type TaskExecutionLogListOptions struct { type TaskExecutionLogListOptions struct {
PlanExecutionLogID *uint PlanExecutionLogID *uint32
TaskID *int TaskID *int
Status *models.ExecutionStatus Status *models.ExecutionStatus
StartTime *time.Time // 基于 created_at 字段 StartTime *time.Time // 基于 created_at 字段
@@ -33,26 +33,26 @@ type TaskExecutionLogListOptions struct {
// ExecutionLogRepository 定义了与执行日志交互的接口。 // ExecutionLogRepository 定义了与执行日志交互的接口。
type ExecutionLogRepository interface { type ExecutionLogRepository interface {
// --- Existing methods --- // --- Existing methods ---
UpdateTaskExecutionLogStatusByIDs(ctx context.Context, logIDs []uint, status models.ExecutionStatus) error UpdateTaskExecutionLogStatusByIDs(ctx context.Context, logIDs []uint32, status models.ExecutionStatus) error
UpdateTaskExecutionLogStatus(ctx context.Context, logID uint, status models.ExecutionStatus) error UpdateTaskExecutionLogStatus(ctx context.Context, logID uint32, status models.ExecutionStatus) error
CreateTaskExecutionLog(ctx context.Context, log *models.TaskExecutionLog) error CreateTaskExecutionLog(ctx context.Context, log *models.TaskExecutionLog) error
CreatePlanExecutionLog(ctx context.Context, log *models.PlanExecutionLog) error CreatePlanExecutionLog(ctx context.Context, log *models.PlanExecutionLog) error
UpdatePlanExecutionLog(ctx context.Context, log *models.PlanExecutionLog) error UpdatePlanExecutionLog(ctx context.Context, log *models.PlanExecutionLog) error
CreateTaskExecutionLogsInBatch(ctx context.Context, logs []*models.TaskExecutionLog) error CreateTaskExecutionLogsInBatch(ctx context.Context, logs []*models.TaskExecutionLog) error
UpdateTaskExecutionLog(ctx context.Context, log *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 更新计划执行日志的状态
UpdatePlanExecutionLogStatus(ctx context.Context, logID uint, status models.ExecutionStatus) error UpdatePlanExecutionLogStatus(ctx context.Context, logID uint32, status models.ExecutionStatus) error
// UpdatePlanExecutionLogsStatusByIDs 批量更新计划执行日志的状态 // UpdatePlanExecutionLogsStatusByIDs 批量更新计划执行日志的状态
UpdatePlanExecutionLogsStatusByIDs(ctx context.Context, logIDs []uint, status models.ExecutionStatus) error UpdatePlanExecutionLogsStatusByIDs(ctx context.Context, logIDs []uint32, status models.ExecutionStatus) error
// FindIncompletePlanExecutionLogs 查找所有未完成的计划执行日志 // FindIncompletePlanExecutionLogs 查找所有未完成的计划执行日志
FindIncompletePlanExecutionLogs(ctx context.Context) ([]models.PlanExecutionLog, error) FindIncompletePlanExecutionLogs(ctx context.Context) ([]models.PlanExecutionLog, error)
// FindInProgressPlanExecutionLogByPlanID 根据 PlanID 查找正在进行的计划执行日志 // FindInProgressPlanExecutionLogByPlanID 根据 PlanID 查找正在进行的计划执行日志
FindInProgressPlanExecutionLogByPlanID(ctx context.Context, planID uint) (*models.PlanExecutionLog, error) FindInProgressPlanExecutionLogByPlanID(ctx context.Context, planID uint32) (*models.PlanExecutionLog, error)
// FindIncompleteTaskExecutionLogsByPlanLogID 根据计划日志ID查找所有未完成的任务日志 // 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 将所有状态为 ExecutionStatusStarted 和 ExecutionStatusWaiting 的计划状态都修改为 ExecutionStatusFailed
FailAllIncompletePlanExecutionLogs(ctx context.Context) error FailAllIncompletePlanExecutionLogs(ctx context.Context) error
@@ -60,16 +60,16 @@ type ExecutionLogRepository interface {
CancelAllIncompleteTaskExecutionLogs(ctx context.Context) error CancelAllIncompleteTaskExecutionLogs(ctx context.Context) error
// FindPlanExecutionLogByID 根据ID查找计划执行日志 // FindPlanExecutionLogByID 根据ID查找计划执行日志
FindPlanExecutionLogByID(ctx context.Context, id uint) (*models.PlanExecutionLog, error) FindPlanExecutionLogByID(ctx context.Context, id uint32) (*models.PlanExecutionLog, error)
// CountIncompleteTasksByPlanLogID 计算一个计划执行中未完成的任务数量 // CountIncompleteTasksByPlanLogID 计算一个计划执行中未完成的任务数量
CountIncompleteTasksByPlanLogID(ctx context.Context, planLogID uint) (int64, error) CountIncompleteTasksByPlanLogID(ctx context.Context, planLogID uint32) (int64, error)
// FailPlanExecution 将指定的计划执行标记为失败 // FailPlanExecution 将指定的计划执行标记为失败
FailPlanExecution(ctx context.Context, planLogID uint, errorMessage string) error FailPlanExecution(ctx context.Context, planLogID uint32, errorMessage string) error
// CancelIncompleteTasksByPlanLogID 取消一个计划执行中的所有未完成任务 // CancelIncompleteTasksByPlanLogID 取消一个计划执行中的所有未完成任务
CancelIncompleteTasksByPlanLogID(ctx context.Context, planLogID uint, reason string) error CancelIncompleteTasksByPlanLogID(ctx context.Context, planLogID uint32, reason string) error
// --- New methods --- // --- New methods ---
ListPlanExecutionLogs(ctx context.Context, opts PlanExecutionLogListOptions, page, pageSize int) ([]models.PlanExecutionLog, int64, error) 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 --- // --- 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") repoCtx := logs.AddFuncName(ctx, r.ctx, "UpdateTaskExecutionLogStatusByIDs")
if len(logIDs) == 0 { if len(logIDs) == 0 {
return nil 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 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") repoCtx := logs.AddFuncName(ctx, r.ctx, "UpdateTaskExecutionLogStatus")
return r.db.WithContext(repoCtx).Model(&models.TaskExecutionLog{}).Where("id = ?", logID).Update("status", status).Error 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 查找单个任务执行日志。 // FindTaskExecutionLogByID 根据 ID 查找单个任务执行日志。
// 它会预加载关联的 Task 信息。 // 它会预加载关联的 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") repoCtx := logs.AddFuncName(ctx, r.ctx, "FindTaskExecutionLogByID")
var log models.TaskExecutionLog var log models.TaskExecutionLog
// 使用 Preload("Task") 来确保关联的任务信息被一并加载 // 使用 Preload("Task") 来确保关联的任务信息被一并加载
@@ -240,13 +240,13 @@ func (r *gormExecutionLogRepository) FindTaskExecutionLogByID(ctx context.Contex
} }
// UpdatePlanExecutionLogStatus 更新计划执行日志的状态 // 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") repoCtx := logs.AddFuncName(ctx, r.ctx, "UpdatePlanExecutionLogStatus")
return r.db.WithContext(repoCtx).Model(&models.PlanExecutionLog{}).Where("id = ?", logID).Update("status", status).Error return r.db.WithContext(repoCtx).Model(&models.PlanExecutionLog{}).Where("id = ?", logID).Update("status", status).Error
} }
// UpdatePlanExecutionLogsStatusByIDs 批量更新计划执行日志的状态 // 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") repoCtx := logs.AddFuncName(ctx, r.ctx, "UpdatePlanExecutionLogsStatusByIDs")
if len(logIDs) == 0 { if len(logIDs) == 0 {
return nil return nil
@@ -263,7 +263,7 @@ func (r *gormExecutionLogRepository) FindIncompletePlanExecutionLogs(ctx context
} }
// FindInProgressPlanExecutionLogByPlanID 根据 PlanID 查找正在进行的计划执行日志 // 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") repoCtx := logs.AddFuncName(ctx, r.ctx, "FindInProgressPlanExecutionLogByPlanID")
var log models.PlanExecutionLog var log models.PlanExecutionLog
err := r.db.WithContext(repoCtx).Where("plan_id = ? AND status = ?", planID, models.ExecutionStatusStarted).First(&log).Error 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查找所有未完成的任务日志 // 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") repoCtx := logs.AddFuncName(ctx, r.ctx, "FindIncompleteTaskExecutionLogsByPlanLogID")
var logs []models.TaskExecutionLog var logs []models.TaskExecutionLog
err := r.db.WithContext(repoCtx).Where("plan_execution_log_id = ? AND (status = ? OR status = ?)", 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查找计划执行日志 // 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") repoCtx := logs.AddFuncName(ctx, r.ctx, "FindPlanExecutionLogByID")
var log models.PlanExecutionLog var log models.PlanExecutionLog
err := r.db.WithContext(repoCtx).First(&log, id).Error err := r.db.WithContext(repoCtx).First(&log, id).Error
@@ -315,7 +315,7 @@ func (r *gormExecutionLogRepository) FindPlanExecutionLogByID(ctx context.Contex
} }
// CountIncompleteTasksByPlanLogID 计算一个计划执行中未完成的任务数量 // 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") repoCtx := logs.AddFuncName(ctx, r.ctx, "CountIncompleteTasksByPlanLogID")
var count int64 var count int64
err := r.db.WithContext(repoCtx).Model(&models.TaskExecutionLog{}). err := r.db.WithContext(repoCtx).Model(&models.TaskExecutionLog{}).
@@ -326,7 +326,7 @@ func (r *gormExecutionLogRepository) CountIncompleteTasksByPlanLogID(ctx context
} }
// FailPlanExecution 将指定的计划执行标记为失败 // 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") repoCtx := logs.AddFuncName(ctx, r.ctx, "FailPlanExecution")
return r.db.WithContext(repoCtx).Model(&models.PlanExecutionLog{}). return r.db.WithContext(repoCtx).Model(&models.PlanExecutionLog{}).
Where("id = ?", planLogID). Where("id = ?", planLogID).
@@ -338,7 +338,7 @@ func (r *gormExecutionLogRepository) FailPlanExecution(ctx context.Context, plan
} }
// CancelIncompleteTasksByPlanLogID 取消一个计划执行中的所有未完成任务 // 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") repoCtx := logs.AddFuncName(ctx, r.ctx, "CancelIncompleteTasksByPlanLogID")
return r.db.WithContext(repoCtx).Model(&models.TaskExecutionLog{}). return r.db.WithContext(repoCtx).Model(&models.TaskExecutionLog{}).
Where("plan_execution_log_id = ? AND status IN (?, ?)", Where("plan_execution_log_id = ? AND status IN (?, ?)",

View File

@@ -12,10 +12,10 @@ import (
// MedicationLogListOptions 定义了查询用药记录时的可选参数 // MedicationLogListOptions 定义了查询用药记录时的可选参数
type MedicationLogListOptions struct { type MedicationLogListOptions struct {
PigBatchID *uint PigBatchID *uint32
MedicationID *uint MedicationID *uint32
Reason *models.MedicationReasonType Reason *models.MedicationReasonType
OperatorID *uint OperatorID *uint32
StartTime *time.Time StartTime *time.Time
EndTime *time.Time EndTime *time.Time
OrderBy string // 例如 "happened_at desc" OrderBy string // 例如 "happened_at desc"

View File

@@ -13,7 +13,7 @@ import (
// NotificationListOptions 定义了查询通知列表时的可选参数 // NotificationListOptions 定义了查询通知列表时的可选参数
type NotificationListOptions struct { type NotificationListOptions struct {
UserID *uint // 按用户ID过滤 UserID *uint32 // 按用户ID过滤
NotifierType *models.NotifierType // 按通知器类型过滤 NotifierType *models.NotifierType // 按通知器类型过滤
Status *models.NotificationStatus // 按通知状态过滤 (例如:"success", "failed") Status *models.NotificationStatus // 按通知状态过滤 (例如:"success", "failed")
Level *zapcore.Level // 按通知等级过滤 (例如:"info", "warning", "error") Level *zapcore.Level // 按通知等级过滤 (例如:"info", "warning", "error")

View File

@@ -12,7 +12,7 @@ import (
// PendingCollectionListOptions 定义了查询待采集请求时的可选参数 // PendingCollectionListOptions 定义了查询待采集请求时的可选参数
type PendingCollectionListOptions struct { type PendingCollectionListOptions struct {
DeviceID *uint DeviceID *uint32
Status *models.PendingCollectionStatus Status *models.PendingCollectionStatus
StartTime *time.Time // 基于 created_at 字段 StartTime *time.Time // 基于 created_at 字段
EndTime *time.Time // 基于 created_at 字段 EndTime *time.Time // 基于 created_at 字段

View File

@@ -16,27 +16,27 @@ import (
// PendingTaskRepository 定义了与待执行任务队列交互的接口。 // PendingTaskRepository 定义了与待执行任务队列交互的接口。
type PendingTaskRepository interface { type PendingTaskRepository interface {
FindAllPendingTasks(ctx context.Context) ([]models.PendingTask, error) FindAllPendingTasks(ctx context.Context) ([]models.PendingTask, error)
FindPendingTriggerByPlanID(ctx context.Context, planID uint) (*models.PendingTask, error) FindPendingTriggerByPlanID(ctx context.Context, planID uint32) (*models.PendingTask, error)
DeletePendingTasksByIDs(ctx context.Context, ids []uint) error DeletePendingTasksByIDs(ctx context.Context, ids []uint32) error
CreatePendingTask(ctx context.Context, task *models.PendingTask) error CreatePendingTask(ctx context.Context, task *models.PendingTask) error
CreatePendingTasksInBatch(ctx context.Context, tasks []*models.PendingTask) error CreatePendingTasksInBatch(ctx context.Context, tasks []*models.PendingTask) error
// UpdatePendingTaskExecuteAt 更新指定待执行任务的执行时间 // UpdatePendingTaskExecuteAt 更新指定待执行任务的执行时间
UpdatePendingTaskExecuteAt(ctx context.Context, id uint, executeAt time.Time) error UpdatePendingTaskExecuteAt(ctx context.Context, id uint32, executeAt time.Time) error
// ClearAllPendingTasks 清空所有待执行任务 // ClearAllPendingTasks 清空所有待执行任务
ClearAllPendingTasks(ctx context.Context) error ClearAllPendingTasks(ctx context.Context) error
// ClaimNextAvailableTask 原子地认领下一个可用的任务。 // 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 安全地将一个任务重新放回队列。
RequeueTask(ctx context.Context, originalPendingTask *models.PendingTask) error RequeueTask(ctx context.Context, originalPendingTask *models.PendingTask) error
// FindPendingTasksByTaskLogIDs 根据 TaskExecutionLogID 列表查找对应的待执行任务 // FindPendingTasksByTaskLogIDs 根据 TaskExecutionLogID 列表查找对应的待执行任务
FindPendingTasksByTaskLogIDs(ctx context.Context, taskLogIDs []uint) ([]models.PendingTask, error) FindPendingTasksByTaskLogIDs(ctx context.Context, taskLogIDs []uint32) ([]models.PendingTask, error)
// DeletePendingTasksByPlanLogID 删除与指定计划执行日志ID相关的所有待执行任务 // DeletePendingTasksByPlanLogID 删除与指定计划执行日志ID相关的所有待执行任务
DeletePendingTasksByPlanLogID(ctx context.Context, planLogID uint) error DeletePendingTasksByPlanLogID(ctx context.Context, planLogID uint32) error
} }
// gormPendingTaskRepository 是使用 GORM 的具体实现。 // gormPendingTaskRepository 是使用 GORM 的具体实现。
@@ -59,7 +59,7 @@ func (r *gormPendingTaskRepository) FindAllPendingTasks(ctx context.Context) ([]
return tasks, err 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") repoCtx := logs.AddFuncName(ctx, r.ctx, "FindPendingTriggerByPlanID")
var pendingTask models.PendingTask var pendingTask models.PendingTask
// 关键修改:通过 JOIN tasks 表并查询 parameters JSON 字段来查找触发器,而不是依赖 task.plan_id // 关键修改:通过 JOIN tasks 表并查询 parameters JSON 字段来查找触发器,而不是依赖 task.plan_id
@@ -73,7 +73,7 @@ func (r *gormPendingTaskRepository) FindPendingTriggerByPlanID(ctx context.Conte
return &pendingTask, err 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") repoCtx := logs.AddFuncName(ctx, r.ctx, "DeletePendingTasksByIDs")
if len(ids) == 0 { if len(ids) == 0 {
return nil return nil
@@ -96,7 +96,7 @@ func (r *gormPendingTaskRepository) CreatePendingTasksInBatch(ctx context.Contex
} }
// UpdatePendingTaskExecuteAt 更新指定待执行任务的执行时间 // 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") repoCtx := logs.AddFuncName(ctx, r.ctx, "UpdatePendingTaskExecuteAt")
return r.db.WithContext(repoCtx).Model(&models.PendingTask{}).Where("id = ?", id).Update("execute_at", executeAt).Error 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 以原子方式认领下一个可用的任务。 // 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") repoCtx := logs.AddFuncName(ctx, r.ctx, "ClaimNextAvailableTask")
var log models.TaskExecutionLog var log models.TaskExecutionLog
var pendingTask models.PendingTask var pendingTask models.PendingTask
@@ -175,7 +175,7 @@ func (r *gormPendingTaskRepository) RequeueTask(ctx context.Context, originalPen
} }
// FindPendingTasksByTaskLogIDs 根据 TaskExecutionLogID 列表查找对应的待执行任务 // 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") repoCtx := logs.AddFuncName(ctx, r.ctx, "FindPendingTasksByTaskLogIDs")
if len(taskLogIDs) == 0 { if len(taskLogIDs) == 0 {
return []models.PendingTask{}, nil return []models.PendingTask{}, nil
@@ -186,7 +186,7 @@ func (r *gormPendingTaskRepository) FindPendingTasksByTaskLogIDs(ctx context.Con
} }
// DeletePendingTasksByPlanLogID 删除与指定计划执行日志ID相关的所有待执行任务 // 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") repoCtx := logs.AddFuncName(ctx, r.ctx, "DeletePendingTasksByPlanLogID")
// 使用子查询找到所有与 planLogID 相关的 task_execution_log_id // 使用子查询找到所有与 planLogID 相关的 task_execution_log_id
subQuery := r.db.WithContext(repoCtx).Model(&models.TaskExecutionLog{}).Select("id").Where("plan_execution_log_id = ?", planLogID) subQuery := r.db.WithContext(repoCtx).Model(&models.TaskExecutionLog{}).Select("id").Where("plan_execution_log_id = ?", planLogID)

View File

@@ -12,9 +12,9 @@ import (
// PigBatchLogListOptions 定义了查询猪批次日志时的可选参数 // PigBatchLogListOptions 定义了查询猪批次日志时的可选参数
type PigBatchLogListOptions struct { type PigBatchLogListOptions struct {
PigBatchID *uint PigBatchID *uint32
ChangeType *models.LogChangeType ChangeType *models.LogChangeType
OperatorID *uint OperatorID *uint32
StartTime *time.Time // 基于 happened_at 字段 StartTime *time.Time // 基于 happened_at 字段
EndTime *time.Time // 基于 happened_at 字段 EndTime *time.Time // 基于 happened_at 字段
OrderBy string // 例如 "happened_at asc" OrderBy string // 例如 "happened_at asc"
@@ -26,10 +26,10 @@ type PigBatchLogRepository interface {
CreateTx(ctx context.Context, tx *gorm.DB, log *models.PigBatchLog) error CreateTx(ctx context.Context, tx *gorm.DB, log *models.PigBatchLog) error
// GetLogsByBatchIDAndDateRangeTx 在指定的事务中,获取指定批次在特定时间范围内的所有日志记录。 // 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 在指定的事务中,获取某批次的最后一条日志记录。
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 支持分页和过滤的列表查询
List(ctx context.Context, opts PigBatchLogListOptions, page, pageSize int) ([]models.PigBatchLog, int64, error) 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 实现了在指定的事务中,获取指定批次在特定时间范围内的所有日志记录的逻辑。 // 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") repoCtx := logs.AddFuncName(ctx, r.ctx, "GetLogsByBatchIDAndDateRangeTx")
var logs []*models.PigBatchLog var logs []*models.PigBatchLog
err := tx.WithContext(repoCtx).Where("pig_batch_id = ? AND created_at >= ? AND created_at <= ?", batchID, startDate, endDate).Find(&logs).Error 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 实现了在指定的事务中,获取某批次的最后一条日志记录的逻辑。 // 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") repoCtx := logs.AddFuncName(ctx, r.ctx, "GetLastLogByBatchIDTx")
var log models.PigBatchLog var log models.PigBatchLog
err := tx.WithContext(repoCtx).Where("pig_batch_id = ?", batchID).Order("id DESC").First(&log).Error err := tx.WithContext(repoCtx).Where("pig_batch_id = ?", batchID).Order("id DESC").First(&log).Error

View File

@@ -14,13 +14,13 @@ import (
type PigBatchRepository interface { type PigBatchRepository interface {
CreatePigBatch(ctx context.Context, batch *models.PigBatch) (*models.PigBatch, error) CreatePigBatch(ctx context.Context, batch *models.PigBatch) (*models.PigBatch, error)
CreatePigBatchTx(ctx context.Context, tx *gorm.DB, 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) GetPigBatchByID(ctx context.Context, id uint32) (*models.PigBatch, error)
GetPigBatchByIDTx(ctx context.Context, tx *gorm.DB, id uint) (*models.PigBatch, error) GetPigBatchByIDTx(ctx context.Context, tx *gorm.DB, id uint32) (*models.PigBatch, error)
// UpdatePigBatch 更新一个猪批次,返回更新后的批次、受影响的行数和错误 // UpdatePigBatch 更新一个猪批次,返回更新后的批次、受影响的行数和错误
UpdatePigBatch(ctx context.Context, batch *models.PigBatch) (*models.PigBatch, int64, error) UpdatePigBatch(ctx context.Context, batch *models.PigBatch) (*models.PigBatch, int64, error)
// DeletePigBatch 根据ID删除一个猪批次返回受影响的行数和错误 // DeletePigBatch 根据ID删除一个猪批次返回受影响的行数和错误
DeletePigBatch(ctx context.Context, id uint) (int64, error) DeletePigBatch(ctx context.Context, id uint32) (int64, error)
DeletePigBatchTx(ctx context.Context, tx *gorm.DB, id uint) (int64, error) DeletePigBatchTx(ctx context.Context, tx *gorm.DB, id uint32) (int64, error)
ListPigBatches(ctx context.Context, isActive *bool) ([]*models.PigBatch, error) ListPigBatches(ctx context.Context, isActive *bool) ([]*models.PigBatch, error)
// ListWeighingBatches 支持分页和过滤的批次称重列表查询 // ListWeighingBatches 支持分页和过滤的批次称重列表查询
@@ -32,7 +32,7 @@ type PigBatchRepository interface {
// WeighingBatchListOptions 定义了查询批次称重记录时的可选参数 // WeighingBatchListOptions 定义了查询批次称重记录时的可选参数
type WeighingBatchListOptions struct { type WeighingBatchListOptions struct {
PigBatchID *uint PigBatchID *uint32
StartTime *time.Time // 基于 weighing_time 字段 StartTime *time.Time // 基于 weighing_time 字段
EndTime *time.Time // 基于 weighing_time 字段 EndTime *time.Time // 基于 weighing_time 字段
OrderBy string // 例如 "weighing_time asc" OrderBy string // 例如 "weighing_time asc"
@@ -40,9 +40,9 @@ type WeighingBatchListOptions struct {
// WeighingRecordListOptions 定义了查询单次称重记录时的可选参数 // WeighingRecordListOptions 定义了查询单次称重记录时的可选参数
type WeighingRecordListOptions struct { type WeighingRecordListOptions struct {
WeighingBatchID *uint WeighingBatchID *uint32
PenID *uint PenID *uint32
OperatorID *uint OperatorID *uint32
StartTime *time.Time // 基于 weighing_time 字段 StartTime *time.Time // 基于 weighing_time 字段
EndTime *time.Time // 基于 weighing_time 字段 EndTime *time.Time // 基于 weighing_time 字段
OrderBy string // 例如 "weighing_time asc" OrderBy string // 例如 "weighing_time asc"
@@ -75,7 +75,7 @@ func (r *gormPigBatchRepository) CreatePigBatchTx(ctx context.Context, tx *gorm.
} }
// GetPigBatchByID 根据ID获取单个猪批次 // 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") repoCtx := logs.AddFuncName(ctx, r.ctx, "GetPigBatchByID")
return r.GetPigBatchByIDTx(repoCtx, r.db, id) return r.GetPigBatchByIDTx(repoCtx, r.db, id)
} }
@@ -92,12 +92,12 @@ func (r *gormPigBatchRepository) UpdatePigBatch(ctx context.Context, batch *mode
} }
// DeletePigBatch 根据ID删除一个猪批次 (GORM 会执行软删除) // 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") repoCtx := logs.AddFuncName(ctx, r.ctx, "DeletePigBatch")
return r.DeletePigBatchTx(repoCtx, r.db, id) 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") repoCtx := logs.AddFuncName(ctx, r.ctx, "DeletePigBatchTx")
result := tx.WithContext(repoCtx).Delete(&models.PigBatch{}, id) result := tx.WithContext(repoCtx).Delete(&models.PigBatch{}, id)
if result.Error != nil { if result.Error != nil {
@@ -130,7 +130,7 @@ func (r *gormPigBatchRepository) ListPigBatches(ctx context.Context, isActive *b
} }
// GetPigBatchByIDTx 在指定的事务中通过ID获取单个猪批次 // 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") repoCtx := logs.AddFuncName(ctx, r.ctx, "GetPigBatchByIDTx")
var batch models.PigBatch var batch models.PigBatch
if err := tx.WithContext(repoCtx).First(&batch, id).Error; err != nil { if err := tx.WithContext(repoCtx).First(&batch, id).Error; err != nil {

View File

@@ -13,13 +13,13 @@ import (
type PigFarmRepository interface { type PigFarmRepository interface {
// PigHouse methods // PigHouse methods
CreatePigHouse(ctx context.Context, house *models.PigHouse) error 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) ListPigHouses(ctx context.Context) ([]models.PigHouse, error)
// UpdatePigHouse 更新一个猪舍,返回受影响的行数和错误 // UpdatePigHouse 更新一个猪舍,返回受影响的行数和错误
UpdatePigHouse(ctx context.Context, house *models.PigHouse) (int64, error) UpdatePigHouse(ctx context.Context, house *models.PigHouse) (int64, error)
// DeletePigHouse 根据ID删除一个猪舍返回受影响的行数和错误 // DeletePigHouse 根据ID删除一个猪舍返回受影响的行数和错误
DeletePigHouse(ctx context.Context, id uint) (int64, error) DeletePigHouse(ctx context.Context, id uint32) (int64, error)
CountPensInHouse(ctx context.Context, houseID uint) (int64, error) CountPensInHouse(ctx context.Context, houseID uint32) (int64, error)
} }
// gormPigFarmRepository 是 PigFarmRepository 的 GORM 实现 // gormPigFarmRepository 是 PigFarmRepository 的 GORM 实现
@@ -42,7 +42,7 @@ func (r *gormPigFarmRepository) CreatePigHouse(ctx context.Context, house *model
} }
// GetPigHouseByID 根据ID获取单个猪舍 // 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") repoCtx := logs.AddFuncName(ctx, r.ctx, "GetPigHouseByID")
var house models.PigHouse var house models.PigHouse
if err := r.db.WithContext(repoCtx).First(&house, id).Error; err != nil { 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删除一个猪舍返回受影响的行数和错误 // 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") repoCtx := logs.AddFuncName(ctx, r.ctx, "DeletePigHouse")
result := r.db.WithContext(repoCtx).Delete(&models.PigHouse{}, id) result := r.db.WithContext(repoCtx).Delete(&models.PigHouse{}, id)
if result.Error != nil { if result.Error != nil {
@@ -82,7 +82,7 @@ func (r *gormPigFarmRepository) DeletePigHouse(ctx context.Context, id uint) (in
} }
// CountPensInHouse 统计猪舍中的猪栏数量 // 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") repoCtx := logs.AddFuncName(ctx, r.ctx, "CountPensInHouse")
var count int64 var count int64
err := r.db.WithContext(repoCtx).Model(&models.Pen{}).Where("house_id = ?", houseID).Count(&count).Error err := r.db.WithContext(repoCtx).Model(&models.Pen{}).Where("house_id = ?", houseID).Count(&count).Error

View File

@@ -13,18 +13,18 @@ import (
type PigPenRepository interface { type PigPenRepository interface {
CreatePen(ctx context.Context, pen *models.Pen) error CreatePen(ctx context.Context, pen *models.Pen) error
// GetPenByID 根据ID获取单个猪栏 (非事务性) // GetPenByID 根据ID获取单个猪栏 (非事务性)
GetPenByID(ctx context.Context, id uint) (*models.Pen, error) GetPenByID(ctx context.Context, id uint32) (*models.Pen, error)
// GetPenByIDTx 根据ID获取单个猪栏 (事务性) // 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) ListPens(ctx context.Context) ([]models.Pen, error)
// UpdatePen 更新一个猪栏,返回受影响的行数和错误 // UpdatePen 更新一个猪栏,返回受影响的行数和错误
UpdatePen(ctx context.Context, pen *models.Pen) (int64, error) UpdatePen(ctx context.Context, pen *models.Pen) (int64, error)
// DeletePen 根据ID删除一个猪栏返回受影响的行数和错误 // DeletePen 根据ID删除一个猪栏返回受影响的行数和错误
DeletePen(ctx context.Context, id uint) (int64, error) DeletePen(ctx context.Context, id uint32) (int64, error)
// GetPensByBatchIDTx 根据批次ID获取所有关联的猪栏 (事务性) // 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 更新猪栏的指定字段 (事务性)
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 实现。 // gormPigPenRepository 是 PigPenRepository 接口的 GORM 实现。
@@ -45,13 +45,13 @@ func (r *gormPigPenRepository) CreatePen(ctx context.Context, pen *models.Pen) e
} }
// GetPenByID 根据ID获取单个猪栏 (非事务性) // 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") repoCtx := logs.AddFuncName(ctx, r.ctx, "GetPenByID")
return r.GetPenByIDTx(repoCtx, r.db, id) // 非Tx方法直接调用Tx方法 return r.GetPenByIDTx(repoCtx, r.db, id) // 非Tx方法直接调用Tx方法
} }
// GetPenByIDTx 在指定的事务中通过ID获取单个猪栏信息。 // 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") repoCtx := logs.AddFuncName(ctx, r.ctx, "GetPenByIDTx")
var pen models.Pen var pen models.Pen
if err := tx.WithContext(repoCtx).First(&pen, id).Error; err != nil { 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删除一个猪栏返回受影响的行数和错误 // 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") repoCtx := logs.AddFuncName(ctx, r.ctx, "DeletePen")
result := r.db.WithContext(repoCtx).Delete(&models.Pen{}, id) result := r.db.WithContext(repoCtx).Delete(&models.Pen{}, id)
if result.Error != nil { if result.Error != nil {
@@ -91,7 +91,7 @@ func (r *gormPigPenRepository) DeletePen(ctx context.Context, id uint) (int64, e
} }
// GetPensByBatchIDTx 在指定的事务中,获取一个猪群当前关联的所有猪栏。 // 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") repoCtx := logs.AddFuncName(ctx, r.ctx, "GetPensByBatchIDTx")
var pens []*models.Pen var pens []*models.Pen
// 注意PigBatchID 是指针类型,需要处理 nil 值 // 注意PigBatchID 是指针类型,需要处理 nil 值
@@ -103,7 +103,7 @@ func (r *gormPigPenRepository) GetPensByBatchIDTx(ctx context.Context, tx *gorm.
} }
// UpdatePenFieldsTx 在指定的事务中,更新一个猪栏的指定字段。 // 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") repoCtx := logs.AddFuncName(ctx, r.ctx, "UpdatePenFieldsTx")
result := tx.WithContext(repoCtx).Model(&models.Pen{}).Where("id = ?", penID).Updates(updates) result := tx.WithContext(repoCtx).Model(&models.Pen{}).Where("id = ?", penID).Updates(updates)
return result.Error return result.Error

View File

@@ -13,11 +13,11 @@ import (
// PigSickLogListOptions 定义了查询病猪日志时的可选参数 // PigSickLogListOptions 定义了查询病猪日志时的可选参数
type PigSickLogListOptions struct { type PigSickLogListOptions struct {
PigBatchID *uint PigBatchID *uint32
PenID *uint PenID *uint32
Reason *models.PigBatchSickPigReasonType Reason *models.PigBatchSickPigReasonType
TreatmentLocation *models.PigBatchSickPigTreatmentLocation TreatmentLocation *models.PigBatchSickPigTreatmentLocation
OperatorID *uint OperatorID *uint32
StartTime *time.Time // 基于 happened_at 字段 StartTime *time.Time // 基于 happened_at 字段
EndTime *time.Time // 基于 happened_at 字段 EndTime *time.Time // 基于 happened_at 字段
OrderBy string // 例如 "happened_at desc" OrderBy string // 例如 "happened_at desc"
@@ -30,7 +30,7 @@ type PigSickLogRepository interface {
CreatePigSickLogTx(ctx context.Context, tx *gorm.DB, log *models.PigSickLog) error CreatePigSickLogTx(ctx context.Context, tx *gorm.DB, log *models.PigSickLog) error
// GetLastLogByBatchTx 在事务中获取指定批次和猪栏的最新一条 PigSickLog 记录 // 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 支持分页和过滤的病猪日志列表查询
ListPigSickLogs(ctx context.Context, opts PigSickLogListOptions, page, pageSize int) ([]models.PigSickLog, int64, error) 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 记录 // 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") repoCtx := logs.AddFuncName(ctx, r.ctx, "GetLastLogByBatchTx")
var lastLog models.PigSickLog var lastLog models.PigSickLog
err := tx.WithContext(repoCtx). err := tx.WithContext(repoCtx).

View File

@@ -12,9 +12,9 @@ import (
// PigPurchaseListOptions 定义了查询猪只采购记录时的可选参数 // PigPurchaseListOptions 定义了查询猪只采购记录时的可选参数
type PigPurchaseListOptions struct { type PigPurchaseListOptions struct {
PigBatchID *uint PigBatchID *uint32
Supplier *string Supplier *string
OperatorID *uint OperatorID *uint32
StartTime *time.Time // 基于 purchase_date 字段 StartTime *time.Time // 基于 purchase_date 字段
EndTime *time.Time // 基于 purchase_date 字段 EndTime *time.Time // 基于 purchase_date 字段
OrderBy string // 例如 "purchase_date desc" OrderBy string // 例如 "purchase_date desc"
@@ -22,9 +22,9 @@ type PigPurchaseListOptions struct {
// PigSaleListOptions 定义了查询猪只销售记录时的可选参数 // PigSaleListOptions 定义了查询猪只销售记录时的可选参数
type PigSaleListOptions struct { type PigSaleListOptions struct {
PigBatchID *uint PigBatchID *uint32
Buyer *string Buyer *string
OperatorID *uint OperatorID *uint32
StartTime *time.Time // 基于 sale_date 字段 StartTime *time.Time // 基于 sale_date 字段
EndTime *time.Time // 基于 sale_date 字段 EndTime *time.Time // 基于 sale_date 字段
OrderBy string // 例如 "sale_date desc" OrderBy string // 例如 "sale_date desc"

View File

@@ -12,10 +12,10 @@ import (
// PigTransferLogListOptions 定义了查询猪只迁移日志时的可选参数 // PigTransferLogListOptions 定义了查询猪只迁移日志时的可选参数
type PigTransferLogListOptions struct { type PigTransferLogListOptions struct {
PigBatchID *uint PigBatchID *uint32
PenID *uint PenID *uint32
TransferType *models.PigTransferType // 迁移类型 TransferType *models.PigTransferType // 迁移类型
OperatorID *uint OperatorID *uint32
CorrelationID *string CorrelationID *string
StartTime *time.Time // 基于 transfer_time 字段 StartTime *time.Time // 基于 transfer_time 字段
EndTime *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 CreatePigTransferLog(ctx context.Context, tx *gorm.DB, log *models.PigTransferLog) error
// GetLogsForPenSince 获取指定猪栏自特定时间点以来的所有迁移日志,按时间倒序排列。 // 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 支持分页和过滤的猪只迁移日志列表查询
ListPigTransferLogs(ctx context.Context, opts PigTransferLogListOptions, page, pageSize int) ([]models.PigTransferLog, int64, error) 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 实现了获取猪栏自特定时间点以来所有迁移日志的逻辑。 // 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") repoCtx := logs.AddFuncName(ctx, r.ctx, "GetLogsForPenSince")
var logs []*models.PigTransferLog var logs []*models.PigTransferLog
err := tx.WithContext(repoCtx).Where("pen_id = ? AND transfer_time >= ?", penID, since).Order("transfer_time DESC").Find(&logs).Error err := tx.WithContext(repoCtx).Where("pen_id = ? AND transfer_time >= ?", penID, since).Order("transfer_time DESC").Find(&logs).Error

View File

@@ -44,11 +44,11 @@ type PlanRepository interface {
// ListPlans 获取计划列表,支持过滤和分页 // ListPlans 获取计划列表,支持过滤和分页
ListPlans(ctx context.Context, opts ListPlansOptions, page, pageSize int) ([]models.Plan, int64, error) ListPlans(ctx context.Context, opts ListPlansOptions, page, pageSize int) ([]models.Plan, int64, error)
// GetBasicPlanByID 根据ID获取计划的基本信息不包含子计划和任务详情 // GetBasicPlanByID 根据ID获取计划的基本信息不包含子计划和任务详情
GetBasicPlanByID(ctx context.Context, id uint) (*models.Plan, error) GetBasicPlanByID(ctx context.Context, id uint32) (*models.Plan, error)
// GetPlanByID 根据ID获取计划包含子计划和任务详情 // GetPlanByID 根据ID获取计划包含子计划和任务详情
GetPlanByID(ctx context.Context, id uint) (*models.Plan, error) GetPlanByID(ctx context.Context, id uint32) (*models.Plan, error)
// GetPlansByIDs 根据ID列表获取计划不包含子计划和任务详情 // GetPlansByIDs 根据ID列表获取计划不包含子计划和任务详情
GetPlansByIDs(ctx context.Context, ids []uint) ([]models.Plan, error) GetPlansByIDs(ctx context.Context, ids []uint32) ([]models.Plan, error)
// GetSystemPlanByName 根据计划名称获取系统计划,包含子计划和任务详情 // GetSystemPlanByName 根据计划名称获取系统计划,包含子计划和任务详情
GetSystemPlanByName(ctx context.Context, planName models.PlanName) (*models.Plan, error) GetSystemPlanByName(ctx context.Context, planName models.PlanName) (*models.Plan, error)
// CreatePlan 创建一个新的计划 // CreatePlan 创建一个新的计划
@@ -60,35 +60,35 @@ type PlanRepository interface {
// UpdatePlan 更新计划的所有字段 // UpdatePlan 更新计划的所有字段
UpdatePlan(ctx context.Context, plan *models.Plan) error UpdatePlan(ctx context.Context, plan *models.Plan) error
// UpdatePlanStatus 更新指定计划的状态 // UpdatePlanStatus 更新指定计划的状态
UpdatePlanStatus(ctx context.Context, id uint, status models.PlanStatus) error UpdatePlanStatus(ctx context.Context, id uint32, status models.PlanStatus) error
// UpdateExecuteCount 更新指定计划的执行计数 // UpdateExecuteCount 更新指定计划的执行计数
UpdateExecuteCount(ctx context.Context, id uint, count uint) error UpdateExecuteCount(ctx context.Context, id uint32, count uint32) error
// DeletePlan 根据ID删除计划同时删除其关联的任务非子任务或子计划关联 // DeletePlan 根据ID删除计划同时删除其关联的任务非子任务或子计划关联
DeletePlan(ctx context.Context, id uint) error DeletePlan(ctx context.Context, id uint32) error
// FlattenPlanTasks 递归展开计划,返回按执行顺序排列的所有任务列表 // FlattenPlanTasks 递归展开计划,返回按执行顺序排列的所有任务列表
FlattenPlanTasks(ctx context.Context, planID uint) ([]models.Task, error) FlattenPlanTasks(ctx context.Context, planID uint32) ([]models.Task, error)
// DeleteTask 根据ID删除任务 // DeleteTask 根据ID删除任务
DeleteTask(ctx context.Context, id int) error DeleteTask(ctx context.Context, id int) error
// FindTaskByID 根据ID获取任务的基本信息 // FindTaskByID 根据ID获取任务的基本信息
FindTaskByID(ctx context.Context, id int) (*models.Task, error) FindTaskByID(ctx context.Context, id int) (*models.Task, error)
// FindPlanAnalysisTaskByParamsPlanID 根据Parameters中的ParamsPlanID字段值查找TaskPlanAnalysis类型的Task // 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 获取所有应执行的计划
FindRunnablePlans(ctx context.Context) ([]*models.Plan, error) FindRunnablePlans(ctx context.Context) ([]*models.Plan, error)
// FindInactivePlans 获取所有已禁用或已停止的计划 // FindInactivePlans 获取所有已禁用或已停止的计划
FindInactivePlans(ctx context.Context) ([]*models.Plan, error) FindInactivePlans(ctx context.Context) ([]*models.Plan, error)
// FindPlanAnalysisTaskByPlanID 根据 PlanID 找到其关联的 'plan_analysis' 任务 // 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 创建一个 plan_analysis 类型的任务并返回它
CreatePlanAnalysisTask(ctx context.Context, plan *models.Plan) (*models.Task, error) CreatePlanAnalysisTask(ctx context.Context, plan *models.Plan) (*models.Task, error)
// FindPlansWithPendingTasks 查找所有正在执行的计划 // FindPlansWithPendingTasks 查找所有正在执行的计划
FindPlansWithPendingTasks(ctx context.Context) ([]*models.Plan, error) FindPlansWithPendingTasks(ctx context.Context) ([]*models.Plan, error)
// StopPlanTransactionally 停止一个计划的执行,包括更新状态、移除待执行任务和更新执行日志 // StopPlanTransactionally 停止一个计划的执行,包括更新状态、移除待执行任务和更新执行日志
StopPlanTransactionally(ctx context.Context, planID uint) error StopPlanTransactionally(ctx context.Context, planID uint32) error
// UpdatePlanStateAfterExecution 更新计划执行后的状态(计数和状态) // 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 根据设备ID获取关联任务列表
ListTasksByDeviceID(ctx context.Context, deviceID uint) ([]*models.Task, error) ListTasksByDeviceID(ctx context.Context, deviceID uint32) ([]*models.Task, error)
} }
// gormPlanRepository 是 PlanRepository 的 GORM 实现 // gormPlanRepository 是 PlanRepository 的 GORM 实现
@@ -140,7 +140,7 @@ func (r *gormPlanRepository) ListPlans(ctx context.Context, opts ListPlansOption
} }
// GetBasicPlanByID 根据ID获取计划的基本信息不包含子计划和任务详情 // 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") repoCtx := logs.AddFuncName(ctx, r.ctx, "GetBasicPlanByID")
var plan models.Plan var plan models.Plan
// GORM 默认不会加载关联,除非使用 Preload所以直接 First 即可满足要求 // GORM 默认不会加载关联,除非使用 Preload所以直接 First 即可满足要求
@@ -152,7 +152,7 @@ func (r *gormPlanRepository) GetBasicPlanByID(ctx context.Context, id uint) (*mo
} }
// GetPlansByIDs 根据ID列表获取计划不包含子计划和任务详情 // 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") repoCtx := logs.AddFuncName(ctx, r.ctx, "GetPlansByIDs")
var plans []models.Plan var plans []models.Plan
if len(ids) == 0 { if len(ids) == 0 {
@@ -183,7 +183,7 @@ func (r *gormPlanRepository) GetSystemPlanByName(ctx context.Context, planName m
} }
// GetPlanByID 根据ID获取计划包含子计划和任务详情 // 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") repoCtx := logs.AddFuncName(ctx, r.ctx, "GetPlanByID")
var plan models.Plan var plan models.Plan
@@ -254,7 +254,7 @@ func (r *gormPlanRepository) CreatePlanTx(ctx context.Context, tx *gorm.DB, plan
// 如果是子计划类型验证所有子计划是否存在且ID不为0 // 如果是子计划类型验证所有子计划是否存在且ID不为0
if plan.ContentType == models.PlanContentTypeSubPlans { if plan.ContentType == models.PlanContentTypeSubPlans {
childIDsToValidate := make(map[uint]bool) childIDsToValidate := make(map[uint32]bool)
for _, subPlanLink := range plan.SubPlans { for _, subPlanLink := range plan.SubPlans {
if subPlanLink.ChildPlanID == 0 { if subPlanLink.ChildPlanID == 0 {
return ErrSubPlanIDIsZeroOnCreate return ErrSubPlanIDIsZeroOnCreate
@@ -262,7 +262,7 @@ func (r *gormPlanRepository) CreatePlanTx(ctx context.Context, tx *gorm.DB, plan
childIDsToValidate[subPlanLink.ChildPlanID] = true childIDsToValidate[subPlanLink.ChildPlanID] = true
} }
var ids []uint var ids []uint32
for id := range childIDsToValidate { for id := range childIDsToValidate {
ids = append(ids, id) ids = append(ids, id)
} }
@@ -334,8 +334,8 @@ func (r *gormPlanRepository) validatePlanTree(ctx context.Context, tx *gorm.DB,
} }
// 2. 递归验证所有子节点,并检测循环引用 // 2. 递归验证所有子节点,并检测循环引用
allIDs := make(map[uint]bool) allIDs := make(map[uint32]bool)
recursionStack := make(map[uint]bool) recursionStack := make(map[uint32]bool)
if err := validateNodeAndDetectCycles(plan, allIDs, recursionStack); err != nil { if err := validateNodeAndDetectCycles(plan, allIDs, recursionStack); err != nil {
return err return err
} }
@@ -346,7 +346,7 @@ func (r *gormPlanRepository) validatePlanTree(ctx context.Context, tx *gorm.DB,
} }
// 4. 一次性数据库存在性校验 // 4. 一次性数据库存在性校验
var idsToCheck []uint var idsToCheck []uint32
for id := range allIDs { for id := range allIDs {
idsToCheck = append(idsToCheck, id) idsToCheck = append(idsToCheck, id)
} }
@@ -364,7 +364,7 @@ func (r *gormPlanRepository) validatePlanTree(ctx context.Context, tx *gorm.DB,
} }
// validateNodeAndDetectCycles 递归地验证节点有效性并检测循环引用 // 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 { if plan == nil {
return nil return nil
} }
@@ -469,7 +469,7 @@ func (r *gormPlanRepository) reconcileSubPlans(ctx context.Context, tx *gorm.DB,
return err return err
} }
existingLinkMap := make(map[uint]bool) existingLinkMap := make(map[uint32]bool)
for _, link := range existingLinks { for _, link := range existingLinks {
existingLinkMap[link.ID] = true 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 { for id := range existingLinkMap {
linksToDelete = append(linksToDelete, id) linksToDelete = append(linksToDelete, id)
} }
@@ -503,7 +503,7 @@ func (r *gormPlanRepository) reconcileSubPlans(ctx context.Context, tx *gorm.DB,
} }
// DeletePlan 根据ID删除计划同时删除其关联的任务非子任务或子计划关联 // 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") repoCtx := logs.AddFuncName(ctx, r.ctx, "DeletePlan")
return r.db.WithContext(repoCtx).Transaction(func(tx *gorm.DB) error { return r.db.WithContext(repoCtx).Transaction(func(tx *gorm.DB) error {
// 1. 检查该计划是否是其他计划的子计划 // 1. 检查该计划是否是其他计划的子计划
@@ -545,7 +545,7 @@ func (r *gormPlanRepository) DeletePlan(ctx context.Context, id uint) error {
} }
// FlattenPlanTasks 递归展开计划,返回按执行顺序排列的所有任务列表 // 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") repoCtx := logs.AddFuncName(ctx, r.ctx, "FlattenPlanTasks")
plan, err := r.GetPlanByID(repoCtx, planID) plan, err := r.GetPlanByID(repoCtx, planID)
if err != nil { if err != nil {
@@ -645,7 +645,7 @@ func (r *gormPlanRepository) deleteTasksTx(ctx context.Context, tx *gorm.DB, ids
} }
// FindPlanAnalysisTaskByParamsPlanID 根据Parameters中的ParamsPlanID字段值查找TaskPlanAnalysis类型的Task // 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") repoCtx := logs.AddFuncName(ctx, r.ctx, "FindPlanAnalysisTaskByParamsPlanID")
return r.findPlanAnalysisTask(repoCtx, r.db, paramsPlanID) return r.findPlanAnalysisTask(repoCtx, r.db, paramsPlanID)
} }
@@ -722,7 +722,7 @@ func (r *gormPlanRepository) FindInactivePlans(ctx context.Context) ([]*models.P
// findPlanAnalysisTask 是一个内部使用的、更高效的查找方法 // findPlanAnalysisTask 是一个内部使用的、更高效的查找方法
// 关键修改:通过查询 parameters JSON 字段来查找 // 关键修改:通过查询 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") repoCtx := logs.AddFuncName(ctx, r.ctx, "findPlanAnalysisTask")
var task models.Task var task models.Task
err := tx.WithContext(repoCtx).Where("type = ? AND parameters->>'plan_id' = ?", models.TaskPlanAnalysis, fmt.Sprintf("%d", planID)).First(&task).Error 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 是暴露给外部的公共方法 // FindPlanAnalysisTaskByPlanID 是暴露给外部的公共方法
// 关键修改:通过查询 parameters JSON 字段来查找 // 关键修改:通过查询 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") repoCtx := logs.AddFuncName(ctx, r.ctx, "FindPlanAnalysisTaskByPlanID")
return r.findPlanAnalysisTask(repoCtx, r.db, planID) return r.findPlanAnalysisTask(repoCtx, r.db, planID)
} }
@@ -769,7 +769,7 @@ func (r *gormPlanRepository) FindPlansWithPendingTasks(ctx context.Context) ([]*
} }
// StopPlanTransactionally 停止一个计划的执行,包括更新状态、移除待执行任务和更新执行日志。 // 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") repoCtx := logs.AddFuncName(ctx, r.ctx, "StopPlanTransactionally")
return r.db.WithContext(repoCtx).Transaction(func(tx *gorm.DB) error { 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 { if len(taskLogs) > 0 {
var taskLogIDs []uint var taskLogIDs []uint32
for _, tl := range taskLogs { for _, tl := range taskLogs {
taskLogIDs = append(taskLogIDs, tl.ID) taskLogIDs = append(taskLogIDs, tl.ID)
} }
@@ -817,7 +817,7 @@ func (r *gormPlanRepository) StopPlanTransactionally(ctx context.Context, planID
} }
if len(pendingTasks) > 0 { if len(pendingTasks) > 0 {
var pendingTaskIDs []uint var pendingTaskIDs []uint32
for _, pt := range pendingTasks { for _, pt := range pendingTasks {
pendingTaskIDs = append(pendingTaskIDs, pt.ID) pendingTaskIDs = append(pendingTaskIDs, pt.ID)
} }
@@ -837,7 +837,7 @@ func (r *gormPlanRepository) StopPlanTransactionally(ctx context.Context, planID
} }
// UpdatePlanStatus 更新指定计划的状态 // 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") repoCtx := logs.AddFuncName(ctx, r.ctx, "UpdatePlanStatus")
result := r.db.WithContext(repoCtx).Model(&models.Plan{}).Where("id = ?", id).Update("status", status) result := r.db.WithContext(repoCtx).Model(&models.Plan{}).Where("id = ?", id).Update("status", status)
if result.Error != nil { if result.Error != nil {
@@ -849,7 +849,7 @@ func (r *gormPlanRepository) UpdatePlanStatus(ctx context.Context, id uint, stat
return nil 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") repoCtx := logs.AddFuncName(ctx, r.ctx, "UpdatePlanStateAfterExecution")
return r.db.WithContext(repoCtx).Model(&models.Plan{}).Where("id = ?", planID).Updates(map[string]interface{}{ return r.db.WithContext(repoCtx).Model(&models.Plan{}).Where("id = ?", planID).Updates(map[string]interface{}{
"execute_count": newCount, "execute_count": newCount,
@@ -858,7 +858,7 @@ func (r *gormPlanRepository) UpdatePlanStateAfterExecution(ctx context.Context,
} }
// UpdateExecuteCount 更新指定计划的执行计数 // 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") repoCtx := logs.AddFuncName(ctx, r.ctx, "UpdateExecuteCount")
result := r.db.WithContext(repoCtx).Model(&models.Plan{}).Where("id = ?", id).Update("execute_count", count) result := r.db.WithContext(repoCtx).Model(&models.Plan{}).Where("id = ?", id).Update("execute_count", count)
if result.Error != nil { if result.Error != nil {
@@ -881,7 +881,7 @@ func (r *gormPlanRepository) FindTaskByID(ctx context.Context, id int) (*models.
return &task, nil 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") repoCtx := logs.AddFuncName(ctx, r.ctx, "ListTasksByDeviceID")
tasks := []*models.Task{} tasks := []*models.Task{}
// 使用 Joins 方法来连接 tasks 表和 device_tasks 关联表, // 使用 Joins 方法来连接 tasks 表和 device_tasks 关联表,

View File

@@ -12,7 +12,7 @@ import (
// RawMaterialPurchaseListOptions 定义了查询原料采购记录时的可选参数 // RawMaterialPurchaseListOptions 定义了查询原料采购记录时的可选参数
type RawMaterialPurchaseListOptions struct { type RawMaterialPurchaseListOptions struct {
RawMaterialID *uint RawMaterialID *uint32
Supplier *string Supplier *string
StartTime *time.Time // 基于 purchase_date 字段 StartTime *time.Time // 基于 purchase_date 字段
EndTime *time.Time // 基于 purchase_date 字段 EndTime *time.Time // 基于 purchase_date 字段
@@ -21,9 +21,9 @@ type RawMaterialPurchaseListOptions struct {
// RawMaterialStockLogListOptions 定义了查询原料库存日志时的可选参数 // RawMaterialStockLogListOptions 定义了查询原料库存日志时的可选参数
type RawMaterialStockLogListOptions struct { type RawMaterialStockLogListOptions struct {
RawMaterialID *uint RawMaterialID *uint32
SourceType *models.StockLogSourceType SourceType *models.StockLogSourceType
SourceID *uint SourceID *uint32
StartTime *time.Time // 基于 happened_at 字段 StartTime *time.Time // 基于 happened_at 字段
EndTime *time.Time // 基于 happened_at 字段 EndTime *time.Time // 基于 happened_at 字段
OrderBy string // 例如 "happened_at asc" OrderBy string // 例如 "happened_at asc"
@@ -31,9 +31,9 @@ type RawMaterialStockLogListOptions struct {
// FeedUsageRecordListOptions 定义了查询饲料使用记录时的可选参数 // FeedUsageRecordListOptions 定义了查询饲料使用记录时的可选参数
type FeedUsageRecordListOptions struct { type FeedUsageRecordListOptions struct {
PenID *uint PenID *uint32
FeedFormulaID *uint FeedFormulaID *uint32
OperatorID *uint OperatorID *uint32
StartTime *time.Time // 基于 recorded_at 字段 StartTime *time.Time // 基于 recorded_at 字段
EndTime *time.Time // 基于 recorded_at 字段 EndTime *time.Time // 基于 recorded_at 字段
OrderBy string // 例如 "recorded_at asc" OrderBy string // 例如 "recorded_at asc"

View File

@@ -12,7 +12,7 @@ import (
// SensorDataListOptions 定义了查询传感器数据列表时的可选参数 // SensorDataListOptions 定义了查询传感器数据列表时的可选参数
type SensorDataListOptions struct { type SensorDataListOptions struct {
DeviceID *uint DeviceID *uint32
SensorType *models.SensorType SensorType *models.SensorType
StartTime *time.Time StartTime *time.Time
EndTime *time.Time EndTime *time.Time
@@ -22,7 +22,7 @@ type SensorDataListOptions struct {
// SensorDataRepository 定义了与传感器数据相关的数据库操作接口。 // SensorDataRepository 定义了与传感器数据相关的数据库操作接口。
type SensorDataRepository interface { type SensorDataRepository interface {
Create(ctx context.Context, sensorData *models.SensorData) error 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 支持分页和过滤的列表查询
List(ctx context.Context, opts SensorDataListOptions, page, pageSize int) ([]models.SensorData, int64, error) 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和传感器类型查询最新的传感器数据。 // 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") repoCtx := logs.AddFuncName(ctx, r.ctx, "GetLatestSensorDataByDeviceIDAndSensorType")
var sensorData models.SensorData var sensorData models.SensorData
// 增加一个时间范围来缩小查询范围, 从而加快查找速度, 当使用时序数据库时时间范围可以让数据库忽略时间靠前的分片 // 增加一个时间范围来缩小查询范围, 从而加快查找速度, 当使用时序数据库时时间范围可以让数据库忽略时间靠前的分片

View File

@@ -12,7 +12,7 @@ import (
// UserActionLogListOptions 定义了查询用户操作日志时的可选参数 // UserActionLogListOptions 定义了查询用户操作日志时的可选参数
type UserActionLogListOptions struct { type UserActionLogListOptions struct {
UserID *uint UserID *uint32
Username *string Username *string
ActionType *string ActionType *string
Status *models.AuditStatus Status *models.AuditStatus

View File

@@ -15,7 +15,7 @@ import (
type UserRepository interface { type UserRepository interface {
Create(ctx context.Context, user *models.User) error Create(ctx context.Context, user *models.User) error
FindByUsername(ctx context.Context, username string) (*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) FindUserForLogin(ctx context.Context, identifier string) (*models.User, error)
FindAll(ctx context.Context) ([]*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 查找用户 // 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") repoCtx := logs.AddFuncName(ctx, r.ctx, "FindByID")
var user models.User var user models.User
if err := r.db.WithContext(repoCtx).First(&user, id).Error; err != nil { if err := r.db.WithContext(repoCtx).First(&user, id).Error; err != nil {

View File

@@ -502,7 +502,7 @@ func (t *LoRaMeshUartPassthroughTransport) handleUpstreamMessage(ctx context.Con
} }
// recordSensorData 是一个通用方法,用于将传感器数据存入数据库。 // 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") loraCtx, logger := logs.Trace(ctx, t.ctx, "recordSensorData")
jsonData, err := json.Marshal(data) jsonData, err := json.Marshal(data)

View File

@@ -9,13 +9,13 @@ import (
// Claims 定义了 JWT 的声明结构 // Claims 定义了 JWT 的声明结构
type Claims struct { type Claims struct {
UserID uint `json:"user_id"` UserID uint32 `json:"user_id"`
jwt.RegisteredClaims jwt.RegisteredClaims
} }
// Generator 定义了 token 操作的接口 // Generator 定义了 token 操作的接口
type Generator interface { type Generator interface {
GenerateToken(userID uint) (string, error) GenerateToken(userID uint32) (string, error)
ParseToken(tokenString string) (*Claims, error) ParseToken(tokenString string) (*Claims, error)
} }
@@ -30,7 +30,7 @@ func NewTokenGenerator(secret []byte) Generator {
} }
// GenerateToken 生成一个新的 JWT token // GenerateToken 生成一个新的 JWT token
func (s *tokenGenerator) GenerateToken(userID uint) (string, error) { func (s *tokenGenerator) GenerateToken(userID uint32) (string, error) {
nowTime := time.Now() nowTime := time.Now()
expireTime := nowTime.Add(24 * time.Hour) // Token 有效期为 24 小时 expireTime := nowTime.Add(24 * time.Hour) // Token 有效期为 24 小时