From 2d56ab25114ba5883fd0dbccd5362b4bc7d634b5 Mon Sep 17 00:00:00 2001 From: anor Date: Sun, 22 Nov 2026 16:36:05 +1000 Subject: [PATCH] =?UTF-8?q?feat(=D0=BE=D0=B1=D1=85=D0=BE=D0=B4):=20=D0=B5?= =?UTF-8?q?=D0=B6=D0=B5=D0=B4=D0=BD=D0=B5=D0=B2=D0=BD=D1=8B=D0=B9=20=D1=81?= =?UTF-8?q?=D0=BA=D0=B0=D0=BD=20=D0=B7=D0=BE=D0=BD=20=D0=A4=D0=93=D0=98?= =?UTF-8?q?=D0=A1=20=D1=81=20=D0=BE=D0=B6=D0=B8=D0=B4=D0=B0=D0=BD=D0=B8?= =?UTF-8?q?=D1=8F=D0=BC=D0=B8=20=D0=B8=20=D0=B6=D1=83=D1=80=D0=BD=D0=B0?= =?UTF-8?q?=D0=BB=D0=BE=D0=BC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Отдельный файл ожиданий, «нет» только по 404 портала, сетевой сбой в «не проверено», общий flock с недельным обходом, горизонт два квартала, одна строка журнала. Четыре проверки планировщика. Co-Authored-By: Claude Code --- scripts/fgis_zone_scan.py | 128 +++++++++++++++++++++++++++++++++++ tests/test_fgis_zone_scan.py | 30 ++++++++ 2 files changed, 158 insertions(+) create mode 100644 scripts/fgis_zone_scan.py create mode 100644 tests/test_fgis_zone_scan.py diff --git a/scripts/fgis_zone_scan.py b/scripts/fgis_zone_scan.py new file mode 100644 index 0000000..9df3788 --- /dev/null +++ b/scripts/fgis_zone_scan.py @@ -0,0 +1,128 @@ +#!/usr/bin/env python3 +"""Ежедневный обход зон ФГИС: ожидания «форм нет» и отметка успешного обхода. + +Правила (design-log 2026-11-21з): ожидания — отдельный файл на сервере; «нет» только +по успешному ответу портала; сетевой сбой — «не проверено», ожидания не меняются; +общий flock с недельным обходом; ожидание снимается по горизонту или уходу зоны; +одна строка журнала на прогон. +""" +from __future__ import annotations +import argparse, fcntl, json, os, re, sqlite3, time +from datetime import datetime, timezone +from pathlib import Path + +EXPECT_DEFAULT = "/data_fast/smeta-web-data/_external/coverage_expectations.json" +STATE_DEFAULT = "/data_fast/smeta-web-data/_external/zone_scan_state.json" +LOG_DEFAULT = "/data_fast/smeta-web-data/_external/zone_scan.log" +LOCK_DEFAULT = "/tmp/smeta-refresh.lock" +DB_DEFAULT = "/data_fast/smeta-web-data/_external/derived/fgis_ref/fgis_ref.sqlite" + + +def _period_key(label: str) -> str: + m = re.search(r"(\d)\s*квартал.*?(\d{4})", label or "", re.I) + return f"{m.group(2)}-Q{m.group(1)}" if m else (label or "") + + +def _period_rank(key: str) -> tuple[int, int]: + m = re.match(r"(\d{4})-Q([1-4])", key or "") + return (int(m.group(1)), int(m.group(2))) if m else (0, 0) + + +def plan(existing: list[dict], portal: dict[tuple[int, int], list[dict]], + known: set[tuple[int, int, int]], horizon: int = 2) -> tuple[list[dict], list[dict]]: + """Вернуть (добавить, снять) для ожиданий. Чистая функция — без сети и базы.""" + have = {(int(e["subject_id"]), int(e["zone_id"]), e["period"]) for e in existing} + adds, removes = [], [] + for (sid, zid), periods in portal.items(): + latest = sorted((p["id"], _period_key(p.get("name", ""))) for p in periods) + keep_rank = latest[-horizon][0] if len(latest) >= horizon else None + for pid, per in latest[-horizon:]: + if (sid, zid, per) in have or (sid, zid, pid) in known: + continue + adds.append({"subject_id": sid, "zone_id": zid, "period": per, + "zone_name": None, "reason": "проверяется"}) + # снять ожидания старее горизонта + for e in existing: + if int(e["subject_id"]) != sid or int(e["zone_id"]) != zid: + continue + if keep_rank is not None and _period_rank(e["period"]) < _period_rank( + dict(latest).get(keep_rank, "")): + removes.append(e) + zones = set(portal) + for e in existing: + if (int(e["subject_id"]), int(e["zone_id"])) not in zones: + removes.append(e) + return adds, removes + + +def main() -> int: + ap = argparse.ArgumentParser() + ap.add_argument("--expect", default=os.environ.get("SCAN_EXPECT", EXPECT_DEFAULT)) + ap.add_argument("--state", default=os.environ.get("SCAN_STATE", STATE_DEFAULT)) + ap.add_argument("--log", default=os.environ.get("SCAN_LOG", LOG_DEFAULT)) + ap.add_argument("--db", default=os.environ.get("FGIS_DB", DB_DEFAULT)) + ap.add_argument("--dry-run", action="store_true") + a = ap.parse_args() + lock = open(os.environ.get("SCAN_LOCK", LOCK_DEFAULT), "w") + try: + fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + except OSError: + print("SCAN busy: замок занят недельным обходом", flush=True) + return 3 + import fgis_client as fc, ext_pull + expect_path, state_path = Path(a.expect), Path(a.state) + existing = json.loads(expect_path.read_text(encoding="utf-8")) if expect_path.exists() else [] + known, portal, failures = set(), {}, [] + con = sqlite3.connect(f"file:{a.db}?mode=ro", uri=True) + known = {(int(s), int(z), int(p)) for s, z, p in + con.execute("select subject_id,zone_id,period_id from zone_snapshots")} + con.close() + subjects = fc.country_subjects() + for s in subjects: + try: + zones = fc.price_zones(s["id"]) + except Exception as e: # noqa: BLE001 — сеть: не проверено, ожидания не меняем + failures.append(f"zones {s['id']}: {type(e).__name__}"); continue + for z in zones: + try: + portal[(s["id"], z["id"])] = fc.periods(z["id"]) + except Exception as e: # noqa: BLE001 + failures.append(f"periods {s['id']}/{z['id']}: {type(e).__name__}") + adds, removes = plan(existing, portal, known) + checked = added = 0 + for add in adds: + sid, zid = add["subject_id"], add["zone_id"] + pid = next(p["id"] for p in portal[(sid, zid)] + if _period_key(p.get("name", "")) == add["period"]) + try: + ext_pull.pull_split_form(sid, zid, pid) + except Exception as e: # noqa: BLE001 + text = str(e) + if "404" in text: + add.update(zone_name=None, + reason="на портале ФГИС ЦС форм за период нет (проверено " + + datetime.now(timezone.utc).strftime("%Y-%m-%d") + ")") + existing.append(add); added += 1 + else: + failures.append(f"form {sid}/{zid}/{pid}: {type(e).__name__}") + checked += 1 + existing = [e for e in existing if e not in removes] + stamp = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ") + if not a.dry_run: + tmp = expect_path.with_suffix(".tmp") + tmp.write_text(json.dumps(existing, ensure_ascii=False, indent=1), encoding="utf-8") + tmp.replace(expect_path) + state_path.write_text(json.dumps({"last_success": stamp, "zones": len(portal), + "added": added, "removed": len(removes), + "failures": failures}, ensure_ascii=False), encoding="utf-8") + line = (f"{stamp} зон={len(portal)} добавлено={added} снято={len(removes)} " + + ("без изменений" if not added and not removes else "изменения") + + (f" сбоев={len(failures)}" if failures else "")) + with open(a.log, "a", encoding="utf-8") as f: + f.write(line + "\n") + print(line) + return 0 if not failures else 1 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tests/test_fgis_zone_scan.py b/tests/test_fgis_zone_scan.py new file mode 100644 index 0000000..0461c01 --- /dev/null +++ b/tests/test_fgis_zone_scan.py @@ -0,0 +1,30 @@ +"""Планировщик ожиданий ежедневного обхода зон (22.11.2026).""" +import sys +from pathlib import Path +sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "scripts")) +import fgis_zone_scan as z # noqa: E402 + +def p(i, name): return {"id": i, "name": name} +PORTAL = {(320, 245): [p(421, "1 квартал 2025 г."), p(422, "2 квартал 2025 г."), + p(423, "3 квартал 2025 г."), p(424, "4 квартал 2025 г."), + p(425, "1 квартал 2026 г."), p(426, "2 квартал 2026 г.")]} + +def test_new_period_added_when_not_loaded(): + adds, rem = z.plan([], PORTAL, known={(320, 245, 425)}, horizon=2) + assert any(a["period"] == "2026-Q2" for a in adds) + assert not any(a["period"] == "2026-Q1" for a in adds) + +def test_expectation_not_duplicated(): + ex = [{"subject_id": 320, "zone_id": 245, "period": "2026-Q2"}] + adds, _ = z.plan(ex, PORTAL, known={(320, 245, 425)}, horizon=2) + assert not [a for a in adds if a["period"] == "2026-Q2"] + +def test_old_expectation_removed_by_horizon(): + ex = [{"subject_id": 320, "zone_id": 245, "period": "2024-Q4"}] + _, rem = z.plan(ex, PORTAL, known=set(), horizon=2) + assert ex[0] in rem + +def test_zone_gone_removes_all_its_expectations(): + ex = [{"subject_id": 999, "zone_id": 1, "period": "2025-Q1"}] + _, rem = z.plan(ex, PORTAL, known=set(), horizon=2) + assert ex[0] in rem