feat(ext): Фаза 1 — скачивание и активация данных ФГИС ЦС
fgis_client: download_split_form/indices/salary (endpoints сняты с сервера). ext_pull: скачивание в снапшоты по региону+кварталу (осознанный шаг, EXT_REGIONS, не все 85). ext_apply: verify (openpyxl+кодов≥1000) → diff по кодам колонки A → ГЕЙТ аномалий (>30% удалено → отказ без --force) → бэкап старого → атомарная подмена fgis_split_form.xlsx → предупреждение о fgis_cache.pkl (удаление только --yes) → напоминание рестарта (сам НЕ рестартит). 11 тестов (гейт red-green).
This commit is contained in:
+149
@@ -0,0 +1,149 @@
|
||||
"""ext_pull — скачивание внешних данных ФГИС ЦС в версионированные снапшоты (срез 1.2).
|
||||
|
||||
ОСОЗНАННЫЙ шаг (не чекер): качает сплит-форму / индексы ГОСР / оплату труда по региону+
|
||||
кварталу, кладёт в снапшот (ext_state.register_snapshot — crash-safe, версионирование),
|
||||
отмечает в state. НЕ активирует данные для движка (это ext_apply). НЕ рестартит сервис.
|
||||
|
||||
Объёмы: сплит-форма ~13.7МБ × регион × квартал. По умолчанию только EXT_REGIONS
|
||||
(id регионов через запятую) — НЕ все 85. Периоды: latest, если не задан.
|
||||
|
||||
CLI: python3 ext_pull.py --source split_form --subject 323 [--zone 191] [--period 426]
|
||||
python3 ext_pull.py --source all --regions 323 # split+indices+salary
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
import ext_state
|
||||
import fgis_client as fc
|
||||
|
||||
SNAP = "snapshots/fgis"
|
||||
|
||||
|
||||
def _snap_dir(kind: str, subject_id: int, zone_id: int, period_id: int) -> Path:
|
||||
return ext_state.ext_dir() / SNAP / kind / str(subject_id) / str(zone_id) / str(period_id)
|
||||
|
||||
|
||||
def _record_state(kind: str, subject_id: int, zone_id: int, period_id: int, meta: dict) -> None:
|
||||
with ext_state.update_state() as st:
|
||||
srcs = st["sources"].setdefault(f"fgis_{kind}", {})
|
||||
srcs[f"{subject_id}/{zone_id}"] = {
|
||||
"period_id": period_id, "sha256": meta["sha256"],
|
||||
"rev": meta["rev"], "pulled_at": meta["fetched_at"],
|
||||
"reuploaded": meta.get("reuploaded", False),
|
||||
}
|
||||
|
||||
|
||||
def _resolve_period(zone_id: int, period_id: int | None) -> int:
|
||||
if period_id:
|
||||
return period_id
|
||||
lp = fc.latest_period(zone_id)
|
||||
if not lp:
|
||||
raise SystemExit(f"нет периодов для зоны {zone_id}")
|
||||
return lp["id"]
|
||||
|
||||
|
||||
def pull_split_form(subject_id: int, zone_id: int, period_id: int | None = None) -> dict:
|
||||
period_id = _resolve_period(zone_id, period_id)
|
||||
dest_dir = _snap_dir("split_form", subject_id, zone_id, period_id)
|
||||
with tempfile.TemporaryDirectory() as td:
|
||||
tmp = Path(td) / "fgis_split_form.xlsx"
|
||||
res = fc.download_split_form(period_id, zone_id, tmp)
|
||||
meta = ext_state.register_snapshot(
|
||||
dest_dir, tmp, source="fgis_split_form", key=f"{subject_id}/{zone_id}/{period_id}",
|
||||
url=fc.BASE + "/api/EstimatedPrice/BuildingResources/ExportSplitForm",
|
||||
params={"periodId": period_id, "priceZoneId": zone_id})
|
||||
_record_state("split_form", subject_id, zone_id, period_id, meta)
|
||||
return {**meta, "downloaded_size": res["size"]}
|
||||
|
||||
|
||||
def pull_indices(subject_id: int, zone_id: int, period_id: int | None = None) -> dict:
|
||||
period_id = _resolve_period(zone_id, period_id)
|
||||
dest_dir = _snap_dir("indices_gosr", subject_id, zone_id, period_id)
|
||||
with tempfile.TemporaryDirectory() as td:
|
||||
tmp = Path(td) / "fgis_indices_gosr.xlsx"
|
||||
fc.download_indices(period_id, zone_id, tmp)
|
||||
meta = ext_state.register_snapshot(
|
||||
dest_dir, tmp, source="fgis_indices_gosr", key=f"{subject_id}/{zone_id}/{period_id}",
|
||||
url=fc.BASE + "/api/IndicesForResourcesGroups/GenerateCustomReport",
|
||||
params={"periodId": period_id, "priceZoneId": zone_id})
|
||||
_record_state("indices_gosr", subject_id, zone_id, period_id, meta)
|
||||
return meta
|
||||
|
||||
|
||||
def pull_salary(subject_id: int, zone_id: int, period_id: int | None = None) -> dict:
|
||||
period_id = _resolve_period(zone_id, period_id)
|
||||
dest_dir = _snap_dir("salary", subject_id, zone_id, period_id)
|
||||
data = fc.salary_registry(zone_id, period_id)
|
||||
with tempfile.TemporaryDirectory() as td:
|
||||
tmp = Path(td) / "salary_registry.json"
|
||||
tmp.write_text(json.dumps(data, ensure_ascii=False, indent=1), encoding="utf-8")
|
||||
meta = ext_state.register_snapshot(
|
||||
dest_dir, tmp, source="fgis_salary", key=f"{subject_id}/{zone_id}/{period_id}",
|
||||
url=fc.BASE + "/api/EstimatedPrice/RimWorkerSalaryRegistry",
|
||||
params={"priceZoneId": zone_id, "periodId": period_id})
|
||||
_record_state("salary", subject_id, zone_id, period_id, meta)
|
||||
return {**meta, "items": data.get("total")}
|
||||
|
||||
|
||||
def _zones_of(subject_id: int) -> list[int]:
|
||||
return [z["id"] for z in fc.price_zones(subject_id)]
|
||||
|
||||
|
||||
def pull_all_for_subject(subject_id: int, period_id: int | None = None) -> list[dict]:
|
||||
out = []
|
||||
for zone_id in _zones_of(subject_id):
|
||||
out.append(pull_split_form(subject_id, zone_id, period_id))
|
||||
out.append(pull_indices(subject_id, zone_id, period_id))
|
||||
out.append(pull_salary(subject_id, zone_id, period_id))
|
||||
return out
|
||||
|
||||
|
||||
def _regions_from_env(cli_regions: str | None) -> list[int]:
|
||||
raw = cli_regions or os.environ.get("EXT_REGIONS", "")
|
||||
return [int(x) for x in raw.replace(";", ",").split(",") if x.strip().isdigit()]
|
||||
|
||||
|
||||
def main(argv=None) -> int:
|
||||
ap = argparse.ArgumentParser(description="Скачать данные ФГИС ЦС в снапшоты (осознанный шаг).")
|
||||
ap.add_argument("--source", choices=["split_form", "indices", "salary", "all"], required=True)
|
||||
ap.add_argument("--subject", type=int, help="id региона")
|
||||
ap.add_argument("--zone", type=int, help="id ценовой зоны (если не задан — все зоны региона)")
|
||||
ap.add_argument("--period", type=int, help="id периода (по умолчанию последний)")
|
||||
ap.add_argument("--regions", help="id регионов через запятую (или env EXT_REGIONS) для --source all")
|
||||
args = ap.parse_args(argv)
|
||||
|
||||
if not fc.alive():
|
||||
print("ФГИС ЦС недоступен (/api/alive). Прервано.", file=sys.stderr)
|
||||
return 2
|
||||
|
||||
if args.source == "all":
|
||||
subjects = [args.subject] if args.subject else _regions_from_env(args.regions)
|
||||
if not subjects:
|
||||
print("не заданы регионы: --subject, --regions или env EXT_REGIONS", file=sys.stderr)
|
||||
return 2
|
||||
for sid in subjects:
|
||||
for r in pull_all_for_subject(sid, args.period):
|
||||
print(f" ✓ {r['source']} {r['key']} rev={r['rev']} sha={r['sha256'][:12]}"
|
||||
+ (" ⚠ПЕРЕЗАЛИВ" if r.get("reuploaded") else ""))
|
||||
return 0
|
||||
|
||||
if not args.subject:
|
||||
print("--subject обязателен", file=sys.stderr)
|
||||
return 2
|
||||
zones = [args.zone] if args.zone else _zones_of(args.subject)
|
||||
fn = {"split_form": pull_split_form, "indices": pull_indices, "salary": pull_salary}[args.source]
|
||||
for zone_id in zones:
|
||||
r = fn(args.subject, zone_id, args.period)
|
||||
print(f" ✓ {r['source']} {r['key']} rev={r['rev']} sha={r['sha256'][:12]}"
|
||||
+ (" ⚠ПЕРЕЗАЛИВ" if r.get("reuploaded") else ""))
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
Reference in New Issue
Block a user