简化控制器层重复代码

This commit is contained in:
2025-10-06 23:48:31 +08:00
parent 5e84b473f6
commit 21661eb748
5 changed files with 477 additions and 475 deletions

View File

@@ -1,10 +1,8 @@
package management
import (
"errors"
"strconv"
"git.huangwc.com/pig/pig-farm-controller/internal/app/controller"
"git.huangwc.com/pig/pig-farm-controller/internal/app/dto"
"git.huangwc.com/pig/pig-farm-controller/internal/app/service"
"git.huangwc.com/pig/pig-farm-controller/internal/infra/logs"
@@ -38,21 +36,16 @@ func NewPigBatchController(logger *logs.Logger, service service.PigBatchService)
func (c *PigBatchController) CreatePigBatch(ctx *gin.Context) {
const action = "创建猪批次"
var req dto.PigBatchCreateDTO
if err := ctx.ShouldBindJSON(&req); err != nil {
controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, "无效的请求体", action, "请求体绑定失败", req)
return
}
userID, err := controller.GetOperatorIDFromContext(ctx)
respDTO, err := c.service.CreatePigBatch(userID, &req)
if err != nil {
c.logger.Errorf("%s: 业务逻辑失败: %v", action, err)
controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "创建猪批次失败", action, "业务逻辑失败", req)
return
}
controller.SendSuccessWithAudit(ctx, controller.CodeCreated, "创建成功", respDTO, action, "创建成功", respDTO)
handleAPIRequestWithResponse(
c, ctx, action, &req,
func(ctx *gin.Context, operatorID uint, primaryID uint, req *dto.PigBatchCreateDTO) (*dto.PigBatchResponseDTO, error) {
// 对于创建操作primaryID通常不从路径中获取而是由服务层生成
return c.service.CreatePigBatch(operatorID, req)
},
"创建成功",
nil, // 无需自定义ID提取器primaryID将为0
)
}
// GetPigBatch godoc
@@ -62,27 +55,18 @@ func (c *PigBatchController) CreatePigBatch(ctx *gin.Context) {
// @Produce json
// @Param id path int true "猪批次ID"
// @Success 200 {object} controller.Response{data=dto.PigBatchResponseDTO} "获取成功"
// @Router /api/v1/pig-batches/{id} [get]
// @Router /api/v1/pig-batches/{id} [get]\
func (c *PigBatchController) GetPigBatch(ctx *gin.Context) {
const action = "获取猪批次"
id, err := strconv.ParseUint(ctx.Param("id"), 10, 32)
if err != nil {
controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, "无效的ID格式", action, "ID格式错误", ctx.Param("id"))
return
}
respDTO, err := c.service.GetPigBatch(uint(id))
if err != nil {
if errors.Is(err, service.ErrPigBatchNotFound) {
controller.SendErrorWithAudit(ctx, controller.CodeNotFound, "猪批次不存在", action, "猪批次不存在", id)
return
}
c.logger.Errorf("%s: 业务逻辑失败: %v", action, err)
controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "获取猪批次失败", action, "业务逻辑失败", id)
return
}
controller.SendSuccessWithAudit(ctx, controller.CodeSuccess, "获取成功", respDTO, action, "获取成功", respDTO)
handleNoBodyAPIRequestWithResponse(
c, ctx, action,
func(ctx *gin.Context, operatorID uint, primaryID uint) (*dto.PigBatchResponseDTO, error) {
return c.service.GetPigBatch(primaryID)
},
"获取成功",
nil, // 默认从 ":id" 路径参数提取ID
)
}
// UpdatePigBatch godoc
@@ -97,30 +81,16 @@ func (c *PigBatchController) GetPigBatch(ctx *gin.Context) {
// @Router /api/v1/pig-batches/{id} [put]
func (c *PigBatchController) UpdatePigBatch(ctx *gin.Context) {
const action = "更新猪批次"
id, err := strconv.ParseUint(ctx.Param("id"), 10, 32)
if err != nil {
controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, "无效的ID格式", action, "ID格式错误", ctx.Param("id"))
return
}
var req dto.PigBatchUpdateDTO
if err := ctx.ShouldBindJSON(&req); err != nil {
controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, "无效的请求体", action, "请求体绑定失败", req)
return
}
respDTO, err := c.service.UpdatePigBatch(uint(id), &req)
if err != nil {
if errors.Is(err, service.ErrPigBatchNotFound) {
controller.SendErrorWithAudit(ctx, controller.CodeNotFound, "猪批次不存在", action, "猪批次不存在", id)
return
}
c.logger.Errorf("%s: 业务逻辑失败: %v", action, err)
controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "更新猪批次失败", action, "业务逻辑失败", req)
return
}
controller.SendSuccessWithAudit(ctx, controller.CodeSuccess, "更新成功", respDTO, action, "更新成功", respDTO)
handleAPIRequestWithResponse(
c, ctx, action, &req,
func(ctx *gin.Context, operatorID uint, primaryID uint, req *dto.PigBatchUpdateDTO) (*dto.PigBatchResponseDTO, error) {
return c.service.UpdatePigBatch(primaryID, req)
},
"更新成功",
nil, // 默认从 ":id" 路径参数提取ID
)
}
// DeletePigBatch godoc
@@ -133,23 +103,15 @@ func (c *PigBatchController) UpdatePigBatch(ctx *gin.Context) {
// @Router /api/v1/pig-batches/{id} [delete]
func (c *PigBatchController) DeletePigBatch(ctx *gin.Context) {
const action = "删除猪批次"
id, err := strconv.ParseUint(ctx.Param("id"), 10, 32)
if err != nil {
controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, "无效的ID格式", action, "ID格式错误", ctx.Param("id"))
return
}
if err := c.service.DeletePigBatch(uint(id)); err != nil {
if errors.Is(err, service.ErrPigBatchNotFound) {
controller.SendErrorWithAudit(ctx, controller.CodeNotFound, "猪批次不存在", action, "猪批次不存在", id)
return
}
c.logger.Errorf("%s: 业务逻辑失败: %v", action, err)
controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "删除猪批次失败", action, "业务逻辑失败", id)
return
}
controller.SendSuccessWithAudit(ctx, controller.CodeSuccess, "删除成功", nil, action, "删除成功", id)
handleNoBodyAPIRequest(
c, ctx, action,
func(ctx *gin.Context, operatorID uint, primaryID uint) error {
return c.service.DeletePigBatch(primaryID)
},
"删除成功",
nil, // 默认从 ":id" 路径参数提取ID
)
}
// ListPigBatches godoc
@@ -163,20 +125,14 @@ func (c *PigBatchController) DeletePigBatch(ctx *gin.Context) {
func (c *PigBatchController) ListPigBatches(ctx *gin.Context) {
const action = "获取猪批次列表"
var query dto.PigBatchQueryDTO
// ShouldBindQuery 会自动处理 URL 查询参数,例如 ?is_active=true
if err := ctx.ShouldBindQuery(&query); err != nil {
controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, "无效的查询参数", action, "查询参数绑定失败", nil)
return
}
respDTOs, err := c.service.ListPigBatches(query.IsActive)
if err != nil {
c.logger.Errorf("%s: 业务逻辑失败: %v", action, err)
controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "获取猪批次列表失败", action, "业务逻辑失败", nil)
return
}
controller.SendSuccessWithAudit(ctx, controller.CodeSuccess, "获取成功", respDTOs, action, "获取成功", respDTOs)
handleQueryAPIRequestWithResponse(
c, ctx, action, &query,
func(ctx *gin.Context, operatorID uint, query *dto.PigBatchQueryDTO) ([]*dto.PigBatchResponseDTO, error) {
return c.service.ListPigBatches(query.IsActive)
},
"获取成功",
)
}
// AssignEmptyPensToBatch godoc
@@ -191,35 +147,16 @@ func (c *PigBatchController) ListPigBatches(ctx *gin.Context) {
// @Router /api/v1/pig-batches/{id}/assign-pens [post]
func (c *PigBatchController) AssignEmptyPensToBatch(ctx *gin.Context) {
const action = "为猪批次分配空栏"
batchID, err := strconv.ParseUint(ctx.Param("id"), 10, 32)
if err != nil {
controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, "无效的猪批次ID格式", action, "ID格式错误", ctx.Param("id"))
return
}
var req dto.AssignEmptyPensToBatchRequest
if err := ctx.ShouldBindJSON(&req); err != nil {
controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, "无效的请求体", action, "请求体绑定失败", req)
return
}
userID, err := controller.GetOperatorIDFromContext(ctx)
err = c.service.AssignEmptyPensToBatch(uint(batchID), req.PenIDs, userID)
if err != nil {
if errors.Is(err, service.ErrPigBatchNotFound) || errors.Is(err, service.ErrPenNotFound) {
controller.SendErrorWithAudit(ctx, controller.CodeNotFound, err.Error(), action, err.Error(), batchID)
return
} else if errors.Is(err, service.ErrPigBatchNotActive) || errors.Is(err, service.ErrPenOccupiedByOtherBatch) || errors.Is(err, service.ErrPenStatusInvalidForAllocation) {
controller.SendErrorWithAudit(ctx, controller.CodeConflict, err.Error(), action, err.Error(), batchID)
return
}
c.logger.Errorf("%s: 业务逻辑失败: %v", action, err)
controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "分配空栏失败", action, err.Error(), batchID)
return
}
controller.SendSuccessWithAudit(ctx, controller.CodeSuccess, "分配成功", nil, action, "分配成功", batchID)
handleAPIRequest(
c, ctx, action, &req,
func(ctx *gin.Context, operatorID uint, primaryID uint, req *dto.AssignEmptyPensToBatchRequest) error {
return c.service.AssignEmptyPensToBatch(primaryID, req.PenIDs, operatorID)
},
"分配成功",
nil, // 默认从 ":id" 路径参数提取ID
)
}
// ReclassifyPenToNewBatch godoc
@@ -234,35 +171,24 @@ func (c *PigBatchController) AssignEmptyPensToBatch(ctx *gin.Context) {
// @Router /api/v1/pig-batches/{fromBatchID}/reclassify-pen [post]
func (c *PigBatchController) ReclassifyPenToNewBatch(ctx *gin.Context) {
const action = "划拨猪栏到新批次"
fromBatchID, err := strconv.ParseUint(ctx.Param("fromBatchID"), 10, 32)
if err != nil {
controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, "无效的源猪批次ID格式", action, "ID格式错误", ctx.Param("fromBatchID"))
return
}
var req dto.ReclassifyPenToNewBatchRequest
if err := ctx.ShouldBindJSON(&req); err != nil {
controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, "无效的请求体", action, "请求体绑定失败", req)
return
}
userID, err := controller.GetOperatorIDFromContext(ctx)
err = c.service.ReclassifyPenToNewBatch(uint(fromBatchID), req.ToBatchID, req.PenID, userID, req.Remarks)
if err != nil {
if errors.Is(err, service.ErrPigBatchNotFound) || errors.Is(err, service.ErrPenNotFound) {
controller.SendErrorWithAudit(ctx, controller.CodeNotFound, err.Error(), action, err.Error(), fromBatchID)
return
} else if errors.Is(err, service.ErrPigBatchNotActive) || errors.Is(err, service.ErrPenOccupiedByOtherBatch) || errors.Is(err, service.ErrPenNotAssociatedWithBatch) || errors.Is(err, service.ErrInvalidOperation) {
controller.SendErrorWithAudit(ctx, controller.CodeConflict, err.Error(), action, err.Error(), fromBatchID)
return
}
c.logger.Errorf("%s: 业务逻辑失败: %v", action, err)
controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "划拨猪栏失败", action, err.Error(), fromBatchID)
return
}
controller.SendSuccessWithAudit(ctx, controller.CodeSuccess, "划拨成功", nil, action, "划拨成功", fromBatchID)
handleAPIRequest(
c, ctx, action, &req,
func(ctx *gin.Context, operatorID uint, primaryID uint, req *dto.ReclassifyPenToNewBatchRequest) error {
// primaryID 在这里是 fromBatchID
return c.service.ReclassifyPenToNewBatch(primaryID, req.ToBatchID, req.PenID, operatorID, req.Remarks)
},
"划拨成功",
func(ctx *gin.Context) (uint, error) { // 自定义ID提取器从 ":fromBatchID" 路径参数提取
idParam := ctx.Param("fromBatchID")
parsedID, err := strconv.ParseUint(idParam, 10, 32)
if err != nil {
return 0, err
}
return uint(parsedID), nil
},
)
}
// RemoveEmptyPenFromBatch godoc
@@ -276,33 +202,28 @@ func (c *PigBatchController) ReclassifyPenToNewBatch(ctx *gin.Context) {
// @Router /api/v1/pig-batches/{batchID}/remove-pen/{penID} [delete]
func (c *PigBatchController) RemoveEmptyPenFromBatch(ctx *gin.Context) {
const action = "从猪批次移除空栏"
batchID, err := strconv.ParseUint(ctx.Param("batchID"), 10, 32)
if err != nil {
controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, "无效的猪批次ID格式", action, "ID格式错误", ctx.Param("batchID"))
return
}
penID, err := strconv.ParseUint(ctx.Param("penID"), 10, 32)
if err != nil {
controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, "无效的猪栏ID格式", action, "ID格式错误", ctx.Param("penID"))
return
}
err = c.service.RemoveEmptyPenFromBatch(uint(batchID), uint(penID))
if err != nil {
if errors.Is(err, service.ErrPigBatchNotFound) || errors.Is(err, service.ErrPenNotFound) || errors.Is(err, service.ErrPenNotAssociatedWithBatch) {
controller.SendErrorWithAudit(ctx, controller.CodeNotFound, err.Error(), action, err.Error(), batchID)
return
} else if errors.Is(err, service.ErrPigBatchNotActive) || errors.Is(err, service.ErrPenNotEmpty) {
controller.SendErrorWithAudit(ctx, controller.CodeConflict, err.Error(), action, err.Error(), batchID)
return
}
c.logger.Errorf("%s: 业务逻辑失败: %v", action, err)
controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "移除空栏失败", action, err.Error(), batchID)
return
}
controller.SendSuccessWithAudit(ctx, controller.CodeSuccess, "移除成功", nil, action, "移除成功", batchID)
handleNoBodyAPIRequest(
c, ctx, action,
func(ctx *gin.Context, operatorID uint, primaryID uint) error {
// primaryID 在这里是 batchID
penIDParam := ctx.Param("penID")
penID, err := strconv.ParseUint(penIDParam, 10, 32)
if err != nil {
return err // 返回错误,因为 penID 格式无效
}
return c.service.RemoveEmptyPenFromBatch(primaryID, uint(penID))
},
"移除成功",
func(ctx *gin.Context) (uint, error) { // 自定义ID提取器从 ":batchID" 路径参数提取
idParam := ctx.Param("batchID")
parsedID, err := strconv.ParseUint(idParam, 10, 32)
if err != nil {
return 0, err
}
return uint(parsedID), nil
},
)
}
// MovePigsIntoPen godoc
@@ -317,33 +238,14 @@ func (c *PigBatchController) RemoveEmptyPenFromBatch(ctx *gin.Context) {
// @Router /api/v1/pig-batches/{id}/move-pigs-into-pen [post]
func (c *PigBatchController) MovePigsIntoPen(ctx *gin.Context) {
const action = "将猪只移入猪栏"
batchID, err := strconv.ParseUint(ctx.Param("id"), 10, 32)
if err != nil {
controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, "无效的猪批次ID格式", action, "ID格式错误", ctx.Param("id"))
return
}
var req dto.MovePigsIntoPenRequest
if err := ctx.ShouldBindJSON(&req); err != nil {
controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, "无效的请求体", action, "请求体绑定失败", req)
return
}
userID, err := controller.GetOperatorIDFromContext(ctx)
err = c.service.MovePigsIntoPen(uint(batchID), req.ToPenID, req.Quantity, userID, req.Remarks)
if err != nil {
if errors.Is(err, service.ErrPigBatchNotFound) || errors.Is(err, service.ErrPenNotFound) {
controller.SendErrorWithAudit(ctx, controller.CodeNotFound, err.Error(), action, err.Error(), batchID)
return
} else if errors.Is(err, service.ErrPigBatchNotActive) || errors.Is(err, service.ErrInvalidOperation) {
controller.SendErrorWithAudit(ctx, controller.CodeConflict, err.Error(), action, err.Error(), batchID)
return
}
c.logger.Errorf("%s: 业务逻辑失败: %v", action, err)
controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "移入猪只失败", action, err.Error(), batchID)
return
}
controller.SendSuccessWithAudit(ctx, controller.CodeSuccess, "移入成功", nil, action, "移入成功", batchID)
handleAPIRequest(
c, ctx, action, &req,
func(ctx *gin.Context, operatorID uint, primaryID uint, req *dto.MovePigsIntoPenRequest) error {
return c.service.MovePigsIntoPen(primaryID, req.ToPenID, req.Quantity, operatorID, req.Remarks)
},
"移入成功",
nil, // 默认从 ":id" 路径参数提取ID
)
}