"""Публичный снимок нормативных документов для главной страницы.""" from __future__ import annotations import html import json import os import sqlite3 import time from datetime import datetime from pathlib import Path import ext_state _CACHE_SECONDS = 300 _cache_until = 0.0 _cache_value: dict | None = None _norm_sig: tuple | None = None _norm_value: int | None = None # Метрики относятся к разным сущностям; их нельзя складывать в «число документов». _DB_METRICS = { "fsnb/fsnb_ref.sqlite": {"fsnb_works": "SELECT COUNT(*) FROM works", "fsnb_resources": "SELECT COUNT(*) FROM resources"}, "fgis_ref/fgis_ref.sqlite": {"fgis_items": "SELECT COUNT(*) FROM items", "ksr": "SELECT COUNT(*) FROM ksr", "fgis_price_rows": "SELECT COALESCE(SUM(rows_loaded), 0) FROM zone_snapshots"}, "tsn/tsn_ref.sqlite": {"tsn_works": "SELECT COUNT(*) FROM works", "tsn_prices": "SELECT COUNT(*) FROM price_items"}, "regional_ref/regional_ref.sqlite": {"regional_works": "SELECT COUNT(*) FROM works", "regional_prices": "SELECT COUNT(*) FROM prices"}, } _DB_KEYS = tuple(key for queries in _DB_METRICS.values() for key in queries) def clear_cache() -> None: """Сброс снимка для тестов и оператора после ручного обновления корпуса.""" global _cache_until, _cache_value, _norm_sig, _norm_value _cache_until = 0.0 _cache_value = None _norm_sig = None _norm_value = None def _read_meta(path: Path) -> dict | None: try: value = json.loads(path.read_text(encoding="utf-8")) return value if isinstance(value, dict) else None except (OSError, ValueError): return None def _date(value: object) -> tuple[str, str] | None: if not isinstance(value, str): return None try: d = datetime.fromisoformat(value.replace("Z", "+00:00")) except ValueError: return None return (d.isoformat(), d.strftime("%d.%m.%Y")) def _read_export(path: Path) -> dict: raw = _read_meta(path) if not raw or not isinstance(raw.get("count"), int) or raw["count"] < 0: return {"count": 0, "recent": [], "document_counts": {}} recent = [] source_items = raw.get("recent") for doc in (source_items[:4] if isinstance(source_items, list) else []): if not isinstance(doc, dict): continue title, source = doc.get("title"), doc.get("source") loaded = _date(doc.get("fetched_at")) if (isinstance(title, str) and title.strip() and source in ("ТСН Москвы", "ФГИС ЦС") and loaded): recent.append({"title": title, "source": source, "loaded": loaded}) counts = raw.get("document_counts") counts = counts if isinstance(counts, dict) else {} return {"count": raw["count"], "recent": recent, "document_counts": {key: counts[key] for key in ("bim_letters", "tsn_documents") if type(counts.get(key)) is int and counts[key] >= 0}} def _external_metrics(root: Path) -> dict[str, int | None]: """Только чтение фиксированных таблиц; на стенде — экспортированные агрегаты.""" export = _read_meta(root / "landing_documents.json") or {} saved = export.get("metrics") saved = saved if isinstance(saved, dict) else {} values: dict[str, int | None] = { key: saved[key] if type(saved.get(key)) is int and saved[key] >= 0 else None for key in _DB_KEYS } for relative, queries in _DB_METRICS.items(): db = root / "derived" / relative if not db.is_file(): continue try: with sqlite3.connect(db.as_uri() + "?mode=ro", uri=True, timeout=1) as con: for key, query in queries.items(): result = con.execute(query).fetchone()[0] values[key] = result if type(result) is int and result >= 0 else None except sqlite3.Error: for key in queries: values[key] = None return values def _collect(root: Path | None = None) -> dict: root = root if root is not None else ext_state.ext_dir() base = root / "snapshots" if not (base / "niac_tsn").is_dir() and not (base / "fgis" / "bim_letters").is_dir(): return _read_export(root / "landing_documents.json") found = [] tsn = base / "niac_tsn" for path in tsn.glob("*/*/meta.json"): if not (path.parent / "extract.json").is_file(): continue meta = _read_meta(path) if not meta or not isinstance(meta.get("title"), str) or not meta["title"].strip(): continue found.append({"title": meta["title"].strip(), "source": "ТСН Москвы", "loaded": _date(meta.get("fetched_at"))}) bim = base / "fgis" / "bim_letters" for path in bim.glob("*/meta.json"): if not (path.parent / "letter.pdf").is_file(): continue meta = _read_meta(path) if not meta or meta.get("source") != "fgis_bim": continue found.append({"title": "Письмо-индекс Минстроя", "source": "ФГИС ЦС", "loaded": _date(meta.get("fetched_at"))}) # Одна пакетная загрузка может содержать сотни документов с соседними # fetched_at. Показываем событие обновления корпуса, а не четыре строки # одного и того же пакета. batches: dict[tuple[str, str], dict] = {} for doc in found: if not doc["loaded"]: continue key = (doc["source"], doc["loaded"][0][:10]) batch = batches.setdefault(key, {"source": doc["source"], "loaded": doc["loaded"], "count": 0}) batch["count"] += 1 if doc["loaded"][0] > batch["loaded"][0]: batch["loaded"] = doc["loaded"] recent = [] for batch in batches.values(): kind = "документов ТСН Москвы" if batch["source"] == "ТСН Москвы" else "писем-индексов Минстроя" recent.append({"title": f"Обновлено {kind}: {batch['count']}", "source": batch["source"], "loaded": batch["loaded"]}) recent.sort(key=lambda doc: doc["loaded"][0], reverse=True) return {"count": len(found), "recent": recent[:4], "document_counts": { "tsn_documents": sum(doc["source"] == "ТСН Москвы" for doc in found), "bim_letters": sum(doc["source"] == "ФГИС ЦС" for doc in found)}} def export_summary(source: Path, destination: Path) -> None: """Копия метаданных внешнего нормативного корпуса для release-стенда.""" data = _collect(Path(source)) exported = {"count": data["count"], "document_counts": data.get("document_counts", {}), "metrics": _external_metrics(Path(source)), "recent": [ {"title": doc["title"], "source": doc["source"], "fetched_at": doc["loaded"][0]} for doc in data["recent"] ]} ext_state._atomic_write_text(Path(destination), json.dumps(exported, ensure_ascii=False)) def _literature_count() -> int: project = os.environ.get("SMETA_PROJECT_DIR") if not project: return 0 root = Path(project) / "literature" if not root.is_dir(): return 0 return sum(1 for path in root.rglob("*") if path.is_file() and not path.is_symlink() and path.suffix.lower() in {".pdf", ".doc", ".docx", ".htm", ".html"}) def _fssc_count() -> int | None: project = os.environ.get("SMETA_PROJECT_DIR") if not project: return None root = Path(project) / "data" / "fssc_2022" if not root.is_dir(): return None return sum(path.is_file() for path in root.glob("region_*.json")) def _norm_count() -> int | None: """Число рабочих норм ГЭСН; повторно парсим JSON только при смене файлов.""" global _norm_sig, _norm_value project = os.environ.get("SMETA_PROJECT_DIR") if not project: return None files = sorted((Path(project) / "data" / "gesn_extra").glob("gesn_*.json")) if not files: return None try: sig = tuple((str(path), path.stat().st_mtime_ns, path.stat().st_size) for path in files) if sig == _norm_sig: return _norm_value total = 0 for path in files: data = json.loads(path.read_text(encoding="utf-8")) if not isinstance(data, dict): return None total += sum(isinstance(item, dict) and "error" not in item for item in data.values()) except (OSError, ValueError): return None _norm_sig, _norm_value = sig, total return total def snapshot() -> dict: """Снимок на пять минут: не читать сотни файлов на каждый просмотр главной.""" global _cache_until, _cache_value now = time.monotonic() if _cache_value is None or now >= _cache_until: external = _collect() project = os.environ.get("SMETA_PROJECT_DIR") literature_root = Path(project) / "literature" if project else None literature = _literature_count() if literature_root and literature_root.is_dir() else None db_metrics = _external_metrics(ext_state.ext_dir()) metrics = {**db_metrics, "gesn_norms": _norm_count(), "fssc_regions": _fssc_count(), "literature_files": literature, "bim_letters": external.get("document_counts", {}).get("bim_letters"), "tsn_documents": external.get("document_counts", {}).get("tsn_documents")} _cache_value = {"count": external["count"] + _literature_count(), "norm_count": metrics["gesn_norms"], "metrics": metrics, "recent": external["recent"]} _cache_until = now + _CACHE_SECONDS return _cache_value def render() -> str: data = snapshot() metrics = data["metrics"] def number(key: str) -> str: value = metrics.get(key) return f"{value:,}".replace(",", "\u00a0") if value is not None else "—" cards = ( ("ГЭСН", "gesn_norms", "норм", None, None), ("ФСНБ", "fsnb_works", "расценок", "fsnb_resources", "ресурсов"), ("ФГИС ЦС", "fgis_items", "ресурсов", "fgis_price_rows", "ценовых записей по зонам и периодам"), ("КСР", "ksr", "позиций классификатора", None, None), ("ТСН Москвы", "tsn_works", "расценок", "tsn_prices", "ценовых позиций"), ("Региональные базы", "regional_works", "расценок", "regional_prices", "цен"), ("ФССЦ", "fssc_regions", "региональных сборников", None, None), ("БИМ", "bim_letters", "писем с индексами", None, None), ("Методические документы", "literature_files", "файлов в библиотеке", None, None), ) stats = "".join( '
  • ' f'{title}' f'{number(primary)}' f'{label}' + (f'{number(secondary)} {secondary_label}' if secondary else "") + '
  • ' for title, primary, label, secondary, secondary_label in cards ) if data["recent"]: items = "".join( '
  • ' f'{html.escape(doc["title"])} ' f'{html.escape(doc["source"])} · ' f'' "
  • " for doc in data["recent"] ) feed = f'
      {items}
    ' else: feed = '

    Документы пока не загружены.

    ' return ( f'
    ' '

    Последние обновления

    ' f'{feed}
    ' )