From 3a92013600375c74dc9ca951a2aa95829bc6e94c Mon Sep 17 00:00:00 2001 From: anor Date: Sat, 18 Jul 2026 01:38:44 +1000 Subject: [PATCH] =?UTF-8?q?feat(ext):=20=D0=A4=D0=B0=D0=B7=D0=B0=203=20?= =?UTF-8?q?=E2=80=94=20=D1=87=D0=B5=D0=BA=D0=B5=D1=80=20=D0=BE=D0=B1=D0=BD?= =?UTF-8?q?=D0=BE=D0=B2=D0=BB=D0=B5=D0=BD=D0=B8=D0=B9=20(=D1=82=D0=BE?= =?UTF-8?q?=D0=BB=D1=8C=D0=BA=D0=BE=20=D0=B4=D0=BE=D0=BA=D0=BB=D0=B0=D0=B4?= =?UTF-8?q?)=20+=20watch=5Fseen/heartbeat/=D0=B4=D0=B0=D0=B9=D0=B4=D0=B6?= =?UTF-8?q?=D0=B5=D1=81=D1=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ext_check: обходит источники (новый период ФГИС по зонам, новые приказы pravo, недоступность), ТОЛЬКО докладывает — state.json НЕ трогает (инвариант в тесте, red-green). watch_seen (дедуп), reports/, watch.log, heartbeat. email_service.send_operator_digest — письмо оператору только при новостях (тишина=норма). 7 тестов. --- email_service.py | 25 +++++++ ext_check.py | 161 ++++++++++++++++++++++++++++++++++++++++ ext_state.py | 37 +++++++++ tests/test_ext_check.py | 113 ++++++++++++++++++++++++++++ 4 files changed, 336 insertions(+) create mode 100644 ext_check.py create mode 100644 tests/test_ext_check.py diff --git a/email_service.py b/email_service.py index f357de4..79ec583 100644 --- a/email_service.py +++ b/email_service.py @@ -15,6 +15,31 @@ SMTP_USER = os.environ.get("SMTP_USER", "") SMTP_PASS = os.environ.get("SMTP_PASS", "") +def send_operator_digest(to_email: str, subject: str, html: str) -> bool: + """Дайджест оператору о новостях внешних источников (чекер ext_check). True при успехе.""" + if not SMTP_USER or not SMTP_PASS: + logger.warning("SMTP not configured, skipping operator digest to %s", to_email) + return False + if not to_email: + return False + msg = MIMEMultipart("alternative") + from email.header import Header + msg["Subject"] = subject + msg["From"] = f"{Header('Сметный ассистент', 'utf-8').encode()} <{SMTP_USER}>" + msg["To"] = to_email + msg.attach(MIMEText(html, "html", "utf-8")) + try: + context = ssl.create_default_context() + with smtplib.SMTP_SSL(SMTP_HOST, SMTP_PORT, context=context, timeout=10) as server: + server.login(SMTP_USER, SMTP_PASS) + server.sendmail(SMTP_USER, to_email, msg.as_string()) + logger.info("Operator digest sent to %s", to_email) + return True + except Exception as e: # noqa: BLE001 + logger.error("Failed to send operator digest to %s: %s", to_email, e) + return False + + def send_verification_code(to_email: str, code: str) -> bool: """Send 6-digit verification code to email. Returns True on success.""" if not SMTP_USER or not SMTP_PASS: diff --git a/ext_check.py b/ext_check.py new file mode 100644 index 0000000..cd99dd4 --- /dev/null +++ b/ext_check.py @@ -0,0 +1,161 @@ +"""ext_check — периодическая проверка обновлений внешних источников (срез 3.1). + +СЕРДЦЕ мониторинга. Строгий контракт: ТОЛЬКО ДОКЛАДЫВАЕТ. НЕ качает данные, НЕ трогает +state.json (его пишут только pull/apply). Пишет: watch_seen.json (дедуп доклада), +reports/.json, watch.log, heartbeat.json. Уведомляет оператора письмом ТОЛЬКО при +новостях/проблемах (тишина = «проверил, изменений нет», видно по heartbeat). + +Сигналы: новый период ФГИС по региону/зоне; новый приказ Минстроя (pravo); недоступность +источника (это тоже новость — недокументированный API мог смениться). +""" +from __future__ import annotations + +import json +import os +import sys +from datetime import datetime, timezone +from pathlib import Path + +import ext_fetch +import ext_state +import fgis_client as fc +import pravo_client as pc + + +def _regions() -> list[int]: + raw = os.environ.get("EXT_REGIONS", "") + return [int(x) for x in raw.replace(";", ",").split(",") if x.strip().isdigit()] + + +def check_fgis(regions: list[int], seen: dict, *, client=None) -> tuple[list[dict], dict]: + """Новый период по каждой зоне сконфигурированных регионов. Дедуп через seen.""" + findings: list[dict] = [] + if not fc.alive(client=client): + findings.append({"source": "fgis", "level": "problem", + "message": "ФГИС ЦС недоступен (/api/alive не отвечает 200)"}) + return findings, seen + reported = seen.get("fgis_periods_reported", {}) + state = ext_state.load_state() # ЧТЕНИЕ, не запись + active_all = state.get("sources", {}).get("fgis_split_form", {}) + for subject_id in regions: + try: + zones = fc.price_zones(subject_id, client=client) + except ext_fetch.FetchError as e: + findings.append({"source": "fgis", "level": "problem", + "message": f"регион {subject_id}: ошибка запроса зон: {e}"}) + continue + for z in zones: + zone_id = z["id"] + lp = fc.latest_period(zone_id, client=client) + if not lp: + continue + key = f"{subject_id}/{zone_id}" + active = (active_all.get(key) or {}).get("period_id") + if lp["id"] != active and reported.get(key) != lp["id"]: + findings.append({ + "source": "fgis_split_form", "level": "update", + "message": f"Новый период «{lp['name']}» (id {lp['id']}) для «{z['name']}»; " + f"активен id {active}", + "action": (f"python3 ext_pull.py --source all --subject {subject_id} " + f"--zone {zone_id} --period {lp['id']} && " + f"python3 ext_apply.py --subject {subject_id} --zone {zone_id} " + f"--period {lp['id']}"), + }) + reported[key] = lp["id"] + seen["fgis_periods_reported"] = reported + return findings, seen + + +def check_pravo(seen: dict, *, client=None) -> tuple[list[dict], dict]: + """Новые приказы Минстроя. Дедуп через seen['pravo_eo'].""" + seen_eo = set(seen.get("pravo_eo", [])) + try: + new = pc.new_since(seen_eo, client=client) + except ext_fetch.FetchError as e: + return [{"source": "pravo", "level": "problem", + "message": f"pravo.gov.ru недоступен: {e}"}], seen + findings: list[dict] = [] + for d in new: + findings.append({ + "source": "pravo", "level": "update" if d["relevant"] else "info", + "message": (f"Приказ {d['number']} от {(d['documentDate'] or '')[:10]}: " + f"{(d['name'] or '')[:130]}" + (" ⚑ релевантно смете" if d["relevant"] else "")), + "pdf": d["pdf_url"], + }) + seen_eo.add(d["eoNumber"]) + seen["pravo_eo"] = sorted(seen_eo)[-500:] # храним последние 500, не растим бесконечно + return findings, seen + + +def _write_report(findings: list[dict], regions: list[int]) -> Path: + ts = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H-%M-%SZ") + rep = {"at": ts, "regions": regions, "findings": findings, + "updates": sum(1 for f in findings if f["level"] == "update"), + "problems": sum(1 for f in findings if f["level"] == "problem")} + rdir = ext_state.ext_dir() / "reports" + rdir.mkdir(parents=True, exist_ok=True) + ext_state._atomic_write_text(rdir / f"{ts}.json", json.dumps(rep, ensure_ascii=False, indent=2)) + # человекочитаемый журнал + log = ext_state.ext_dir() / "watch.log" + with open(log, "a", encoding="utf-8") as f: + f.write(f"[{ts}] находок: {len(findings)} " + f"(обновлений {rep['updates']}, проблем {rep['problems']})\n") + for fnd in findings: + f.write(f" - [{fnd['level']}] {fnd['source']}: {fnd['message']}\n") + return rdir / f"{ts}.json" + + +def _notify(findings: list[dict]) -> None: + to = os.environ.get("OPERATOR_EMAIL", "") + if not to or not findings: + return + try: + import email_service + except Exception: # noqa: BLE001 + return + updates = [f for f in findings if f["level"] in ("update", "problem")] + rows = "".join( + f"
  • [{f['level']}] {f['source']}: {f['message']}" + + (f"
    {f['action']}" if f.get("action") else "") + + (f"
    PDF" if f.get("pdf") else "") + + "
  • " + for f in findings) + html = (f"

    Внешние источники: {len(findings)} новостей

    " + f"" + f"

    Данные НЕ скачаны автоматически — это доклад. " + f"Команды для скачивания/активации — в пунктах выше.

    ") + subj = f"Сметный ассистент: обновления источников ({len(updates)} важных)" + email_service.send_operator_digest(to, subj, html) + + +def run_check(regions: list[int] | None = None, *, notify: bool = True) -> dict: + """Один прогон чекера. Возвращает отчёт. НЕ трогает state.json.""" + regions = regions if regions is not None else _regions() + seen = ext_state.load_watch_seen() + f_fgis, seen = check_fgis(regions, seen) + f_pravo, seen = check_pravo(seen) + findings = f_fgis + f_pravo + ext_state.save_watch_seen(seen) # дедуп-состояние (не state.json!) + _write_report(findings, regions) + if notify and findings: + _notify(findings) + ext_state.write_heartbeat() # «я жив» — последним, только при успешном проходе + return {"findings": findings, "regions": regions, + "updates": sum(1 for f in findings if f["level"] == "update"), + "problems": sum(1 for f in findings if f["level"] == "problem")} + + +def main(argv=None) -> int: + import argparse + ap = argparse.ArgumentParser(description="Проверка обновлений внешних источников (только доклад).") + ap.add_argument("--no-notify", action="store_true", help="не слать письмо (для ручного запуска)") + args = ap.parse_args(argv) + rep = run_check(notify=not args.no_notify) + print(f"находок: {len(rep['findings'])} (обновлений {rep['updates']}, проблем {rep['problems']})") + for f in rep["findings"]: + print(f" [{f['level']}] {f['source']}: {f['message']}") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/ext_state.py b/ext_state.py index d7ab278..6f5b224 100644 --- a/ext_state.py +++ b/ext_state.py @@ -151,6 +151,43 @@ def update_state(): save_state(st) +# --- watch_seen.json + heartbeat (пишет ТОЛЬКО чекер ext_check; state.json он НЕ трогает) --- + +def _watch_seen_path() -> Path: + return ext_dir() / "watch_seen.json" + + +def load_watch_seen() -> dict: + p = _watch_seen_path() + if not p.exists(): + return {} + try: + return json.loads(p.read_text(encoding="utf-8")) + except (json.JSONDecodeError, OSError): + return {} + + +def save_watch_seen(data: dict) -> None: + _atomic_write_text(_watch_seen_path(), json.dumps(data, ensure_ascii=False, indent=2)) + + +def write_heartbeat() -> None: + _atomic_write_text(ext_dir() / "heartbeat.json", json.dumps({"at": _utcnow()})) + + +def heartbeat_age_days() -> float | None: + """Сколько дней назад чекер успешно отработал. None если ни разу.""" + p = ext_dir() / "heartbeat.json" + if not p.exists(): + return None + try: + at = json.loads(p.read_text(encoding="utf-8"))["at"] + dt = datetime.strptime(at, "%Y-%m-%dT%H:%M:%SZ").replace(tzinfo=timezone.utc) + return (datetime.now(timezone.utc) - dt).total_seconds() / 86400.0 + except (json.JSONDecodeError, OSError, KeyError, ValueError): + return None + + # --- снапшоты --- def _read_meta(meta_path: Path) -> dict: diff --git a/tests/test_ext_check.py b/tests/test_ext_check.py new file mode 100644 index 0000000..0af2120 --- /dev/null +++ b/tests/test_ext_check.py @@ -0,0 +1,113 @@ +"""Срез 3.1: чекер обновлений. Главный инвариант — ЧЕКЕР НЕ МУТИРУЕТ state.json +(его пишут только pull/apply). red-green: тест на неизменность state — первым по важности. +Сеть замокана (fgis_client/pravo_client). +""" +import json +import sys +from pathlib import Path + +import pytest + +sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) +import ext_check as ec # noqa: E402 +import ext_state as es # noqa: E402 +import fgis_client as fc # noqa: E402 +import pravo_client as pc # noqa: E402 + + +@pytest.fixture +def _tmp(monkeypatch, tmp_path): + monkeypatch.setenv("EXT_SNAPSHOT_DIR", str(tmp_path)) + monkeypatch.delenv("OPERATOR_EMAIL", raising=False) + return tmp_path + + +def _mock_fgis(monkeypatch, *, alive=True, latest=426): + monkeypatch.setattr(fc, "alive", lambda client=None: alive) + monkeypatch.setattr(fc, "price_zones", lambda s, client=None: [{"id": 191, "name": "город Москва"}]) + monkeypatch.setattr(fc, "latest_period", lambda z, client=None: {"id": latest, "name": f"период {latest}"}) + + +def _mock_pravo(monkeypatch, new_docs): + monkeypatch.setattr(pc, "new_since", lambda seen, pages=1, client=None: new_docs) + + +def test_new_period_produces_finding_with_action(_tmp, monkeypatch): + _mock_fgis(monkeypatch, latest=426) + _mock_pravo(monkeypatch, []) + # активен период 425 → 426 новее + with es.update_state() as st: + st["sources"]["fgis_split_form"] = {"323/191": {"period_id": 425}} + rep = ec.run_check(regions=[323], notify=False) + ups = [f for f in rep["findings"] if f["source"] == "fgis_split_form"] + assert len(ups) == 1 and "426" in ups[0]["message"] and "ext_pull.py" in ups[0]["action"] + + +def test_no_finding_when_period_is_active(_tmp, monkeypatch): + _mock_fgis(monkeypatch, latest=426) + _mock_pravo(monkeypatch, []) + with es.update_state() as st: + st["sources"]["fgis_split_form"] = {"323/191": {"period_id": 426}} + rep = ec.run_check(regions=[323], notify=False) + assert not [f for f in rep["findings"] if f["source"] == "fgis_split_form"] + + +def test_checker_does_not_mutate_state_json(_tmp, monkeypatch): + """КЛЮЧЕВОЙ ИНВАРИАНТ: прогон чекера НЕ меняет state.json ни на байт.""" + _mock_fgis(monkeypatch, latest=999) # заведомо новый период + _mock_pravo(monkeypatch, [{"eoNumber": "E1", "number": "1/пр", "name": "смета", + "documentDate": "2026-07-01", "relevant": True, "pdf_url": "u"}]) + with es.update_state() as st: + st["sources"]["fgis_split_form"] = {"323/191": {"period_id": 425}} + before = (_tmp / "state.json").read_bytes() + ec.run_check(regions=[323], notify=False) + after = (_tmp / "state.json").read_bytes() + assert before == after, "чекер изменил state.json — нарушение контракта" + + +def test_alive_false_reports_problem_no_crash(_tmp, monkeypatch): + _mock_fgis(monkeypatch, alive=False) + _mock_pravo(monkeypatch, []) + rep = ec.run_check(regions=[323], notify=False) + assert rep["problems"] >= 1 + assert any("недоступен" in f["message"] for f in rep["findings"]) + + +def test_pravo_new_orders_and_seen_dedup(_tmp, monkeypatch): + _mock_fgis(monkeypatch, latest=426) + docs = [{"eoNumber": "E1", "number": "1/пр", "name": "Об индексах сметной стоимости", + "documentDate": "2026-07-01", "relevant": True, "pdf_url": "http://p/E1"}] + _mock_pravo(monkeypatch, docs) + with es.update_state() as st: + st["sources"]["fgis_split_form"] = {"323/191": {"period_id": 426}} + rep = ec.run_check(regions=[323], notify=False) + pravo = [f for f in rep["findings"] if f["source"] == "pravo"] + assert len(pravo) == 1 and pravo[0]["level"] == "update" # релевантный → update + # eoNumber попал в seen (дедуп на следующий прогон) + assert "E1" in es.load_watch_seen()["pravo_eo"] + + +def test_heartbeat_written(_tmp, monkeypatch): + _mock_fgis(monkeypatch, latest=426) + _mock_pravo(monkeypatch, []) + assert es.heartbeat_age_days() is None + ec.run_check(regions=[323], notify=False) + age = es.heartbeat_age_days() + assert age is not None and age < 1 + + +def test_notify_called_only_with_findings(_tmp, monkeypatch): + _mock_fgis(monkeypatch, latest=426) + _mock_pravo(monkeypatch, []) + monkeypatch.setenv("OPERATOR_EMAIL", "op@test") + calls = [] + import email_service + monkeypatch.setattr(email_service, "send_operator_digest", + lambda to, subj, html: calls.append((to, subj)) or True) + with es.update_state() as st: + st["sources"]["fgis_split_form"] = {"323/191": {"period_id": 426}} + ec.run_check(regions=[323], notify=True) # нет новостей + assert calls == [] + _mock_fgis(monkeypatch, latest=430) # теперь новый период + ec.run_check(regions=[323], notify=True) + assert len(calls) == 1 and calls[0][0] == "op@test" # письмо ушло с новостью