xyc
2 小时以前 5b41c8896ef7850be2672e45b69bb58e149729ec
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
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<String> cities() {
        return new ArrayList<>(RegionUtil.cityList());
    }
 
    public List<LedgerEnterpriseOption> enterprises(String city, String period) {
        String normalizedCity = normalizeCity(city);
        if (normalizedCity.isEmpty() || blank(period)) return new ArrayList<>();
        List<H2032EnterpriseMonthly> records = monthlyMapper.selectList(
            new LambdaQueryWrapper<H2032EnterpriseMonthly>().eq(H2032EnterpriseMonthly::getReportPeriod, period.trim()));
        Map<String, LedgerEnterpriseOption> 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<LedgerEnterpriseOption> 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<MultipartFile> 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<String, Object> metadata() {
        Map<String, Object> 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<H2032EnterpriseMonthly> records = monthlyMapper.selectList(
            new LambdaQueryWrapper<H2032EnterpriseMonthly>().eq(H2032EnterpriseMonthly::getReportPeriod, period));
        String target = normalizeEnterprise(enterpriseName);
        List<H2032EnterpriseMonthly> 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<H2032EnterpriseMonthly> records = monthlyMapper.selectList(
            new LambdaQueryWrapper<H2032EnterpriseMonthly>().eq(H2032EnterpriseMonthly::getReportPeriod, period));
        List<H2032EnterpriseMonthly> 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<TransportAuthVehicle> records = authMapper.selectList(
            new LambdaQueryWrapper<TransportAuthVehicle>().eq(TransportAuthVehicle::getReportPeriod, period));
        List<TransportAuthVehicle> 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();
    }
}