xyc
4 小时以前 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
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Load enterprise ledger spot-check evidence and build a review workbook."""
 
import argparse
import csv
import hashlib
import json
import math
import os
import re
import sys
from collections import Counter, defaultdict
from dataclasses import dataclass, field
from datetime import date, datetime, timedelta
from decimal import Decimal
from pathlib import Path
from typing import Any, Dict, Iterable, List, Optional, Sequence, Tuple, Union
 
import pymysql
import xlrd
from openpyxl import Workbook, load_workbook
from openpyxl.styles import Alignment, Border, Font, PatternFill, Side
from openpyxl.utils import get_column_letter
 
PLATE_RE = re.compile(r"[\u4e00-\u9fff][A-Z][A-Z0-9]{5,6}")
DATE_TIME_RE = re.compile(r"(\d{2})-(\d{1,2})-(\d{1,2})\s+(\d{1,2}):(\d{2}):(\d{2})")
PERIOD_RE = re.compile(r"^(\d{4})-(\d{2})$")
TRAILER_PLATE_RE = re.compile(r"[\u4e00-\u9fff][A-Z][A-Z0-9]{3,7}\u6302")
 
 
@dataclass
class Profile:
    key: str
    city: str
    enterprise: str
    ledger_file: str
    ledger_sheet: str
    ledger_parser: str
    ledger_type: str
    track_file: str
    header_row: int = 1
    first_data_row: int = 2
    max_scan_rows: int = 2000
    preferred_sample_plate: str = ""
 
 
@dataclass(frozen=True)
class VehicleRegistryCounts:
    total: int
    main: int
    tractor: int
    trailer: int
    other: int
 
 
PROFILES: List[Profile] = [
    Profile("anxin", "咸宁", "湖北安欣物流有限责任公司", r"咸宁\安欣.xlsx", "9月", "anxin", "MONTHLY_ROUTE", r"work\咸宁\安欣\车辆轨迹分析明细_咸宁_安欣.xls", 2, 3, 200, "鄂L1N523"),
    Profile("demin", "咸宁", "湖北省德敏物流有限公司", r"咸宁\德敏.xlsx", "Sheet1", "demin", "MONTHLY_ROUTE", r"work\咸宁\德敏\车辆轨迹分析明细_咸宁_德敏.xls", 2, 3, 200, "鄂L1J689"),
    Profile("huinong", "咸宁", "湖北供销惠侬物流运输有限公司", r"咸宁\惠侬物流货运量原始台账(1).xls", "2026年9月   ", "huinong", "MONTHLY_ROUTE", r"work\咸宁\惠侬\车辆轨迹分析明细_咸宁_惠侬.xls", 2, 3, 200, "鄂L1K202"),
    Profile("luchang", "咸宁", "通城县路畅通运输有限公司", r"咸宁\路畅通2026.09.xlsx", "2026.09", "luchang", "MONTHLY_ROUTE", r"work\咸宁\路畅通\车辆轨迹分析明细_咸宁_路畅通.xls", 3, 4, 200, "鄂L5A039"),
    Profile("guangfa", "黄冈", "黄梅县广发汽车运输有限公司", r"黄冈\黄冈9月份抽查台账\9月-广发.xls", "9月", "guangfa", "MONTHLY_ROUTE", r"work\黄冈\车辆轨迹分析明细_黄冈_广发.xls", 2, 4, 500),
    Profile("datong", "黄冈", "湖北大通临空物流有限公司", r"黄冈\黄冈9月份抽查台账\大通.xlsx", "9月", "datong", "MONTHLY_ROUTE", r"work\黄冈\大通\车辆轨迹分析明细_黄冈_大通.xls", 4, 6, 500, "鄂J28801"),
    Profile("kaiying", "黄冈", "湖北凯赢运输有限公司", r"黄冈\黄冈9月份抽查台账\凯赢.xls", "危货", "kaiying", "DAILY_DETAIL", r"work\黄冈\车辆轨迹分析明细_黄冈_凯赢.xls", 1, 2, 1000),
    Profile("xindafei", "黄冈", "黄冈市鑫达飞物流有限公司", r"黄冈\黄冈9月份抽查台账\鑫达飞.xlsx", "9月", "xindafei", "MONTHLY_ROUTE", r"work\黄冈\车辆轨迹分析明细_黄冈_鑫达飞.xls", 1, 2, 200),
    Profile("shengda", "宜昌", "宜昌晟达物流有限公司", r"宜昌\晟达2026运管一套报表台账(10.15).xlsx", "26.9", "shengda", "DAILY_DETAIL", r"work\宜昌\车辆轨迹分析明细_宜昌_晟达.xls", 4, 6, 1000),
    Profile("heyun", "宜昌", "湖北訸运石化物流有限公司", r"宜昌\訸运2609.xlsx", "9月", "heyun", "DAILY_DETAIL", r"work\宜昌\车辆轨迹分析明细_宜昌_訸运.xls", 1, 2, 1000),
    Profile("kaixiangda", "宜昌", "宜昌凯祥达物流有限公司", r"宜昌\凯翔达2026年1-12月周转量.xlsx", "9月", "kaixiangda", "DAILY_DETAIL", r"work\宜昌\车辆轨迹分析明细_宜昌_凯祥达.xls", 4, 5, 1500),
    Profile("minkun", "宜昌", "湖北民坤建筑工程有限公司", r"宜昌\宜昌民坤建筑工程有限公司9月台账.xlsx", "9月 ", "minkun", "MONTHLY_ROUTE", r"work\宜昌\车辆轨迹分析明细_宜昌_民坤.xls", 2, 4, 200),
]
 
 
@dataclass
class LedgerRow:
    city: str
    enterprise: str
    plate: str
    plate_no_raw: str = ""
    trailer_plate_no: str = ""
    route: str = ""
    cargo_type: str = ""
    cargo_tons: Optional[float] = None
    trips: Optional[float] = None
    mileage_per_trip: Optional[float] = None
    total_mileage: Optional[float] = None
    freight: Optional[float] = None
    turnover: Optional[float] = None
    transport_date: Optional[date] = None
    ledger_type: str = ""
    source_file: str = ""
    source_path_hash: str = ""
    source_sha256: str = ""
    sheet_name: str = ""
    row_no: int = 0
    block_no: int = 1
 
 
@dataclass
class TrackDailyRow:
    city: str
    enterprise: str
    plate: str
    track_date: Optional[date]
    agency: str = ""
    label: str = ""
    operator: str = ""
    point_count: int = 0
    complete_mileage: float = 0.0
    abnormal_mileage: float = 0.0
    total_mileage: float = 0.0
    drift_count: int = 0
    anomaly_rate: Optional[float] = None
    route: str = ""
    trips: Optional[float] = None
    straight_distance: Optional[float] = None
    source_file: str = ""
    source_path_hash: str = ""
    source_sha256: str = ""
    source_row: int = 0
    plate_no_raw: str = ""
    track_text: str = ""
    approved_traction_tonnage: Optional[float] = None
    cargo_tons: Optional[float] = None
 
 
@dataclass
class RawSummary:
    file_count: int = 0
    point_count: int = 0
    days: set = field(default_factory=set)
    first_time: Optional[datetime] = None
    last_time: Optional[datetime] = None
    provinces: Counter = field(default_factory=Counter)
    prefectures: Counter = field(default_factory=Counter)
    counties: Counter = field(default_factory=Counter)
    companies: Counter = field(default_factory=Counter)
 
 
@dataclass
class SourceFile:
    city: str
    enterprise: str
    source_type: str
    path: str
    sha256: str
    size: int
    sheet_name: str = ""
    source_rows: int = 0
    status: str = "IMPORTED"
    error: str = ""
    path_hash: str = ""
 
 
class SheetView:
    def __init__(self, workbook: Any, kind: str, sheet_name: str, row_limit: int = 2000):
        self.kind = kind
        self.workbook = workbook
        self.obj = workbook[sheet_name] if kind == "xlsx" else workbook.sheet_by_name(sheet_name)
        if kind == "xlsx":
            self.max_row = min(int(self.obj.max_row), max(row_limit, 1))
            self.max_col = min(int(self.obj.max_column), 64)
            self._rows = list(self.obj.iter_rows(min_row=1, max_row=self.max_row,
                                                 max_col=self.max_col, values_only=True))
        else:
            self.max_row = int(self.obj.nrows)
            self.max_col = int(self.obj.ncols)
            self._rows = None
 
    def cell(self, row: int, col: int) -> Any:
        if row < 1 or col < 1 or row > self.max_row or col > self.max_col:
            return None
        if self.kind == "xlsx":
            values = self._rows[row - 1]
            return values[col - 1] if col <= len(values) else None
        return self.obj.cell_value(row - 1, col - 1)
 
 
def normalize_plate_text(value: Any) -> str:
    if value is None:
        return ""
    return str(value).strip().upper().replace(" ", "").replace("\u3000", "")
 
 
def canonical_plate(value: Any) -> str:
    value_text = normalize_plate_text(value).split("/")[0]
    match = PLATE_RE.search(value_text)
    return match.group(0) if match else ""
 
 
def trailer_plate(value: Any) -> str:
    match = TRAILER_PLATE_RE.search(normalize_plate_text(value))
    return match.group(0) if match else ""
 
 
def to_float(value: Any) -> Optional[float]:
    if value is None:
        return None
    if isinstance(value, bool):
        return float(value)
    if isinstance(value, (int, float, Decimal)):
        if isinstance(value, float) and (math.isnan(value) or math.isinf(value)):
            return None
        return float(value)
    value_text = str(value).strip().replace(",", "")
    if not value_text or value_text in {"-", "", "/", "nan", "None", "#DIV/0!"}:
        return None
    if value_text.endswith("%"):
        try:
            return float(value_text[:-1]) / 100.0
        except ValueError:
            return None
    try:
        return float(value_text)
    except ValueError:
        return None
 
 
def to_date(value: Any, default_year: int = 2026) -> Optional[date]:
    if value is None or value == "":
        return None
    if isinstance(value, datetime):
        return value.date()
    if isinstance(value, date):
        return value
    if isinstance(value, (int, float)):
        try:
            return xlrd.xldate_as_datetime(float(value), 0).date()
        except Exception:
            return None
    value_text = str(value).strip()
    if not value_text:
        return None
    for fmt in ("%Y-%m-%d", "%Y/%m/%d", "%Y.%m.%d", "%Y-%m-%d %H:%M:%S"):
        try:
            return datetime.strptime(value_text, fmt).date()
        except ValueError:
            pass
    match = re.match(r"^(\d{1,2})[.\-/](\d{1,2})$", value_text)
    if match:
        try:
            return date(default_year, int(match.group(1)), int(match.group(2)))
        except ValueError:
            return None
    return None
 
 
def parse_datetime_text(value: Any) -> Optional[datetime]:
    if value is None:
        return None
    if isinstance(value, datetime):
        return value
    value_text = str(value).strip()
    match = DATE_TIME_RE.search(value_text)
    if match:
        return datetime(2000 + int(match.group(1)), int(match.group(2)), int(match.group(3)), int(match.group(4)), int(match.group(5)), int(match.group(6)))
    for fmt in ("%Y-%m-%d %H:%M:%S", "%Y/%m/%d %H:%M:%S"):
        try:
            return datetime.strptime(value_text, fmt)
        except ValueError:
            pass
    return None
 
 
def text(value: Any) -> str:
    return "" if value is None else str(value).strip()
 
 
def number(value: Any, default: float = 0.0) -> float:
    parsed = to_float(value)
    return default if parsed is None else parsed
 
 
def safe_div(numerator: Optional[float], denominator: Optional[float]) -> Optional[float]:
    if numerator is None or denominator in (None, 0):
        return None
    return float(numerator) / float(denominator)
 
 
def ratio_diff(numerator: Optional[float], denominator: Optional[float]) -> Optional[float]:
    ratio = safe_div(numerator, denominator)
    return None if ratio is None else ratio - 1.0
 
 
def sha256_file(path: Path) -> str:
    digest = hashlib.sha256()
    with path.open("rb") as handle:
        for chunk in iter(lambda: handle.read(1024 * 1024), b""):
            digest.update(chunk)
    return digest.hexdigest()
 
 
def sha256_text(value: str) -> str:
    return hashlib.sha256(value.encode("utf-8")).hexdigest()
 
 
def source_path_hash(path: Path) -> str:
    return sha256_text(str(path.resolve()).casefold())
 
 
def load_source(profile: Profile, source_root: Path) -> Tuple[Any, str]:
    path = source_root / profile.ledger_file
    if path.suffix.lower() == ".xlsx":
        return load_workbook(path, read_only=True, data_only=True), "xlsx"
    return xlrd.open_workbook(str(path), on_demand=True), "xls"
 
 
def make_ledger_row(profile: Profile, values: Dict[str, Any], source_hash: str,
                    path_hash: str, source_path: Path, sheet: str, row: int,
                    block: int = 1) -> Optional[LedgerRow]:
    plate = canonical_plate(values.get("plate"))
    if not plate:
        return None
    plate_no_raw = text(values.get("plate_raw")).strip() or text(values.get("plate")).strip()
    cargo_tons = to_float(values.get("cargo_tons"))
    trips = to_float(values.get("trips"))
    mileage_per_trip = to_float(values.get("mileage_per_trip"))
    total_mileage = to_float(values.get("total_mileage"))
    freight = to_float(values.get("freight"))
    turnover = to_float(values.get("turnover"))
    if total_mileage is None and mileage_per_trip is not None and trips is not None:
        total_mileage = mileage_per_trip * trips
    if freight is None and cargo_tons is not None and trips is not None:
        freight = cargo_tons * trips
    if turnover is None and freight is not None and mileage_per_trip is not None:
        turnover = freight * mileage_per_trip
    if all(v is None for v in (trips, total_mileage, freight, turnover)):
        return None
    return LedgerRow(
        city=profile.city, enterprise=profile.enterprise, plate=plate,
        plate_no_raw=plate_no_raw, trailer_plate_no=trailer_plate(plate_no_raw),
        route=text(values.get("route")), cargo_type=text(values.get("cargo_type")),
        cargo_tons=cargo_tons, trips=trips, mileage_per_trip=mileage_per_trip,
        total_mileage=total_mileage, freight=freight, turnover=turnover,
        transport_date=values.get("transport_date"), ledger_type=profile.ledger_type,
        source_file=str(source_path), source_path_hash=path_hash,
        source_sha256=source_hash, sheet_name=sheet, row_no=row, block_no=block,
    )
 
 
def parse_ledger(profile: Profile, source_root: Path) -> Tuple[List[LedgerRow], SourceFile]:
    path = source_root / profile.ledger_file
    digest = sha256_file(path)
    path_hash = source_path_hash(path)
    workbook, kind = load_source(profile, source_root)
    rows: List[LedgerRow] = []
    try:
        sheet_names = [profile.ledger_sheet]
        if profile.ledger_parser == "kaiying":
            sheet_names = ["危货", "普货"]
        for sheet_name in sheet_names:
            sheet = SheetView(workbook, kind, sheet_name, profile.max_scan_rows)
            if profile.ledger_parser == "anxin":
                limit = min(sheet.max_row, profile.max_scan_rows)
                for r in range(profile.first_data_row, limit + 1):
                    for base, block in ((1, 1), (12, 2)):
                        values = {
                            "plate": sheet.cell(r, base + 1), "route": sheet.cell(r, base + 3),
                            "mileage_per_trip": sheet.cell(r, base + 4), "trips": sheet.cell(r, base + 5),
                            "cargo_tons": sheet.cell(r, base + 6), "freight": sheet.cell(r, base + 8),
                            "turnover": sheet.cell(r, base + 9), "cargo_type": sheet.cell(r, base + 10),
                        }
                        item = make_ledger_row(profile, values, digest, path_hash, path, sheet_name, r, block)
                        if item:
                            rows.append(item)
                continue
 
            last_plate = ""
            last_plate_raw = ""
            last_route = ""
            blank_streak = 0
            limit = min(sheet.max_row, profile.max_scan_rows)
            for r in range(profile.first_data_row, limit + 1):
                if profile.ledger_parser in {"demin", "luchang", "guangfa", "datong", "xindafei", "shengda", "kaixiangda"}:
                    raw_plate = sheet.cell(r, 2)
                elif profile.ledger_parser == "heyun":
                    raw_plate = sheet.cell(r, 4)
                else:
                    raw_plate = sheet.cell(r, 1)
                explicit_plate = canonical_plate(raw_plate)
                raw_plate_text = text(raw_plate).strip()
                plate = explicit_plate
                if explicit_plate:
                    last_plate = explicit_plate
                    last_plate_raw = raw_plate_text
                elif profile.ledger_parser in {"demin", "guangfa"}:
                    plate = last_plate
 
                values: Dict[str, Any] = {}
                if profile.ledger_parser == "demin":
                    route = "-".join(x for x in (text(sheet.cell(r, 4)), text(sheet.cell(r, 5))) if x)
                    values = {"plate": plate, "route": route, "cargo_tons": sheet.cell(r, 6),
                              "trips": sheet.cell(r, 7), "freight": sheet.cell(r, 8),
                              "mileage_per_trip": sheet.cell(r, 9), "turnover": sheet.cell(r, 10)}
                elif profile.ledger_parser == "huinong":
                    values = {"plate": sheet.cell(r, 2), "route": sheet.cell(r, 5),
                              "mileage_per_trip": sheet.cell(r, 6), "trips": sheet.cell(r, 7),
                              "cargo_tons": sheet.cell(r, 9), "freight": sheet.cell(r, 9),
                              "turnover": sheet.cell(r, 10), "cargo_type": sheet.cell(r, 11)}
                elif profile.ledger_parser == "luchang":
                    route = "-".join(x for x in (text(sheet.cell(r, 5)), text(sheet.cell(r, 6))) if x)
                    values = {"plate": plate, "route": route, "cargo_tons": sheet.cell(r, 7),
                              "trips": sheet.cell(r, 8), "freight": sheet.cell(r, 9),
                              "mileage_per_trip": sheet.cell(r, 10), "turnover": sheet.cell(r, 11)}
                elif profile.ledger_parser in {"guangfa", "datong"}:
                    raw_route = text(sheet.cell(r, 5))
                    if raw_route:
                        last_route = raw_route
                    values = {"plate": plate, "route": last_route, "cargo_type": sheet.cell(r, 6),
                              "cargo_tons": sheet.cell(r, 7), "trips": sheet.cell(r, 8),
                              "freight": sheet.cell(r, 9), "mileage_per_trip": sheet.cell(r, 10),
                              "total_mileage": sheet.cell(r, 11), "turnover": sheet.cell(r, 12)}
                elif profile.ledger_parser == "kaiying":
                    values = {"plate": sheet.cell(r, 1), "transport_date": to_date(sheet.cell(r, 3)),
                              "route": sheet.cell(r, 4), "cargo_type": sheet.cell(r, 5),
                              "cargo_tons": sheet.cell(r, 6), "trips": 1, "freight": sheet.cell(r, 6),
                              "mileage_per_trip": sheet.cell(r, 7), "turnover": sheet.cell(r, 8)}
                elif profile.ledger_parser == "xindafei":
                    trips = to_float(sheet.cell(r, 7))
                    freight = to_float(sheet.cell(r, 8))
                    values = {"plate": plate, "route": sheet.cell(r, 5), "cargo_type": sheet.cell(r, 6),
                              "cargo_tons": safe_div(freight, trips), "trips": trips, "freight": freight,
                              "mileage_per_trip": sheet.cell(r, 9), "total_mileage": sheet.cell(r, 11),
                              "turnover": sheet.cell(r, 10)}
                elif profile.ledger_parser == "shengda":
                    values = {"plate": plate, "transport_date": to_date(sheet.cell(r, 1)),
                              "route": sheet.cell(r, 4), "cargo_type": sheet.cell(r, 5),
                              "cargo_tons": sheet.cell(r, 6), "trips": sheet.cell(r, 7),
                              "freight": sheet.cell(r, 8), "mileage_per_trip": sheet.cell(r, 9),
                              "total_mileage": sheet.cell(r, 10), "turnover": sheet.cell(r, 11)}
                elif profile.ledger_parser == "heyun":
                    route = "-".join(x for x in (text(sheet.cell(r, 6)), text(sheet.cell(r, 7))) if x)
                    volume = to_float(sheet.cell(r, 8))
                    trips = to_float(sheet.cell(r, 9))
                    try:
                        transport_date = date(2026, int(number(sheet.cell(r, 2), 9)), int(number(sheet.cell(r, 3), 1)))
                    except ValueError:
                        transport_date = None
                    values = {"plate": plate, "transport_date": transport_date, "route": route,
                              "cargo_type": sheet.cell(r, 5), "cargo_tons": volume, "trips": trips,
                              "freight": (volume or 0.0) * (trips or 0.0),
                              "mileage_per_trip": sheet.cell(r, 10), "turnover": sheet.cell(r, 11)}
                elif profile.ledger_parser == "kaixiangda":
                    values = {"plate": plate, "transport_date": to_date(sheet.cell(r, 1)),
                              "route": sheet.cell(r, 5), "cargo_type": sheet.cell(r, 6),
                              "cargo_tons": sheet.cell(r, 7), "trips": 1, "freight": sheet.cell(r, 7),
                              "mileage_per_trip": sheet.cell(r, 8), "turnover": sheet.cell(r, 9)}
                elif profile.ledger_parser == "minkun":
                    values = {"plate": plate, "route": sheet.cell(r, 4), "cargo_type": sheet.cell(r, 5),
                              "cargo_tons": sheet.cell(r, 6), "trips": sheet.cell(r, 7),
                              "freight": sheet.cell(r, 8), "mileage_per_trip": sheet.cell(r, 9),
                              "total_mileage": sheet.cell(r, 10), "turnover": sheet.cell(r, 11)}
                else:
                    raise ValueError("Unsupported ledger parser: " + profile.ledger_parser)
 
                values["plate_raw"] = raw_plate_text if explicit_plate else last_plate_raw
                if not explicit_plate:
                    if profile.ledger_parser == "demin" and not text(values.get("route")):
                        continue
                    if profile.ledger_parser == "guangfa" and not text(values.get("cargo_type")):
                        continue
 
                item = make_ledger_row(profile, values, digest, path_hash, path, sheet_name, r, 1)
                if item:
                    rows.append(item)
                    blank_streak = 0
                else:
                    blank_streak += 1
                if profile.ledger_parser in {"guangfa", "datong", "kaiying"} and blank_streak >= 20:
                    break
    finally:
        if kind == "xlsx":
            workbook.close()
        else:
            workbook.release_resources()
    source = SourceFile(profile.city, profile.enterprise, "LEDGER", str(path), digest,
                        path.stat().st_size, ",".join(sheet_names), len(rows),
                        path_hash=path_hash)
    return rows, source
 
 
def parse_track_summary(profile: Profile, work_root: Path) -> Tuple[List[TrackDailyRow], SourceFile]:
    path = work_root / profile.track_file
    if not path.exists():
        matches = [candidate for candidate in work_root.rglob(Path(profile.track_file).name) if "备份" not in candidate.parts]
        if not matches:
            raise FileNotFoundError(str(path))
        path = sorted(matches, key=lambda item: str(item))[0]
    digest = sha256_file(path)
    path_hash = source_path_hash(path)
    workbook = xlrd.open_workbook(str(path), on_demand=True)
    rows: List[TrackDailyRow] = []
    try:
        sheet = workbook.sheet_by_index(0)
        headers = [text(sheet.cell_value(0, c)) for c in range(sheet.ncols)]
        idx = {name: i for i, name in enumerate(headers)}
 
        def cell_value(row_index: int, name: str, fallback: int) -> Any:
            column = idx.get(name, fallback)
            if column < 0 or column >= sheet.ncols:
                return None
            return sheet.cell_value(row_index, column)
 
        for r in range(1, sheet.nrows):
            plate_raw = text(cell_value(r, "车辆牌照号", 2))
            plate = canonical_plate(plate_raw)
            if not plate:
                continue
            route_value = cell_value(r, "路线", 14)
            trips_value = cell_value(r, "趟数", 15)
            distance_value = cell_value(r, "直线距离(km)", 16)
            rows.append(TrackDailyRow(
                city=profile.city, enterprise=profile.enterprise, plate=plate,
                track_date=to_date(cell_value(r, "日期", 3)),
                agency=text(cell_value(r, "管辖机构", 0)),
                label=text(cell_value(r, "车辆标签", 4)),
                operator=text(cell_value(r, "运营商", 5)),
                point_count=int(number(cell_value(r, "定位数", 6))),
                complete_mileage=number(cell_value(r, "完整里程(公里)", 7)),
                abnormal_mileage=number(cell_value(r, "异常里程(公里)", 8)),
                total_mileage=number(cell_value(r, "总里程(公里)", 9)),
                drift_count=int(number(cell_value(r, "漂移数", 10))),
                anomaly_rate=to_float(cell_value(r, "异常率", 11)),
                route=text(route_value), trips=to_float(trips_value), straight_distance=to_float(distance_value),
                source_file=str(path), source_path_hash=path_hash, source_sha256=digest,
                source_row=r + 1, plate_no_raw=plate_raw,
                track_text=text(cell_value(r, "轨迹", 12)),
                approved_traction_tonnage=to_float(cell_value(r, "准牵引车核定载质量(吨)", 13)),
                cargo_tons=to_float(cell_value(r, "运货吨数", 17)),
            ))
    finally:
        workbook.release_resources()
    source = SourceFile(profile.city, profile.enterprise, "TRACK_SUMMARY", str(path), digest,
                        path.stat().st_size, "车辆轨迹分析明细", len(rows),
                        path_hash=path_hash)
    return rows, source
 
def split_location(value: Any) -> Tuple[str, str, str]:
    raw = text(value)
    if not raw:
        return "", "", ""
    parts = [p.strip() for p in re.split(r"[,,/]", raw) if p.strip()]
    province = parts[0] if parts else ""
    prefecture = parts[1] if len(parts) > 1 else ""
    county = parts[2] if len(parts) > 2 else ""
    return province, prefecture, county
 
 
def read_manifest(path: Path) -> List[Dict[str, str]]:
    with path.open("r", encoding="utf-8-sig", newline="") as handle:
        return list(csv.DictReader(handle, delimiter="\t"))
 
 
def parse_raw_points(manifest_path: Path, profiles: Sequence[Profile], work_root: Path) -> Tuple[List[Tuple[Any, ...]], Dict[Tuple[str, str], RawSummary], List[SourceFile]]:
    city_by_enterprise = {p.enterprise: p.city for p in profiles}
    point_rows: List[Tuple[Any, ...]] = []
    summaries: Dict[Tuple[str, str], RawSummary] = defaultdict(RawSummary)
    source_files: List[SourceFile] = []
    for entry in read_manifest(manifest_path):
        source_path = Path(entry["source_path"])
        if not source_path.exists():
            matches = [candidate for candidate in work_root.rglob("*")
                       if candidate.is_file() and candidate.name == source_path.name and "备份" not in candidate.parts]
            if not matches:
                continue
            source_path = sorted(matches, key=lambda item: str(item))[0]
        output_path = Path(entry["output_path"])
        if not output_path.exists():
            continue
        digest = sha256_file(source_path)
        path_hash = source_path_hash(source_path)
        workbook = load_workbook(output_path, read_only=True, data_only=True)
        try:
            sheet = workbook.worksheets[0]
            rows_iter = sheet.iter_rows(values_only=True)
            headers = [text(value) for value in next(rows_iter, ())]
            idx = {name: i for i, name in enumerate(headers) if name}
 
            def get(row_value: Tuple[Any, ...], name: str, fallback_index: int) -> Any:
                index = idx.get(name, fallback_index)
                return row_value[index] if index < len(row_value) else None
 
            file_company = ""
            row_count = 0
            for row_no, row_value in enumerate(rows_iter, start=2):
                company = text(get(row_value, "单位名称", 0))
                plate = canonical_plate(get(row_value, "车辆牌号", 1))
                if not plate:
                    continue
                if not file_company:
                    file_company = company
                city = city_by_enterprise.get(company, "")
                if not city:
                    parent = source_path.parent.name
                    city = parent if parent in {"咸宁", "黄冈", "宜昌"} else ""
                location = text(get(row_value, "当前地点", 10))
                province, prefecture, county = split_location(location)
                terminal_time = parse_datetime_text(get(row_value, "终端时间", 2))
                receive_time = parse_datetime_text(get(row_value, "接收时间", 3))
                point_rows.append((
                    city, company, plate, terminal_time, receive_time,
                    to_float(get(row_value, "定位经度", 4)),
                    to_float(get(row_value, "定位纬度", 5)),
                    text(get(row_value, "行驶速度", 6)),
                    text(get(row_value, "车辆状态", 7)),
                    text(get(row_value, "报警状态", 8)),
                    text(get(row_value, "运营商", 9)),
                    location, province, prefecture, county,
                    str(source_path), path_hash, digest, row_no,
                ))
                summary = summaries[(company, plate)]
                summary.point_count += 1
                if terminal_time:
                    summary.days.add(terminal_time.date())
                    if summary.first_time is None or terminal_time < summary.first_time:
                        summary.first_time = terminal_time
                    if summary.last_time is None or terminal_time > summary.last_time:
                        summary.last_time = terminal_time
                if province:
                    summary.provinces[province] += 1
                if prefecture:
                    summary.prefectures[prefecture] += 1
                if county:
                    summary.counties[county] += 1
                summary.companies[company] += 1
                row_count += 1
            if file_company:
                city = city_by_enterprise.get(file_company, "")
                source_files.append(SourceFile(
                    city, file_company, "TRACK_POINT", str(source_path), digest,
                    source_path.stat().st_size, sheet.title, row_count,
                    path_hash=path_hash,
                ))
        finally:
            workbook.close()
    for source in source_files:
        plate = canonical_plate(Path(source.path).name)
        key = (source.enterprise, plate)
        if key in summaries:
            summaries[key].file_count += 1
    return point_rows, summaries, source_files
 
 
def load_h2032(conn: pymysql.connections.Connection, period: str, names: Sequence[str]) -> Dict[str, Dict[str, Any]]:
    placeholders = ",".join(["%s"] * len(names))
    sql = ("SELECT id, enterprise_code, enterprise_name, vehicle_total, vehicle_tractor, "
           "freight_total, turnover_total FROM h2032_enterprise_monthly "
           "WHERE report_period=%s AND enterprise_name IN (" + placeholders + ")")
    with conn.cursor(pymysql.cursors.DictCursor) as cur:
        cur.execute(sql, [period] + list(names))
        rows = cur.fetchall()
    result = {row["enterprise_name"]: row for row in rows}
    missing = [name for name in names if name not in result]
    if missing:
        raise RuntimeError("Missing H2032 rows: " + ", ".join(missing))
    return result
 
 
def default_vehicle_registry_path(source_root: Path, period: str) -> Path:
    year, month = period.split("-")
    return (source_root.parents[2] / "101_运政车辆信息" / year / f"{int(month)}月"
            / "01.规上企业车辆数查询—黄何.xls")
 
 
def load_vehicle_registry(path: Path, names: Sequence[str]) -> Dict[str, VehicleRegistryCounts]:
    if not path.is_file():
        raise RuntimeError(f"Missing transport authority vehicle file: {path}")
    workbook = xlrd.open_workbook(str(path), on_demand=True)
    try:
        sheet = workbook.sheet_by_index(0)
        header_row = -1
        header_map: Dict[str, int] = {}
        aliases = {
            "企业名称": "enterprise",
            "总牵引车数": "tractor",
            "总挂车数": "trailer",
            "其它车辆数": "other",
            "其他车辆数": "other",
        }
        for row_no in range(min(sheet.nrows, 50)):
            current = {
                aliases[re.sub(r"\s+", "", text(sheet.cell_value(row_no, col)))]: col
                for col in range(sheet.ncols)
                if re.sub(r"\s+", "", text(sheet.cell_value(row_no, col))) in aliases
            }
            if all(key in current for key in ("enterprise", "tractor", "trailer", "other")):
                header_row = row_no
                header_map = current
                break
        if header_row < 0:
            raise RuntimeError(f"Cannot locate vehicle registry headers in {path}")
 
        result: Dict[str, VehicleRegistryCounts] = {}
        for row_no in range(header_row + 1, sheet.nrows):
            enterprise = text(sheet.cell_value(row_no, header_map["enterprise"])).strip()
            if not enterprise:
                continue
            tractor = int(round(number(sheet.cell_value(row_no, header_map["tractor"]))))
            trailer = int(round(number(sheet.cell_value(row_no, header_map["trailer"]))))
            other = int(round(number(sheet.cell_value(row_no, header_map["other"]))))
            if enterprise in result:
                raise RuntimeError(f"Duplicate enterprise in vehicle registry: {enterprise}")
            result[enterprise] = VehicleRegistryCounts(
                total=tractor + trailer + other,
                main=tractor + other,
                tractor=tractor,
                trailer=trailer,
                other=other,
            )
    finally:
        workbook.release_resources()
 
    missing = [name for name in names if name not in result]
    if missing:
        raise RuntimeError("Missing transport authority vehicle rows: " + ", ".join(missing))
    return result
 
 
def aggregate_ledger(rows: Sequence[LedgerRow]) -> Tuple[Dict[str, Dict[str, Any]], Dict[str, Any]]:
    vehicles: Dict[str, Dict[str, Any]] = {}
    for row in rows:
        item = vehicles.setdefault(row.plate, {
            "routes": 0, "trips": 0.0, "freight": 0.0, "turnover": 0.0,
            "mileage": 0.0, "route_texts": [], "raw_route_rows": [],
        })
        item["routes"] += 1
        item["trips"] += number(row.trips)
        item["freight"] += number(row.freight)
        item["turnover"] += number(row.turnover)
        item["mileage"] += number(row.total_mileage)
        if row.route:
            item["route_texts"].append(row.route)
        item["raw_route_rows"].append(row)
    total = {
        "routes": len(rows), "vehicles": len(vehicles),
        "trips": sum(v["trips"] for v in vehicles.values()),
        "freight": sum(v["freight"] for v in vehicles.values()),
        "turnover": sum(v["turnover"] for v in vehicles.values()),
        "mileage": sum(v["mileage"] for v in vehicles.values()),
    }
    return vehicles, total
 
 
def aggregate_tracks(rows: Sequence[TrackDailyRow]) -> Dict[str, Dict[str, Any]]:
    vehicles: Dict[str, Dict[str, Any]] = {}
    for row in rows:
        item = vehicles.setdefault(row.plate, {
            "days": set(), "point_count": 0, "complete_mileage": 0.0,
            "abnormal_mileage": 0.0, "total_mileage": 0.0, "daily_rows": [],
        })
        if row.track_date:
            item["days"].add(row.track_date)
        item["point_count"] += row.point_count
        item["complete_mileage"] += row.complete_mileage
        item["abnormal_mileage"] += row.abnormal_mileage
        item["total_mileage"] += row.total_mileage
        item["daily_rows"].append(row)
    for item in vehicles.values():
        item["anomaly_rate"] = safe_div(item["abnormal_mileage"], item["total_mileage"])
    return vehicles
 
def pct_text(value: Optional[float]) -> str:
    return "无有效基准" if value is None else f"{value * 100:.2f}%"
 
 
def fmt_num(value: Optional[float], digits: int = 2) -> str:
    return "无" if value is None else f"{value:,.{digits}f}"
 
 
def assess_enterprise(item: Dict[str, Any], raw_summary: RawSummary) -> Tuple[str, str, str]:
    report = item["report"]
    ledger = item["ledger_total"]
    matched = len(item["matched"])
    tracked = item["active_track_vehicles"]
    report_ledger = ratio_diff(report["turnover_total"], ledger["turnover"])
    report_track = ratio_diff(report["turnover_total"], item["normalized_track"])
    mileage_cov = safe_div(item["track_mileage"], ledger["mileage"])
    route_note = ""
    if raw_summary.point_count > 0:
        top_cities = "、".join(name for name, _ in raw_summary.prefectures.most_common(3))
        route_note = f"已下载具体轨迹点{raw_summary.point_count:,}个,覆盖{len(raw_summary.days)}天,主要活动地为{top_cities or '未知'}。"
    parts = [
        f"月报周转量{fmt_num(report['turnover_total'])},台账周转量{fmt_num(ledger['turnover'])},差异率{pct_text(report_ledger)}。",
        f"平台轨迹匹配{matched}辆(台账{ledger['vehicles']}辆),监测里程{fmt_num(item['track_mileage'])}公里,占台账里程{pct_text(mileage_cov)}。",
        f"按台账吨位与线路结构折算的企业周转量为{fmt_num(item['normalized_track'])},月报与其差异率{pct_text(report_track)}。",
        route_note,
    ]
    conclusion = "".join(part for part in parts if part)
    severity = "低"
    if matched == 0 or tracked == 0:
        severity = "高"
        conclusion = "平台逐日轨迹与台账车辆未形成有效匹配,当前无法用轨迹核验企业周转量。" + conclusion
    elif mileage_cov is not None and mileage_cov < 0.3:
        severity = "高"
        conclusion += " 轨迹覆盖明显不足,不能据此支持企业全月申报规模。"
    elif report_ledger is not None and abs(report_ledger) >= 0.5:
        severity = "高"
        conclusion += " 月报与台账周转量差异超过50%,应优先核查。"
    elif report_track is not None and abs(report_track) >= 0.5:
        severity = "高"
        conclusion += " 月报与轨迹折算周转量差异超过50%,应优先核查。"
    elif (report_ledger is not None and abs(report_ledger) >= 0.3) or (report_track is not None and abs(report_track) >= 0.3):
        severity = "中"
        conclusion += " 差异超过30%,建议补充线路和装卸凭证。"
    else:
        conclusion += " 当前差异未超过30%阈值,仍需人工抽查原始凭证。"
    suggestion = "核对车辆清单、运输趟次、线路里程和载重凭据;对轨迹覆盖低的车辆补充下载全月轨迹后再复算。"
    return severity, conclusion, suggestion
 
 
def build_analysis(conn: pymysql.connections.Connection, profiles: Sequence[Profile], period: str,
                   source_root: Path, work_root: Path, raw_manifest: Path) -> Dict[str, Any]:
    h2032 = load_h2032(conn, period, [p.enterprise for p in profiles])
    point_rows, raw_summaries, raw_sources = parse_raw_points(raw_manifest, profiles, work_root)
    enterprises: Dict[str, Dict[str, Any]] = {}
    all_ledger_rows: List[LedgerRow] = []
    all_track_rows: List[TrackDailyRow] = []
    source_files: List[SourceFile] = []
    for profile in profiles:
        ledger_rows, ledger_source = parse_ledger(profile, source_root)
        track_rows, track_source = parse_track_summary(profile, work_root)
        ledger_vehicles, ledger_total = aggregate_ledger(ledger_rows)
        track_vehicles = aggregate_tracks(track_rows)
        report = h2032[profile.enterprise]
        matched = sorted(set(ledger_vehicles) & {p for p, item in track_vehicles.items() if item["total_mileage"] > 0})
        matched_ledger_turnover = sum(ledger_vehicles[p]["turnover"] for p in matched)
        track_estimated = sum(
            track_vehicles[p]["total_mileage"] * safe_div(ledger_vehicles[p]["turnover"], ledger_vehicles[p]["mileage"])
            for p in matched if ledger_vehicles[p]["mileage"] > 0
        )
        normalized = track_estimated * ledger_total["turnover"] / matched_ledger_turnover if matched_ledger_turnover > 0 else None
        track_mileage = sum(item["total_mileage"] for item in track_vehicles.values())
        track_complete = sum(item["complete_mileage"] for item in track_vehicles.values())
        track_abnormal = sum(item["abnormal_mileage"] for item in track_vehicles.values())
        track_days = sum(len(item["days"]) for item in track_vehicles.values())
        active_track_vehicles = sum(1 for item in track_vehicles.values() if item["total_mileage"] > 0)
        raw_for_enterprise = [summary for (company, _), summary in raw_summaries.items() if company == profile.enterprise]
        raw_point_count = sum(summary.point_count for summary in raw_for_enterprise)
        raw_file_count = sum(summary.file_count for summary in raw_for_enterprise)
        raw_vehicle_count = sum(1 for summary in raw_for_enterprise if summary.point_count > 0)
        item = {
            "profile": profile, "report": report, "ledger_rows": ledger_rows, "track_rows": track_rows,
            "ledger_vehicles": ledger_vehicles, "ledger_total": ledger_total,
            "track_vehicles": track_vehicles, "matched": matched,
            "matched_ledger_turnover": matched_ledger_turnover, "track_estimated": track_estimated,
            "normalized_track": normalized, "track_mileage": track_mileage,
            "track_complete": track_complete, "track_abnormal": track_abnormal,
            "track_days": track_days, "active_track_vehicles": active_track_vehicles,
            "track_day_coverage": safe_div(track_days, active_track_vehicles * 30) if active_track_vehicles else None,
            "raw_track_vehicle_count": raw_vehicle_count, "raw_track_file_count": raw_file_count,
            "raw_track_point_count": raw_point_count,
            "report_vs_ledger_rate": ratio_diff(report["turnover_total"], ledger_total["turnover"]),
            "report_vs_track_rate": ratio_diff(report["turnover_total"], normalized),
            "mileage_diff_rate": ratio_diff(ledger_total["mileage"], track_mileage),
        }
        raw_combined = RawSummary()
        for summary in raw_for_enterprise:
            raw_combined.point_count += summary.point_count
            raw_combined.file_count += summary.file_count
            raw_combined.days.update(summary.days)
            raw_combined.prefectures.update(summary.prefectures)
            raw_combined.provinces.update(summary.provinces)
            raw_combined.counties.update(summary.counties)
        item["severity"], item["conclusion"], item["suggestion"] = assess_enterprise(item, raw_combined)
        enterprises[profile.enterprise] = item
        all_ledger_rows.extend(ledger_rows)
        all_track_rows.extend(track_rows)
        source_files.extend([ledger_source, track_source])
    source_files.extend(raw_sources)
    return {
        "period": period, "h2032": h2032, "enterprises": enterprises,
        "ledger_rows": all_ledger_rows, "track_rows": all_track_rows,
        "source_files": source_files, "raw_summaries": raw_summaries, "point_rows": point_rows,
    }
 
 
 
def _style_header_row(sheet: Any, row: int, column_count: int) -> None:
    fill = PatternFill("solid", fgColor="1F4E78")
    font = Font(color="FFFFFF", bold=True, size=10)
    border = Border(bottom=Side(style="thin", color="A6A6A6"))
    for col in range(1, column_count + 1):
        cell = sheet.cell(row, col)
        cell.fill = fill
        cell.font = font
        cell.alignment = Alignment(horizontal="center", vertical="center", wrap_text=True)
        cell.border = border
    sheet.row_dimensions[row].height = 34
 
 
def _style_data_sheet(sheet: Any, header_row: int, last_row: int, column_count: int) -> None:
    thin = Side(style="thin", color="D9E2F3")
    for row in range(header_row + 1, last_row + 1):
        for col in range(1, column_count + 1):
            cell = sheet.cell(row, col)
            cell.border = Border(left=thin, right=thin, top=thin, bottom=thin)
            cell.alignment = Alignment(vertical="center", wrap_text=(col == 2))
            if row % 2 == 0:
                cell.fill = PatternFill("solid", fgColor="F5F8FC")
    sheet.freeze_panes = sheet.cell(header_row + 1, 1)
    sheet.auto_filter.ref = f"A{header_row}:{get_column_letter(column_count)}{last_row}"
 
 
def _format_overview_sheet(sheet: Any, last_row: int) -> None:
    _style_header_row(sheet, 3, 18)
    _style_data_sheet(sheet, 3, last_row, 18)
    widths = [9, 31, 11, 10, 15, 16, 11, 15, 16, 15, 15, 20, 16, 18, 18, 13, 15, 22]
    for index, width in enumerate(widths, start=1):
        sheet.column_dimensions[get_column_letter(index)].width = width
    for row in range(4, last_row + 1):
        sheet.row_dimensions[row].height = 42
        for col in (3, 4, 7, 16):
            sheet.cell(row, col).number_format = "#,##0"
        for col in (5, 6, 8, 9, 13, 14):
            sheet.cell(row, col).number_format = "#,##0.00"
        for col in (10, 11, 15, 17):
            sheet.cell(row, col).number_format = "0.00%"
 
        first_rate = sheet.cell(row, 11).value
        if isinstance(first_rate, (int, float)):
            if abs(first_rate) > 0.05:
                first_color = "C00000"
            elif abs(first_rate) > 0.01:
                first_color = "BF9000"
            else:
                first_color = "006100"
        else:
            first_color = "808080"
        sheet.cell(row, 12).font = Font(color=first_color, bold=True)
        sheet.cell(row, 12).alignment = Alignment(horizontal="center", vertical="center", wrap_text=True)
 
        mileage_rate = sheet.cell(row, 15).value
        if isinstance(mileage_rate, (int, float)):
            second_color = "006100" if abs(mileage_rate) <= 0.30 else "C00000"
        else:
            second_color = "808080"
        sheet.cell(row, 18).font = Font(color=second_color, bold=True)
        sheet.cell(row, 18).alignment = Alignment(horizontal="center", vertical="center", wrap_text=True)
 
 
def _format_vehicle_sheet(sheet: Any, last_row: int) -> None:
    _style_header_row(sheet, 3, 12)
    _style_data_sheet(sheet, 3, last_row, 12)
    widths = [9, 31, 13, 12, 18, 18, 14, 12, 16, 12, 18, 20]
    for index, width in enumerate(widths, start=1):
        sheet.column_dimensions[get_column_letter(index)].width = width
    for row in range(4, last_row + 1):
        sheet.row_dimensions[row].height = 24
        for col in (4, 8):
            sheet.cell(row, col).number_format = "#,##0.00"
        for col in (5, 6, 9, 11):
            sheet.cell(row, col).number_format = "#,##0.00"
        for col in (7, 10):
            sheet.cell(row, col).number_format = "0.00%"
        rate = sheet.cell(row, 7).value
        if isinstance(rate, (int, float)):
            color = "C00000" if abs(rate) >= 1 else "BF9000" if abs(rate) >= 0.3 else "006100"
            sheet.cell(row, 7).font = Font(color=color, bold=abs(rate) >= 0.3)
 
 
def build_overview(conn: pymysql.connections.Connection, profiles: Sequence[Profile], period: str,
                   source_root: Path, auth_vehicle_file: Optional[Path] = None) -> Dict[str, Any]:
    h2032 = load_h2032(conn, period, [profile.enterprise for profile in profiles])
    registry_path = auth_vehicle_file or default_vehicle_registry_path(source_root, period)
    vehicle_registry = load_vehicle_registry(registry_path, [profile.enterprise for profile in profiles])
    enterprises: List[Dict[str, Any]] = []
    vehicles: List[Dict[str, Any]] = []
    for profile in profiles:
        ledger_rows, _ = parse_ledger(profile, source_root)
        track_rows, _ = parse_track_summary(profile, source_root)
        ledger_vehicles, ledger_total = aggregate_ledger(ledger_rows)
        track_vehicles = aggregate_tracks(track_rows)
        report = h2032[profile.enterprise]
        authority_vehicles = vehicle_registry[profile.enterprise]
        matched = sorted(set(ledger_vehicles) & {
            plate for plate, item in track_vehicles.items() if item["total_mileage"] > 0
        })
        track_mileage = sum(item["total_mileage"] for item in track_vehicles.values())
        track_complete = sum(item["complete_mileage"] for item in track_vehicles.values())
        track_abnormal = sum(item["abnormal_mileage"] for item in track_vehicles.values())
        converted_turnover = None
        if ledger_total["mileage"] > 0:
            converted_turnover = track_mileage * ledger_total["turnover"] / ledger_total["mileage"]
        item = {
            "city": profile.city,
            "enterprise": profile.enterprise,
            "report_vehicle_total": report["vehicle_total"],
            "report_tractor_count": report["vehicle_tractor"],
            "authority_vehicle_total": authority_vehicles.total,
            "authority_main_vehicle_count": authority_vehicles.main,
            "converted_turnover": converted_turnover,
            "report_freight": report["freight_total"],
            "report_turnover": report["turnover_total"],
            "report_vs_converted_rate": ratio_diff(report["turnover_total"], converted_turnover),
            "ledger_vehicle_count": ledger_total["vehicles"],
            "ledger_freight": ledger_total["freight"],
            "ledger_turnover": ledger_total["turnover"],
            "ledger_mileage": ledger_total["mileage"],
            "track_mileage": track_mileage,
            "ledger_vs_track_rate": ratio_diff(ledger_total["mileage"], track_mileage),
            "matched_vehicle_count": len(matched),
            "no_track_vehicle_count": ledger_total["vehicles"] - len(matched),
            "no_track_vehicle_ratio": safe_div(ledger_total["vehicles"] - len(matched), ledger_total["vehicles"]),
            "report_vs_ledger_rate": ratio_diff(report["turnover_total"], ledger_total["turnover"]),
            "report_vs_ledger_freight_rate": ratio_diff(report["freight_total"], ledger_total["freight"]),
            "track_complete_mileage": track_complete,
            "track_abnormal_mileage": track_abnormal,
        }
        ledger_rate = item["report_vs_ledger_rate"]
        if ledger_rate is None:
            item["layer1_status"] = "无法比较"
        elif abs(ledger_rate) <= 0.01:
            item["layer1_status"] = "一致(≤1%)"
        elif abs(ledger_rate) <= 0.05:
            item["layer1_status"] = "轻微差异(1%-5%)"
        else:
            item["layer1_status"] = "差异较大(>5%)"
        mileage_rate = item["ledger_vs_track_rate"]
        if mileage_rate is None:
            item["layer2_status"] = "无平台里程"
        elif abs(mileage_rate) <= 0.30:
            item["layer2_status"] = "正常(-30%~+30%)"
        else:
            item["layer2_status"] = "超出正常范围(<-30%或>30%)"
        notes = []
        if item["no_track_vehicle_count"] > 0:
            notes.append("存在无轨迹车辆")
        item["note"] = ";".join(notes)
        enterprises.append(item)
 
        for plate, ledger_item in ledger_vehicles.items():
            track_item = track_vehicles.get(plate)
            track_value = track_item["total_mileage"] if track_item and track_item["total_mileage"] > 0 else None
            anomaly_rate = None
            track_days = 0
            abnormal_mileage = None
            if track_item:
                track_days = len(track_item["days"])
                abnormal_mileage = track_item["abnormal_mileage"]
                anomaly_rate = track_item["anomaly_rate"]
            if track_value is None:
                match_status = "平台明细无匹配"
            elif profile.preferred_sample_plate == plate:
                match_status = "原抽查车辆"
            else:
                match_status = "已匹配"
            vehicles.append({
                "city": profile.city,
                "enterprise": profile.enterprise,
                "plate": plate,
                "ledger_trips": ledger_item["trips"],
                "ledger_mileage": ledger_item["mileage"],
                "track_mileage": track_value,
                "mileage_diff_rate": ratio_diff(ledger_item["mileage"], track_value),
                "track_days": track_days,
                "abnormal_mileage": abnormal_mileage,
                "anomaly_rate": anomaly_rate,
                "ledger_turnover": ledger_item["turnover"],
                "match_status": match_status,
            })
    vehicle_order = {profile.enterprise: index for index, profile in enumerate(profiles)}
    vehicles.sort(key=lambda row: (
        vehicle_order[row["enterprise"]],
        1 if row["mileage_diff_rate"] is None else 0,
        -abs(row["mileage_diff_rate"] or 0),
        row["plate"],
    ))
    return {
        "period": period,
        "enterprises": enterprises,
        "vehicles": vehicles,
        "vehicle_registry_file": str(registry_path),
    }
 
 
def write_overview_workbook(data: Dict[str, Any], output_path: Path) -> None:
    workbook = Workbook()
    overview = workbook.active
    overview.title = "总体情况"
    vehicle_sheet = workbook.create_sheet("车辆里程差异情况")
 
    title_fill = PatternFill("solid", fgColor="D9EAF7")
    title_font = Font(bold=True, size=14, color="17365D")
    for sheet, title, column_count in (
        (overview, f"{data['period']} 企业台账抽查总体情况(运政车辆口径)", 18),
        (vehicle_sheet, f"{data['period']} 车辆月度里程差异情况", 12),
    ):
        sheet.merge_cells(start_row=1, start_column=1, end_row=1, end_column=column_count)
        cell = sheet.cell(1, 1, title)
        cell.fill = title_fill
        cell.font = title_font
        cell.alignment = Alignment(horizontal="center", vertical="center")
        sheet.row_dimensions[1].height = 28
        sheet.sheet_view.showGridLines = False
 
    overview_headers = [
        "市州", "企业", "运政车辆数", "主车数", "月报货运量", "月报周转量",
        "台账车辆数", "台账货运量", "台账周转量",
        "月报/台账货运量差异率", "月报/台账周转量差异率", "第一层核查结论",
        "台账总里程", "平台监测总里程", "台账/平台里程差异率",
        "无轨迹车辆数", "无轨迹车辆占比", "第二层核查结论",
    ]
    for col, value in enumerate(overview_headers, start=1):
        overview.cell(3, col, value)
    for row_index, item in enumerate(data["enterprises"], start=4):
        second_layer = item["layer2_status"]
        if item["note"]:
            second_layer += ";" + item["note"]
        values = [
            item["city"], item["enterprise"], item["authority_vehicle_total"],
            item["authority_main_vehicle_count"], item["report_freight"], item["report_turnover"],
            item["ledger_vehicle_count"], item["ledger_freight"], item["ledger_turnover"],
            item["report_vs_ledger_freight_rate"], item["report_vs_ledger_rate"],
            item["layer1_status"], item["ledger_mileage"], item["track_mileage"],
            item["ledger_vs_track_rate"], item["no_track_vehicle_count"],
            item["no_track_vehicle_ratio"], second_layer,
        ]
        for col, value in enumerate(values, start=1):
            overview.cell(row_index, col, value)
 
    vehicle_headers = [
        "市州", "企业", "车牌号", "台账记录趟数", "台账总里程",
        "平台监测总里程", "里程差异率", "平台轨迹天数", "平台异常里程",
        "平台异常率", "台账周转量", "匹配状态",
    ]
    for col, value in enumerate(vehicle_headers, start=1):
        vehicle_sheet.cell(3, col, value)
    for row_index, item in enumerate(data["vehicles"], start=4):
        values = [
            item["city"], item["enterprise"], item["plate"], item["ledger_trips"],
            item["ledger_mileage"], item["track_mileage"], item["mileage_diff_rate"],
            item["track_days"], item["abnormal_mileage"], item["anomaly_rate"],
            item["ledger_turnover"], item["match_status"],
        ]
        for col, value in enumerate(values, start=1):
            vehicle_sheet.cell(row_index, col, value)
 
    overview_last = 3 + len(data["enterprises"])
    vehicle_last = 3 + len(data["vehicles"])
    _format_overview_sheet(overview, overview_last)
    _format_vehicle_sheet(vehicle_sheet, vehicle_last)
    overview.sheet_properties.pageSetUpPr.fitToPage = True
    overview.page_setup.orientation = "landscape"
    overview.page_setup.fitToWidth = 1
    overview.page_setup.fitToHeight = 0
    vehicle_sheet.sheet_properties.pageSetUpPr.fitToPage = True
    vehicle_sheet.page_setup.orientation = "landscape"
    vehicle_sheet.page_setup.fitToWidth = 1
    vehicle_sheet.page_setup.fitToHeight = 0
    output_path.parent.mkdir(parents=True, exist_ok=True)
    workbook.save(output_path)
 
 
def validate_analysis(data: Dict[str, Any]) -> None:
    expected = {
        "湖北安欣物流有限责任公司": (28, 64984.0, 7652452.0, 241046.0, 87433.40),
        "湖北省德敏物流有限公司": (27, 51551.0, 9652249.5, 325413.3, 151807.31),
        "湖北供销惠侬物流运输有限公司": (84, 4319.0, 557765.0, 307560.0, 57074.69),
        "通城县路畅通运输有限公司": (84, 68700.63, 2567246.93, 216220.629862196, 72409.91),
    }
    for name, target in expected.items():
        item = data["enterprises"][name]
        ledger = item["ledger_total"]
        actual = (ledger["vehicles"], ledger["freight"], ledger["turnover"], ledger["mileage"], item["track_mileage"])
        checks = [actual[0] == target[0], abs(actual[1] - target[1]) < 0.01,
                  abs(actual[2] - target[2]) < 0.05, abs(actual[3] - target[3]) < 0.05,
                  abs(actual[4] - target[4]) < 0.05]
        if not all(checks):
            raise AssertionError(f"Calibration failed for {name}: {actual} != {target}")
    if len(data["enterprises"]) != 12:
        raise AssertionError(f"Expected 12 enterprises, got {len(data['enterprises'])}")
 
def summarize_analysis(data: Dict[str, Any]) -> Dict[str, Any]:
    result = {
        "period": data["period"],
        "enterprises": {},
        "totals": {
            "ledger_rows": len(data["ledger_rows"]),
            "track_rows": len(data["track_rows"]),
            "raw_point_rows": len(data["point_rows"]),
            "source_files": len(data["source_files"]),
        },
    }
    for name, item in data["enterprises"].items():
        ledger = item["ledger_total"]
        report = item["report"]
        result["enterprises"][name] = {
            "city": item["profile"].city,
            "report_vehicle_total": report["vehicle_total"],
            "report_freight": report["freight_total"],
            "report_turnover": report["turnover_total"],
            "ledger_vehicle_count": ledger["vehicles"],
            "ledger_freight": round(ledger["freight"], 6),
            "ledger_turnover": round(ledger["turnover"], 6),
            "ledger_mileage": round(ledger["mileage"], 6),
            "matched_vehicle_count": len(item["matched"]),
            "track_vehicle_count": item["active_track_vehicles"],
            "track_mileage": round(item["track_mileage"], 6),
            "track_estimated_turnover": round(item["track_estimated"], 6),
            "normalized_track_turnover": None if item["normalized_track"] is None else round(item["normalized_track"], 6),
            "report_vs_ledger_rate": item["report_vs_ledger_rate"],
            "report_vs_track_rate": item["report_vs_track_rate"],
            "raw_track_point_count": item["raw_track_point_count"],
            "severity": item["severity"],
            "conclusion": item["conclusion"],
        }
    return result
 
 
def main(argv: Optional[Sequence[str]] = None) -> int:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--period", required=True)
    parser.add_argument("--source-root", required=True)
    parser.add_argument("--work-root", default="")
    parser.add_argument("--raw-manifest", default="")
    parser.add_argument("--output", required=True)
    parser.add_argument("--auth-vehicle-file", default="",
                        help="Transport authority vehicle-count workbook; defaults to the sibling 101 folder.")
    parser.add_argument("--task-code", default="")
    parser.add_argument("--task-name", default="")
    parser.add_argument("--db-host", default=os.environ.get("TRAFFIC_DB_HOST", "127.0.0.1"))
    parser.add_argument("--db-port", type=int, default=int(os.environ.get("TRAFFIC_DB_PORT", "3305")))
    parser.add_argument("--db-user", default=os.environ.get("TRAFFIC_DB_USER", "root"))
    parser.add_argument("--db-password", default=os.environ.get("TRAFFIC_DB_PASSWORD", ""))
    parser.add_argument("--db-name", default=os.environ.get("TRAFFIC_DB_NAME", "traffic_audit"))
    parser.add_argument("--apply", action="store_true", help="Write task data and report to the database.")
    parser.add_argument("--overview-only", action="store_true", help="Generate overview and vehicle mileage sheets only.")
    parser.add_argument("--summary-json", default="")
    args = parser.parse_args(argv)
    if not PERIOD_RE.match(args.period):
        raise SystemExit("period must use YYYY-MM")
    if not args.db_password:
        raise SystemExit("Set TRAFFIC_DB_PASSWORD or pass --db-password")
    conn = pymysql.connect(host=args.db_host, port=args.db_port, user=args.db_user,
                           password=args.db_password, database=args.db_name, charset="utf8mb4",
                           cursorclass=pymysql.cursors.DictCursor, autocommit=False)
    try:
        if args.overview_only:
            auth_vehicle_file = Path(args.auth_vehicle_file) if args.auth_vehicle_file else None
            data = build_overview(conn, PROFILES, args.period, Path(args.source_root), auth_vehicle_file)
            write_overview_workbook(data, Path(args.output))
            summary = {
                "period": args.period,
                "mode": "overview_only",
                "enterprise_count": len(data["enterprises"]),
                "vehicle_count": len(data["vehicles"]),
                "matched_vehicle_count": sum(
                    1 for item in data["vehicles"] if item["track_mileage"] is not None
                ),
                "vehicle_registry_file": data["vehicle_registry_file"],
                "output": str(Path(args.output)),
            }
        else:
            if not args.work_root or not args.raw_manifest:
                raise SystemExit("--work-root and --raw-manifest are required unless --overview-only is used")
            data = build_analysis(conn, PROFILES, args.period, Path(args.source_root), Path(args.work_root),
                                  Path(args.raw_manifest))
            validate_analysis(data)
            summary = summarize_analysis(data)
            summary["apply_requested"] = args.apply
        if args.summary_json:
            with Path(args.summary_json).open("w", encoding="utf-8") as handle:
                json.dump(summary, handle, ensure_ascii=False, indent=2)
        else:
            print(json.dumps(summary, ensure_ascii=False, indent=2))
        return 0
    finally:
        conn.close()
 
 
if __name__ == "__main__":
    raise SystemExit(main())