150 lines
5.6 KiB
Python
150 lines
5.6 KiB
Python
"""Публичный снимок нормативных документов для главной страницы."""
|
|
from __future__ import annotations
|
|
|
|
import html
|
|
import json
|
|
import os
|
|
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
|
|
|
|
|
|
def clear_cache() -> None:
|
|
"""Сброс снимка для тестов и оператора после ручного обновления корпуса."""
|
|
global _cache_until, _cache_value
|
|
_cache_until = 0.0
|
|
_cache_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": []}
|
|
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})
|
|
return {"count": raw["count"], "recent": recent}
|
|
|
|
|
|
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"))})
|
|
|
|
dated = [doc for doc in found if doc["loaded"]]
|
|
dated.sort(key=lambda doc: doc["loaded"][0], reverse=True)
|
|
return {"count": len(found), "recent": dated[:4]}
|
|
|
|
|
|
def export_summary(source: Path, destination: Path) -> None:
|
|
"""Копия метаданных внешнего нормативного корпуса для release-стенда."""
|
|
data = _collect(Path(source))
|
|
exported = {"count": data["count"], "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 snapshot() -> dict:
|
|
"""Снимок на пять минут: не читать сотни файлов на каждый просмотр главной."""
|
|
global _cache_until, _cache_value
|
|
now = time.monotonic()
|
|
if _cache_value is None or now >= _cache_until:
|
|
external = _collect()
|
|
_cache_value = {"count": external["count"] + _literature_count(),
|
|
"recent": external["recent"]}
|
|
_cache_until = now + _CACHE_SECONDS
|
|
return _cache_value
|
|
|
|
|
|
def render() -> str:
|
|
data = snapshot()
|
|
count = data["count"]
|
|
if data["recent"]:
|
|
items = "".join(
|
|
'<li class="public-doc-item">'
|
|
f'<span class="public-doc-title">{html.escape(doc["title"])}</span>'
|
|
f'<span class="public-doc-meta">{html.escape(doc["source"])} · '
|
|
f'<time datetime="{doc["loaded"][0][:10]}">{doc["loaded"][1]}</time></span>'
|
|
"</li>"
|
|
for doc in data["recent"]
|
|
)
|
|
feed = f'<ol class="public-doc-list">{items}</ol>'
|
|
else:
|
|
feed = '<p class="public-doc-empty">Документы пока не загружены.</p>'
|
|
return (
|
|
'<div class="public-doc-stat">'
|
|
f'<strong id="public-doc-count">{count}</strong>'
|
|
'<span>нормативных документов<br>в базе сервиса</span>'
|
|
'</div><div class="public-doc-feed">'
|
|
'<h3>Последние загрузки из внешних источников</h3>'
|
|
f'{feed}</div>'
|
|
)
|