# ScheduleSchedulerJobController.java

    package cloud.wconnect.workperformance.controller.schedule;

    import cloud.wconnect.commonlib.annotation.ApiId;
    import cloud.wconnect.commonlib.component.SessionContext;
    import cloud.wconnect.commonlib.cons.BaseErrorCodeEnum;
    import cloud.wconnect.commonlib.cons.CommonErrorI18nConstant;
    import cloud.wconnect.commonlib.cons.SchedulerCons;
    import cloud.wconnect.commonlib.exception.BadRequestException;
    import cloud.wconnect.commonlib.exception.ForbiddenException;
    import cloud.wconnect.commonlib.redis.PropertyI18nRedisService;
    import cloud.wconnect.commonlib.util.CronRuleUtil;
    import cloud.wconnect.commonlib.util.I18nMessageUtils;
    import cloud.wconnect.commonlib.util.JobParameterUtils;
    import cloud.wconnect.workperformance.entity.schedule.ScheduleSchedulerJob;
    import cloud.wconnect.workperformance.pojo.dto.schedule.ScheduleSchedulerDTO;
    import cloud.wconnect.workperformance.service.schedule.IScheduleSchedulerJobService;
    import com.fasterxml.jackson.databind.ObjectMapper;
    import com.google.common.collect.ImmutableMap;
    import jakarta.validation.Valid;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.web.bind.annotation.*;

    import java.util.List;
    import java.util.Map;

    /**
     * <p>
     *  前端控制器
     * </p>
     *
     * @author yyt
     * @since 2024-03-15
     */
    @RestController
    @RequestMapping("/schedule/scheduler")
    public class ScheduleSchedulerJobController {

        @Autowired
        private SessionContext sessionContext;
        @Autowired
        private IScheduleSchedulerJobService schedulerJobService;
        @Autowired
        private ObjectMapper objectMapper;
        @Autowired
        private I18nMessageUtils i18nMessageUtils;

        /**
         * 查询定时任务
         *
         * @param property 资产标识
         * @param category  类型（1：employee 报告缺失，3：history and forecast 报告缺失）
         * @return 定时任务
         * @author yyt
         * @date 2024/3/15
         */
        @ApiId(1082)
        @GetMapping("/{category:\\d+}")
        public List<ScheduleSchedulerDTO> list(String property, @PathVariable int category) {
            Integer propertyId = sessionContext.getPropertyId(property);
            return schedulerJobService.listDTO(propertyId, category);
        }

        /**
         * 保存定时任务
         *
         * @param property     资产标识
         * @param id           定时任务 id
         * @param schedulerDTO 定时任务
         * @return {}
         * @author yyt
         * @date 2024/3/15
         */
        @ApiId(1083)
        @PostMapping("/{id}")
        public Map<String, String> save(String property, @PathVariable String id, @Valid @RequestBody ScheduleSchedulerDTO schedulerDTO) {
            // 校验定时规则
            checkScheduler(schedulerDTO);

            Integer propertyId = sessionContext.getPropertyId(property);
            int loginUserId = sessionContext.getLoginUserId();

            if (id.equals("0")) {
                // 限制 同一个 category 只能存在一条未删除中的数据
                schedulerJobService.checkRepeat(propertyId, schedulerDTO.getCategory());

                id = schedulerJobService.save(propertyId, schedulerDTO, loginUserId);
            } else {
                //校验调度任务是否存在
                ScheduleSchedulerJob scheduler = schedulerJobService.checkExist(id);

                //校验是否归属于资产
                checkBelong(scheduler, propertyId);

                if (scheduler.getStatus() == SchedulerCons.STATUS_DELETING) {
                    throw new BadRequestException(CommonErrorI18nConstant.SCHEDULER_CANNOT_UPDATE_DELETING,
                            BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                            "deleting scheduleScheduler do not support update; scheduleSchedulerId:" + id);
                }
                if (!scheduler.getCategory().equals(schedulerDTO.getCategory())) {
                    throw new BadRequestException(CommonErrorI18nConstant.SCHEDULER_CANNOT_CHANGE_CATEGORY,
                            BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                            "scheduleScheduler category do not support update; scheduleSchedulerId:" + id);
                }

                id = schedulerJobService.update(propertyId, scheduler, schedulerDTO, loginUserId);
            }

            return ImmutableMap.of("id", id);
        }

        /**
         * 校验定时规则
         *
         * @param schedulerDTO 定时
         * @author yyt
         * @date 2024/3/15
         **/
        private void checkScheduler(ScheduleSchedulerDTO schedulerDTO) {
            switch (schedulerDTO.getCategory()) {
                case ScheduleSchedulerDTO.MISSING_EMPLOYEE_REPORT, ScheduleSchedulerDTO.MISSING_HISTORY_AND_FORECAST_REPORT -> {
                    // 检查 scheduler json 格式是否合法，目前支持配置按天执行；
                    CronRuleUtil.validateCronRuleForScheduler(objectMapper, List.of(SchedulerCons.EVERY_DAY), schedulerDTO.getScheduler());

                    //检查 parameters json 格式是否合法
                    JobParameterUtils.checkParametersThreshold(objectMapper, schedulerDTO.getParameters(), i18nMessageUtils);
                }
            }
        }

        /**
         * 校验数据归属
         *
         * @param schedulerJob 定时任务
         * @param propertyId   资产 id
         * @author yyt
         * @date 2024/3/15
         */
        private void checkBelong(ScheduleSchedulerJob schedulerJob, Integer propertyId) {
            if (!schedulerJob.getPropertyId().equals(propertyId)) {
                throw new ForbiddenException(BaseErrorCodeEnum.DATA_FORBIDDEN.getI18nCode(),
                        BaseErrorCodeEnum.DATA_FORBIDDEN.getCode(), "the property id parameter is different from " +
                        "the property id of the scheduleSchedulerJob;propertyId:" + propertyId + ",scheduleSchedulerJobPropertyId:" +
                        schedulerJob.getPropertyId() + ",scheduleSchedulerJobId:" + schedulerJob.getId());
            }
        }

    }