From dd3c0399c9f3c2e70bfd0072cddadcd8d34f18bb Mon Sep 17 00:00:00 2001
From: yuan <123@>
Date: 星期日, 24 五月 2026 18:11:21 +0800
Subject: [PATCH] 测试类

---
 src/test/java/com/ruoyi/inspectiontask/service/impl/TimingTaskJobTest.java |  339 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++
 1 files changed, 339 insertions(+), 0 deletions(-)

diff --git a/src/test/java/com/ruoyi/inspectiontask/service/impl/TimingTaskJobTest.java b/src/test/java/com/ruoyi/inspectiontask/service/impl/TimingTaskJobTest.java
new file mode 100644
index 0000000..426f332
--- /dev/null
+++ b/src/test/java/com/ruoyi/inspectiontask/service/impl/TimingTaskJobTest.java
@@ -0,0 +1,339 @@
+package com.ruoyi.inspectiontask.service.impl;
+
+import com.ruoyi.inspectiontask.mapper.InspectionTaskMapper;
+import com.ruoyi.inspectiontask.pojo.InspectionTask;
+import com.ruoyi.inspectiontask.pojo.TimingTask;
+import org.junit.jupiter.api.Test;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.test.context.SpringBootTest;
+import org.springframework.jdbc.core.JdbcTemplate;
+
+import java.time.DayOfWeek;
+import java.time.LocalDateTime;
+import java.time.LocalTime;
+import java.time.YearMonth;
+import java.time.LocalDate;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+
+/**
+ * 璁惧宸℃瀹氭椂浠诲姟娴嬭瘯绫�
+ *
+ * 鏌ヨ鏁版嵁搴撲腑鐨勫贰妫�浠诲姟锛屾牴鎹櫥璁版棩鏈熴�侀娆°�佸紑濮嬫棩鏈熶笌鏃堕棿鏉ョ敓鎴愬贰妫�璁板綍
+ * 骞舵洿鏂� timing_task 琛ㄧ殑鏈�鍚庢墽琛屾椂闂村拰涓嬫鎵ц鏃堕棿
+ */
+@SpringBootTest
+public class TimingTaskJobTest {
+
+    @Autowired
+    private InspectionTaskMapper inspectionTaskMapper;
+
+    @Autowired
+    private JdbcTemplate jdbcTemplate;
+
+    /**
+     * 娴嬭瘯锛氭牴鎹墍鏈夊贰妫�浠诲姟鐢熸垚宸℃璁板綍
+     * 浠庣櫥璁版棩鏈熷埌浠婂ぉ锛屾寜棰戞姣忓懆鐢熸垚涓�鏉¤褰�
+     */
+    @Test
+    void testGenerateInspectionRecordForAllTasks() {
+        // 鏌ヨ鎵�鏈夊惎鐢ㄧ殑宸℃浠诲姟
+        String sql = "SELECT * FROM timing_task WHERE is_enabled = 1 AND deleted = 0";
+        List<TimingTask> tasks = jdbcTemplate.query(sql,
+                (rs, rowNum) -> {
+                    TimingTask task = new TimingTask();
+                    task.setId(rs.getLong("id"));
+                    task.setTaskName(rs.getString("task_name"));
+                    task.setInspectionProject(rs.getString("inspection_project"));
+                    task.setTaskId(rs.getInt("task_id"));
+                    task.setInspectorIds(rs.getString("inspector_ids"));
+                    task.setInspectionLocation(rs.getString("inspection_location"));
+                    task.setFrequencyType(rs.getString("frequency_type"));
+                    task.setFrequencyDetail(rs.getString("frequency_detail"));
+                    task.setRemarks(rs.getString("remarks"));
+                    task.setRegistrantId(rs.getLong("registrant_id"));
+                    task.setRegistrant(rs.getString("registrant"));
+                    task.setTenantId(rs.getLong("tenant_id"));
+                    // 鑾峰彇鐧昏鏃ユ湡
+                    java.sql.Date regDate = rs.getDate("registration_date");
+                    if (regDate != null) {
+                        task.setRegistrationDate(regDate.toLocalDate());
+                    }
+                    return task;
+                });
+
+        System.out.println("=== 鍏辨壘鍒� " + tasks.size() + " 涓贰妫�浠诲姟 ===\n");
+
+        int totalRecords = 0;
+        for (TimingTask task : tasks) {
+            try {
+                // 鐢熸垚鎵�鏈夌鍚堥娆$殑璁板綍
+                int recordCount = generateRecordsForTask(task);
+                totalRecords += recordCount;
+                System.out.println("鉁� 浠诲姟ID: " + task.getId() + " | " + task.getTaskName()
+                        + " | 鐧昏鏃ユ湡: " + task.getRegistrationDate()
+                        + " | 鐢熸垚璁板綍鏁�: " + recordCount);
+            } catch (Exception e) {
+                System.out.println("鉁� 浠诲姟ID: " + task.getId() + " | " + task.getTaskName() + " | 澶辫触: " + e.getMessage());
+            }
+        }
+
+        System.out.println("\n=== 鎵ц瀹屾垚: 鍏辩敓鎴� " + totalRecords + " 鏉¤褰� ===");
+    }
+
+    /**
+     * 涓哄崟涓换鍔$敓鎴愭墍鏈夌鍚堥娆$殑璁板綍
+     */
+    private int generateRecordsForTask(TimingTask task) {
+        LocalDate startDate = task.getRegistrationDate();
+        if (startDate == null) {
+            startDate = LocalDate.now();
+        }
+        LocalDate endDate = LocalDate.now();
+
+        // 鏍规嵁棰戞鑾峰彇鎵�鏈夐渶瑕佹墽琛岀殑鏃ユ湡
+        List<LocalDateTime> executionDates = getExecutionDates(task.getFrequencyType(), task.getFrequencyDetail(), startDate, endDate);
+
+        int count = 0;
+        for (LocalDateTime executionDate : executionDates) {
+            try {
+                // 鐢熸垚宸℃璁板綍
+                InspectionTask record = createInspectionRecord(task, executionDate);
+                inspectionTaskMapper.insert(record);
+
+                // 鏇存柊浠诲姟鐨勪笂娆℃墽琛屾椂闂�
+                updateTaskLastExecutionTime(task.getId(), executionDate);
+
+                count++;
+            } catch (Exception e) {
+                System.out.println("  鉁� 鏃ユ湡: " + executionDate + " | 澶辫触: " + e.getMessage());
+            }
+        }
+
+        // 鏇存柊浠诲姟鐨勪笅娆℃墽琛屾椂闂�
+        if (count > 0) {
+            LocalDateTime lastExecution = executionDates.get(executionDates.size() - 1);
+            LocalDateTime nextExecution = calculateNextExecutionTime(task.getFrequencyType(), task.getFrequencyDetail(), lastExecution);
+            updateTaskNextExecutionTime(task.getId(), nextExecution);
+        }
+
+        return count;
+    }
+
+    /**
+     * 鑾峰彇鎸囧畾鏃ユ湡鑼冨洿鍐呮墍鏈夌鍚堥娆$殑鎵ц鏃堕棿
+     */
+    private List<LocalDateTime> getExecutionDates(String frequencyType, String frequencyDetail, LocalDate startDate, LocalDate endDate) {
+        List<LocalDateTime> dates = new java.util.ArrayList<>();
+
+        switch (frequencyType) {
+            case "DAILY":
+                dates.addAll(getDailyDates(startDate, endDate, frequencyDetail));
+                break;
+            case "WEEKLY":
+                dates.addAll(getWeeklyDates(startDate, endDate, frequencyDetail));
+                break;
+            case "MONTHLY":
+                dates.addAll(getMonthlyDates(startDate, endDate, frequencyDetail));
+                break;
+            case "QUARTERLY":
+                dates.addAll(getQuarterlyDates(startDate, endDate, frequencyDetail));
+                break;
+        }
+
+        return dates;
+    }
+
+    private List<LocalDateTime> getDailyDates(LocalDate startDate, LocalDate endDate, String timeStr) {
+        List<LocalDateTime> dates = new java.util.ArrayList<>();
+        LocalTime time = LocalTime.parse(timeStr);
+
+        LocalDate current = startDate;
+        while (!current.isAfter(endDate)) {
+            dates.add(LocalDateTime.of(current, time));
+            current = current.plusDays(1);
+        }
+        return dates;
+    }
+
+    private List<LocalDateTime> getWeeklyDates(LocalDate startDate, LocalDate endDate, String detail) {
+        List<LocalDateTime> dates = new java.util.ArrayList<>();
+        String[] parts = detail.split(",");
+        String dayOfWeekStr = parts[0];
+        LocalTime time = LocalTime.parse(parts[1]);
+
+        Set<DayOfWeek> targetDays = parseDayOfWeeks(dayOfWeekStr);
+
+        LocalDate current = startDate;
+        while (!current.isAfter(endDate)) {
+            if (targetDays.contains(current.getDayOfWeek())) {
+                dates.add(LocalDateTime.of(current, time));
+            }
+            current = current.plusDays(1);
+        }
+        return dates;
+    }
+
+    private List<LocalDateTime> getMonthlyDates(LocalDate startDate, LocalDate endDate, String detail) {
+        List<LocalDateTime> dates = new java.util.ArrayList<>();
+        String[] parts = detail.split(",");
+        int dayOfMonth = Integer.parseInt(parts[0]);
+        LocalTime time = LocalTime.parse(parts[1]);
+
+        LocalDate current = startDate.plusMonths(0).withDayOfMonth(Math.min(dayOfMonth, startDate.lengthOfMonth()));
+        while (!current.isAfter(endDate)) {
+            dates.add(LocalDateTime.of(current, time));
+            current = current.plusMonths(1).withDayOfMonth(Math.min(dayOfMonth, current.plusMonths(1).lengthOfMonth()));
+        }
+        return dates;
+    }
+
+    private List<LocalDateTime> getQuarterlyDates(LocalDate startDate, LocalDate endDate, String detail) {
+        List<LocalDateTime> dates = new java.util.ArrayList<>();
+        String[] parts = detail.split(",");
+        int quarterMonth = Integer.parseInt(parts[0]);
+        int dayOfMonth = Integer.parseInt(parts[1]);
+        LocalTime time = LocalTime.parse(parts[2]);
+
+        int currentMonth = startDate.getMonthValue();
+        int targetMonth = ((currentMonth - 1) / 3) * 3 + quarterMonth;
+        int yearAdjust = 0;
+
+        if (targetMonth > 12) {
+            targetMonth -= 12;
+            yearAdjust = 1;
+        }
+
+        LocalDate current = startDate.withYear(startDate.getYear() + yearAdjust)
+                .withMonth(targetMonth)
+                .withDayOfMonth(Math.min(dayOfMonth, YearMonth.of(startDate.getYear() + yearAdjust, targetMonth).lengthOfMonth()));
+
+        while (!current.isAfter(endDate)) {
+            dates.add(LocalDateTime.of(current, time));
+            current = current.plusMonths(3).withDayOfMonth(Math.min(dayOfMonth, current.plusMonths(3).lengthOfMonth()));
+        }
+        return dates;
+    }
+
+    private Set<DayOfWeek> parseDayOfWeeks(String dayOfWeekStr) {
+        Set<DayOfWeek> days = new HashSet<>();
+        String[] dayStrs = dayOfWeekStr.split("\\|");
+
+        for (String dayStr : dayStrs) {
+            switch (dayStr.toUpperCase()) {
+                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;
+            }
+        }
+        return days;
+    }
+
+    /**
+     * 璁$畻涓嬫鎵ц鏃堕棿
+     */
+    private LocalDateTime calculateNextExecutionTime(String frequencyType, String frequencyDetail, LocalDateTime currentTime) {
+        return switch (frequencyType) {
+            case "DAILY" -> calculateDailyNextTime(frequencyDetail, currentTime);
+            case "WEEKLY" -> calculateWeeklyNextTime(frequencyDetail, currentTime);
+            case "MONTHLY" -> calculateMonthlyNextTime(frequencyDetail, currentTime);
+            case "QUARTERLY" -> calculateQuarterlyNextTime(frequencyDetail, currentTime);
+            default -> throw new IllegalArgumentException("涓嶆敮鎸佺殑棰戞绫诲瀷: " + frequencyType);
+        };
+    }
+
+    private LocalDateTime calculateDailyNextTime(String timeStr, LocalDateTime current) {
+        LocalTime executionTime = LocalTime.parse(timeStr);
+        LocalDateTime nextTime = LocalDateTime.of(current.toLocalDate(), executionTime);
+        return current.isBefore(nextTime) ? nextTime : nextTime.plusDays(1);
+    }
+
+    private LocalDateTime calculateMonthlyNextTime(String detail, LocalDateTime current) {
+        String[] parts = detail.split(",");
+        int dayOfMonth = Integer.parseInt(parts[0]);
+        LocalTime time = LocalTime.parse(parts[1]);
+        return current.plusMonths(1)
+                .withDayOfMonth(Math.min(dayOfMonth, current.plusMonths(1).toLocalDate().lengthOfMonth()))
+                .with(time);
+    }
+
+    private LocalDateTime calculateWeeklyNextTime(String detail, LocalDateTime current) {
+        String[] parts = detail.split(",");
+        String dayOfWeekStr = parts[0];
+        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 calculateQuarterlyNextTime(String detail, LocalDateTime current) {
+        String[] parts = detail.split(",");
+        int quarterMonth = Integer.parseInt(parts[0]);
+        int dayOfMonth = Integer.parseInt(parts[1]);
+        LocalTime time = LocalTime.parse(parts[2]);
+
+        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 InspectionTask createInspectionRecord(TimingTask timingTask, LocalDateTime executionDate) {
+        InspectionTask inspectionTask = new InspectionTask();
+        inspectionTask.setTaskName(timingTask.getTaskName());
+        inspectionTask.setInspectionProject(timingTask.getInspectionProject());
+        inspectionTask.setTaskId(timingTask.getTaskId());
+        inspectionTask.setInspectorId(timingTask.getInspectorIds());
+        inspectionTask.setInspectionLocation(timingTask.getInspectionLocation());
+        inspectionTask.setRemarks("鑷姩鐢熸垚鑷畾鏃朵换鍔D: " + timingTask.getId() + "锛�" + timingTask.getRemarks());
+        inspectionTask.setRegistrantId(timingTask.getRegistrantId());
+        inspectionTask.setFrequencyType(timingTask.getFrequencyType());
+        inspectionTask.setFrequencyDetail(timingTask.getFrequencyDetail());
+        inspectionTask.setTenantId(timingTask.getTenantId());
+        // 璁剧疆鐧昏鏃ユ湡涓烘墽琛屾棩鏈�
+        inspectionTask.setCreateTime(executionDate);
+        inspectionTask.setUpdateTime(executionDate);
+        return inspectionTask;
+    }
+
+    /**
+     * 鏇存柊浠诲姟鐨勪笂娆℃墽琛屾椂闂�
+     */
+    private void updateTaskLastExecutionTime(Long taskId, LocalDateTime lastExecutionTime) {
+        String updateSql = "UPDATE timing_task SET last_execution_time = ? WHERE id = ?";
+        jdbcTemplate.update(updateSql, lastExecutionTime, taskId);
+    }
+
+    /**
+     * 鏇存柊浠诲姟鐨勪笅娆℃墽琛屾椂闂�
+     */
+    private void updateTaskNextExecutionTime(Long taskId, LocalDateTime nextExecutionTime) {
+        String updateSql = "UPDATE timing_task SET next_execution_time = ? WHERE id = ?";
+        jdbcTemplate.update(updateSql, nextExecutionTime, taskId);
+    }
+}

--
Gitblit v1.9.3