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 новых тестов.
190 lines
9.3 KiB
Python
190 lines
9.3 KiB
Python
"""fgis_client — клиент справочной иерархии ФГИС ЦС (срез 1.1).
|
|
|
|
ФГИС ЦС — недокументированный, но открытый REST (проверено живыми запросами 2026-07):
|
|
/api/alive → 200 (пре-чек живости)
|
|
/api/EstimatedPrice/CountrySubjects → [{id, name}] (регионы)
|
|
/api/EstimatedPrice/PriceZones?subjectId= → [{id, name}] (ценовые зоны региона)
|
|
/api/EstimatedPrice/Periods?priceZoneId= → [{id, name}] (кварталы, id↑ = свежее)
|
|
|
|
Форма каждого ответа ВАЛИДИРУЕТСЯ: если ФГИС молча сменит схему JSON — получим явную
|
|
FgisFormatError («источник изменил формат»), а не тихую чушь вниз по конвейеру.
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
import os
|
|
|
|
import httpx
|
|
|
|
import ext_fetch
|
|
|
|
BASE = os.environ.get("FGIS_BASE", "https://fgiscs.minstroyrf.ru")
|
|
|
|
|
|
class FgisFormatError(ext_fetch.FetchError):
|
|
"""Ответ пришёл, но структура не та, что ждём (API изменился)."""
|
|
|
|
|
|
def _id_name_list(data, ctx: str) -> list[dict]:
|
|
if not isinstance(data, list):
|
|
raise FgisFormatError(f"{ctx}: ждали список, пришло {type(data).__name__}")
|
|
for it in data:
|
|
if not (isinstance(it, dict) and "id" in it and "name" in it):
|
|
raise FgisFormatError(f"{ctx}: элемент без id/name: {str(it)[:80]}")
|
|
return data
|
|
|
|
|
|
def alive(client: httpx.Client | None = None) -> bool:
|
|
"""GET /api/alive → 200. Пре-чек перед операциями: лежит → доклад «источник
|
|
недоступен», а не каскад ошибок. Тело пустое, JSON не парсим."""
|
|
c = client or ext_fetch.make_client()
|
|
try:
|
|
r = c.get(f"{BASE}/api/alive")
|
|
return r.status_code == 200
|
|
except httpx.HTTPError:
|
|
return False
|
|
finally:
|
|
if client is None:
|
|
c.close()
|
|
|
|
|
|
def country_subjects(client: httpx.Client | None = None) -> list[dict]:
|
|
data = ext_fetch.fetch_json(f"{BASE}/api/EstimatedPrice/CountrySubjects", client=client)
|
|
return _id_name_list(data, "CountrySubjects")
|
|
|
|
|
|
def price_zones(subject_id: int, client: httpx.Client | None = None) -> list[dict]:
|
|
data = ext_fetch.fetch_json(f"{BASE}/api/EstimatedPrice/PriceZones",
|
|
params={"subjectId": subject_id}, client=client)
|
|
return _id_name_list(data, "PriceZones")
|
|
|
|
|
|
def periods(price_zone_id: int, client: httpx.Client | None = None) -> list[dict]:
|
|
data = ext_fetch.fetch_json(f"{BASE}/api/EstimatedPrice/Periods",
|
|
params={"priceZoneId": price_zone_id}, client=client)
|
|
return _id_name_list(data, "Periods")
|
|
|
|
|
|
def latest_period(price_zone_id: int, client: httpx.Client | None = None) -> dict | None:
|
|
"""Самый свежий период зоны (наибольший id). None если периодов нет."""
|
|
ps = periods(price_zone_id, client=client)
|
|
return max(ps, key=lambda p: p["id"]) if ps else None
|
|
|
|
|
|
def subject_id_by_name(name_substr: str, client: httpx.Client | None = None) -> int | None:
|
|
"""Найти id региона по подстроке имени (для конфигурации EXT_REGIONS по-человечески)."""
|
|
for s in country_subjects(client=client):
|
|
if name_substr.lower() in s["name"].lower():
|
|
return s["id"]
|
|
return None
|
|
|
|
|
|
# --- Выгрузки (проверено на сервере 2026-07: content-type spreadsheet, размеры реальны) ---
|
|
_SPREADSHEET = "spreadsheet" # часть application/vnd.openxmlformats-...spreadsheetml.sheet
|
|
|
|
|
|
def download_split_form(period_id: int, price_zone_id: int, dest, client=None) -> dict:
|
|
"""Сплит-форма: полный каталог текущих цен ресурсов зоны за квартал (~13.7 МБ xlsx).
|
|
Это то, чем питается движок (fgis_split_form.xlsx)."""
|
|
return ext_fetch.fetch_file(
|
|
f"{BASE}/api/EstimatedPrice/BuildingResources/ExportSplitForm", dest,
|
|
params={"periodId": period_id, "priceZoneId": price_zone_id},
|
|
expect_min_size=1_000_000, expected_content_type=_SPREADSHEET, client=client)
|
|
|
|
|
|
def download_indices(period_id: int, price_zone_id: int, dest, client=None) -> dict:
|
|
"""Индексы к группам однородных ресурсов (ГОСР) зоны за квартал (~2.2 МБ xlsx, РИМ)."""
|
|
return ext_fetch.fetch_file(
|
|
f"{BASE}/api/IndicesForResourcesGroups/GenerateCustomReport", dest,
|
|
params={"periodId": period_id, "priceZoneId": price_zone_id, "authorityId": "null"},
|
|
expect_min_size=50_000, expected_content_type=_SPREADSHEET, client=client)
|
|
|
|
|
|
def download_by_guid(guid: str, dest, client=None, expect_min_size: int = 100) -> dict:
|
|
"""Скачать файл ФГИС по guid (общий механизм: /api/values/GetFileContent/{guid})."""
|
|
return ext_fetch.fetch_file(f"{BASE}/api/values/GetFileContent/{guid}", dest,
|
|
expect_min_size=expect_min_size, client=client)
|
|
|
|
|
|
# --- Открытые данные (15 датасетов: КСР, ФСНБ-2020/2022, СПСРП, оплата труда, 9 ПССР) ---
|
|
|
|
def opendata_list(client=None) -> list[dict]:
|
|
"""Список датасетов: [{id, datasetName, lastChangeDate, ...}]. Ответ {total, items}."""
|
|
data = ext_fetch.fetch_json(f"{BASE}/api/OpenData", client=client)
|
|
items = data.get("items") if isinstance(data, dict) else data
|
|
if not isinstance(items, list):
|
|
raise FgisFormatError("OpenData: нет списка items")
|
|
for it in items:
|
|
if not (isinstance(it, dict) and "id" in it and "lastChangeDate" in it):
|
|
raise FgisFormatError(f"OpenData: элемент без id/lastChangeDate: {str(it)[:80]}")
|
|
return items
|
|
|
|
|
|
def opendata_meta(dataset_id: int, client=None) -> dict:
|
|
"""Метаданные датасета: datasetName, lastChangeDate, datasetFile:{path,name}, ..."""
|
|
data = ext_fetch.fetch_json(f"{BASE}/api/OpenData/{dataset_id}", client=client)
|
|
if not (isinstance(data, dict) and isinstance(data.get("datasetFile"), dict)):
|
|
raise FgisFormatError(f"OpenData/{dataset_id}: нет datasetFile")
|
|
return data
|
|
|
|
|
|
def download_opendata(dataset_id: int, dest, client=None) -> tuple[dict, str]:
|
|
"""Скачать текущий файл датасета. Возвращает (fetch-результат, имя файла)."""
|
|
meta = opendata_meta(dataset_id, client=client)
|
|
df = meta["datasetFile"]
|
|
guid, name = df.get("path"), df.get("name") or f"dataset_{dataset_id}"
|
|
if not guid:
|
|
raise FgisFormatError(f"OpenData/{dataset_id}: пустой datasetFile.path")
|
|
return download_by_guid(guid, dest, client=client), name
|
|
|
|
|
|
# --- БИМ-письма (индексы изменения сметной стоимости): дерево NormLegalDocPublished ---
|
|
|
|
def _norm_tree(parent_guid: str | None, client=None) -> list[dict]:
|
|
params = {"normLegalDocPublishedType": 10, "state": 20, "normLegalDocBaseKind": 40}
|
|
if parent_guid:
|
|
params["parentGuid"] = parent_guid
|
|
data = ext_fetch.fetch_json(f"{BASE}/api/NormLegalDocPublished", params=params, client=client)
|
|
# Ответ вида {"": [ ... ]} или список — берём значения.
|
|
if isinstance(data, dict):
|
|
nodes = []
|
|
for v in data.values():
|
|
if isinstance(v, list):
|
|
nodes.extend(v)
|
|
return nodes
|
|
return data if isinstance(data, list) else []
|
|
|
|
|
|
def bim_leaf_docs(max_nodes: int = 4000, client=None) -> list[dict]:
|
|
"""Все листовые документы дерева БИМ-писем (у листа есть filePath). Обход по parentGuid
|
|
с потолком узлов (защита от зацикливания при дрейфе схемы)."""
|
|
out: list[dict] = []
|
|
stack = [None]
|
|
seen: set[str] = set()
|
|
visited = 0
|
|
while stack and visited < max_nodes:
|
|
pg = stack.pop()
|
|
for node in _norm_tree(pg, client=client):
|
|
visited += 1
|
|
g = node.get("guid")
|
|
if not g or g in seen:
|
|
continue
|
|
seen.add(g)
|
|
if node.get("filePath"): # лист-документ
|
|
out.append({"guid": g, "name": node.get("name"), "date": node.get("date"),
|
|
"number": node.get("number"), "filePath": node.get("filePath")})
|
|
else: # папка (год/квартал) — углубляемся
|
|
stack.append(g)
|
|
if visited >= max_nodes:
|
|
break
|
|
return out
|
|
|
|
|
|
def salary_registry(price_zone_id: int, period_id: int, client=None) -> dict:
|
|
"""Реестр оплаты труда рабочих по разрядам (JSON: {total, items:[...]})."""
|
|
data = ext_fetch.fetch_json(f"{BASE}/api/EstimatedPrice/RimWorkerSalaryRegistry",
|
|
params={"priceZoneId": price_zone_id, "periodId": period_id},
|
|
client=client)
|
|
if not (isinstance(data, dict) and "items" in data):
|
|
raise FgisFormatError("RimWorkerSalaryRegistry: нет ключа items")
|
|
return data
|