maven
2026-03-02 d6c07c838abeabdd23c4fdcfc69e08a9aaa9725f
yys 劳保报表开发
已添加7个文件
已修改7个文件
992 ■■■■■ 文件已修改
src/main/java/com/ruoyi/device/controller/MaintenanceTaskController.java 60 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/main/java/com/ruoyi/device/mapper/MaintenanceTaskMapper.java 11 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/main/java/com/ruoyi/device/pojo/DeviceMaintenance.java 15 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/main/java/com/ruoyi/device/pojo/DeviceRepair.java 5 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/main/java/com/ruoyi/device/pojo/MaintenanceTask.java 113 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/main/java/com/ruoyi/device/service/MaintenanceTaskService.java 22 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/main/java/com/ruoyi/device/service/impl/DeviceRepairServiceImpl.java 1 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/main/java/com/ruoyi/device/service/impl/MaintenanceTaskJob.java 243 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/main/java/com/ruoyi/device/service/impl/MaintenanceTaskScheduler.java 278 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/main/java/com/ruoyi/device/service/impl/MaintenanceTaskServiceImpl.java 119 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/main/java/com/ruoyi/inspectiontask/service/impl/TimingTaskServiceImpl.java 2 ●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/main/java/com/ruoyi/lavorissue/controller/LavorIssueController.java 21 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/main/java/com/ruoyi/lavorissue/service/LavorIssueService.java 6 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/main/java/com/ruoyi/lavorissue/service/impl/LavorIssueServiceImpl.java 96 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/main/java/com/ruoyi/device/controller/MaintenanceTaskController.java
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,60 @@
package com.ruoyi.device.controller;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.device.pojo.MaintenanceTask;
import com.ruoyi.device.service.MaintenanceTaskService;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.enums.BusinessType;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
/**
 * @author :yys
 * @date : 2025/12/22 14:58
 */
@Api(tags = "设备保养定时任务管理")
@RestController
@RequestMapping("/deviceMaintenanceTask")
public class MaintenanceTaskController extends BaseController {
    @Autowired
    private MaintenanceTaskService maintenanceTaskService;
    @GetMapping("/listPage")
    @ApiOperation(value = "设备保养定时任务列表")
    public AjaxResult listPage(Page page, MaintenanceTask maintenanceTask) {
        return maintenanceTaskService.listPage(page,maintenanceTask);
    }
    @PostMapping("/add")
    @ApiOperation(value = "添加设备保养定时任务")
    @Log(title = "设备保养定时任务", businessType = BusinessType.INSERT)
    public AjaxResult add(@RequestBody MaintenanceTask maintenanceTask) {
        return maintenanceTaskService.add(maintenanceTask);
    }
    @PostMapping("/update")
    @ApiOperation(value = "修改设备保养定时任务")
    @Log(title = "设备保养定时任务", businessType = BusinessType.UPDATE)
    public AjaxResult update(@RequestBody MaintenanceTask maintenanceTask) {
        return maintenanceTaskService.updateByMaintenanceTaskId(maintenanceTask);
    }
    @DeleteMapping("/delete")
    @ApiOperation(value = "删除设备保养定时任务")
    @Log(title = "设备保养定时任务", businessType = BusinessType.DELETE)
    public AjaxResult delete(@RequestBody List<Long> ids) {
        return maintenanceTaskService.delete(ids);
    }
}
src/main/java/com/ruoyi/device/mapper/MaintenanceTaskMapper.java
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,11 @@
package com.ruoyi.device.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.ruoyi.device.pojo.MaintenanceTask;
/**
 * @author :yys
 * @date : 2025/12/22 14:56
 */
public interface MaintenanceTaskMapper extends BaseMapper<MaintenanceTask> {
}
src/main/java/com/ruoyi/device/pojo/DeviceMaintenance.java
@@ -26,6 +26,21 @@
    @ApiModelProperty("设备保养金额")
    private BigDecimal maintenancePrice;
    @ApiModelProperty("保养任务id")
    private Long maintenanceTaskId;
    @ApiModelProperty(value = "频次")
    private String frequencyType;
    @ApiModelProperty(value = "频次详情")
    private String frequencyDetail;
    @ApiModelProperty(value = "下次执行时间")
    private LocalDateTime nextExecutionTime;
    @ApiModelProperty(value = "最后执行时间")
    private LocalDateTime lastExecutionTime;
    private String deviceName;
src/main/java/com/ruoyi/device/pojo/DeviceRepair.java
@@ -52,9 +52,12 @@
    @ApiModelProperty("维修结果")
    private String maintenanceResult;
    @ApiModelProperty("状态 0 å¾…ç»´ä¿® 1完结")
    @ApiModelProperty("状态 0 å¾…ç»´ä¿® 1完结 2待审核 3审核不通过")
    private Integer status;
    @ApiModelProperty("审核人")
    private String auditName;
    @ApiModelProperty("创建时间")
    @TableField(fill = FieldFill.INSERT)
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
src/main/java/com/ruoyi/device/pojo/MaintenanceTask.java
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,113 @@
package com.ruoyi.device.pojo;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.ruoyi.framework.aspectj.lang.annotation.Excel;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import org.springframework.format.annotation.DateTimeFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
/**
 * @author :yys
 * @date : 2025/9/19 10:27
 */
@Data
@ApiModel
@TableName("maintenance_task")
public class MaintenanceTask {
    private static final long serialVersionUID = 1L;
    @ApiModelProperty(value = "规格型号")
    private String deviceModel;
    /**
     * ä¸»é”®ID
     */
    @TableId(type = IdType.AUTO)
    private Long id;
    @ApiModelProperty(value = "设备名称")
    @Excel(name = "保养任务名称")
    private String taskName;
    @ApiModelProperty(value = "设备id")
    private Long taskId;
    @ApiModelProperty(value = "频次")
    @Excel(name = "频次")
    private String frequencyType;
    @ApiModelProperty(value = "频次详情")
    @Excel(name = "开始日期与时间")
    private String frequencyDetail;
    @ApiModelProperty(value = "下次执行时间")
    private LocalDateTime nextExecutionTime;
    @ApiModelProperty(value = "最后执行时间")
    private LocalDateTime lastExecutionTime;
    @ApiModelProperty(value = "是否激活")
    private boolean isActive;
    @ApiModelProperty(value = "备注")
    @Excel(name = "备注")
    private String remarks;
    @ApiModelProperty(value = "录入人id")
    private Long registrantId;
    @ApiModelProperty(value = "录入人")
    @Excel(name = "录入人")
    private String registrant;
    @ApiModelProperty(value = "录入日期")
    @Excel(name = "录入日期", width = 30, dateFormat = "yyyy-MM-dd HH:mm:ss")
    @JsonFormat(pattern = "yyyy-MM-dd")
    @DateTimeFormat(pattern = "yyyy-MM-dd")
    private LocalDate registrationDate;
    @ApiModelProperty(value = "状态 å¾…审核 å®¡æ ¸ä¸é€šè¿‡ å®¡æ ¸é€šè¿‡")
    private String status;
    @ApiModelProperty(value = "审核人")
    @Excel(name = "审核人")
    private String auditName;
    @ApiModelProperty(value = "软删除标志,0=未删除,1=已删除")
    private Integer deleted;
    @TableField(exist = false)
    private String dateStr;
    @ApiModelProperty(value = "创建该记录的用户")
    @TableField(fill = com.baomidou.mybatisplus.annotation.FieldFill.INSERT)
    private Integer createUser;
    @ApiModelProperty(value = "记录创建时间")
    @TableField(fill = com.baomidou.mybatisplus.annotation.FieldFill.INSERT)
//    @JsonFormat(pattern = "yyyy-MM-dd")
//    @DateTimeFormat(pattern = "yyyy-MM-dd")
    private LocalDateTime createTime;
    @ApiModelProperty(value = "最后修改该记录的用户")
    @TableField(fill = com.baomidou.mybatisplus.annotation.FieldFill.INSERT_UPDATE)
    private Integer updateUser;
    @ApiModelProperty(value = "记录最后更新时间")
    @TableField(fill = com.baomidou.mybatisplus.annotation.FieldFill.INSERT_UPDATE)
    private LocalDateTime updateTime;
    @ApiModelProperty(value = "租户ID")
    @TableField(fill = com.baomidou.mybatisplus.annotation.FieldFill.INSERT)
    private Long tenantId;
}
src/main/java/com/ruoyi/device/service/MaintenanceTaskService.java
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,22 @@
package com.ruoyi.device.service;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.IService;
import com.ruoyi.device.pojo.MaintenanceTask;
import com.ruoyi.framework.web.domain.AjaxResult;
import java.util.List;
/**
 * @author :yys
 * @date : 2025/12/22 14:56
 */
public interface MaintenanceTaskService extends IService<MaintenanceTask> {
    AjaxResult listPage(Page page, MaintenanceTask maintenanceTask);
    AjaxResult add(MaintenanceTask maintenanceTask);
    AjaxResult updateByMaintenanceTaskId(MaintenanceTask maintenanceTask);
    AjaxResult delete(List<Long> ids);
}
src/main/java/com/ruoyi/device/service/impl/DeviceRepairServiceImpl.java
@@ -54,6 +54,7 @@
        DeviceLedger byId = deviceLedgerService.getById(deviceRepair.getDeviceLedgerId());
        deviceRepair.setDeviceName(byId.getDeviceName());
        deviceRepair.setDeviceModel(byId.getDeviceModel());
        deviceRepair.setStatus(2);
        boolean save = this.save(deviceRepair);
        if (save){
            return AjaxResult.success();
src/main/java/com/ruoyi/device/service/impl/MaintenanceTaskJob.java
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,243 @@
package com.ruoyi.device.service.impl;
import com.ruoyi.device.pojo.DeviceMaintenance;
import com.ruoyi.device.pojo.MaintenanceTask;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import java.io.Serializable;
import java.time.DayOfWeek;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.YearMonth;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
@Component
@DisallowConcurrentExecution // ç¦æ­¢å¹¶å‘执行同一个Job
public class MaintenanceTaskJob implements Job, Serializable {
    private static final long serialVersionUID = 1L; // å¿…须定义序列化ID
    @Autowired
    private DeviceMaintenanceServiceImpl deviceMaintenanceService;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        JobDataMap jobDataMap = context.getJobDetail().getJobDataMap();
        // ä¿®å¤ç±»åž‹è½¬æ¢é”™è¯¯ï¼Œæ­£ç¡®èŽ·å–taskId
        Long taskId = jobDataMap.getLong("maintenanceTaskId");
        try {
            // 3. å°è¯•查询你的业务数据
            // é€šè¿‡JDBC模板查询定时任务信息,使用参数化查询防止SQL注入
            String yourSql = "SELECT * FROM maintenance_task where id = ? and status = '审核通过'";
            List<MaintenanceTask> tasks = jdbcTemplate.query(
                    yourSql,
                    new BeanPropertyRowMapper<>(MaintenanceTask.class),
                    taskId
            );
            MaintenanceTask timingTask = tasks.isEmpty() ? null : tasks.get(0);
            if (timingTask == null) {
                throw new JobExecutionException("MaintenanceTaskJob找不到定时任务: " + taskId);
            }
            // 2. åˆ›å»ºå¹¶ä¿å­˜å·¡æ£€ä»»åŠ¡è®°å½• - è¿™å°±æ˜¯æ‚¨æä¾›çš„代码应该放的位置
            DeviceMaintenance deviceMaintenance = createInspectionTask(timingTask);
            deviceMaintenanceService.save(deviceMaintenance);
            // 3. æ›´æ–°å®šæ—¶ä»»åŠ¡çš„æ‰§è¡Œæ—¶é—´
            if (!tasks.isEmpty()) {
                MaintenanceTask task = tasks.get(0);
                // æ›´æ–°æœ€åŽæ‰§è¡Œæ—¶é—´ä¸ºå½“前时间
                LocalDateTime lastExecutionTime = LocalDateTime.now();
                // è®¡ç®—下次执行时间
                LocalDateTime nextExecutionTime = calculateNextExecutionTime(
                        task.getFrequencyType(),
                        task.getFrequencyDetail(),
                        lastExecutionTime
                );
                // æ‰§è¡Œæ›´æ–°æ“ä½œ
                String updateSql = "UPDATE maintenance_task " +
                        "SET last_execution_time = ?, next_execution_time = ? " +
                        "WHERE id = ?";
                jdbcTemplate.update(
                        updateSql,
                        lastExecutionTime,
                        nextExecutionTime,
                        taskId
                );
            }
        } catch (Exception e) {
            throw new JobExecutionException(e);
        }
    }
    // è¿™å°±æ˜¯æ‚¨æä¾›çš„代码封装成的方法
    private DeviceMaintenance createInspectionTask(MaintenanceTask timingTask) {
        DeviceMaintenance inspectionTask = new DeviceMaintenance();
        // å¤åˆ¶åŸºæœ¬å±žæ€§
        inspectionTask.setDeviceName(timingTask.getTaskName());
        inspectionTask.setMaintenanceTaskId(timingTask.getId());
        inspectionTask.setDeviceLedgerId(timingTask.getTaskId());
        inspectionTask.setMaintenancePlanTime(LocalDateTime.now());
        inspectionTask.setFrequencyType(timingTask.getFrequencyType());
        inspectionTask.setFrequencyDetail(timingTask.getFrequencyDetail());
        inspectionTask.setTenantId(timingTask.getTenantId());
        inspectionTask.setStatus(0);
        inspectionTask.setDeviceModel(timingTask.getDeviceModel());
        inspectionTask.setCreateUser(Integer.parseInt(timingTask.getRegistrantId().toString()));
        inspectionTask.setUpdateTime(LocalDateTime.now());
        inspectionTask.setCreateTime(LocalDateTime.now());
        inspectionTask.setUpdateUser(Integer.parseInt(timingTask.getRegistrantId().toString()));
        return inspectionTask;
    }
    /**
     * è®¡ç®—下次执行时间
     */
    private LocalDateTime calculateNextExecutionTime(String frequencyType,
                                                     String frequencyDetail,
                                                     LocalDateTime currentTime) {
        try {
            switch (frequencyType) {
                case "DAILY":
                    return calculateDailyNextTime(frequencyDetail, currentTime);
                case "WEEKLY":
                    return calculateWeeklyNextTime(frequencyDetail, currentTime);
                case "MONTHLY":
                    return calculateMonthlyNextTime(frequencyDetail, currentTime);
                case "QUARTERLY":
                    return calculateQuarterlyNextTime(frequencyDetail, currentTime);
                default:
                    throw new IllegalArgumentException("不支持的频率类型: " + frequencyType);
            }
        } catch (Exception e) {
            throw new RuntimeException("计算下次执行时间失败: " + e.getMessage(), e);
        }
    }
    /**
     * è®¡ç®—每日任务的下次执行时间
     */
    private LocalDateTime calculateDailyNextTime(String timeStr, LocalDateTime current) {
        LocalTime executionTime = LocalTime.parse(timeStr); // è§£æžæ ¼å¼ "HH:mm"
        LocalDateTime nextTime = LocalDateTime.of(current.toLocalDate(), executionTime);
        // å¦‚果今天的时间已过,则安排明天
        return current.isBefore(nextTime) ? nextTime : nextTime.plusDays(1);
    }
    /**
     * è®¡ç®—每周任务的下次执行时间
     */
    private LocalDateTime calculateWeeklyNextTime(String detail, LocalDateTime current) {
        String[] parts = detail.split(",");
        String dayOfWeekStr = parts[0];  // å¦‚ "MON" æˆ– "MON|WED|FRI"
        LocalTime time = LocalTime.parse(parts[1]); // æ—¶é—´éƒ¨åˆ†
        // è§£æžæ˜ŸæœŸå‡ (支持多个星期)
        Set<DayOfWeek> targetDays = parseDayOfWeeks(dayOfWeekStr);
        // ä»Žå½“前时间开始找下一个符合条件的星期几
        LocalDateTime nextTime = current;
        while (true) {
            nextTime = nextTime.plusDays(1);
            if (targetDays.contains(nextTime.getDayOfWeek())) {
                return LocalDateTime.of(nextTime.toLocalDate(), time);
            }
            // é˜²æ­¢æ— é™å¾ªçޝ(理论上不会发生)
            if (nextTime.isAfter(current.plusYears(1))) {
                throw new RuntimeException("无法找到下次执行时间");
            }
        }
    }
    /**
     * è®¡ç®—每月任务的下次执行时间
     */
    private LocalDateTime calculateMonthlyNextTime(String detail, LocalDateTime current) {
        String[] parts = detail.split(",");
        int dayOfMonth = Integer.parseInt(parts[0]);
        LocalTime time = LocalTime.parse(parts[1]);
        // ä»Žä¸‹ä¸ªæœˆå¼€å§‹è®¡ç®—
        LocalDateTime nextTime = current.plusMonths(1)
                .withDayOfMonth(Math.min(dayOfMonth, current.plusMonths(1).toLocalDate().lengthOfMonth()))
                .with(time);
        return nextTime;
    }
    /**
     * è®¡ç®—每季度任务的下次执行时间
     */
    private LocalDateTime calculateQuarterlyNextTime(String detail, LocalDateTime current) {
        String[] parts = detail.split(",");
        int quarterMonth = Integer.parseInt(parts[0]); // 1=第1个月,2=第2个月,3=第3个月
        int dayOfMonth = Integer.parseInt(parts[1]);
        LocalTime time = LocalTime.parse(parts[2]);
        // è®¡ç®—当前季度
        int currentQuarter = (current.getMonthValue() - 1) / 3 + 1;
        int currentMonthInQuarter = (current.getMonthValue() - 1) % 3 + 1;
        YearMonth targetYearMonth;
        if (currentMonthInQuarter < quarterMonth) {
            // æœ¬å­£åº¦å†…还有执行机会
            targetYearMonth = YearMonth.from(current)
                    .plusMonths(quarterMonth - currentMonthInQuarter);
        } else {
            // éœ€è¦åˆ°ä¸‹ä¸ªå­£åº¦
            targetYearMonth = YearMonth.from(current)
                    .plusMonths(3 - currentMonthInQuarter + quarterMonth);
        }
        // å¤„理月末日期
        int adjustedDay = Math.min(dayOfMonth, targetYearMonth.lengthOfMonth());
        return LocalDateTime.of(
                targetYearMonth.getYear(),
                targetYearMonth.getMonthValue(),
                adjustedDay,
                time.getHour(),
                time.getMinute()
        );
    }
    /**
     * è§£æžæ˜ŸæœŸå‡ å­—符串
     */
    private Set<DayOfWeek> parseDayOfWeeks(String dayOfWeekStr) {
        Set<DayOfWeek> days = new HashSet<>();
        String[] dayStrs = dayOfWeekStr.split("\\|");
        for (String dayStr : dayStrs) {
            switch (dayStr) {
                case "MON": days.add(DayOfWeek.MONDAY); break;
                case "TUE": days.add(DayOfWeek.TUESDAY); break;
                case "WED": days.add(DayOfWeek.WEDNESDAY); break;
                case "THU": days.add(DayOfWeek.THURSDAY); break;
                case "FRI": days.add(DayOfWeek.FRIDAY); break;
                case "SAT": days.add(DayOfWeek.SATURDAY); break;
                case "SUN": days.add(DayOfWeek.SUNDAY); break;
                default: throw new IllegalArgumentException("无效的星期几: " + dayStr);
            }
        }
        return days;
    }
}
src/main/java/com/ruoyi/device/service/impl/MaintenanceTaskScheduler.java
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,278 @@
package com.ruoyi.device.service.impl;
import com.ruoyi.device.pojo.MaintenanceTask;
import lombok.extern.slf4j.Slf4j;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.time.LocalTime;
import java.time.ZoneId;
import java.time.format.DateTimeParseException;
import java.util.Arrays;
import java.util.Date;
import java.util.stream.Collectors;
/**
 * @author :yys
 * @date : 2025/12/22 15:16
 */
@Service
@Slf4j
public class MaintenanceTaskScheduler {
    @Autowired
    private Scheduler scheduler;
    /**
     * æ·»åŠ æ–°ä»»åŠ¡åˆ°è°ƒåº¦å™¨
     */
    public void scheduleMaintenanceTask(MaintenanceTask task){
        try {
            JobDetail jobDetail = buildJobDetail(task);
            Trigger trigger = buildJobTrigger(task, jobDetail);
            scheduler.scheduleJob(jobDetail, trigger);
        }catch (SchedulerException e){
            log.error("SchedulerException scheduleMaintenanceTask ERROR",e);
            throw new RuntimeException(e);
        }
    }
    /**
     * æ›´æ–°å·²æœ‰ä»»åŠ¡
     */
    public void rescheduleMaintenanceTask(MaintenanceTask task){
       try{
           TriggerKey triggerKey = new TriggerKey("triggerMaintenanceTask_" + task.getId());
           // èŽ·å–çŽ°æœ‰è§¦å‘å™¨å¹¶è½¬æ¢ä¸º CronTrigger
           Trigger oldTrigger = scheduler.getTrigger(triggerKey);
           if (!(oldTrigger instanceof CronTrigger)) {
               throw new SchedulerException("Existing trigger is not a CronTrigger");
           }
           // 3. æž„建CronTrigger,确保持久化配置
           CronTrigger newTrigger = TriggerBuilder.newTrigger()
                   .withIdentity(triggerKey)                // å”¯ä¸€æ ‡è¯†ï¼Œç”¨äºŽæŒä¹…化存储
                   .withDescription(task.getTaskName() + "_TRIGGER") // è§¦å‘器描述
                   .forJob(oldTrigger.getJobKey())                       // å…³è”对应的Job
                   .withSchedule(CronScheduleBuilder
                           .cronSchedule(convertToCronExpression(task)) // é”™è¿‡æ‰§è¡Œæ—¶çš„策略(根据业务调整)
                   )
                   // 4. è®¾ç½®å¼€å§‹æ—¶é—´ï¼ˆè‹¥ä¸ºnull则立即生效)
                   .startAt(task.getNextExecutionTime() != null
                           ? Date.from(task.getNextExecutionTime().atZone(ZoneId.systemDefault()).toInstant())
                           : new Date())
                   .build();
           scheduler.rescheduleJob(triggerKey, newTrigger);
       }catch (SchedulerException e){
           log.error("SchedulerException rescheduleMaintenanceTask ERROR",e);
           throw new RuntimeException(e);
       }
    }
    /**
     * æš‚停任务
     */
    public void pauseMaintenanceTask(Long taskId) throws SchedulerException {
        JobKey jobKey = new JobKey("MaintenanceTask_" + taskId);
        scheduler.pauseJob(jobKey);
    }
    /**
     * æ¢å¤ä»»åŠ¡
     */
    public void resumeMaintenanceTask(Long taskId) throws SchedulerException {
        JobKey jobKey = new JobKey("MaintenanceTask_" + taskId);
        scheduler.resumeJob(jobKey);
    }
    /**
     * åˆ é™¤ä»»åŠ¡
     */
    public void unscheduleMaintenanceTask(Long taskId){
        try {
            JobKey jobKey = new JobKey("MaintenanceTask_" + taskId);
            scheduler.deleteJob(jobKey);
        }catch (SchedulerException e){
            log.error("SchedulerException unscheduleMaintenanceTask ERROR",e);
            throw new RuntimeException(e);
        }
    }
    private JobDetail buildJobDetail(MaintenanceTask task) {
        // 1. æž„建唯一JobKey(基于任务ID,确保重启后能识别)
        JobKey jobKey = new JobKey("MaintenanceTask_" + task.getId());
        // 2. å°è£…任务数据(仅使用基本类型,确保可序列化)
        JobDataMap jobDataMap = new JobDataMap();
        jobDataMap.put("maintenanceTaskId", task.getId());           // ä»»åŠ¡ID(Long,可序列化)
        jobDataMap.put("taskName", task.getTaskName());   // ä»»åŠ¡åç§°ï¼ˆString,可序列化)
        jobDataMap.put("taskType", task.getFrequencyType()); // ä»»åŠ¡ç±»åž‹ï¼ˆString)
        // æŒ‰éœ€æ·»åŠ å…¶ä»–å¿…è¦çš„åŸºæœ¬ç±»åž‹å‚æ•°
        // 3. æž„建JobDetail,设置持久化相关属性
        return JobBuilder.newJob(MaintenanceTaskJob.class)
                .withIdentity(jobKey)                    // å”¯ä¸€æ ‡è¯†ï¼Œç”¨äºŽæŒä¹…化存储
                .withDescription(task.getTaskName())     // ä»»åŠ¡æè¿°ï¼Œå­˜å…¥æ•°æ®åº“
                .usingJobData(jobDataMap)                // ç»‘定任务数据
                .storeDurably(true)                          // å³ä½¿æ²¡æœ‰è§¦å‘器关联也持久化保存
                .requestRecovery(true)                   // å½“调度器崩溃后恢复时,重新执行未完成的任务
                .build();
    }
    private Trigger buildJobTrigger(MaintenanceTask task, JobDetail jobDetail) {
        // 1. æž„建唯一TriggerKey(基于任务ID)
        TriggerKey triggerKey = new TriggerKey("triggerMaintenanceTask_" + task.getId());
        // 2. ç”ŸæˆCron表达式(原逻辑不变)
        String cronExpression = convertToCronExpression(task);
        // 3. æž„建CronTrigger,确保持久化配置
        return TriggerBuilder.newTrigger()
                .withIdentity(triggerKey)                // å”¯ä¸€æ ‡è¯†ï¼Œç”¨äºŽæŒä¹…化存储
                .withDescription(task.getTaskName() + "_TRIGGER") // è§¦å‘器描述
                .forJob(jobDetail)                       // å…³è”对应的Job
                .withSchedule(CronScheduleBuilder
                        .cronSchedule(cronExpression)
                        .withMisfireHandlingInstructionDoNothing() // é”™è¿‡æ‰§è¡Œæ—¶çš„策略(根据业务调整)
                )
                // 4. è®¾ç½®å¼€å§‹æ—¶é—´ï¼ˆè‹¥ä¸ºnull则立即生效)
                .startAt(task.getNextExecutionTime() != null
                        ? Date.from(task.getNextExecutionTime().atZone(ZoneId.systemDefault()).toInstant())
                        : new Date())
                .build();
    }
    private String convertToCronExpression(MaintenanceTask task) {
        // å‚数校验
        if (task == null || task.getFrequencyType() == null || task.getFrequencyDetail() == null) {
            throw new IllegalArgumentException("任务参数不能为空");
        }
        // ä½¿ç”¨switch确保条件互斥
        String frequencyType = task.getFrequencyType().toUpperCase(); // ç»Ÿä¸€è½¬ä¸ºå¤§å†™æ¯”较
        switch (frequencyType) {
            case "DAILY":
                return convertDailyToCron(task.getFrequencyDetail());
            case "WEEKLY":
                return convertWeeklyToCron(task.getFrequencyDetail());
            case "MONTHLY":
                return convertMonthlyToCron(task.getFrequencyDetail());
            case "QUARTERLY":
                return convertQuarterlyToCron(task.getFrequencyDetail());
            default:
                throw new IllegalArgumentException("不支持的频率类型: " + task.getFrequencyType());
        }
    }
    // æ¯æ—¥ä»»åŠ¡è½¬æ¢
    private String convertDailyToCron(String frequencyDetail) {
        LocalTime time = parseTime(frequencyDetail);
        return String.format("0 %d %d * * ?", time.getMinute(), time.getHour());
    }
    // æ¯å‘¨ä»»åŠ¡è½¬æ¢
    private String convertWeeklyToCron(String frequencyDetail) {
        String[] parts = validateAndSplit(frequencyDetail, ",", 2);
        String daysOfWeek = convertDayNamesToCron(parts[0]);
        LocalTime time = parseTime(parts[1]);
        return String.format("0 %d %d ? * %s", time.getMinute(), time.getHour(), daysOfWeek);
    }
    // æ¯æœˆä»»åŠ¡è½¬æ¢
    private String convertMonthlyToCron(String frequencyDetail) {
        String[] parts = validateAndSplit(frequencyDetail, ",", 2);
        int day = validateDayOfMonth(parts[0]);
        LocalTime time = parseTime(parts[1]);
        return String.format("0 %d %d %d * ?", time.getMinute(), time.getHour(), day);
    }
    // æ¯å­£åº¦ä»»åŠ¡è½¬æ¢
    private String convertQuarterlyToCron(String frequencyDetail) {
        String[] parts = validateAndSplit(frequencyDetail, ",", 3);
        int month = validateMonth(parts[0]);  // éªŒè¯æœˆä»½(1-12)
        int day = validateDayOfMonth(parts[1]);  // éªŒè¯æ—¥æœŸ
        LocalTime time = parseTime(parts[2]);  // è§£æžæ—¶é—´
        // è®¡ç®—季度起始月份(1月=1, 4月=4, 7月=7, 10月=10)
        int quarterStartMonth = ((month - 1) / 3) * 3 + 1;
        return String.format("0 %d %d %d %d/3 ?",
                time.getMinute(),
                time.getHour(),
                day,
                quarterStartMonth);
    }
    // æ–°å¢žéªŒè¯æœˆä»½çš„æ–¹æ³•(1-12)
    private int validateMonth(String monthStr) {
        try {
            int month = Integer.parseInt(monthStr);
            if (month < 1 || month > 12) {
                throw new IllegalArgumentException("月份必须在1-12之间");
            }
            return month;
        } catch (NumberFormatException e) {
            throw new IllegalArgumentException("无效的月份格式");
        }
    }
    // è¾…助方法:解析时间
    private LocalTime parseTime(String timeStr) {
        try {
            return LocalTime.parse(timeStr);
        } catch (DateTimeParseException e) {
            throw new IllegalArgumentException("时间格式必须为HH:mm", e);
        }
    }
    // è¾…助方法:验证并分割字符串
    private String[] validateAndSplit(String input, String delimiter, int expectedParts) {
        String[] parts = input.split(delimiter);
        if (parts.length != expectedParts) {
            throw new IllegalArgumentException(
                    String.format("格式错误,应为%d部分用'%s'分隔", expectedParts, delimiter));
        }
        return parts;
    }
    // è¾…助方法:验证月份中的日
    private int validateDayOfMonth(String dayStr) {
        int day = Integer.parseInt(dayStr);
        if (day < 1 || day > 31) {
            throw new IllegalArgumentException("日期必须在1-31之间");
        }
        return day;
    }
    // è¾…助方法:验证季度中的月
    private int validateMonthInQuarter(String monthStr) {
        int month = Integer.parseInt(monthStr);
        if (month < 1 || month > 3) {
            throw new IllegalArgumentException("季度月份必须是1、2或3");
        }
        return month;
    }
    // è½¬æ¢æ˜ŸæœŸå‡ åç§°
    private String convertDayNamesToCron(String dayNames) {
        return Arrays.stream(dayNames.split("\\|"))
                .map(this::convertSingleDayName)
                .collect(Collectors.joining(","));
    }
    // è½¬æ¢å•个星期几名称
    private String convertSingleDayName(String dayName) {
        switch (dayName.toUpperCase()) {
            case "MON": return "MON";
            case "TUE": return "TUE";
            case "WED": return "WED";
            case "THU": return "THU";
            case "FRI": return "FRI";
            case "SAT": return "SAT";
            case "SUN": return "SUN";
            default: throw new IllegalArgumentException("无效的星期几: " + dayName);
        }
    }
}
src/main/java/com/ruoyi/device/service/impl/MaintenanceTaskServiceImpl.java
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,119 @@
package com.ruoyi.device.service.impl;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.device.mapper.MaintenanceTaskMapper;
import com.ruoyi.device.pojo.MaintenanceTask;
import com.ruoyi.device.service.MaintenanceTaskService;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.inspectiontask.pojo.TimingTask;
import com.ruoyi.inspectiontask.service.impl.TimingTaskServiceImpl;
import com.ruoyi.project.system.domain.SysUser;
import com.ruoyi.project.system.mapper.SysUserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.time.LocalDateTime;
import java.util.*;
/**
 * @author :yys
 * @date : 2025/12/22 14:57
 */
@Service
@Slf4j
public class MaintenanceTaskServiceImpl extends ServiceImpl<MaintenanceTaskMapper, MaintenanceTask> implements MaintenanceTaskService {
    @Autowired
    private MaintenanceTaskMapper maintenanceTaskMapper;
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private TimingTaskServiceImpl timingTaskService;
    @Autowired
    private MaintenanceTaskScheduler maintenanceTaskScheduler;
    @Override
    public AjaxResult listPage(Page page, MaintenanceTask maintenanceTask) {
        Page<MaintenanceTask> taskPage = maintenanceTaskMapper.selectPage(page, null);
        // 2. å¦‚果没有数据,直接返回空分页
        if (taskPage.getRecords().isEmpty()) {
            return AjaxResult.success(taskPage);
        }
        // 3. æ”¶é›†æ‰€æœ‰éœ€è¦æŸ¥è¯¢çš„用户ID
        Set<Long> userIds = new HashSet<>();
        // æ”¶é›†ç™»è®°äººID
        taskPage.getRecords().forEach(task -> {
            if (task.getRegistrantId() != null) {
                userIds.add(task.getRegistrantId());
            }
        });
        // 4. æ‰¹é‡æŸ¥è¯¢ç”¨æˆ·ä¿¡æ¯
        Map<Long, String> userNickNameMap = new HashMap<>();
        if (!userIds.isEmpty()) {
            List<SysUser> users = sysUserMapper.selectUserByIds((new ArrayList<>(userIds)));
            users.forEach(user -> userNickNameMap.put(user.getUserId(), user.getNickName()));
        }
        taskPage.getRecords().forEach(task -> {
            // è®¾ç½®ç™»è®°äººæ˜µç§°
            if (task.getRegistrantId() != null) {
                task.setRegistrant(userNickNameMap.getOrDefault(task.getRegistrantId(), "未知用户"));
            }
        });
        return AjaxResult.success(taskPage);
    }
    @Override
    public AjaxResult add(MaintenanceTask maintenanceTask) {
        if(StringUtils.isEmpty(maintenanceTask.getAuditName())) {
            return AjaxResult.warn("请填写审核人");
        }
        maintenanceTask.setActive(true);
        // è®¡ç®—首次执行时间
        TimingTask task = new TimingTask();
        task.setFrequencyType(maintenanceTask.getFrequencyType());
        task.setFrequencyDetail(maintenanceTask.getFrequencyDetail());
        LocalDateTime firstExecutionTime = timingTaskService.calculateFirstExecutionTime(task);
        maintenanceTask.setNextExecutionTime(firstExecutionTime);
        maintenanceTask.setStatus("待审核");
        int insert = maintenanceTaskMapper.insert(maintenanceTask);
        if (insert > 0) {
            maintenanceTaskScheduler.scheduleMaintenanceTask(maintenanceTask);
        }
        return AjaxResult.success("添加成功");
    }
    @Override
    public AjaxResult updateByMaintenanceTaskId(MaintenanceTask maintenanceTask) {
        MaintenanceTask maintenanceTask1 = maintenanceTaskMapper.selectById(maintenanceTask.getId());
        if (maintenanceTask1 == null) {
            return AjaxResult.warn("没有此数据");
        }
        BeanUtils.copyProperties(maintenanceTask, maintenanceTask1);
        int update = maintenanceTaskMapper.updateById(maintenanceTask1);
        if (update > 0) {
            maintenanceTaskScheduler.rescheduleMaintenanceTask(maintenanceTask1);
        }
        return AjaxResult.success("更新成功");
    }
    @Override
    public AjaxResult delete(List<Long> ids) {
        int delete = maintenanceTaskMapper.deleteBatchIds(ids);
        if (delete > 0) {
            ids.forEach(id -> {
                maintenanceTaskScheduler.unscheduleMaintenanceTask(id);
            });
        }
        return AjaxResult.success("删除成功");
    }
}
src/main/java/com/ruoyi/inspectiontask/service/impl/TimingTaskServiceImpl.java
@@ -144,7 +144,7 @@
        }
    }
    private LocalDateTime calculateFirstExecutionTime(TimingTask task) {
    public LocalDateTime calculateFirstExecutionTime(TimingTask task) {
        // æ ¹æ®é¢‘率类型和详情计算首次执行时间
        String frequencyType = task.getFrequencyType();
        if ("DAILY".equals(frequencyType)) {
src/main/java/com/ruoyi/lavorissue/controller/LavorIssueController.java
@@ -130,6 +130,27 @@
        return AjaxResult.success(statisticsLaborIssue);
    }
    @ApiOperation("发放进度-总计")
    @GetMapping("/progressTotal")
    public AjaxResult progressTotal(LaborIssue laborIssue) throws Exception {
        Map<String, Object> list = laborIssueService.progressTotal(laborIssue);
        return AjaxResult.success(list);
    }
    @ApiOperation("领取进度占比")
    @GetMapping("/progressPercent")
    public AjaxResult progressPercent(LaborIssue laborIssue) throws Exception {
        Map<String, Object> list = laborIssueService.progressPercent(laborIssue);
        return AjaxResult.success(list);
    }
    @ApiOperation("进度分布")
    @GetMapping("/progressDistribution")
    public AjaxResult progressDistribution(LaborIssue laborIssue) throws Exception {
        Map<String, Object> list = laborIssueService.progressDistribution(laborIssue);
        return AjaxResult.success(list);
    }
    /**
src/main/java/com/ruoyi/lavorissue/service/LavorIssueService.java
@@ -31,4 +31,10 @@
    void exportCopy(HttpServletResponse response, LaborIssue laborIssue) throws UnsupportedEncodingException;
    List<Map<String, Object>> statisticsList(LaborIssue laborIssue);
    Map<String, Object> progressTotal(LaborIssue laborIssue);
    Map<String, Object> progressPercent(LaborIssue laborIssue);
    Map<String, Object> progressDistribution(LaborIssue laborIssue);
}
src/main/java/com/ruoyi/lavorissue/service/impl/LavorIssueServiceImpl.java
@@ -93,6 +93,102 @@
        return records;
    }
    @Override
    public Map<String, Object> progressTotal(LaborIssue req) {
        StartAndEndDateDto startAndEndDateDto = getStartAndEndDateDto(req.getSeason(), req.getIssueDate());
        req.setStartDate(startAndEndDateDto.getStartDate());
        req.setEndDate(startAndEndDateDto.getEndDate());
        List<LaborIssue> laborIssueIPage = lavorIssueMapper.list(req);
        Map<String, Object> map = new HashMap<>();
        map.put("total", 0); // å‘放总数量
        // é¢†å–数量
        map.put("adopted", 0);
        // æœªé¢†å–数量
        map.put("notAdopted", 0);
        // é¢†å–完成率
        map.put("adoptedPercent", 0);
        if(!CollectionUtils.isEmpty(laborIssueIPage)){
            long sum = laborIssueIPage.stream().mapToLong(LaborIssue::getNum).sum();
            map.put("total", sum);
            long sum1 = laborIssueIPage
                    .stream()
                    .filter(laborIssue -> laborIssue.getAdoptedDate() != null)
                    .mapToLong(LaborIssue::getNum)
                    .sum();
            map.put("adopted", sum1);
            map.put("notAdopted", sum - sum1);
            map.put("adoptedPercent", sum1 * 100.0 / sum);
        }
        return map;
    }
    @Override
    public Map<String, Object> progressPercent(LaborIssue req) {
        StartAndEndDateDto startAndEndDateDto = getStartAndEndDateDto(req.getSeason(), req.getIssueDate());
        req.setStartDate(startAndEndDateDto.getStartDate());
        req.setEndDate(startAndEndDateDto.getEndDate());
        List<LaborIssue> laborIssueIPage = lavorIssueMapper.list(req);
        Map<String, Object> map = new HashMap<>();
        // é¢†å–数量
        map.put("adopted", 0);
        // æœªé¢†å–数量
        map.put("notAdopted", 0);
        if(!CollectionUtils.isEmpty(laborIssueIPage)){
            long sum = laborIssueIPage.stream().mapToLong(LaborIssue::getNum).sum();
            long sum1 = laborIssueIPage
                    .stream()
                    .filter(laborIssue -> laborIssue.getAdoptedDate() != null)
                    .mapToLong(LaborIssue::getNum)
                    .sum();
            map.put("adopted", sum1);
            map.put("notAdopted", sum - sum1);
        }
        return map;
    }
    @Override
    public Map<String, Object> progressDistribution(LaborIssue req) {
        StartAndEndDateDto startAndEndDateDto = getStartAndEndDateDto(req.getSeason(), req.getIssueDate());
        req.setStartDate(startAndEndDateDto.getStartDate());
        req.setEndDate(startAndEndDateDto.getEndDate());
        List<LaborIssue> laborIssueIPage = lavorIssueMapper.list(req);
        Map<String, Object> map = new HashMap<>();
        if(!CollectionUtils.isEmpty(laborIssueIPage)){
            // æ ¹æ®å‘放日期,领用日期计算及时已领取,及时未领取,超时已领取,超时未领取数据
            // åŠæ—¶å·²é¢†å–
            List<List<Long>> list = new ArrayList<>();
            List<Long> sumList = new ArrayList<>();
            long sum = laborIssueIPage.stream()
                    .filter(laborIssue -> laborIssue.getAdoptedDate() != null && laborIssue.getAdoptedDate().getTime() <= laborIssue.getIssueDate().getTime())
                    .mapToLong(LaborIssue::getNum)
                    .sum();
            // åŠæ—¶æœªé¢†å–
            long sum1 = laborIssueIPage.stream()
                    .filter(laborIssue -> laborIssue.getAdoptedDate() == null && laborIssue.getIssueDate().getTime() <= new Date().getTime())
                    .mapToLong(LaborIssue::getNum)
                    .sum();
            sumList.add(sum);
            sumList.add(sum1);
            list.add(sumList);
            List<Long> sumList1 = new ArrayList<>();
            // è¶…时已领取
            long sum2 = laborIssueIPage.stream()
                    .filter(laborIssue -> laborIssue.getAdoptedDate() != null && laborIssue.getAdoptedDate().getTime() > laborIssue.getIssueDate().getTime())
                    .mapToLong(LaborIssue::getNum)
                    .sum();
            // è¶…时未领取
            long sum3 = laborIssueIPage.stream()
                    .filter(laborIssue -> laborIssue.getAdoptedDate() == null && laborIssue.getIssueDate().getTime() > new Date().getTime())
                    .mapToLong(LaborIssue::getNum)
                    .sum();
            sumList1.add(sum2);
            sumList1.add(sum3);
            list.add(sumList1);
            map.put("series", list);
        }
        return map;
    }
    public StartAndEndDateDto getStartAndEndDateDto(Integer season,Date payDate){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        StartAndEndDateDto startAndEndDateDto = new StartAndEndDateDto();