feat(1.4): /api/data-version — свежесть корпусной базы цен из данных + индикатор в UI

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
anor
2026-06-10 17:13:10 +10:00
co-authored by Claude Fable 5
parent 0619c53de9
commit 4ce2c060b0
2 changed files with 49 additions and 1 deletions
+42
View File
@@ -1,7 +1,9 @@
"""smeta-web: AI assistant for estimators — FastAPI + Claude Code or GLM-5."""
import asyncio
import json
import os
import re
import shutil
import time
from pathlib import Path
@@ -310,6 +312,46 @@ async def version():
return {"version": APP_VERSION}
# Свежесть корпусной базы цен — чтобы сметчик видел, на какой период данные.
# Берём реальный ценовой период ИЗ данных (а не mtime файла: после git clone
# mtime = дата клонирования и врёт). Кэшируем — файлы корпуса по 5–12 МБ.
_DATA_PERIODS_CACHE = None
def _compute_data_periods():
base = Path(__file__).resolve().parent / "data" / "real_corpus"
rx = re.compile(r"(20[12]\d) ?Q([1-4])") # 2010–2029, отсекаем мусор вроде «2052 Q1»
srcs = [
("Корпус смет (расценки/цены)", "estimates_index.json"),
("База материалов (КА)", "ka_index.json"),
("База работ (ВОР)", "vor_index.json"),
]
result = []
for label, fn in srcs:
period = None
try:
txt = (base / fn).read_text(encoding="utf-8")
ms = rx.findall(txt)
if ms:
y, q = max(ms, key=lambda yq: (int(yq[0]), int(yq[1])))
period = f"{y} Q{q}"
except OSError:
pass
result.append({"label": label, "period": period})
return result
@app.get("/api/data-version")
async def data_version():
"""Public — на какой ценовой период актуальна корпусная база (свежесть данных)."""
global _DATA_PERIODS_CACHE
if _DATA_PERIODS_CACHE is None:
_DATA_PERIODS_CACHE = await asyncio.to_thread(_compute_data_periods)
periods = [s["period"] for s in _DATA_PERIODS_CACHE if s["period"]]
newest = max(periods, key=lambda s: (int(s[:4]), int(s[-1]))) if periods else None
return {"newest_period": newest, "sources": _DATA_PERIODS_CACHE, "app_version": APP_VERSION}
# Resumable uploads (tus 1.0.0). Same-process, reuses auth + per-user work dir;
# the finished file lands in the work dir exactly like legacy /api/upload.
TUS_MAX_SIZE = 3 * 1024 * 1024 * 1024 # 3 GB
+7 -1
View File
@@ -262,7 +262,7 @@ html { color-scheme: light; }
</div>
</div>
<input type="file" id="file-input" multiple hidden onchange="handleFiles(this.files)">
<div style="text-align:center;margin-top:4px"><a href="/static/security.html" target="_blank" style="font-size:.65rem;color:var(--text-muted);opacity:.4;text-decoration:none">О безопасности сервиса</a><span class="app-version" style="font-size:.65rem;color:var(--text-muted);opacity:.4;margin-left:.6rem"></span></div>
<div style="text-align:center;margin-top:4px"><a href="/static/security.html" target="_blank" style="font-size:.65rem;color:var(--text-muted);opacity:.4;text-decoration:none">О безопасности сервиса</a><span class="app-version" style="font-size:.65rem;color:var(--text-muted);opacity:.4;margin-left:.6rem"></span><span class="data-version" title="Период, на который актуальны цены корпусной базы" style="font-size:.65rem;color:var(--text-muted);opacity:.4;margin-left:.6rem"></span></div>
</div>
</div><!-- /.main-col -->
</div><!-- /.app-layout -->
@@ -295,6 +295,12 @@ fetch('/api/version').then(function (r) { return r.json(); }).then(function (d)
document.querySelectorAll('.app-version').forEach(function (el) { el.textContent = 'v.' + d.version; });
}).catch(function () {});
// Индикатор свежести данных: на какой ценовой период актуальна корпусная база.
fetch('/api/data-version').then(function (r) { return r.json(); }).then(function (d) {
if (!d.newest_period) return;
document.querySelectorAll('.data-version').forEach(function (el) { el.textContent = 'цены: ' + d.newest_period; });
}).catch(function () {});
function renderMarkdown(text) {
// Санитайзим вывод модели перед innerHTML: вырезаем onerror/onclick/javascript:
// и прочие XSS-векторы, сохраняя таблицы/ссылки/форматирование. Требуем оба