{html.escape(card['field'])}
" f"План
- {''.join(plan_html) or '
- В этих книгах нет '}
Весовая
- {''.join(fact_html)}
#!/usr/bin/env python3 """Сверка книг плана с фактом прихода с полей. Читает Excel поставки, кэш ves2020 и пишет свод xlsx и HTML-отчёт. Запуск из корня репозитория: python analysis/checker/check_plans.py """ from __future__ import annotations import html import json import math import re from collections import Counter, defaultdict from datetime import datetime, date from pathlib import Path import openpyxl import xlsxwriter ROOT = Path(__file__).resolve().parents[2] INCOMING = ROOT / "project_data" / "Входящие" / "20261104" VES = ROOT / "analysis" / "output" / "ves2020" OUT_XLSX = ROOT / "analysis" / "output" / "свод_приёмки.xlsx" OUT_HTML = ROOT / "analysis" / "output" / "отчет_приёмки.html" PLANS = [ { "key": "jul2026", "file": "План_2026_июль_14_дней.xlsx", "short": "10–23.07.2026", "focus": "пшеница", "focus_word": "пшен", }, { "key": "aug14", "file": "План_2026_август_14_дней.xlsx", "short": "25.08–07.09.2026", "focus": "свекла", "focus_word": "свекл", }, { "key": "aug50", "file": "План_2026_август_50_дней.xlsx", "short": "25.08–13.10.2026", "focus": "свекла", "focus_word": "свекл", }, { "key": "jul2025", "file": "ML_план_2025_14_дней.xlsx", "short": "02–15.07.2025", "focus": "пшеница", "focus_word": "пшен", }, ] EXAMPLES = ("23-05-ГАЗР-159", "23-05-БСЖВ-008", "23-13-НВМШ-016") FOCUS_FACT = { "jul2026": "пшеница", "aug14": "свекла", "aug50": "свекла", "jul2025": "пшеница", } def fnum(value): if value is None or value == "": return 0.0 if isinstance(value, (int, float)): return float(value) try: return float(str(value).replace(",", ".").replace(" ", "")) except ValueError: return 0.0 def capacity(value): if value is None: return None match = re.search(r"[\d]+(?:[.,]\d+)?", str(value)) if not match: return None return float(match.group(0).replace(",", ".")) def field_code(load_point): text = str(load_point or "") return text.split("·")[0].strip() def as_date(value): if isinstance(value, datetime): return value.date() if isinstance(value, date): return value return None def fmt_t(value): return f"{value:,.1f}".replace(",", " ").replace(".", ",") def fmt_pct(value): if value is None: return "—" return f"{value * 100:.1f}%".replace(".", ",") def read_plan(path): wb = openpyxl.load_workbook(path, read_only=True, data_only=True) ws = wb["ПЛАН_ВЫВОЗА"] title = None rows = [] alerts = Counter() for index, row in enumerate(ws.iter_rows(values_only=True), 1): if index == 1: title = str(row[0] or "") continue if index < 4: continue marker = row[0] if isinstance(marker, str) and marker.startswith("ИТОГО"): break if marker is None: continue own = fnum(row[7]) hired = fnum(row[14]) hired_tkm_a = fnum(row[15]) hired_tkm_b = fnum(row[17]) if hired_tkm_a and hired_tkm_b and abs(hired_tkm_a - hired_tkm_b) <= 0.05 * max(hired_tkm_a, hired_tkm_b): hired_tkm = hired_tkm_a else: hired_tkm = hired_tkm_a + hired_tkm_b item = { "date": as_date(marker), "field": field_code(row[1]), "load": str(row[1] or ""), "warehouse": str(row[2] or "").strip(), "culture": str(row[3] or "").strip(), "tons": own + hired, "tkm": fnum(row[8]) + hired_tkm, "cost": fnum(row[20]), "ok": True, "issues": [], } issues = row_issues(row, own, hired) item["ok"] = not issues item["issues"] = issues rows.append(item) alert_ws = wb["ALERTS"] for index, row in enumerate(alert_ws.iter_rows(values_only=True), 1): if index <= 2 or not row or not row[0]: continue alerts[str(row[0])] += 1 params = read_params(wb["PARAMS_USED"]) wb.close() return {"title": title, "rows": rows, "alerts": alerts, "params": params} def row_issues(row, own, hired): issues = [] if own < -1e-6 or hired < -1e-6: issues.append("отрицательные тонны") if not row[2] or not row[3]: issues.append("пустой пункт или культура") checks = ( (own, row[4], capacity(row[6]), row[9], row[10], "свой"), (hired, row[11], capacity(row[12]), row[18], row[19], "наём"), ) for tons, trips, cap, rate, cost, label in checks: if tons <= 1e-6: continue if cap is None or cap <= 0: issues.append(f"нет грузоподъёмности ({label})") continue expect = math.ceil(tons / cap - 1e-6) if trips is None or abs(fnum(trips) - expect) > 0.51: issues.append(f"рейсы не сходятся ({label})") if rate not in (None, "") and cost not in (None, ""): expected_cost = tons * fnum(rate) if abs(fnum(cost) - expected_cost) > max(1.0, 0.001 * abs(expected_cost)): issues.append(f"стоимость не сходится ({label})") return issues def read_params(ws): mode = None headers = [] fields_rows = 0 positive = 0 in_plan_n = 0 in_plan_tons = 0.0 all_tons = 0.0 yield_methods = Counter() window_methods = Counter() for row in ws.iter_rows(values_only=True): if not row: continue head = row[0] labels = [str(cell) if cell is not None else "" for cell in row] if head == "Поле" and "Плановый_урожай_т" in labels: mode = "fields" headers = labels continue if head == "Поле" and "Метод_урожайности" in labels: mode = "ml" headers = labels continue if head in ("Бригады", "Точки приемки", "Транспорт", "Экономика", "Сценарий", "Конфигурация", "ML-прогнозы"): if mode == "fields": mode = None continue if mode == "fields" and isinstance(head, str) and "-" in head: fields_rows += 1 rem_idx = headers.index("Остаток_неубранного_т") flag_idx = headers.index("В_плане") rem = fnum(row[rem_idx]) all_tons += rem if rem > 0.5: positive += 1 if row[flag_idx] in (True, "True", "Да", 1): in_plan_n += 1 in_plan_tons += rem elif mode == "ml" and isinstance(head, str) and head != "Поле" and "-" in str(head): yield_methods[str(row[headers.index("Метод_урожайности")])] += 1 window_methods[str(row[headers.index("Метод_окна")])] += 1 return { "field_rows": fields_rows, "positive_remainder": positive, "in_plan_n": in_plan_n, "in_plan_tons": in_plan_tons, "remainder_tons": all_tons, "yield_methods": yield_methods, "window_methods": window_methods, } def read_sverka(path): wb = openpyxl.load_workbook(path, read_only=True, data_only=True) ws = wb["Итог"] data = {} for row in ws.iter_rows(values_only=True): if row and row[0] is not None and len(row) > 1 and row[1] is not None: data[str(row[0])] = row[1] wb.close() return data def load_json(path): return json.loads(path.read_text(encoding="utf-8")) def summarize(plan_spec, plan, ves_window): rows = plan["rows"] tons = sum(item["tons"] for item in rows) cost = sum(item["cost"] for item in rows) tkm = sum(item["tkm"] for item in rows) fields = {item["field"] for item in rows if item["field"]} focus_tons = sum(item["tons"] for item in rows if plan_spec["focus_word"] in item["culture"].lower()) ok = sum(1 for item in rows if item["ok"]) daily = defaultdict(float) for item in rows: if item["date"]: daily[item["date"].isoformat()] += item["tons"] fact_tons = ves_window["tons"] focus_fact = ves_window["groups"].get(plan_spec["focus"], 0.0) return { "key": plan_spec["key"], "file": plan_spec["file"], "title": plan["title"], "short": plan_spec["short"], "focus": plan_spec["focus"], "rows": len(rows), "fields": len(fields), "tons": tons, "focus_tons": focus_tons, "cost": cost, "tkm": tkm, "km_per_t": (tkm / tons) if tons else None, "arith_ok": ok, "arith_share": ok / len(rows) if rows else None, "fact_tons": fact_tons, "fact_rows": ves_window["rows"], "focus_fact": focus_fact, "share_all": tons / fact_tons if fact_tons else None, "share_focus": focus_tons / focus_fact if focus_fact else None, "daily_plan": dict(daily), "daily_fact": ves_window.get("daily") or {}, "groups": ves_window.get("groups") or {}, "alerts": plan["alerts"], "params": { "field_rows": plan["params"]["field_rows"], "positive_remainder": plan["params"]["positive_remainder"], "in_plan_n": plan["params"]["in_plan_n"], "in_plan_tons": plan["params"]["in_plan_tons"], "remainder_tons": plan["params"]["remainder_tons"], "yield_methods": dict(plan["params"]["yield_methods"]), "window_methods": dict(plan["params"]["window_methods"]), }, "detail": rows, } def example_cards(summaries, fact_rows): by_key = {item["key"]: item for item in summaries} cards = [] for code in EXAMPLES: plan_bits = [] for key, summary in by_key.items(): hits = [row for row in summary["detail"] if row["field"] == code] if not hits: continue plan_bits.append( { "window": summary["title"], "key": key, "tons": sum(row["tons"] for row in hits), "dates": sorted({row["date"].isoformat() for row in hits if row["date"]}), "warehouses": sorted({row["warehouse"] for row in hits}), "culture": hits[0]["culture"], } ) facts = [row for row in fact_rows if row["field"] == code] cards.append({"field": code, "plan": plan_bits, "fact": facts}) return cards def write_xlsx(summaries, sverka, cards): OUT_XLSX.parent.mkdir(parents=True, exist_ok=True) book = xlsxwriter.Workbook(str(OUT_XLSX)) header = book.add_format({"bold": True, "bg_color": "#1d4e89", "font_color": "#ffffff", "text_wrap": True}) num = book.add_format({"num_format": "# ##0.00"}) pct = book.add_format({"num_format": "0.0%"}) text = book.add_format({"text_wrap": True, "valign": "top"}) sheet = book.add_worksheet("Сводка") columns = [ "Окно", "Файл", "Строк", "Полей", "План, т", "Факт весовой, т", "План / факт", "Культура сравнения", "План культуры, т", "Факт культуры, т", "План культуры / факт", "Стоимость, руб", "Т/км", "Арифметика строк", ] for col, name in enumerate(columns): sheet.write(0, col, name, header) for row_index, item in enumerate(summaries, 1): values = [ item["title"], item["file"], item["rows"], item["fields"], item["tons"], item["fact_tons"], item["share_all"], item["focus"], item["focus_tons"], item["focus_fact"], item["share_focus"], item["cost"], item["tkm"], item["arith_share"], ] for col, value in enumerate(values): fmt = None if col in (4, 5, 8, 9, 11, 12): fmt = num elif col in (6, 10, 13): fmt = pct sheet.write(row_index, col, value, fmt) sheet.set_column(0, 1, 42) sheet.set_column(2, 13, 18) sheet.freeze_panes(1, 0) fields = book.add_worksheet("Три_поля") field_header = ["Поле", "Сторона", "Окно или культура", "Тонны", "Даты", "Склад", "Строк регистра"] for col, name in enumerate(field_header): fields.write(0, col, name, header) cursor = 1 for card in cards: for bit in card["plan"]: fields.write(cursor, 0, card["field"]) fields.write(cursor, 1, "план") fields.write(cursor, 2, bit["window"]) fields.write(cursor, 3, bit["tons"], num) fields.write(cursor, 4, ", ".join(bit["dates"]), text) fields.write(cursor, 5, "; ".join(bit["warehouses"]), text) cursor += 1 for fact in card["fact"]: fields.write(cursor, 0, card["field"]) fields.write(cursor, 1, "весовая") fields.write(cursor, 2, fact["culture"]) fields.write(cursor, 3, fact["tons"], num) fields.write(cursor, 4, f"{fact['start']} — {fact['end']}") fields.write(cursor, 5, fact["warehouse"], text) fields.write(cursor, 6, fact["rows"]) cursor += 1 fields.set_column(0, 0, 22) fields.set_column(1, 2, 36) fields.set_column(4, 5, 55) den = book.add_worksheet("Знаменатели_август") den.write(0, 0, "Показатель", header) den.write(0, 1, "Значение", header) aug = next(item for item in summaries if item["key"] == "aug14") rows_out = [ ("Назначено в ПЛАН_ВЫВОЗА, 14 дней, т", aug["tons"]), ("Остаток с признаком В_плане, т", aug["params"]["in_plan_tons"]), ("Посевов с В_плане", aug["params"]["in_plan_n"]), ("Сумма остатка таблицы полей PARAMS, т", aug["params"]["remainder_tons"]), ("Строк таблицы полей", aug["params"]["field_rows"]), ("Факт весовой 25.08–07.09.2026, т", aug["fact_tons"]), ("Из них свёкла, т", aug["focus_fact"]), ] for key, value in sverka.items(): rows_out.append((f"Сверка: {key}", value if isinstance(value, (int, float)) else str(value))) for index, (label, value) in enumerate(rows_out, 1): den.write(index, 0, label, text) if isinstance(value, (int, float)): den.write(index, 1, value, num) else: den.write(index, 1, value, text) den.set_column(0, 0, 78) den.set_column(1, 1, 22) methods = book.add_worksheet("Методы_ML") methods.write(0, 0, "Книга", header) methods.write(0, 1, "Что", header) methods.write(0, 2, "Метод", header) methods.write(0, 3, "Посевов", header) cursor = 1 for item in summaries: for name, count in item["params"]["yield_methods"].items(): methods.write(cursor, 0, item["file"]) methods.write(cursor, 1, "урожайность") methods.write(cursor, 2, name) methods.write(cursor, 3, count) cursor += 1 for name, count in item["params"]["window_methods"].items(): methods.write(cursor, 0, item["file"]) methods.write(cursor, 1, "окно уборки") methods.write(cursor, 2, name) methods.write(cursor, 3, count) cursor += 1 methods.set_column(0, 2, 46) daily = book.add_worksheet("Подневный") for col, name in enumerate(("Окно", "Дата", "План, т", "Факт весовой, т")): daily.write(0, col, name, header) cursor = 1 for item in summaries: if not item["daily_fact"]: continue days = sorted(set(item["daily_fact"]) | set(item["daily_plan"])) for day in days: daily.write(cursor, 0, item["title"]) daily.write(cursor, 1, day) daily.write(cursor, 2, item["daily_plan"].get(day, 0.0), num) daily.write(cursor, 3, item["daily_fact"].get(day, 0.0), num) cursor += 1 daily.set_column(0, 1, 28) note = book.add_worksheet("Как_читать") lines = [ "Гипотеза пилота не подтверждается этими книгами: план закрывает единицы процентов факта весовой.", "Арифметика рейсов и ставок на строках детализации сходится. Это не улучшение работы отдела.", "Окно 50 дней включает окно 14 дней. Строки свода не складывать.", "Факт — РегистрНакопления.ПриходСПолей базы ves2020, вес в тоннах, снят 2026-11-04.", "Поле Расстояние регистра в свод не переведено в километры: на ГАЗР-159 оно не сходится с плечом соседних строк плана.", "В файлах один режим «Оптимально». Три режима в поставке отдельными книгами не пришли.", ] for index, line in enumerate(lines): note.write(index, 0, line, text) note.set_column(0, 0, 120) book.close() def svg_share(summaries): width, height = 760, 250 left, right, top = 210, 28, 24 plot_w = width - left - right row_h = 42 parts = [f'") return "\n".join(parts) def svg_denominators(aug, sverka_tons): rows = [ ("Назначено планом", aug["tons"], "#1d4e89"), ("Остаток с признаком «в плане»", aug["params"]["in_plan_tons"], "#64748b"), ("Числовой остаток сверки", sverka_tons, "#b45309"), ("Факт весовой за 14 дней", aug["fact_tons"], "#9f1239"), ] width, height = 760, 230 left, top = 280, 20 plot_w = width - left - 90 max_v = max(value for _, value, _ in rows) parts = [f'") return "\n".join(parts) def svg_daily(item): days = sorted(set(item["daily_fact"]) | set(item["daily_plan"])) if not days: return "" width, height = 760, 320 left, right, gap = 48, 16, 36 panel_h = 100 top1, top2 = 36, 36 + panel_h + gap plot_w = width - left - right slot = plot_w / len(days) fact_max = max(item["daily_fact"].values()) or 1 plan_max = max(item["daily_plan"].values() or [1]) or 1 parts = [f'") return "\n".join(parts) def svg_methods(params): groups = ( ("Урожайность", params["yield_methods"]), ("Окно уборки", params["window_methods"]), ) palette = ("#1d4e89", "#b45309", "#64748b", "#3f6212") width, height = 760, 210 parts = [f'") return "\n".join(parts) def render_html(summaries, sverka, cards): aug = next(item for item in summaries if item["key"] == "aug14") sverka_tons = fnum(sverka.get("Числовой неубранный остаток всего реестра, т")) share_rows = [] for item in summaries: share_rows.append( "
Верхняя полоса — факт отдела, нижняя — план. Высота каждой полосы от своего максимума, " "иначе столбцы плана не видны. Ноль в нижней полосе — день без назначения.
Гипотеза пилота — модель и оптимизатор планируют вывоз с поля лучше отдела. На четырёх книгах этого не видно: план закрывает от 0,8% до 10% той культуры, которую отдел за те же дни уже сдал на весовую.
Пшеница для июля, свёкла для августа. Красная отметка — 95%, если бы шкала была долей всего факта. Столбцы до неё не доходят.
{svg_share(summaries)}| Окно | План, т | Факт, т | План / факт | Культура | План культуры, т | Факт культуры, т | Доля культуры | Строки без расхождения |
|---|
Окно 25.08–13.10 включает окно 25.08–07.09. Складывать эти строки нельзя. В каждой книге один режим «Оптимально».
Длина полос сжата квадратным корнем, иначе 6 тыс. т не видно рядом с 445 тыс. т. Подписи — исходные тонны.
{svg_denominators(aug, sverka_tons)}Сверка на 25.08.2026: числовой остаток реестра {fmt_t(sverka_tons)} т. В таблице полей августовского плана сумма остатка {fmt_t(aug['params']['remainder_tons'])} т, признак «в плане» — {aug['params']['in_plan_n']} посевов и {fmt_t(aug['params']['in_plan_tons'])} т.
{''.join(daily_blocks)}1 570 строк блока ML в книге на 14 дней августа. Выработка бригады в эту книгу моделью не попала: в отчёте 14.10 ошибка около 52% при пороге 15%.
{svg_methods(aug['params'])}ГАЗР-159 весовая закрыла 20–21 августа, план ставит вывоз на 1–5 сентября на тот же склад. НВМШ-016 по тоннам близок к факту, склады другие. БСЖВ-008: план 2 тыс. т за четыре дня, регистр — 528 т за полтора месяца на том же складе; это повод спросить, весь ли урожай поля попал в этот код.