Files
pig-farm-controller/internal/app/controller/plan/plan_controller.go
2025-10-03 23:02:43 +08:00

461 lines
20 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package plan
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/domain/task"
"git.huangwc.com/pig/pig-farm-controller/internal/infra/logs"
"git.huangwc.com/pig/pig-farm-controller/internal/infra/models"
"git.huangwc.com/pig/pig-farm-controller/internal/infra/repository"
"github.com/gin-gonic/gin"
"gorm.io/gorm"
)
// --- Controller 定义 ---
// Controller 定义了计划相关的控制器
type Controller struct {
logger *logs.Logger
planRepo repository.PlanRepository
analysisPlanTaskManager *task.AnalysisPlanTaskManager
}
// NewController 创建一个新的 Controller 实例
func NewController(logger *logs.Logger, planRepo repository.PlanRepository, analysisPlanTaskManager *task.AnalysisPlanTaskManager) *Controller {
return &Controller{
logger: logger,
planRepo: planRepo,
analysisPlanTaskManager: analysisPlanTaskManager,
}
}
// --- 接口方法实现 ---
// CreatePlan godoc
// @Summary 创建计划
// @Description 创建一个新的计划,包括其基本信息和所有关联的子计划/任务。
// @Tags 计划管理
// @Accept json
// @Produce json
// @Param plan body dto.CreatePlanRequest true "计划信息"
// @Success 200 {object} controller.Response{data=dto.PlanResponse} "业务码为201代表创建成功"
// @Router /api/v1/plans [post]
func (c *Controller) CreatePlan(ctx *gin.Context) {
var req dto.CreatePlanRequest
const actionType = "创建计划"
if err := ctx.ShouldBindJSON(&req); err != nil {
c.logger.Errorf("%s: 参数绑定失败: %v", actionType, err)
controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, "无效的请求体: "+err.Error(), actionType, "请求体绑定失败", req)
return
}
// 使用已有的转换函数,它已经包含了验证和重排逻辑
planToCreate, err := dto.NewPlanFromCreateRequest(&req)
if err != nil {
c.logger.Errorf("%s: 计划数据校验失败: %v", actionType, err)
controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, "计划数据校验失败: "+err.Error(), actionType, "计划数据校验失败", req)
return
}
// --- 自动判断 ContentType ---
if len(req.SubPlanIDs) > 0 {
planToCreate.ContentType = models.PlanContentTypeSubPlans
} else {
// 如果 SubPlanIDs 未提供,则默认为 Tasks 类型(即使 Tasks 字段也未提供)
planToCreate.ContentType = models.PlanContentTypeTasks
}
// 调用仓库方法创建计划
if err := c.planRepo.CreatePlan(planToCreate); err != nil {
c.logger.Errorf("%s: 数据库创建计划失败: %v", actionType, err)
controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "创建计划失败: "+err.Error(), actionType, "数据库创建计划失败", planToCreate)
return
}
// 创建成功后,调用 manager 确保触发器任务定义存在,但不立即加入待执行队列
if err := c.analysisPlanTaskManager.EnsureAnalysisTaskDefinition(planToCreate.ID); err != nil {
// 这是一个非阻塞性错误,我们只记录日志,因为主流程(创建计划)已经成功
c.logger.Errorf("为新创建的计划 %d 确保触发器任务定义失败: %v", planToCreate.ID, err)
}
// 使用已有的转换函数将创建后的模型转换为响应对象
resp, err := dto.NewPlanToResponse(planToCreate)
if err != nil {
c.logger.Errorf("%s: 序列化响应失败: %v", actionType, err)
controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "计划创建成功,但响应生成失败", actionType, "响应序列化失败", planToCreate)
return
}
// 使用统一的成功响应函数
c.logger.Infof("%s: 计划创建成功, ID: %d", actionType, planToCreate.ID)
controller.SendSuccessWithAudit(ctx, controller.CodeCreated, "计划创建成功", resp, actionType, "计划创建成功", resp)
}
// GetPlan godoc
// @Summary 获取计划详情
// @Description 根据计划ID获取单个计划的详细信息。
// @Tags 计划管理
// @Produce json
// @Param id path int true "计划ID"
// @Success 200 {object} controller.Response{data=dto.PlanResponse} "业务码为200代表成功获取"
// @Router /api/v1/plans/{id} [get]
func (c *Controller) GetPlan(ctx *gin.Context) {
const actionType = "获取计划详情"
// 1. 从 URL 路径中获取 ID
idStr := ctx.Param("id")
id, err := strconv.ParseUint(idStr, 10, 32)
if err != nil {
c.logger.Errorf("%s: 计划ID格式错误: %v, ID: %s", actionType, err, idStr)
controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, "无效的计划ID格式", actionType, "计划ID格式错误", idStr)
return
}
// 2. 调用仓库层获取计划详情
plan, err := c.planRepo.GetPlanByID(uint(id))
if err != nil {
// 判断是否为“未找到”错误
if errors.Is(err, gorm.ErrRecordNotFound) {
c.logger.Warnf("%s: 计划不存在, ID: %d", actionType, id)
controller.SendErrorWithAudit(ctx, controller.CodeNotFound, "计划不存在", actionType, "计划不存在", id)
return
}
// 其他数据库错误视为内部错误
c.logger.Errorf("%s: 数据库查询失败: %v, ID: %d", actionType, err, id)
controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "获取计划详情时发生内部错误", actionType, "数据库查询失败", id)
return
}
// 3. 将模型转换为响应 DTO
resp, err := dto.NewPlanToResponse(plan)
if err != nil {
c.logger.Errorf("%s: 序列化响应失败: %v, Plan: %+v", actionType, err, plan)
controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "获取计划详情失败: 内部数据格式错误", actionType, "响应序列化失败", plan)
return
}
// 4. 发送成功响应
c.logger.Infof("%s: 获取计划详情成功, ID: %d", actionType, id)
controller.SendSuccessWithAudit(ctx, controller.CodeSuccess, "获取计划详情成功", resp, actionType, "获取计划详情成功", resp)
}
// ListPlans godoc
// @Summary 获取计划列表
// @Description 获取所有计划的列表
// @Tags 计划管理
// @Produce json
// @Success 200 {object} controller.Response{data=[]dto.PlanResponse} "业务码为200代表成功获取列表"
// @Router /api/v1/plans [get]
func (c *Controller) ListPlans(ctx *gin.Context) {
const actionType = "获取计划列表"
// 1. 调用仓库层获取所有计划
plans, err := c.planRepo.ListBasicPlans()
if err != nil {
c.logger.Errorf("%s: 数据库查询失败: %v", actionType, err)
controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "获取计划列表时发生内部错误", actionType, "数据库查询失败", nil)
return
}
// 2. 将模型转换为响应 DTO
planResponses := make([]dto.PlanResponse, 0, len(plans))
for _, p := range plans {
resp, err := dto.NewPlanToResponse(&p)
if err != nil {
c.logger.Errorf("%s: 序列化响应失败: %v, Plan: %+v", actionType, err, p)
controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "获取计划列表失败: 内部数据格式错误", actionType, "响应序列化失败", p)
return
}
planResponses = append(planResponses, *resp)
}
// 3. 构造并发送成功响应
resp := dto.ListPlansResponse{
Plans: planResponses,
Total: len(planResponses),
}
c.logger.Infof("%s: 获取计划列表成功, 数量: %d", actionType, len(planResponses))
controller.SendSuccessWithAudit(ctx, controller.CodeSuccess, "获取计划列表成功", resp, actionType, "获取计划列表成功", resp)
}
// UpdatePlan godoc
// @Summary 更新计划
// @Description 根据计划ID更新计划的详细信息。
// @Tags 计划管理
// @Accept json
// @Produce json
// @Param id path int true "计划ID"
// @Param plan body dto.UpdatePlanRequest true "更新后的计划信息"
// @Success 200 {object} controller.Response{data=dto.PlanResponse} "业务码为200代表更新成功"
// @Router /api/v1/plans/{id} [put]
func (c *Controller) UpdatePlan(ctx *gin.Context) {
const actionType = "更新计划"
// 1. 从 URL 路径中获取 ID
idStr := ctx.Param("id")
id, err := strconv.ParseUint(idStr, 10, 32)
if err != nil {
c.logger.Errorf("%s: 计划ID格式错误: %v, ID: %s", actionType, err, idStr)
controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, "无效的计划ID格式", actionType, "计划ID格式错误", idStr)
return
}
// 2. 绑定请求体
var req dto.UpdatePlanRequest
if err := ctx.ShouldBindJSON(&req); err != nil {
c.logger.Errorf("%s: 参数绑定失败: %v", actionType, err)
controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, "无效的请求体: "+err.Error(), actionType, "请求体绑定失败", req)
return
}
// 3. 将请求转换为模型(转换函数带校验)
planToUpdate, err := dto.NewPlanFromUpdateRequest(&req)
if err != nil {
c.logger.Errorf("%s: 计划数据校验失败: %v", actionType, err)
controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, "计划数据校验失败: "+err.Error(), actionType, "计划数据校验失败", req)
return
}
planToUpdate.ID = uint(id) // 确保ID被设置
// --- 自动判断 ContentType ---
if len(req.SubPlanIDs) > 0 {
planToUpdate.ContentType = models.PlanContentTypeSubPlans
} else {
// 如果 SubPlanIDs 未提供,则默认为 Tasks 类型(即使 Tasks 字段也未提供)
planToUpdate.ContentType = models.PlanContentTypeTasks
}
// 4. 检查计划是否存在
_, err = c.planRepo.GetBasicPlanByID(uint(id))
if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
c.logger.Warnf("%s: 计划不存在, ID: %d", actionType, id)
controller.SendErrorWithAudit(ctx, controller.CodeNotFound, "计划不存在", actionType, "计划不存在", id)
return
}
c.logger.Errorf("%s: 获取计划信息失败: %v, ID: %d", actionType, err, id)
controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "获取计划信息时发生内部错误", actionType, "数据库查询失败", id)
return
}
// 5. 调用仓库方法更新计划
// 只要是更新任务,就重置执行计数器
planToUpdate.ExecuteCount = 0 // 重置计数器
c.logger.Infof("计划 #%d 被更新,执行计数器已重置为 0。", planToUpdate.ID)
if err := c.planRepo.UpdatePlan(planToUpdate); err != nil {
c.logger.Errorf("%s: 数据库更新计划失败: %v, Plan: %+v", actionType, err, planToUpdate)
controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "更新计划失败: "+err.Error(), actionType, "数据库更新计划失败", planToUpdate)
return
}
// 更新成功后,调用 manager 确保触发器任务定义存在
if err := c.analysisPlanTaskManager.EnsureAnalysisTaskDefinition(planToUpdate.ID); err != nil {
// 这是一个非阻塞性错误,我们只记录日志
c.logger.Errorf("为更新后的计划 %d 确保触发器任务定义失败: %v", planToUpdate.ID, err)
}
// 6. 获取更新后的完整计划用于响应
updatedPlan, err := c.planRepo.GetPlanByID(uint(id))
if err != nil {
c.logger.Errorf("%s: 获取更新后计划详情失败: %v, ID: %d", actionType, err, id)
controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "获取更新后计划详情时发生内部错误", actionType, "获取更新后计划详情失败", id)
return
}
// 7. 将模型转换为响应 DTO
resp, err := dto.NewPlanToResponse(updatedPlan)
if err != nil {
c.logger.Errorf("%s: 序列化响应失败: %v, Updated Plan: %+v", actionType, err, updatedPlan)
controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "计划更新成功,但响应生成失败", actionType, "响应序列化失败", updatedPlan)
return
}
// 8. 发送成功响应
c.logger.Infof("%s: 计划更新成功, ID: %d", actionType, updatedPlan.ID)
controller.SendSuccessWithAudit(ctx, controller.CodeSuccess, "计划更新成功", resp, actionType, "计划更新成功", resp)
}
// DeletePlan godoc
// @Summary 删除计划
// @Description 根据计划ID删除计划。软删除
// @Tags 计划管理
// @Produce json
// @Param id path int true "计划ID"
// @Success 200 {object} controller.Response "业务码为200代表删除成功"
// @Router /api/v1/plans/{id} [delete]
func (c *Controller) DeletePlan(ctx *gin.Context) {
const actionType = "删除计划"
// 1. 从 URL 路径中获取 ID
idStr := ctx.Param("id")
id, err := strconv.ParseUint(idStr, 10, 32)
if err != nil {
c.logger.Errorf("%s: 计划ID格式错误: %v, ID: %s", actionType, err, idStr)
controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, "无效的计划ID格式", actionType, "计划ID格式错误", idStr)
return
}
// 2. 检查计划是否存在
plan, err := c.planRepo.GetBasicPlanByID(uint(id))
if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
c.logger.Warnf("%s: 计划不存在, ID: %d", actionType, id)
controller.SendErrorWithAudit(ctx, controller.CodeNotFound, "计划不存在", actionType, "计划不存在", id)
return
}
c.logger.Errorf("%s: 获取计划信息失败: %v, ID: %d", actionType, err, id)
controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "获取计划信息时发生内部错误", actionType, "数据库查询失败", id)
return
}
// 3. 停止这个计划
if plan.Status == models.PlanStatusEnabled {
if err := c.planRepo.StopPlanTransactionally(uint(id)); err != nil {
c.logger.Errorf("%s: 停止计划失败: %v, ID: %d", actionType, err, id)
controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "停止计划时发生内部错误: "+err.Error(), actionType, "停止计划失败", id)
return
}
}
// 4. 调用仓库层删除计划
if err := c.planRepo.DeletePlan(uint(id)); err != nil {
c.logger.Errorf("%s: 数据库删除失败: %v, ID: %d", actionType, err, id)
controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "删除计划时发生内部错误", actionType, "数据库删除失败", id)
return
}
// 5. 发送成功响应
c.logger.Infof("%s: 计划删除成功, ID: %d", actionType, id)
controller.SendSuccessWithAudit(ctx, controller.CodeSuccess, "计划删除成功", nil, actionType, "计划删除成功", id)
}
// StartPlan godoc
// @Summary 启动计划
// @Description 根据计划ID启动一个计划的执行。
// @Tags 计划管理
// @Produce json
// @Param id path int true "计划ID"
// @Success 200 {object} controller.Response "业务码为200代表成功启动计划"
// @Router /api/v1/plans/{id}/start [post]
func (c *Controller) StartPlan(ctx *gin.Context) {
const actionType = "启动计划"
// 1. 从 URL 路径中获取 ID
idStr := ctx.Param("id")
id, err := strconv.ParseUint(idStr, 10, 32)
if err != nil {
c.logger.Errorf("%s: 计划ID格式错误: %v, ID: %s", actionType, err, idStr)
controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, "无效的计划ID格式", actionType, "计划ID格式错误", idStr)
return
}
// 2. 检查计划是否存在
plan, err := c.planRepo.GetBasicPlanByID(uint(id))
if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
c.logger.Warnf("%s: 计划不存在, ID: %d", actionType, id)
controller.SendErrorWithAudit(ctx, controller.CodeNotFound, "计划不存在", actionType, "计划不存在", id)
return
}
c.logger.Errorf("%s: 获取计划信息失败: %v, ID: %d", actionType, err, id)
controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "获取计划信息时发生内部错误", actionType, "数据库查询失败", id)
return
}
// 3. 检查计划当前状态
if plan.Status == models.PlanStatusEnabled {
c.logger.Warnf("%s: 计划已处于启动状态,无需重复操作, ID: %d", actionType, id)
controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, "计划已处于启动状态,无需重复操作", actionType, "计划已处于启动状态", id)
return
}
// 4. 检查并重置执行计数器,然后更新计划状态为“已启动”
// 只有当计划是从非 Enabled 状态(如 Disabled, Stopeed, Failed启动时才需要重置计数器
if plan.Status != models.PlanStatusEnabled {
// 如果计划是从停止或失败状态重新启动且计数器不为0则重置执行计数
if plan.ExecuteCount > 0 {
if err := c.planRepo.UpdateExecuteCount(plan.ID, 0); err != nil {
c.logger.Errorf("%s: 重置计划执行计数失败: %v, ID: %d", actionType, err, plan.ID)
controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "重置计划执行计数失败", actionType, "重置执行计数失败", plan.ID)
return
}
c.logger.Infof("计划 #%d 的执行计数器已重置为 0。", plan.ID)
}
// 更新计划状态为“已启动”
if err := c.planRepo.UpdatePlanStatus(plan.ID, models.PlanStatusEnabled); err != nil {
c.logger.Errorf("%s: 更新计划状态失败: %v, ID: %d", actionType, err, plan.ID)
controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "更新计划状态失败", actionType, "更新计划状态失败", plan.ID)
return
}
c.logger.Infof("已成功更新计划 #%d 的状态为 '已启动'。", plan.ID)
} else {
// 如果计划已经处于 Enabled 状态,则无需更新
c.logger.Infof("计划 #%d 已处于启动状态,无需重复操作。", plan.ID)
controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, "计划已处于启动状态,无需重复操作", actionType, "计划已处于启动状态", plan.ID)
return
}
// 5. 为计划创建或更新触发器
if err := c.analysisPlanTaskManager.CreateOrUpdateTrigger(plan.ID); err != nil {
// 此处错误不回滚状态,因为状态更新已成功,但需要明确告知用户触发器创建失败
c.logger.Errorf("%s: 创建或更新触发器失败: %v, ID: %d", actionType, err, plan.ID)
controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "计划状态已更新,但创建执行触发器失败,请检查计划配置或稍后重试", actionType, "创建执行触发器失败", plan.ID)
return
}
// 6. 发送成功响应
c.logger.Infof("%s: 计划已成功启动, ID: %d", actionType, id)
controller.SendSuccessWithAudit(ctx, controller.CodeSuccess, "计划已成功启动", nil, actionType, "计划已成功启动", id)
}
// StopPlan godoc
// @Summary 停止计划
// @Description 根据计划ID停止一个正在执行的计划。
// @Tags 计划管理
// @Produce json
// @Param id path int true "计划ID"
// @Success 200 {object} controller.Response "业务码为200代表成功停止计划"
// @Router /api/v1/plans/{id}/stop [post]
func (c *Controller) StopPlan(ctx *gin.Context) {
const actionType = "停止计划"
// 1. 从 URL 路径中获取 ID
idStr := ctx.Param("id")
id, err := strconv.ParseUint(idStr, 10, 32)
if err != nil {
c.logger.Errorf("%s: 计划ID格式错误: %v, ID: %s", actionType, err, idStr)
controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, "无效的计划ID格式", actionType, "计划ID格式错误", idStr)
return
}
// 2. 检查计划是否存在
plan, err := c.planRepo.GetBasicPlanByID(uint(id))
if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
c.logger.Warnf("%s: 计划不存在, ID: %d", actionType, id)
controller.SendErrorWithAudit(ctx, controller.CodeNotFound, "计划不存在", actionType, "计划不存在", id)
return
}
c.logger.Errorf("%s: 获取计划信息失败: %v, ID: %d", actionType, err, id)
controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "获取计划信息时发生内部错误", actionType, "数据库查询失败", id)
return
}
// 3. 检查计划当前状态
if plan.Status != models.PlanStatusEnabled {
c.logger.Warnf("%s: 计划当前不是启用状态, ID: %d, Status: %s", actionType, id, plan.Status)
controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, "计划当前不是启用状态", actionType, "计划未启用", id)
return
}
// 4. 调用仓库层方法,该方法内部处理事务
if err := c.planRepo.StopPlanTransactionally(uint(id)); err != nil {
c.logger.Errorf("%s: 停止计划失败: %v, ID: %d", actionType, err, id)
controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "停止计划时发生内部错误: "+err.Error(), actionType, "停止计划失败", id)
return
}
// 5. 发送成功响应
c.logger.Infof("%s: 计划已成功停止, ID: %d", actionType, id)
controller.SendSuccessWithAudit(ctx, controller.CodeSuccess, "计划已成功停止", nil, actionType, "计划已成功停止", id)
}