xyc
2026-11-12 cb13d459288e2732cb7adc30a8cf80121e3216db
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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Build the reader-facing issue summary workbook for ledger inspection."""
 
from __future__ import annotations
 
import argparse
import json
import math
from pathlib import Path
from typing import Any, Dict, List, Sequence, Tuple
 
from openpyxl import Workbook
from openpyxl.styles import Alignment, Border, Font, PatternFill, Side
from openpyxl.utils import get_column_letter
from openpyxl.worksheet.page import PageMargins
from openpyxl.worksheet.pagebreak import Break
from openpyxl.worksheet.properties import PageSetupProperties
 
from build_ledger_inspection_report import (
    KAIXIANGDA_TOTAL_CORRECT,
    KAIXIANGDA_TOTAL_OVER,
    KAIXIANGDA_TOTAL_RATE,
    KAIXIANGDA_TOTAL_REPORT,
    city_sort_key,
    fmt_int,
    fmt_num,
    fmt_pct,
    fmt_wan_ton_km,
    ledger_route_text,
    main_region,
    read_enterprises,
    short_city_name,
    strict_missing_endpoints,
)
 
FANGSONG = "\u4eff\u5b8b_GB2312"
HEITI = "\u9ed1\u4f53"
BORDER_COLOR = "D9D9D9"
EMPTY = "\u2014"
TITLE_FONT = Font(name=HEITI, size=18, bold=True, color="000000")
HEADER_FONT = Font(name=FANGSONG, size=14, bold=True, color="000000")
BODY_FONT = Font(name=FANGSONG, size=12, color="000000")
THIN = Side(style="thin", color=BORDER_COLOR)
BORDER = Border(left=THIN, right=THIN, top=THIN, bottom=THIN)
 
HEADERS = [
    "\u5e8f\u53f7",
    "\u5e02\u5dde",
    "\u4f01\u4e1a",
    "\u95ee\u9898\u7c7b\u522b",
    "\u5177\u4f53\u95ee\u9898",
    "\u6d89\u53ca\u8f66\u8f86",
    "\u53f0\u8d26\u60c5\u51b5",
    "\u6708\u62a5\u53ca\u5e73\u53f0\u76d1\u6d4b\u60c5\u51b5",
    "\u6838\u67e5\u7ed3\u8bba",
    "\u6838\u67e5\u4f9d\u636e",
]
COLUMN_WIDTHS = [5.5, 7.5, 20.0, 14.0, 24.0, 13.0, 28.0, 40.0, 26.0, 26.0]
DATA_ALIGNMENTS = [
    "center", "center", "center", "center", "left", "center",
    "left", "left", "left", "left",
]
 
 
def plate_summary(item: Dict[str, Any]) -> str:
    plates = [str(value) for value in item.get("no_track_plates", []) if value]
    return "\u3001".join(plates)
 
 
def make_issue(
    item: Dict[str, Any],
    category: str,
    problem: str,
    scope: str,
    ledger_situation: str,
    monitoring_situation: str,
    conclusion: str,
    evidence: str,
) -> Dict[str, Any]:
    return {
        "city": short_city_name(item["city"]),
        "enterprise": str(item["enterprise"]),
        "category": category,
        "problem": problem,
        "scope": scope,
        "ledger": ledger_situation,
        "monitoring": monitoring_situation,
        "conclusion": conclusion,
        "evidence": evidence,
    }
 
 
def build_issue_records(
    enterprises: Sequence[Dict[str, Any]],
    vehicles: Sequence[Dict[str, Any]],
) -> List[Dict[str, Any]]:
    vehicles_by_enterprise = {str(item["enterprise"]): item for item in vehicles}
    ordered = sorted(
        enterprises,
        key=lambda item: (city_sort_key(item["city"]), str(item["enterprise"])),
    )
    records: List[Dict[str, Any]] = []
 
    for item in ordered:
        enterprise = str(item["enterprise"])
        vehicle = vehicles_by_enterprise.get(enterprise)
        if vehicle is None:
            raise RuntimeError("missing sample vehicle for %s" % enterprise)
 
        if "\u51ef\u7965\u8fbe" in enterprise:
            records.append(make_issue(
                item=item,
                category="\u5468\u8f6c\u91cf\u6c47\u603b",
                problem="2026\u5e741\u20149\u6708\u5468\u8f6c\u91cf\u6c47\u603b\u516c\u5f0f\u9519\u8bef",
                scope="\u4f01\u4e1a\u6574\u4f53",
                ledger_situation="\u53f0\u8d26\u9010\u884c\u6b63\u786e\u5408\u8ba1%s\u4e07\u5428\u516c\u91cc" % fmt_wan_ton_km(KAIXIANGDA_TOTAL_CORRECT),
                monitoring_situation="\u6708\u62a5%s\u4e07\u5428\u516c\u91cc" % fmt_wan_ton_km(KAIXIANGDA_TOTAL_REPORT),
                conclusion="\u6c47\u603b\u516c\u5f0f\u9519\u8bef\uff0c1\u20149\u6708\u7d2f\u8ba1\u591a\u62a5%s\u4e07\u5428\u516c\u91cc\uff0c\u591a\u62a5%s" % (
                    fmt_wan_ton_km(KAIXIANGDA_TOTAL_OVER),
                    fmt_pct(KAIXIANGDA_TOTAL_RATE, False),
                ),
                evidence="\u63091\u20149\u6708\u6708\u62a5\u4e0e\u53f0\u8d26\u660e\u7ec6\u9010\u6708\u91cd\u7b97\u6bd4\u5bf9\u3002",
            ))
 
        mileage_diff = float(item["mileage_diff"] or 0)
        if abs(mileage_diff) > 0.30:
            direction = "\u9ad8\u4e8e" if mileage_diff > 0 else "\u4f4e\u4e8e"
            records.append(make_issue(
                item=item,
                category="\u53f0\u8d26\u4e0e\u5e73\u53f0\u91cc\u7a0b",
                problem="\u53f0\u8d26\u91cc\u7a0b\u660e\u663e%s\u5e73\u53f0\u76d1\u6d4b\u91cc\u7a0b" % direction,
                scope="\u4f01\u4e1a\u6574\u4f53",
                ledger_situation="\u53f0\u8d26\u8f66\u8f86%s\u8f86\uff1b\u53f0\u8d26\u91cc\u7a0b%s\u516c\u91cc" % (
                    fmt_int(item["ledger_vehicles"]),
                    fmt_num(item["ledger_mileage"], 0),
                ),
                monitoring_situation="\u5e73\u53f0\u76d1\u6d4b\u91cc\u7a0b%s\u516c\u91cc" % fmt_num(item["platform_mileage"], 0),
                conclusion="\u53f0\u8d26\u4e0e\u5e73\u53f0\u5dee\u5f02\u7387%s\uff0c\u8d85\u51fa\u6b63\u8d1f30%%\u6b63\u5e38\u8303\u56f4" % fmt_pct(mileage_diff),
                evidence="\u6309\u4f01\u4e1a\u53f0\u8d26\u8f66\u8f86\u4e0e\u5e73\u53f0\u6708\u5ea6\u65e5\u91cc\u7a0b\u9010\u8f66\u6c47\u603b\u6bd4\u5bf9\u3002",
            ))
 
        no_track = int(item["no_track"] or 0)
        ledger_vehicles = int(item["ledger_vehicles"] or 0)
        if no_track > 0:
            plate_text = plate_summary(item)
            plate_clause = "\uff08%s\uff09" % plate_text if plate_text else ""
            records.append(make_issue(
                item=item,
                category="\u52a8\u6001\u76d1\u6d4b\u8986\u76d6",
                problem="\u90e8\u5206\u53f0\u8d26\u8f66\u8f86\u65e0\u5e73\u53f0\u6708\u91cc\u7a0b\u8bb0\u5f55",
                scope="\u4f01\u4e1a\u6574\u4f53",
                ledger_situation="\u53f0\u8d26\u8f66\u8f86%s\u8f86" % fmt_int(ledger_vehicles),
                monitoring_situation="\u65e0\u5e73\u53f0\u6708\u91cc\u7a0b\u8bb0\u5f55\u8f66\u8f86%s\u8f86%s" % (fmt_int(no_track), plate_clause),
                conclusion="\u65e0\u5e73\u53f0\u6708\u91cc\u7a0b\u8f66\u8f86\u5360\u6bd4%s" % fmt_pct(no_track / ledger_vehicles if ledger_vehicles else 0, False),
                evidence="\u6309\u53f0\u8d26\u8f66\u724c\u4e0e\u5e73\u53f0\u65e5\u91cc\u7a0b\u8bb0\u5f55\u9010\u8f66\u5339\u914d\u3002",
            ))
 
        positive_days = int(vehicle["platform"].get("positive_mileage_days") or 0)
        daily_days = int(vehicle["platform"].get("daily_record_days") or vehicle["platform"].get("days") or 0)
        if positive_days < 30:
            records.append(make_issue(
                item=item,
                category="\u52a8\u6001\u76d1\u6d4b\u8986\u76d6",
                problem="\u91cd\u70b9\u8f66\u8f86\u5e73\u53f0\u603b\u91cc\u7a0b\u5927\u4e8e0\u7684\u5929\u6570\u4e0d\u8db330\u5929",
                scope=str(vehicle["plate"]),
                ledger_situation="\u53f0\u8d26%s\u8d9f\uff0c%s\u516c\u91cc" % (
                    fmt_num(vehicle["ledger"]["trips"], 0),
                    fmt_num(vehicle["ledger"]["mileage"], 2),
                ),
                monitoring_situation="\u5e73\u53f0\u65e5\u8bb0\u5f55%s\u5929\uff0c\u603b\u91cc\u7a0b\u5927\u4e8e0\u7684%s\u5929" % (
                    fmt_int(daily_days),
                    fmt_int(positive_days),
                ),
                conclusion="\u5e73\u53f0\u603b\u91cc\u7a0b\u5927\u4e8e0\u4ec5%s\u5929\uff0c\u5c11\u4e8e30\u5929" % fmt_int(positive_days),
                evidence="\u5e73\u53f0\u65e5\u91cc\u7a0b\u8bb0\u5f55\u4e2d\u5b58\u5728\u603b\u91cc\u7a0b\u4e3a0\u7684\u65e5\u671f\u3002",
            ))
 
        missing = strict_missing_endpoints(vehicle)
        route_text = ledger_route_text(vehicle)
        total_mileage = fmt_num(vehicle["platform"]["total_mileage"], 2)
        point_count = fmt_int(vehicle["points"]["valid_point_count"])
        region = main_region(vehicle)
        support_rate = float(vehicle["comparison"].get("trip_support_rate") or 0)
        if missing:
            missing_text = "\u3001".join(missing)
            monitoring = (
                "\u5e73\u53f0%s\u516c\u91cc\uff1b\u8f68\u8ff9\u70b9%s\u4e2a\uff1b"
                "\u4e3b\u8981\u6d3b\u52a8\u533a\u57df%s\uff1b\u5e73\u53f0\u8f68\u8ff9\u672a\u76d1\u6d4b\u5230%s"
            ) % (total_mileage, point_count, region, missing_text)
            category = "\u91cd\u70b9\u8f66\u8f86\u7ebf\u8def"
            problem = "\u7533\u62a5\u7ebf\u8def\u672a\u83b7\u8f68\u8ff9\u652f\u6301"
            conclusion = "\u7533\u62a5\u7ebf\u8def\u672a\u83b7\u8f68\u8ff9\u652f\u6301"
            evidence = "\u8f68\u8ff9\u6d3b\u52a8\u533a\u57df\u4e0e\u7533\u62a5\u7ebf\u8def\u7aef\u70b9\u4e0d\u4e00\u81f4\u3002"
        else:
            monitoring = (
                "\u5e73\u53f0%s\u516c\u91cc\uff1b\u8f68\u8ff9\u70b9%s\u4e2a\uff1b"
                "\u4e3b\u8981\u6d3b\u52a8\u533a\u57df%s\uff1b\u8f68\u8ff9\u53ef\u652f\u6301\u8d9f\u6b21\u6bd4\u4f8b%s"
            ) % (total_mileage, point_count, region, fmt_pct(support_rate, False))
            category = "\u91cd\u70b9\u8f66\u8f86\u8d9f\u6b21"
            problem = "\u7ebf\u8def\u65b9\u5411\u6709\u652f\u6301\uff0c\u4f46\u53ef\u652f\u6301\u8d9f\u6b21\u4e0d\u8db3"
            conclusion = "\u8d9f\u6b21\u4e0d\u8db3\uff0c\u8f68\u8ff9\u53ef\u652f\u6301\u6bd4\u4f8b%s" % fmt_pct(support_rate, False)
            evidence = "\u8f68\u8ff9\u8986\u76d6\u7533\u62a5\u7ebf\u8def\u65b9\u5411\uff0c\u4f46\u62b5\u8fbe\u7ebf\u8def\u7aef\u70b9\u7684\u9891\u6b21\u4e0d\u8db3\u3002"
 
        records.append(make_issue(
            item=item,
            category=category,
            problem=problem,
            scope=str(vehicle["plate"]),
            ledger_situation="\u53f0\u8d26\u7ebf\u8def%s\uff1b\u53f0\u8d26%s\u8d9f\uff0c%s\u516c\u91cc" % (
                route_text,
                fmt_num(vehicle["ledger"]["trips"], 0),
                fmt_num(vehicle["ledger"]["mileage"], 2),
            ),
            monitoring_situation=monitoring,
            conclusion=conclusion,
            evidence=evidence,
        ))
 
    return records
 
 
def display_units(value: Any) -> int:
    text = str(value or "")
    return sum(2 if ord(char) > 127 else 1 for char in text)
 
 
def estimated_row_height(values: Sequence[Any], widths: Sequence[float]) -> float:
    lines = 1
    for value, width in zip(values, widths):
        capacity = max(6, int(width * 0.86))
        value_lines = 0
        for part in str(value or "").split("\n"):
            value_lines += max(1, math.ceil(display_units(part) / capacity))
        lines = max(lines, value_lines)
    return max(44.0, min(170.0, 16.0 * lines + 12.0))
 
 
def style_cell(cell: Any, value: Any, font: Font, alignment: str) -> None:
    cell.value = value
    cell.font = font
    cell.border = BORDER
    cell.fill = PatternFill(fill_type=None)
    cell.alignment = Alignment(horizontal=alignment, vertical="center", wrap_text=True)
 
 
def write_workbook(records: Sequence[Dict[str, Any]], output_path: Path) -> None:
    workbook = Workbook()
    sheet = workbook.active
    sheet.title = "\u95ee\u9898\u6c47\u603b"
    sheet.sheet_view.showGridLines = False
 
    column_count = len(HEADERS)
    sheet.merge_cells(start_row=1, start_column=1, end_row=1, end_column=column_count)
    title_cell = sheet.cell(1, 1, "2026\u5e749\u6708\u4f01\u4e1a\u53f0\u8d26\u62bd\u67e5\u6838\u67e5\u95ee\u9898\u6c47\u603b\u8868")
    title_cell.font = TITLE_FONT
    title_cell.alignment = Alignment(horizontal="center", vertical="center")
    title_cell.border = Border(bottom=THIN)
    sheet.row_dimensions[1].height = 36
 
    for column, header in enumerate(HEADERS, start=1):
        style_cell(sheet.cell(2, column), header, HEADER_FONT, "center")
    sheet.row_dimensions[2].height = 47
 
    group_starts: List[Tuple[int, int]] = []
    current_enterprise = None
    group_start = 3
    for index, record in enumerate(records, start=1):
        row = index + 2
        if record["enterprise"] != current_enterprise:
            if current_enterprise is not None:
                group_starts.append((group_start, row - 1))
            current_enterprise = record["enterprise"]
            group_start = row
        values = [
            index,
            record["city"],
            record["enterprise"],
            record["category"],
            record["problem"],
            record["scope"],
            record["ledger"],
            record["monitoring"],
            record["conclusion"],
            record["evidence"],
        ]
        for column, value in enumerate(values, start=1):
            style_cell(sheet.cell(row, column), value, BODY_FONT, DATA_ALIGNMENTS[column - 1])
        sheet.row_dimensions[row].height = estimated_row_height(values, COLUMN_WIDTHS)
    if current_enterprise is not None:
        group_starts.append((group_start, len(records) + 2))
 
    for start_row, end_row in group_starts:
        if end_row > start_row:
            for column in (2, 3):
                sheet.merge_cells(start_row=start_row, start_column=column, end_row=end_row, end_column=column)
                cell = sheet.cell(start_row, column)
                cell.alignment = Alignment(horizontal="center", vertical="center", wrap_text=True)
                for row in range(start_row, end_row + 1):
                    sheet.cell(row, column).border = BORDER
 
    for column, width in enumerate(COLUMN_WIDTHS, start=1):
        sheet.column_dimensions[get_column_letter(column)].width = width
 
    page_capacity = 790.0
    header_height = float(sheet.row_dimensions[2].height or 0)
    used_height = sum(float(sheet.row_dimensions[row].height or 0) for row in (1, 2))
    for start_row, end_row in group_starts:
        group_height = sum(float(sheet.row_dimensions[row].height or 0) for row in range(start_row, end_row + 1))
        if used_height > 0 and used_height + group_height > page_capacity and start_row > 3:
            sheet.row_breaks.append(Break(id=start_row - 1))
            used_height = header_height
        used_height += group_height
 
    last_row = len(records) + 2
    sheet.print_area = "A1:J%d" % last_row
    sheet.print_title_rows = "2:2"
    sheet.freeze_panes = "A3"
    sheet.sheet_properties.pageSetUpPr = PageSetupProperties(fitToPage=True)
    sheet.page_setup.orientation = "landscape"
    sheet.page_setup.paperSize = sheet.PAPERSIZE_A3
    sheet.page_setup.fitToWidth = 1
    sheet.page_setup.fitToHeight = 0
    sheet.print_options.horizontalCentered = True
    sheet.print_options.verticalCentered = False
    # Keep at least a two-centimetre binding allowance on both sides.
    sheet.page_margins = PageMargins(left=0.8, right=0.8, top=0.35, bottom=0.35, header=0.2, footer=0.2)
    sheet.oddFooter.center.text = "\u7b2c &P \u9875\uff0c\u5171 &N \u9875"
    sheet.oddFooter.center.font = FANGSONG
    sheet.oddFooter.center.size = 9
 
    output_path.parent.mkdir(parents=True, exist_ok=True)
    workbook.save(output_path)
 
 
def validate_records(records: Sequence[Dict[str, Any]]) -> None:
    if len(records) != 40:
        raise RuntimeError("expected 40 issue records, got %d" % len(records))
    enterprise_names = {record["enterprise"] for record in records}
    city_names = {record["city"] for record in records}
    if len(enterprise_names) != 12 or city_names != {"\u5b9c\u660c", "\u9ec4\u5188", "\u54b8\u5b81"}:
        raise RuntimeError("enterprise or city grouping mismatch")
    counts: Dict[str, int] = {}
    for record in records:
        counts[record["category"]] = counts.get(record["category"], 0) + 1
    expected = {
        "\u5468\u8f6c\u91cf\u6c47\u603b": 1,
        "\u53f0\u8d26\u4e0e\u5e73\u53f0\u91cc\u7a0b": 11,
        "\u52a8\u6001\u76d1\u6d4b\u8986\u76d6": 16,
        "\u91cd\u70b9\u8f66\u8f86\u7ebf\u8def": 7,
        "\u91cd\u70b9\u8f66\u8f86\u8d9f\u6b21": 5,
    }
    if counts != expected:
        raise RuntimeError("category counts mismatch: %s" % counts)
 
 
def main() -> int:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--workbook", required=True)
    parser.add_argument("--diagnostics", required=True)
    parser.add_argument("--output", required=True)
    args = parser.parse_args()
 
    workbook_path = Path(args.workbook)
    diagnostics_path = Path(args.diagnostics)
    output_path = Path(args.output)
    if not workbook_path.is_file():
        raise SystemExit("workbook not found: %s" % workbook_path)
    if not diagnostics_path.is_file():
        raise SystemExit("diagnostics not found: %s" % diagnostics_path)
 
    enterprises = read_enterprises(workbook_path)
    diagnostics = json.loads(diagnostics_path.read_text(encoding="utf-8"))
    vehicles = diagnostics["vehicles"]
    if len(enterprises) != 12 or len(vehicles) != 12:
        raise RuntimeError("expected 12 enterprises and 12 sample vehicles")
    records = build_issue_records(enterprises, vehicles)
    validate_records(records)
    write_workbook(records, output_path)
    print(str(output_path))
    return 0
 
 
if __name__ == "__main__":
    raise SystemExit(main())