feat(ext): Фаза 4/5 — охват всех источников/документов + все регионы

fgis_client: opendata_list/meta/download (15 датасетов: КСР/ФСНБ/СПСРП/оплата труда/9 ПССР),
bim_leaf_docs (дерево писем-индексов), download_by_guid, all_subject_ids. xsd_client: скрейп
.zip-схем экспертизы (html.parser, fail-loud на 0 ссылок). ext_pull: pull_opendata/bim/xsd,
--source opendata/bim/xsd/all-sources, --regions all (все 86). ext_check: check_opendata
(lastChangeDate)/check_bim(guid)/check_xsd(ссылки) + режим all-regions — чекер мониторит ВСЁ.
10 новых тестов.
This commit is contained in:
anor
2026-07-18 10:04:17 +10:00
parent 8aef1a1f42
commit c5e210c918
6 changed files with 405 additions and 15 deletions
+107 -13
View File
@@ -113,10 +113,70 @@ def pull_salary(subject_id: int, zone_id: int, period_id: int | None = None) ->
return {**meta, "items": data.get("total")}
def pull_opendata(dataset_id: int) -> dict:
"""Скачать текущий файл датасета открытых данных (КСР/ФСНБ/СПСРП/оплата труда/ПССР)."""
dest_dir = ext_state.ext_dir() / "snapshots/fgis/opendata" / str(dataset_id)
with tempfile.TemporaryDirectory() as td:
tmp = Path(td) / "download.bin"
_res, name = fc.download_opendata(dataset_id, tmp)
named = Path(td) / (Path(name).name or f"dataset_{dataset_id}")
tmp.replace(named)
meta = ext_state.register_snapshot(
dest_dir, named, source="fgis_opendata", key=f"opendata/{dataset_id}",
url=fc.BASE + f"/api/OpenData/{dataset_id}")
return {**meta, "dataset_id": dataset_id}
def pull_all_opendata() -> list[dict]:
out = []
for ds in fc.opendata_list():
out.append(pull_opendata(ds["id"]))
time.sleep(POLITE_PAUSE_S)
return out
def pull_bim() -> list[dict]:
"""Скачать все письма-индексы (БИМ) — листовые документы дерева NormLegalDocPublished."""
out = []
docs = fc.bim_leaf_docs()
for d in docs:
dest_dir = ext_state.ext_dir() / "snapshots/fgis/bim_letters" / d["guid"]
with tempfile.TemporaryDirectory() as td:
tmp = Path(td) / (Path(str(d.get("filePath") or "letter")).name or "letter.pdf")
fc.download_by_guid(d["guid"], tmp, expect_min_size=500)
meta = ext_state.register_snapshot(
dest_dir, tmp, source="fgis_bim", key=f"bim/{d['guid']}",
url=fc.BASE + f"/api/values/GetFileContent/{d['guid']}")
out.append({**meta, "letter": d.get("name")})
time.sleep(POLITE_PAUSE_S)
return out
def pull_xsd() -> list[dict]:
"""Скачать все .zip-пакеты XSD-схем экспертизы со страницы Минстроя."""
import xsd_client
out = []
for href in xsd_client.schema_links():
fname = xsd_client._fname(href)
dest_dir = ext_state.ext_dir() / "snapshots/xsd" / fname
with tempfile.TemporaryDirectory() as td:
tmp = Path(td) / fname
xsd_client.download_schema(href, tmp)
meta = ext_state.register_snapshot(
dest_dir, tmp, source="xsd_schema", key=f"xsd/{fname}", url=href)
out.append(meta)
time.sleep(POLITE_PAUSE_S)
return out
def _zones_of(subject_id: int) -> list[int]:
return [z["id"] for z in fc.price_zones(subject_id)]
def all_subject_ids() -> list[int]:
return [s["id"] for s in fc.country_subjects()]
def pull_all_for_subject(subject_id: int, period_id: int | None = None) -> list[dict]:
out = []
for zone_id in _zones_of(subject_id):
@@ -130,33 +190,69 @@ def pull_all_for_subject(subject_id: int, period_id: int | None = None) -> list[
def _regions_from_env(cli_regions: str | None) -> list[int]:
raw = cli_regions or os.environ.get("EXT_REGIONS", "")
raw = (cli_regions or os.environ.get("EXT_REGIONS", "")).strip()
if raw.lower() == "all":
return all_subject_ids()
return [int(x) for x in raw.replace(";", ",").split(",") if x.strip().isdigit()]
def _p(r: dict) -> None:
print(f" ✓ {r['source']} {r['key']} rev={r['rev']} sha={r['sha256'][:12]}"
+ (" ⚠ПЕРЕЗАЛИВ" if r.get("reuploaded") else ""))
def main(argv=None) -> int:
ap = argparse.ArgumentParser(description="Скачать данные ФГИС ЦС в снапшоты (осознанный шаг).")
ap.add_argument("--source", choices=["split_form", "indices", "salary", "all"], required=True)
ap = argparse.ArgumentParser(description="Скачать данные ФГИС/схемы в снапшоты (осознанный шаг).")
ap.add_argument("--source", required=True, choices=[
"split_form", "indices", "salary", "all", # цены ФГИС по региону
"opendata", "bim", "xsd", "all-sources"]) # справочники/письма/схемы
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")
ap.add_argument("--dataset", type=int, help="id датасета для --source opendata (иначе все)")
ap.add_argument("--regions", help="id регионов через запятую, или 'all', или env EXT_REGIONS")
args = ap.parse_args(argv)
if not fc.alive():
# источники без региона (opendata/bim/xsd) — не требуют ФГИС-alive-пречека кроме ФГИС-овских
if args.source in ("opendata", "bim", "all-sources") and not fc.alive():
print("ФГИС ЦС недоступен (/api/alive). Прервано.", file=sys.stderr)
return 2
if args.source == "opendata":
for r in ([pull_opendata(args.dataset)] if args.dataset else pull_all_opendata()):
_p(r)
return 0
if args.source == "bim":
for r in pull_bim():
_p(r)
return 0
if args.source == "xsd":
for r in pull_xsd():
_p(r)
return 0
if args.source == "all-sources":
for r in pull_all_opendata() + pull_bim() + pull_xsd():
_p(r)
return 0
# ФГИС по регионам (цены/индексы/оплата)
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)
print("не заданы регионы: --subject, --regions=all или env EXT_REGIONS", file=sys.stderr)
return 2
failed = 0
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
try:
for r in pull_all_for_subject(sid, args.period):
_p(r)
except Exception as e: # noqa: BLE001 — один регион не валит остальные
failed += 1
print(f" ✗ регион {sid}: {type(e).__name__}: {e}", file=sys.stderr)
return 1 if failed else 0
if not args.subject:
print("--subject обязателен", file=sys.stderr)
@@ -164,9 +260,7 @@ def main(argv=None) -> int:
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 ""))
_p(fn(args.subject, zone_id, args.period))
return 0