Show coverage of all normative databases on public landing
This commit is contained in:
@@ -2058,3 +2058,14 @@ event loop без `to_thread`.
|
||||
7. Отвергнута привязка по первому запросу: чужой первый вызов мог бы закрепить адрес. Отвергнут `X-Forwarded-For` из приложения: доверие к заголовку должно оставаться у Uvicorn за прокси.
|
||||
8. Вживую: после выката вызвать API с тестовым ключом с правильного и неправильного адресов, сверить HTTP и отсутствие записи расчёта у отказа.
|
||||
9. Независимый сигнал: predeploy gate и HTTP-ответ dev плюс запись ключа в SQLite сверяют применённый SHA и эффект.
|
||||
|
||||
## 2026-12-01 — статистика нормативных баз и серверный предпросмотр
|
||||
|
||||
1. Действие: читать только агрегаты из производных нормативных SQLite-баз, передавать их на изолированный release-стенд и открыть отдельный URL предпросмотра главной через nginx сервера.
|
||||
2. Класс риска: чтение общей боевой нормативной базы, повторяемые запросы главной, правка общего nginx.
|
||||
3. Прогон №1: точные счётчики и публичная лента; №100: пятиминутный кеш исключает сканирование баз на каждый просмотр; №1000: накопления и записи в базу нет, предпросмотр принимает только GET/HEAD.
|
||||
4. Побочку видят посетители главной и оператор nginx. Внешним посетителям доступна лишь публичная главная release-стенда, без проксирования его API, сессий или PDF.
|
||||
5. Проверка читает только фиксированные таблицы в SQLite mode=ro и HTML главной; не меняет базы, не посылает уведомления и не выдаёт содержимое документов.
|
||||
6. Обратимость: откат release до предыдущего SHA; удалить точный location nginx и reload. Радиус nginx — только новый путь предпросмотра в существующем домене.
|
||||
7. Отвергнута публикация всего release-стенда: там копия боевой базы пользователей. Отвергнут туннель на компьютере пользователя: он явно запретил такой подход.
|
||||
8. Вживую: сравнить показатели с SQL на сервере, проверить браузером 360/1280 px и прямой HTTPS URL, попытаться открыть API и получить отказ/боевой маршрут, не release.
|
||||
|
||||
@@ -2,11 +2,11 @@
|
||||
|
||||
## Критерии приёмки
|
||||
|
||||
1. Главная показывает два явно подписанных числа: количество рабочих норм ГЭСН из 47 JSON-сборников и количество нормативных файлов в проектной библиотеке плюс доступных документов ТСН Москвы и писем БИМ.
|
||||
1. Главная показывает отдельные показатели ГЭСН, ФСНБ, ФГИС ЦС, КСР, ТСН Москвы, региональных баз, ФССЦ, БИМ и методической библиотеки. Единицы счёта подписаны; показатели не складываются из-за пересечений и разных типов записей.
|
||||
2. Лента содержит не более четырёх последних документов из внешних источников по времени загрузки, с названием, источником и датой; при пустом корпусе есть честное пустое состояние.
|
||||
3. Сырые HTML и пути к хранилищу не попадают в публичный HTML.
|
||||
4. Блок доступен без входа, адаптивен для 360 px и читаем в светлой и тёмной темах.
|
||||
5. Изолированный release-стенд показывает копию сводки внешних документов и свою копию проектной библиотеки.
|
||||
5. Изолированный release-стенд показывает только агрегаты из внешних SQLite-баз и сводку документов, без копирования самих баз и PDF; ГЭСН и ФССЦ считает из своей копии нормативного проекта.
|
||||
|
||||
## Порядок
|
||||
|
||||
|
||||
+99
-17
@@ -4,6 +4,7 @@ from __future__ import annotations
|
||||
import html
|
||||
import json
|
||||
import os
|
||||
import sqlite3
|
||||
import time
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
@@ -16,6 +17,20 @@ _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:
|
||||
"""Сброс снимка для тестов и оператора после ручного обновления корпуса."""
|
||||
@@ -47,7 +62,7 @@ def _date(value: object) -> tuple[str, str] | None:
|
||||
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": []}
|
||||
return {"count": 0, "recent": [], "document_counts": {}}
|
||||
recent = []
|
||||
source_items = raw.get("recent")
|
||||
for doc in (source_items[:4] if isinstance(source_items, list) else []):
|
||||
@@ -58,7 +73,35 @@ def _read_export(path: Path) -> dict:
|
||||
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}
|
||||
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:
|
||||
@@ -89,13 +132,18 @@ def _collect(root: Path | None = None) -> dict:
|
||||
|
||||
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]}
|
||||
return {"count": len(found), "recent": dated[: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"], "recent": [
|
||||
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"]
|
||||
@@ -116,6 +164,16 @@ def _literature_count() -> int:
|
||||
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
|
||||
@@ -149,8 +207,17 @@ def snapshot() -> dict:
|
||||
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": _norm_count(),
|
||||
"norm_count": metrics["gesn_norms"], "metrics": metrics,
|
||||
"recent": external["recent"]}
|
||||
_cache_until = now + _CACHE_SECONDS
|
||||
return _cache_value
|
||||
@@ -158,10 +225,32 @@ def snapshot() -> dict:
|
||||
|
||||
def render() -> str:
|
||||
data = snapshot()
|
||||
count = data["count"]
|
||||
norm_count = data["norm_count"]
|
||||
norm_text = (f"{norm_count:,}".replace(",", "\u00a0")
|
||||
if norm_count is not None else "—")
|
||||
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(
|
||||
'<li class="public-doc-stat-item">'
|
||||
f'<span class="public-doc-stat-name">{title}</span>'
|
||||
f'<strong id="public-{primary.replace("_", "-")}">{number(primary)}</strong>'
|
||||
f'<span>{label}</span>'
|
||||
+ (f'<small>{number(secondary)} {secondary_label}</small>' if secondary else "")
|
||||
+ '</li>'
|
||||
for title, primary, label, secondary, secondary_label in cards
|
||||
)
|
||||
if data["recent"]:
|
||||
items = "".join(
|
||||
'<li class="public-doc-item">'
|
||||
@@ -175,14 +264,7 @@ def render() -> str:
|
||||
else:
|
||||
feed = '<p class="public-doc-empty">Документы пока не загружены.</p>'
|
||||
return (
|
||||
'<div class="public-doc-stat">'
|
||||
'<div class="public-doc-primary">'
|
||||
f'<strong id="public-norm-count">{norm_text}</strong>'
|
||||
'<span>норм ГЭСН в поисковой базе</span></div>'
|
||||
'<div class="public-doc-secondary">'
|
||||
f'<strong id="public-doc-count">{count}</strong>'
|
||||
'<span>нормативных файлов-источников</span></div>'
|
||||
'</div><div class="public-doc-feed">'
|
||||
f'<ul class="public-doc-stat">{stats}</ul><div class="public-doc-feed">'
|
||||
'<h3>Последние загрузки из внешних источников</h3>'
|
||||
f'{feed}</div>'
|
||||
)
|
||||
|
||||
+14
-9
@@ -114,19 +114,24 @@ button { font-family: inherit; }
|
||||
.shot-caption { position: absolute; left: 1rem; bottom: 0; background: var(--bg-card); border: 1px solid var(--border-light); border-radius: var(--radius); box-shadow: var(--shadow-sm); padding: .35rem .6rem; font-size: .76rem; color: var(--text-muted); }
|
||||
/* Секции */
|
||||
.landing-section { padding: 2rem 0 .6rem; }
|
||||
.public-documents { display: grid; grid-template-columns: minmax(190px, .34fr) 1fr; gap: 1.4rem;
|
||||
.public-documents { display: grid; grid-template-columns: 1fr; gap: 1.1rem;
|
||||
margin: 1.4rem 0 .3rem; padding: 1.4rem; border: 1px solid var(--border-light);
|
||||
border-radius: var(--radius-lg); background: var(--bg-card); box-shadow: var(--shadow-sm); }
|
||||
.public-documents h2 { font-size: 1.13rem; margin-bottom: .35rem; }
|
||||
.public-documents > div:first-child { grid-column: 1 / -1; }
|
||||
.public-documents .section-lead { margin-bottom: 0; font-size: .88rem; }
|
||||
.public-doc-content { display: contents; }
|
||||
.public-doc-stat { align-self: center; display: grid; gap: 1rem; }
|
||||
.public-doc-primary { display: flex; flex-direction: column; gap: .25rem; }
|
||||
.public-doc-primary strong { font-size: clamp(2.4rem, 5vw, 3.8rem); line-height: 1; letter-spacing: -.04em; color: var(--accent); font-variant-numeric: tabular-nums; }
|
||||
.public-doc-stat span { color: var(--text-muted); font-size: .83rem; line-height: 1.35; }
|
||||
.public-doc-secondary { display: flex; align-items: baseline; gap: .45rem; }
|
||||
.public-doc-secondary strong { color: var(--text); font-size: 1.3rem; font-variant-numeric: tabular-nums; }
|
||||
.public-doc-content { display: grid; gap: 1rem; }
|
||||
.public-doc-stat { list-style: none; margin: 0; padding: 0; display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(155px, 1fr)); gap: .5rem; }
|
||||
.public-doc-stat-item { min-width: 0; display: flex; flex-direction: column; gap: .12rem;
|
||||
padding: .8rem; border: 1px solid var(--border-light); border-radius: var(--radius);
|
||||
background: var(--bg); }
|
||||
.public-doc-stat-name { color: var(--text); font-size: .82rem; font-weight: 650; }
|
||||
.public-doc-stat strong { color: var(--accent); font-size: clamp(1.45rem, 2.4vw, 2rem);
|
||||
line-height: 1.12; font-variant-numeric: tabular-nums; overflow-wrap: anywhere; }
|
||||
.public-doc-stat-item > span:not(.public-doc-stat-name), .public-doc-stat-item small {
|
||||
color: var(--text-muted); font-size: .76rem; line-height: 1.3; }
|
||||
.public-doc-stat-item small { margin-top: .2rem; }
|
||||
.public-doc-feed { min-width: 0; }
|
||||
.public-doc-feed h3 { font-size: .9rem; margin-bottom: .45rem; }
|
||||
.public-doc-list { list-style: none; margin: 0; padding: 0; }
|
||||
@@ -583,7 +588,7 @@ html { color-scheme: light; }
|
||||
<section class="public-documents" id="public-documents" aria-labelledby="public-documents-h">
|
||||
<div>
|
||||
<h2 id="public-documents-h">Нормативы в сервисе</h2>
|
||||
<p class="section-lead">Методики и сборники в базе, документы из внешних источников.</p>
|
||||
<p class="section-lead">Расценки, ресурсы и нормативные документы. Показатели разных баз не суммируются.</p>
|
||||
</div>
|
||||
<div class="public-doc-content">{{PUBLIC_DOCUMENTS}}</div>
|
||||
</section>
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
"""Публичная витрина показывает нормативный корпус."""
|
||||
import json
|
||||
import sqlite3
|
||||
import sys
|
||||
from pathlib import Path
|
||||
import pytest
|
||||
@@ -63,7 +64,7 @@ def test_public_markup_escapes_titles_and_has_honest_empty_state(tmp_path, monke
|
||||
public_documents.clear_cache()
|
||||
html = public_documents.render()
|
||||
assert "Документы пока не загружены" in html
|
||||
assert 'id="public-doc-count">0<' in html
|
||||
assert 'id="public-gesn-norms">—<' in html
|
||||
|
||||
_tsn(tmp_path, "xss", '<img src=x onerror=alert(1)>', "2026-11-18T10:00:00Z")
|
||||
public_documents.clear_cache()
|
||||
@@ -71,7 +72,7 @@ def test_public_markup_escapes_titles_and_has_honest_empty_state(tmp_path, monke
|
||||
assert "<img" in html
|
||||
assert "<img" not in html
|
||||
assert str(tmp_path) not in html
|
||||
assert 'id="public-doc-count">1<' in html
|
||||
assert 'id="public-tsn-works">—<' in html
|
||||
|
||||
|
||||
def test_landing_contains_public_documents_section():
|
||||
@@ -92,7 +93,7 @@ def test_homepage_renders_public_feed_without_login(tmp_path, monkeypatch):
|
||||
_tsn(tmp_path, "new", "ТСН: опубликованный", "2026-11-18T10:00:00Z")
|
||||
response = TestClient(main.app).get("/?v=" + main.APP_VERSION)
|
||||
assert response.status_code == 200
|
||||
assert 'id="public-doc-count">1<' in response.text
|
||||
assert 'id="public-gesn-norms"' in response.text
|
||||
assert "ТСН: опубликованный" in response.text
|
||||
assert "{{PUBLIC_DOCUMENTS}}" not in response.text
|
||||
|
||||
@@ -140,5 +141,67 @@ def test_counts_builtin_normative_literature_too(tmp_path, monkeypatch):
|
||||
result = public_documents.snapshot()
|
||||
assert result["count"] == 3
|
||||
assert result["norm_count"] == 2
|
||||
assert 'id="public-norm-count">2<' in public_documents.render()
|
||||
assert 'id="public-gesn-norms">2<' in public_documents.render()
|
||||
assert [doc["title"] for doc in result["recent"]] == ["ТСН"]
|
||||
|
||||
|
||||
def test_all_normative_databases_have_separate_counters(tmp_path, monkeypatch):
|
||||
import ext_state
|
||||
import public_documents
|
||||
|
||||
ext = tmp_path / "ext"
|
||||
specs = {
|
||||
"fsnb/fsnb_ref.sqlite": {"works": 3, "resources": 5},
|
||||
"fgis_ref/fgis_ref.sqlite": {"items": 7, "ksr": 11,
|
||||
"zone_snapshots": 2},
|
||||
"tsn/tsn_ref.sqlite": {"works": 13, "price_items": 17},
|
||||
"regional_ref/regional_ref.sqlite": {"works": 19, "prices": 23},
|
||||
}
|
||||
for relative, tables in specs.items():
|
||||
path = ext / "derived" / relative
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
with sqlite3.connect(path) as con:
|
||||
for table, count in tables.items():
|
||||
if table == "zone_snapshots":
|
||||
con.execute("CREATE TABLE zone_snapshots (rows_loaded INTEGER)")
|
||||
con.executemany("INSERT INTO zone_snapshots VALUES (?)", [(31,), (37,)])
|
||||
else:
|
||||
con.execute(f"CREATE TABLE {table} (id INTEGER)")
|
||||
con.executemany(f"INSERT INTO {table} VALUES (?)",
|
||||
[(n,) for n in range(count)])
|
||||
monkeypatch.setattr(ext_state, "ext_dir", lambda: ext)
|
||||
result = public_documents.snapshot()
|
||||
assert result["metrics"] == {
|
||||
"fsnb_works": 3, "fsnb_resources": 5,
|
||||
"fgis_items": 7, "ksr": 11, "fgis_price_rows": 68,
|
||||
"tsn_works": 13, "tsn_prices": 17,
|
||||
"regional_works": 19, "regional_prices": 23,
|
||||
"bim_letters": None, "tsn_documents": None,
|
||||
"gesn_norms": None, "fssc_regions": None,
|
||||
"literature_files": None,
|
||||
}
|
||||
markup = public_documents.render()
|
||||
assert "ФСНБ" in markup and "ФГИС ЦС" in markup
|
||||
assert "ТСН Москвы" in markup and "Региональные базы" in markup
|
||||
assert "КСР" in markup and "ГЭСН" in markup
|
||||
assert "ФССЦ" in markup and "БИМ" in markup
|
||||
assert "нормативных файлов-источников" not in markup
|
||||
|
||||
|
||||
def test_export_preserves_database_counters_without_copying_databases(tmp_path, monkeypatch):
|
||||
import ext_state
|
||||
import public_documents
|
||||
|
||||
source = tmp_path / "source"
|
||||
db = source / "derived" / "fsnb" / "fsnb_ref.sqlite"
|
||||
db.parent.mkdir(parents=True)
|
||||
with sqlite3.connect(db) as con:
|
||||
con.execute("CREATE TABLE works (id INTEGER)")
|
||||
con.execute("CREATE TABLE resources (id INTEGER)")
|
||||
con.execute("INSERT INTO works VALUES (1)")
|
||||
stage = tmp_path / "stage"
|
||||
public_documents.export_summary(source, stage / "landing_documents.json")
|
||||
monkeypatch.setattr(ext_state, "ext_dir", lambda: stage)
|
||||
public_documents.clear_cache()
|
||||
assert public_documents.snapshot()["metrics"]["fsnb_works"] == 1
|
||||
assert not (stage / "derived").exists()
|
||||
|
||||
Reference in New Issue
Block a user