From 5b41c8896ef7850be2672e45b69bb58e149729ec Mon Sep 17 00:00:00 2001
From: xyc <jc_xiong@hotmail.com>
Date: 星期二, 01 十二月 2026 09:03:48 +0800
Subject: [PATCH] feat(货运统计): 完善台账核查与轨迹里程管理功能

---
 traffic-audit-server/src/main/java/com/trafficaudit/dataimport/service/DataImportService.java |  162 +++++++++++++++++++++++++++++++++++++++++++++--------
 1 files changed, 136 insertions(+), 26 deletions(-)

diff --git a/traffic-audit-server/src/main/java/com/trafficaudit/dataimport/service/DataImportService.java b/traffic-audit-server/src/main/java/com/trafficaudit/dataimport/service/DataImportService.java
index f7fa8e8..7fc84b8 100644
--- a/traffic-audit-server/src/main/java/com/trafficaudit/dataimport/service/DataImportService.java
+++ b/traffic-audit-server/src/main/java/com/trafficaudit/dataimport/service/DataImportService.java
@@ -505,6 +505,7 @@
             throw new RuntimeException("鎶ヨ〃鏈熸牸寮忓簲涓� yyyy-MM锛�" + period);
         }
         int titleRow = -1;
+        List<Integer> titleMonths = new ArrayList<Integer>();
         for (int r = 0; r <= sheet.getLastRowNum(); r++) {
             Row row = sheet.getRow(r);
             if (row == null) continue;
@@ -512,11 +513,14 @@
             if (t == null || !t.contains("鍏ㄧ渷") || !t.contains("鏈�")) continue;
             java.util.regex.Matcher m = java.util.regex.Pattern.compile("鍏ㄧ渷(\\d+)鏈�").matcher(t);
             if (!m.find()) continue;
-            if (Integer.parseInt(m.group(1)) == targetMonth) { titleRow = r; break; }
-            if (titleRow < 0) titleRow = r; // 鏍囬涓嶅惈鐩爣鏈堜唤鏃舵殏璁扮涓�涓爣棰樺潡鍏滃簳
+            int titleMonth = Integer.parseInt(m.group(1));
+            titleMonths.add(titleMonth);
+            if (titleMonth == targetMonth) { titleRow = r; break; }
         }
         if (titleRow < 0) {
-            throw new RuntimeException("鏈壘鍒般�屽叏鐪丯鏈堜釜浣撳杩愰噺姹囨�昏〃銆嶆爣棰樺潡锛岃浣跨敤銆婃ā鏉縚婀栧寳鐪佸叕璺梾瀹㈣繍杈撲釜浣撴埛鏈堝害鐢熶骇鎯呭喌锛圷YYY.M锛夈�嬫暣鐞嗗悗瀵煎叆");
+            throw new RuntimeException("鏈壘鍒般�屽叏鐪�" + targetMonth + "鏈堜釜浣撳杩愰噺姹囨�昏〃銆嶆爣棰樺潡"
+                + (titleMonths.isEmpty() ? "" : "锛屾枃浠朵腑鐨勬爣棰樻湀浠戒负锛�" + titleMonths)
+                + "锛涜纭繚妯℃澘鏍囬鏈堜唤涓庢墍閫夋姤琛ㄦ湡涓�鑷�");
         }
         Row header = sheet.getRow(titleRow + 1);
         if (header == null) {
@@ -1272,26 +1276,7 @@
         List<TransportAuthVehicle> list = new ArrayList<>();
         int failRows = 0;
         try (Workbook wb = WorkbookFactory.create(file.getInputStream())) {
-            Sheet sheet = wb.getSheetAt(0);
-            requireHeaderCols(sheet, "杩愭斂杞﹁締", "浼佷笟鍚嶇О", "鎬荤壍寮曡溅鏁�", "鎬绘寕杞︽暟", "鍏跺畠杞﹁締鏁�", "鎸傝溅鎬诲惃浣�(鍚�)", "鍏跺畠杞﹁締鎬诲惃浣�(鍚�)");
-            Map<String, Integer> colMap = buildHeaderMap(sheet.getRow(0));
-            for (int r = 1; r <= sheet.getLastRowNum(); r++) {
-                Row row = sheet.getRow(r);
-                if (row == null) continue;
-                String name = gs(row, colMap, "浼佷笟鍚嶇О");
-                if (name == null || name.trim().isEmpty()) continue;
-                TransportAuthVehicle entity = new TransportAuthVehicle();
-                entity.setReportPeriod(period);
-                entity.setEnterpriseName(name);
-                entity.setTractorCount(gi(row, colMap, "鎬荤壍寮曡溅鏁�"));
-                entity.setTrailerCount(gi(row, colMap, "鎬绘寕杞︽暟"));
-                entity.setOtherCount(gi(row, colMap, "鍏跺畠杞﹁締鏁�"));
-                entity.setTrailerTons(gd(row, colMap, "鎸傝溅鎬诲惃浣�(鍚�)"));
-                entity.setOtherTons(gd(row, colMap, "鍏跺畠杞﹁締鎬诲惃浣�(鍚�)"));
-                list.add(entity);
-            }
-        } catch (Exception e) {
-            throw e;
+            list = TransportAuthWorkbookParser.parse(wb, period);
         }
 
         // 骞傜瓑锛氬悓鎶ヨ〃鏈熼噸鏂板鍏ワ紝鍏堝垹闄ゆ棫鏁版嵁
@@ -1328,6 +1313,8 @@
         int aboveScale = 0;
         int passenger = 0;
         for (VehicleTrackMileage entity : list) {
+            entity.setDataSource(VehicleTrackMileage.SOURCE_PROVINCIAL);
+            entity.setCityName("鍏ㄧ渷");
             if (VehicleTrackMileage.CATEGORY_PASSENGER.equals(entity.getEnterpriseCategory())) {
                 passenger++;
             } else {
@@ -1337,7 +1324,9 @@
 
         // Replacement is transactional so a failed import cannot leave a half-replaced month.
         trackMileageMapper.delete(new LambdaQueryWrapper<VehicleTrackMileage>()
-            .eq(VehicleTrackMileage::getReportPeriod, period));
+            .eq(VehicleTrackMileage::getReportPeriod, period)
+            .eq(VehicleTrackMileage::getDataSource, VehicleTrackMileage.SOURCE_PROVINCIAL)
+            .eq(VehicleTrackMileage::getCityName, "鍏ㄧ渷"));
         deleteRuleResults("H2032", period);
 
         int success = 0;
@@ -1351,10 +1340,131 @@
             }
         }
         Long batchId = recordBatch(file.getOriginalFilename(), "TRACK_MILEAGE", period, list.size(), success, 0, null);
-        attachBatchId("vehicle_track_mileage", period, batchId);
+        attachProvincialTrackBatchId(period, batchId);
         log.info("Track mileage imported: {} rows for {} (above scale={}, passenger={})",
             success, period, aboveScale, passenger);
         return success;
+    }
+
+    /** Imports and merges city third-party mileage files for one report period. */
+    @Transactional(rollbackFor = Exception.class)
+    public synchronized int importCityTrackMileage(List<MultipartFile> files, String period,
+                                                   String cityName) throws Exception {
+        if (files == null || files.isEmpty()) {
+            throw new IllegalArgumentException("Please select at least one city track mileage file");
+        }
+        String city = RegionUtil.normalizeCityName(cityName);
+        if (city == null || !RegionUtil.CITY_LIST.contains(city)) {
+            throw new IllegalArgumentException("Invalid city name: " + cityName);
+        }
+
+        List<Workbook> workbooks = new ArrayList<>();
+        List<VehicleTrackMileage> list;
+        try {
+            for (MultipartFile file : files) {
+                workbooks.add(WorkbookFactory.create(file.getInputStream()));
+            }
+            Set<String> standardNames = loadLatestCityStandardEnterprises(period, city);
+            list = CityTrackMileageWorkbookParser.parse(workbooks, period, city, standardNames);
+        } finally {
+            for (Workbook workbook : workbooks) {
+                try {
+                    workbook.close();
+                } catch (IOException e) {
+                    log.warn("Failed to close city track workbook", e);
+                }
+            }
+        }
+
+        int aboveScale = 0;
+        int unregistered = 0;
+        for (VehicleTrackMileage entity : list) {
+            if (VehicleTrackMileage.CATEGORY_UNREGISTERED.equals(entity.getEnterpriseCategory())) {
+                unregistered++;
+            } else {
+                aboveScale++;
+            }
+        }
+
+        trackMileageMapper.delete(new LambdaQueryWrapper<VehicleTrackMileage>()
+            .eq(VehicleTrackMileage::getReportPeriod, period)
+            .eq(VehicleTrackMileage::getDataSource, VehicleTrackMileage.SOURCE_CITY_THIRD_PARTY)
+            .eq(VehicleTrackMileage::getCityName, city));
+        deleteRuleResults("H2032", period);
+
+        for (VehicleTrackMileage entity : list) {
+            try {
+                trackMileageMapper.insert(entity);
+            } catch (Exception e) {
+                throw new IllegalStateException("City track mileage insert failed: city=" + city
+                    + ", category=" + entity.getEnterpriseCategory()
+                    + ", enterprise=" + entity.getEnterpriseName(), e);
+            }
+        }
+
+        String batchFile = files.stream().map(MultipartFile::getOriginalFilename)
+            .filter(name -> name != null && !name.trim().isEmpty()).collect(Collectors.joining(", "));
+        if (batchFile.length() > 1000) batchFile = batchFile.substring(0, 1000) + "...";
+        Long batchId = recordBatch(batchFile, "TRACK_MILEAGE_CITY", period, list.size(), list.size(), 0, null);
+        attachCityTrackBatchId(period, city, batchId);
+        log.info("City track mileage imported: city={}, period={}, rows={}, aboveScale={}, unregistered={}",
+            city, period, list.size(), aboveScale, unregistered);
+        return list.size();
+    }
+
+    private Set<String> loadLatestCityStandardEnterprises(String period, String city) {
+        List<H2032EnterpriseMonthly> periods = h2032Mapper.selectList(
+            new LambdaQueryWrapper<H2032EnterpriseMonthly>()
+                .select(H2032EnterpriseMonthly::getReportPeriod)
+                .le(H2032EnterpriseMonthly::getReportPeriod, period)
+                .orderByDesc(H2032EnterpriseMonthly::getReportPeriod)
+                .last("LIMIT 1"));
+        if (periods.isEmpty()) {
+            throw new IllegalStateException("No H2032 enterprise list found at or before " + period);
+        }
+        String listPeriod = periods.get(0).getReportPeriod();
+        String regionPrefix = RegionUtil.codeOfCity(city);
+        if (regionPrefix == null || regionPrefix.length() < 4) {
+            throw new IllegalArgumentException("Cannot resolve region code for city: " + city);
+        }
+        regionPrefix = regionPrefix.substring(0, 4);
+        List<H2032EnterpriseMonthly> enterprises = h2032Mapper.selectList(
+            new LambdaQueryWrapper<H2032EnterpriseMonthly>()
+                .select(H2032EnterpriseMonthly::getEnterpriseName)
+                .eq(H2032EnterpriseMonthly::getReportPeriod, listPeriod)
+                .likeRight(H2032EnterpriseMonthly::getRegionCode, regionPrefix));
+        Set<String> names = new LinkedHashSet<>();
+        for (H2032EnterpriseMonthly enterprise : enterprises) {
+            if (enterprise.getEnterpriseName() != null && !enterprise.getEnterpriseName().trim().isEmpty()) {
+                names.add(enterprise.getEnterpriseName().trim());
+            }
+        }
+        if (names.isEmpty()) {
+            throw new IllegalStateException("No above-scale enterprises found for " + city
+                + " in H2032 period " + listPeriod);
+        }
+        return names;
+    }
+
+    private void attachProvincialTrackBatchId(String period, Long batchId) {
+        if (batchId == null) return;
+        int rows = jdbcTemplate.update("UPDATE vehicle_track_mileage SET import_batch_id=? " +
+                "WHERE report_period=? AND data_source=? AND city_name=? AND import_batch_id IS NULL",
+            batchId, period, VehicleTrackMileage.SOURCE_PROVINCIAL, "鍏ㄧ渷");
+        if (rows > 0) {
+            log.info("Provincial track import batch attached: period={}, batch={}, rows={}", period, batchId, rows);
+        }
+    }
+
+    private void attachCityTrackBatchId(String period, String city, Long batchId) {
+        if (batchId == null) return;
+        int rows = jdbcTemplate.update("UPDATE vehicle_track_mileage SET import_batch_id=? " +
+                "WHERE report_period=? AND data_source=? AND city_name=? AND import_batch_id IS NULL",
+            batchId, period, VehicleTrackMileage.SOURCE_CITY_THIRD_PARTY, city);
+        if (rows > 0) {
+            log.info("City track import batch attached: city={}, period={}, batch={}, rows={}",
+                city, period, batchId, rows);
+        }
     }
 
     // ========== 瑙勪笂瑙勪笅鎷嗗垎 ==========
@@ -1949,7 +2059,7 @@
         CLEAR_TYPE_TO_BATCH.put("h2032", new String[]{"H2032"});
         CLEAR_TYPE_TO_BATCH.put("h202", new String[]{"H202"});
         CLEAR_TYPE_TO_BATCH.put("transportAuth", new String[]{"TRANSPORT_AUTH"});
-        CLEAR_TYPE_TO_BATCH.put("trackMileage", new String[]{"TRACK_MILEAGE"});
+        CLEAR_TYPE_TO_BATCH.put("trackMileage", new String[]{"TRACK_MILEAGE", "TRACK_MILEAGE_CITY"});
         CLEAR_TYPE_TO_BATCH.put("scaleSplit", new String[]{"SCALE_SPLIT"});
         CLEAR_TYPE_TO_BATCH.put("freightTurnover", new String[]{"FREIGHT_TURNOVER"});
         CLEAR_TYPE_TO_BATCH.put("passengerMonthly", new String[]{"H2031"});

--
Gitblit v1.9.1