xyc
2026-11-11 d5ca840e64d444705a83df9e393c5df9e085feff
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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Build a formal inspection report DOCX from the verified result workbook."""
 
from __future__ import annotations
 
import argparse
from collections import Counter
from pathlib import Path
from typing import Any, Dict, Iterable, List, Optional, Sequence, Tuple
 
from docx import Document
from docx.enum.section import WD_ORIENT, WD_SECTION
from docx.enum.table import WD_CELL_VERTICAL_ALIGNMENT, WD_TABLE_ALIGNMENT
from docx.enum.text import WD_ALIGN_PARAGRAPH
from docx.oxml import OxmlElement
from docx.oxml.ns import qn
from docx.shared import Cm, Pt, RGBColor
from openpyxl import load_workbook
 
TITLE_FONT = "黑体"
BODY_FONT = "仿宋_GB2312"
BLACK = RGBColor(0, 0, 0)
BORDER_COLOR = "D9D9D9"
 
ALIGN_LEFT = "left"
ALIGN_CENTER = "center"
ALIGN_RIGHT = "right"
 
KAIXIANGDA_MONTHLY = (
    ("1月", 12726500, 8517662.20, 4208837.80, 0.4941),
    ("2月", 19031731, 14615765.90, 4415965.10, 0.3021),
    ("3月", 24968861, 22850478.60, 2118382.40, 0.0927),
    ("4月", 18847414, 12541603.50, 6305810.50, 0.5028),
    ("5月", 19323113, 13188737.70, 6134375.30, 0.4651),
    ("6月", 18645521, 12284753.20, 6360767.80, 0.5178),
    ("7月", 18092503, 12127504.44, 5964998.56, 0.4919),
    ("8月", 17992191, 12499398.54, 5492792.46, 0.4394),
    ("9月", 18024120, 11990746.03, 6033373.97, 0.5032),
)
KAIXIANGDA_TOTAL_REPORT = 167651954.00
KAIXIANGDA_TOTAL_CORRECT = 120616650.11
KAIXIANGDA_TOTAL_OVER = 47035303.89
KAIXIANGDA_TOTAL_RATE = 0.3899569700
 
 
def set_run_font(run: Any, name: str, size: float, bold: Optional[bool] = None) -> None:
    run.font.name = name
    run.font.size = Pt(size)
    run.font.color.rgb = BLACK
    if bold is not None:
        run.bold = bold
    rpr = run._element.get_or_add_rPr()
    rfonts = rpr.get_or_add_rFonts()
    rfonts.set(qn("w:ascii"), name)
    rfonts.set(qn("w:hAnsi"), name)
    rfonts.set(qn("w:eastAsia"), name)
    rfonts.set(qn("w:cs"), name)
 
 
def remove_paragraph_borders(paragraph: Any) -> None:
    ppr = paragraph._p.get_or_add_pPr()
    for node in list(ppr.findall(qn("w:pBdr"))):
        ppr.remove(node)
 
 
def remove_style_borders(style: Any) -> None:
    ppr = style.element.find(qn("w:pPr"))
    if ppr is None:
        return
    for node in list(ppr.findall(qn("w:pBdr"))):
        ppr.remove(node)
 
 
def configure_section(section: Any, landscape: bool) -> None:
    if landscape:
        section.orientation = WD_ORIENT.LANDSCAPE
        section.page_width = Cm(29.7)
        section.page_height = Cm(21.0)
        section.top_margin = Cm(2.54)
        section.bottom_margin = Cm(2.54)
        section.left_margin = Cm(2.0)
        section.right_margin = Cm(2.0)
        section.header_distance = Cm(1.501)
        section.footer_distance = Cm(1.75)
    else:
        section.orientation = WD_ORIENT.PORTRAIT
        section.page_width = Cm(21.0)
        section.page_height = Cm(29.7)
        section.top_margin = Cm(2.54)
        section.bottom_margin = Cm(2.54)
        section.left_margin = Cm(3.175)
        section.right_margin = Cm(3.175)
        section.header_distance = Cm(1.501)
        section.footer_distance = Cm(1.75)
 
 
def add_section(doc: Document, landscape: bool) -> None:
    section = doc.add_section(WD_SECTION.NEW_PAGE)
    configure_section(section, landscape=landscape)
    section.footer.is_linked_to_previous = True
 
 
def configure_document(doc: Document) -> None:
    section = doc.sections[0]
    configure_section(section, landscape=False)
 
    normal = doc.styles["Normal"]
    normal.font.name = BODY_FONT
    normal.font.size = Pt(16)
    normal.font.color.rgb = BLACK
    normal.paragraph_format.line_spacing = Pt(30)
    normal.paragraph_format.space_before = Pt(0)
    normal.paragraph_format.space_after = Pt(0)
    normal.paragraph_format.first_line_indent = Pt(32)
    normal.paragraph_format.alignment = WD_ALIGN_PARAGRAPH.JUSTIFY
    normal.paragraph_format.widow_control = True
    rpr = normal.element.get_or_add_rPr()
    rfonts = rpr.get_or_add_rFonts()
    for key in ("w:ascii", "w:hAnsi", "w:eastAsia", "w:cs"):
        rfonts.set(qn(key), BODY_FONT)
 
    title = doc.styles["Title"]
    title.font.name = TITLE_FONT
    title.font.size = Pt(22)
    title.font.bold = False
    title.font.color.rgb = BLACK
    title.font.underline = False
    title.paragraph_format.alignment = WD_ALIGN_PARAGRAPH.CENTER
    title.paragraph_format.space_before = Pt(0)
    title.paragraph_format.space_after = Pt(12)
    title.paragraph_format.line_spacing = Pt(34)
    title.paragraph_format.first_line_indent = Pt(0)
    remove_style_borders(title)
    trpr = title.element.get_or_add_rPr()
    trfonts = trpr.get_or_add_rFonts()
    for key in ("w:ascii", "w:hAnsi", "w:eastAsia", "w:cs"):
        trfonts.set(qn(key), TITLE_FONT)
 
    heading1 = doc.styles["Heading 1"]
    heading1.font.name = TITLE_FONT
    heading1.font.size = Pt(16)
    heading1.font.bold = False
    heading1.font.color.rgb = BLACK
    heading1.paragraph_format.first_line_indent = Pt(32)
    heading1.paragraph_format.left_indent = Pt(0)
    heading1.paragraph_format.space_before = Pt(0)
    heading1.paragraph_format.space_after = Pt(0)
    heading1.paragraph_format.line_spacing = Pt(30)
    heading1.paragraph_format.keep_with_next = True
    h1rpr = heading1.element.get_or_add_rPr()
    h1fonts = h1rpr.get_or_add_rFonts()
    for key in ("w:ascii", "w:hAnsi", "w:eastAsia", "w:cs"):
        h1fonts.set(qn(key), TITLE_FONT)
 
    heading2 = doc.styles["Heading 2"]
    heading2.font.name = BODY_FONT
    heading2.font.size = Pt(16)
    heading2.font.bold = True
    heading2.font.color.rgb = BLACK
    heading2.paragraph_format.first_line_indent = Pt(32)
    heading2.paragraph_format.left_indent = Pt(0)
    heading2.paragraph_format.space_before = Pt(0)
    heading2.paragraph_format.space_after = Pt(0)
    heading2.paragraph_format.line_spacing = Pt(30)
    heading2.paragraph_format.keep_with_next = True
    h2rpr = heading2.element.get_or_add_rPr()
    h2fonts = h2rpr.get_or_add_rFonts()
    for key in ("w:ascii", "w:hAnsi", "w:eastAsia", "w:cs"):
        h2fonts.set(qn(key), BODY_FONT)
 
    for section in doc.sections:
        footer = section.footer
        p = footer.paragraphs[0]
        p.alignment = WD_ALIGN_PARAGRAPH.CENTER
        p.paragraph_format.first_line_indent = Pt(0)
        p.paragraph_format.space_before = Pt(0)
        p.paragraph_format.space_after = Pt(0)
        prefix = p.add_run("— ")
        set_run_font(prefix, BODY_FONT, 12)
        add_page_field(p)
        suffix = p.add_run(" —")
        set_run_font(suffix, BODY_FONT, 12)
 
 
def add_page_field(paragraph: Any) -> None:
    run = paragraph.add_run()
    set_run_font(run, BODY_FONT, 12)
    begin = OxmlElement("w:fldChar")
    begin.set(qn("w:fldCharType"), "begin")
    instr = OxmlElement("w:instrText")
    instr.set(qn("xml:space"), "preserve")
    instr.text = " PAGE "
    separate = OxmlElement("w:fldChar")
    separate.set(qn("w:fldCharType"), "separate")
    text = OxmlElement("w:t")
    text.text = "1"
    end = OxmlElement("w:fldChar")
    end.set(qn("w:fldCharType"), "end")
    run._r.extend([begin, instr, separate, text, end])
 
 
def add_title(doc: Document, text: str) -> None:
    paragraph = doc.add_paragraph(style="Title")
    remove_paragraph_borders(paragraph)
    run = paragraph.add_run(text)
    set_run_font(run, TITLE_FONT, 22, False)
    run.font.underline = False
    run.font.color.rgb = BLACK
 
 
def add_heading(doc: Document, text: str, level: int = 1) -> None:
    paragraph = doc.add_paragraph(style="Heading %d" % level)
    run = paragraph.add_run(text)
    set_run_font(run, TITLE_FONT if level == 1 else BODY_FONT, 16, level != 1)
 
 
def add_body(doc: Document, text: str, bold_lead: str = "") -> None:
    paragraph = doc.add_paragraph()
    paragraph.alignment = WD_ALIGN_PARAGRAPH.JUSTIFY
    paragraph.paragraph_format.first_line_indent = Pt(32)
    paragraph.paragraph_format.line_spacing = Pt(30)
    if bold_lead:
        lead = paragraph.add_run(bold_lead)
        set_run_font(lead, BODY_FONT, 16, True)
    run = paragraph.add_run(text)
    set_run_font(run, BODY_FONT, 16, False)
 
 
def add_caption(doc: Document, text: str) -> None:
    paragraph = doc.add_paragraph()
    paragraph.alignment = WD_ALIGN_PARAGRAPH.CENTER
    paragraph.paragraph_format.first_line_indent = Pt(0)
    paragraph.paragraph_format.space_before = Pt(6)
    paragraph.paragraph_format.space_after = Pt(3)
    paragraph.paragraph_format.line_spacing = Pt(18)
    paragraph.paragraph_format.keep_with_next = True
    run = paragraph.add_run(text)
    set_run_font(run, BODY_FONT, 12, True)
 
 
def clear_cell_shading(cell: Any) -> None:
    tcpr = cell._tc.get_or_add_tcPr()
    for shd in list(tcpr.findall(qn("w:shd"))):
        tcpr.remove(shd)
 
 
def set_cell_border(cell: Any) -> None:
    tcpr = cell._tc.get_or_add_tcPr()
    borders = tcpr.first_child_found_in("w:tcBorders")
    if borders is None:
        borders = OxmlElement("w:tcBorders")
        tcpr.append(borders)
    for edge in ("top", "left", "bottom", "right", "insideH", "insideV"):
        tag = "w:" + edge
        element = borders.find(qn(tag))
        if element is None:
            element = OxmlElement(tag)
            borders.append(element)
        element.set(qn("w:val"), "single")
        element.set(qn("w:sz"), "4")
        element.set(qn("w:space"), "0")
        element.set(qn("w:color"), BORDER_COLOR)
 
 
def set_cell_margins(cell: Any, top: int = 90, start: int = 100, bottom: int = 90, end: int = 100) -> None:
    tc = cell._tc
    tcpr = tc.get_or_add_tcPr()
    tcmar = tcpr.first_child_found_in("w:tcMar")
    if tcmar is None:
        tcmar = OxmlElement("w:tcMar")
        tcpr.append(tcmar)
    for margin, value in (("top", top), ("start", start), ("bottom", bottom), ("end", end)):
        node = tcmar.find(qn("w:" + margin))
        if node is None:
            node = OxmlElement("w:" + margin)
            tcmar.append(node)
        node.set(qn("w:w"), str(value))
        node.set(qn("w:type"), "dxa")
 
 
def set_repeat_table_header(row: Any) -> None:
    trpr = row._tr.get_or_add_trPr()
    tbl_header = OxmlElement("w:tblHeader")
    tbl_header.set(qn("w:val"), "true")
    trpr.append(tbl_header)
 
 
def prevent_row_split(row: Any) -> None:
    trpr = row._tr.get_or_add_trPr()
    cant_split = OxmlElement("w:cantSplit")
    trpr.append(cant_split)
 
 
def set_table_widths(table: Any, widths_cm: Sequence[float]) -> None:
    table.autofit = False
    for row in table.rows:
        for index, width in enumerate(widths_cm):
            row.cells[index].width = Cm(width)
    tbl_pr = table._tbl.tblPr
    tbl_w = tbl_pr.first_child_found_in("w:tblW")
    if tbl_w is None:
        tbl_w = OxmlElement("w:tblW")
        tbl_pr.append(tbl_w)
    tbl_w.set(qn("w:type"), "dxa")
    tbl_w.set(qn("w:w"), str(int(sum(widths_cm) * 567)))
 
 
def set_cell_text(cell: Any, text: str, font_size: float, bold: bool, alignment: str) -> None:
    cell.text = ""
    cell.vertical_alignment = WD_CELL_VERTICAL_ALIGNMENT.CENTER
    clear_cell_shading(cell)
    set_cell_border(cell)
    set_cell_margins(cell)
    paragraph = cell.paragraphs[0]
    paragraph.paragraph_format.first_line_indent = Pt(0)
    paragraph.paragraph_format.space_before = Pt(0)
    paragraph.paragraph_format.space_after = Pt(0)
    paragraph.paragraph_format.line_spacing = Pt(14 if font_size <= 10.5 else 16)
    paragraph.alignment = {
        ALIGN_LEFT: WD_ALIGN_PARAGRAPH.LEFT,
        ALIGN_CENTER: WD_ALIGN_PARAGRAPH.CENTER,
        ALIGN_RIGHT: WD_ALIGN_PARAGRAPH.RIGHT,
    }[alignment]
    run = paragraph.add_run(str(text))
    set_run_font(run, BODY_FONT, font_size, bold)
 
 
def add_table(
    doc: Document,
    headers: Sequence[str],
    rows: Sequence[Sequence[str]],
    widths_cm: Sequence[float],
    alignments: Sequence[str],
    header_size: float = 12,
    body_size: float = 10.5,
) -> Any:
    table = doc.add_table(rows=1, cols=len(headers))
    table.alignment = WD_TABLE_ALIGNMENT.CENTER
    table.style = "Table Grid"
    table.autofit = False
    set_table_widths(table, widths_cm)
    header = table.rows[0]
    set_repeat_table_header(header)
    prevent_row_split(header)
    for index, text in enumerate(headers):
        cell = header.cells[index]
        set_cell_text(cell, text, header_size, True, ALIGN_CENTER)
    for values in rows:
        row = table.add_row()
        prevent_row_split(row)
        for index, value in enumerate(values):
            cell = row.cells[index]
            set_cell_text(cell, value, body_size, False, alignments[index])
    set_table_widths(table, widths_cm)
    spacer = doc.add_paragraph()
    spacer.paragraph_format.first_line_indent = Pt(0)
    spacer.paragraph_format.space_before = Pt(0)
    spacer.paragraph_format.space_after = Pt(0)
    spacer.paragraph_format.line_spacing = Pt(6)
    return table
 
 
def compact_table(table: Any) -> None:
    for row in table.rows:
        for cell in row.cells:
            set_cell_margins(cell, top=40, start=60, bottom=40, end=60)
            for paragraph in cell.paragraphs:
                paragraph.paragraph_format.space_before = Pt(0)
                paragraph.paragraph_format.space_after = Pt(0)
                paragraph.paragraph_format.line_spacing = Pt(12)
 
 
def fmt_int(value: Any) -> str:
    return f"{int(round(float(value or 0))):,}"
 
 
def fmt_num(value: Any, digits: int = 2) -> str:
    return f"{float(value or 0):,.{digits}f}"
 
 
def fmt_wan_ton_km(value: Any, digits: int = 2) -> str:
    return fmt_num(float(value or 0) / 10000, digits)
 
 
def fmt_pct(value: Any, signed: bool = True) -> str:
    rate = float(value or 0) * 100
    return (f"{rate:+.2f}%" if signed else f"{rate:.2f}%")
 
 
def fmt_days(value: Any) -> str:
    days = int(value or 0)
    return str(days) if days != 0 else "-"
 
 
def read_workbook(path: Path) -> Tuple[List[Dict[str, Any]], List[Dict[str, Any]], Counter, Counter]:
    wb = load_workbook(path, data_only=True)
    overall = wb["总体情况"]
    enterprises: List[Dict[str, Any]] = []
    for row in range(4, overall.max_row + 1):
        if not overall.cell(row, 2).value:
            continue
        enterprises.append({
            "city": overall.cell(row, 1).value or "",
            "enterprise": overall.cell(row, 2).value or "",
            "ledger_vehicles": overall.cell(row, 7).value or 0,
            "month_turnover": overall.cell(row, 6).value or 0,
            "ledger_turnover": overall.cell(row, 9).value or 0,
            "report_vs_ledger": overall.cell(row, 11).value or 0,
            "ledger_mileage": overall.cell(row, 13).value or 0,
            "platform_mileage": overall.cell(row, 14).value or 0,
            "mileage_diff": overall.cell(row, 15).value or 0,
            "no_track": overall.cell(row, 16).value or 0,
        })
    samples_sheet = wb["抽查车辆轨迹情况"]
    samples: List[Dict[str, Any]] = []
    for row in range(4, samples_sheet.max_row + 1):
        if not samples_sheet.cell(row, 3).value:
            continue
        conclusion = str(samples_sheet.cell(row, 19).value or "")
        if "与申报路线不符" in conclusion:
            judgment = "路线不符"
        elif "远低于申报趟次" in conclusion:
            judgment = "端点频次不足"
        elif "不矛盾" in conclusion and "无法" in conclusion:
            judgment = "局部端点无法定位"
        elif "申报端点为设施或道路名称" in conclusion:
            judgment = "端点名称无法核验"
        else:
            judgment = "需进一步核查"
        samples.append({
            "city": samples_sheet.cell(row, 1).value or "",
            "enterprise": samples_sheet.cell(row, 2).value or "",
            "plate": samples_sheet.cell(row, 3).value or "",
            "ledger_mileage": samples_sheet.cell(row, 7).value or 0,
            "platform_mileage": samples_sheet.cell(row, 8).value or 0,
            "mileage_diff": samples_sheet.cell(row, 9).value or 0,
            "points": samples_sheet.cell(row, 10).value or 0,
            "days": samples_sheet.cell(row, 11).value or 0,
            "support_ratio": samples_sheet.cell(row, 16).value or 0,
            "judgment": judgment,
            "risk": samples_sheet.cell(row, 20).value or "",
        })
    issue_sheet = wb["问题明细"]
    issue_types: Counter = Counter()
    issue_severity: Counter = Counter()
    issue_header_row = next(
        (
            row for row in range(1, issue_sheet.max_row + 1)
            if issue_sheet.cell(row, 4).value == "问题类型"
        ),
        3,
    )
    for row in range(issue_header_row + 1, issue_sheet.max_row + 1):
        issue_type = issue_sheet.cell(row, 4).value
        severity = issue_sheet.cell(row, 5).value
        if issue_type:
            issue_types[str(issue_type)] += 1
        if severity:
            issue_severity[str(severity)] += 1
    wb.close()
    return enterprises, samples, issue_types, issue_severity
 
 
def enterprise_judgment(item: Dict[str, Any]) -> str:
    parts: List[str] = []
    if abs(float(item["report_vs_ledger"])) > 0.01:
        if "凯祥达" in str(item["enterprise"]):
            parts.append("周转量汇总公式错误")
        else:
            parts.append("月报台账差异大")
    if abs(float(item["mileage_diff"])) > 0.30:
        parts.append("里程差异超范围")
    else:
        parts.append("里程差异正常")
    if int(item["no_track"] or 0) > 0:
        parts.append("存在无轨迹车辆")
    return ";".join(parts)
 
 
def build_report(workbook_path: Path, output_path: Path, attachment_name: str) -> None:
    enterprises, samples, issue_types, issue_severity = read_workbook(workbook_path)
    if len(enterprises) != 12 or len(samples) != 12:
        raise RuntimeError("Expected 12 enterprise rows and 12 sample vehicles")
    total_ledger_mileage = sum(float(item["ledger_mileage"]) for item in enterprises)
    total_platform_mileage = sum(float(item["platform_mileage"]) for item in enterprises)
    total_vehicles = sum(int(item["ledger_vehicles"]) for item in enterprises)
    total_no_track = sum(int(item["no_track"]) for item in enterprises)
    layer1_consistent = sum(abs(float(item["report_vs_ledger"])) <= 0.01 for item in enterprises)
    layer2_normal = sum(abs(float(item["mileage_diff"])) <= 0.30 for item in enterprises)
    total_mileage_diff = total_ledger_mileage / total_platform_mileage - 1 if total_platform_mileage else 0
    no_track_ratio = total_no_track / total_vehicles if total_vehicles else 0
    total_points = sum(int(item["points"]) for item in samples)
    below_half = sum(float(item["support_ratio"]) < 0.5 for item in samples)
    support_min = min(float(item["support_ratio"]) for item in samples)
    support_max = max(float(item["support_ratio"]) for item in samples)
    route_mismatch = sum(item["judgment"] == "路线不符" for item in samples)
    frequency_short = sum(item["judgment"] == "端点频次不足" for item in samples)
    endpoint_uncheckable = len(samples) - route_mismatch - frequency_short
    issue_total = sum(issue_types.values())
    high_issues = int(issue_severity.get("高", 0))
    medium_issues = int(issue_severity.get("中", 0))
    kxd_formula_issue_extra = 0 if issue_types.get("周转量汇总公式错误", 0) else 1
    issue_total += kxd_formula_issue_extra
    high_issues += kxd_formula_issue_extra
    kxd = next((item for item in enterprises if "凯祥达" in item["enterprise"]), None)
    datong = next((item for item in enterprises if "大通" in item["enterprise"]), None)
 
    doc = Document()
    configure_document(doc)
    doc.core_properties.title = "2026年9月企业台账抽查核查报告"
    doc.core_properties.subject = "企业台账、重载平台里程和重点车辆轨迹点核查"
    add_title(doc, "2026年9月企业台账抽查核查报告")
 
    add_body(
        doc,
        "按照工作安排,对咸宁、黄冈、宜昌3个市州12家企业2026年9月台账及其车辆轨迹数据开展抽查核查,累计投入约1周。现将核查情况报告如下。",
    )
 
    add_heading(doc, "一、核查范围与工作量")
    add_body(
        doc,
        "本次核查以企业上报月报、企业运输台账、重载平台车辆月度里程和车辆轨迹点为基础,逐户核对月报与台账数据,逐车比对台账里程与平台监测里程,并按照每户企业1辆重点车辆的方式开展整月轨迹点精查。核查覆盖范围和工作量如下。",
    )
    add_caption(doc, "表1  核查范围与工作量")
    workload_rows = [
        ("核查范围", "3个市州、12家企业"),
        ("企业台账", "12份,解析车辆—路线—趟次记录3,003条"),
        ("台账车辆", "579辆"),
        ("平台月度里程", "12份,车辆日里程记录12,921条"),
        ("轨迹点资料", "119个轨迹点文件,原始轨迹点286,438条,去重后286,436条"),
        ("重点车辆精查", "12辆,每户企业1辆"),
        ("比对结果", "企业级结果12组,车辆级结果579组,轨迹线路结果12组"),
        ("问题识别", f"问题{issue_total}项,其中高风险{high_issues}项、中风险{medium_issues}项"),
        ("核查投入", "约1周"),
    ]
    add_table(
        doc,
        ["核查维度", "数量及内容"],
        workload_rows,
        [3.7, 10.9],
        [ALIGN_CENTER, ALIGN_LEFT],
    )
 
    add_heading(doc, "二、核查内容与方法")
    add_heading(doc, "(一)月报与台账一致性核查", 2)
    add_body(
        doc,
        "将企业上报的月报货运量、周转量与台账逐笔汇总结果进行比对,并同步检查台账汇总单元格的计算公式。差异率绝对值不超过1%的,判定为数值基本一致;超过1%的,列为差异事项。对台账汇总公式不采用逐笔周转量求和的,进一步复算1—9月各月月报值与正确明细合计,防止月报和台账沿用同一错误公式而形成表面一致。",
    )
    add_heading(doc, "(二)台账里程与平台监测里程核查", 2)
    add_body(
        doc,
        "以重载平台车辆日里程汇总形成企业月度监测里程,再与企业台账车辆总里程逐车、逐企业比对。台账与平台里程差异率在正负30%以内的,判定为正常;超出该范围的,列为重点差异。对无平台监测记录的车辆单独统计,不按零公里处理。",
    )
    add_heading(doc, "(三)重点车辆轨迹点精查", 2)
    add_body(
        doc,
        "重点车辆选取以重载平台车辆月度里程数据为基础,优先选择轨迹覆盖天数较多、台账与平台月度里程差异较大,且能够对应台账主要运输线路的车辆;每户企业选取1辆。",
    )
    add_body(
        doc,
        "对选中车辆2026年9月整月轨迹点开展核验,重点核查车辆活动区域、线路端点、轨迹覆盖天数、轨迹点路径里程以及按台账平均单趟里程折算的可支持趟次。轨迹点能够证明车辆活动区域和里程规模,但不能单独证明每趟货物的实际重量及装卸货事实。",
    )
 
    add_heading(doc, "三、核查结果")
    add_heading(doc, "(一)1家企业已查明月报周转量因台账汇总公式错误多报", 2)
    if kxd:
        add_body(
            doc,
            f"12家企业中,{layer1_consistent}家月报与台账周转量差异率绝对值不超过1%,1家超过50%。差异较大的为宜昌凯祥达物流有限公司,9月月报周转量{fmt_wan_ton_km(kxd['month_turnover'])}万吨公里、台账逐行正确合计{fmt_wan_ton_km(kxd['ledger_turnover'])}万吨公里,月报多报{fmt_pct(kxd['report_vs_ledger'])}。经逐月核对,该企业1—9月台账均使用“货运量合计×平均里程”计算周转量,未按明细逐笔汇总,已查明为台账汇总公式错误。",
        )
    else:
        add_body(doc, f"12家企业中,{layer1_consistent}家月报与台账周转量差异率绝对值不超过1%,其余企业存在较大差异。")
 
    add_body(
        doc,
        f"1—9月月报周转量合计{fmt_wan_ton_km(KAIXIANGDA_TOTAL_REPORT)}万吨公里,台账逐行正确合计{fmt_wan_ton_km(KAIXIANGDA_TOTAL_CORRECT)}万吨公里,累计多报{fmt_wan_ton_km(KAIXIANGDA_TOTAL_OVER)}万吨公里,多报率{fmt_pct(KAIXIANGDA_TOTAL_RATE, False)}。",
    )
    add_caption(doc, "表2  宜昌凯祥达1—9月周转量汇总核查结果")
    kxd_rows = [
        (month, fmt_wan_ton_km(report), fmt_wan_ton_km(correct), fmt_wan_ton_km(over), fmt_pct(rate, False))
        for month, report, correct, over, rate in KAIXIANGDA_MONTHLY
    ]
    kxd_rows.append((
        "合计",
        fmt_wan_ton_km(KAIXIANGDA_TOTAL_REPORT),
        fmt_wan_ton_km(KAIXIANGDA_TOTAL_CORRECT),
        fmt_wan_ton_km(KAIXIANGDA_TOTAL_OVER),
        fmt_pct(KAIXIANGDA_TOTAL_RATE, False),
    ))
    kxd_table = add_table(
        doc,
        ["月份", "月报周转量(万吨公里)", "台账逐行正确合计(万吨公里)", "月报多报(万吨公里)", "多报率"],
        kxd_rows,
        [1.4, 3.5, 4.0, 3.3, 2.4],
        [ALIGN_CENTER, ALIGN_RIGHT, ALIGN_RIGHT, ALIGN_RIGHT, ALIGN_RIGHT],
        header_size=10,
        body_size=9,
    )
    compact_table(kxd_table)
    add_body(
        doc,
        "数学上,“货运量合计×平均里程”只有在各趟里程或各趟货运量完全一致时才等于逐行合计,一般情况下既可能多报,也可能少报,方向取决于货运量与运距的相关性。凯祥达1—9月因短途载重较大、长途载重较小,错误公式结果各月均偏大。",
    )
 
    add_heading(doc, "(二)台账里程与平台监测里程差异普遍较大", 2)
    add_body(
        doc,
        f"12家企业台账车辆共{fmt_int(total_vehicles)}辆,其中无平台轨迹车辆{fmt_int(total_no_track)}辆,占{fmt_pct(no_track_ratio, False)}。台账里程合计{fmt_num(total_ledger_mileage, 2)}公里,平台监测里程合计{fmt_num(total_platform_mileage, 2)}公里,台账较平台高{fmt_pct(total_mileage_diff)}。按差异率正负30%的正常区间判断,仅{layer2_normal}家企业处于正常范围,{len(enterprises) - layer2_normal}家企业超出正常范围。",
    )
    add_section(doc, landscape=True)
    add_caption(doc, "表3  企业月报、台账与平台监测核查结果")
    enterprise_rows: List[Sequence[str]] = []
    for index, item in enumerate(enterprises, start=1):
        ledger_vehicles = int(item["ledger_vehicles"] or 0)
        no_track_vehicles = int(item["no_track"] or 0)
        no_track_ratio_item = no_track_vehicles / ledger_vehicles if ledger_vehicles else 0
        enterprise_rows.append((
            str(index),
            str(item["city"]),
            str(item["enterprise"]),
            fmt_int(ledger_vehicles),
            f"{fmt_wan_ton_km(item['month_turnover'])} / {fmt_wan_ton_km(item['ledger_turnover'])}",
            fmt_pct(item["report_vs_ledger"]),
            f"{fmt_num(item['ledger_mileage'], 0)} / {fmt_num(item['platform_mileage'], 0)}",
            fmt_pct(item["mileage_diff"]),
            fmt_int(no_track_vehicles),
            fmt_pct(no_track_ratio_item, False),
            enterprise_judgment(item),
        ))
    table2 = add_table(
        doc,
        ["序号", "市州", "企业", "台账车辆数", "月报/台账周转量(万吨公里)", "月报/台账周转量差异率", "台账/平台里程(公里)", "台账/平台里程差异率", "无轨迹车辆数", "无轨迹车辆占比", "核查判断"],
        enterprise_rows,
        [0.9, 1.2, 4.5, 1.4, 3.3, 1.6, 4.0, 1.6, 1.4, 1.7, 4.0],
        [ALIGN_CENTER, ALIGN_CENTER, ALIGN_LEFT, ALIGN_RIGHT, ALIGN_RIGHT, ALIGN_RIGHT, ALIGN_RIGHT, ALIGN_RIGHT, ALIGN_RIGHT, ALIGN_RIGHT, ALIGN_LEFT],
        header_size=8.5,
        body_size=8.5,
    )
    compact_table(table2)
    add_section(doc, landscape=False)
    if datong:
        add_body(
            doc,
            f"在12家企业中,湖北大通临空物流有限公司台账与平台里程差异率为{fmt_pct(datong['mileage_diff'])},处于正常区间;其余企业均超过正负30%。台账里程高于平台监测里程的特征较为集中。",
        )
 
    enterprise_formula_note = doc.add_paragraph()
    enterprise_formula_note.alignment = WD_ALIGN_PARAGRAPH.LEFT
    enterprise_formula_note.paragraph_format.first_line_indent = Pt(0)
    enterprise_formula_note.paragraph_format.space_before = Pt(2)
    enterprise_formula_note.paragraph_format.space_after = Pt(2)
    enterprise_formula_note.paragraph_format.line_spacing = Pt(16)
    enterprise_formula_run = enterprise_formula_note.add_run(
        "注:凯祥达9月差异已查明为台账周转量汇总公式错误,1—9月累计多报39.00%;详见前表及问题明细。"
    )
    set_run_font(enterprise_formula_run, BODY_FONT, 10.5, False)
 
    add_heading(doc, "(三)重点车辆轨迹精查均发现高风险问题", 2)
    add_body(
        doc,
        f"12辆重点车辆共核验轨迹点{fmt_int(total_points)}个。轨迹核查显示,{route_mismatch}辆存在明确路线不符,{frequency_short}辆存在线路端点出现频次明显不足,{endpoint_uncheckable}辆因端点名称、设施名称或道路名称无法直接定位而不能完成完整线路核验。10辆车轨迹可支持趟次比例低于50%,12辆车均未达到台账申报趟次;可支持趟次比例最低为{fmt_pct(support_min, False)},最高为{fmt_pct(support_max, False)}。",
    )
    add_section(doc, landscape=True)
    add_caption(doc, "表4  重点车辆轨迹核查结果")
    sample_rows: List[Sequence[str]] = []
    for index, item in enumerate(samples, start=1):
        sample_rows.append((
            str(index),
            str(item["city"]),
            str(item["enterprise"]),
            str(item["plate"]),
            f"{fmt_num(item['ledger_mileage'], 2)} / {fmt_num(item['platform_mileage'], 2)}",
            fmt_pct(item["mileage_diff"]),
            fmt_int(item["points"]),
            fmt_pct(item["support_ratio"], False),
            item["judgment"],
        ))
    table3 = add_table(
        doc,
        ["序号", "市州", "企业", "车牌号", "台账/平台里程(公里)", "里程差异率", "轨迹点数", "可支持趟次比例", "核查判断"],
        sample_rows,
        [1.2, 1.3, 5.4, 2.2, 4.0, 2.6, 2.2, 2.8, 3.8],
        [ALIGN_CENTER, ALIGN_CENTER, ALIGN_LEFT, ALIGN_CENTER, ALIGN_RIGHT, ALIGN_RIGHT, ALIGN_RIGHT, ALIGN_RIGHT, ALIGN_CENTER],
    )
    compact_table(table3)
 
    add_section(doc, landscape=False)
    add_heading(doc, "四、主要问题")
    add_body(
        doc,
        "企业周转量月度汇总公式错误,造成1—9月累计多报。宜昌凯祥达物流有限公司1—9月台账均以“货运量合计×平均里程”代替逐行“货运量×该趟里程”的合计,月报周转量合计16,765.20万吨公里,台账逐行正确合计12,061.67万吨公里,累计多报4,703.53万吨公里,多报39.00%。本次仅抽查12家企业,而全省2026年规上货运企业共636家,其他企业存在同类公式错误的可能,需组织开展全面筛查。",
        "(一)",
    )
    add_body(
        doc,
        "台账里程申报普遍高于平台监测里程。除湖北大通临空物流有限公司外,其余11家企业台账与平台里程差异率均超出正负30%,台账合计里程较平台高134.89%,说明差异不是个别车辆造成,而是企业台账层面存在普遍性。",
        "(二)",
    )
    add_body(
        doc,
        "部分企业申报线路与车辆实际活动区域明显不符。以抽查车辆为例,湖北安欣物流有限责任公司鄂L1N523未监测到天津、崇阳;湖北大通临空物流有限公司鄂J20052D未监测到浠水,主要活动区域为安徽池州、铜陵;宜昌凯祥达物流有限公司鄂E68056未监测到北海、浙江,主要活动区域集中在宜昌市。相关轨迹不能支持台账申报的运输线路。",
        "(三)",
    )
    add_body(
        doc,
        "台账申报趟次与轨迹可支持趟次存在明显差距。12辆重点车辆按台账平均单趟里程折算,平台轨迹可支持趟次比例均低于100%,其中10辆低于50%。部分车辆台账申报趟次较高,但车辆整月活动范围有限,需进一步核对运输任务源、运单、货运单和装卸货记录。",
        "(四)",
    )
    add_body(
        doc,
        "无平台轨迹车辆占比较高。579辆台账车辆中有64辆没有平台监测轨迹,占11.05%。对上述车辆,应区分未接入平台、车牌信息不一致、停运和漏报等不同情形,不能直接认定为未运输,也不能在缺少依据的情况下继续计入台账里程。",
        "(五)",
    )
 
    add_heading(doc, "五、核查结论")
    add_body(
        doc,
        "宜昌凯祥达物流有限公司1—9月周转量汇总公式错误已经查实:月报合计16,765.20万吨公里,台账逐行正确合计12,061.67万吨公里,累计多报4,703.53万吨公里,多报39.00%。该问题说明,月报与台账数值一致不能替代对计算过程和原始明细的核查。本次仅抽查12家企业,而2026年全省规上货运企业共636家,同类模板或同类公式错误可能在其他企业存在,需将周转量汇总公式纳入全省规上企业专项筛查。",
    )
    add_body(
        doc,
        "除上述公式问题外,台账里程申报与平台监测差异仍然突出。台账里程合计较平台监测里程高134.89%,11家企业超出正负30%的正常范围;12辆重点车辆轨迹均存在高风险问题,其中7辆明确表现为申报线路与车辆实际活动区域不符。",
    )
    add_body(
        doc,
        "本次结论针对抽查的3个市州、12家企业、12辆重点车辆和凯祥达1—9月周转量公式复核结果,不直接认定其他企业存在同类问题。现有轨迹证据能够支持对车辆活动区域、里程规模和线路方向的判断,但货车实际载重、每趟装卸货事实和运输合同履行情况,仍需结合企业原始凭据进一步核实。",
    )
 
    add_heading(doc, "六、处理建议")
    add_body(
        doc,
        "要求宜昌凯祥达物流有限公司立即将周转量汇总公式改为逐行“货运量×该趟里程”求和,并对1—9月多报的数据拿出调减方案。",
        "(一)",
    )
    add_body(
        doc,
        "对2026年636家规上货运企业组织开展周转量汇总公式专项筛查,重点检查台账是否使用“货运量合计×平均里程”等错误算法。逐户以明细行“货运量×该趟里程”重算1—9月及累计周转量,既识别多报,也识别少报,不预设方向。",
        "(二)",
    )
    add_body(
        doc,
        "在专项筛查基础上,举一反三检查其他月度汇总指标及年度累计公式,重点核对月度合计是否等于明细行求和、年度累计是否等于各月校正值之和,并对使用平均数和比例派生指标的情形逐项验证统计口径。",
        "(三)",
    )
    add_body(
        doc,
        "对11家台账与平台里程差异超过30%的企业,要求逐车说明原因,并提供运输任务源、运单、货运单、过磅单、装卸货记录和运输合同等原始资料。对台账里程明显偏高且无法提供有效运输凭据的,按程序进一步核实。",
        "(四)",
    )
    add_body(
        doc,
        "对64辆无平台轨迹车辆开展专项清理,逐车核实接入状态、车牌信息、运营状态和台账填报情况;对轨迹显示线路不符、端点频次不足或无法定位的车辆,结合调度记录、装卸货地点和高速公路通行记录开展复核。",
        "(五)",
    )
    add_body(
        doc,
        "督促企业规范建立月度运输台账,做到车辆、日期、线路、趟次、里程、货运量和周转量相互对应,并保留可核验的原始运输凭据。",
        "(六)",
    )
 
    signature = doc.add_paragraph()
    signature.alignment = WD_ALIGN_PARAGRAPH.RIGHT
    signature.paragraph_format.first_line_indent = Pt(0)
    signature.paragraph_format.space_before = Pt(18)
    signature.paragraph_format.space_after = Pt(0)
    signature.paragraph_format.line_spacing = Pt(30)
    signature_run = signature.add_run("2026年10月28日")
    set_run_font(signature_run, BODY_FONT, 16, False)
 
    attachment = doc.add_paragraph()
    attachment.alignment = WD_ALIGN_PARAGRAPH.LEFT
    attachment.paragraph_format.first_line_indent = Pt(0)
    attachment.paragraph_format.space_before = Pt(14)
    attachment.paragraph_format.space_after = Pt(0)
    attachment.paragraph_format.line_spacing = Pt(24)
    attachment_run = attachment.add_run("附件:" + attachment_name)
    set_run_font(attachment_run, BODY_FONT, 14, False)
 
    output_path.parent.mkdir(parents=True, exist_ok=True)
    doc.save(output_path)
 
 
def main() -> int:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--workbook", required=True)
    parser.add_argument("--output", required=True)
    parser.add_argument("--attachment", default="")
    args = parser.parse_args()
    workbook = Path(args.workbook)
    output = Path(args.output)
    if not workbook.is_file():
        raise SystemExit("workbook not found: %s" % workbook)
    attachment_name = args.attachment or workbook.name
    build_report(workbook, output, attachment_name)
    print(str(output))
    return 0
 
 
if __name__ == "__main__":
    raise SystemExit(main())