| | |
| | | import com.trafficaudit.dataimport.entity.EnergyAuthVehicle; |
| | | import com.trafficaudit.dataimport.entity.EnergyVehicleQuarterly; |
| | | import com.trafficaudit.dataimport.entity.FreightTurnoverImport; |
| | | import com.trafficaudit.dataimport.entity.H202FreightVehicleOwnership; |
| | | import com.trafficaudit.dataimport.entity.H2032EnterpriseMonthly; |
| | | import com.trafficaudit.dataimport.entity.PassengerAuthVehicle; |
| | | import com.trafficaudit.dataimport.entity.PassengerEnterpriseMonthly; |
| | |
| | | import com.trafficaudit.dataimport.mapper.EnergyAuthVehicleMapper; |
| | | import com.trafficaudit.dataimport.mapper.EnergyVehicleQuarterlyMapper; |
| | | import com.trafficaudit.dataimport.mapper.FreightTurnoverImportMapper; |
| | | import com.trafficaudit.dataimport.mapper.H202FreightVehicleOwnershipMapper; |
| | | import com.trafficaudit.dataimport.mapper.H2032EnterpriseMonthlyMapper; |
| | | import com.trafficaudit.dataimport.mapper.PassengerAuthVehicleMapper; |
| | | import com.trafficaudit.dataimport.mapper.PassengerEnterpriseMonthlyMapper; |
| | |
| | | |
| | | @Resource |
| | | private H2032EnterpriseMonthlyMapper h2032Mapper; |
| | | @Resource |
| | | private H202FreightVehicleOwnershipMapper h202Mapper; |
| | | @Resource |
| | | private TransportAuthVehicleMapper transportAuthMapper; |
| | | @Resource |
| | |
| | | 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; |
| | |
| | | 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("未找到「全省N月个体客运量汇总表」标题块,请使用《模板_湖北省公路旅客运输个体户月度生产情况(YYYY.M)》整理后导入"); |
| | | throw new RuntimeException("未找到「全省" + targetMonth + "月个体客运量汇总表」标题块" |
| | | + (titleMonths.isEmpty() ? "" : ",文件中的标题月份为:" + titleMonths) |
| | | + ";请确保模板标题月份与所选报表期一致"); |
| | | } |
| | | Row header = sheet.getRow(titleRow + 1); |
| | | if (header == null) { |
| | |
| | | return val == null ? null : val.intValue(); |
| | | } |
| | | |
| | | |
| | | // ========== H202 highway freight vehicle ownership ========== |
| | | |
| | | /** Imports one regional H202 workbook and atomically replaces that region's report period. */ |
| | | public ImportResult importH202(MultipartFile file, String period) throws Exception { |
| | | H202WorkbookParser.ParsedWorkbook parsed; |
| | | try (Workbook wb = WorkbookFactory.create(file.getInputStream())) { |
| | | parsed = H202WorkbookParser.parse(wb, file.getOriginalFilename(), period); |
| | | } |
| | | int success = replaceH202Rows(parsed); |
| | | Long batchId = recordBatch(file.getOriginalFilename(), "H202", period, parsed.getRows().size(), success, 0, null); |
| | | attachBatchId("h202_freight_vehicle_ownership", period, batchId); |
| | | log.info("H202 imported: region={}, period={}, rows={}", parsed.getRegionName(), period, success); |
| | | return new ImportResult(success, 0, new ArrayList<String>()); |
| | | } |
| | | |
| | | /** Batch H202 import: parse every file first; duplicate regions are rejected as a whole group. */ |
| | | public Map<String, Object> importH202BatchFiles(String period, List<MultipartFile> files) throws Exception { |
| | | List<Map<String, Object>> fileResults = new ArrayList<Map<String, Object>>(); |
| | | List<H202ParsedFile> parsedFiles = new ArrayList<H202ParsedFile>(); |
| | | int totalSuccess = 0; |
| | | int totalFail = 0; |
| | | |
| | | for (MultipartFile file : files) { |
| | | Map<String, Object> fileResult = new LinkedHashMap<String, Object>(); |
| | | fileResult.put("fileName", file.getOriginalFilename()); |
| | | try (Workbook wb = WorkbookFactory.create(file.getInputStream())) { |
| | | H202WorkbookParser.ParsedWorkbook parsed = H202WorkbookParser.parse( |
| | | wb, file.getOriginalFilename(), period); |
| | | fileResult.put("city", parsed.getRegionName()); |
| | | fileResult.put("period", period); |
| | | parsedFiles.add(new H202ParsedFile(file.getOriginalFilename(), parsed, fileResult)); |
| | | } catch (Exception e) { |
| | | markH202FileFailure(fileResult, e); |
| | | totalFail++; |
| | | } |
| | | fileResults.add(fileResult); |
| | | } |
| | | |
| | | Map<String, List<H202ParsedFile>> regionGroups = new LinkedHashMap<String, List<H202ParsedFile>>(); |
| | | for (H202ParsedFile item : parsedFiles) { |
| | | String region = item.parsed.getRegionName(); |
| | | List<H202ParsedFile> group = regionGroups.get(region); |
| | | if (group == null) { |
| | | group = new ArrayList<H202ParsedFile>(); |
| | | regionGroups.put(region, group); |
| | | } |
| | | group.add(item); |
| | | } |
| | | |
| | | List<H202ParsedFile> importable = new ArrayList<H202ParsedFile>(); |
| | | for (Map.Entry<String, List<H202ParsedFile>> entry : regionGroups.entrySet()) { |
| | | List<H202ParsedFile> group = entry.getValue(); |
| | | if (group.size() == 1) { |
| | | importable.add(group.get(0)); |
| | | continue; |
| | | } |
| | | List<String> names = new ArrayList<String>(); |
| | | for (H202ParsedFile item : group) { |
| | | names.add(item.fileName); |
| | | } |
| | | String message = "\u540c\u4e00\u6279\u6b21\u4e2d\u5730\u533a\u3010" + entry.getKey() |
| | | + "\u3011\u91cd\u590d\uff1a" + String.join("\u3001", names) |
| | | + "\uff1b\u4e3a\u907f\u514d\u91cd\u590d\u8986\u76d6\uff0c\u8be5\u7ec4\u6587\u4ef6\u5747\u672a\u5bfc\u5165"; |
| | | for (H202ParsedFile item : group) { |
| | | markH202FileFailure(item.fileResult, message); |
| | | totalFail++; |
| | | } |
| | | } |
| | | |
| | | for (H202ParsedFile item : importable) { |
| | | try { |
| | | int success = replaceH202Rows(item.parsed); |
| | | Long batchId = recordBatch(item.fileName, "H202", period, item.parsed.getRows().size(), success, 0, null); |
| | | attachBatchId("h202_freight_vehicle_ownership", period, batchId); |
| | | item.fileResult.put("success", success); |
| | | item.fileResult.put("fail", 0); |
| | | totalSuccess += success; |
| | | } catch (Exception e) { |
| | | markH202FileFailure(item.fileResult, e); |
| | | totalFail++; |
| | | log.error("H202 batch import error: file={}", item.fileName, e); |
| | | } |
| | | } |
| | | |
| | | Map<String, Object> result = new LinkedHashMap<String, Object>(); |
| | | result.put("type", "h202"); |
| | | result.put("total", files.size()); |
| | | result.put("success", totalSuccess); |
| | | result.put("fail", totalFail); |
| | | result.put("files", fileResults); |
| | | return result; |
| | | } |
| | | |
| | | private void markH202FileFailure(Map<String, Object> fileResult, Exception error) { |
| | | String message = error.getMessage() == null ? error.toString() : error.getMessage(); |
| | | markH202FileFailure(fileResult, message); |
| | | } |
| | | |
| | | private void markH202FileFailure(Map<String, Object> fileResult, String message) { |
| | | fileResult.put("success", 0); |
| | | fileResult.put("fail", 1); |
| | | fileResult.put("error", message); |
| | | } |
| | | |
| | | private int replaceH202Rows(H202WorkbookParser.ParsedWorkbook parsed) { |
| | | String period = parsed.getRows().isEmpty() ? null : parsed.getRows().get(0).getReportPeriod(); |
| | | String region = parsed.getRegionName(); |
| | | try (SqlSession session = sqlSessionFactory.openSession(ExecutorType.BATCH, false)) { |
| | | try { |
| | | H202FreightVehicleOwnershipMapper batchMapper = session.getMapper(H202FreightVehicleOwnershipMapper.class); |
| | | batchMapper.delete(new LambdaQueryWrapper<H202FreightVehicleOwnership>() |
| | | .eq(H202FreightVehicleOwnership::getReportPeriod, period) |
| | | .eq(H202FreightVehicleOwnership::getRegionName, region)); |
| | | for (H202FreightVehicleOwnership row : parsed.getRows()) { |
| | | batchMapper.insert(row); |
| | | } |
| | | session.flushStatements(); |
| | | session.commit(); |
| | | return parsed.getRows().size(); |
| | | } catch (Exception e) { |
| | | session.rollback(); |
| | | throw e; |
| | | } |
| | | } |
| | | } |
| | | |
| | | private static final class H202ParsedFile { |
| | | private final String fileName; |
| | | private final H202WorkbookParser.ParsedWorkbook parsed; |
| | | private final Map<String, Object> fileResult; |
| | | |
| | | private H202ParsedFile(String fileName, H202WorkbookParser.ParsedWorkbook parsed, |
| | | Map<String, Object> fileResult) { |
| | | this.fileName = fileName; |
| | | this.parsed = parsed; |
| | | this.fileResult = fileResult; |
| | | } |
| | | } |
| | | |
| | | // ========== 运政车辆 ========== |
| | | |
| | | /** 运政车辆导入:与 H203-2 月报一致,按表头名称定位列,列顺序变化也能正确导入 */ |
| | |
| | | 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); |
| | | } |
| | | |
| | | // 幂等:同报表期重新导入,先删除旧数据 |
| | |
| | | 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 { |
| | |
| | | |
| | | // 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; |
| | |
| | | } |
| | | } |
| | | 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); |
| | | } |
| | | } |
| | | |
| | | // ========== 规上规下拆分 ========== |
| | |
| | | |
| | | static { |
| | | CLEAR_TYPE_TO_OP.put("h2032", "H2032"); |
| | | CLEAR_TYPE_TO_OP.put("h202", "H202"); |
| | | CLEAR_TYPE_TO_OP.put("transportAuth", "TRANSPORT_AUTH"); |
| | | CLEAR_TYPE_TO_OP.put("trackMileage", "TRACK_MILEAGE"); |
| | | CLEAR_TYPE_TO_OP.put("scaleSplit", "SCALE_SPLIT"); |
| | |
| | | String[] investPassengerBatch = {"INVEST_客运站场", "INVEST_客运站场_CITY"}; |
| | | String[] investLogisticsBatch = {"INVEST_物流园区", "INVEST_物流园区_CITY"}; |
| | | 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"}); |
| | |
| | | if (clearAll) { |
| | | dataRows += h2032Mapper.delete(new LambdaQueryWrapper<H2032EnterpriseMonthly>() |
| | | .eq(H2032EnterpriseMonthly::getReportPeriod, period)); |
| | | dataRows += h202Mapper.delete(new LambdaQueryWrapper<H202FreightVehicleOwnership>() |
| | | .eq(H202FreightVehicleOwnership::getReportPeriod, period)); |
| | | dataRows += transportAuthMapper.delete(new LambdaQueryWrapper<TransportAuthVehicle>() |
| | | .eq(TransportAuthVehicle::getReportPeriod, period)); |
| | | dataRows += trackMileageMapper.delete(new LambdaQueryWrapper<VehicleTrackMileage>() |
| | |
| | | case "H2032": |
| | | return h2032Mapper.delete(new LambdaQueryWrapper<H2032EnterpriseMonthly>() |
| | | .eq(H2032EnterpriseMonthly::getReportPeriod, period)); |
| | | case "H202": |
| | | return h202Mapper.delete(new LambdaQueryWrapper<H202FreightVehicleOwnership>() |
| | | .eq(H202FreightVehicleOwnership::getReportPeriod, period)); |
| | | case "TRANSPORT_AUTH": |
| | | return transportAuthMapper.delete(new LambdaQueryWrapper<TransportAuthVehicle>() |
| | | .eq(TransportAuthVehicle::getReportPeriod, period)); |
| | |
| | | public Map<String, Object> importBatchFiles(String type, String period, List<MultipartFile> files) throws Exception { |
| | | if (files == null || files.isEmpty()) { |
| | | throw new RuntimeException("未接收到任何文件"); |
| | | } |
| | | if ("h202".equals(type)) { |
| | | return importH202BatchFiles(period, files); |
| | | } |
| | | if ("investment".equals(type) || "investmentLogistics".equals(type)) { |
| | | String category = "investment".equals(type) ? "客运站场" : "物流园区"; |
| | |
| | | private ImportResult importDirFile(String type, MultipartFile file, String period) throws Exception { |
| | | switch (type) { |
| | | case "h2032": return importH2032(file, period); |
| | | case "h202": return importH202(file, period); |
| | | case "passengerMonthly": return importPassengerMonthly(file, period); |
| | | case "passengerIndividual": return importPassengerIndividual(file, period); |
| | | case "passengerAuth": return importPassengerAuth(file, period); |