"""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 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