feat(企业台账抽查): 完成2026年9月台账核查、轨迹落库及结果报告
| | |
| | | - 写入本地 `docs/工作日结/`,命名:`工作日结_<YYYY-MM-DD>.md`;**该目录已 gitignore,不入库**(给自己看)。 |
| | | - 内容至少包含:今天做了什么、测试结果摘要、遗留问题与待办、明天计划;当天无代码/测试工作也要写一句话说明。 |
| | | - 需要交接的部分:把"当前状态 + 待办"追加到 `HANDOFF.md`(同事的做法就是这样)。 |
| | | 3. **git 工作流(2026-09-03 用户授权,无需再询问是否推送;提交粒度参考同事 xyc)** |
| | | 3. **git 工作流(提交粒度参考同事 xyc;2026-10-27 改为验收通过后才可提交)** |
| | | - **一条提交 = 一个改动**:代码/脚本 + 该改动的说明文档(`HANDOFF.md` / 方案 / 口径清单)放在同一条提交里;不要为每个小改动单独建报告再单独提交。 |
| | | - message 写法(**对齐同事 xyc 风格;2026-10-09 用户确认**):`feat(模块): …` / `fix(模块): …` / `docs: …` / `docs(模块): …`,一句话说清"改了什么"。 |
| | | - **类型只用** `feat` / `fix` / `docs`(同事另有过少量 `chore`);不要自造类型。 |
| | | - **scope 用模块名**,中英均可——同事用过 `holiday` / `version` / `deploy` / `observation` 与 `交接` / `部署` / `节假日` / `汇总表`;**约 6 成提交不带 scope**(如 `docs: add …`),不带也合规。 |
| | | - **不写正文**(同事 91 条里 90 条无正文):全部信息放在主题这一行,不要 bullet、不要多段、不要署名或工具尾注。 |
| | | - 主题中位约 40 字(最长 119),可以长,但只讲**一件事**。 |
| | | - 待验收标注按第 5 条以 `(待验收)` 收尾,例:`fix(汇总大表): 四页取数月份列改按表头动态定位(待验收)`。 |
| | | - 只有用户明确说“验收通过”后才可提交;提交前未验收的改动不得写成“已完成/已验证”。 |
| | | |
| | | - **禁止入库**:临时脚本与调试产物(`_tmp_*`、`_shots/`、`outputs/`)、构建产物(jar / dist / target)、密钥与口令、大体积备份(`*.sql` 全库导出);过程日志与日结只留本地。 |
| | | - 推送前:先按上面完成测试,再 `git fetch origin` 与远端 `main` 对比合并(必要时解决冲突),确认无误后 commit 并 push 到公司 gitea(`http://61.183.254.94:3000/r/trafficAudit.git`,账号 zyj)。 |
| | | - 用户明确说“验收通过”后,才可执行提交;推送前先 `git fetch origin` 与远端 `main` 对比合并(必要时解决冲突),确认无误后 commit 并 push 到公司 gitea(`http://61.183.254.94:3000/r/trafficAudit.git`,账号 zyj)。 |
| | | - 若远端已有同事新提交:必须先合并/基于最新再推,禁止强推覆盖同事代码。 |
| | | - 公司 git 账号密码只通过本机 git 凭据/临时 askpass 使用,禁止写进仓库内任何文档或提交内容。 |
| | | |
| | | 4. **git 单仓库约定(2026-09-21 用户确认,替代 2026-09-07 的双仓库约定)** |
| | | - 本机只使用公司 gitea:`origin` = `http://61.183.254.94:3000/r/trafficAudit.git`(账号 zyj)。个人 gitee 仓库已不再使用,不要再把它当作 origin 或额外拉取源。 |
| | | - 拉取/推送一律走 `origin`(远端分支 `main`):先拉合并,禁强推,再 commit/push。 |
| | | - 拉取/推送一律走 `origin`(远端分支 `main`):用户验收通过后先拉合并,禁强推,再 commit/push。 |
| | | |
| | | |
| | | 5. **验收门禁(分级;2026-10-06 用户确认,参考同事 xyc 的做法)** |
| | | - **一般功能 / 修复 / 重构**:沿用现行规则——按第 1 条完成测试后即 commit + push,不等待人工验收。 |
| | | - **口径类 / 版式类 / 任何会改变输出数字或表格版式的改动**:代码与文档照常提交推送,但必须在 `HANDOFF.md` 对应段落标注 **【待验收】**,写清验收项与产物路径;用户验收通过后,再补一条 `docs(交接): …` 提交把状态改为「已验收(YYYY-MM-DD)」。 |
| | | - 未验收的改动,提交信息与交接段里禁止写成「已完成 / 已验证」,只能写「待用户验收」。 |
| | | - 例外优先:用户当次明确说「先不提交 / 等验收再提交」时,一切以用户当次指示为准。 |
| | | 5. **验收与提交门禁(2026-10-27 用户再次明确,替代以前的分级自动提交规则)** |
| | | - **所有改动一律先留在工作区,不得执行 `git commit`、不得 `git push`、不得创建提交。** |
| | | - 功能开发、修复、重构、口径、版式、数据处理等任何类型都没有例外;测试通过只代表可以交付验收,不代表可以提交。 |
| | | - 只有用户明确说出“验收通过”后,才可 commit + push;未明确说出这句话时,一律视为“待用户验收”。 |
| | | - 待验收阶段可以在 `HANDOFF.md` 写“待用户验收”及测试/核对结果,但不能写成“已完成/已验证”,也不能提交这些文档。 |
| | | - 用户如明确给出不同指示,以当次指示为准;否则本条第 1—4 项优先于其他旧的自动提交约定。 |
| | |
| | | - 2026-10-12(交接快照,用户准备新开对话):电脑重启后已用 `start-dev.ps1` 拉起前后端,脚本输出后端 OK、前端 OK;前端访问 http://localhost:8080,后端 8090,日志分别见 `backend.log` / `traffic-audit-web/frontend.log`。当前 git 分支 `main`,无已跟踪文件改动;工作区有 10-09 生成的未入库临时目录/文件(`_tmp_doc_compare/`、`_tmp_flow_table/`、`_tmp_holiday_verify/`、`_tmp_rail_label/`、`_tmp_pack_smoke_trend.docx`)及用户数据 `docs/专项统计/重要节假日/观测站分日调查数据 (2026年10月1日).xls`,不要删除或误提交。本轮未改代码、未跑测试、未提交。 |
| | | |
| | | - 2026-10-12(业务疑点核查,只读):企业上报的「厚坪-远安」「后坪到远安」两个地名已初核。可确认「后坪」在兴山县水月寺镇后坪一带(后坪林场、后坪磷矿附近),后坪磷矿公开资料还涉及榛子乡石柱村;「远安」指宜昌市远安县;「厚坪」在宜昌/兴山公开地名中未查到有效地点,判断大概率是「后坪」的错字或简称(另有「兴山厚坪物流有限公司」注册在峡口镇泗湘溪村,但公司名不能等同地名)。按水月寺镇后坪到远安县城的公开道路测算,单程约 106.7 km;企业均填 201 km,不能直接认定错误,需企业补充具体装货点、卸货点、单程/往返及绕行路线后再核。系统 `h2032_enterprise_monthly` 的审核说明中未留下这两处地点原文。 |
| | | |
| | | ## 2026-10-20 宜昌新增营运货车补贴材料 OCR 交接(下班快照) |
| | | |
| | | - 需求:宜昌交通投资 2025 年货车“两新”材料识别,重点核验购车发票“价税合计”。只关注新增车辆,不关注报废车辆;OCR 读不到合计时必须报警,不能静默通过。 |
| | | - 源目录:`D:\03_公司\02_项目\27_湖北省道路运输事业发展中心\10_业务\205_投资\宜昌交通投资(2025年货车两新资料,2026年9月28日报送)` |
| | | - 已盘点:93 份 PDF、1 张 `鄂E58048发票.jpg`、1 份汇总 Excel;PDF 合计约 961 页、约 490 MB。Excel 共 251 台车,序号 1–251,车牌和购置价格均有值,“已取得申请表”均为“是”。 |
| | | - 已按材料结构提取 251 张发票页到 `_tmp_ocr_yichang_invoice_pages\invoice-001.png` 至 `invoice-251.png`,150 dpi 渲染无报错。任务清单在 `_tmp_ocr_yichang_tasks.json`。 |
| | | - 特殊文件 `205-208.鄂E22606D-鄂E15509D(4台).pdf` 只有 10 页,结构为 2 页申请表 + 每台车 2 页(行驶证/运输证、发票);已按其第 4、6、8、10 页提取。4 台样张的价税合计初步稳定识别为 570000、570000、570000、585000。 |
| | | |
| | | ### 当前批量 OCR 进度 |
| | | |
| | | - 使用本地 RapidOCR,结果在 `_tmp_ocr_yichang_ocr_results\ocr-001.json` 至 `ocr-251.json`。 |
| | | - **当前已完成 78/251 张**;下班前已手动停止 OCR 进程,确认没有残留的 `_tmp_ocr_yichang_batch.py` 或其 multiprocessing 子进程。 |
| | | - 当前结果分布: |
| | | - `MATCH`:71 张,OCR 价税合计与 Excel 购置价格一致。 |
| | | - `ALERT_NO_TOTAL`:4 张,序号 15(鄂E68362,期望 385000)、129(鄂E58048,期望 255800)、130(鄂E84439,期望 255800)、164(鄂E14559D,期望 440000)。 |
| | | - `MISMATCH`:3 张,序号 136(OCR 4968.00,期望 496800)、185(OCR 582000,期望 390000)、186(OCR 390000,期望 582000)。 |
| | | - **这 78 条只能视为“金额初步比对结果”,不能直接视为业务核验通过。** 发票原文中的 VIN、申请表填写值、补贴标准尚未完成全量核验。 |
| | | |
| | | ### 已确认的问题与判断 |
| | | |
| | | 1. 序号 136 是 OCR 小数位解析问题,不是已经确认的业务金额不符:原文 OCR 为 `¥4968.00.00`,同一张发票还识别出中文大写“肆拾玖万陆仟捌佰圆整”,金额应为 496800。后续解析器需要支持重复小数点/OCR 拼接,并以中文大写和“价税合计”上下文交叉校验。 |
| | | 2. 序号 185/186 的金额互换,说明不能简单按 PDF 页面顺序绑定 Excel 序号。`185、186.鄂E99440、鄂E10295D.pdf` 的第 5、8 页分别读到 582000、390000,但 Excel 中 185 为 390000、186 为 582000。后续必须用发票 VIN 与申请表/行驶证 VIN 建立车辆级映射,或至少按材料页中的车牌进行匹配;仅按页码顺序会误报。 |
| | | 3. 序号 129(鄂E58048)另有一张独立 `鄂E58048发票.jpg`,尚未与 PDF 第 11 页做交叉核对;不能假定两者内容相同。 |
| | | 4. 手写申请表样张识别效果明显差于印刷发票:车牌有时可读,VIN、补贴标准等关键字段无法稳定读出。当前结论是手写内容只能辅助定位、不能作为自动通过依据;正式功能应要求印刷体/结构化字段,或对低置信度人工复核。 |
| | | 5. 普通印刷发票在 150 dpi 下可识别,但当前批量环境单页耗时波动较大(实测平均约 18.8 秒/页,2 进程时)。批量脚本已改为 6 进程,已有 JSON 会跳过,可断点续跑。 |
| | | |
| | | ### 明天续跑方法 |
| | | |
| | | ```powershell |
| | | Set-Location 'D:\Codex\MyProject\trafficAudit' |
| | | & 'D:\python38\python.exe' _tmp_ocr_yichang_batch.py |
| | | ``` |
| | | |
| | | - 脚本:`_tmp_ocr_yichang_batch.py`;结果:`_tmp_ocr_yichang_ocr_results\`;任务:`_tmp_ocr_yichang_tasks.json`;清单:`_tmp_ocr_yichang_inventory.json`。 |
| | | - 续跑会跳过已有结果,不会重做前 78 张。临时文件不要删除、不要提交。 |
| | | - 剩余步骤: |
| | | 1. 跑完 251 张,汇总 `MATCH / ALERT_NO_TOTAL / MISMATCH` 数量。 |
| | | 2. 对所有 `ALERT_NO_TOTAL` 和 `MISMATCH` 用 300 dpi 重新渲染并复核,区分低清、版式偏移、页序错位、金额小数误读和真实不一致。 |
| | | 3. 修正重复小数点、`¥`/`¥`、金额被拆成多个文本框等解析问题,同时保留“无法确认即报警”。 |
| | | 4. 用发票 VIN 与申请表/行驶证建立车辆级映射,不能只依赖 PDF 页面顺序。 |
| | | 5. 单独处理 `鄂E58048发票.jpg`,与 PDF 对应页核对。 |
| | | 6. 若后续接入软件,申请表手写字段必须设置低置信度/无法识别的人工复核门槛,不能自动放行。 |
| | | |
| | | ### 约束 |
| | | |
| | | - 本轮和后续识别均未修改、编译或接入软件业务代码;临时 OCR 脚本和结果仅供本次业务验证。 |
| | | - 未执行任何数据导入、覆盖或重导。 |
| | | - 工作区原有未提交改动不属于本轮,不要回滚;临时目录和用户数据不要删除或误提交。 |
| | | ## 2026-10-22 宜昌新增营运货车材料 OCR 验证最终交接(最新,覆盖 10-20 进度) |
| | | |
| | | ### 新对话先看 |
| | | |
| | | - 第一步:读根目录 `AGENTS.md` 和本段交接。当前阶段是 OCR 与材料核验,用户尚未授权把功能接入软件。 |
| | | - 当前待办:先人工确认序号 130(鄂E84439)的发票价税合计;之后做购车发票 VIN 与申请表 VIN 的逐车一致性核验。 |
| | | - 工作边界:不修改或编译业务代码,不导入、覆盖或重导数据,不删除临时 OCR 文件和用户材料,不回滚工作区原有改动。 |
| | | - 逐车金额结果:`_tmp_ocr_yichang_final_summary.csv`;手写无法识别汇总:`_tmp_ocr_yichang_unreadable_review\unreadable_handwriting_review.pdf`。 |
| | | |
| | | |
| | | ### 结论 |
| | | |
| | | - 源目录:`D:\03_公司\02_项目\27_湖北省道路运输事业发展中心\10_业务\205_投资\宜昌交通投资(2025年货车两新资料,2026年9月28日报送)` |
| | | - 范围:只核新增营运货车,不处理报废车辆。目录含 93 份 PDF、1 张 `鄂E58048发票.jpg`、1 份汇总 Excel;Excel 共 251 台车。 |
| | | - 购车发票“价税合计”识别效果可用:251 张发票页中,150 dpi 首轮直接一致 232 张;经 300/600 dpi 复核、中文大写金额校验、独立 JPG 补读和车辆页序校正后,250 张可确认与 Excel 购置价格一致,1 张必须报警人工复核。 |
| | | - 申请表手写内容不适合自动放行。45 份手写申请表中,车牌无法完整准确自动识别 43 份、VIN 无法完整准确自动识别 45 份、补贴标准无法准确自动识别 18 份、三项均无法识别 18 份。 |
| | | - 本轮仍为 OCR 验证,没有修改、编译或接入软件业务代码,没有导入/覆盖/重导数据,也没有提交 git。 |
| | | |
| | | ### 发票价税合计最终结果 |
| | | |
| | | - 完整逐车结果:`_tmp_ocr_yichang_final_summary.csv`。 |
| | | - 唯一必须报警项:序号 130,车牌 `鄂E84439`,Excel 购置价格 255800;来源 `127-131.鄂E67180-鄂E72050(5台).pdf` 第 14 页。小写金额未稳定读出,中文大写 OCR 多处缺字,只疑似“贰拾伍万伍仟捌佰圆整”,不能自动通过。 |
| | | - 序号 129 `鄂E58048`:PDF 发票页严重低清,但目录中的独立 `鄂E58048发票.jpg` 可稳定读出 255800.00。 |
| | | - 序号 185/186:`185、186.鄂E99440、鄂E10295D.pdf` 的材料页序与 Excel 序号相反。按运输证车牌关联发票后,鄂E99440 为 390000、鄂E10295D 为 582000,均一致;不能按固定页码顺序绑定 Excel 行。 |
| | | - 常见误识别: |
| | | - `¥3:63000.00` 需规范化为 363000。 |
| | | - `¥4968.00.00` 需结合中文大写“肆拾玖万陆仟捌佰圆整”校验为 496800。 |
| | | - 部分发票同时出现价税合计 `466000.00` 和不含税价 `412389.38/412399.38`;必须优先取“价税合计/小写”行,不能取距离最近的任意金额。 |
| | | - 部分页面价税合计标签被识别成“阶税奇计”“价配合计”“斤税合计”等,需结合“小写”和中文大写校验。 |
| | | - 结果口径:250 张是“发票价税合计与 Excel 购置价格一致”;发票 VIN 与申请表 VIN 的全量一致性尚未完成,不能把 250 张理解为完整业务审核通过。 |
| | | |
| | | ### 申请表结构及手写统计 |
| | | |
| | | - 93 份 PDF 的申请表页共 212 页,包括车辆数据页、补贴标准/签字审批续页。 |
| | | - 按第一页车牌填写清晰度和 OCR 置信度分类:手写申请表 45 份,对应 117 个申请表扫描页、覆盖 173 台车;打印/电子填写 48 份,对应 95 页。 |
| | | - 45 份手写表中按“可直接自动采用”口径统计: |
| | | - 车牌号无法完整准确识别:43 份。 |
| | | - 车辆识别代号(VIN)无法完整准确识别:45 份。 |
| | | - 补贴标准无法准确识别:18 份;判定要求标签附近能读出 20000~100000 且为 5000 整数倍的合理金额。 |
| | | - 车牌、VIN、补贴标准三项均无法识别:18 份。 |
| | | - 注:部分车牌肉眼可辨,但 OCR 会多字母、少字符或错一位;这些不能算自动识别成功,必须人工复核。 |
| | | |
| | | ### 复核产物(临时文件,不要删除、不要提交) |
| | | |
| | | - 无法识别手写内容汇总 PDF:`_tmp_ocr_yichang_unreadable_review\unreadable_handwriting_review.pdf` |
| | | - 车辆数据区 45 份,共 5 张汇总图。 |
| | | - 补贴标准无法识别 18 份,共 2 张汇总图。 |
| | | - 单份裁剪图分别在 `vehicle_fields\`、`subsidy_fields\`,索引为 `index.csv`。 |
| | | - 发票逐车结果:`_tmp_ocr_yichang_final_summary.csv`。 |
| | | - 251 张发票页:`_tmp_ocr_yichang_invoice_pages\`。 |
| | | - 251 份原始 OCR JSON:`_tmp_ocr_yichang_ocr_results\`。 |
| | | - 300/600 dpi 异常复核:`_tmp_ocr_yichang_recheck_300\`、`_tmp_ocr_yichang_recheck_600\`、`_tmp_ocr_yichang_recheck_results\`、`_tmp_ocr_yichang_recheck_600_results\`。 |
| | | - 93 张申请表首页:`_tmp_ocr_yichang_app_all_150\`;OCR 结果:`_tmp_ocr_yichang_app_all_results\`。 |
| | | - 手写表续页:`_tmp_ocr_yichang_app_hand_pages\`;OCR 结果:`_tmp_ocr_yichang_app_hand_results\`。 |
| | | |
| | | ### 后续实现建议 |
| | | |
| | | 1. 先人工确认序号 130 的发票价税合计;这是当前唯一金额报警项。 |
| | | 2. 如果用户明确要求接入软件,再实现功能;不要擅自导入用户材料或修改业务代码。 |
| | | 3. 发票页识别流程应固定为:300 dpi 渲染 → 找“价税合计/小写”行 → 解析小写数字 → 解析中文大写交叉校验 → 排除“不含税价” → 无法一致时报警。 |
| | | 4. 发票必须按车牌/VIN 与车辆级材料关联,不能只按 PDF 页码顺序绑定 Excel。 |
| | | 5. 手写申请表需提供“原图裁剪 + 人工确认”界面;车牌、VIN、补贴标准任一低置信度都不得自动通过。 |
| | | 6. 发票 VIN 与申请表 VIN 的全量比对仍未完成,是下一阶段业务核验的主要待办。 |
| | | |
| | | ### 当前进程状态 |
| | | |
| | | - 所有 OCR 进程已结束,没有残留 `_tmp_ocr_yichang*` Python 进程。 |
| | | - 工作区原有未提交代码/配置改动不属于本轮,不要回滚;临时 OCR 目录和用户数据不要删除或误提交。 |
| | | |
| | | ## 2026-10-26 客运企业统计与 OCR 双线交接(用户准备新开对话) |
| | | |
| | | ### 新对话先看 |
| | | |
| | | - 第一步:读根目录 `AGENTS.md` 和本段交接。涉及业务数据时,先按当前应用配置确认数据库;本轮只读库为 `localhost:3305/traffic_audit`。 |
| | | - 用户对措辞有明确要求:“看看、查一下、调查、核对、分析”只表示只读检查;除非用户明确说“改、重新做、生成、恢复、更新”,否则不得修改数据库、重做 Excel 或调整已确认口径。 |
| | | - 当前工作区本来就有未提交改动,不要回滚、覆盖或删除。`HANDOFF.md`、`traffic-audit-server/pom.xml` 有已跟踪改动;`docs/专项统计/重要节假日/观测站分日调查数据 (2026年10月1日).xls`、`traffic-audit-server/src/main/java/com/trafficaudit/subsidy...`、`traffic-audit-server/src/main/resources/ocr/` 等为未跟踪文件。 |
| | | - OCR 事项尚未结束,不能关闭或删除相关临时材料;具体要求沿用下方“OCR 待办”。 |
| | | |
| | | ### 2026年9月与2025年9月企业范围 |
| | | |
| | | - `h2031_enterprise_monthly` 中,2025年9月有月报 796 家,2026年9月有月报 767 家;按企业代码去重后,两期都有月报的持续企业 **735 家**,仅2025年9月 61 家,仅2026年9月 32 家。 |
| | | - 735 家中,两期都有班线或包车业务 695 家;两期都有班线业务 395 家;两期都有包车业务 365 家;两期同时兼有班线和包车 65 家(395 + 365 - 65 = 695);14 家两期有月报但两期均无业务。 |
| | | - 6 家两期名称变化,企业代码不变: |
| | | - `914201005655611472`:武汉浩程汽车租赁有限公司 -> 武汉市浩程旅游客运有限公司 |
| | | - `9142022288156098XY`:阳新县汽车运输公司 -> 阳新交建客运联营有限公司 |
| | | - `914203237641338318`:竹山城乡公交客运有限责任公司 -> 竹山县城乡运输有限责任公司 |
| | | - `91420683753442137F`:枣阳市益成运输有限公司 -> 枣阳市益成汽车运输有限公司 |
| | | - `91429004181663937H`:仙桃市第二汽车运输总公司 -> 仙桃市天顺运输有限公司 |
| | | - `91429004181688771B`:仙桃市仙运公司 -> 仙桃市仙运交通运输有限公司 |
| | | - 735 家完整名单已在上一轮对话输出,可用上述代码交集重新查询;不在交接文档里重复 735 行。 |
| | | |
| | | ### 规上企业所属市州与平均运距分析 |
| | | |
| | | - 市州归属以 H2032 月报的 `region_code` 为准,不用企业代码猜。映射规则:取前 4 位(`4201` 武汉、`4202` 黄石、`4203` 十堰、`4205` 宜昌、`4206` 襄阳、`4207` 鄂州、`4208` 荆门、`4209` 孝感、`4210` 荆州、`4211` 黄冈、`4212` 咸宁、`4213` 随州、`4228` 恩施);直管地区优先匹配 `429004` 仙桃、`429005` 潜江、`429006` 天门、`429021` 神农架林区。项目实现见 `RegionUtil.java`。 |
| | | - 2026年9月 `h2032_enterprise_monthly` 共 636 家,`region_code` 缺失 0 家;2025年各月及2026年各月当前均无缺失。 |
| | | - 运距口径:`Σ货物周转量 ÷ Σ货运量`,不是企业平均运距的简单算术平均。库内逐企业 `avg_distance` 与该公式一致,单位为公里。 |
| | | - 本次“连续两年在规企业”按 **2025年9月与2026年9月同月**、同企业代码、且两期 `freight_total > 0` 和 `turnover_total > 0` 取数,共 **537 家**。这个 537 与“两期都有月报的 735 家”不是同一口径,不能混用。 |
| | | - 537家结果:2025年9月全省运距 146.778588 公里,2026年9月 159.312626 公里,同比 +8.5394%。分市州结果见 Excel: |
| | | `D:\Codex\MyProject\trafficAudit\outputs\01a16115-ae39-7950-987c-12cb78882468\各市州连续两年在规企业运距及同比_2025-09_2026-09.xlsx` |
| | | - 仙桃市没有企业同时满足两期有效货运数据条件,Excel 中保留该市行,运距及同比为空。 |
| | | |
| | | ### 公路客运三张企业清单与已确认口径 |
| | | |
| | | - 最终确认口径:班线 **401家**、包车 **397家**、班线+包车合计 **767家**。不要擅自改回 402 家或剔除全零企业;用户曾明确纠正过擅自重做。 |
| | | - 输出目录: |
| | | `D:\Codex\MyProject\trafficAudit\outputs\01a16115-ae39-7950-987c-12cb78882468` |
| | | - 三个文件: |
| | | - `公路客运企业班线经营情况_2026年9月及1-9月_同比清单.xlsx` |
| | | - `公路客运企业包车经营情况_2026年9月及1-9月_同比清单.xlsx` |
| | | - `公路客运企业班线+包车合计_2026年9月及1-9月_同比清单.xlsx` |
| | | - 三张表均 21 列,字段单位已补齐;同比后已有增量字段;没有背景色、没有 Excel 表格对象。生成脚本在输出目录 `_work` 下。 |
| | | - 生成 Excel 后不要在屏幕右侧自动打开,只告诉用户文件位置。 |
| | | |
| | | ### 合计表“1-9月客运量”差异结论(重要,尚未按用户指令修改) |
| | | |
| | | - 合计 Excel 的“全省班线+包车指标”实际是 **2026年9月仍存在的767家企业同口径累计**,不是全省逐月全部企业累计。脚本在 `build_total_performance.mjs` 中先过滤 `current_total_business === 1`,再对767家求和。 |
| | | - 2026年1-9月: |
| | | - 全省逐月全部企业合计:**14248.9028万人** |
| | | - Excel 按2026年9月767家范围累计:**13738.5988万人** |
| | | - 差额:**510.3040万人** |
| | | - 差额来源:37家企业1-8月有月报、9月无相同企业代码,其中19家有客运量。最大的“长江三峡旅游发展有限责任公司运输分公司”1-8月用旧代码 `914205007959186665`,累计472.4304万人;9月改为新代码 `91420500747677685M`、名称“长江三峡旅游发展有限责任公司”,9月56.0381万人已进入767家范围。旧代码1-8月的472.4304万人被漏在累计之外,占差额约92.6%。 |
| | | - 2025年1-9月同样存在范围差异:全省全部企业累计15365.1834万人;按2026年9月767家范围回溯累计14238.7090万人。 |
| | | - 当前 Excel 的1-9月同比 -3.51% 是767家同口径同比;全省全部企业口径同比约 -7.27%。9月当月1557.4529万人与数据库9月全量一致,差异只在累计及同比。 |
| | | - 用户已表示“明白了”,但**尚未明确选择以后采用“全省全量累计”还是“767家同口径累计”**。下一步若用户明确要求改表,再按其选定口径重做;不要自行修改。 |
| | | |
| | | ### 其他业务口径备查 |
| | | |
| | | - 班线客运量 = `passenger_total - passenger_charter`;班线周转量 = `turnover_total - turnover_charter`。 |
| | | - 班线业务判定:班线车辆数 > 0,或班线客运量/周转量 > 0;包车业务判定:包车车辆数 > 0,或包车客运量/周转量 > 0。 |
| | | - 新能源车常见统计口径:纯电动、插电式混合动力、燃料电池汽车算新能源;普通不插电油电混动、普通气电混动、甲醇、天然气一般不算;氢气需区分燃料电池(算)和氢内燃机(通常不算)。最终以机动车登记信息或工信部新能源车型目录为准。 |
| | | |
| | | ### OCR 待办(沿用 2026-10-22 最终交接) |
| | | |
| | | - 宜昌新增营运货车材料仍未接入软件。251台车中,250张购车发票“价税合计”已确认与 Excel 购置价格一致;唯一金额报警项为序号130、车牌 `鄂E84439`、Excel价格255800,仍需人工确认。 |
| | | - 下一阶段主要待办:完成购车发票 VIN 与申请表/行驶证 VIN 的逐车一致性核验。手写申请表不能自动放行,车牌、VIN、补贴标准任一低置信度都要人工复核。 |
| | | - 逐车金额结果:`_tmp_ocr_yichang_final_summary.csv`;手写复核汇总:`_tmp_ocr_yichang_unreadable_review\unreadable_handwriting_review.pdf`。 |
| | | - 临时 OCR 文件、结果和用户材料不要删除、不要误提交;本轮没有运行 OCR 进程。 |
| | | |
| | | ### 本轮工作边界与下一步 |
| | | |
| | | - 本轮仅做数据库只读查询和 Excel 产物生成/核对;没有修改业务代码、没有导入/覆盖/重导数据。 |
| | | - 已生成的文件都在 `outputs`(gitignored),临时脚本和预览图不要删除或误提交。 |
| | | - 新对话下一步优先级: |
| | | 1. 等用户明确说明合计表累计口径是否调整,再决定是否重做。 |
| | | 2. 若用户继续客运统计,先确认期间、企业范围和单位,再执行只读查询。 |
| | | 3. 若用户回到 OCR,先人工确认序号130,再做 VIN 逐车比对,未经授权不接入软件。 |
| | | |
| | | ## 2026-10-27 新对话交接(前后端已启动;OCR 暂停) |
| | | |
| | | ### 新对话先看 |
| | | |
| | | - 第一步:读根目录 `AGENTS.md` 和本段交接。此后每次开发任务开始时,先检查并按需执行 `start-dev.ps1` 拉起前后端。 |
| | | - 用户 2026-10-27 已明确:**OCR 是之前的任务,现在不需要继续做**。本文件前面的 OCR 内容保留备查,但新对话不要主动续跑 OCR、不要启动相关批处理,也不要在未经明确要求时把 OCR 接入软件。 |
| | | - “看看、查一下、核对、分析”仍然只表示只读检查;未经用户明确说“改、重新做、生成、恢复、更新”,不要修改数据库、业务文件、Excel 公式或已确认口径。 |
| | | - 除非用户明确要求导入,否则不要执行任何数据导入、覆盖或重导。 |
| | | |
| | | ### 当前启动状态 |
| | | |
| | | - 电脑重启后已执行 `powershell -NoProfile -ExecutionPolicy Bypass -File start-dev.ps1`,脚本返回“后端 OK,前端 OK”。 |
| | | - 前端:http://localhost:8080 ,已返回 HTTP 200。 |
| | | - 后端:http://localhost:8090 ,已返回 HTTP 200。 |
| | | - 日志:`backend.log`、`traffic-audit-web/frontend.log`。 |
| | | - 本次仅启动服务,没有修改代码,没有运行测试,没有提交 Git。 |
| | | |
| | | ### 咸宁轨迹与企业台账核查(已完成,属于业务只读分析) |
| | | |
| | | - `鄂L1N523` 已完成 2026 年 9 月轨迹与企业台账核对,结论是存在实质性、根本性不符,不是普通统计误差: |
| | | - 企业申报 45 趟、线路里程 16,740 公里;轨迹原始累计仅 4,248.21 公里,只相当于申报里程的 25.38%,少 12,491.79 公里。 |
| | | - 10 个轨迹文件、17,656 个定位点全部在湖北省内;天津 0 点、崇阳 0 点,最远距公司驻地 56.15 公里。 |
| | | - 实际活动主要集中在咸安区、赤壁市,9 月 8-9 日延伸到武汉江夏;无法支持“咸宁/天津”“咸宁/崇阳”两条申报线路。 |
| | | - 台账“咸宁/崇阳”周转量公式存在无说明的 366 吨公里调减。 |
| | | - 结论文件:`outputs\01a16115-ae39-7950-987c-12cb78882468\鄂L1N523_轨迹与企业报送台账核对_2026年9月.xlsx`;分析文件:同名目录下 `鄂L1N523_轨迹与台账核对分析_2026年9月.xlsx`。 |
| | | - `鄂L1J689`:用户补齐 2026-09-19 至 09-30 轨迹后已完成复核;源轨迹、分析明细和台账均在 `咸宁\德敏` 目录。临时解析脚本为 `_tmp_analyze_L1J689.py`。 |
| | | - `鄂L1K202`:已在 `咸宁\惠侬` 目录按轨迹与台账路线完成比对;未修改台账。 |
| | | - `鄂L5A039`:已完成路畅通轨迹分析。用户确认 `车辆轨迹分析明细_咸宁_路畅通.xls` 只有 1-18 日轨迹,与已有历史轨迹口径一致,不要把 19-30 日缺失简单理解为车辆零公里。 |
| | | - 以上轨迹核查均未导入、覆盖或重导业务数据;原始用户文件和临时分析文件不要删除、不要误提交。 |
| | | |
| | | ### Excel 核查状态 |
| | | |
| | | - 原文件 `工作簿1 - 计算错误7→9.xlsx` 的“汇总”第 14、15 行共有 34 个公式误除以 7,按 1-9 月口径应除以 9,原结果因此偏大约 28.57%;此外 `Sheet1` 有两处 `#DIV/0!`。 |
| | | - 用户修改后的 `工作簿1.xlsx` 已核对:第 14、15 行公式已改为除以 9;`1-9月轨迹里程` 整行为空属于确认过的正常情况,不需要补数。 |
| | | - 本轮没有修改上述 Excel;以后代用户检查提交前文件时,应优先检查月度累计公式的除数、空行口径和缓存公式错误。 |
| | | - `咸宁_德敏.xlsx` 的 Sheet1 `M53` 显示 4707.3、用户认为应为 4706 的差异已经讨论过;用户明确表示不用改数值,后续不要自行修改。 |
| | | |
| | | ### 工作区与待办 |
| | | |
| | | - 当前分支为 `main`;工作区本来就有未提交内容,不要回滚、覆盖或清理。已知包括 `HANDOFF.md`、`traffic-audit-server/pom.xml`,以及未跟踪的节假日用户数据、`subsidyaudit` 代码和 OCR 资源。 |
| | | - 本轮没有需要继续处理的轨迹/Excel 待办;下一步等待用户给出新的明确任务。 |
| | | - 新对话如继续业务核查,先确认期间、企业/车辆范围和输出口径;如继续开发,先启动并验证 8080/8090,再按 `AGENTS.md` 的测试与提交流程执行。 |
| | | |
| | | |
| | | ## 2026-10-27 企业台账抽查核查阶段一(总体及车辆里程) |
| | | |
| | | - 用户明确核查分三层:先核月报与台账,再核台账里程与平台里程,最后精查逐点轨迹。当前只生成前两层,供用户按车辆全月里程差异率选车。 |
| | | - 【待验收】输出文件:`D:\03_公司\02_项目\27_湖北省道路运输事业发展中心\10_业务\280_厅里抽查企业台账\2026\9月\work\2026年9月企业台账抽查核查结果_总体及车辆里程_20261027.xlsx`。包含“总体情况”和“车辆里程差异情况”两页,共12家企业、579台台账车辆,其中515台匹配平台车辆日明细。 |
| | | - 第一层月报与台账:11家企业周转量差异率绝对值不超过1%;宜昌凯祥达月报18,024,120吨公里、台账明细逐行合计11,990,746.03吨公里,差异50.3169%,需后续核实台账明细与月报汇总口径。 |
| | | - 第二层企业级台账/平台里程差异率以及579台车辆逐车差异率已生成。64台台账车辆没有平台车辆日明细,统一留空并标注“平台明细无匹配”,没有按零公里处理。 |
| | | - 生成脚本:`tools/enterprise_ledger_inspection.py`,当前阶段命令使用 `--overview-only`。本阶段未写数据库、未导入/覆盖/重导数据、未修改企业源台账。 |
| | | - 本地测试记录:`docs/功能测试报告/功能测试报告_企业台账抽查总体及车辆里程_2026-10-27.md`(gitignored)。 |
| | | - 下一步等待用户从“车辆里程差异情况”确定每家企业抽查车辆;之后再生成逐点轨迹核查页,并完善 `ledger_inspection_*` 表的月度任务、抽查车辆、证据状态和问题明细字段后执行落库。 |
| | | |
| | | ## 2026-10-27 轨迹里程模板适配与 2026 年 1—9 月导入(待验收) |
| | | |
| | | - 【待验收】依据更新后的 `docs/货运/模板_轨迹里程.xlsx` 完成 `vehicle_track_mileage` 表、导入代码、审核查询和数据查看页面适配。 |
| | | - 表新增 `enterprise_category`(`ABOVE_SCALE` 规上企业 / `PASSENGER` 两客企业)和 `anomaly_mileage`;唯一键为 `report_period + enterprise_category + enterprise_name`。迁移脚本:`docs/sql_vehicle_track_mileage_template_migration.sql`。 |
| | | - 导入器现扫描工作簿全部 Sheet,按核心表头定位,兼容表头不在首行及历史文件无异常里程列;同月重导使用事务覆盖,解析失败不会删除旧数据。 |
| | | - 审核规则及 `loadTrackMap` 只读取 `ABOVE_SCALE`,避免两客企业同名数据覆盖货运审核基准;数据查看页新增企业类别和异常里程,类别显示为中文。 |
| | | - 已通过正式导入接口导入 2026 年 1—9 月数据。最新导入批次为 598—606;旧批次日志保留,查询当前批次时按最新 `id`。 |
| | | - 数据库共 7,681 条,分布:1 月 631、2 月 631、3 月 630、4 月 628、5 月 628、6 月 628、7 月 1,304、8 月 1,300、9 月 1,301。9 月为规上 625 + 两客 676。 |
| | | - 1—6 月源文件无异常里程列,数据库为 NULL;7—9 月异常里程已导入。 |
| | | - 源表与数据库按“报表期+企业类别+企业名称”逐企业核对:缺失 0、多出 0、字段差异 0;重复键 0。验证文件:`outputs/track_mileage_import_20261027/verification.json`。 |
| | | - 迁移前备份:`outputs/db_backups/vehicle_track_mileage_before_20261027.sql`。定向单元测试及后端全量 `mvn test` 均通过。 |
| | | - 负向用例:把规上规下拆分模板作为轨迹里程导入 `2026-08` 被拒绝,原 628 条保持不变。 |
| | | - 本地测试记录:`docs/功能测试报告/功能测试报告_轨迹里程模板适配及1-9月导入_2026-10-27.md`(gitignored)。 |
| | | ## 2026-10-27 规上企业年度名录(已验收 2026-10-28) |
| | | |
| | | - 新增 `h2032_enterprise_year`,按年份保存规上企业年度名录,字段包括 `stat_year`、`enterprise_code`、`enterprise_name`、`region_code`、`city`、`source_period`,并保留创建/更新时间。 |
| | | - 唯一约束为 `(stat_year, enterprise_name)` 和 `(stat_year, enterprise_code)`;市州索引为 `(stat_year, city)`。2026 年名录从 `h2032_enterprise_monthly` 的 `2026-09` 报表生成,来源期写入 `source_period`。 |
| | | - 当前库核对结果:2026 年 636 行、636 个企业名称、636 个企业代码、17 个市州;名称/代码/区划/市州空值均为 0,与 2026-09 月报逐字段差异为 0;重复执行迁移后仍为 636 行。 |
| | | - 2026 年 1—9 月 `vehicle_track_mileage` 的规上记录共 5654 条,按年份和企业名称关联年度名录,未匹配 0 条;2026-09 的 625 家轨迹企业全部命中,12 家抽查企业也全部命中并得到咸宁/黄冈/宜昌市州。 |
| | | - 迁移脚本:`docs/sql_h2032_enterprise_year_migration.sql`;部署模板:`deploy-templates/db/sql_h2032_enterprise_year_migration.sql`。后续年份按相同方式从对应年份月报补充年度名录即可。 |
| | | - 轨迹表后续关联示例:`JOIN h2032_enterprise_year y ON y.stat_year=CAST(LEFT(t.report_period,4) AS UNSIGNED) AND y.enterprise_name=TRIM(t.enterprise_name)`,无需再在查询中重复转换区划。 |
| | | - 本轮改动已于 2026-10-28 用户验收通过后提交。 |
| | | |
| | | ## 2026-10-27 企业台账抽查车辆数改用运政口径(已验收 2026-10-28) |
| | | |
| | | - “总体情况”页原“月报车辆数”改为“运政车辆数”,并新增“主车数”。口径:运政车辆数=总牵引车数+总挂车数+其它车辆数;主车数=总牵引车数+其它车辆数。 |
| | | - 数据源为 `D:\03_公司\02_项目\27_湖北省道路运输事业发展中心\10_业务\101_运政车辆信息\2026\9月\01.规上企业车辆数查询—黄何.xls`。脚本默认按抽查任务年月定位该路径,也可通过 `--auth-vehicle-file` 指定。 |
| | | - 安欣由月报 68 更正为运政 67、主车 25;12 家企业运政车辆数和主车数均已核对。H2032 月报原值未修改。 |
| | | - “台账/平台里程差异率”改为百分比显示;绝对值不超过30%判为正常,超过±30%判为超出正常范围。 |
| | | - 原“轨迹匹配车辆数”改为“无轨迹车辆数”,口径为台账车辆数减去平台监测里程大于0的台账车辆数;新增“无轨迹车辆占比”(无轨迹车辆数÷台账车辆数)。 |
| | | - 新核查结果:`D:\03_公司\02_项目\27_湖北省道路运输事业发展中心\10_业务\280_厅里抽查企业台账\2026\9月\work\2026年9月企业台账抽查核查结果_总体及车辆里程_20261027_运政车辆数_无轨迹车辆.xlsx`。原 `_运政车辆数.xlsx` 因被 Excel/WPS 占用未能覆盖,保留为上一版本。 |
| | | - 原有货运量、周转量、台账数据、平台里程和 579 条车辆里程明细经逐项比对保持不变;工作簿无公式错误值。负向用例确认错误文件不会生成结果。 |
| | | - 本地测试记录:`docs/功能测试报告/功能测试报告_企业台账抽查运政车辆数与主车数_2026-10-27.md`(gitignored)。 |
| | | - 本轮未修改数据库、未导入数据;改动已于 2026-10-28 用户验收通过后提交。 |
| | | |
| | | |
| | | ## 2026-10-28 Enterprise Ledger Track-Point Inspection and Database Import (Accepted 2026-10-28) |
| | | |
| | | - Status: accepted by the user on 2026-10-28; committed after acceptance. |
| | | - Review workbook: `D:\03_公司\02_项目\27_湖北省道路运输事业发展中心\10_业务\280_厅里抽查企业台账\2026\9月\work\2026年9月企业台账抽查核查结果_轨迹核查_20261028.xlsx`. |
| | | - Inspection task log: `ledger_inspection_task` stores `task_code`, `task_name`, `inspection_period`, city/enterprise/sample-vehicle summary lists, counts, source roots, status, and start/finish timestamps. Current record: `LEDGER_SPOT_202609_R1`, period `2026-09`, 3 cities, 12 enterprises, 12 sample vehicles, status `COMPLETED`. |
| | | - Normalized inspection details remain task-scoped in the `ledger_inspection_*` tables. Current counts: 12 ledger source files, 12 enterprises, 3,003 route rows, 579 ledger vehicles, 12 sample vehicles, and 1 report. |
| | | - Platform observations are independent from inspection tasks in `vehicle_track_daily` and `vehicle_track_point`. Current `2026-09` counts: 12,921 daily mileage rows and 286,438 point rows. Neither table contains `task_id`, segment numbers, or download start/end dates. |
| | | - `vehicle_track_source_file` indexes 131 platform source files: 12 daily mileage files and 119 point-download files. The three-day limit is treated only as a download-file coverage constraint; point rows are stored according to their source headers. |
| | | - All 12 selected vehicles match the diagnostics row by row at the vehicle level. `鄂E68056` has 9 download files because the `25日-27日` file is missing; its 15,135 stored points are otherwise complete. |
| | | - Point-path mileage differs from monthly platform mileage by only 0.01%-0.12% across the 12 vehicles, providing mutual corroboration between the two platform datasets. |
| | | - Workbook terminology now says `download-file coverage` and `missing download files`; it no longer presents three-day grouping as a property of the track-point data. The existing `总体情况` and `车辆里程差异情况` business values are unchanged. |
| | | - Verification passed: `outputs\enterprise_ledger_track_points_20261028\db_verification.json` and `workbook_verification.json`. Idempotent re-import and negative input checks also passed. |
| | | - Local test record: `docs\功能测试报告\功能测试报告_企业台账抽查轨迹点核查及落库_2026-10-28.md`. |
| | | - Implementation files: `tools\enterprise_track_point_inspection.py`, `tools\build_enterprise_track_report.py`, `tools\import_ledger_inspection.py`, `tools\import_vehicle_track_observation.py`, `docs\sql_ledger_inspection.sql`, `docs\sql_vehicle_track_observation.sql`, and matching deploy templates. |
| | | |
| | | ## 2026-10-28 Formal Reader Workbook and Word Report (Accepted 2026-10-28) |
| | | |
| | | - Status: accepted by the user on 2026-10-28; committed after acceptance. |
| | | - Formal reader-facing workbook: `D:\03_公司\02_项目\27_湖北省道路运输事业发展中心\10_业务\280_厅里抽查企业台账\2026\9月\work\2026年9月企业台账抽查核查结果.xlsx`. |
| | | - Formal report: `D:\03_公司\02_项目\27_湖北省道路运输事业发展中心\10_业务\280_厅里抽查企业台账\2026\9月\work\2026年9月企业台账抽查核查报告.docx`. |
| | | - The formal workbook contains four reader-facing sheets: inspection overview, enterprise results, sample-vehicle results, and issue details. It excludes track-file inventories, hashes, local paths, download batches, and other operational details. |
| | | - The workbook now records 34 issues: 22 high risk and 12 medium risk. It adds the confirmed Yichang Kaixiangda turnover formula issue and the recommendation to screen all 636 regulated enterprises for the same error. |
| | | - Confirmed formula issue: the ledger used total freight volume multiplied by average mileage instead of summing freight volume multiplied by route mileage row by row. For January-September, reported turnover was 167,651,954.00 tonne-kilometres, the correct ledger total was 120,616,650.11, and the overstatement was 47,035,303.89 (39.00%). |
| | | - The erroneous formula itself produced 167,608,117.72 for January-September, 46,991,467.61 (38.96%) above the correct total. Monthly reports differed from that erroneous value by only 43,836.28 (0.0262%), indicating that the reports substantially inherited the incorrect summary value. |
| | | - The report states the mathematical boundary explicitly: the erroneous formula may overstate or understate an enterprise depending on its route pattern, so all 636 enterprises should be recalculated from line items and checked for both overstatement and understatement. It also recommends checking monthly and annual cumulative formulas. |
| | | - A new monthly table for Yichang Kaixiangda was added to the report. Existing tables were renumbered, and the 636-enterprise screening recommendation was added to the conclusions and recommendations. |
| | | - The former `(领导版)` workbook was archived under `_backups` with an old-name marker; the formal Excel filename no longer contains `(领导版)`. |
| | | - Report formatting: title is SimHei 22 pt; body is FangSong_GB2312 16 pt; tables use FangSong_GB2312 with 12 pt bold headers and 10.5 pt body text. The two wide result tables use dedicated landscape pages and each fits on one page. |
| | | - Report workload figures: 3 cities, 12 enterprises, 3,003 ledger route rows, 579 ledger vehicles, 12,921 platform daily-mileage rows, 119 point source files, 286,438 raw points, 286,436 deduplicated points, 12 sample vehicles, and about one week of work. |
| | | - Final verification: `outputs\enterprise_ledger_track_points_20261028\final_deliverables_verification.json` has `status=PASS`; the Word report renders to 11 pages, page numbering is continuous, the two wide tables each fit on one landscape page, and no text reaches the page edge. |
| | | - Local test record: `docs\功能测试报告\功能测试报告_企业台账抽查正式附件及核查报告_2026-10-28.md` (gitignored). |
| | | - QA-only PDF and page images remain under `outputs\enterprise_ledger_track_points_20261028\report_render_final_v2\`; they are not user-facing deliverables. |
| | | |
| | | |
| | | ## 2026-10-28 Multi-sheet Source Metadata Correction (Accepted 2026-10-28) |
| | | |
| | | - Status: accepted by the user on 2026-10-28; committed after acceptance. |
| | | - `parse_ledger` now records all sheets actually parsed for one ledger file in `ledger_inspection_source_file.sheet_name`, joined by ASCII commas without spaces. |
| | | - Hubei Kaiying currently records `危货,普货`. Its route rows remain 543 in total: 401 from `危货` and 142 from `普货`; all business aggregates are unchanged. |
| | | - The existing database source row was corrected in place from `危货` to `危货,普货`; source row count remains 543. |
| | | - Single-sheet control: Huanggang Xindafei still records the single sheet name `9月`, with no comma added. |
| | | - Verification: Python compilation passed, parser regression checks passed, and the live database query returned `(危货,普货, 543)`. |
| | | |
| | | ## Pending TODO: Imported Source-File Archive and Recovery |
| | | |
| | | - Status: not implemented. This is a future audit-traceability requirement; the current system stores metadata only and does not retain a recoverable copy of imported Excel files. |
| | | - Requirement: when audit rules require traceable and recoverable imported originals, add an explicit attachment-archive mechanism. |
| | | - Storage design: save each original file in a dedicated archive directory using its SHA-256 as the stable identity, for example `<archive-root>/<first-two-hash-chars>/<sha256>.<ext>`. Do not store Excel binaries as BLOBs in MySQL. |
| | | - Database metadata: record archive path, archive SHA-256, original filename, original client/path where applicable, file size, import type, report period, sheet names, importer/task identifier, and archived time. |
| | | - Deduplication: if the same SHA-256 already exists, reuse the archived file and attach the new import record; do not create duplicate file copies. |
| | | - Coverage: apply consistently to normal web imports and to the ledger/track source imports that currently store only external source paths and hashes. |
| | | - Integrity: verify SHA-256 after archive write and expose a recovery check that can confirm the archived file exists and still matches the recorded hash. |
| | | - Operations: define retention, access control, backup, deletion approval, and orphan-file reconciliation rules before enabling deletion or cleanup. |
| | | - Acceptance criteria: an auditor can locate any archived import from its database record, download/recover the exact original bytes, and independently verify the stored SHA-256. |
| | | |
| | | |
| | | ## 2026-10-28 Ledger Combination Plate Fields and Platform Vehicle Identity (Accepted 2026-10-28) |
| | | |
| | | - Status: accepted by the user on 2026-10-28; committed after acceptance. |
| | | - `ledger_inspection_route` now stores `plate_no_raw` for the complete ledger identifier and `trailer_plate_no` for the extracted trailer plate. `plate_no` remains the tractor plate and the only vehicle-matching key. |
| | | - Example: `鄂J58993/鄂J2093挂黄` is stored as `plate_no=鄂J58993`, `plate_no_raw=鄂J58993/鄂J2093挂黄`, and `trailer_plate_no=鄂J2093挂`. Blank vehicle cells on Guangfa cargo continuation rows inherit the preceding complete identifier. |
| | | - Migration: `docs/sql_ledger_inspection_plate_components_migration.sql` and the matching deploy template. It was executed twice on the live MySQL 5.7 database; the second run was a no-op. |
| | | - Backup before migration: `_backups/ledger_inspection_route_before_plate_components_20261028.sql`, SHA-256 `9CDF430F9003B041827908CB617EFB1A0B32E125DC6D324D85AD91038FAE8574`. |
| | | - Database re-import remains 12 enterprises, 3,003 route rows, and 579 ledger vehicles. All 3,003 rows have `plate_no_raw`; Guangfa contributes 136 rows and 68 distinct trailer plates. No route is keyed by a trailer plate. |
| | | - Per-enterprise route counts, vehicle counts, ledger mileage, and turnover match the source-ledger recomputation. The only difference is the existing six-decimal storage tail, at most 0.001 in aggregate. |
| | | - Platform data identity conclusion: the 2026-09 platform daily mileage and point downloads are tractor-only in the current dataset. `vehicle_track_daily` has 12,921 rows and `vehicle_track_point` has 286,438 rows; neither contains a plate with `挂`. |
| | | - Guangfa sample vehicle `鄂J50898` has 21,401 stored points, all with raw platform plate `鄂J50898[黄色]` and normalized plate `鄂J50898`; no trailer plate appears. The paired trailer `鄂J3038挂` remains ledger relationship data only. |
| | | - Verification: `outputs/enterprise_ledger_track_points_20261028/ledger_plate_component_verification.json` has all checks passed. |
| | | - Local test record: `docs/功能测试报告/功能测试报告_台账组合号牌拆解与平台轨迹车辆类型_2026-10-28.md` (gitignored). |
| | | |
| | | ## 2026-10-28 核查报告版式及文字修订(已验收 2026-10-28) |
| | | |
| | | - 状态:用户已于 2026-10-28 验收通过,验收后提交。 |
| | | - 正式报告:`D:\03_公司\02_项目\27_湖北省道路运输事业发展中心\10_业务\280_厅里抽查企业台账\2026\9月\work\2026年9月企业台账抽查核查报告.docx`,SHA-256 `08161FC0CB53548682FE6074C37AFA99F156A52CE86CF4E10E7D5A8334C7729B`。 |
| | | - 版式按参考稿调整:纵向页上下2.54cm、左右3.175cm,正文仿宋_GB2312 16pt、固定行距30pt;一级标题黑体16pt,首行缩进2字符。两张横向表页上下2.54cm、左右2.0cm。 |
| | | - `Title` 样式和标题段落均删除 `w:pBdr`,标题无蓝色横线;4张表全部取消单元格底色,表头只保留加粗。 |
| | | - 增加重点车辆选取标准;删除轨迹点与平台月度里程内部一致性验证、旧公式比较段、636家推断句、轨迹资料覆盖缺口问题及补充下载复核表述。 |
| | | - 核查结果明确为12家中11家月报与台账周转量差异率不超过1%、1家超过50%;凯祥达相关周转量在正文、表2、主要问题和核查结论中统一使用万吨公里。 |
| | | - 表3扩展为11列,增加月报/台账周转量比较值、台账/平台里程比较值、无轨迹车辆数及无轨迹车辆占比;12家企业数据齐全。 |
| | | - 处理建议(一)明确要求凯祥达立即将周转量汇总公式改为逐行“货运量×该趟里程”求和,并对1—9月多报的数据拿出调减方案;主要问题(六)已删除,处理建议(六)保留台账规范要求。 |
| | | - 渲染验证:11页连续;表1和表2宽度均为14.6cm并收进正文页边距;表3为13行×11列、表4为13行×9列,均完整落在横向页内;页面蓝色像素为0。 |
| | | - 旧版备份:`D:\03_公司\02_项目\27_湖北省道路运输事业发展中心\10_业务\280_厅里抽查企业台账\2026\9月\work\_backups\2026年9月企业台账抽查核查报告_before_format_20261028.docx`。 |
| | | - 本地测试记录:`docs\功能测试报告\功能测试报告_企业台账抽查核查报告版式修订_2026-10-28.md`(gitignored)。 |
| | | |
| | | ## 2026-10-28 企业台账抽查核查结果 Excel 排版与字段调整(已验收 2026-10-28) |
| | | |
| | | - 状态:用户已于 2026-10-28 验收通过,验收后提交。 |
| | | - 正式文件:`D:\03_公司\02_项目\27_湖北省道路运输事业发展中心\10_业务\280_厅里抽查企业台账\2026\9月\work\2026年9月企业台账抽查核查结果.xlsx`,SHA-256 `67CEABE2A38C8A296DDD0FC2493AFEDAABC0FF355509AB68D165BDD411512FFB`。 |
| | | - 工作簿改为全黑字、无底色、无彩色标签;标题为黑体18磅加粗、行高36磅,表头为仿宋_GB2312 14磅加粗、行高47磅且全部水平与垂直居中,正文为仿宋_GB2312 11磅、行高35磅。 |
| | | - 企业核查结果增加“月报/台账周转量(万吨公里)”和“台账/平台里程(公里)”比较值;重点车辆核查结果增加“台账/平台里程(公里)”比较值。 |
| | | - 问题明细第6行以后按咸宁→黄冈→宜昌排列,同一市州车辆集中;相同车牌号合并12组,公式问题 `—` 不合并。 |
| | | - 12家企业与12辆重点车辆已逐字段对齐正式 Word 表3、表4;周转量统一为万吨公里,公式问题处置建议保留“逐行货运量×该趟里程求和”和1—9月调减方案。 |
| | | - 打印为A3横向、全部列一页宽:核查概况1页、企业核查结果1页、重点车辆核查结果1页、问题明细2页,共5页;Excel COM导出正常,无 `####`、截断或彩色像素,12组车辆问题均未跨页,“广发”鄂J50898两项问题完整同页。 |
| | | - 本次覆盖前备份:`work\_backups\2026年9月企业台账抽查核查结果_before_city_group_header_center_20261028_121103.xlsx`(旧版 SHA-256 `C810093F0A849A5DBFEF8801122065491EFC87038D8B20A6DC30AC936D88C80F`)。 |
| | | - 本地测试记录:`docs\功能测试报告\功能测试报告_企业台账抽查核查结果Excel排版与字段调整_2026-10-28.md`(gitignored)。 |
| New file |
| | |
| | | -- Annual master of H2032 above-scale enterprises. |
| | | -- One row per enterprise per statistical year. |
| | | CREATE TABLE IF NOT EXISTS h2032_enterprise_year ( |
| | | id BIGINT AUTO_INCREMENT PRIMARY KEY, |
| | | stat_year SMALLINT NOT NULL COMMENT 'Statistical year', |
| | | enterprise_code VARCHAR(50) NULL COMMENT 'Enterprise code', |
| | | enterprise_name VARCHAR(200) NOT NULL COMMENT 'Enterprise name', |
| | | region_code VARCHAR(20) NULL COMMENT 'Administrative region code', |
| | | city VARCHAR(50) NOT NULL COMMENT 'Prefecture-level city', |
| | | source_period VARCHAR(20) NOT NULL COMMENT 'Source monthly report period', |
| | | created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, |
| | | updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, |
| | | UNIQUE KEY uk_h2032_enterprise_year_name (stat_year, enterprise_name), |
| | | UNIQUE KEY uk_h2032_enterprise_year_code (stat_year, enterprise_code), |
| | | KEY idx_h2032_enterprise_year_city (stat_year, city) |
| | | ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='Annual master of H2032 above-scale enterprises'; |
| | | |
| | | -- Seed 2026 from the September monthly report. The annual list is fixed for |
| | | -- the year, so the source period is retained for audit traceability. |
| | | INSERT INTO h2032_enterprise_year ( |
| | | stat_year, |
| | | enterprise_code, |
| | | enterprise_name, |
| | | region_code, |
| | | city, |
| | | source_period |
| | | ) |
| | | SELECT |
| | | 2026, |
| | | TRIM(enterprise_code), |
| | | TRIM(enterprise_name), |
| | | TRIM(region_code), |
| | | CASE LEFT(TRIM(region_code), 4) |
| | | WHEN '4201' THEN '武汉市' |
| | | WHEN '4202' THEN '黄石市' |
| | | WHEN '4203' THEN '十堰市' |
| | | WHEN '4205' THEN '宜昌市' |
| | | WHEN '4206' THEN '襄阳市' |
| | | WHEN '4207' THEN '鄂州市' |
| | | WHEN '4208' THEN '荆门市' |
| | | WHEN '4209' THEN '孝感市' |
| | | WHEN '4210' THEN '荆州市' |
| | | WHEN '4211' THEN '黄冈市' |
| | | WHEN '4212' THEN '咸宁市' |
| | | WHEN '4213' THEN '随州市' |
| | | WHEN '4228' THEN '恩施州' |
| | | WHEN '4290' THEN |
| | | CASE LEFT(TRIM(region_code), 6) |
| | | WHEN '429004' THEN '仙桃市' |
| | | WHEN '429005' THEN '潜江市' |
| | | WHEN '429006' THEN '天门市' |
| | | WHEN '429021' THEN '神农架林区' |
| | | ELSE NULL |
| | | END |
| | | ELSE NULL |
| | | END, |
| | | report_period |
| | | FROM h2032_enterprise_monthly |
| | | WHERE report_period = '2026-09' |
| | | ON DUPLICATE KEY UPDATE |
| | | enterprise_code = VALUES(enterprise_code), |
| | | region_code = VALUES(region_code), |
| | | city = VALUES(city), |
| | | source_period = VALUES(source_period); |
| New file |
| | |
| | | -- Reusable schema for enterprise ledger spot checks. |
| | | -- ledger_inspection_task is the task log: one row per inspection round, |
| | | -- including the reporting period, sampled cities, enterprises, and vehicles. |
| | | CREATE TABLE IF NOT EXISTS ledger_inspection_task ( |
| | | id BIGINT AUTO_INCREMENT PRIMARY KEY, |
| | | task_code VARCHAR(100) NOT NULL, |
| | | task_name VARCHAR(200) NOT NULL, |
| | | inspection_period VARCHAR(7) NOT NULL, |
| | | city_names VARCHAR(500) NULL, |
| | | enterprise_names MEDIUMTEXT NULL, |
| | | sample_plate_nos MEDIUMTEXT NULL, |
| | | city_count INT NOT NULL DEFAULT 0, |
| | | enterprise_count INT NOT NULL DEFAULT 0, |
| | | sample_vehicle_count INT NOT NULL DEFAULT 0, |
| | | source_root VARCHAR(1000) NULL, |
| | | work_root VARCHAR(1000) NULL, |
| | | status VARCHAR(30) NOT NULL DEFAULT 'RUNNING', |
| | | started_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, |
| | | finished_at DATETIME NULL, |
| | | created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, |
| | | updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, |
| | | UNIQUE KEY uk_ledger_task_code (task_code), |
| | | KEY idx_ledger_task_period (inspection_period) |
| | | ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='Ledger spot-check task log'; |
| | | |
| | | CREATE TABLE IF NOT EXISTS ledger_inspection_source_file ( |
| | | id BIGINT AUTO_INCREMENT PRIMARY KEY, |
| | | task_id BIGINT NOT NULL, |
| | | inspection_period VARCHAR(7) NOT NULL, |
| | | city_name VARCHAR(50) NOT NULL, |
| | | enterprise_name VARCHAR(200) NULL, |
| | | source_type VARCHAR(30) NOT NULL, |
| | | source_path VARCHAR(1000) NOT NULL, |
| | | source_name VARCHAR(255) NOT NULL, |
| | | source_path_hash CHAR(64) NOT NULL, |
| | | source_sha256 CHAR(64) NOT NULL, |
| | | file_size BIGINT NOT NULL DEFAULT 0, |
| | | sheet_name VARCHAR(200) NULL, |
| | | source_rows INT NOT NULL DEFAULT 0, |
| | | status VARCHAR(30) NOT NULL DEFAULT 'IMPORTED', |
| | | error_message TEXT NULL, |
| | | imported_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, |
| | | UNIQUE KEY uk_ledger_source (task_id, source_type, source_path_hash), |
| | | KEY idx_ledger_source_period (task_id, inspection_period, city_name) |
| | | ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; |
| | | |
| | | CREATE TABLE IF NOT EXISTS ledger_inspection_enterprise ( |
| | | id BIGINT AUTO_INCREMENT PRIMARY KEY, |
| | | task_id BIGINT NOT NULL, |
| | | inspection_period VARCHAR(7) NOT NULL, |
| | | city_name VARCHAR(50) NOT NULL, |
| | | enterprise_name VARCHAR(200) NOT NULL, |
| | | enterprise_code VARCHAR(50) NULL, |
| | | h2032_report_id BIGINT NULL, |
| | | month_vehicle_total INT NULL, |
| | | month_tractor_count INT NULL, |
| | | authority_vehicle_total INT NULL, |
| | | authority_main_vehicle_count INT NULL, |
| | | month_freight DECIMAL(20,6) NULL, |
| | | month_turnover DECIMAL(24,6) NULL, |
| | | ledger_route_count INT NOT NULL DEFAULT 0, |
| | | ledger_vehicle_count INT NOT NULL DEFAULT 0, |
| | | ledger_trips DECIMAL(20,6) NOT NULL DEFAULT 0, |
| | | ledger_freight DECIMAL(20,6) NOT NULL DEFAULT 0, |
| | | ledger_turnover DECIMAL(24,6) NOT NULL DEFAULT 0, |
| | | ledger_mileage DECIMAL(24,6) NOT NULL DEFAULT 0, |
| | | matched_vehicle_count INT NOT NULL DEFAULT 0, |
| | | matched_ledger_turnover DECIMAL(24,6) NOT NULL DEFAULT 0, |
| | | tracked_vehicle_count INT NOT NULL DEFAULT 0, |
| | | track_mileage DECIMAL(24,6) NOT NULL DEFAULT 0, |
| | | track_complete_mileage DECIMAL(24,6) NOT NULL DEFAULT 0, |
| | | track_abnormal_mileage DECIMAL(24,6) NOT NULL DEFAULT 0, |
| | | track_vehicle_days INT NOT NULL DEFAULT 0, |
| | | track_day_coverage DECIMAL(12,8) NULL, |
| | | raw_track_vehicle_count INT NOT NULL DEFAULT 0, |
| | | raw_track_file_count INT NOT NULL DEFAULT 0, |
| | | raw_track_point_count BIGINT NOT NULL DEFAULT 0, |
| | | track_estimated_turnover DECIMAL(24,6) NULL, |
| | | normalized_track_turnover DECIMAL(24,6) NULL, |
| | | report_vs_ledger_rate DECIMAL(16,8) NULL, |
| | | report_vs_ledger_freight_rate DECIMAL(16,8) NULL, |
| | | report_vs_track_rate DECIMAL(16,8) NULL, |
| | | mileage_diff_rate DECIMAL(16,8) NULL, |
| | | no_track_vehicle_count INT NOT NULL DEFAULT 0, |
| | | no_track_vehicle_ratio DECIMAL(12,8) NULL, |
| | | layer1_status VARCHAR(50) NULL, |
| | | layer2_status VARCHAR(100) NULL, |
| | | note TEXT NULL, |
| | | severity VARCHAR(20) NULL, |
| | | conclusion TEXT NULL, |
| | | suggestion TEXT NULL, |
| | | source_ledger_path VARCHAR(1000) NULL, |
| | | source_track_path VARCHAR(1000) NULL, |
| | | created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, |
| | | updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, |
| | | UNIQUE KEY uk_ledger_enterprise (task_id, city_name, enterprise_name), |
| | | KEY idx_ledger_enterprise_period (inspection_period, city_name) |
| | | ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; |
| | | |
| | | CREATE TABLE IF NOT EXISTS ledger_inspection_route ( |
| | | id BIGINT AUTO_INCREMENT PRIMARY KEY, |
| | | task_id BIGINT NOT NULL, |
| | | inspection_period VARCHAR(7) NOT NULL, |
| | | city_name VARCHAR(50) NOT NULL, |
| | | enterprise_name VARCHAR(200) NOT NULL, |
| | | plate_no VARCHAR(30) NOT NULL, |
| | | plate_no_raw VARCHAR(100) NULL, |
| | | trailer_plate_no VARCHAR(30) NULL, |
| | | route_text VARCHAR(500) NULL, |
| | | cargo_type VARCHAR(200) NULL, |
| | | cargo_tons DECIMAL(20,6) NULL, |
| | | trips DECIMAL(20,6) NULL, |
| | | mileage_per_trip DECIMAL(20,6) NULL, |
| | | total_mileage DECIMAL(24,6) NULL, |
| | | freight_tons DECIMAL(20,6) NULL, |
| | | turnover DECIMAL(24,6) NULL, |
| | | transport_date DATE NULL, |
| | | source_file VARCHAR(1000) NOT NULL, |
| | | source_path_hash CHAR(64) NOT NULL, |
| | | sheet_name VARCHAR(200) NOT NULL, |
| | | row_no INT NOT NULL, |
| | | block_no INT NOT NULL DEFAULT 1, |
| | | record_key CHAR(64) NOT NULL, |
| | | created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, |
| | | UNIQUE KEY uk_ledger_route (task_id, record_key), |
| | | KEY idx_ledger_route_vehicle (task_id, enterprise_name, plate_no), |
| | | KEY idx_ledger_route_period (inspection_period, city_name) |
| | | ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; |
| | | |
| | | CREATE TABLE IF NOT EXISTS ledger_inspection_vehicle ( |
| | | id BIGINT AUTO_INCREMENT PRIMARY KEY, |
| | | task_id BIGINT NOT NULL, |
| | | inspection_period VARCHAR(7) NOT NULL, |
| | | city_name VARCHAR(50) NOT NULL, |
| | | enterprise_name VARCHAR(200) NOT NULL, |
| | | plate_no VARCHAR(30) NOT NULL, |
| | | ledger_route_count INT NOT NULL DEFAULT 0, |
| | | ledger_trips DECIMAL(20,6) NOT NULL DEFAULT 0, |
| | | ledger_freight DECIMAL(20,6) NOT NULL DEFAULT 0, |
| | | ledger_turnover DECIMAL(24,6) NOT NULL DEFAULT 0, |
| | | ledger_mileage DECIMAL(24,6) NOT NULL DEFAULT 0, |
| | | turnover_per_km DECIMAL(20,8) NULL, |
| | | track_total_mileage DECIMAL(24,6) NULL, |
| | | track_complete_mileage DECIMAL(24,6) NULL, |
| | | track_abnormal_mileage DECIMAL(24,6) NULL, |
| | | track_days INT NOT NULL DEFAULT 0, |
| | | first_track_date DATE NULL, |
| | | last_track_date DATE NULL, |
| | | track_point_count BIGINT NOT NULL DEFAULT 0, |
| | | raw_track_file_count INT NOT NULL DEFAULT 0, |
| | | raw_track_point_count BIGINT NOT NULL DEFAULT 0, |
| | | raw_track_days INT NOT NULL DEFAULT 0, |
| | | track_estimated_turnover DECIMAL(24,6) NULL, |
| | | mileage_diff_rate DECIMAL(16,8) NULL, |
| | | anomaly_rate DECIMAL(12,8) NULL, |
| | | match_status VARCHAR(50) NOT NULL, |
| | | conclusion TEXT NULL, |
| | | created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, |
| | | updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, |
| | | UNIQUE KEY uk_ledger_vehicle (task_id, city_name, enterprise_name, plate_no), |
| | | KEY idx_ledger_vehicle_period (inspection_period, enterprise_name) |
| | | ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; |
| | | |
| | | CREATE TABLE IF NOT EXISTS ledger_inspection_sample_vehicle ( |
| | | id BIGINT AUTO_INCREMENT PRIMARY KEY, |
| | | task_id BIGINT NOT NULL, |
| | | inspection_period VARCHAR(7) NOT NULL, |
| | | city_name VARCHAR(50) NOT NULL, |
| | | enterprise_name VARCHAR(200) NOT NULL, |
| | | plate_no VARCHAR(30) NOT NULL, |
| | | missing_days TEXT NULL, |
| | | unique_point_count BIGINT NOT NULL DEFAULT 0, |
| | | duplicate_point_count BIGINT NOT NULL DEFAULT 0, |
| | | point_first_time DATETIME NULL, |
| | | point_last_time DATETIME NULL, |
| | | point_coverage_days INT NOT NULL DEFAULT 0, |
| | | point_path_mileage DECIMAL(24,6) NULL, |
| | | point_vs_platform_rate DECIMAL(16,8) NULL, |
| | | platform_vs_ledger_rate DECIMAL(16,8) NULL, |
| | | ledger_vs_platform_rate DECIMAL(16,8) NULL, |
| | | average_trip_mileage DECIMAL(20,6) NULL, |
| | | supported_trip_count DECIMAL(20,6) NULL, |
| | | trip_support_rate DECIMAL(16,8) NULL, |
| | | endpoint_check TEXT NULL, |
| | | main_activity_regions TEXT NULL, |
| | | route_conclusion TEXT NULL, |
| | | risk_level VARCHAR(20) NULL, |
| | | created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, |
| | | updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, |
| | | UNIQUE KEY uk_ledger_sample_vehicle (task_id, city_name, enterprise_name, plate_no), |
| | | KEY idx_ledger_sample_period (inspection_period, city_name, plate_no) |
| | | ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; |
| | | |
| | | CREATE TABLE IF NOT EXISTS ledger_inspection_report ( |
| | | id BIGINT AUTO_INCREMENT PRIMARY KEY, |
| | | task_id BIGINT NOT NULL, |
| | | inspection_period VARCHAR(7) NOT NULL, |
| | | report_type VARCHAR(30) NOT NULL, |
| | | report_path VARCHAR(1000) NOT NULL, |
| | | report_sha256 CHAR(64) NOT NULL, |
| | | file_size BIGINT NOT NULL DEFAULT 0, |
| | | generated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, |
| | | UNIQUE KEY uk_ledger_report (task_id, report_type, report_sha256) |
| | | ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; |
| New file |
| | |
| | | -- Add normalized ledger plate components without changing the tractor matching key. |
| | | |
| | | SET @add_plate_no_raw = ( |
| | | SELECT IF( |
| | | COUNT(*) = 0, |
| | | 'ALTER TABLE `ledger_inspection_route` ADD COLUMN `plate_no_raw` VARCHAR(100) NULL AFTER `plate_no`', |
| | | 'SELECT 1' |
| | | ) |
| | | FROM information_schema.COLUMNS |
| | | WHERE TABLE_SCHEMA = DATABASE() |
| | | AND TABLE_NAME = 'ledger_inspection_route' |
| | | AND COLUMN_NAME = 'plate_no_raw' |
| | | ); |
| | | PREPARE add_plate_no_raw_stmt FROM @add_plate_no_raw; |
| | | EXECUTE add_plate_no_raw_stmt; |
| | | DEALLOCATE PREPARE add_plate_no_raw_stmt; |
| | | |
| | | SET @add_trailer_plate_no = ( |
| | | SELECT IF( |
| | | COUNT(*) = 0, |
| | | 'ALTER TABLE `ledger_inspection_route` ADD COLUMN `trailer_plate_no` VARCHAR(30) NULL AFTER `plate_no_raw`', |
| | | 'SELECT 1' |
| | | ) |
| | | FROM information_schema.COLUMNS |
| | | WHERE TABLE_SCHEMA = DATABASE() |
| | | AND TABLE_NAME = 'ledger_inspection_route' |
| | | AND COLUMN_NAME = 'trailer_plate_no' |
| | | ); |
| | | PREPARE add_trailer_plate_no_stmt FROM @add_trailer_plate_no; |
| | | EXECUTE add_trailer_plate_no_stmt; |
| | | DEALLOCATE PREPARE add_trailer_plate_no_stmt; |
| New file |
| | |
| | | -- Objective observations downloaded from the heavy-haul monitoring platform. |
| | | -- These tables are independent from enterprise ledger inspection tasks. |
| | | CREATE TABLE IF NOT EXISTS vehicle_track_daily ( |
| | | id BIGINT AUTO_INCREMENT PRIMARY KEY, |
| | | report_period VARCHAR(7) NOT NULL, |
| | | freight_enterprise_name VARCHAR(200) NOT NULL, |
| | | plate_no_raw VARCHAR(50) NOT NULL, |
| | | plate_no VARCHAR(30) NOT NULL, |
| | | track_date DATE NULL, |
| | | agency_name VARCHAR(200) NULL, |
| | | vehicle_label VARCHAR(100) NULL, |
| | | operator_name VARCHAR(100) NULL, |
| | | point_count BIGINT NOT NULL DEFAULT 0, |
| | | complete_mileage DECIMAL(24,6) NOT NULL DEFAULT 0, |
| | | abnormal_mileage DECIMAL(24,6) NOT NULL DEFAULT 0, |
| | | total_mileage DECIMAL(24,6) NOT NULL DEFAULT 0, |
| | | drift_count BIGINT NOT NULL DEFAULT 0, |
| | | anomaly_rate DECIMAL(12,8) NULL, |
| | | track_text VARCHAR(500) NULL, |
| | | approved_traction_tonnage DECIMAL(20,6) NULL, |
| | | route_text VARCHAR(500) NULL, |
| | | trips DECIMAL(20,6) NULL, |
| | | straight_distance DECIMAL(20,6) NULL, |
| | | cargo_tons DECIMAL(20,6) NULL, |
| | | source_file VARCHAR(1000) NOT NULL, |
| | | source_path_hash CHAR(64) NOT NULL, |
| | | source_sha256 CHAR(64) NOT NULL, |
| | | source_row INT NOT NULL, |
| | | created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, |
| | | updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, |
| | | UNIQUE KEY uk_vehicle_track_daily_source (report_period, source_sha256, source_row), |
| | | KEY idx_vehicle_track_daily_vehicle (report_period, plate_no, track_date), |
| | | KEY idx_vehicle_track_daily_enterprise (report_period, freight_enterprise_name) |
| | | ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; |
| | | |
| | | CREATE TABLE IF NOT EXISTS vehicle_track_point ( |
| | | id BIGINT AUTO_INCREMENT PRIMARY KEY, |
| | | report_period VARCHAR(7) NOT NULL, |
| | | unit_name VARCHAR(200) NOT NULL, |
| | | plate_no_raw VARCHAR(50) NOT NULL, |
| | | plate_no VARCHAR(30) NOT NULL, |
| | | terminal_time DATETIME NULL, |
| | | receive_time DATETIME NULL, |
| | | longitude DECIMAL(12,7) NULL, |
| | | latitude DECIMAL(12,7) NULL, |
| | | speed_text VARCHAR(50) NULL, |
| | | vehicle_status VARCHAR(200) NULL, |
| | | alarm_status VARCHAR(200) NULL, |
| | | operator_name VARCHAR(100) NULL, |
| | | location_text VARCHAR(500) NULL, |
| | | province_name VARCHAR(50) NULL, |
| | | prefecture_name VARCHAR(50) NULL, |
| | | county_name VARCHAR(50) NULL, |
| | | source_file VARCHAR(1000) NOT NULL, |
| | | source_path_hash CHAR(64) NOT NULL, |
| | | source_sha256 CHAR(64) NOT NULL, |
| | | source_row INT NOT NULL, |
| | | created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, |
| | | updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, |
| | | UNIQUE KEY uk_vehicle_track_point_source (report_period, source_sha256, source_row), |
| | | KEY idx_vehicle_track_point_vehicle (report_period, plate_no, terminal_time), |
| | | KEY idx_vehicle_track_point_unit (report_period, unit_name) |
| | | ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; |
| | | |
| | | CREATE TABLE IF NOT EXISTS vehicle_track_source_file ( |
| | | id BIGINT AUTO_INCREMENT PRIMARY KEY, |
| | | report_period VARCHAR(7) NOT NULL, |
| | | data_type VARCHAR(30) NOT NULL, |
| | | enterprise_name VARCHAR(200) NULL, |
| | | source_path VARCHAR(1000) NOT NULL, |
| | | source_name VARCHAR(255) NOT NULL, |
| | | source_path_hash CHAR(64) NOT NULL, |
| | | source_sha256 CHAR(64) NOT NULL, |
| | | file_size BIGINT NOT NULL DEFAULT 0, |
| | | sheet_name VARCHAR(200) NULL, |
| | | source_rows INT NOT NULL DEFAULT 0, |
| | | imported_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, |
| | | UNIQUE KEY uk_vehicle_track_source (report_period, data_type, source_sha256), |
| | | KEY idx_vehicle_track_source_period (report_period, data_type) |
| | | ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; |
| New file |
| | |
| | | -- Annual master of H2032 above-scale enterprises. |
| | | -- One row per enterprise per statistical year. |
| | | CREATE TABLE IF NOT EXISTS h2032_enterprise_year ( |
| | | id BIGINT AUTO_INCREMENT PRIMARY KEY, |
| | | stat_year SMALLINT NOT NULL COMMENT 'Statistical year', |
| | | enterprise_code VARCHAR(50) NULL COMMENT 'Enterprise code', |
| | | enterprise_name VARCHAR(200) NOT NULL COMMENT 'Enterprise name', |
| | | region_code VARCHAR(20) NULL COMMENT 'Administrative region code', |
| | | city VARCHAR(50) NOT NULL COMMENT 'Prefecture-level city', |
| | | source_period VARCHAR(20) NOT NULL COMMENT 'Source monthly report period', |
| | | created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, |
| | | updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, |
| | | UNIQUE KEY uk_h2032_enterprise_year_name (stat_year, enterprise_name), |
| | | UNIQUE KEY uk_h2032_enterprise_year_code (stat_year, enterprise_code), |
| | | KEY idx_h2032_enterprise_year_city (stat_year, city) |
| | | ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='Annual master of H2032 above-scale enterprises'; |
| | | |
| | | -- Seed 2026 from the September monthly report. The annual list is fixed for |
| | | -- the year, so the source period is retained for audit traceability. |
| | | INSERT INTO h2032_enterprise_year ( |
| | | stat_year, |
| | | enterprise_code, |
| | | enterprise_name, |
| | | region_code, |
| | | city, |
| | | source_period |
| | | ) |
| | | SELECT |
| | | 2026, |
| | | TRIM(enterprise_code), |
| | | TRIM(enterprise_name), |
| | | TRIM(region_code), |
| | | CASE LEFT(TRIM(region_code), 4) |
| | | WHEN '4201' THEN '武汉市' |
| | | WHEN '4202' THEN '黄石市' |
| | | WHEN '4203' THEN '十堰市' |
| | | WHEN '4205' THEN '宜昌市' |
| | | WHEN '4206' THEN '襄阳市' |
| | | WHEN '4207' THEN '鄂州市' |
| | | WHEN '4208' THEN '荆门市' |
| | | WHEN '4209' THEN '孝感市' |
| | | WHEN '4210' THEN '荆州市' |
| | | WHEN '4211' THEN '黄冈市' |
| | | WHEN '4212' THEN '咸宁市' |
| | | WHEN '4213' THEN '随州市' |
| | | WHEN '4228' THEN '恩施州' |
| | | WHEN '4290' THEN |
| | | CASE LEFT(TRIM(region_code), 6) |
| | | WHEN '429004' THEN '仙桃市' |
| | | WHEN '429005' THEN '潜江市' |
| | | WHEN '429006' THEN '天门市' |
| | | WHEN '429021' THEN '神农架林区' |
| | | ELSE NULL |
| | | END |
| | | ELSE NULL |
| | | END, |
| | | report_period |
| | | FROM h2032_enterprise_monthly |
| | | WHERE report_period = '2026-09' |
| | | ON DUPLICATE KEY UPDATE |
| | | enterprise_code = VALUES(enterprise_code), |
| | | region_code = VALUES(region_code), |
| | | city = VALUES(city), |
| | | source_period = VALUES(source_period); |
| New file |
| | |
| | | -- Reusable schema for enterprise ledger spot checks. |
| | | -- ledger_inspection_task is the task log: one row per inspection round, |
| | | -- including the reporting period, sampled cities, enterprises, and vehicles. |
| | | CREATE TABLE IF NOT EXISTS ledger_inspection_task ( |
| | | id BIGINT AUTO_INCREMENT PRIMARY KEY, |
| | | task_code VARCHAR(100) NOT NULL, |
| | | task_name VARCHAR(200) NOT NULL, |
| | | inspection_period VARCHAR(7) NOT NULL, |
| | | city_names VARCHAR(500) NULL, |
| | | enterprise_names MEDIUMTEXT NULL, |
| | | sample_plate_nos MEDIUMTEXT NULL, |
| | | city_count INT NOT NULL DEFAULT 0, |
| | | enterprise_count INT NOT NULL DEFAULT 0, |
| | | sample_vehicle_count INT NOT NULL DEFAULT 0, |
| | | source_root VARCHAR(1000) NULL, |
| | | work_root VARCHAR(1000) NULL, |
| | | status VARCHAR(30) NOT NULL DEFAULT 'RUNNING', |
| | | started_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, |
| | | finished_at DATETIME NULL, |
| | | created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, |
| | | updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, |
| | | UNIQUE KEY uk_ledger_task_code (task_code), |
| | | KEY idx_ledger_task_period (inspection_period) |
| | | ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='Ledger spot-check task log'; |
| | | |
| | | CREATE TABLE IF NOT EXISTS ledger_inspection_source_file ( |
| | | id BIGINT AUTO_INCREMENT PRIMARY KEY, |
| | | task_id BIGINT NOT NULL, |
| | | inspection_period VARCHAR(7) NOT NULL, |
| | | city_name VARCHAR(50) NOT NULL, |
| | | enterprise_name VARCHAR(200) NULL, |
| | | source_type VARCHAR(30) NOT NULL, |
| | | source_path VARCHAR(1000) NOT NULL, |
| | | source_name VARCHAR(255) NOT NULL, |
| | | source_path_hash CHAR(64) NOT NULL, |
| | | source_sha256 CHAR(64) NOT NULL, |
| | | file_size BIGINT NOT NULL DEFAULT 0, |
| | | sheet_name VARCHAR(200) NULL, |
| | | source_rows INT NOT NULL DEFAULT 0, |
| | | status VARCHAR(30) NOT NULL DEFAULT 'IMPORTED', |
| | | error_message TEXT NULL, |
| | | imported_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, |
| | | UNIQUE KEY uk_ledger_source (task_id, source_type, source_path_hash), |
| | | KEY idx_ledger_source_period (task_id, inspection_period, city_name) |
| | | ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; |
| | | |
| | | CREATE TABLE IF NOT EXISTS ledger_inspection_enterprise ( |
| | | id BIGINT AUTO_INCREMENT PRIMARY KEY, |
| | | task_id BIGINT NOT NULL, |
| | | inspection_period VARCHAR(7) NOT NULL, |
| | | city_name VARCHAR(50) NOT NULL, |
| | | enterprise_name VARCHAR(200) NOT NULL, |
| | | enterprise_code VARCHAR(50) NULL, |
| | | h2032_report_id BIGINT NULL, |
| | | month_vehicle_total INT NULL, |
| | | month_tractor_count INT NULL, |
| | | authority_vehicle_total INT NULL, |
| | | authority_main_vehicle_count INT NULL, |
| | | month_freight DECIMAL(20,6) NULL, |
| | | month_turnover DECIMAL(24,6) NULL, |
| | | ledger_route_count INT NOT NULL DEFAULT 0, |
| | | ledger_vehicle_count INT NOT NULL DEFAULT 0, |
| | | ledger_trips DECIMAL(20,6) NOT NULL DEFAULT 0, |
| | | ledger_freight DECIMAL(20,6) NOT NULL DEFAULT 0, |
| | | ledger_turnover DECIMAL(24,6) NOT NULL DEFAULT 0, |
| | | ledger_mileage DECIMAL(24,6) NOT NULL DEFAULT 0, |
| | | matched_vehicle_count INT NOT NULL DEFAULT 0, |
| | | matched_ledger_turnover DECIMAL(24,6) NOT NULL DEFAULT 0, |
| | | tracked_vehicle_count INT NOT NULL DEFAULT 0, |
| | | track_mileage DECIMAL(24,6) NOT NULL DEFAULT 0, |
| | | track_complete_mileage DECIMAL(24,6) NOT NULL DEFAULT 0, |
| | | track_abnormal_mileage DECIMAL(24,6) NOT NULL DEFAULT 0, |
| | | track_vehicle_days INT NOT NULL DEFAULT 0, |
| | | track_day_coverage DECIMAL(12,8) NULL, |
| | | raw_track_vehicle_count INT NOT NULL DEFAULT 0, |
| | | raw_track_file_count INT NOT NULL DEFAULT 0, |
| | | raw_track_point_count BIGINT NOT NULL DEFAULT 0, |
| | | track_estimated_turnover DECIMAL(24,6) NULL, |
| | | normalized_track_turnover DECIMAL(24,6) NULL, |
| | | report_vs_ledger_rate DECIMAL(16,8) NULL, |
| | | report_vs_ledger_freight_rate DECIMAL(16,8) NULL, |
| | | report_vs_track_rate DECIMAL(16,8) NULL, |
| | | mileage_diff_rate DECIMAL(16,8) NULL, |
| | | no_track_vehicle_count INT NOT NULL DEFAULT 0, |
| | | no_track_vehicle_ratio DECIMAL(12,8) NULL, |
| | | layer1_status VARCHAR(50) NULL, |
| | | layer2_status VARCHAR(100) NULL, |
| | | note TEXT NULL, |
| | | severity VARCHAR(20) NULL, |
| | | conclusion TEXT NULL, |
| | | suggestion TEXT NULL, |
| | | source_ledger_path VARCHAR(1000) NULL, |
| | | source_track_path VARCHAR(1000) NULL, |
| | | created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, |
| | | updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, |
| | | UNIQUE KEY uk_ledger_enterprise (task_id, city_name, enterprise_name), |
| | | KEY idx_ledger_enterprise_period (inspection_period, city_name) |
| | | ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; |
| | | |
| | | CREATE TABLE IF NOT EXISTS ledger_inspection_route ( |
| | | id BIGINT AUTO_INCREMENT PRIMARY KEY, |
| | | task_id BIGINT NOT NULL, |
| | | inspection_period VARCHAR(7) NOT NULL, |
| | | city_name VARCHAR(50) NOT NULL, |
| | | enterprise_name VARCHAR(200) NOT NULL, |
| | | plate_no VARCHAR(30) NOT NULL, |
| | | plate_no_raw VARCHAR(100) NULL, |
| | | trailer_plate_no VARCHAR(30) NULL, |
| | | route_text VARCHAR(500) NULL, |
| | | cargo_type VARCHAR(200) NULL, |
| | | cargo_tons DECIMAL(20,6) NULL, |
| | | trips DECIMAL(20,6) NULL, |
| | | mileage_per_trip DECIMAL(20,6) NULL, |
| | | total_mileage DECIMAL(24,6) NULL, |
| | | freight_tons DECIMAL(20,6) NULL, |
| | | turnover DECIMAL(24,6) NULL, |
| | | transport_date DATE NULL, |
| | | source_file VARCHAR(1000) NOT NULL, |
| | | source_path_hash CHAR(64) NOT NULL, |
| | | sheet_name VARCHAR(200) NOT NULL, |
| | | row_no INT NOT NULL, |
| | | block_no INT NOT NULL DEFAULT 1, |
| | | record_key CHAR(64) NOT NULL, |
| | | created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, |
| | | UNIQUE KEY uk_ledger_route (task_id, record_key), |
| | | KEY idx_ledger_route_vehicle (task_id, enterprise_name, plate_no), |
| | | KEY idx_ledger_route_period (inspection_period, city_name) |
| | | ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; |
| | | |
| | | CREATE TABLE IF NOT EXISTS ledger_inspection_vehicle ( |
| | | id BIGINT AUTO_INCREMENT PRIMARY KEY, |
| | | task_id BIGINT NOT NULL, |
| | | inspection_period VARCHAR(7) NOT NULL, |
| | | city_name VARCHAR(50) NOT NULL, |
| | | enterprise_name VARCHAR(200) NOT NULL, |
| | | plate_no VARCHAR(30) NOT NULL, |
| | | ledger_route_count INT NOT NULL DEFAULT 0, |
| | | ledger_trips DECIMAL(20,6) NOT NULL DEFAULT 0, |
| | | ledger_freight DECIMAL(20,6) NOT NULL DEFAULT 0, |
| | | ledger_turnover DECIMAL(24,6) NOT NULL DEFAULT 0, |
| | | ledger_mileage DECIMAL(24,6) NOT NULL DEFAULT 0, |
| | | turnover_per_km DECIMAL(20,8) NULL, |
| | | track_total_mileage DECIMAL(24,6) NULL, |
| | | track_complete_mileage DECIMAL(24,6) NULL, |
| | | track_abnormal_mileage DECIMAL(24,6) NULL, |
| | | track_days INT NOT NULL DEFAULT 0, |
| | | first_track_date DATE NULL, |
| | | last_track_date DATE NULL, |
| | | track_point_count BIGINT NOT NULL DEFAULT 0, |
| | | raw_track_file_count INT NOT NULL DEFAULT 0, |
| | | raw_track_point_count BIGINT NOT NULL DEFAULT 0, |
| | | raw_track_days INT NOT NULL DEFAULT 0, |
| | | track_estimated_turnover DECIMAL(24,6) NULL, |
| | | mileage_diff_rate DECIMAL(16,8) NULL, |
| | | anomaly_rate DECIMAL(12,8) NULL, |
| | | match_status VARCHAR(50) NOT NULL, |
| | | conclusion TEXT NULL, |
| | | created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, |
| | | updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, |
| | | UNIQUE KEY uk_ledger_vehicle (task_id, city_name, enterprise_name, plate_no), |
| | | KEY idx_ledger_vehicle_period (inspection_period, enterprise_name) |
| | | ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; |
| | | |
| | | CREATE TABLE IF NOT EXISTS ledger_inspection_sample_vehicle ( |
| | | id BIGINT AUTO_INCREMENT PRIMARY KEY, |
| | | task_id BIGINT NOT NULL, |
| | | inspection_period VARCHAR(7) NOT NULL, |
| | | city_name VARCHAR(50) NOT NULL, |
| | | enterprise_name VARCHAR(200) NOT NULL, |
| | | plate_no VARCHAR(30) NOT NULL, |
| | | missing_days TEXT NULL, |
| | | unique_point_count BIGINT NOT NULL DEFAULT 0, |
| | | duplicate_point_count BIGINT NOT NULL DEFAULT 0, |
| | | point_first_time DATETIME NULL, |
| | | point_last_time DATETIME NULL, |
| | | point_coverage_days INT NOT NULL DEFAULT 0, |
| | | point_path_mileage DECIMAL(24,6) NULL, |
| | | point_vs_platform_rate DECIMAL(16,8) NULL, |
| | | platform_vs_ledger_rate DECIMAL(16,8) NULL, |
| | | ledger_vs_platform_rate DECIMAL(16,8) NULL, |
| | | average_trip_mileage DECIMAL(20,6) NULL, |
| | | supported_trip_count DECIMAL(20,6) NULL, |
| | | trip_support_rate DECIMAL(16,8) NULL, |
| | | endpoint_check TEXT NULL, |
| | | main_activity_regions TEXT NULL, |
| | | route_conclusion TEXT NULL, |
| | | risk_level VARCHAR(20) NULL, |
| | | created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, |
| | | updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, |
| | | UNIQUE KEY uk_ledger_sample_vehicle (task_id, city_name, enterprise_name, plate_no), |
| | | KEY idx_ledger_sample_period (inspection_period, city_name, plate_no) |
| | | ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; |
| | | |
| | | CREATE TABLE IF NOT EXISTS ledger_inspection_report ( |
| | | id BIGINT AUTO_INCREMENT PRIMARY KEY, |
| | | task_id BIGINT NOT NULL, |
| | | inspection_period VARCHAR(7) NOT NULL, |
| | | report_type VARCHAR(30) NOT NULL, |
| | | report_path VARCHAR(1000) NOT NULL, |
| | | report_sha256 CHAR(64) NOT NULL, |
| | | file_size BIGINT NOT NULL DEFAULT 0, |
| | | generated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, |
| | | UNIQUE KEY uk_ledger_report (task_id, report_type, report_sha256) |
| | | ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; |
| New file |
| | |
| | | -- Add normalized ledger plate components without changing the tractor matching key. |
| | | |
| | | SET @add_plate_no_raw = ( |
| | | SELECT IF( |
| | | COUNT(*) = 0, |
| | | 'ALTER TABLE `ledger_inspection_route` ADD COLUMN `plate_no_raw` VARCHAR(100) NULL AFTER `plate_no`', |
| | | 'SELECT 1' |
| | | ) |
| | | FROM information_schema.COLUMNS |
| | | WHERE TABLE_SCHEMA = DATABASE() |
| | | AND TABLE_NAME = 'ledger_inspection_route' |
| | | AND COLUMN_NAME = 'plate_no_raw' |
| | | ); |
| | | PREPARE add_plate_no_raw_stmt FROM @add_plate_no_raw; |
| | | EXECUTE add_plate_no_raw_stmt; |
| | | DEALLOCATE PREPARE add_plate_no_raw_stmt; |
| | | |
| | | SET @add_trailer_plate_no = ( |
| | | SELECT IF( |
| | | COUNT(*) = 0, |
| | | 'ALTER TABLE `ledger_inspection_route` ADD COLUMN `trailer_plate_no` VARCHAR(30) NULL AFTER `plate_no_raw`', |
| | | 'SELECT 1' |
| | | ) |
| | | FROM information_schema.COLUMNS |
| | | WHERE TABLE_SCHEMA = DATABASE() |
| | | AND TABLE_NAME = 'ledger_inspection_route' |
| | | AND COLUMN_NAME = 'trailer_plate_no' |
| | | ); |
| | | PREPARE add_trailer_plate_no_stmt FROM @add_trailer_plate_no; |
| | | EXECUTE add_trailer_plate_no_stmt; |
| | | DEALLOCATE PREPARE add_trailer_plate_no_stmt; |
| New file |
| | |
| | | -- Objective observations downloaded from the heavy-haul monitoring platform. |
| | | -- These tables are independent from enterprise ledger inspection tasks. |
| | | CREATE TABLE IF NOT EXISTS vehicle_track_daily ( |
| | | id BIGINT AUTO_INCREMENT PRIMARY KEY, |
| | | report_period VARCHAR(7) NOT NULL, |
| | | freight_enterprise_name VARCHAR(200) NOT NULL, |
| | | plate_no_raw VARCHAR(50) NOT NULL, |
| | | plate_no VARCHAR(30) NOT NULL, |
| | | track_date DATE NULL, |
| | | agency_name VARCHAR(200) NULL, |
| | | vehicle_label VARCHAR(100) NULL, |
| | | operator_name VARCHAR(100) NULL, |
| | | point_count BIGINT NOT NULL DEFAULT 0, |
| | | complete_mileage DECIMAL(24,6) NOT NULL DEFAULT 0, |
| | | abnormal_mileage DECIMAL(24,6) NOT NULL DEFAULT 0, |
| | | total_mileage DECIMAL(24,6) NOT NULL DEFAULT 0, |
| | | drift_count BIGINT NOT NULL DEFAULT 0, |
| | | anomaly_rate DECIMAL(12,8) NULL, |
| | | track_text VARCHAR(500) NULL, |
| | | approved_traction_tonnage DECIMAL(20,6) NULL, |
| | | route_text VARCHAR(500) NULL, |
| | | trips DECIMAL(20,6) NULL, |
| | | straight_distance DECIMAL(20,6) NULL, |
| | | cargo_tons DECIMAL(20,6) NULL, |
| | | source_file VARCHAR(1000) NOT NULL, |
| | | source_path_hash CHAR(64) NOT NULL, |
| | | source_sha256 CHAR(64) NOT NULL, |
| | | source_row INT NOT NULL, |
| | | created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, |
| | | updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, |
| | | UNIQUE KEY uk_vehicle_track_daily_source (report_period, source_sha256, source_row), |
| | | KEY idx_vehicle_track_daily_vehicle (report_period, plate_no, track_date), |
| | | KEY idx_vehicle_track_daily_enterprise (report_period, freight_enterprise_name) |
| | | ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; |
| | | |
| | | CREATE TABLE IF NOT EXISTS vehicle_track_point ( |
| | | id BIGINT AUTO_INCREMENT PRIMARY KEY, |
| | | report_period VARCHAR(7) NOT NULL, |
| | | unit_name VARCHAR(200) NOT NULL, |
| | | plate_no_raw VARCHAR(50) NOT NULL, |
| | | plate_no VARCHAR(30) NOT NULL, |
| | | terminal_time DATETIME NULL, |
| | | receive_time DATETIME NULL, |
| | | longitude DECIMAL(12,7) NULL, |
| | | latitude DECIMAL(12,7) NULL, |
| | | speed_text VARCHAR(50) NULL, |
| | | vehicle_status VARCHAR(200) NULL, |
| | | alarm_status VARCHAR(200) NULL, |
| | | operator_name VARCHAR(100) NULL, |
| | | location_text VARCHAR(500) NULL, |
| | | province_name VARCHAR(50) NULL, |
| | | prefecture_name VARCHAR(50) NULL, |
| | | county_name VARCHAR(50) NULL, |
| | | source_file VARCHAR(1000) NOT NULL, |
| | | source_path_hash CHAR(64) NOT NULL, |
| | | source_sha256 CHAR(64) NOT NULL, |
| | | source_row INT NOT NULL, |
| | | created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, |
| | | updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, |
| | | UNIQUE KEY uk_vehicle_track_point_source (report_period, source_sha256, source_row), |
| | | KEY idx_vehicle_track_point_vehicle (report_period, plate_no, terminal_time), |
| | | KEY idx_vehicle_track_point_unit (report_period, unit_name) |
| | | ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; |
| | | |
| | | CREATE TABLE IF NOT EXISTS vehicle_track_source_file ( |
| | | id BIGINT AUTO_INCREMENT PRIMARY KEY, |
| | | report_period VARCHAR(7) NOT NULL, |
| | | data_type VARCHAR(30) NOT NULL, |
| | | enterprise_name VARCHAR(200) NULL, |
| | | source_path VARCHAR(1000) NOT NULL, |
| | | source_name VARCHAR(255) NOT NULL, |
| | | source_path_hash CHAR(64) NOT NULL, |
| | | source_sha256 CHAR(64) NOT NULL, |
| | | file_size BIGINT NOT NULL DEFAULT 0, |
| | | sheet_name VARCHAR(200) NULL, |
| | | source_rows INT NOT NULL DEFAULT 0, |
| | | imported_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, |
| | | UNIQUE KEY uk_vehicle_track_source (report_period, data_type, source_sha256), |
| | | KEY idx_vehicle_track_source_period (report_period, data_type) |
| | | ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; |
| New file |
| | |
| | | #!/usr/bin/env python |
| | | # -*- coding: utf-8 -*- |
| | | """Build a review workbook from enterprise track point diagnostics.""" |
| | | |
| | | from __future__ import annotations |
| | | |
| | | import argparse |
| | | import json |
| | | from collections import Counter |
| | | from pathlib import Path |
| | | from typing import Any, Dict, Iterable, List, Optional, Sequence, Tuple |
| | | |
| | | from openpyxl import Workbook, load_workbook |
| | | from openpyxl.styles import Alignment, Border, Font, PatternFill, Side |
| | | from openpyxl.utils import get_column_letter |
| | | |
| | | |
| | | SELECTED_PLATES = { |
| | | "\u9102L1N523", |
| | | "\u9102L1J689", |
| | | "\u9102J20052D", |
| | | "\u9102LH832D", |
| | | "\u9102L53508", |
| | | "\u9102J50898", |
| | | "\u9102J0C916", |
| | | "\u9102J21646D", |
| | | "\u9102E19507", |
| | | "\u9102E69878", |
| | | "\u9102E68056", |
| | | "\u9102E36292", |
| | | } |
| | | EXISTING_PLATES = {"\u9102L1N523", "\u9102L1J689"} |
| | | PREVIOUS_SAMPLE_PLATES = {"\u9102J28801", "\u9102L1K202", "\u9102L5A039"} |
| | | |
| | | CN_DELIMITER = "\u3001" |
| | | |
| | | |
| | | def pct(value: Optional[float]) -> Optional[float]: |
| | | return value |
| | | |
| | | |
| | | def safe_support_ratio(value: Dict[str, Any]) -> Optional[float]: |
| | | return value["comparison"].get("trip_support_rate") |
| | | |
| | | |
| | | def unique(items: Iterable[str]) -> List[str]: |
| | | result: List[str] = [] |
| | | for item in items: |
| | | if item and item not in result: |
| | | result.append(item) |
| | | return result |
| | | |
| | | |
| | | def short_county(name: str) -> str: |
| | | parts = [part for part in name.split("|") if part] |
| | | if len(parts) >= 3: |
| | | return parts[-2] + parts[-1] |
| | | return parts[-1] if parts else name |
| | | |
| | | |
| | | def top_region_text(vehicle: Dict[str, Any], limit: int = 3) -> str: |
| | | regions = [] |
| | | for name, points, days in vehicle["points"]["top_counties"][:limit]: |
| | | regions.append(f"{short_county(name)}({points:,}点/{days}天)") |
| | | return "、".join(regions) if regions else "无有效活动区域" |
| | | |
| | | |
| | | def endpoint_text(vehicle: Dict[str, Any]) -> str: |
| | | parts = [] |
| | | for endpoint in vehicle["points"]["endpoints"]: |
| | | label = endpoint["label"] |
| | | days = endpoint["day_count"] |
| | | if days: |
| | | parts.append(f"{label}:{days}天") |
| | | elif endpoint.get("strict", True): |
| | | parts.append(f"{label}:未出现") |
| | | else: |
| | | parts.append(f"{label}:当前地点字段无法直接定位") |
| | | unresolved = vehicle["points"].get("unresolved_route_terms", []) |
| | | if unresolved: |
| | | parts.append(";".join(unresolved) + ":设施或道路名称,当前字段无法直接定位") |
| | | return ";".join(parts) if parts else "无可直接定位的线路端点" |
| | | |
| | | |
| | | def route_status(vehicle: Dict[str, Any]) -> str: |
| | | endpoints = vehicle["points"]["endpoints"] |
| | | strict_missing = [ |
| | | endpoint["label"] for endpoint in endpoints |
| | | if endpoint.get("strict", True) and endpoint["day_count"] == 0 |
| | | ] |
| | | weak_missing = [ |
| | | endpoint["label"] for endpoint in endpoints |
| | | if not endpoint.get("strict", True) and endpoint["day_count"] == 0 |
| | | ] |
| | | if strict_missing: |
| | | return "\u8def\u7ebf\u4e0d\u7b26" |
| | | if endpoints and any(endpoint["day_count"] > 0 for endpoint in endpoints): |
| | | if weak_missing: |
| | | return "\u8def\u7ebf\u65b9\u5411\u57fa\u672c\u76f8\u7b26" |
| | | return "\u8def\u7ebf\u65b9\u5411\u6709\u652f\u6301" |
| | | if vehicle["points"].get("unresolved_route_terms"): |
| | | return "\u7aef\u70b9\u540d\u79f0\u65e0\u6cd5\u76f4\u63a5\u6838\u9a8c" |
| | | return "\u8def\u7ebf\u65b9\u5411\u6709\u652f\u6301" |
| | | |
| | | |
| | | def risk_level(vehicle: Dict[str, Any]) -> str: |
| | | status = route_status(vehicle) |
| | | support = safe_support_ratio(vehicle) |
| | | difference = vehicle["comparison"].get("ledger_vs_platform_rate") |
| | | if status == "\u8def\u7ebf\u4e0d\u7b26": |
| | | return "\u9ad8" |
| | | if support is not None and support < 0.5: |
| | | return "\u9ad8" |
| | | if difference is not None and abs(difference) > 0.30: |
| | | return "\u9ad8" |
| | | return "\u4e2d" |
| | | |
| | | |
| | | def conclusion_text(vehicle: Dict[str, Any]) -> str: |
| | | status = route_status(vehicle) |
| | | comparisons = vehicle["comparison"] |
| | | ledger = vehicle["ledger"] |
| | | platform = vehicle["platform"] |
| | | region = top_region_text(vehicle) |
| | | strict_missing = [ |
| | | endpoint["label"] for endpoint in vehicle["points"]["endpoints"] |
| | | if endpoint.get("strict", True) and endpoint["day_count"] == 0 |
| | | ] |
| | | weak_missing = [ |
| | | endpoint["label"] for endpoint in vehicle["points"]["endpoints"] |
| | | if not endpoint.get("strict", True) and endpoint["day_count"] == 0 |
| | | ] |
| | | |
| | | if strict_missing: |
| | | route_clause = f"\u8f68\u8ff9\u672a\u51fa\u73b0{CN_DELIMITER.join(strict_missing)}\uff0c\u4e3b\u8981\u6d3b\u52a8\u533a\u57df\u4e3a{region}\uff0c\u4e0e\u7533\u62a5\u8def\u7ebf\u4e0d\u7b26\u3002" |
| | | elif status == "\u8def\u7ebf\u65b9\u5411\u57fa\u672c\u76f8\u7b26": |
| | | route_clause = f"\u8f68\u8ff9\u4e3b\u8981\u4f4d\u4e8e{region}\uff0c\u4e0e\u7533\u62a5\u8def\u7ebf\u65b9\u5411\u4e0d\u77db\u76fe\uff1b{CN_DELIMITER.join(weak_missing)}\u65e0\u6cd5\u4ec5\u51ed\u5f53\u524d\u5730\u70b9\u5b57\u6bb5\u76f4\u63a5\u5b9a\u4f4d\u3002" |
| | | elif status == "\u7aef\u70b9\u540d\u79f0\u65e0\u6cd5\u76f4\u63a5\u6838\u9a8c": |
| | | route_clause = f"\u8f68\u8ff9\u4e3b\u8981\u4f4d\u4e8e{region}\uff0c\u4f46\u7533\u62a5\u7aef\u70b9\u4e3a\u8bbe\u65bd\u6216\u9053\u8def\u540d\u79f0\uff0c\u65e0\u6cd5\u4ec5\u51ed\u5f53\u524d\u5730\u70b9\u5b57\u6bb5\u9010\u70b9\u5b9a\u4f4d\u3002" |
| | | else: |
| | | endpoint_days = "\u3001".join( |
| | | f"{endpoint['label']}{endpoint['day_count']}\u5929" |
| | | for endpoint in vehicle["points"]["endpoints"] |
| | | if endpoint["day_count"] > 0 |
| | | ) |
| | | route_clause = f"\u8f68\u8ff9\u4e2d\u5df2\u51fa\u73b0{endpoint_days}\uff0c\u7533\u62a5\u7ebf\u8def\u65b9\u5411\u6709\u652f\u6301\uff0c\u4f46\u7aef\u70b9\u51fa\u73b0\u5929\u6570\u8fdc\u4f4e\u4e8e\u7533\u62a5\u8d9f\u6b21\u3002" |
| | | |
| | | support = comparisons.get("platform_supported_trips") |
| | | support_rate = comparisons.get("trip_support_rate") |
| | | volume_clause = ( |
| | | f"\u5e73\u53f0\u8f68\u8ff9\u91cc\u7a0b{platform['total_mileage']:,.2f}\u516c\u91cc\uff0c" |
| | | f"\u4e3a\u53f0\u8d26\u91cc\u7a0b{ledger['mileage']:,.2f}\u516c\u91cc\u7684" |
| | | f"{platform['total_mileage'] / ledger['mileage'] * 100 if ledger['mileage'] else 0:.2f}%\uff1b" |
| | | f"\u6309\u53f0\u8d26\u5e73\u5747\u5355\u8d9f{comparisons['average_trip_mileage']:.2f}\u516c\u91cc\u6298\u7b97\uff0c" |
| | | f"\u8f68\u8ff9\u53ef\u652f\u6301\u7ea6{support:.2f}\u8d9f\uff0c" |
| | | f"\u4e3a\u7533\u62a5{ledger['trips']:.2f}\u8d9f\u7684{support_rate * 100:.2f}%\u3002" |
| | | if support is not None and support_rate is not None and comparisons.get("average_trip_mileage") |
| | | else "\u7f3a\u5c11\u8db3\u591f\u7684\u8d9f\u6b21\u6298\u7b97\u57fa\u7840\u3002" |
| | | ) |
| | | return route_clause + volume_clause |
| | | |
| | | |
| | | def issue_rows(vehicle: Dict[str, Any]) -> List[Tuple[str, str, str, str]]: |
| | | status = route_status(vehicle) |
| | | endpoints = vehicle["points"]["endpoints"] |
| | | strict_missing = [ |
| | | endpoint["label"] for endpoint in endpoints |
| | | if endpoint.get("strict", True) and endpoint["day_count"] == 0 |
| | | ] |
| | | weak_missing = [ |
| | | endpoint["label"] for endpoint in endpoints |
| | | if not endpoint.get("strict", True) and endpoint["day_count"] == 0 |
| | | ] |
| | | issues: List[Tuple[str, str, str, str]] = [] |
| | | if strict_missing: |
| | | issues.append(( |
| | | "\u8def\u7ebf\u4e0d\u7b26", |
| | | "\u9ad8", |
| | | f"\u672a\u76d1\u6d4b\u5230{CN_DELIMITER.join(strict_missing)}\uff0c\u4e3b\u8981\u6d3b\u52a8\u533a\u57df\u4e3a{top_region_text(vehicle)}\u3002", |
| | | "\u6838\u5bf9\u8f66\u8f86\u5b9e\u9645\u8fd0\u8f93\u4efb\u52a1\u6e90\u3001\u8fd0\u5355\u548c\u88c5\u5378\u8d27\u5730\u70b9\u3002", |
| | | )) |
| | | elif weak_missing: |
| | | issues.append(( |
| | | "\u5c40\u90e8\u7aef\u70b9\u65e0\u6cd5\u76f4\u63a5\u5b9a\u4f4d", |
| | | "\u4e2d", |
| | | f"{CN_DELIMITER.join(weak_missing)}\u4e3a\u53bf\u5185\u6216\u4e61\u9547\u5730\u540d\uff0c\u5f53\u524d\u5730\u70b9\u5b57\u6bb5\u4ec5\u5230\u53bf\u7ea7\u3002", |
| | | "\u7ed3\u5408\u8f68\u8ff9\u70b9\u5730\u56fe\u4eba\u5de5\u6838\u5bf9\u8d77\u8bab\u70b9\u3002", |
| | | )) |
| | | elif status == "\u7aef\u70b9\u540d\u79f0\u65e0\u6cd5\u76f4\u63a5\u6838\u9a8c": |
| | | issues.append(( |
| | | "\u7aef\u70b9\u65e0\u6cd5\u76f4\u63a5\u6838\u9a8c", |
| | | "\u4e2d", |
| | | "\u7533\u62a5\u7aef\u70b9\u4e3a\u8bbe\u65bd\u6216\u9053\u8def\u540d\u79f0\uff0c\u5f53\u524d\u5730\u70b9\u5b57\u6bb5\u65e0\u6cd5\u76f4\u63a5\u6620\u5c04\u3002", |
| | | "\u7ed3\u5408\u5730\u56fe\u5750\u6807\u3001\u505c\u8f66\u70b9\u548c\u88c5\u5378\u8d27\u51ed\u8bc1\u590d\u6838\u3002", |
| | | )) |
| | | else: |
| | | endpoint_days = [ |
| | | (endpoint["label"], endpoint["day_count"]) |
| | | for endpoint in endpoints |
| | | if endpoint["day_count"] > 0 |
| | | ] |
| | | issues.append(( |
| | | "\u7aef\u70b9\u51fa\u73b0\u9891\u6b21\u4e0d\u8db3", |
| | | "\u9ad8", |
| | | "\u8f68\u8ff9\u7aef\u70b9\u8986\u76d6\u4e3a" + "\u3001".join(f"{name}{days}\u5929" for name, days in endpoint_days) |
| | | + f"\uff0c\u8fdc\u4f4e\u4e8e\u53f0\u8d26{vehicle['ledger']['trips']:.2f}\u8d9f\u3002", |
| | | "\u6838\u5bf9\u8fd0\u5355\u3001\u8d27\u8fd0\u5355\u548c\u8f66\u8f86\u9014\u7ecf\u8def\u7ebf\u3002", |
| | | )) |
| | | difference = vehicle["comparison"].get("ledger_vs_platform_rate") |
| | | support_rate = vehicle["comparison"].get("trip_support_rate") |
| | | if difference is not None and (abs(difference) > 0.30 or (support_rate is not None and support_rate < 0.7)): |
| | | issues.append(( |
| | | "\u91cc\u7a0b\u6216\u8d9f\u6b21\u4e0d\u5339\u914d", |
| | | "\u9ad8", |
| | | f"\u53f0\u8d26\u91cc\u7a0b\u4e0e\u5e73\u53f0\u5dee\u5f02{difference * 100:+.2f}%\uff0c" |
| | | f"\u8f68\u8ff9\u53ef\u652f\u6301\u8d9f\u6b21\u6bd4\u4f8b{(support_rate or 0) * 100:.2f}%\u3002", |
| | | "\u8981\u6c42\u4f01\u4e1a\u63d0\u4f9b\u8fd0\u5355\u3001\u8fc7\u78c5\u5355\u3001\u88c5\u5378\u8d27\u8bb0\u5f55\u548c\u8fd0\u8f93\u5408\u540c\u3002", |
| | | )) |
| | | anomaly_rate = vehicle["platform"].get("anomaly_rate") |
| | | if anomaly_rate is not None and anomaly_rate >= 0.10: |
| | | issues.append(( |
| | | "\u5e73\u53f0\u5f02\u5e38\u91cc\u7a0b\u504f\u9ad8", |
| | | "\u4e2d", |
| | | f"\u5e73\u53f0\u5f02\u5e38\u91cc\u7a0b{vehicle['platform']['abnormal_mileage']:,.2f}\u516c\u91cc\uff0c" |
| | | f"\u5360\u603b\u91cc\u7a0b{anomaly_rate * 100:.2f}%\u3002", |
| | | "\u7ed3\u5408\u8f68\u8ff9\u6f02\u79fb\u70b9\u548c\u5b9e\u9645\u8fd0\u8f93\u8fdb\u884c\u590d\u6838\u3002", |
| | | )) |
| | | if vehicle["points"]["missing_segments"] or vehicle["points"]["missing_days"]: |
| | | issues.append(( |
| | | "\u8f68\u8ff9\u8986\u76d6\u4e0d\u5b8c\u6574", |
| | | "\u4e2d", |
| | | "\u7f3a\u5c11\u4e0b\u8f7d\u6587\u4ef6\uff1a" |
| | | + ("\u3001".join(vehicle["points"]["missing_segments"]) or "\u65e0") |
| | | + "\uff1b\u672a\u89c1\u8f68\u8ff9\u65e5\u671f\uff1a" |
| | | + ("\u3001".join(vehicle["points"]["missing_days"]) or "\u65e0"), |
| | | "\u8865\u4e0b\u7f3a\u5931\u6587\u4ef6\u540e\u590d\u7b97\u3002", |
| | | )) |
| | | return issues |
| | | |
| | | |
| | | def style_title(sheet: Any, title: str, column_count: int) -> None: |
| | | sheet.merge_cells(start_row=1, start_column=1, end_row=1, end_column=column_count) |
| | | cell = sheet.cell(1, 1, title) |
| | | cell.fill = PatternFill("solid", fgColor="D9EAF7") |
| | | cell.font = Font(bold=True, size=14, color="17365D") |
| | | cell.alignment = Alignment(horizontal="center", vertical="center") |
| | | sheet.row_dimensions[1].height = 28 |
| | | sheet.sheet_view.showGridLines = False |
| | | |
| | | |
| | | def style_header(sheet: Any, row: int, column_count: int) -> None: |
| | | fill = PatternFill("solid", fgColor="1F4E78") |
| | | font = Font(color="FFFFFF", bold=True, size=10) |
| | | 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) |
| | | sheet.row_dimensions[row].height = 38 |
| | | |
| | | |
| | | def style_table(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=True) |
| | | if row % 2 == 0: |
| | | cell.fill = PatternFill("solid", fgColor="F5F8FC") |
| | | sheet.row_dimensions[row].height = 64 |
| | | 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 set_widths(sheet: Any, widths: Sequence[float]) -> None: |
| | | for index, width in enumerate(widths, start=1): |
| | | sheet.column_dimensions[get_column_letter(index)].width = width |
| | | |
| | | |
| | | def write_summary_sheet(workbook: Workbook, vehicles: Sequence[Dict[str, Any]]) -> None: |
| | | sheet = workbook.create_sheet("\u62bd\u67e5\u8f66\u8f86\u8f68\u8ff9\u60c5\u51b5") |
| | | headers = [ |
| | | "\u5e02\u5dde", "\u4f01\u4e1a", "\u8f66\u724c\u53f7", "\u62bd\u67e5\u6279\u6b21", |
| | | "\u53f0\u8d26\u7ebf\u8def", "\u53f0\u8d26\u8d9f\u6b21", "\u53f0\u8d26\u91cc\u7a0b", |
| | | "\u5e73\u53f0\u8f68\u8ff9\u91cc\u7a0b", "\u53f0\u8d26/\u5e73\u53f0\u91cc\u7a0b\u5dee\u5f02\u7387", |
| | | "\u8f68\u8ff9\u70b9\u6570", "\u8f68\u8ff9\u8986\u76d6\u5929\u6570", "\u8f68\u8ff9\u70b9\u8def\u5f84\u91cc\u7a0b", |
| | | "\u8f68\u8ff9\u70b9/\u5e73\u53f0\u91cc\u7a0b\u5dee\u5f02\u7387", "\u53f0\u8d26\u5e73\u5747\u5355\u8d9f\u91cc\u7a0b", |
| | | "\u8f68\u8ff9\u53ef\u652f\u6301\u8d9f\u6b21", "\u8f68\u8ff9\u652f\u6301\u8d9f\u6b21\u6bd4\u4f8b", |
| | | "\u7aef\u70b9\u6838\u67e5", "\u4e3b\u8981\u6d3b\u52a8\u533a\u57df", "\u6838\u67e5\u7ed3\u8bba", "\u98ce\u9669\u7b49\u7ea7", |
| | | ] |
| | | style_title(sheet, "2026\u5e749\u6708 \u4f01\u4e1a\u53f0\u8d26\u62bd\u67e5\u8f66\u8f86\u8f68\u8ff9\u6838\u67e5\u60c5\u51b5", len(headers)) |
| | | for col, header in enumerate(headers, start=1): |
| | | sheet.cell(3, col, header) |
| | | for row_no, vehicle in enumerate(vehicles, start=4): |
| | | routes = unique(vehicle["ledger"]["routes"]) |
| | | values = [ |
| | | vehicle["city"], vehicle["enterprise"], vehicle["plate"], |
| | | "\u65e2\u6709\u6838\u67e5" if vehicle["plate"] in EXISTING_PLATES else "\u672c\u8f6e\u65b0\u589e", |
| | | "\uff1b".join(routes), vehicle["ledger"]["trips"], vehicle["ledger"]["mileage"], |
| | | vehicle["platform"]["total_mileage"], vehicle["comparison"]["ledger_vs_platform_rate"], |
| | | vehicle["points"]["unique_point_count"], vehicle["points"]["day_count"], |
| | | vehicle["points"]["raw_distance"], vehicle["comparison"]["raw_vs_platform_rate"], |
| | | vehicle["comparison"]["average_trip_mileage"], vehicle["comparison"]["platform_supported_trips"], |
| | | vehicle["comparison"]["trip_support_rate"], endpoint_text(vehicle), |
| | | top_region_text(vehicle), conclusion_text(vehicle), risk_level(vehicle), |
| | | ] |
| | | for col, value in enumerate(values, start=1): |
| | | sheet.cell(row_no, col, value) |
| | | last_row = 3 + len(vehicles) |
| | | style_header(sheet, 3, len(headers)) |
| | | style_table(sheet, 3, last_row, len(headers)) |
| | | set_widths(sheet, [9, 28, 14, 11, 24, 12, 14, 15, 18, 12, 12, 16, 18, 16, 16, 16, 32, 42, 70, 9]) |
| | | for row in range(4, last_row + 1): |
| | | for col in (6, 10, 11, 15): |
| | | sheet.cell(row, col).number_format = "#,##0.00" |
| | | for col in (7, 8, 12, 14): |
| | | sheet.cell(row, col).number_format = "#,##0.00" |
| | | for col in (9, 13, 16): |
| | | sheet.cell(row, col).number_format = "0.00%" |
| | | value = sheet.cell(row, 9).value |
| | | if isinstance(value, (int, float)): |
| | | color = "C00000" if abs(value) > 0.30 else "006100" |
| | | sheet.cell(row, 9).font = Font(color=color, bold=True) |
| | | risk = sheet.cell(row, 20).value |
| | | sheet.cell(row, 20).font = Font(color="C00000" if risk == "\u9ad8" else "BF9000", bold=True) |
| | | sheet.cell(row, 20).alignment = Alignment(horizontal="center", vertical="center") |
| | | |
| | | |
| | | def write_route_sheet(workbook: Workbook, vehicles: Sequence[Dict[str, Any]]) -> None: |
| | | sheet = workbook.create_sheet("\u8f68\u8ff9\u7ebf\u8def\u660e\u7ec6") |
| | | headers = [ |
| | | "\u5e02\u5dde", "\u4f01\u4e1a", "\u8f66\u724c\u53f7", "\u53f0\u8d26\u7ebf\u8def", "\u8d27\u7269\u7c7b\u578b", |
| | | "\u53f0\u8d26\u8d9f\u6b21", "\u53f0\u8d26\u7ebf\u8def\u91cc\u7a0b", "\u53f0\u8d26\u5355\u8d9f\u91cc\u7a0b", |
| | | "\u7aef\u70b9\u8f68\u8ff9\u8bc1\u636e", "\u7ebf\u8def\u6838\u67e5\u610f\u89c1", |
| | | ] |
| | | style_title(sheet, "2026\u5e749\u6708 \u62bd\u67e5\u8f66\u8f86\u8f68\u8ff9\u7ebf\u8def\u660e\u7ec6", len(headers)) |
| | | for col, header in enumerate(headers, start=1): |
| | | sheet.cell(3, col, header) |
| | | row_no = 4 |
| | | for vehicle in vehicles: |
| | | endpoint_by_label = {item["label"]: item for item in vehicle["points"]["endpoints"]} |
| | | for group in vehicle["ledger"]["route_groups"]: |
| | | route = group["route"] |
| | | matched_endpoints = [ |
| | | endpoint for endpoint in vehicle["points"]["endpoints"] |
| | | if any(alias in route for alias in endpoint["aliases"]) |
| | | ] |
| | | evidence_parts = [] |
| | | verdict_parts = [] |
| | | for endpoint in matched_endpoints: |
| | | if endpoint["day_count"]: |
| | | evidence_parts.append(f"{endpoint['label']}:{endpoint['day_count']}天/{endpoint['point_count']:,}点") |
| | | elif endpoint.get("strict", True): |
| | | evidence_parts.append(f"{endpoint['label']}:未出现") |
| | | verdict_parts.append(f"\u672a\u76d1\u6d4b\u5230{endpoint['label']}\uff0c\u8def\u7ebf\u4e0d\u7b26") |
| | | else: |
| | | evidence_parts.append(f"{endpoint['label']}:\u5f53\u524d\u5730\u70b9\u5b57\u6bb5\u65e0\u6cd5\u76f4\u63a5\u5b9a\u4f4d") |
| | | verdict_parts.append(f"{endpoint['label']}\u4e3a\u53bf\u5185\u6216\u4e61\u9547\u5730\u540d\uff0c\u884c\u653f\u533a\u57df\u65b9\u5411\u4e0d\u77db\u76fe") |
| | | unresolved = [ |
| | | term for term in vehicle["points"].get("unresolved_route_terms", []) |
| | | if term in route |
| | | ] |
| | | if unresolved: |
| | | evidence_parts.append("\u3001".join(unresolved) + "\uff1a\u672a\u76f4\u63a5\u5b9a\u4f4d") |
| | | verdict_parts.append("\u7aef\u70b9\u4e3a\u8bbe\u65bd\u6216\u9053\u8def\u540d\u79f0\uff0c\u9700\u7ed3\u5408\u5730\u56fe\u5750\u6807\u4eba\u5de5\u6838\u5bf9") |
| | | if matched_endpoints and all(item["day_count"] > 0 for item in matched_endpoints if item.get("strict", True)): |
| | | verdict_parts.append("\u8def\u7ebf\u65b9\u5411\u6709\u8f68\u8ff9\u652f\u6301") |
| | | average_trip = group["mileage"] / group["trips"] if group["trips"] else None |
| | | values = [ |
| | | vehicle["city"], vehicle["enterprise"], vehicle["plate"], route, |
| | | "\u3001".join(group["cargo_types"]), group["trips"], group["mileage"], average_trip, |
| | | "\uff1b".join(evidence_parts) or "\u65e0\u53ef\u76f4\u63a5\u5b9a\u4f4d\u7aef\u70b9", |
| | | "\uff1b".join(unique(verdict_parts)) or "\u9700\u7ed3\u5408\u8f68\u8ff9\u5730\u56fe\u590d\u6838", |
| | | ] |
| | | for col, value in enumerate(values, start=1): |
| | | sheet.cell(row_no, col, value) |
| | | row_no += 1 |
| | | last_row = row_no - 1 |
| | | style_header(sheet, 3, len(headers)) |
| | | style_table(sheet, 3, last_row, len(headers)) |
| | | set_widths(sheet, [9, 28, 14, 45, 15, 12, 16, 16, 38, 44]) |
| | | for row in range(4, last_row + 1): |
| | | sheet.cell(row, 6).number_format = "#,##0.00" |
| | | for col in (7, 8): |
| | | sheet.cell(row, col).number_format = "#,##0.00" |
| | | |
| | | |
| | | def write_activity_sheet(workbook: Workbook, vehicles: Sequence[Dict[str, Any]]) -> None: |
| | | sheet = workbook.create_sheet("\u6d3b\u52a8\u533a\u57df\u6c47\u603b") |
| | | headers = [ |
| | | "\u5e02\u5dde", "\u4f01\u4e1a", "\u8f66\u724c\u53f7", "\u7701", "\u5e02\u5dde", |
| | | "\u53bf\u5e02\u533a", "\u5b9a\u4f4d\u70b9\u6570", "\u8986\u76d6\u5929\u6570", "\u70b9\u4f4d\u5360\u6bd4", |
| | | ] |
| | | style_title(sheet, "2026\u5e749\u6708 \u62bd\u67e5\u8f66\u8f86\u4e3b\u8981\u6d3b\u52a8\u533a\u57df", len(headers)) |
| | | for col, header in enumerate(headers, start=1): |
| | | sheet.cell(3, col, header) |
| | | row_no = 4 |
| | | for vehicle in vehicles: |
| | | total = vehicle["points"]["unique_point_count"] |
| | | for name, point_count, day_count in vehicle["points"]["top_counties"]: |
| | | parts = name.split("|") |
| | | province = parts[0] if len(parts) > 0 else "" |
| | | prefecture = parts[1] if len(parts) > 1 else "" |
| | | county = parts[2] if len(parts) > 2 else "" |
| | | values = [ |
| | | vehicle["city"], vehicle["enterprise"], vehicle["plate"], province, |
| | | prefecture, county, point_count, day_count, point_count / total if total else None, |
| | | ] |
| | | for col, value in enumerate(values, start=1): |
| | | sheet.cell(row_no, col, value) |
| | | row_no += 1 |
| | | last_row = row_no - 1 |
| | | style_header(sheet, 3, len(headers)) |
| | | style_table(sheet, 3, last_row, len(headers)) |
| | | set_widths(sheet, [9, 28, 14, 12, 14, 16, 13, 12, 12]) |
| | | for row in range(4, last_row + 1): |
| | | sheet.cell(row, 7).number_format = "#,##0" |
| | | sheet.cell(row, 8).number_format = "#,##0" |
| | | sheet.cell(row, 9).number_format = "0.00%" |
| | | |
| | | |
| | | def write_file_sheet(workbook: Workbook, vehicles: Sequence[Dict[str, Any]]) -> None: |
| | | sheet = workbook.create_sheet("\u8f68\u8ff9\u6587\u4ef6\u6e05\u5355") |
| | | headers = [ |
| | | "\u5e02\u5dde", "\u4f01\u4e1a", "\u8f66\u724c\u53f7", "\u6587\u4ef6\u540d", "\u884c\u6570", |
| | | "\u6709\u6548\u5b9a\u4f4d\u70b9", "\u9996\u6b21\u65f6\u95f4", "\u672b\u6b21\u65f6\u95f4", |
| | | "\u6587\u4ef6\u5185\u4f01\u4e1a", "\u6587\u4ef6\u5185\u8f66\u724c", "SHA256", |
| | | ] |
| | | style_title(sheet, "2026\u5e749\u6708 \u8f68\u8ff9\u70b9\u6587\u4ef6\u5b8c\u6574\u6027\u6e05\u5355", len(headers)) |
| | | for col, header in enumerate(headers, start=1): |
| | | sheet.cell(3, col, header) |
| | | row_no = 4 |
| | | for vehicle in vehicles: |
| | | for file_item in vehicle["files"]: |
| | | values = [ |
| | | vehicle["city"], vehicle["enterprise"], vehicle["plate"], |
| | | Path(file_item["path"]).name, file_item["row_count"], file_item["valid_point_count"], |
| | | file_item["first_time"], file_item["last_time"], |
| | | "\u3001".join(file_item["companies"].keys()), "\u3001".join(file_item["plates"].keys()), |
| | | file_item["sha256"], |
| | | ] |
| | | for col, value in enumerate(values, start=1): |
| | | sheet.cell(row_no, col, value) |
| | | row_no += 1 |
| | | last_row = row_no - 1 |
| | | style_header(sheet, 3, len(headers)) |
| | | style_table(sheet, 3, last_row, len(headers)) |
| | | sheet.row_dimensions[3].height = 38 |
| | | set_widths(sheet, [9, 28, 14, 64, 12, 14, 20, 20, 30, 15, 68]) |
| | | for row in range(4, last_row + 1): |
| | | sheet.row_dimensions[row].height = 28 |
| | | sheet.cell(row, 5).number_format = "#,##0" |
| | | sheet.cell(row, 6).number_format = "#,##0" |
| | | |
| | | |
| | | def write_issue_sheet(workbook: Workbook, vehicles: Sequence[Dict[str, Any]]) -> None: |
| | | sheet = workbook.create_sheet("\u95ee\u9898\u660e\u7ec6") |
| | | headers = ["\u5e02\u5dde", "\u4f01\u4e1a", "\u8f66\u724c\u53f7", "\u95ee\u9898\u7c7b\u578b", "\u4e25\u91cd\u7a0b\u5ea6", "\u95ee\u9898\u63cf\u8ff0", "\u6838\u67e5\u5efa\u8bae"] |
| | | style_title(sheet, "2026\u5e749\u6708 \u62bd\u67e5\u8f66\u8f86\u8f68\u8ff9\u95ee\u9898\u660e\u7ec6", len(headers)) |
| | | for col, header in enumerate(headers, start=1): |
| | | sheet.cell(3, col, header) |
| | | row_no = 4 |
| | | for vehicle in vehicles: |
| | | for issue_type, severity, detail, suggestion in issue_rows(vehicle): |
| | | values = [vehicle["city"], vehicle["enterprise"], vehicle["plate"], issue_type, severity, detail, suggestion] |
| | | for col, value in enumerate(values, start=1): |
| | | sheet.cell(row_no, col, value) |
| | | row_no += 1 |
| | | last_row = row_no - 1 |
| | | style_header(sheet, 3, len(headers)) |
| | | style_table(sheet, 3, last_row, len(headers)) |
| | | set_widths(sheet, [9, 28, 14, 22, 10, 72, 46]) |
| | | for row in range(4, last_row + 1): |
| | | severity = sheet.cell(row, 5).value |
| | | sheet.cell(row, 5).font = Font(color="C00000" if severity == "\u9ad8" else "BF9000", bold=True) |
| | | sheet.cell(row, 5).alignment = Alignment(horizontal="center", vertical="center") |
| | | |
| | | |
| | | def write_method_sheet(workbook: Workbook, vehicles: Sequence[Dict[str, Any]]) -> None: |
| | | sheet = workbook.create_sheet("\u6838\u67e5\u53e3\u5f84") |
| | | style_title(sheet, "2026\u5e749\u6708 \u62bd\u67e5\u8f66\u8f86\u8f68\u8ff9\u70b9\u6838\u67e5\u53e3\u5f84", 2) |
| | | rows = [ |
| | | ("\u6570\u636e\u8303\u56f4", "\u5171 12 \u8f86\u62bd\u67e5\u8f66\uff0c\u5305\u62ec\u54b8\u5b81 4 \u8f86\u3001\u9ec4\u5188 4 \u8f86\u3001\u5b9c\u660c 4 \u8f86\u3002\u53f0\u8d26\u3001\u5e73\u53f0\u6708\u5ea6\u8f68\u8ff9\u548c\u8f66\u8f86\u8f68\u8ff9\u70b9\u4e09\u7c7b\u6570\u636e\u4ea4\u53c9\u6838\u5bf9\u3002"), |
| | | ("\u4e0b\u8f7d\u6587\u4ef6\u8986\u76d6", "\u91cd\u8f7d\u5e73\u53f0\u5355\u6b21\u6700\u591a\u4e0b\u8f7d 3 \u5929\uff0c\u56e0\u6b64\u5b8c\u6574\u6708\u8f68\u8ff9\u70b9\u901a\u5e38\u7531\u591a\u4e2a\u4e0b\u8f7d\u6587\u4ef6\u7ec4\u6210\u3002\u6587\u4ef6\u5929\u6570\u4ec5\u7528\u4e8e\u68c0\u67e5\u4e0b\u8f7d\u8986\u76d6\uff0c\u4e0d\u4f5c\u4e3a\u8f68\u8ff9\u70b9\u6570\u636e\u5b57\u6bb5\u3002\u672c\u6b21 11 \u8f86\u5404 10 \u4e2a\u6587\u4ef6\uff0c\u9102E68056 \u4e3a 9 \u4e2a\u6587\u4ef6\uff0c\u7f3a\u5c1125\u65e5-27\u65e5\u6587\u4ef6\u3002"), |
| | | ("\u8f68\u8ff9\u70b9\u91cc\u7a0b", "\u5c06\u6bcf\u4e2a\u8f66\u8f86\u7684\u8f68\u8ff9\u70b9\u6309\u7ec8\u7aef\u65f6\u95f4\u6392\u5e8f\uff0c\u5bf9\u76f8\u90bb\u5b9a\u4f4d\u70b9\u6309\u7403\u9762\u8ddd\u79bb\u9010\u6bb5\u7d2f\u52a0\uff0c\u5f97\u5230\u201c\u8f68\u8ff9\u70b9\u8def\u5f84\u91cc\u7a0b\u201d\u3002\u8be5\u503c\u4e0e\u91cd\u8f7d\u5e73\u53f0\u201c\u603b\u91cc\u7a0b\u201d\u57fa\u672c\u4e00\u81f4\uff0c\u8bc1\u660e\u6708\u5ea6\u6c47\u603b\u4e0e\u8f68\u8ff9\u70b9\u660e\u7ec6\u53ef\u76f8\u4e92\u5370\u8bc1\u3002"), |
| | | ("\u8d9f\u6b21\u6298\u7b97", "\u53f0\u8d26\u5e73\u5747\u5355\u8d9f\u91cc\u7a0b = \u53f0\u8d26\u8f66\u8f86\u603b\u91cc\u7a0b \u00f7 \u53f0\u8d26\u603b\u8d9f\u6b21\u3002\u8f68\u8ff9\u53ef\u652f\u6301\u8d9f\u6b21 = \u5e73\u53f0\u603b\u91cc\u7a0b \u00f7 \u53f0\u8d26\u5e73\u5747\u5355\u8d9f\u91cc\u7a0b\u3002\u8be5\u503c\u7528\u4e8e\u5224\u65ad\u91cc\u7a0b\u4e0e\u8d9f\u6b21\u7684\u6570\u91cf\u7ea7\u662f\u5426\u5339\u914d\uff0c\u4e0d\u4ee3\u8868\u8f68\u8ff9\u80fd\u9010\u8d9f\u8bc6\u522b\u88c5\u5378\u8d27\u4e8b\u4ef6\u3002"), |
| | | ("\u7aef\u70b9\u5b9a\u4f4d", "\u7aef\u70b9\u6838\u67e5\u4f7f\u7528\u8f68\u8ff9\u70b9\u201c\u5f53\u524d\u5730\u70b9\u201d\u5b57\u6bb5\u7684\u7701\u3001\u5e02\u5dde\u3001\u53bf\u5e02\u533a\u4fe1\u606f\u3002\u4f01\u4e1a\u540d\u79f0\u3001\u56ed\u533a\u540d\u79f0\u548c\u9053\u8def\u540d\u79f0\u4e0d\u80fd\u76f4\u63a5\u6620\u5c04\u65f6\uff0c\u6807\u8bb0\u4e3a\u65e0\u6cd5\u76f4\u63a5\u6838\u9a8c\u3002"), |
| | | ("\u53bf\u5185\u77ed\u9014", "\u901a\u57ce-\u9ec4\u9f99\u7b49\u53bf\u5185\u6216\u4e61\u9547\u7ebf\u8def\uff0c\u7531\u4e8e\u201c\u5f53\u524d\u5730\u70b9\u201d\u4ec5\u5230\u53bf\u7ea7\uff0c\u53ea\u80fd\u5224\u65ad\u884c\u653f\u533a\u57df\u548c\u884c\u9a76\u65b9\u5411\u662f\u5426\u77db\u76fe\uff0c\u4e0d\u76f4\u63a5\u8ba4\u5b9a\u7aef\u70b9\u672a\u5230\u8fbe\u3002"), |
| | | ("\u7ed3\u8bba\u8fb9\u754c", "\u8def\u7ebf\u660e\u663e\u4e0d\u7b26\u6216\u8f68\u8ff9\u53ef\u652f\u6301\u8d9f\u6b21\u8fdc\u4f4e\u4e8e\u53f0\u8d26\u65f6\uff0c\u5217\u4e3a\u9ad8\u98ce\u9669\u3002\u8f68\u8ff9\u70b9\u80fd\u8bc1\u660e\u8f66\u8f86\u5b9e\u9645\u6d3b\u52a8\u533a\u57df\u548c\u91cc\u7a0b\u89c4\u6a21\uff0c\u4f46\u65e0\u8d27\u8fd0\u5355\u3001\u8fc7\u78c5\u5355\u65f6\uff0c\u4e0d\u80fd\u76f4\u63a5\u8ba4\u5b9a\u6bcf\u4e00\u8d9f\u7684\u8d27\u7269\u91cd\u91cf\u548c\u8d38\u6613\u80cc\u666f\u3002"), |
| | | ] |
| | | sheet.cell(3, 1, "\u9879\u76ee") |
| | | sheet.cell(3, 2, "\u8bf4\u660e") |
| | | for row_no, (name, detail) in enumerate(rows, start=4): |
| | | sheet.cell(row_no, 1, name) |
| | | sheet.cell(row_no, 2, detail) |
| | | last_row = 3 + len(rows) |
| | | style_header(sheet, 3, 2) |
| | | style_table(sheet, 3, last_row, 2) |
| | | set_widths(sheet, [18, 120]) |
| | | for row in range(4, last_row + 1): |
| | | sheet.row_dimensions[row].height = 72 |
| | | |
| | | |
| | | def update_existing_overview(workbook: Workbook) -> None: |
| | | if "\u8f66\u8f86\u91cc\u7a0b\u5dee\u5f02\u60c5\u51b5" not in workbook.sheetnames: |
| | | return |
| | | sheet = workbook["\u8f66\u8f86\u91cc\u7a0b\u5dee\u5f02\u60c5\u51b5"] |
| | | for row in range(4, sheet.max_row + 1): |
| | | plate = str(sheet.cell(row, 3).value or "").strip() |
| | | if plate in SELECTED_PLATES: |
| | | sheet.cell(row, 12, "\u672c\u6b21\u62bd\u67e5\u8f66\u8f86") |
| | | elif plate in PREVIOUS_SAMPLE_PLATES: |
| | | sheet.cell(row, 12, "\u5386\u53f2\u62bd\u67e5\u8f66\u8f86") |
| | | |
| | | |
| | | def build_workbook(diagnostics_path: Path, output_path: Path, base_workbook: Optional[Path]) -> Dict[str, Any]: |
| | | data = json.loads(diagnostics_path.read_text(encoding="utf-8")) |
| | | vehicles = data["vehicles"] |
| | | if base_workbook and base_workbook.is_file(): |
| | | workbook = load_workbook(base_workbook) |
| | | update_existing_overview(workbook) |
| | | else: |
| | | workbook = Workbook() |
| | | default_sheet = workbook.active |
| | | workbook.remove(default_sheet) |
| | | for name in ("\u62bd\u67e5\u8f66\u8f86\u8f68\u8ff9\u60c5\u51b5", "\u8f68\u8ff9\u7ebf\u8def\u660e\u7ec6", |
| | | "\u6d3b\u52a8\u533a\u57df\u6c47\u603b", "\u8f68\u8ff9\u6587\u4ef6\u6e05\u5355", |
| | | "\u95ee\u9898\u660e\u7ec6", "\u6838\u67e5\u53e3\u5f84"): |
| | | if name in workbook.sheetnames: |
| | | workbook.remove(workbook[name]) |
| | | write_summary_sheet(workbook, vehicles) |
| | | write_route_sheet(workbook, vehicles) |
| | | write_activity_sheet(workbook, vehicles) |
| | | write_file_sheet(workbook, vehicles) |
| | | write_issue_sheet(workbook, vehicles) |
| | | write_method_sheet(workbook, vehicles) |
| | | for sheet in workbook.worksheets: |
| | | if sheet.title == "\u62bd\u67e5\u8f66\u8f86\u8f68\u8ff9\u60c5\u51b5": |
| | | sheet.sheet_properties.pageSetUpPr.fitToPage = True |
| | | sheet.page_setup.orientation = "landscape" |
| | | sheet.page_setup.fitToWidth = 1 |
| | | sheet.page_setup.fitToHeight = 0 |
| | | output_path.parent.mkdir(parents=True, exist_ok=True) |
| | | workbook.save(output_path) |
| | | issues = sum(len(issue_rows(vehicle)) for vehicle in vehicles) |
| | | return { |
| | | "output": str(output_path), |
| | | "vehicle_count": len(vehicles), |
| | | "file_count": sum(vehicle["points"]["file_count"] for vehicle in vehicles), |
| | | "point_count": sum(vehicle["points"]["unique_point_count"] for vehicle in vehicles), |
| | | "issue_count": issues, |
| | | "risk_counts": dict(Counter(risk_level(vehicle) for vehicle in vehicles)), |
| | | } |
| | | |
| | | |
| | | def main(argv: Optional[Sequence[str]] = None) -> int: |
| | | parser = argparse.ArgumentParser(description=__doc__) |
| | | parser.add_argument("--diagnostics", required=True) |
| | | parser.add_argument("--output", required=True) |
| | | parser.add_argument("--base-workbook", default="") |
| | | args = parser.parse_args(argv) |
| | | result = build_workbook( |
| | | Path(args.diagnostics), |
| | | Path(args.output), |
| | | Path(args.base_workbook) if args.base_workbook else None, |
| | | ) |
| | | print(json.dumps(result, ensure_ascii=False, indent=2)) |
| | | return 0 |
| | | |
| | | |
| | | if __name__ == "__main__": |
| | | raise SystemExit(main()) |
| New file |
| | |
| | | #!/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()) |
| New file |
| | |
| | | param( |
| | | [Parameter(Mandatory=$true)][string]$InputRoot, |
| | | [Parameter(Mandatory=$true)][string]$OutputRoot, |
| | | [Parameter(Mandatory=$true)][string]$ManifestPath |
| | | ) |
| | | |
| | | $ErrorActionPreference = 'Stop' |
| | | if (-not [System.IO.Path]::IsPathRooted($OutputRoot)) { $OutputRoot = Join-Path (Get-Location).Path $OutputRoot } |
| | | if (-not [System.IO.Path]::IsPathRooted($ManifestPath)) { $ManifestPath = Join-Path (Get-Location).Path $ManifestPath } |
| | | New-Item -ItemType Directory -Force -Path $OutputRoot | Out-Null |
| | | $OutputRoot = (Resolve-Path -LiteralPath $OutputRoot).Path |
| | | $ManifestPath = [System.IO.Path]::GetFullPath($ManifestPath) |
| | | $before = @(Get-Process EXCEL -ErrorAction SilentlyContinue | Select-Object -ExpandProperty Id) |
| | | $files = @(Get-ChildItem -LiteralPath $InputRoot -Recurse -File | |
| | | Where-Object { $_.Extension -ieq '.xls' -and $_.Name -match '^\p{IsCJKUnifiedIdeographs}[^\[\]]+\[[^\[\]]+\]\.xls$' -and $_.DirectoryName -notmatch '\\备份(\\|$)' } | |
| | | Sort-Object FullName) |
| | | |
| | | $utf8 = New-Object System.Text.UTF8Encoding($false) |
| | | $writer = New-Object System.IO.StreamWriter($ManifestPath, $false, $utf8) |
| | | $excel = $null |
| | | $converted = 0 |
| | | try { |
| | | $excel = New-Object -ComObject Excel.Application |
| | | $excel.Visible = $false |
| | | $excel.DisplayAlerts = $false |
| | | $writer.WriteLine("index`tsource_path`toutput_path`tstatus") |
| | | for ($i = 0; $i -lt $files.Count; $i++) { |
| | | $file = $files[$i] |
| | | $dest = Join-Path $OutputRoot ('raw_{0:D4}.xlsx' -f ($i + 1)) |
| | | $status = 'converted' |
| | | if (Test-Path -LiteralPath $dest) { |
| | | $jsonPath = Join-Path $OutputRoot ('raw_{0:D4}.json' -f ($i + 1)) |
| | | $status = 'exists' |
| | | } else { |
| | | $workbook = $null |
| | | try { |
| | | $workbook = $excel.Workbooks.Open($file.FullName, 0, $true) |
| | | $workbook.SaveAs($dest, 51) |
| | | $converted++ |
| | | } finally { |
| | | if ($null -ne $workbook) { $workbook.Close($false) } |
| | | } |
| | | $meta = [ordered]@{source_path=$file.FullName; output_path=$dest; source_size=$file.Length} |
| | | $metaJson = $meta | ConvertTo-Json -Compress |
| | | [System.IO.File]::WriteAllText((Join-Path $OutputRoot ('raw_{0:D4}.json' -f ($i + 1))), $metaJson, $utf8) |
| | | } |
| | | $writer.WriteLine(("{0}`t{1}`t{2}`t{3}" -f ($i + 1), $file.FullName, $dest, $status)) |
| | | } |
| | | } finally { |
| | | $writer.Close() |
| | | if ($null -ne $excel) { $excel.Quit() } |
| | | [GC]::Collect() |
| | | [GC]::WaitForPendingFinalizers() |
| | | } |
| | | $after = @(Get-Process EXCEL -ErrorAction SilentlyContinue | Select-Object -ExpandProperty Id) |
| | | $newPids = @($after | Where-Object { $_ -notin $before }) |
| | | if ($newPids.Count -gt 0) { |
| | | Start-Sleep -Seconds 1 |
| | | foreach ($pidValue in $newPids) { |
| | | $proc = Get-Process -Id $pidValue -ErrorAction SilentlyContinue |
| | | if ($null -ne $proc) { Stop-Process -Id $pidValue -Force } |
| | | } |
| | | } |
| | | "RAWFILES=$($files.Count) CONVERTED=$converted" |
| New file |
| | |
| | | #!/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()) |
| New file |
| | |
| | | #!/usr/bin/env python |
| | | # -*- coding: utf-8 -*- |
| | | """Inspect raw vehicle track points against enterprise ledger routes.""" |
| | | |
| | | from __future__ import annotations |
| | | |
| | | import argparse |
| | | import calendar |
| | | import hashlib |
| | | import json |
| | | import math |
| | | import re |
| | | import struct |
| | | from collections import Counter, defaultdict |
| | | from dataclasses import dataclass, field |
| | | from datetime import date, datetime |
| | | from pathlib import Path |
| | | from typing import Any, Dict, Iterable, List, Optional, Sequence, Tuple |
| | | |
| | | import sys |
| | | |
| | | |
| | | PROJECT_ROOT = Path(__file__).resolve().parents[1] |
| | | if str(PROJECT_ROOT) not in sys.path: |
| | | sys.path.insert(0, str(PROJECT_ROOT)) |
| | | |
| | | from tools.enterprise_ledger_inspection import ( # noqa: E402 |
| | | PROFILES, |
| | | aggregate_ledger, |
| | | aggregate_tracks, |
| | | canonical_plate, |
| | | parse_ledger, |
| | | parse_track_summary, |
| | | ) |
| | | |
| | | |
| | | @dataclass(frozen=True) |
| | | class Endpoint: |
| | | label: str |
| | | aliases: Tuple[str, ...] |
| | | strict: bool = True |
| | | |
| | | |
| | | @dataclass(frozen=True) |
| | | class VehicleSpec: |
| | | profile_key: str |
| | | plate: str |
| | | directory: str |
| | | endpoints: Tuple[Endpoint, ...] = () |
| | | unresolved_route_terms: Tuple[str, ...] = () |
| | | |
| | | |
| | | SELECTED_VEHICLES: Tuple[VehicleSpec, ...] = ( |
| | | VehicleSpec( |
| | | "anxin", |
| | | "\u9102L1N523", |
| | | "\u54b8\u5b81/\u5b89\u6b23", |
| | | ( |
| | | Endpoint("\u54b8\u5b81", ("\u54b8\u5b81",)), |
| | | Endpoint("\u5929\u6d25", ("\u5929\u6d25",)), |
| | | Endpoint("\u5d07\u9633", ("\u5d07\u9633",)), |
| | | ), |
| | | ), |
| | | VehicleSpec( |
| | | "demin", |
| | | "\u9102L1J689", |
| | | "\u54b8\u5b81/\u5fb7\u654f", |
| | | ( |
| | | Endpoint("\u60e0\u5dde", ("\u60e0\u5dde",)), |
| | | Endpoint("\u6c5f\u95e8", ("\u6c5f\u95e8",)), |
| | | Endpoint("\u4f5b\u5c71", ("\u4f5b\u5c71",)), |
| | | ), |
| | | ), |
| | | VehicleSpec( |
| | | "datong", |
| | | "\u9102J20052D", |
| | | "\u9ec4\u5188/\u5927\u901a", |
| | | (Endpoint("\u6d60\u6c34", ("\u6d60\u6c34",)),), |
| | | ), |
| | | VehicleSpec( |
| | | "huinong", |
| | | "\u9102LH832D", |
| | | "\u54b8\u5b81/\u60e0\u4fac", |
| | | ( |
| | | Endpoint("\u54b8\u5b81", ("\u54b8\u5b81",)), |
| | | Endpoint("\u6f5c\u6c5f", ("\u6f5c\u6c5f",)), |
| | | ), |
| | | ), |
| | | VehicleSpec( |
| | | "luchang", |
| | | "\u9102L53508", |
| | | "\u54b8\u5b81/\u8def\u7545\u901a", |
| | | ( |
| | | Endpoint("\u901a\u57ce", ("\u901a\u57ce",)), |
| | | Endpoint("\u9ec4\u9f99", ("\u9ec4\u9f99",), False), |
| | | ), |
| | | ), |
| | | VehicleSpec( |
| | | "guangfa", |
| | | "\u9102J50898", |
| | | "\u9ec4\u5188/\u5e7f\u53d1", |
| | | ( |
| | | Endpoint("\u9ec4\u6885", ("\u9ec4\u6885",)), |
| | | Endpoint("\u4e49\u4e4c", ("\u4e49\u4e4c",)), |
| | | ), |
| | | ), |
| | | VehicleSpec( |
| | | "kaiying", |
| | | "\u9102J0C916", |
| | | "\u9ec4\u5188/\u51ef\u8d62", |
| | | unresolved_route_terms=("\u5b89\u9053\u9ea6", "\u946b\u745e\u666f"), |
| | | ), |
| | | VehicleSpec( |
| | | "xindafei", |
| | | "\u9102J21646D", |
| | | "\u9ec4\u5188/\u946b\u8fbe\u98de", |
| | | ( |
| | | Endpoint("\u9ec4\u5dde", ("\u9ec4\u5dde",)), |
| | | Endpoint("\u76d0\u57ce", ("\u76d0\u57ce",)), |
| | | ), |
| | | ), |
| | | VehicleSpec( |
| | | "shengda", |
| | | "\u9102E19507", |
| | | "\u5b9c\u660c/\u665f\u8fbe", |
| | | ( |
| | | Endpoint("\u5408\u80a5", ("\u5408\u80a5",)), |
| | | Endpoint("\u6b66\u6c49", ("\u6b66\u6c49",)), |
| | | Endpoint("\u5b9c\u660c", ("\u5b9c\u660c",)), |
| | | ), |
| | | ("\u5174\u798f\u7535\u5b50", "\u8054\u4ed5(\u6e56\u5317)\u65b0\u6750\u6599"), |
| | | ), |
| | | VehicleSpec( |
| | | "heyun", |
| | | "\u9102E69878", |
| | | "\u5b9c\u660c/\u8a38\u8fd0", |
| | | ( |
| | | Endpoint("\u679d\u6c5f", ("\u679d\u6c5f",)), |
| | | Endpoint("\u5949\u8282", ("\u5949\u8282",)), |
| | | ), |
| | | ), |
| | | VehicleSpec( |
| | | "kaixiangda", |
| | | "\u9102E68056", |
| | | "\u5b9c\u660c/\u51ef\u7965\u8fbe", |
| | | ( |
| | | Endpoint("\u7307\u4ead", ("\u7307\u4ead",)), |
| | | Endpoint("\u5317\u6d77", ("\u5317\u6d77",)), |
| | | Endpoint("\u6d59\u6c5f", ("\u6d59\u6c5f", "\u5609\u5174")), |
| | | ), |
| | | ), |
| | | VehicleSpec( |
| | | "minkun", |
| | | "\u9102E36292", |
| | | "\u5b9c\u660c/\u6c11\u5764", |
| | | unresolved_route_terms=("\u5408\u76ca\u8def", "\u5927\u6811\u6e7e"), |
| | | ), |
| | | ) |
| | | |
| | | |
| | | @dataclass |
| | | class Cell: |
| | | row: int |
| | | col: int |
| | | value: Any |
| | | |
| | | |
| | | @dataclass |
| | | class TrackPoint: |
| | | timestamp: datetime |
| | | longitude: float |
| | | latitude: float |
| | | speed: float |
| | | speed_text: str |
| | | status: str |
| | | alarm: str |
| | | location: str |
| | | province: str |
| | | prefecture: str |
| | | county: str |
| | | company: str |
| | | plate: str |
| | | plate_no_raw: str |
| | | source_file: str |
| | | receive_time: Optional[datetime] = None |
| | | operator: str = "" |
| | | source_path: str = "" |
| | | source_path_hash: str = "" |
| | | source_row: int = 0 |
| | | |
| | | |
| | | @dataclass |
| | | class FileAudit: |
| | | path: str |
| | | sha256: str |
| | | row_count: int |
| | | valid_point_count: int |
| | | first_time: Optional[datetime] = None |
| | | last_time: Optional[datetime] = None |
| | | plates: Counter = field(default_factory=Counter) |
| | | companies: Counter = field(default_factory=Counter) |
| | | segment_no: int = 0 |
| | | segment_start_date: Optional[date] = None |
| | | segment_end_date: Optional[date] = None |
| | | |
| | | def to_dict(self) -> Dict[str, Any]: |
| | | return { |
| | | "path": self.path, |
| | | "sha256": self.sha256, |
| | | "row_count": self.row_count, |
| | | "valid_point_count": self.valid_point_count, |
| | | "first_time": self.first_time.isoformat(sep=" ") if self.first_time else None, |
| | | "last_time": self.last_time.isoformat(sep=" ") if self.last_time else None, |
| | | "plates": dict(self.plates), |
| | | "companies": dict(self.companies), |
| | | "segment_no": self.segment_no, |
| | | "segment_start_date": str(self.segment_start_date) if self.segment_start_date else None, |
| | | "segment_end_date": str(self.segment_end_date) if self.segment_end_date else None, |
| | | } |
| | | |
| | | |
| | | def read_records(data: bytes) -> Iterable[Tuple[int, bytes]]: |
| | | position = 0 |
| | | size = len(data) |
| | | while position + 4 <= size: |
| | | record_type, record_length = struct.unpack_from("<HH", data, position) |
| | | position += 4 |
| | | payload = data[position:position + record_length] |
| | | if len(payload) != record_length: |
| | | raise ValueError( |
| | | "Truncated record at %d: type 0x%04x expected %d got %d" |
| | | % (position - 4, record_type, record_length, len(payload)) |
| | | ) |
| | | position += record_length |
| | | yield record_type, payload |
| | | |
| | | |
| | | def parse_label(payload: bytes) -> Optional[Cell]: |
| | | if len(payload) < 8: |
| | | return None |
| | | row, col = struct.unpack_from("<HH", payload, 0) |
| | | text_length = payload[7] |
| | | raw = payload[8:8 + text_length] |
| | | if len(raw) != text_length: |
| | | return None |
| | | try: |
| | | value = raw.decode("gbk") |
| | | except UnicodeDecodeError: |
| | | value = raw.decode("latin1") |
| | | return Cell(row, col, value) |
| | | |
| | | |
| | | def parse_number(payload: bytes) -> Optional[Cell]: |
| | | if len(payload) != 15: |
| | | return None |
| | | row, col = struct.unpack_from("<HH", payload, 0) |
| | | value = struct.unpack_from("<d", payload, 7)[0] |
| | | return Cell(row, col, value) |
| | | |
| | | |
| | | def parse_integer(payload: bytes) -> Optional[Cell]: |
| | | if len(payload) != 9: |
| | | return None |
| | | row, col = struct.unpack_from("<HH", payload, 0) |
| | | value = struct.unpack_from("<H", payload, 7)[0] |
| | | return Cell(row, col, value) |
| | | |
| | | |
| | | def read_cells(path: Path) -> List[Cell]: |
| | | data = path.read_bytes() |
| | | cells: List[Cell] = [] |
| | | for record_type, payload in read_records(data): |
| | | cell = None |
| | | if record_type == 0x0004: |
| | | cell = parse_label(payload) |
| | | elif record_type == 0x0003: |
| | | cell = parse_number(payload) |
| | | elif record_type == 0x0002: |
| | | cell = parse_integer(payload) |
| | | if cell is not None: |
| | | cells.append(cell) |
| | | return cells |
| | | |
| | | |
| | | def table_from_cells(cells: Sequence[Cell]) -> List[Dict[int, Any]]: |
| | | by_row: Dict[int, Dict[int, Any]] = defaultdict(dict) |
| | | for cell in cells: |
| | | by_row[cell.row][cell.col] = cell.value |
| | | max_row = max(by_row, default=-1) |
| | | return [by_row.get(row, {}) for row in range(max_row + 1)] |
| | | |
| | | |
| | | SEGMENT_DATE_RE = re.compile( |
| | | "(\\d{2})\u5e74(\\d{1,2})\u6708(\\d{1,2})\u65e5.*?" |
| | | "(\\d{2})\u5e74(\\d{1,2})\u6708(\\d{1,2})\u65e5" |
| | | ) |
| | | |
| | | |
| | | def parse_timestamp(value: Any) -> datetime: |
| | | return datetime.strptime(str(value), "%y-%m-%d %H:%M:%S") |
| | | |
| | | |
| | | def parse_timestamp_optional(value: Any) -> Optional[datetime]: |
| | | try: |
| | | return parse_timestamp(value) |
| | | except (TypeError, ValueError): |
| | | return None |
| | | |
| | | |
| | | def parse_segment_dates(path: Path, period: str) -> Tuple[Optional[date], Optional[date]]: |
| | | match = SEGMENT_DATE_RE.search(path.name) |
| | | if not match: |
| | | return None, None |
| | | try: |
| | | return ( |
| | | date(2000 + int(match.group(1)), int(match.group(2)), int(match.group(3))), |
| | | date(2000 + int(match.group(4)), int(match.group(5)), int(match.group(6))), |
| | | ) |
| | | except ValueError: |
| | | return None, None |
| | | |
| | | |
| | | def segment_sort_key(path: Path, period: str) -> Tuple[date, str]: |
| | | start, _ = parse_segment_dates(path, period) |
| | | fallback = date(9999, 12, 31) |
| | | return (start or fallback, path.name) |
| | | |
| | | |
| | | def parse_speed(value: Any) -> float: |
| | | text = str(value or "0km/h").lower().replace("km/h", "").strip() |
| | | try: |
| | | return float(text) |
| | | except ValueError: |
| | | return 0.0 |
| | | |
| | | |
| | | def split_location(value: Any) -> Tuple[str, str, str]: |
| | | parts = [part.strip() for part in str(value or "").replace("/", ",").split(",") if part.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 sha256_file(path: Path) -> str: |
| | | digest = hashlib.sha256() |
| | | with path.open("rb") as handle: |
| | | for block in iter(lambda: handle.read(1024 * 1024), b""): |
| | | digest.update(block) |
| | | return digest.hexdigest() |
| | | |
| | | |
| | | def haversine_km(a: TrackPoint, b: TrackPoint) -> float: |
| | | radius_km = 6371.0088 |
| | | lat1 = math.radians(a.latitude) |
| | | lat2 = math.radians(b.latitude) |
| | | dlat = lat2 - lat1 |
| | | dlon = math.radians(b.longitude - a.longitude) |
| | | h = ( |
| | | math.sin(dlat / 2.0) ** 2 |
| | | + math.cos(lat1) * math.cos(lat2) * math.sin(dlon / 2.0) ** 2 |
| | | ) |
| | | return 2.0 * radius_km * math.asin(min(1.0, math.sqrt(h))) |
| | | |
| | | |
| | | def load_track_points(spec: VehicleSpec, work_root: Path, period: str) -> Tuple[List[TrackPoint], List[FileAudit]]: |
| | | directory = work_root / spec.directory |
| | | paths = sorted(directory.glob("*%s*.xls" % spec.plate[1:]), key=lambda item: segment_sort_key(item, period)) |
| | | if not paths: |
| | | raise RuntimeError("No track point files found for %s in %s" % (spec.plate, directory)) |
| | | |
| | | points: List[TrackPoint] = [] |
| | | audits: List[FileAudit] = [] |
| | | for segment_no, path in enumerate(paths, start=1): |
| | | cells = read_cells(path) |
| | | rows = table_from_cells(cells) |
| | | segment_start_date, segment_end_date = parse_segment_dates(path, period) |
| | | audit = FileAudit( |
| | | str(path), sha256_file(path), max(0, len(rows) - 1), 0, |
| | | segment_no=segment_no, |
| | | segment_start_date=segment_start_date, |
| | | segment_end_date=segment_end_date, |
| | | ) |
| | | path_hash = hashlib.sha256(str(path.resolve()).casefold().encode("utf-8")).hexdigest() |
| | | seen_header = False |
| | | for source_row, row in enumerate(rows, start=1): |
| | | if not seen_header and str(row.get(0, "")) == "\u5355\u4f4d\u540d\u79f0": |
| | | seen_header = True |
| | | continue |
| | | if not seen_header or not all(col in row for col in (2, 4, 5)): |
| | | continue |
| | | company = str(row.get(0, "")).strip() |
| | | raw_plate_text = str(row.get(1, "")).strip() |
| | | raw_plate = canonical_plate(raw_plate_text) |
| | | audit.plates[raw_plate] += 1 |
| | | audit.companies[company] += 1 |
| | | if raw_plate != spec.plate: |
| | | continue |
| | | try: |
| | | timestamp = parse_timestamp(row[2]) |
| | | longitude = float(row[4]) |
| | | latitude = float(row[5]) |
| | | except (TypeError, ValueError): |
| | | continue |
| | | if not (-180 <= longitude <= 180 and -90 <= latitude <= 90): |
| | | continue |
| | | if longitude == 0 or latitude == 0: |
| | | continue |
| | | province, prefecture, county = split_location(row.get(10, "")) |
| | | point = TrackPoint( |
| | | timestamp=timestamp, |
| | | longitude=longitude, |
| | | latitude=latitude, |
| | | speed=parse_speed(row.get(6)), |
| | | speed_text=str(row.get(6, "")).strip(), |
| | | status=str(row.get(7, "")), |
| | | alarm=str(row.get(8, "")), |
| | | location=str(row.get(10, "")), |
| | | province=province, |
| | | prefecture=prefecture, |
| | | county=county, |
| | | company=company, |
| | | plate=raw_plate, |
| | | plate_no_raw=raw_plate_text, |
| | | source_file=path.name, |
| | | receive_time=parse_timestamp_optional(row.get(3)), |
| | | operator=str(row.get(9, "")).strip(), |
| | | source_path=str(path), |
| | | source_path_hash=path_hash, |
| | | source_row=source_row, |
| | | ) |
| | | points.append(point) |
| | | audit.valid_point_count += 1 |
| | | if audit.first_time is None or timestamp < audit.first_time: |
| | | audit.first_time = timestamp |
| | | if audit.last_time is None or timestamp > audit.last_time: |
| | | audit.last_time = timestamp |
| | | audits.append(audit) |
| | | |
| | | points.sort(key=lambda point: (point.timestamp, point.longitude, point.latitude)) |
| | | return points, audits |
| | | |
| | | |
| | | def deduplicate_points(points: Sequence[TrackPoint]) -> List[TrackPoint]: |
| | | seen = set() |
| | | result: List[TrackPoint] = [] |
| | | for point in points: |
| | | key = ( |
| | | point.timestamp, |
| | | round(point.longitude, 6), |
| | | round(point.latitude, 6), |
| | | point.status, |
| | | point.location, |
| | | ) |
| | | if key in seen: |
| | | continue |
| | | seen.add(key) |
| | | result.append(point) |
| | | return result |
| | | |
| | | |
| | | def point_distance_stats(points: Sequence[TrackPoint]) -> Dict[str, Any]: |
| | | raw_distance = 0.0 |
| | | clean_distance = 0.0 |
| | | clean_steps = 0 |
| | | rejected_time_gap = 0 |
| | | rejected_speed = 0 |
| | | daily_distance: Dict[str, float] = defaultdict(float) |
| | | for start, end in zip(points, points[1:]): |
| | | distance = haversine_km(start, end) |
| | | raw_distance += distance |
| | | seconds = (end.timestamp - start.timestamp).total_seconds() |
| | | if seconds <= 0 or seconds > 900: |
| | | rejected_time_gap += 1 |
| | | continue |
| | | speed = distance / (seconds / 3600.0) |
| | | if speed > 120: |
| | | rejected_speed += 1 |
| | | continue |
| | | clean_distance += distance |
| | | clean_steps += 1 |
| | | daily_distance[end.timestamp.date().isoformat()] += distance |
| | | moving_days = sorted(day for day, distance in daily_distance.items() if distance >= 1.0) |
| | | return { |
| | | "raw_distance": raw_distance, |
| | | "clean_distance": clean_distance, |
| | | "clean_steps": clean_steps, |
| | | "rejected_time_gap": rejected_time_gap, |
| | | "rejected_speed": rejected_speed, |
| | | "daily_distance": dict(sorted(daily_distance.items())), |
| | | "moving_days": moving_days, |
| | | } |
| | | |
| | | |
| | | def top_counter(counter: Counter, limit: int = 8) -> List[Tuple[str, int]]: |
| | | return [(name, count) for name, count in counter.most_common(limit) if name] |
| | | |
| | | |
| | | def endpoint_stats(points: Sequence[TrackPoint], endpoints: Sequence[Endpoint]) -> List[Dict[str, Any]]: |
| | | result = [] |
| | | for endpoint in endpoints: |
| | | matching = [ |
| | | point for point in points |
| | | if any(alias in point.location for alias in endpoint.aliases) |
| | | ] |
| | | result.append({ |
| | | "label": endpoint.label, |
| | | "aliases": list(endpoint.aliases), |
| | | "strict": endpoint.strict, |
| | | "point_count": len(matching), |
| | | "day_count": len({point.timestamp.date() for point in matching}), |
| | | "first_time": min((point.timestamp for point in matching), default=None), |
| | | "last_time": max((point.timestamp for point in matching), default=None), |
| | | }) |
| | | return result |
| | | |
| | | |
| | | def route_group_stats(ledger_rows: Sequence[Any]) -> List[Dict[str, Any]]: |
| | | grouped: Dict[str, Dict[str, Any]] = {} |
| | | for row in ledger_rows: |
| | | key = row.route or "(blank)" |
| | | item = grouped.setdefault(key, { |
| | | "route": row.route, |
| | | "cargo_types": set(), |
| | | "rows": 0, |
| | | "trips": 0.0, |
| | | "mileage": 0.0, |
| | | "freight": 0.0, |
| | | "turnover": 0.0, |
| | | }) |
| | | item["rows"] += 1 |
| | | item["trips"] += row.trips or 0.0 |
| | | item["mileage"] += row.total_mileage or 0.0 |
| | | item["freight"] += row.freight or 0.0 |
| | | item["turnover"] += row.turnover or 0.0 |
| | | if row.cargo_type: |
| | | item["cargo_types"].add(row.cargo_type) |
| | | result = [] |
| | | for item in grouped.values(): |
| | | item["cargo_types"] = sorted(item["cargo_types"]) |
| | | result.append(item) |
| | | return sorted(result, key=lambda item: (-item["mileage"], item["route"])) |
| | | |
| | | |
| | | def safe_rate(numerator: Optional[float], denominator: Optional[float]) -> Optional[float]: |
| | | if numerator is None or denominator in (None, 0): |
| | | return None |
| | | return numerator / denominator - 1.0 |
| | | |
| | | |
| | | def period_month_days(period: str) -> int: |
| | | year, month = [int(value) for value in period.split("-")] |
| | | return calendar.monthrange(year, month)[1] |
| | | |
| | | |
| | | def expected_segments(period: str) -> List[Tuple[date, date]]: |
| | | year, month = [int(value) for value in period.split("-")] |
| | | last_day = period_month_days(period) |
| | | result: List[Tuple[date, date]] = [] |
| | | for start_day in range(1, last_day + 1, 3): |
| | | end_day = min(start_day + 2, last_day) |
| | | result.append((date(year, month, start_day), date(year, month, end_day))) |
| | | return result |
| | | |
| | | |
| | | def missing_segments(paths: Sequence[Path], period: str) -> List[str]: |
| | | actual = {parse_segment_dates(path, period) for path in paths} |
| | | return [ |
| | | "%d\u65e5-%d\u65e5" % (start.day, end.day) |
| | | for start, end in expected_segments(period) |
| | | if (start, end) not in actual |
| | | ] |
| | | |
| | | |
| | | def inspect_vehicle(spec: VehicleSpec, source_root: Path, work_root: Path, period: str) -> Dict[str, Any]: |
| | | profile = next(profile for profile in PROFILES if profile.key == spec.profile_key) |
| | | ledger_rows, ledger_source = parse_ledger(profile, source_root) |
| | | selected_ledger = [row for row in ledger_rows if row.plate == spec.plate] |
| | | if not selected_ledger: |
| | | raise RuntimeError("No ledger rows for %s / %s" % (profile.enterprise, spec.plate)) |
| | | ledger_vehicles, ledger_total = aggregate_ledger(selected_ledger) |
| | | ledger_vehicle = ledger_vehicles[spec.plate] |
| | | |
| | | track_rows, track_source = parse_track_summary(profile, source_root) |
| | | track_vehicles = aggregate_tracks(track_rows) |
| | | selected_track = track_vehicles.get(spec.plate) |
| | | if not selected_track: |
| | | raise RuntimeError("No monthly track summary for %s" % spec.plate) |
| | | |
| | | points, file_audits = load_track_points(spec, work_root, period) |
| | | unique_points = deduplicate_points(points) |
| | | distance_stats = point_distance_stats(unique_points) |
| | | location_counties = Counter( |
| | | "%s|%s|%s" % (point.province, point.prefecture, point.county) |
| | | for point in unique_points |
| | | if point.county |
| | | ) |
| | | location_prefectures = Counter(point.prefecture for point in unique_points if point.prefecture) |
| | | location_provinces = Counter(point.province for point in unique_points if point.province) |
| | | location_days: Dict[str, set] = defaultdict(set) |
| | | for point in unique_points: |
| | | location_days["%s|%s|%s" % ( |
| | | point.province, point.prefecture, point.county |
| | | )].add(point.timestamp.date()) |
| | | endpoint_evidence = endpoint_stats(unique_points, spec.endpoints) |
| | | files = sorted((work_root / spec.directory).glob("*%s*.xls" % spec.plate[1:])) |
| | | observed_dates = sorted({point.timestamp.date() for point in unique_points}) |
| | | year, month = [int(value) for value in period.split("-")] |
| | | expected_dates = {date(year, month, day) for day in range(1, period_month_days(period) + 1)} |
| | | missing_days = sorted(expected_dates - set(observed_dates)) |
| | | |
| | | raw_vs_platform_rate = safe_rate(distance_stats["raw_distance"], selected_track["total_mileage"]) |
| | | clean_vs_platform_rate = safe_rate(distance_stats["clean_distance"], selected_track["total_mileage"]) |
| | | platform_vs_ledger_rate = safe_rate(selected_track["total_mileage"], ledger_vehicle["mileage"]) |
| | | ledger_vs_platform_rate = safe_rate(ledger_vehicle["mileage"], selected_track["total_mileage"]) |
| | | point_vs_ledger_rate = safe_rate(distance_stats["raw_distance"], ledger_vehicle["mileage"]) |
| | | average_trip_mileage = ( |
| | | ledger_vehicle["mileage"] / ledger_vehicle["trips"] |
| | | if ledger_vehicle["trips"] > 0 else None |
| | | ) |
| | | point_supported_trips = ( |
| | | distance_stats["raw_distance"] / average_trip_mileage |
| | | if average_trip_mileage and average_trip_mileage > 0 else None |
| | | ) |
| | | platform_supported_trips = ( |
| | | selected_track["total_mileage"] / average_trip_mileage |
| | | if average_trip_mileage and average_trip_mileage > 0 else None |
| | | ) |
| | | |
| | | return { |
| | | "city": profile.city, |
| | | "enterprise": profile.enterprise, |
| | | "profile_key": profile.key, |
| | | "plate": spec.plate, |
| | | "directory": str(work_root / spec.directory), |
| | | "ledger": { |
| | | "source_file": ledger_source.path, |
| | | "routes": [row.route for row in selected_ledger if row.route], |
| | | "route_groups": route_group_stats(selected_ledger), |
| | | "trips": ledger_vehicle["trips"], |
| | | "mileage": ledger_vehicle["mileage"], |
| | | "freight": ledger_vehicle["freight"], |
| | | "turnover": ledger_vehicle["turnover"], |
| | | }, |
| | | "platform": { |
| | | "source_file": track_source.path, |
| | | "total_mileage": selected_track["total_mileage"], |
| | | "complete_mileage": selected_track["complete_mileage"], |
| | | "abnormal_mileage": selected_track["abnormal_mileage"], |
| | | "anomaly_rate": selected_track["anomaly_rate"], |
| | | "days": len(selected_track["days"]), |
| | | }, |
| | | "points": { |
| | | "file_count": len(files), |
| | | "missing_segments": missing_segments(files, period), |
| | | "valid_point_count": len(points), |
| | | "unique_point_count": len(unique_points), |
| | | "duplicate_point_count": len(points) - len(unique_points), |
| | | "first_time": unique_points[0].timestamp if unique_points else None, |
| | | "last_time": unique_points[-1].timestamp if unique_points else None, |
| | | "day_count": len({point.timestamp.date() for point in unique_points}), |
| | | "observed_dates": [str(value) for value in observed_dates], |
| | | "missing_days": [str(value) for value in missing_days], |
| | | "moving_day_count": len(distance_stats["moving_days"]), |
| | | "clean_distance": distance_stats["clean_distance"], |
| | | "raw_distance": distance_stats["raw_distance"], |
| | | "rejected_time_gap": distance_stats["rejected_time_gap"], |
| | | "rejected_speed": distance_stats["rejected_speed"], |
| | | "top_provinces": top_counter(location_provinces), |
| | | "top_prefectures": top_counter(location_prefectures), |
| | | "top_counties": [ |
| | | ( |
| | | name, |
| | | count, |
| | | len(location_days[name]), |
| | | ) |
| | | for name, count in location_counties.most_common(10) |
| | | ], |
| | | "endpoints": endpoint_evidence, |
| | | "unresolved_route_terms": list(spec.unresolved_route_terms), |
| | | }, |
| | | "comparison": { |
| | | "raw_vs_platform_rate": raw_vs_platform_rate, |
| | | "clean_vs_platform_rate": clean_vs_platform_rate, |
| | | "platform_vs_ledger_rate": platform_vs_ledger_rate, |
| | | "ledger_vs_platform_rate": ledger_vs_platform_rate, |
| | | "point_vs_ledger_rate": point_vs_ledger_rate, |
| | | "average_trip_mileage": average_trip_mileage, |
| | | "point_supported_trips": point_supported_trips, |
| | | "platform_supported_trips": platform_supported_trips, |
| | | "trip_support_rate": ( |
| | | platform_supported_trips / ledger_vehicle["trips"] |
| | | if platform_supported_trips is not None and ledger_vehicle["trips"] > 0 else None |
| | | ), |
| | | }, |
| | | "files": [audit.to_dict() for audit in file_audits], |
| | | } |
| | | |
| | | |
| | | def json_default(value: Any) -> Any: |
| | | if isinstance(value, datetime): |
| | | return value.isoformat(sep=" ") |
| | | if isinstance(value, set): |
| | | return sorted(value) |
| | | raise TypeError("Unsupported value: %r" % (value,)) |
| | | |
| | | |
| | | def main(argv: Optional[Sequence[str]] = None) -> int: |
| | | parser = argparse.ArgumentParser(description=__doc__) |
| | | parser.add_argument("--period", default="2026-09") |
| | | parser.add_argument("--source-root", required=True) |
| | | parser.add_argument("--work-root", required=True) |
| | | parser.add_argument("--output-json", required=True) |
| | | args = parser.parse_args(argv) |
| | | |
| | | source_root = Path(args.source_root) |
| | | work_root = Path(args.work_root) |
| | | result = { |
| | | "source_root": str(source_root), |
| | | "work_root": str(work_root), |
| | | "vehicles": [ |
| | | inspect_vehicle(spec, source_root, work_root, args.period) |
| | | for spec in SELECTED_VEHICLES |
| | | ], |
| | | } |
| | | with Path(args.output_json).open("w", encoding="utf-8") as handle: |
| | | json.dump(result, handle, ensure_ascii=False, indent=2, default=json_default) |
| | | return 0 |
| | | |
| | | |
| | | if __name__ == "__main__": |
| | | raise SystemExit(main()) |
| New file |
| | |
| | | #!/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()) |
| New file |
| | |
| | | #!/usr/bin/env python |
| | | # -*- coding: utf-8 -*- |
| | | """Import objective vehicle daily mileage and track-point observations.""" |
| | | |
| | | from __future__ import annotations |
| | | |
| | | import argparse |
| | | import json |
| | | import os |
| | | import re |
| | | import sys |
| | | from pathlib import Path |
| | | from typing import Any, 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.enterprise_ledger_inspection import ( # noqa: E402 |
| | | PROFILES, |
| | | TrackDailyRow, |
| | | parse_track_summary, |
| | | source_path_hash, |
| | | ) |
| | | from tools.enterprise_track_point_inspection import SELECTED_VEHICLES, load_track_points # noqa: E402 |
| | | |
| | | |
| | | 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 = 1000) -> 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() |
| | | |
| | | |
| | | SOURCE_COLUMNS = ( |
| | | "report_period", "data_type", "enterprise_name", "source_path", "source_name", |
| | | "source_path_hash", "source_sha256", "file_size", "sheet_name", "source_rows", |
| | | ) |
| | | DAILY_COLUMNS = ( |
| | | "report_period", "freight_enterprise_name", "plate_no_raw", "plate_no", "track_date", |
| | | "agency_name", "vehicle_label", "operator_name", "point_count", "complete_mileage", |
| | | "abnormal_mileage", "total_mileage", "drift_count", "anomaly_rate", "track_text", |
| | | "approved_traction_tonnage", "route_text", "trips", "straight_distance", "cargo_tons", |
| | | "source_file", "source_path_hash", "source_sha256", "source_row", |
| | | ) |
| | | POINT_COLUMNS = ( |
| | | "report_period", "unit_name", "plate_no_raw", "plate_no", "terminal_time", |
| | | "receive_time", "longitude", "latitude", "speed_text", "vehicle_status", |
| | | "alarm_status", "operator_name", "location_text", "province_name", |
| | | "prefecture_name", "county_name", "source_file", "source_path_hash", |
| | | "source_sha256", "source_row", |
| | | ) |
| | | |
| | | |
| | | def daily_row_tuple(period: str, row: TrackDailyRow) -> Tuple[Any, ...]: |
| | | return ( |
| | | period, row.enterprise, row.plate_no_raw or row.plate, row.plate, row.track_date, |
| | | row.agency or None, row.label or None, row.operator or None, row.point_count, |
| | | row.complete_mileage, row.abnormal_mileage, row.total_mileage, row.drift_count, |
| | | row.anomaly_rate, row.track_text or None, row.approved_traction_tonnage, |
| | | row.route or None, row.trips, row.straight_distance, row.cargo_tons, |
| | | row.source_file, row.source_path_hash, row.source_sha256, row.source_row, |
| | | ) |
| | | |
| | | |
| | | def import_observations(conn: pymysql.connections.Connection, period: str, work_root: Path, |
| | | schema_path: Path) -> Dict[str, Any]: |
| | | execute_schema(conn, schema_path) |
| | | profile_by_key = {profile.key: profile for profile in PROFILES} |
| | | enterprise_names = [profile.enterprise for profile in PROFILES] |
| | | daily_rows: List[Tuple[Any, ...]] = [] |
| | | source_rows: List[Tuple[Any, ...]] = [] |
| | | summary_files = 0 |
| | | with conn.cursor() as cur: |
| | | placeholders = ",".join(["%s"] * len(enterprise_names)) |
| | | cur.execute( |
| | | "DELETE FROM vehicle_track_point WHERE report_period=%s AND unit_name IN (" + placeholders + ")", |
| | | [period] + enterprise_names, |
| | | ) |
| | | cur.execute( |
| | | "DELETE FROM vehicle_track_daily WHERE report_period=%s AND freight_enterprise_name IN (" + placeholders + ")", |
| | | [period] + enterprise_names, |
| | | ) |
| | | cur.execute( |
| | | "DELETE FROM vehicle_track_source_file WHERE report_period=%s AND data_type='VEHICLE_DAILY_MILEAGE' " |
| | | "AND enterprise_name IN (" + placeholders + ")", |
| | | [period] + enterprise_names, |
| | | ) |
| | | cur.execute( |
| | | "DELETE FROM vehicle_track_source_file WHERE report_period=%s AND data_type='VEHICLE_TRACK_POINT' " |
| | | "AND enterprise_name IN (" + placeholders + ")", |
| | | [period] + enterprise_names, |
| | | ) |
| | | |
| | | for profile in PROFILES: |
| | | rows, source = parse_track_summary(profile, work_root) |
| | | daily_rows.extend(daily_row_tuple(period, row) for row in rows) |
| | | source_rows.append(( |
| | | period, "VEHICLE_DAILY_MILEAGE", profile.enterprise, source.path, |
| | | Path(source.path).name, source.path_hash, source.sha256, source.size, |
| | | source.sheet_name or None, len(rows), |
| | | )) |
| | | summary_files += 1 |
| | | insert_rows(cur, "vehicle_track_source_file", SOURCE_COLUMNS, source_rows, 200) |
| | | insert_rows(cur, "vehicle_track_daily", DAILY_COLUMNS, daily_rows, 1000) |
| | | |
| | | point_file_count = 0 |
| | | point_count = 0 |
| | | for spec in SELECTED_VEHICLES: |
| | | profile = profile_by_key[spec.profile_key] |
| | | points, audits = load_track_points(spec, work_root, period) |
| | | point_source_rows = [] |
| | | for audit in audits: |
| | | point_source_rows.append(( |
| | | period, "VEHICLE_TRACK_POINT", profile.enterprise, audit.path, |
| | | Path(audit.path).name, source_path_hash(Path(audit.path)), audit.sha256, |
| | | Path(audit.path).stat().st_size, "车辆轨迹明细", audit.valid_point_count, |
| | | )) |
| | | insert_rows(cur, "vehicle_track_source_file", SOURCE_COLUMNS, point_source_rows, 500) |
| | | point_rows = [( |
| | | period, point.company, point.plate_no_raw or point.plate, point.plate, |
| | | point.timestamp, point.receive_time, point.longitude, point.latitude, |
| | | point.speed_text or None, point.status or None, point.alarm or None, |
| | | point.operator or None, point.location or None, point.province or None, |
| | | point.prefecture or None, point.county or None, point.source_path, |
| | | point.source_path_hash, next( |
| | | audit.sha256 for audit in audits if audit.path == point.source_path |
| | | ), point.source_row, |
| | | ) for point in points] |
| | | insert_rows(cur, "vehicle_track_point", POINT_COLUMNS, point_rows, 1000) |
| | | point_file_count += len(audits) |
| | | point_count += len(point_rows) |
| | | conn.commit() |
| | | return { |
| | | "period": period, |
| | | "daily_source_file_count": summary_files, |
| | | "daily_row_count": len(daily_rows), |
| | | "point_source_file_count": point_file_count, |
| | | "point_row_count": point_count, |
| | | } |
| | | |
| | | |
| | | def main(argv: Optional[Sequence[str]] = None) -> int: |
| | | parser = argparse.ArgumentParser(description=__doc__) |
| | | parser.add_argument("--period", required=True) |
| | | parser.add_argument("--work-root", required=True) |
| | | parser.add_argument("--schema", default=str(PROJECT_ROOT / "docs" / "sql_vehicle_track_observation.sql")) |
| | | 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") |
| | | if not Path(args.work_root).is_dir(): |
| | | raise SystemExit("work root not found: %s" % args.work_root) |
| | | if not Path(args.schema).is_file(): |
| | | raise SystemExit("schema file not found: %s" % args.schema) |
| | | 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_observations(conn, args.period, Path(args.work_root), 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()) |