Эх сурвалжийг харах

feat: 实现睿行车辆用车月统计数据入库定时任务

weijianghai 1 жил өмнө
parent
commit
2cb641b9c2

+ 10 - 0
readme.md

@@ -60,6 +60,16 @@ curl --location 'http://localhost:39110/jobs/runJob' \
 }'
 ```
 
+##### 睿行车辆用车月统计数据入库定时任务
+
+```shell
+curl --location 'http://localhost:39110/jobs/runJob' \
+--header 'Content-Type: application/json' \
+--data '{
+    "jobName": "CAR_YONG_CHE_JOB"
+}'
+```
+
 #### 成本系统
 
 ##### 河北成本管理系统车辆燃油数据入库定时任务

+ 8 - 0
src/main/java/com/nokia/finance/tasks/config/JobConfig.java

@@ -72,6 +72,14 @@ public class JobConfig {
      * 睿行车辆无单用车报警月统计数据归档路径
      */
     private String carWuDanYongCheHistoryPath;
+    /**
+     * 睿行车辆用车月统计数据路径
+     */
+    private String carYongCheSourcePath;
+    /**
+     * 睿行车辆用车月统计数据归档路径
+     */
+    private String carYongCheHistoryPath;
     /**
      * 河北成本管理系统车辆燃油数据路径
      */

+ 4 - 0
src/main/java/com/nokia/finance/tasks/enums/JobEnum.java

@@ -21,6 +21,10 @@ public enum JobEnum {
      * 睿行车辆无单用车报警月统计数据入库定时任务
      */
     CAR_WU_DAN_YONG_CHE_JOB,
+    /**
+     * 睿行车辆用车月统计数据入库定时任务
+     */
+    CAR_YONG_CHE_JOB,
     /**
      * 河北成本管理系统车辆燃油数据入库定时任务
      */

+ 3 - 3
src/main/java/com/nokia/finance/tasks/jobs/car/ruixing/CarWuDanYongCheJob.java

@@ -63,14 +63,14 @@ public class CarWuDanYongCheJob {
     /**
      * 执行任务
      */
-    @Scheduled(cron = "0 50 23 * * ?")
+    @Scheduled(cron = "0 50 23 1 * ?")
     public void runJob() {
         // 数据目录
         Path dir = Paths.get(jobConfig.getCarWuDanYongCheSourcePath());
         try (Stream<Path> stream = Files.list(dir)) {
             // 获取数据目录下的文件列表
             List<Path> pathList = stream.filter(t -> t.toString().endsWith(".xlsx")).sorted().toList();
-            log.info("睿行车辆无单用车报警月统计数据数据文件列表: {}", pathList);
+            log.info("睿行车辆无单用车报警月统计数据文件列表: {}", pathList);
             if (CollectionUtils.isEmpty(pathList)) {
                 throw new MyRuntimeException("睿行车辆无单用车报警月统计数据没有文件");
             }
@@ -92,7 +92,7 @@ public class CarWuDanYongCheJob {
         List<Map<String, String>> distinctList = dataProcessing(path, list);
         Path csvPath = toCsv(path, distinctList);
         copyCsv(csvPath);
-        move(path);
+//        move(path);
     }
 
     /**

+ 320 - 0
src/main/java/com/nokia/finance/tasks/jobs/car/ruixing/CarYongCheJob.java

@@ -0,0 +1,320 @@
+package com.nokia.finance.tasks.jobs.car.ruixing;
+
+import com.nokia.finance.tasks.common.exception.MyRuntimeException;
+import com.nokia.finance.tasks.common.utils.psql.PsqlUtil;
+import com.nokia.finance.tasks.config.JobConfig;
+import com.nokia.finance.tasks.pojo.po.common.AreaPo;
+import com.nokia.finance.tasks.pojo.po.common.OrganizationPo;
+import com.nokia.finance.tasks.service.car.CarService;
+import com.nokia.finance.tasks.service.common.AreaService;
+import com.nokia.finance.tasks.service.common.OrganizationService;
+import lombok.extern.slf4j.Slf4j;
+import org.apache.commons.csv.CSVFormat;
+import org.apache.commons.csv.CSVPrinter;
+import org.apache.poi.ss.usermodel.Cell;
+import org.apache.poi.ss.usermodel.DateUtil;
+import org.apache.poi.ss.usermodel.Row;
+import org.apache.poi.ss.usermodel.Sheet;
+import org.apache.poi.ss.usermodel.Workbook;
+import org.apache.poi.xssf.usermodel.XSSFWorkbook;
+import org.springframework.scheduling.annotation.Scheduled;
+import org.springframework.stereotype.Service;
+import org.springframework.util.CollectionUtils;
+import org.springframework.util.StringUtils;
+
+import java.io.InputStream;
+import java.io.OutputStreamWriter;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.nio.file.StandardCopyOption;
+import java.time.LocalDate;
+import java.time.LocalDateTime;
+import java.time.format.DateTimeFormatter;
+import java.util.ArrayList;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.stream.Stream;
+
+/**
+ * 睿行车辆用车月统计数据入库定时任务
+ */
+@Slf4j
+@Service
+public class CarYongCheJob {
+    private final JobConfig jobConfig;
+    private final CarService carService;
+    private final OrganizationService organizationService;
+    private final AreaService areaService;
+
+    public CarYongCheJob(JobConfig jobConfig, CarService carService, OrganizationService organizationService,
+                         AreaService areaService) {
+        this.jobConfig = jobConfig;
+        this.carService = carService;
+        this.organizationService = organizationService;
+        this.areaService = areaService;
+    }
+
+    /**
+     * 执行任务
+     */
+    @Scheduled(cron = "0 48 23 1 * ?")
+    public void runJob() {
+        // 数据目录
+        Path dir = Paths.get(jobConfig.getCarYongCheSourcePath());
+        try (Stream<Path> stream = Files.list(dir)) {
+            // 获取数据目录下的文件列表
+            List<Path> pathList = stream.filter(t -> t.toString().endsWith(".xlsx")).sorted().toList();
+            log.info("睿行车辆用车月统计数据文件列表: {}", pathList);
+            if (CollectionUtils.isEmpty(pathList)) {
+                throw new MyRuntimeException("睿行车辆用车月统计数据没有文件");
+            }
+            for (Path path : pathList) {
+                singleJob(path);
+            }
+        } catch (Exception e) {
+            log.error(e.getMessage(), e);
+        }
+    }
+
+    /**
+     * 处理单个文件
+     *
+     * @param path 文件路径
+     */
+    public void singleJob(Path path) throws Exception {
+        List<Map<String, String>> list = readFile(path);
+        List<Map<String, String>> distinctList = dataProcessing(path, list);
+        Path csvPath = toCsv(path, distinctList);
+        copyCsv(csvPath);
+        move(path);
+    }
+
+    /**
+     * 读取文件
+     *
+     * @param path 文件路径
+     */
+    public List<Map<String, String>> readFile(Path path) throws Exception {
+        log.info("读取: {}", path);
+        List<String> rawHeaders = Stream.of("申请单号", "派遣单号", "申请类型", "车牌号", "车辆类型", "车辆级别",
+                "司机名称", "用车人", "用车部门", "用车事由", "出发地", "目的地", "出发时间", "归队时间", "行驶里程", "出车时长")
+                .toList();
+        List<String> headers = Stream.of("shen_qing_dan_hao", "pai_qian_dan_hao", "shen_qing_lei_xing",
+                "che_pai_hao", "che_liang_lei_xing", "che_liang_ji_bie", "si_ji_ming_cheng", "yong_che_ren",
+                "yong_che_bu_men", "yong_che_shi_you", "chu_fa_di", "mu_di_di", "chu_fa_shi_jian", "gui_dui_shi_jian",
+                "xing_shi_li_cheng", "chu_che_shi_chang").toList();
+        try (InputStream inputStream = Files.newInputStream(path);
+             Workbook workbook = new XSSFWorkbook(inputStream)
+        ) {
+            List<Map<String, String>> resultList = new ArrayList<>();
+            // 读取第一个工作表
+            Sheet sheet = workbook.getSheetAt(0);
+            // 表头行
+            Row headerRow = sheet.getRow(0);
+            // 列数
+            int columnCount = headerRow.getPhysicalNumberOfCells();
+            log.info("columnCount: {}", columnCount);
+            // 检查表头
+            if (headers.size() != columnCount) {
+                throw new MyRuntimeException(path.getFileName() + "列数错误");
+            }
+            for (int i = 0; i < columnCount; i++) {
+                Cell cell = headerRow.getCell(i);
+                if (cell == null || !rawHeaders.get(i).equals(cell.getStringCellValue())) {
+                    throw new MyRuntimeException(path.getFileName() + " 表头错误");
+                }
+            }
+            // 最后行数
+            int lastRowNum = sheet.getLastRowNum();
+            log.info("lastRowNum: {}", lastRowNum);
+            if (lastRowNum == 0) {
+                throw new MyRuntimeException(path.getFileName() + " 为空");
+            }
+            // 遍历行
+            for (int i = 1; i <= lastRowNum; i++) {
+                Row row = sheet.getRow(i);
+                if (row == null) {
+                    continue;
+                }
+                Map<String, String> rowMap = new LinkedHashMap<>();
+                // 遍历列
+                for (int j = 0; j < columnCount; j++) {
+                    String header = headers.get(j);
+                    String cellValue = "";
+                    rowMap.put(header, cellValue);
+                    Cell cell = row.getCell(j);
+                    if (cell == null) {
+                        continue;
+                    }
+                    switch (cell.getCellType()) {
+                        case STRING:
+                            boolean skipTrim = "chu_fa_shi_jian".equals(header)
+                                    || "gui_dui_shi_jian".equals(header);
+                            // 删除字符串空白字符
+                            cellValue = skipTrim ? cell.getStringCellValue()
+                                    : StringUtils.trimAllWhitespace(cell.getStringCellValue());
+                            if ("chu_fa_shi_jian".equals(header)
+                                    || "gui_dui_shi_jian".equals(header)) {
+                                if (StringUtils.hasText(cellValue)) {
+                                    try {
+                                        cellValue = LocalDateTime.parse(cellValue,
+                                                DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))
+                                                .format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
+                                    } catch (Exception e1) {
+                                        try {
+                                            cellValue = LocalDate.parse(cellValue,
+                                                            DateTimeFormatter.ofPattern("yyyy-MM-dd")).atStartOfDay()
+                                                    .format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
+                                        } catch (Exception e2) {
+                                            log.error("{} 时间格式化失败", cellValue);
+                                        }
+                                    }
+                                }
+                            }
+                            break;
+                        case NUMERIC:
+                            if (DateUtil.isCellDateFormatted(cell)) {
+                                cellValue = DateUtil.getLocalDateTime(cell.getNumericCellValue())
+                                        .format(DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss"));
+                                break;
+                            }
+                            cellValue = String.valueOf(cell.getNumericCellValue());
+                            break;
+                        case BOOLEAN:
+                            cellValue = String.valueOf(cell.getBooleanCellValue());
+                            break;
+                        default:
+                            break;
+                    }
+                    rowMap.put(header, cellValue);
+                }
+                resultList.add(rowMap);
+            }
+            return resultList;
+        }
+    }
+
+    /**
+     * 数据加工
+     *
+     * @param path 文件路径
+     * @param list 数据
+     */
+    public List<Map<String, String>> dataProcessing(Path path, List<Map<String, String>> list) {
+        List<OrganizationPo> secondOrgs = organizationService.getSecondOrgs();
+        List<OrganizationPo> thirdOrgs = organizationService.getThirdOrgs();
+        Map<String, OrganizationPo> orgMap = organizationService.getOrgMap(secondOrgs, thirdOrgs);
+        Map<String, List<OrganizationPo>> thirdOrganizationListMap =
+                organizationService.getThirdOrganizationListMap(secondOrgs, thirdOrgs);
+        List<AreaPo> cities = areaService.getCities();
+        List<AreaPo> districts = areaService.getDistricts();
+        Map<String, AreaPo> areaMap = areaService.getAreaMap(cities, districts);
+        Map<String, List<AreaPo>> districtListMap = areaService.getDistrictListMap(cities, districts);
+        for (Map<String, String> map : list) {
+            String yearMonth = "";
+            String year = "";
+            String month = "";
+            String chuFaShiJian = map.get("chu_fa_shi_jian");
+            if (StringUtils.hasText(chuFaShiJian)) {
+                LocalDateTime localDateTime = LocalDateTime.parse(chuFaShiJian,
+                        DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
+                yearMonth = localDateTime.format(DateTimeFormatter.ofPattern("yyyyMM"));
+                year = String.valueOf(localDateTime.getYear());
+                month = String.valueOf(localDateTime.getMonthValue());
+            }
+            map.put("year_month", yearMonth);
+            map.put("year_no", year);
+            map.put("month_no", month);
+            String rawChePaiHao = map.get("che_pai_hao");
+            map.put("raw_che_pai_hao", rawChePaiHao);
+            String chePaiHao = carService.getChePai(rawChePaiHao);
+            map.put("che_pai_hao", chePaiHao);
+            String chePaiFail = carService.chePaiFail(rawChePaiHao);
+            map.put("che_pai_fail", chePaiFail);
+            String yongCheBuMen = map.get("yong_che_bu_men");
+            String firstUnit = carService.getFirstUnit(yongCheBuMen);
+            map.put("first_unit", firstUnit);
+            String secondUnit = carService.getSecondUnit(yongCheBuMen, firstUnit);
+            map.put("second_unit", secondUnit);
+            String thirdUnit = carService.getThirdUnit(yongCheBuMen, secondUnit);
+            map.put("third_unit", thirdUnit);
+            String areaNo = carService.getAreaNo(secondOrgs, yongCheBuMen);
+            map.put("area_no", areaNo);
+            String areaName = carService.getOrgName(orgMap, areaNo);
+            map.put("area_name", areaName);
+            String cityNo = carService.getCityNo(thirdOrganizationListMap, areaNo, areaName, yongCheBuMen);
+            map.put("city_no", cityNo);
+            String cityName = carService.getOrgName(orgMap, cityNo);
+            map.put("city_name", cityName);
+            String areaNo2 = carService.getAreaNo2(areaName, cityName);
+            map.put("area_no2", areaNo2);
+            String areaName2 = carService.getOrgName(orgMap, areaNo2);
+            map.put("area_name2", areaName2);
+            String cityId = carService.getCityId(cities, yongCheBuMen);
+            map.put("city_id", cityId);
+            String city = carService.getAreaName(areaMap, cityId);
+            map.put("city", city);
+            String districtId = carService.getDistrictId(districtListMap, cityId, cityName, yongCheBuMen);
+            map.put("district_id", districtId);
+            String district = carService.getAreaName(areaMap, districtId);
+            map.put("district", district);
+            String baoFei = carService.baoFei(rawChePaiHao);
+            map.put("bao_fei", baoFei);
+            map.put("source", path.getFileName().toString());
+        }
+        return list;
+    }
+
+    /**
+     * 生成csv
+     *
+     * @param path 源文件路径
+     * @param list 数据
+     */
+    public Path toCsv(Path path, List<Map<String, String>> list) throws Exception {
+        log.info("去重后条数:{}", list.size());
+        Files.createDirectories(Paths.get(jobConfig.getCarYongCheHistoryPath()));
+        Path csvPath = Paths.get(jobConfig.getCarYongCheHistoryPath() + path.getFileName() + ".csv");
+        try (OutputStreamWriter osw = new OutputStreamWriter(Files.newOutputStream(csvPath),
+                StandardCharsets.UTF_8);
+             CSVPrinter printer = new CSVPrinter(osw, CSVFormat.DEFAULT)) {
+            // 添加bom头避免excel乱码
+            osw.write('\ufeff');
+            Map<String, String> header = list.get(0);
+            // 表头
+            printer.printRecord(header.keySet());
+            for (Map<String, String> map : list) {
+                printer.printRecord(map.values());
+            }
+        }
+        return csvPath;
+    }
+
+    /**
+     * 导入数据库
+     *
+     * @param path 文件路径
+     */
+    public void copyCsv(Path path) {
+        String dbTable = "car.car_yong_che";
+        String csv = path.toString();
+        String columns = "(shen_qing_dan_hao,pai_qian_dan_hao,shen_qing_lei_xing,che_pai_hao,che_liang_lei_xing,che_liang_ji_bie,si_ji_ming_cheng,yong_che_ren,yong_che_bu_men,yong_che_shi_you,chu_fa_di,mu_di_di,chu_fa_shi_jian,gui_dui_shi_jian,xing_shi_li_cheng,chu_che_shi_chang,year_month,year_no,month_no,raw_che_pai_hao,che_pai_fail,first_unit,second_unit,third_unit,area_no,area_name,city_no,city_name,area_no2,area_name2,city_id,city,district_id,district,bao_fei,source)";
+        Long timeout = 60000L;
+        PsqlUtil.copyCsv(jobConfig.getCopyScriptPath(), jobConfig.getDbHost(), jobConfig.getDbPort(),
+                jobConfig.getDbUsername(), jobConfig.getDbPassword(), jobConfig.getDbName(), dbTable, csv, columns,
+                timeout, null);
+    }
+
+    /**
+     * 移动源文件到历史文件夹
+     *
+     * @param path 源文件路径
+     */
+    public void move(Path path) throws Exception {
+        Path targetPath = Paths.get(jobConfig.getCarYongCheHistoryPath(), path.getFileName().toString());
+        Files.move(path, targetPath, StandardCopyOption.REPLACE_EXISTING);
+    }
+}

+ 7 - 0
src/main/java/com/nokia/finance/tasks/service/JobService.java

@@ -12,6 +12,7 @@ import com.nokia.finance.tasks.jobs.car.ruixing.CarBaoFeiJob;
 import com.nokia.finance.tasks.jobs.car.ruixing.CarBaseDataDayJob;
 import com.nokia.finance.tasks.jobs.car.ruixing.CarLiChengMonthJob;
 import com.nokia.finance.tasks.jobs.car.ruixing.CarWuDanYongCheJob;
+import com.nokia.finance.tasks.jobs.car.ruixing.CarYongCheJob;
 import com.nokia.finance.tasks.jobs.car.ruixing.CarYueJieJob;
 import com.nokia.finance.tasks.jobs.house.chengben.HouseBuildingRepairMonthJob;
 import com.nokia.finance.tasks.pojo.RunJobDto;
@@ -24,6 +25,7 @@ public class JobService {
     private final CarBaoFeiJob carBaoFeiJob;
     private final CarLiChengMonthJob carLiChengMonthJob;
     private final CarWuDanYongCheJob carWuDanYongCheJob;
+    private final CarYongCheJob carYongCheJob;
     private final CarRanYouJob carRanYouJob;
     private final CarDaWeiXiuJob carDaWeiXiuJob;
     private final CarWeiXiuJob carWeiXiuJob;
@@ -35,6 +37,7 @@ public class JobService {
 
     public JobService(CarBaseDataDayJob carBaseDataDayJob, CarYueJieJob carYueJieJob, CarBaoFeiJob carBaoFeiJob,
                       CarLiChengMonthJob carLiChengMonthJob, CarWuDanYongCheJob carWuDanYongCheJob,
+                      CarYongCheJob carYongCheJob,
                       CarRanYouJob carRanYouJob, CarDaWeiXiuJob carDaWeiXiuJob, CarWeiXiuJob carWeiXiuJob,
                       CarLuQiaoJob carLuQiaoJob, CarBaoXianJob carBaoXianJob, CarNianJianFeiJob carNianJianFeiJob,
                       CarQiTaJob carQiTaJob, HouseBuildingRepairMonthJob houseBuildingRepairMonthJob) {
@@ -43,6 +46,7 @@ public class JobService {
         this.carBaoFeiJob = carBaoFeiJob;
         this.carLiChengMonthJob = carLiChengMonthJob;
         this.carWuDanYongCheJob = carWuDanYongCheJob;
+        this.carYongCheJob = carYongCheJob;
         this.carRanYouJob = carRanYouJob;
         this.carDaWeiXiuJob = carDaWeiXiuJob;
         this.carWeiXiuJob = carWeiXiuJob;
@@ -70,6 +74,9 @@ public class JobService {
             case CAR_WU_DAN_YONG_CHE_JOB:
                 carWuDanYongCheJob.runJob();
                 break;
+            case CAR_YONG_CHE_JOB:
+                carYongCheJob.runJob();
+                break;
             case CAR_RAN_YOU_JOB:
                 carRanYouJob.runJob();
                 break;

+ 4 - 0
src/main/resources/application-dev.yml

@@ -39,6 +39,10 @@ job:
     car-wu-dan-yong-che-source-path: data/rxftp/wdycbjytjbjcs/
     # 睿行车辆无单用车报警月统计数据归档路径
     car-wu-dan-yong-che-history-path: data/history/rxftp/wdycbjytjbjcs/
+    # 睿行车辆用车月统计数据路径
+    car-yong-che-source-path: data/rxftp/wdycbjytjcccs/
+    # 睿行车辆用车月统计数据归档路径
+    car-yong-che-history-path: data/history/rxftp/wdycbjytjcccs/
     # 河北成本管理系统车辆燃油数据路径
     car-ran-you-source-path: data/jzftp/HE_M_MTC_VEHICLE_OIL/
     # 河北成本管理系统车辆燃油数据归档路径

+ 4 - 0
src/main/resources/application-prod.yml

@@ -39,6 +39,10 @@ job:
     car-wu-dan-yong-che-source-path: /data/rxftp/wdycbjytjbjcs/
     # 睿行车辆无单用车报警月统计数据归档路径
     car-wu-dan-yong-che-history-path: /data/history/rxftp/wdycbjytjbjcs/
+    # 睿行车辆用车月统计数据路径
+    car-yong-che-source-path: /data/rxftp/wdycbjytjcccs/
+    # 睿行车辆用车月统计数据归档路径
+    car-yong-che-history-path: /data/history/rxftp/wdycbjytjcccs/
     # 河北成本管理系统车辆燃油数据路径
     car-ran-you-source-path: /data/jzftp/HE_M_MTC_VEHICLE_OIL/
     # 河北成本管理系统车辆燃油数据归档路径

+ 22 - 0
src/test/java/com/nokia/finance/tasks/car/ruixing/CarYongCheJobTests.java

@@ -0,0 +1,22 @@
+package com.nokia.finance.tasks.car.ruixing;
+
+import com.nokia.finance.tasks.jobs.car.ruixing.CarYongCheJob;
+import lombok.extern.slf4j.Slf4j;
+import org.junit.jupiter.api.Test;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.test.context.SpringBootTest;
+import org.springframework.test.context.ActiveProfiles;
+
+@Slf4j
+@SpringBootTest
+@ActiveProfiles("dev")
+class CarYongCheJobTests {
+    @Autowired
+    CarYongCheJob carYongCheJob;
+
+    @Test
+    void runJobTest() {
+        carYongCheJob.runJob();
+    }
+
+}