759 lines
35 KiB
Python
759 lines
35 KiB
Python
#!/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'<svg viewBox="0 0 {width} {height}" role="img" aria-label="Доля плана от факта весовой">']
|
||
parts.append(f'<line x1="{left + plot_w * 0.95}" y1="16" x2="{left + plot_w * 0.95}" y2="{height - 28}" stroke="#9f1239" stroke-dasharray="4 3"/>')
|
||
parts.append(f'<text x="{left + plot_w * 0.95 - 4}" y="14" text-anchor="end" font-size="11" fill="#9f1239">порог 95% на шкале факта</text>')
|
||
for index, item in enumerate(summaries):
|
||
y = top + index * row_h
|
||
share = item["share_focus"] or 0
|
||
bar = max(2, plot_w * min(share, 1))
|
||
parts.append(f'<text x="{left - 10}" y="{y + 18}" text-anchor="end" font-size="13" fill="#1c1917">{html.escape(item["short"])}</text>')
|
||
parts.append(f'<rect x="{left}" y="{y}" width="{plot_w}" height="22" fill="#efeae3" rx="3"/>')
|
||
parts.append(f'<rect x="{left}" y="{y}" width="{bar:.1f}" height="22" fill="#1d4e89" rx="3"/>')
|
||
parts.append(
|
||
f'<text x="{left + bar + 8:.1f}" y="{y + 16}" font-size="13" fill="#1c1917">{fmt_pct(share)} от {html.escape(item["focus"])}</text>'
|
||
)
|
||
parts.append("</svg>")
|
||
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'<svg viewBox="0 0 {width} {height}" role="img" aria-label="Четыре знаменателя августа">']
|
||
for index, (label, value, color) in enumerate(rows):
|
||
y = top + index * 50
|
||
# Log-like compression so the small bars stay visible: sqrt scale.
|
||
bar = plot_w * math.sqrt(value / max_v)
|
||
parts.append(f'<text x="{left - 12}" y="{y + 18}" text-anchor="end" font-size="13" fill="#1c1917">{html.escape(label)}</text>')
|
||
parts.append(f'<rect x="{left}" y="{y}" width="{bar:.1f}" height="24" fill="{color}" rx="3"/>')
|
||
parts.append(f'<text x="{left + bar + 8:.1f}" y="{y + 17}" font-size="13" fill="#1c1917">{fmt_t(value)} т</text>')
|
||
parts.append("</svg>")
|
||
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'<svg viewBox="0 0 {width} {height}" role="img" aria-label="План и факт по дням">']
|
||
parts.append(f'<text x="{left}" y="16" font-size="12" fill="#9f1239">Факт весовой, шкала до {fmt_t(fact_max)} т/день</text>')
|
||
parts.append(f'<text x="{left}" y="{top2 - 12}" font-size="12" fill="#1d4e89">План, шкала до {fmt_t(plan_max)} т/день. Шкалы разные.</text>')
|
||
for index, day in enumerate(days):
|
||
x = left + index * slot
|
||
fact = item["daily_fact"].get(day, 0.0)
|
||
plan = item["daily_plan"].get(day, 0.0)
|
||
fh = panel_h * fact / fact_max
|
||
ph = panel_h * plan / plan_max
|
||
parts.append(f'<rect x="{x + 2:.1f}" y="{top1 + panel_h - fh:.1f}" width="{max(slot - 4, 2):.1f}" height="{fh:.1f}" fill="#b45309"/>')
|
||
parts.append(f'<rect x="{x + 2:.1f}" y="{top2 + panel_h - ph:.1f}" width="{max(slot - 4, 2):.1f}" height="{ph:.1f}" fill="#1d4e89"/>')
|
||
if index % 2 == 0:
|
||
parts.append(f'<text x="{x + slot / 2:.1f}" y="{height - 8}" text-anchor="middle" font-size="10" fill="#57534e">{day[8:10]}.{day[5:7]}</text>')
|
||
parts.append("</svg>")
|
||
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'<svg viewBox="0 0 {width} {height}" role="img" aria-label="Источники урожайности и сроков">']
|
||
y = 20
|
||
for title, counter in groups:
|
||
total = sum(counter.values()) or 1
|
||
x = 150
|
||
parts.append(f'<text x="140" y="{y + 16}" text-anchor="end" font-size="13" fill="#1c1917">{html.escape(title)}</text>')
|
||
for index, (name, count) in enumerate(counter.items()):
|
||
w = 580 * count / total
|
||
color = palette[index % len(palette)]
|
||
parts.append(f'<rect x="{x:.1f}" y="{y}" width="{max(w, 0):.1f}" height="24" fill="{color}"/>')
|
||
if w > 48:
|
||
parts.append(f'<text x="{x + 6:.1f}" y="{y + 16}" font-size="11" fill="#ffffff">{count}</text>')
|
||
x += w
|
||
y += 32
|
||
x = 150
|
||
for index, (name, count) in enumerate(counter.items()):
|
||
color = palette[index % len(palette)]
|
||
parts.append(f'<rect x="{x}" y="{y}" width="10" height="10" fill="{color}"/>')
|
||
label = f"{name}: {count}"
|
||
parts.append(f'<text x="{x + 14}" y="{y + 10}" font-size="11" fill="#57534e">{html.escape(label)}</text>')
|
||
x += 14 + len(label) * 6.2 + 16
|
||
y += 28
|
||
parts.append("</svg>")
|
||
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(
|
||
"<tr>"
|
||
f"<td>{html.escape(item['short'])}</td>"
|
||
f"<td class='num'>{fmt_t(item['tons'])}</td>"
|
||
f"<td class='num'>{fmt_t(item['fact_tons'])}</td>"
|
||
f"<td class='num'>{fmt_pct(item['share_all'])}</td>"
|
||
f"<td>{html.escape(item['focus'])}</td>"
|
||
f"<td class='num'>{fmt_t(item['focus_tons'])}</td>"
|
||
f"<td class='num'>{fmt_t(item['focus_fact'])}</td>"
|
||
f"<td class='num'>{fmt_pct(item['share_focus'])}</td>"
|
||
f"<td class='num'>{item['arith_ok']} / {item['rows']}</td>"
|
||
"</tr>"
|
||
)
|
||
field_blocks = []
|
||
for card in cards:
|
||
plan_html = []
|
||
for bit in card["plan"]:
|
||
plan_html.append(
|
||
f"<li><b>{fmt_t(bit['tons'])} т</b> · {html.escape(bit['culture'])} · "
|
||
f"{html.escape(bit['window'])}<br>{html.escape(', '.join(bit['dates']))}<br>"
|
||
f"{html.escape('; '.join(bit['warehouses']))}</li>"
|
||
)
|
||
fact_html = []
|
||
for fact in card["fact"]:
|
||
fact_html.append(
|
||
f"<li><b>{fmt_t(fact['tons'])} т</b> · {html.escape(fact['culture'])}<br>"
|
||
f"{html.escape(fact['start'])} — {html.escape(fact['end'])}, {fact['rows']} строк<br>"
|
||
f"{html.escape(fact['warehouse'])}</li>"
|
||
)
|
||
field_blocks.append(
|
||
f"<article class='card'><h3>{html.escape(card['field'])}</h3>"
|
||
f"<h4>План</h4><ul>{''.join(plan_html) or '<li>В этих книгах нет</li>'}</ul>"
|
||
f"<h4>Весовая</h4><ul>{''.join(fact_html)}</ul></article>"
|
||
)
|
||
daily_blocks = []
|
||
for item in summaries:
|
||
if item["daily_fact"]:
|
||
daily_blocks.append(
|
||
f"<section><h2>{html.escape(item['short'])}: дни плана и дни весовой</h2>"
|
||
f"{svg_daily(item)}"
|
||
"<p class='note'>Верхняя полоса — факт отдела, нижняя — план. Высота каждой полосы от своего максимума, "
|
||
"иначе столбцы плана не видны. Ноль в нижней полосе — день без назначения.</p></section>"
|
||
)
|
||
document = f"""<!DOCTYPE html>
|
||
<html lang="ru">
|
||
<head>
|
||
<meta charset="utf-8">
|
||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||
<title>Проверка плана вывоза — отчёт заказчика</title>
|
||
<style>
|
||
:root {{ color-scheme: light; }}
|
||
body {{ margin: 0; background: #f4f0e8; color: #1c1917; font: 16px/1.45 "Segoe UI", sans-serif; }}
|
||
main {{ max-width: 980px; margin: 0 auto; padding: 32px 20px 64px; }}
|
||
h1 {{ font-size: 32px; line-height: 1.15; margin: 0 0 8px; }}
|
||
h2 {{ font-size: 22px; margin: 32px 0 8px; }}
|
||
h3 {{ margin: 0 0 8px; font-size: 18px; }}
|
||
h4 {{ margin: 12px 0 4px; font-size: 13px; letter-spacing: .04em; text-transform: uppercase; color: #57534e; }}
|
||
p, li {{ color: #292524; }}
|
||
.lead {{ font-size: 18px; max-width: 68ch; }}
|
||
.verdict {{ background: #fff7ed; border-left: 6px solid #9f1239; padding: 14px 16px; margin: 16px 0 8px; }}
|
||
.meta {{ color: #57534e; font-size: 14px; }}
|
||
table {{ width: 100%; border-collapse: collapse; background: white; font-size: 14px; }}
|
||
th, td {{ border-bottom: 1px solid #e7e5e4; padding: 8px 6px; text-align: left; vertical-align: top; }}
|
||
th {{ background: #1d4e89; color: white; font-weight: 600; }}
|
||
td.num {{ text-align: right; font-variant-numeric: tabular-nums; white-space: nowrap; }}
|
||
svg {{ width: 100%; height: auto; background: white; border: 1px solid #e7e5e4; }}
|
||
.cards {{ display: grid; grid-template-columns: 1fr; gap: 12px; }}
|
||
.card {{ background: white; border: 1px solid #e7e5e4; padding: 12px 14px; }}
|
||
.card ul {{ margin: 0; padding-left: 18px; }}
|
||
.note {{ font-size: 14px; color: #57534e; }}
|
||
a {{ color: #1d4e89; }}
|
||
@media (min-width: 800px) {{ .cards {{ grid-template-columns: 1fr 1fr 1fr; }} }}
|
||
</style>
|
||
</head>
|
||
<body>
|
||
<main>
|
||
<p class="meta">Заказчик · поставка 27.10.2026 · факт весовой снят 04.11.2026</p>
|
||
<h1>План вывоза не заменяет работу отдела логистики</h1>
|
||
<p class="lead">Гипотеза пилота — модель и оптимизатор планируют вывоз с поля лучше отдела. На четырёх книгах этого не видно: план закрывает от 0,8% до 10% той культуры, которую отдел за те же дни уже сдал на весовую.</p>
|
||
<div class="verdict">
|
||
<b>К переговорам.</b> Покрытие «около 95%» в отчёте подрядчика посчитано от остатка, который модель сама допустила в расчёт (около 6 тыс. т). Факт прихода с полей за 14 дней августа — 445 тыс. т. Арифметика строк плана при этом сходится полностью. Это разные утверждения.
|
||
</div>
|
||
<p class="meta">Как устроена проверка — <a href="../методика_приёмки.md">методика</a>. Вопросы на сессию — <a href="../пакет_к_переговорам.md">пакет к переговорам</a>. Числа этой страницы пересчитывает <a href="../checker/check_plans.py">analysis/checker/check_plans.py</a>.</p>
|
||
|
||
<h2>Доля плана от факта своей культуры</h2>
|
||
<p class="note">Пшеница для июля, свёкла для августа. Красная отметка — 95%, если бы шкала была долей всего факта. Столбцы до неё не доходят.</p>
|
||
{svg_share(summaries)}
|
||
|
||
<h2>Сводка</h2>
|
||
<table>
|
||
<thead>
|
||
<tr>
|
||
<th>Окно</th><th>План, т</th><th>Факт, т</th><th>План / факт</th>
|
||
<th>Культура</th><th>План культуры, т</th><th>Факт культуры, т</th><th>Доля культуры</th><th>Строки без расхождения</th>
|
||
</tr>
|
||
</thead>
|
||
<tbody>
|
||
{''.join(share_rows)}
|
||
</tbody>
|
||
</table>
|
||
<p class="note">Окно 25.08–13.10 включает окно 25.08–07.09. Складывать эти строки нельзя. В каждой книге один режим «Оптимально».</p>
|
||
|
||
<h2>Четыре знаменателя августа, 14 дней</h2>
|
||
<p class="note">Длина полос сжата квадратным корнем, иначе 6 тыс. т не видно рядом с 445 тыс. т. Подписи — исходные тонны.</p>
|
||
{svg_denominators(aug, sverka_tons)}
|
||
<p class="note">Сверка на 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'])} т.</p>
|
||
|
||
{''.join(daily_blocks)}
|
||
|
||
<h2>Откуда в августовском плане урожай и сроки</h2>
|
||
<p class="note">1 570 строк блока ML в книге на 14 дней августа. Выработка бригады в эту книгу моделью не попала: в отчёте 14.10 ошибка около 52% при пороге 15%.</p>
|
||
{svg_methods(aug['params'])}
|
||
|
||
<h2>Три поля из отчёта подрядчика</h2>
|
||
<div class="cards">
|
||
{''.join(field_blocks)}
|
||
</div>
|
||
<p class="note">ГАЗР-159 весовая закрыла 20–21 августа, план ставит вывоз на 1–5 сентября на тот же склад. НВМШ-016 по тоннам близок к факту, склады другие. БСЖВ-008: план 2 тыс. т за четыре дня, регистр — 528 т за полтора месяца на том же складе; это повод спросить, весь ли урожай поля попал в этот код.</p>
|
||
|
||
<h2>Что из этого следует на сессии</h2>
|
||
<ol>
|
||
<li>Спросить, на каком объёме план считается лучше работы отдела. Фактический вывоз, который в сравнение не вошёл, назвать явно.</li>
|
||
<li>Не принимать 95% от допущенного остатка как покрытие работы весовой.</li>
|
||
<li>По ГАЗР-159 разобрать, зачем план назначает поле, которое весовая уже приняла.</li>
|
||
<li>Потребовать три режима в файле, если выбор «дешевле / быстрее» ещё считается результатом пилота.</li>
|
||
</ol>
|
||
</main>
|
||
</body>
|
||
</html>
|
||
"""
|
||
OUT_HTML.write_text(document, encoding="utf-8")
|
||
|
||
|
||
def main():
|
||
ves = load_json(VES / "windows.json")["windows"]
|
||
examples = load_json(VES / "example_fields.json")["fields"]
|
||
sverka = read_sverka(INCOMING / "Сверка_остатков_2026-08-25.xlsx")
|
||
summaries = []
|
||
for spec in PLANS:
|
||
plan = read_plan(INCOMING / spec["file"])
|
||
summaries.append(summarize(spec, plan, ves[spec["key"]]))
|
||
cards = example_cards(summaries, examples)
|
||
write_xlsx(summaries, sverka, cards)
|
||
render_html(summaries, sverka, cards)
|
||
print(f"xlsx {OUT_XLSX}")
|
||
print(f"html {OUT_HTML}")
|
||
for item in summaries:
|
||
print(
|
||
item["key"],
|
||
f"plan={item['tons']:.1f}",
|
||
f"fact={item['fact_tons']:.1f}",
|
||
f"share={item['share_focus']:.3%}" if item["share_focus"] is not None else "",
|
||
f"arith={item['arith_ok']}/{item['rows']}",
|
||
)
|
||
|
||
|
||
if __name__ == "__main__":
|
||
main()
|