package com.trafficaudit.ledgeraudit.service; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.trafficaudit.common.util.RegionUtil; import com.trafficaudit.dataimport.entity.H2032EnterpriseMonthly; import com.trafficaudit.dataimport.entity.TransportAuthVehicle; import com.trafficaudit.dataimport.mapper.H2032EnterpriseMonthlyMapper; import com.trafficaudit.dataimport.mapper.TransportAuthVehicleMapper; import com.trafficaudit.ledgeraudit.config.LedgerAuditProperties; import com.trafficaudit.ledgeraudit.dto.LedgerBatchAuditResponse; import com.trafficaudit.ledgeraudit.dto.LedgerAuditResponse; import com.trafficaudit.ledgeraudit.dto.LedgerEnterpriseOption; import com.trafficaudit.ledgeraudit.model.ParsedLedger; import com.trafficaudit.ledgeraudit.route.RouteDistanceProvider; import org.springframework.stereotype.Service; import org.springframework.web.multipart.MultipartFile; import java.time.LocalDateTime; import java.math.BigDecimal; import java.math.RoundingMode; import java.text.Collator; import java.util.ArrayList; import java.util.Comparator; import java.util.LinkedHashMap; import java.util.List; import java.util.Locale; import java.util.Map; @Service public class LedgerAuditService { private final H2032EnterpriseMonthlyMapper monthlyMapper; private final TransportAuthVehicleMapper authMapper; private final LedgerWorkbookParser parser; private final LedgerAuditAnalyzer analyzer; private final RouteDistanceProvider routeProvider; private final LedgerAuditProperties properties; public LedgerAuditService(H2032EnterpriseMonthlyMapper monthlyMapper, TransportAuthVehicleMapper authMapper, LedgerWorkbookParser parser, LedgerAuditAnalyzer analyzer, RouteDistanceProvider routeProvider, LedgerAuditProperties properties) { this.monthlyMapper = monthlyMapper; this.authMapper = authMapper; this.parser = parser; this.analyzer = analyzer; this.routeProvider = routeProvider; this.properties = properties; } public List cities() { return new ArrayList<>(RegionUtil.cityList()); } public List enterprises(String city, String period) { String normalizedCity = normalizeCity(city); if (normalizedCity.isEmpty() || blank(period)) return new ArrayList<>(); List records = monthlyMapper.selectList( new LambdaQueryWrapper().eq(H2032EnterpriseMonthly::getReportPeriod, period.trim())); Map unique = new LinkedHashMap<>(); for (H2032EnterpriseMonthly record : records) { if (!normalizedCity.equals(RegionUtil.cityByCode(record.getRegionCode()))) continue; String name = safe(record.getEnterpriseName()); if (name.isEmpty()) continue; String key = normalizeEnterprise(name); LedgerEnterpriseOption current = unique.get(key); if (current == null) { unique.put(key, new LedgerEnterpriseOption(name, record.getRegionCode(), record.getVehicleTotal(), round0(record.getFreightTotal()), round0(record.getTurnoverTotal()))); } } List result = new ArrayList<>(unique.values()); Collator collator = Collator.getInstance(Locale.CHINA); result.sort(Comparator.comparing(LedgerEnterpriseOption::getEnterpriseName, collator)); return result; } public LedgerAuditResponse check(String city, String period, String enterpriseName, MultipartFile file) throws Exception { String normalizedCity = normalizeCity(city); if (normalizedCity.isEmpty()) throw new IllegalArgumentException("Please select a city"); if (blank(period)) throw new IllegalArgumentException("Please select a report period"); if (blank(enterpriseName)) throw new IllegalArgumentException("Please select an enterprise"); validateFile(file); ensureMapReady(); H2032EnterpriseMonthly monthly = findMonthly(normalizedCity, period.trim(), enterpriseName.trim()); TransportAuthVehicle auth = findAuth(period.trim(), enterpriseName.trim()); ParsedLedger parsed = parser.parse(file); LedgerAuditResponse response = analyzer.analyze(normalizedCity, period.trim(), enterpriseName.trim(), parsed, monthly, auth); if (monthly == null) { response.setEnterpriseName(enterpriseName.trim()); } return response; } public LedgerAuditResponse.MapProviderInfo mapStatus() { return routeProvider.status(); } public LedgerBatchAuditResponse checkBatch(String period, List files) { if (blank(period)) throw new IllegalArgumentException("\u8bf7\u9009\u62e9\u62a5\u8868\u671f"); if (files == null || files.isEmpty()) throw new IllegalArgumentException("\u8bf7\u9009\u62e9\u53f0\u8d26\u6587\u4ef6\u5939"); ensureMapReady(); LedgerBatchAuditResponse response = new LedgerBatchAuditResponse(); response.setCity("\u6309\u6587\u4ef6\u540d\u8bc6\u522b"); response.setReportPeriod(period.trim()); response.setCheckedAt(LocalDateTime.now()); int total = 0; int success = 0; int complete = 0; int incomplete = 0; for (MultipartFile file : files) { String fileName = safe(file == null ? null : file.getOriginalFilename()); if (!isLedgerFile(fileName)) continue; total++; LedgerBatchAuditResponse.Item item = new LedgerBatchAuditResponse.Item(); item.setFileName(fileName); item.setEnterpriseName(enterpriseNameFromFileName(fileName)); try { H2032EnterpriseMonthly monthly = findMonthlyByEnterprise(period.trim(), item.getEnterpriseName()); String city = RegionUtil.cityByCode(monthly.getRegionCode()); TransportAuthVehicle auth = findAuth(period.trim(), item.getEnterpriseName()); ParsedLedger parsed = parser.parse(file); LedgerAuditResponse result = analyzer.analyze(city, period.trim(), item.getEnterpriseName(), parsed, monthly, auth); item.setStatus(result.isAuditComplete() ? "SUCCESS" : "INCOMPLETE"); item.setMessage(result.isAuditComplete() ? "\u6838\u67e5\u5b8c\u6210\uff0c\u5730\u56fe\u91cc\u7a0b\u5df2\u5168\u8986\u76d6" : "\u5df2\u5b8c\u6210\u90e8\u5206\u6838\u67e5\uff0c\u4f46\u5730\u56fe\u91cc\u7a0b\u672a\u5b8c\u6574\u8986\u76d6"); item.setResult(result); success++; if (result.isAuditComplete()) complete++; else incomplete++; } catch (Exception e) { item.setStatus("FAILED"); item.setMessage(e.getMessage() == null ? e.getClass().getSimpleName() : e.getMessage()); } response.getItems().add(item); } if (total == 0) throw new IllegalArgumentException("\u6240\u9009\u6587\u4ef6\u5939\u4e2d\u6ca1\u6709 .xls\u3001.xlsx \u6216 .xlsm \u6587\u4ef6"); response.setTotalCount(total); response.setSuccessCount(success); response.setFailCount(total - success); response.setCompleteCount(complete); response.setIncompleteCount(incomplete); return response; } public Map metadata() { Map result = new LinkedHashMap<>(); result.put("cities", cities()); result.put("mapProvider", mapStatus()); result.put("mapRequired", properties.getMap().isRequired()); result.put("mapTurnoverAllowanceFactor", 1.3); result.put("overreportedTurnoverFormula", "max(0, declaredTurnover - mapTurnover * 1.3)"); return result; } private void ensureMapReady() { if (!properties.getMap().isRequired()) return; LedgerAuditResponse.MapProviderInfo info = routeProvider.status(); if (!info.isConfigured()) { throw new IllegalStateException("\u5730\u56fe\u91cc\u7a0b\u662f\u6838\u67e5\u5fc5\u9009\u9879\uff0c\u5730\u56fe\u670d\u52a1\u672a\u914d\u7f6e\u6216\u4e0d\u53ef\u7528\uff1a" + info.getMessage()); } } private H2032EnterpriseMonthly findMonthlyByEnterprise(String period, String enterpriseName) { List records = monthlyMapper.selectList( new LambdaQueryWrapper().eq(H2032EnterpriseMonthly::getReportPeriod, period)); String target = normalizeEnterprise(enterpriseName); List matches = new ArrayList<>(); for (H2032EnterpriseMonthly record : records) { if (target.equals(normalizeEnterprise(record.getEnterpriseName()))) matches.add(record); } if (matches.size() > 1) { throw new IllegalArgumentException("\u6309\u6587\u4ef6\u540d\u627e\u5230\u591a\u6761\u6708\u62a5\u8bb0\u5f55\uff0c\u8bf7\u6b63\u786e\u4fee\u6539\u6587\u4ef6\u540d\u6216\u6838\u5b9e\u4f01\u4e1a\u552f\u4e00\u540d\u79f0"); } if (matches.isEmpty()) { throw new IllegalArgumentException("\u6309\u6587\u4ef6\u540d\u672a\u5728\u8be5\u62a5\u8868\u671f\u6708\u62a5\u4e2d\u627e\u5230\u4f01\u4e1a\uff1a" + enterpriseName); } H2032EnterpriseMonthly monthly = matches.get(0); if (RegionUtil.cityByCode(monthly.getRegionCode()) == null) { throw new IllegalArgumentException("\u6708\u62a5\u4e2d\u7684\u884c\u653f\u533a\u5212\u4ee3\u7801\u65e0\u6cd5\u8bc6\u522b\u5e02\u5dde\uff1a" + monthly.getRegionCode()); } return monthly; } private H2032EnterpriseMonthly findMonthly(String city, String period, String enterpriseName) { List records = monthlyMapper.selectList( new LambdaQueryWrapper().eq(H2032EnterpriseMonthly::getReportPeriod, period)); List matches = new ArrayList<>(); String target = normalizeEnterprise(enterpriseName); for (H2032EnterpriseMonthly record : records) { if (!city.equals(RegionUtil.cityByCode(record.getRegionCode()))) continue; if (target.equals(normalizeEnterprise(record.getEnterpriseName()))) matches.add(record); } if (matches.size() > 1) { throw new IllegalArgumentException("Multiple monthly report records match the selected enterprise; please verify the database source"); } return matches.isEmpty() ? null : matches.get(0); } private TransportAuthVehicle findAuth(String period, String enterpriseName) { List records = authMapper.selectList( new LambdaQueryWrapper().eq(TransportAuthVehicle::getReportPeriod, period)); List matches = new ArrayList<>(); String target = normalizeEnterprise(enterpriseName); for (TransportAuthVehicle record : records) { if (target.equals(normalizeEnterprise(record.getEnterpriseName()))) matches.add(record); } if (matches.size() > 1) { throw new IllegalArgumentException("Multiple transport-authority vehicle records match the selected enterprise; please verify the database source"); } return matches.isEmpty() ? null : matches.get(0); } private void validateFile(MultipartFile file) { if (file == null || file.isEmpty()) throw new IllegalArgumentException("Please select a ledger file"); String name = safe(file.getOriginalFilename()).toLowerCase(Locale.ROOT); if (!name.endsWith(".xls") && !name.endsWith(".xlsx") && !name.endsWith(".xlsm")) { throw new IllegalArgumentException("Only .xls, .xlsx and .xlsm ledger files are supported"); } } private boolean isLedgerFile(String fileName) { String lower = safe(fileName).toLowerCase(Locale.ROOT); return lower.endsWith(".xls") || lower.endsWith(".xlsx") || lower.endsWith(".xlsm"); } private String enterpriseNameFromFileName(String fileName) { String name = safe(fileName).replace('\\', '/'); int slash = name.lastIndexOf('/'); if (slash >= 0) name = name.substring(slash + 1); int dot = name.lastIndexOf('.'); return dot > 0 ? name.substring(0, dot).trim() : name.trim(); } private String normalizeCity(String city) { String value = RegionUtil.normalizeCityName(city); if (value == null || !RegionUtil.cityList().contains(value)) return ""; return value; } private String normalizeEnterprise(String value) { return safe(value).replaceAll("\\s+", "") .replace('\uff08', '(').replace('\uff09', ')') .toUpperCase(Locale.ROOT); } private BigDecimal round0(Double value) { return value == null ? null : BigDecimal.valueOf(value).setScale(0, RoundingMode.HALF_UP); } private String safe(String value) { return value == null ? "" : value.trim(); } private boolean blank(String value) { return value == null || value.trim().isEmpty(); } }