345 lines
		
	
	
		
			12 KiB
		
	
	
	
		
			Go
		
	
	
	
	
	
			
		
		
	
	
			345 lines
		
	
	
		
			12 KiB
		
	
	
	
		
			Go
		
	
	
	
	
	
package service
 | 
						|
 | 
						|
import (
 | 
						|
	"errors"
 | 
						|
 | 
						|
	"git.huangwc.com/pig/pig-farm-controller/internal/app/dto"
 | 
						|
	"git.huangwc.com/pig/pig-farm-controller/internal/domain/scheduler"
 | 
						|
	"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"
 | 
						|
	"gorm.io/gorm"
 | 
						|
)
 | 
						|
 | 
						|
var (
 | 
						|
	// ErrPlanNotFound 表示未找到计划
 | 
						|
	ErrPlanNotFound = errors.New("计划不存在")
 | 
						|
	// ErrPlanCannotBeModified 表示计划不允许修改
 | 
						|
	ErrPlanCannotBeModified = errors.New("系统计划不允许修改")
 | 
						|
	// ErrPlanCannotBeDeleted 表示计划不允许删除
 | 
						|
	ErrPlanCannotBeDeleted = errors.New("系统计划不允许删除")
 | 
						|
	// ErrPlanCannotBeStarted 表示计划不允许手动启动
 | 
						|
	ErrPlanCannotBeStarted = errors.New("系统计划不允许手动启动")
 | 
						|
	// ErrPlanAlreadyEnabled 表示计划已处于启动状态
 | 
						|
	ErrPlanAlreadyEnabled = errors.New("计划已处于启动状态,无需重复操作")
 | 
						|
	// ErrPlanNotEnabled 表示计划未处于启动状态
 | 
						|
	ErrPlanNotEnabled = errors.New("计划当前不是启用状态")
 | 
						|
	// ErrPlanCannotBeStopped 表示计划不允许停止
 | 
						|
	ErrPlanCannotBeStopped = errors.New("系统计划不允许停止")
 | 
						|
)
 | 
						|
 | 
						|
// PlanService 定义了计划相关的应用服务接口
 | 
						|
type PlanService interface {
 | 
						|
	// CreatePlan 创建一个新的计划
 | 
						|
	CreatePlan(req *dto.CreatePlanRequest) (*dto.PlanResponse, error)
 | 
						|
	// GetPlanByID 根据ID获取计划详情
 | 
						|
	GetPlanByID(id uint) (*dto.PlanResponse, error)
 | 
						|
	// ListPlans 获取计划列表,支持过滤和分页
 | 
						|
	ListPlans(query *dto.ListPlansQuery) (*dto.ListPlansResponse, error)
 | 
						|
	// UpdatePlan 更新计划
 | 
						|
	UpdatePlan(id uint, req *dto.UpdatePlanRequest) (*dto.PlanResponse, error)
 | 
						|
	// DeletePlan 删除计划(软删除)
 | 
						|
	DeletePlan(id uint) error
 | 
						|
	// StartPlan 启动计划
 | 
						|
	StartPlan(id uint) error
 | 
						|
	// StopPlan 停止计划
 | 
						|
	StopPlan(id uint) error
 | 
						|
}
 | 
						|
 | 
						|
// planService 是 PlanService 接口的实现
 | 
						|
type planService struct {
 | 
						|
	logger                  *logs.Logger
 | 
						|
	planRepo                repository.PlanRepository
 | 
						|
	analysisPlanTaskManager *scheduler.AnalysisPlanTaskManager
 | 
						|
}
 | 
						|
 | 
						|
// NewPlanService 创建一个新的 PlanService 实例
 | 
						|
func NewPlanService(
 | 
						|
	logger *logs.Logger,
 | 
						|
	planRepo repository.PlanRepository,
 | 
						|
	analysisPlanTaskManager *scheduler.AnalysisPlanTaskManager,
 | 
						|
) PlanService {
 | 
						|
	return &planService{
 | 
						|
		logger:                  logger,
 | 
						|
		planRepo:                planRepo,
 | 
						|
		analysisPlanTaskManager: analysisPlanTaskManager,
 | 
						|
	}
 | 
						|
}
 | 
						|
 | 
						|
// CreatePlan 创建一个新的计划
 | 
						|
func (s *planService) CreatePlan(req *dto.CreatePlanRequest) (*dto.PlanResponse, error) {
 | 
						|
	const actionType = "服务层:创建计划"
 | 
						|
 | 
						|
	// 使用已有的转换函数,它已经包含了验证和重排逻辑
 | 
						|
	planToCreate, err := dto.NewPlanFromCreateRequest(req)
 | 
						|
	if err != nil {
 | 
						|
		s.logger.Errorf("%s: 计划数据校验失败: %v", actionType, err)
 | 
						|
		return nil, err
 | 
						|
	}
 | 
						|
 | 
						|
	// --- 业务规则处理 ---
 | 
						|
	// 1. 设置计划类型:用户创建的计划永远是自定义计划
 | 
						|
	planToCreate.PlanType = models.PlanTypeCustom
 | 
						|
 | 
						|
	// 2. 自动判断 ContentType
 | 
						|
	if len(req.SubPlanIDs) > 0 {
 | 
						|
		planToCreate.ContentType = models.PlanContentTypeSubPlans
 | 
						|
	} else {
 | 
						|
		// 如果 SubPlanIDs 未提供,则默认为 Tasks 类型(即使 Tasks 字段也未提供)
 | 
						|
		planToCreate.ContentType = models.PlanContentTypeTasks
 | 
						|
	}
 | 
						|
 | 
						|
	// 调用仓库方法创建计划
 | 
						|
	if err := s.planRepo.CreatePlan(planToCreate); err != nil {
 | 
						|
		s.logger.Errorf("%s: 数据库创建计划失败: %v", actionType, err)
 | 
						|
		return nil, err
 | 
						|
	}
 | 
						|
 | 
						|
	// 创建成功后,调用 manager 确保触发器任务定义存在,但不立即加入待执行队列
 | 
						|
	if err := s.analysisPlanTaskManager.EnsureAnalysisTaskDefinition(planToCreate.ID); err != nil {
 | 
						|
		// 这是一个非阻塞性错误,我们只记录日志,因为主流程(创建计划)已经成功
 | 
						|
		s.logger.Errorf("为新创建的计划 %d 确保触发器任务定义失败: %v", planToCreate.ID, err)
 | 
						|
	}
 | 
						|
 | 
						|
	// 使用已有的转换函数将创建后的模型转换为响应对象
 | 
						|
	resp, err := dto.NewPlanToResponse(planToCreate)
 | 
						|
	if err != nil {
 | 
						|
		s.logger.Errorf("%s: 序列化响应失败: %v, Plan: %+v", actionType, err, planToCreate)
 | 
						|
		return nil, errors.New("计划创建成功,但响应生成失败")
 | 
						|
	}
 | 
						|
 | 
						|
	s.logger.Infof("%s: 计划创建成功, ID: %d", actionType, planToCreate.ID)
 | 
						|
	return resp, nil
 | 
						|
}
 | 
						|
 | 
						|
// GetPlanByID 根据ID获取计划详情
 | 
						|
func (s *planService) GetPlanByID(id uint) (*dto.PlanResponse, error) {
 | 
						|
	const actionType = "服务层:获取计划详情"
 | 
						|
 | 
						|
	plan, err := s.planRepo.GetPlanByID(id)
 | 
						|
	if err != nil {
 | 
						|
		if errors.Is(err, gorm.ErrRecordNotFound) {
 | 
						|
			s.logger.Warnf("%s: 计划不存在, ID: %d", actionType, id)
 | 
						|
			return nil, ErrPlanNotFound
 | 
						|
		}
 | 
						|
		s.logger.Errorf("%s: 数据库查询失败: %v, ID: %d", actionType, err, id)
 | 
						|
		return nil, err
 | 
						|
	}
 | 
						|
 | 
						|
	resp, err := dto.NewPlanToResponse(plan)
 | 
						|
	if err != nil {
 | 
						|
		s.logger.Errorf("%s: 序列化响应失败: %v, Plan: %+v", actionType, err, plan)
 | 
						|
		return nil, errors.New("获取计划详情失败: 内部数据格式错误")
 | 
						|
	}
 | 
						|
 | 
						|
	s.logger.Infof("%s: 获取计划详情成功, ID: %d", actionType, id)
 | 
						|
	return resp, nil
 | 
						|
}
 | 
						|
 | 
						|
// ListPlans 获取计划列表,支持过滤和分页
 | 
						|
func (s *planService) ListPlans(query *dto.ListPlansQuery) (*dto.ListPlansResponse, error) {
 | 
						|
	const actionType = "服务层:获取计划列表"
 | 
						|
 | 
						|
	opts := repository.ListPlansOptions{PlanType: query.PlanType}
 | 
						|
	plans, total, err := s.planRepo.ListPlans(opts, query.Page, query.PageSize)
 | 
						|
	if err != nil {
 | 
						|
		s.logger.Errorf("%s: 数据库查询失败: %v", actionType, err)
 | 
						|
		return nil, err
 | 
						|
	}
 | 
						|
 | 
						|
	planResponses := make([]dto.PlanResponse, 0, len(plans))
 | 
						|
	for _, p := range plans {
 | 
						|
		resp, err := dto.NewPlanToResponse(&p)
 | 
						|
		if err != nil {
 | 
						|
			s.logger.Errorf("%s: 序列化单个计划响应失败: %v, Plan: %+v", actionType, err, p)
 | 
						|
			// 这里选择跳过有问题的计划,并记录错误,而不是中断整个列表的返回
 | 
						|
			continue
 | 
						|
		}
 | 
						|
		planResponses = append(planResponses, *resp)
 | 
						|
	}
 | 
						|
 | 
						|
	resp := &dto.ListPlansResponse{
 | 
						|
		Plans: planResponses,
 | 
						|
		Total: total,
 | 
						|
	}
 | 
						|
	s.logger.Infof("%s: 获取计划列表成功, 数量: %d", actionType, len(planResponses))
 | 
						|
	return resp, nil
 | 
						|
}
 | 
						|
 | 
						|
// UpdatePlan 更新计划
 | 
						|
func (s *planService) UpdatePlan(id uint, req *dto.UpdatePlanRequest) (*dto.PlanResponse, error) {
 | 
						|
	const actionType = "服务层:更新计划"
 | 
						|
 | 
						|
	existingPlan, err := s.planRepo.GetBasicPlanByID(id)
 | 
						|
	if err != nil {
 | 
						|
		if errors.Is(err, gorm.ErrRecordNotFound) {
 | 
						|
			s.logger.Warnf("%s: 计划不存在, ID: %d", actionType, id)
 | 
						|
			return nil, ErrPlanNotFound
 | 
						|
		}
 | 
						|
		s.logger.Errorf("%s: 获取计划信息失败: %v, ID: %d", actionType, err, id)
 | 
						|
		return nil, err
 | 
						|
	}
 | 
						|
 | 
						|
	if existingPlan.PlanType == models.PlanTypeSystem {
 | 
						|
		s.logger.Warnf("%s: 尝试修改系统计划, ID: %d", actionType, id)
 | 
						|
		return nil, ErrPlanCannotBeModified
 | 
						|
	}
 | 
						|
 | 
						|
	planToUpdate, err := dto.NewPlanFromUpdateRequest(req)
 | 
						|
	if err != nil {
 | 
						|
		s.logger.Errorf("%s: 计划数据校验失败: %v", actionType, err)
 | 
						|
		return nil, err
 | 
						|
	}
 | 
						|
	planToUpdate.ID = id // 确保ID被设置
 | 
						|
 | 
						|
	if len(req.SubPlanIDs) > 0 {
 | 
						|
		planToUpdate.ContentType = models.PlanContentTypeSubPlans
 | 
						|
	} else {
 | 
						|
		planToUpdate.ContentType = models.PlanContentTypeTasks
 | 
						|
	}
 | 
						|
 | 
						|
	// 只要是更新任务,就重置执行计数器
 | 
						|
	planToUpdate.ExecuteCount = 0
 | 
						|
	s.logger.Infof("计划 #%d 被更新,执行计数器已重置为 0。", planToUpdate.ID)
 | 
						|
 | 
						|
	if err := s.planRepo.UpdatePlan(planToUpdate); err != nil {
 | 
						|
		s.logger.Errorf("%s: 数据库更新计划失败: %v, Plan: %+v", actionType, err, planToUpdate)
 | 
						|
		return nil, err
 | 
						|
	}
 | 
						|
 | 
						|
	if err := s.analysisPlanTaskManager.EnsureAnalysisTaskDefinition(planToUpdate.ID); err != nil {
 | 
						|
		s.logger.Errorf("为更新后的计划 %d 确保触发器任务定义失败: %v", planToUpdate.ID, err)
 | 
						|
	}
 | 
						|
 | 
						|
	updatedPlan, err := s.planRepo.GetPlanByID(id)
 | 
						|
	if err != nil {
 | 
						|
		s.logger.Errorf("%s: 获取更新后计划详情失败: %v, ID: %d", actionType, err, id)
 | 
						|
		return nil, errors.New("获取更新后计划详情时发生内部错误")
 | 
						|
	}
 | 
						|
 | 
						|
	resp, err := dto.NewPlanToResponse(updatedPlan)
 | 
						|
	if err != nil {
 | 
						|
		s.logger.Errorf("%s: 序列化响应失败: %v, Updated Plan: %+v", actionType, err, updatedPlan)
 | 
						|
		return nil, errors.New("计划更新成功,但响应生成失败")
 | 
						|
	}
 | 
						|
 | 
						|
	s.logger.Infof("%s: 计划更新成功, ID: %d", actionType, updatedPlan.ID)
 | 
						|
	return resp, nil
 | 
						|
}
 | 
						|
 | 
						|
// DeletePlan 删除计划(软删除)
 | 
						|
func (s *planService) DeletePlan(id uint) error {
 | 
						|
	const actionType = "服务层:删除计划"
 | 
						|
 | 
						|
	plan, err := s.planRepo.GetBasicPlanByID(id)
 | 
						|
	if err != nil {
 | 
						|
		if errors.Is(err, gorm.ErrRecordNotFound) {
 | 
						|
			s.logger.Warnf("%s: 计划不存在, ID: %d", actionType, id)
 | 
						|
			return ErrPlanNotFound
 | 
						|
		}
 | 
						|
		s.logger.Errorf("%s: 获取计划信息失败: %v, ID: %d", actionType, err, id)
 | 
						|
		return err
 | 
						|
	}
 | 
						|
 | 
						|
	if plan.PlanType == models.PlanTypeSystem {
 | 
						|
		s.logger.Warnf("%s: 尝试删除系统计划, ID: %d", actionType, id)
 | 
						|
		return ErrPlanCannotBeDeleted
 | 
						|
	}
 | 
						|
 | 
						|
	if plan.Status == models.PlanStatusEnabled {
 | 
						|
		if err := s.planRepo.StopPlanTransactionally(id); err != nil {
 | 
						|
			s.logger.Errorf("%s: 停止计划失败: %v, ID: %d", actionType, err, id)
 | 
						|
			return err
 | 
						|
		}
 | 
						|
	}
 | 
						|
 | 
						|
	if err := s.planRepo.DeletePlan(id); err != nil {
 | 
						|
		s.logger.Errorf("%s: 数据库删除失败: %v, ID: %d", actionType, err, id)
 | 
						|
		return err
 | 
						|
	}
 | 
						|
 | 
						|
	s.logger.Infof("%s: 计划删除成功, ID: %d", actionType, id)
 | 
						|
	return nil
 | 
						|
}
 | 
						|
 | 
						|
// StartPlan 启动计划
 | 
						|
func (s *planService) StartPlan(id uint) error {
 | 
						|
	const actionType = "服务层:启动计划"
 | 
						|
 | 
						|
	plan, err := s.planRepo.GetBasicPlanByID(id)
 | 
						|
	if err != nil {
 | 
						|
		if errors.Is(err, gorm.ErrRecordNotFound) {
 | 
						|
			s.logger.Warnf("%s: 计划不存在, ID: %d", actionType, id)
 | 
						|
			return ErrPlanNotFound
 | 
						|
		}
 | 
						|
		s.logger.Errorf("%s: 获取计划信息失败: %v, ID: %d", actionType, err, id)
 | 
						|
		return err
 | 
						|
	}
 | 
						|
 | 
						|
	if plan.PlanType == models.PlanTypeSystem {
 | 
						|
		s.logger.Warnf("%s: 尝试手动启动系统计划, ID: %d", actionType, id)
 | 
						|
		return ErrPlanCannotBeStarted
 | 
						|
	}
 | 
						|
	if plan.Status == models.PlanStatusEnabled {
 | 
						|
		s.logger.Warnf("%s: 计划已处于启动状态,无需重复操作, ID: %d", actionType, id)
 | 
						|
		return ErrPlanAlreadyEnabled
 | 
						|
	}
 | 
						|
 | 
						|
	if plan.Status != models.PlanStatusEnabled {
 | 
						|
		if plan.ExecuteCount > 0 {
 | 
						|
			if err := s.planRepo.UpdateExecuteCount(plan.ID, 0); err != nil {
 | 
						|
				s.logger.Errorf("%s: 重置计划执行计数失败: %v, ID: %d", actionType, err, plan.ID)
 | 
						|
				return err
 | 
						|
			}
 | 
						|
			s.logger.Infof("计划 #%d 的执行计数器已重置为 0。", plan.ID)
 | 
						|
		}
 | 
						|
 | 
						|
		if err := s.planRepo.UpdatePlanStatus(plan.ID, models.PlanStatusEnabled); err != nil {
 | 
						|
			s.logger.Errorf("%s: 更新计划状态失败: %v, ID: %d", actionType, err, plan.ID)
 | 
						|
			return err
 | 
						|
		}
 | 
						|
		s.logger.Infof("已成功更新计划 #%d 的状态为 '已启动'。", plan.ID)
 | 
						|
	}
 | 
						|
 | 
						|
	if err := s.analysisPlanTaskManager.CreateOrUpdateTrigger(plan.ID); err != nil {
 | 
						|
		s.logger.Errorf("%s: 创建或更新触发器失败: %v, ID: %d", actionType, err, plan.ID)
 | 
						|
		return err
 | 
						|
	}
 | 
						|
 | 
						|
	s.logger.Infof("%s: 计划已成功启动, ID: %d", actionType, id)
 | 
						|
	return nil
 | 
						|
}
 | 
						|
 | 
						|
// StopPlan 停止计划
 | 
						|
func (s *planService) StopPlan(id uint) error {
 | 
						|
	const actionType = "服务层:停止计划"
 | 
						|
 | 
						|
	plan, err := s.planRepo.GetBasicPlanByID(id)
 | 
						|
	if err != nil {
 | 
						|
		if errors.Is(err, gorm.ErrRecordNotFound) {
 | 
						|
			s.logger.Warnf("%s: 计划不存在, ID: %d", actionType, id)
 | 
						|
			return ErrPlanNotFound
 | 
						|
		}
 | 
						|
		s.logger.Errorf("%s: 获取计划信息失败: %v, ID: %d", actionType, err, id)
 | 
						|
		return err
 | 
						|
	}
 | 
						|
 | 
						|
	if plan.PlanType == models.PlanTypeSystem {
 | 
						|
		s.logger.Warnf("%s: 尝试停止系统计划, ID: %d", actionType, id)
 | 
						|
		return ErrPlanCannotBeStopped
 | 
						|
	}
 | 
						|
 | 
						|
	if plan.Status != models.PlanStatusEnabled {
 | 
						|
		s.logger.Warnf("%s: 计划当前不是启用状态, ID: %d, Status: %s", actionType, id, plan.Status)
 | 
						|
		return ErrPlanNotEnabled
 | 
						|
	}
 | 
						|
 | 
						|
	if err := s.planRepo.StopPlanTransactionally(id); err != nil {
 | 
						|
		s.logger.Errorf("%s: 停止计划失败: %v, ID: %d", actionType, err, id)
 | 
						|
		return err
 | 
						|
	}
 | 
						|
 | 
						|
	s.logger.Infof("%s: 计划已成功停止, ID: %d", actionType, id)
 | 
						|
	return nil
 | 
						|
}
 |