xyc
2026-11-11 f9ccdc1663bc98b1e068ab47c58887e3b482bc6d
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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Import enterprise-ledger inspection tasks, results, and evidence summaries."""
 
from __future__ import annotations
 
import argparse
import json
import os
import re
import sys
from datetime import date, datetime
from pathlib import Path
from typing import Any, Dict, Iterable, List, Optional, Sequence, Tuple
 
import pymysql
 
PROJECT_ROOT = Path(__file__).resolve().parents[1]
if str(PROJECT_ROOT) not in sys.path:
    sys.path.insert(0, str(PROJECT_ROOT))
 
from tools.build_enterprise_track_report import (  # noqa: E402
    conclusion_text,
    endpoint_text,
    risk_level,
    top_region_text,
)
from tools.enterprise_ledger_inspection import (  # noqa: E402
    PROFILES,
    SourceFile,
    aggregate_ledger,
    aggregate_tracks,
    default_vehicle_registry_path,
    load_h2032,
    load_vehicle_registry,
    parse_ledger,
    parse_track_summary,
    ratio_diff,
    safe_div,
    sha256_file,
    sha256_text,
)
from tools.enterprise_track_point_inspection import SELECTED_VEHICLES  # noqa: E402
 
 
def number(value: Any, default: float = 0.0) -> float:
    return default if value is None else float(value)
 
 
def chunked(items: Sequence[Tuple[Any, ...]], size: int) -> Iterable[Sequence[Tuple[Any, ...]]]:
    for index in range(0, len(items), size):
        yield items[index:index + size]
 
 
def insert_rows(cur: Any, table: str, columns: Sequence[str], rows: Sequence[Tuple[Any, ...]],
                batch_size: int = 500) -> int:
    if not rows:
        return 0
    sql = "INSERT INTO `%s` (%s) VALUES (%s)" % (
        table, ",".join("`%s`" % column for column in columns),
        ",".join(["%s"] * len(columns)),
    )
    total = 0
    for batch in chunked(rows, batch_size):
        cur.executemany(sql, batch)
        total += len(batch)
    return total
 
 
def execute_schema(conn: pymysql.connections.Connection, path: Path) -> None:
    statements = [item.strip() for item in path.read_text(encoding="utf-8").split(";") if item.strip()]
    with conn.cursor() as cur:
        for statement in statements:
            cur.execute(statement)
    conn.commit()
 
 
def unique_join(values: Sequence[str]) -> str:
    result: List[str] = []
    for value in values:
        if value and value not in result:
            result.append(value)
    return "\u3001".join(result)
 
 
def make_record_key(city: str, enterprise: str, plate: str, path_hash: str,
                    sheet: str, row_no: int, block_no: int) -> str:
    return sha256_text("|".join([
        city, enterprise, plate, path_hash, sheet, str(row_no), str(block_no),
    ]))
 
 
def parse_datetime(value: Any) -> Optional[datetime]:
    if value in (None, ""):
        return None
    if isinstance(value, datetime):
        return value
    return datetime.strptime(str(value), "%Y-%m-%d %H:%M:%S")
 
 
def source_file_rows(task_id: int, period: str, sources: Sequence[SourceFile]) -> List[Tuple[Any, ...]]:
    rows: List[Tuple[Any, ...]] = []
    seen = set()
    for source in sources:
        key = (source.source_type, source.path_hash)
        if key in seen:
            continue
        seen.add(key)
        rows.append((
            task_id, period, source.city, source.enterprise or None, source.source_type,
            source.path, Path(source.path).name, source.path_hash, source.sha256,
            source.size, source.sheet_name or None, source.source_rows,
            source.status, source.error or None,
        ))
    return rows
 
 
def month_days(period: str) -> int:
    year, month = [int(value) for value in period.split("-")]
    first = date(year, month, 1)
    next_month = date(year + (1 if month == 12 else 0), 1 if month == 12 else month + 1, 1)
    return (next_month - first).days
 
 
def build_task_rows(
    task_id: int,
    period: str,
    source_root: Path,
    work_root: Path,
    auth_vehicle_file: Optional[Path],
    h2032: Dict[str, Dict[str, Any]],
    diagnostics: Dict[str, Any],
) -> Tuple[List[Tuple[Any, ...]], List[Tuple[Any, ...]], List[Tuple[Any, ...]],
           List[Tuple[Any, ...]], List[Tuple[Any, ...]], List[SourceFile]]:
    registry_path = auth_vehicle_file or default_vehicle_registry_path(source_root, period)
    registry = load_vehicle_registry(registry_path, [profile.enterprise for profile in PROFILES])
    diagnostics_by_enterprise = {item["enterprise"]: item for item in diagnostics["vehicles"]}
    selected_by_profile = {spec.profile_key: spec.plate for spec in SELECTED_VEHICLES}
    enterprise_rows: List[Tuple[Any, ...]] = []
    route_rows: List[Tuple[Any, ...]] = []
    vehicle_rows: List[Tuple[Any, ...]] = []
    sample_rows: List[Tuple[Any, ...]] = []
    source_files: List[SourceFile] = []
    period_days = month_days(period)
 
    for profile in PROFILES:
        ledger_items, ledger_source = parse_ledger(profile, source_root)
        track_items, track_source = parse_track_summary(profile, work_root)
        source_files.append(ledger_source)
        ledger_vehicles, ledger_total = aggregate_ledger(ledger_items)
        track_vehicles = aggregate_tracks(track_items)
        report = h2032[profile.enterprise]
        authority = registry[profile.enterprise]
        active_track = {
            plate: item for plate, item in track_vehicles.items() if item["total_mileage"] > 0
        }
        matched = sorted(set(ledger_vehicles) & set(active_track))
        matched_ledger_turnover = sum(ledger_vehicles[plate]["turnover"] for plate in matched)
        track_estimated = sum(
            active_track[plate]["total_mileage"] * safe_div(
                ledger_vehicles[plate]["turnover"], ledger_vehicles[plate]["mileage"]
            )
            for plate in matched
            if ledger_vehicles[plate]["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())
        report_vs_ledger = ratio_diff(report["turnover_total"], ledger_total["turnover"])
        report_vs_ledger_freight = ratio_diff(report["freight_total"], ledger_total["freight"])
        report_vs_track = ratio_diff(report["turnover_total"], normalized)
        mileage_diff = ratio_diff(ledger_total["mileage"], track_mileage)
        no_track = ledger_total["vehicles"] - len(matched)
        no_track_rate = safe_div(no_track, ledger_total["vehicles"])
        diag = diagnostics_by_enterprise.get(profile.enterprise, {})
        raw_point_count = number(diag.get("points", {}).get("valid_point_count"))
        raw_file_count = number(diag.get("points", {}).get("file_count"))
        if report_vs_ledger is not None and abs(report_vs_ledger) <= 0.01:
            layer1 = "\u4e00\u81f4\uff08\u22641%\uff09"
        elif report_vs_ledger is not None and abs(report_vs_ledger) <= 0.05:
            layer1 = "\u8f7b\u5fae\u5dee\u5f02\uff081%-5%\uff09"
        elif report_vs_ledger is None:
            layer1 = "\u65e0\u6cd5\u6bd4\u8f83"
        else:
            layer1 = "\u5dee\u5f02\u8f83\u5927\uff08>5%\uff09"
        if mileage_diff is None:
            layer2 = "\u65e0\u5e73\u53f0\u91cc\u7a0b"
        elif abs(mileage_diff) <= 0.30:
            layer2 = "\u6b63\u5e38\uff08-30%\uff5e+30%\uff09"
        else:
            layer2 = "\u8d85\u51fa\u6b63\u5e38\u8303\u56f4\uff08<-30%\u6216>30%\uff09"
        note = "\u5b58\u5728\u65e0\u8f68\u8ff9\u8f66\u8f86" if no_track else ""
        severity = "\u9ad8" if (
            (report_vs_ledger is not None and abs(report_vs_ledger) > 0.05)
            or (mileage_diff is not None and abs(mileage_diff) > 0.30)
        ) else "\u4e2d" if (
            (report_vs_ledger is not None and abs(report_vs_ledger) > 0.01) or no_track > 0
        ) else "\u4f4e"
        conclusion = "\u7b2c\u4e00\u5c42\uff1a%s\uff1b\u7b2c\u4e8c\u5c42\uff1a%s\u3002" % (layer1, layer2)
        if note:
            conclusion += note + "\u3002"
        suggestion = "\u6838\u5bf9\u8f66\u8f86\u6e05\u5355\u3001\u8fd0\u5355\u3001\u8fc7\u78c5\u5355\u3001\u88c5\u5378\u8d27\u8bb0\u5f55\u4e0e\u8fd0\u8f93\u5408\u540c\u3002"
        enterprise_rows.append((
            task_id, period, profile.city, profile.enterprise, report.get("enterprise_code"),
            report.get("id"), report.get("vehicle_total"), report.get("vehicle_tractor"),
            authority.total, authority.main, report.get("freight_total"), report.get("turnover_total"),
            len(ledger_items), ledger_total["vehicles"], ledger_total["trips"],
            ledger_total["freight"], ledger_total["turnover"], ledger_total["mileage"],
            len(matched), matched_ledger_turnover, len(active_track), track_mileage,
            track_complete, track_abnormal, track_days,
            safe_div(track_days, len(active_track) * period_days) if active_track else None,
            1 if raw_point_count > 0 else 0, raw_file_count, raw_point_count,
            track_estimated, normalized, report_vs_ledger, report_vs_ledger_freight,
            report_vs_track, mileage_diff, no_track, no_track_rate, layer1, layer2, note,
            severity, conclusion, suggestion, ledger_source.path, track_source.path,
        ))
 
        for item in ledger_items:
            route_rows.append((
                task_id, period, item.city, item.enterprise, item.plate,
                item.plate_no_raw or None, item.trailer_plate_no or None, item.route or None,
                item.cargo_type or None, item.cargo_tons, item.trips, item.mileage_per_trip,
                item.total_mileage, item.freight, item.turnover, item.transport_date,
                item.source_file, item.source_path_hash, item.sheet_name, item.row_no,
                item.block_no,
                make_record_key(item.city, item.enterprise, item.plate, item.source_path_hash,
                                item.sheet_name, item.row_no, item.block_no),
            ))
 
        selected_plate = selected_by_profile.get(profile.key, "")
        for plate, ledger_item in ledger_vehicles.items():
            track_item = track_vehicles.get(plate)
            track_mileage_vehicle = track_item["total_mileage"] if track_item else None
            match_status = "\u5e73\u53f0\u660e\u7ec6\u65e0\u5339\u914d"
            if track_mileage_vehicle and track_mileage_vehicle > 0:
                match_status = "\u672c\u6b21\u62bd\u67e5\u8f66\u8f86" if plate == selected_plate else "\u5df2\u5339\u914d"
            first_date = min(track_item["days"]) if track_item and track_item["days"] else None
            last_date = max(track_item["days"]) if track_item and track_item["days"] else None
            vehicle_rows.append((
                task_id, period, profile.city, profile.enterprise, plate, ledger_item["routes"],
                ledger_item["trips"], ledger_item["freight"], ledger_item["turnover"],
                ledger_item["mileage"], safe_div(ledger_item["turnover"], ledger_item["mileage"]),
                track_mileage_vehicle,
                track_item["complete_mileage"] if track_item else None,
                track_item["abnormal_mileage"] if track_item else None,
                len(track_item["days"]) if track_item else 0, first_date, last_date,
                track_item["point_count"] if track_item else 0,
                number(diag.get("points", {}).get("file_count")) if plate == selected_plate else 0,
                number(diag.get("points", {}).get("valid_point_count")) if plate == selected_plate else 0,
                number(diag.get("points", {}).get("day_count")) if plate == selected_plate else 0,
                track_mileage_vehicle * safe_div(ledger_item["turnover"], ledger_item["mileage"])
                if track_mileage_vehicle and ledger_item["mileage"] > 0 else None,
                ratio_diff(ledger_item["mileage"], track_mileage_vehicle),
                track_item["anomaly_rate"] if track_item else None, match_status,
                "\u53f0\u8d26\u91cc\u7a0b%.2f\u516c\u91cc\uff0c\u5e73\u53f0\u91cc\u7a0b%s\u3002" % (
                    ledger_item["mileage"],
                    "\u65e0" if track_mileage_vehicle is None else "%.2f\u516c\u91cc" % track_mileage_vehicle,
                ),
            ))
 
        points = diag.get("points", {})
        comparison = diag.get("comparison", {})
        sample_rows.append((
            task_id, period, profile.city, profile.enterprise, selected_plate or None,
            "\u3001".join(points.get("missing_days", [])) or None,
            number(points.get("unique_point_count")), number(points.get("duplicate_point_count")),
            parse_datetime(points.get("first_time")), parse_datetime(points.get("last_time")),
            number(points.get("day_count")), comparison.get("raw_distance") or points.get("raw_distance"),
            comparison.get("raw_vs_platform_rate"), comparison.get("platform_vs_ledger_rate"),
            comparison.get("ledger_vs_platform_rate"), comparison.get("average_trip_mileage"),
            comparison.get("platform_supported_trips"), comparison.get("trip_support_rate"),
            endpoint_text(diag), top_region_text(diag), conclusion_text(diag), risk_level(diag),
        )) if diag else None
    return enterprise_rows, route_rows, vehicle_rows, sample_rows, source_files
 
 
ENTERPRISE_COLUMNS = (
    "task_id", "inspection_period", "city_name", "enterprise_name", "enterprise_code",
    "h2032_report_id", "month_vehicle_total", "month_tractor_count", "authority_vehicle_total",
    "authority_main_vehicle_count", "month_freight", "month_turnover", "ledger_route_count",
    "ledger_vehicle_count", "ledger_trips", "ledger_freight", "ledger_turnover", "ledger_mileage",
    "matched_vehicle_count", "matched_ledger_turnover", "tracked_vehicle_count", "track_mileage",
    "track_complete_mileage", "track_abnormal_mileage", "track_vehicle_days", "track_day_coverage",
    "raw_track_vehicle_count", "raw_track_file_count", "raw_track_point_count",
    "track_estimated_turnover", "normalized_track_turnover", "report_vs_ledger_rate",
    "report_vs_ledger_freight_rate", "report_vs_track_rate", "mileage_diff_rate",
    "no_track_vehicle_count", "no_track_vehicle_ratio", "layer1_status", "layer2_status", "note",
    "severity", "conclusion", "suggestion", "source_ledger_path", "source_track_path",
)
ROUTE_COLUMNS = (
    "task_id", "inspection_period", "city_name", "enterprise_name", "plate_no",
    "plate_no_raw", "trailer_plate_no", "route_text", "cargo_type", "cargo_tons", "trips",
    "mileage_per_trip", "total_mileage", "freight_tons", "turnover", "transport_date",
    "source_file", "source_path_hash", "sheet_name", "row_no", "block_no", "record_key",
)
VEHICLE_COLUMNS = (
    "task_id", "inspection_period", "city_name", "enterprise_name", "plate_no",
    "ledger_route_count", "ledger_trips", "ledger_freight", "ledger_turnover", "ledger_mileage",
    "turnover_per_km", "track_total_mileage", "track_complete_mileage", "track_abnormal_mileage",
    "track_days", "first_track_date", "last_track_date", "track_point_count", "raw_track_file_count",
    "raw_track_point_count", "raw_track_days", "track_estimated_turnover", "mileage_diff_rate",
    "anomaly_rate", "match_status", "conclusion",
)
SAMPLE_COLUMNS = (
    "task_id", "inspection_period", "city_name", "enterprise_name", "plate_no", "missing_days",
    "unique_point_count", "duplicate_point_count", "point_first_time", "point_last_time",
    "point_coverage_days", "point_path_mileage", "point_vs_platform_rate",
    "platform_vs_ledger_rate", "ledger_vs_platform_rate", "average_trip_mileage",
    "supported_trip_count", "trip_support_rate", "endpoint_check", "main_activity_regions",
    "route_conclusion", "risk_level",
)
SOURCE_COLUMNS = (
    "task_id", "inspection_period", "city_name", "enterprise_name", "source_type",
    "source_path", "source_name", "source_path_hash", "source_sha256", "file_size",
    "sheet_name", "source_rows", "status", "error_message",
)
 
 
def clear_task_data(cur: Any, task_id: int) -> None:
    for table in (
        "ledger_inspection_sample_vehicle", "ledger_inspection_vehicle",
        "ledger_inspection_route", "ledger_inspection_enterprise",
        "ledger_inspection_source_file", "ledger_inspection_report",
    ):
        cur.execute("DELETE FROM `%s` WHERE task_id=%%s" % table, (task_id,))
 
 
def upsert_task(conn: pymysql.connections.Connection, task_code: str, task_name: str,
                period: str, source_root: Path, work_root: Path) -> int:
    cities = unique_join([profile.city for profile in PROFILES])
    enterprises = unique_join([profile.enterprise for profile in PROFILES])
    plates = unique_join([spec.plate for spec in SELECTED_VEHICLES])
    with conn.cursor(pymysql.cursors.DictCursor) as cur:
        cur.execute(
            "INSERT INTO ledger_inspection_task "
            "(task_code,task_name,inspection_period,city_names,enterprise_names,sample_plate_nos,"
            "city_count,enterprise_count,sample_vehicle_count,source_root,work_root,status) "
            "VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,'RUNNING') "
            "ON DUPLICATE KEY UPDATE task_name=VALUES(task_name),inspection_period=VALUES(inspection_period),"
            "city_names=VALUES(city_names),enterprise_names=VALUES(enterprise_names),"
            "sample_plate_nos=VALUES(sample_plate_nos),city_count=VALUES(city_count),"
            "enterprise_count=VALUES(enterprise_count),sample_vehicle_count=VALUES(sample_vehicle_count),"
            "source_root=VALUES(source_root),work_root=VALUES(work_root),status='RUNNING',"
            "finished_at=NULL,started_at=CURRENT_TIMESTAMP",
            (task_code, task_name, period, cities, enterprises, plates,
             len({profile.city for profile in PROFILES}), len(PROFILES), len(SELECTED_VEHICLES),
             str(source_root), str(work_root)),
        )
        cur.execute("SELECT id FROM ledger_inspection_task WHERE task_code=%s", (task_code,))
        return int(cur.fetchone()["id"])
 
 
def import_all(
    conn: pymysql.connections.Connection,
    task_code: str,
    task_name: str,
    period: str,
    source_root: Path,
    work_root: Path,
    report_path: Path,
    diagnostics_path: Path,
    auth_vehicle_file: Optional[Path],
    schema_path: Path,
) -> Dict[str, Any]:
    diagnostics = json.loads(diagnostics_path.read_text(encoding="utf-8"))
    execute_schema(conn, schema_path)
    task_id = upsert_task(conn, task_code, task_name, period, source_root, work_root)
    h2032 = load_h2032(conn, period, [profile.enterprise for profile in PROFILES])
    enterprise_rows, route_rows, vehicle_rows, sample_rows, sources = build_task_rows(
        task_id, period, source_root, work_root, auth_vehicle_file, h2032, diagnostics
    )
    with conn.cursor() as cur:
        clear_task_data(cur, task_id)
        insert_rows(cur, "ledger_inspection_source_file", SOURCE_COLUMNS,
                    source_file_rows(task_id, period, sources), 100)
        insert_rows(cur, "ledger_inspection_enterprise", ENTERPRISE_COLUMNS, enterprise_rows, 100)
        insert_rows(cur, "ledger_inspection_route", ROUTE_COLUMNS, route_rows, 500)
        insert_rows(cur, "ledger_inspection_vehicle", VEHICLE_COLUMNS, vehicle_rows, 500)
        insert_rows(cur, "ledger_inspection_sample_vehicle", SAMPLE_COLUMNS, sample_rows, 100)
        insert_rows(cur, "ledger_inspection_report", (
            "task_id", "inspection_period", "report_type", "report_path",
            "report_sha256", "file_size",
        ), [(
            task_id, period, "TRACK_POINT_XLSX", str(report_path),
            sha256_file(report_path), report_path.stat().st_size,
        )], 10)
        cur.execute(
            "UPDATE ledger_inspection_task SET status='COMPLETED',finished_at=CURRENT_TIMESTAMP WHERE id=%s",
            (task_id,),
        )
    conn.commit()
    return {
        "task_id": task_id,
        "task_code": task_code,
        "inspection_period": period,
        "enterprise_count": len(enterprise_rows),
        "route_count": len(route_rows),
        "vehicle_count": len(vehicle_rows),
        "sample_vehicle_count": len(sample_rows),
        "source_file_count": len(source_file_rows(task_id, period, sources)),
    }
 
 
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", required=True)
    parser.add_argument("--report", required=True)
    parser.add_argument("--diagnostics", required=True)
    parser.add_argument("--auth-vehicle-file", default="")
    parser.add_argument("--schema", default=str(PROJECT_ROOT / "docs" / "sql_ledger_inspection.sql"))
    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"))
    args = parser.parse_args(argv)
    if not re.match(r"^\d{4}-(0[1-9]|1[0-2])$", args.period):
        raise SystemExit("period must use YYYY-MM")
    for label, file_path in (("source root", args.source_root), ("work root", args.work_root)):
        if not Path(file_path).is_dir():
            raise SystemExit("%s not found: %s" % (label, file_path))
    for label, file_path in (("report", args.report), ("diagnostics", args.diagnostics),
                             ("schema", args.schema)):
        if not Path(file_path).is_file():
            raise SystemExit("%s file not found: %s" % (label, file_path))
    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:
        result = import_all(
            conn,
            args.task_code or "LEDGER_SPOT_%s_R1" % args.period.replace("-", ""),
            args.task_name or "%s enterprise ledger spot check round 1" % args.period,
            args.period,
            Path(args.source_root),
            Path(args.work_root),
            Path(args.report),
            Path(args.diagnostics),
            Path(args.auth_vehicle_file) if args.auth_vehicle_file else None,
            Path(args.schema),
        )
        print(json.dumps(result, ensure_ascii=False, indent=2))
        return 0
    except Exception:
        conn.rollback()
        raise
    finally:
        conn.close()
 
 
if __name__ == "__main__":
    raise SystemExit(main())