# PastReservationSchedulerController.java

    package cloud.wconnect.frontoffice.controller.pastreservation;

    import cloud.wconnect.commonlib.annotation.ApiId;
    import cloud.wconnect.commonlib.component.BeanMapper;
    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.pojo.dto.PropertyDTO;
    import cloud.wconnect.commonlib.redis.PropertyI18nRedisService;
    import cloud.wconnect.commonlib.util.CronRuleUtil;
    import cloud.wconnect.frontoffice.entity.pastreservation.PastReservationSchedulerJob;
    import cloud.wconnect.frontoffice.pojo.dto.pastreservation.PastReservationSchedulerDTO;
    import cloud.wconnect.frontoffice.service.pastreservation.IPastReservationSchedulerJobService;
    import com.fasterxml.jackson.databind.ObjectMapper;
    import com.google.common.collect.ImmutableMap;
    import com.google.common.collect.Lists;
    import jakarta.validation.Valid;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.web.bind.annotation.*;

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

    /**
     * @author: yyt
     * 2024-10-2
     */
    @RestController
    @RequestMapping("/past-reservations/scheduler")
    public class PastReservationSchedulerController {

        @Autowired
        private BeanMapper beanMapper;
        @Autowired
        private SessionContext sessionContext;
        @Autowired
        private IPastReservationSchedulerJobService schedulerJobService;
        @Autowired
        private PropertyI18nRedisService propertyI18nRedisService;
        @Autowired
        private ObjectMapper objectMapper;

        /**
         * 1263 - 查询定时任务
         *
         * @param property 资产标识
         * @param category 类型 (1：guest in house 报告缺失，2：连续入住通知，4：credit limit 报告缺失)
         * @return 定时任务
         * @author yyt
         * @date 2024/10/2
         */
        @ApiId(1263)
        @GetMapping("/{category:\\d+}")
        public List<PastReservationSchedulerDTO> get(String property, @PathVariable int category) {
            Integer propertyId = sessionContext.getPropertyId(property);
            // 查询非删除中的定时任务
            List<PastReservationSchedulerJob> schedulers = schedulerJobService.list(propertyId, category, String.valueOf(0));

            return beanMapper.mapList(schedulers, PastReservationSchedulerDTO.class);
        }

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

            PropertyDTO propertyDTO = propertyI18nRedisService.get(sessionContext.getPropertyId(property));
            Integer propertyId = propertyDTO.getId();

            if (!Lists.newArrayList(PastReservationSchedulerDTO.MISSING_REPORT_GUEST_IN_HOUSE, PastReservationSchedulerDTO.MISSING_REPORT_CREDIT_LIMIT)
                    .contains(schedulerDTO.getCategory())) {
                schedulerDTO.setParameters("{}");
            }

            // 校验 scheduler 不能重复
            checkSchedulerRepeat(propertyId, schedulerDTO.getCategory(), schedulerDTO.getScheduler(), id);

            if (id.equals("0")) {
                if (schedulerDTO.getCategory() == PastReservationSchedulerDTO.NOTIFY_CONSECUTIVE_STAY) {
                    // 未删除状态下，连续入住通知，最多只能创建 5个
                    schedulerJobService.checkCountLimit(propertyId, schedulerDTO.getCategory(), 5);
                } else if(schedulerDTO.getCategory() == PastReservationSchedulerDTO.MISSING_REPORT_GUEST_IN_HOUSE) {
                    // 未删除状态下，guest in house 报告缺失，最多只能创建 2个
                    schedulerJobService.checkCountLimit(propertyId, schedulerDTO.getCategory(), 2);
                } else {
                    // 未删除状态下，credit limit 报告缺失，最多只能创建 1个
                    schedulerJobService.checkCountLimit(propertyId, schedulerDTO.getCategory(), 1);
                }

                id = schedulerJobService.save(propertyDTO, schedulerDTO, sessionContext.getLoginUserId());
            } else {
                //校验调度任务是否存在
                PastReservationSchedulerJob scheduler = schedulerJobService.checkExist(id);

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

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

                id = schedulerJobService.update(propertyDTO, scheduler, schedulerDTO, sessionContext.getLoginUserId());
            }

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

        /**
         * 校验 scheduler 不能重复
         *
         * @param propertyId      资产 id
         * @param category        分类
         * @param updateScheduler 修改后的 scheduler
         * @param id              排除自身
         * @author yyt
         * @date 2024/3/19
         **/
        private void checkSchedulerRepeat(Integer propertyId, Integer category, String updateScheduler, String id) {
            List<PastReservationSchedulerJob> existSchedulerJobs = schedulerJobService.list(propertyId, category, id);
            if (existSchedulerJobs.isEmpty()) {
                return;
            }

            CronRuleUtil.checkSchedulerRepeat(objectMapper, existSchedulerJobs.stream().map(PastReservationSchedulerJob::getScheduler).toList(), updateScheduler);
        }

        /**
         * 1265 - 删除定时任务
         *
         * @param property 资产标识
         * @param id       定时任务 id
         * @return {}
         * @author yyt
         * @date 2024/10/2
         **/
        @ApiId(1265)
        @DeleteMapping("/{id}")
        public Map<String, Object> delete(String property, @PathVariable String id) {
            PropertyDTO propertyDTO = propertyI18nRedisService.get(sessionContext.getPropertyId(property));
            //校验调度任务是否存在
            PastReservationSchedulerJob scheduler = schedulerJobService.checkExist(id);

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

            if (scheduler.getStatus() == SchedulerCons.STATUS_DELETING) {
                throw new BadRequestException(CommonErrorI18nConstant.SCHEDULER_CANNOT_DELETE_DELETING,
                        BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                        "deleting scheduler do not support deletion; schedulerId:" + id);
            }
            if (Lists.newArrayList(PastReservationSchedulerDTO.MISSING_REPORT_GUEST_IN_HOUSE, PastReservationSchedulerDTO.MISSING_REPORT_CREDIT_LIMIT)
                    .contains(scheduler.getCategory())) {
                throw new BadRequestException(CommonErrorI18nConstant.SCHEDULER_CANNOT_DELETE,
                        BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                        "scheduler that report missing types do not support deletion; schedulerId:" + id);
            }

            schedulerJobService.delete(propertyDTO, scheduler);

            return Collections.emptyMap();
        }

        /**
         * 校验定时规则
         *
         * @param schedulerDTO 定时
         * @author yyt
         * @date 2024/10/2
         **/
        private void checkScheduler(PastReservationSchedulerDTO schedulerDTO) {
            switch (schedulerDTO.getCategory()) {
                case PastReservationSchedulerDTO.MISSING_REPORT_GUEST_IN_HOUSE, PastReservationSchedulerDTO.MISSING_REPORT_CREDIT_LIMIT -> {
                    // 检查 scheduler json 格式是否合法，目前支持配置按天执行；
                    CronRuleUtil.validateCronRuleForScheduler(objectMapper, List.of(SchedulerCons.EVERY_DAY), schedulerDTO.getScheduler());
                }
                case PastReservationSchedulerDTO.NOTIFY_CONSECUTIVE_STAY -> {
                    // 检查 scheduler json 格式是否合法，目前支持配置按天 / 周/ 月 执行
                    CronRuleUtil.validateCronRuleForScheduler(objectMapper,
                            List.of(SchedulerCons.EVERY_DAY, SchedulerCons.EVERY_WEEK, SchedulerCons.EVERY_MONTH),
                            schedulerDTO.getScheduler());
                }
            }
        }

        /**
         * 校验数据归属
         *
         * @param schedulerJob 定时任务
         * @param propertyId   资产 id
         * @author yyt
         * @date 2024/10/2
         */
        private void checkBelong(PastReservationSchedulerJob 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 scheduler;propertyId:" + propertyId + ",schedulerPropertyId:" +
                        schedulerJob.getPropertyId() + ",schedulerId:" + schedulerJob.getId());
            }
        }

    }