feat(ui/core): срез 6.2 — правка сметы → пересчёт ДВИЖКОМ (не JS)

Объёмы в панели редактируемы (input); «Пересчитать движком» → POST /api/recalc →
estimate_contract.calc_estimate в threadpool (не блокирует сервер) → новая панель с
детерминир. пересчётом. JS не считает — только движок. Браузер-verified (100→250 → итог
пересчитан). APP_VERSION 2026-07-17r.
This commit is contained in:
anor
2026-07-17 23:57:23 +10:00
parent 281bf411e4
commit 04cb1a5c74
3 changed files with 82 additions and 4 deletions
+30 -1
View File
@@ -138,7 +138,7 @@ MAX_MESSAGE_LEN = 10_000
# ⚠️ Версия UI — единый источник. БАМПАТЬ ПРИ КАЖДОМ ДЕПЛОЕ (формат: YYYY-MM-DD + буква).
# Фронт берёт её через GET /api/version (chat.html + admin.html, элемент .app-version).
APP_VERSION = "2026-07-17q"
APP_VERSION = "2026-07-17r"
# Audit: path → action name mapping
_AUDIT_MAP = [
@@ -603,6 +603,35 @@ async def sessions(request: Request):
return list_sessions(user)
@app.post("/api/recalc")
async def recalc(request: Request):
"""Пересчитать смету движком по правкам объёмов (срез 6.2). Числа — из движка, не из JS.
body: {positions:[{code, qty, unit?}], meta?}. Тяжёлую загрузку движка гоним в
threadpool, чтобы не блокировать сервер."""
_get_user(request)
body = await request.json()
positions = body.get("positions") or []
if not isinstance(positions, list) or not positions:
raise HTTPException(400, "Нет позиций для расчёта")
meta = body.get("meta") if isinstance(body.get("meta"), dict) else {}
import estimate_contract as ec
if not ec.engine_enabled():
raise HTTPException(400, "Расчётный движок выключен")
import asyncio
try:
r = await asyncio.get_event_loop().run_in_executor(None, lambda: ec.calc_estimate(positions, meta))
except Exception: # noqa: BLE001 — движок недоступен/данные битые: честный 500, детали в логах uvicorn
import traceback; traceback.print_exc()
raise HTTPException(500, "Не удалось пересчитать")
return {
"title": meta.get("title") or "Смета (пересчёт)",
"positions": [{"code": p.get("code"), "name": p.get("name"), "unit": p.get("unit"),
"qty": p.get("qty"), "total": p.get("total")} for p in r.get("positions", [])],
"totals": {"grand_total": r.get("grand_total")},
"ok": r.get("ok"), "missing": r.get("missing"),
}
@app.delete("/api/sessions/{tab_id}")
async def delete_session_ep(tab_id: str, request: Request):
"""Удалить свой диалог ЦЕЛИКОМ (история в БД + загруженные файлы на диске).
+43 -3
View File
@@ -126,6 +126,8 @@ button { font-family: inherit; }
.est-actions { padding: .5rem .9rem; border-top: 1px solid var(--border); display: flex; justify-content: flex-end; }
.est-dl { font-size: .82rem; padding: .35rem .8rem; border: 1px solid var(--border); border-radius: 6px; background: var(--bg-sunken); color: var(--text); cursor: pointer; }
.est-dl:hover { border-color: var(--accent); color: var(--accent); }
.est-qty { width: 5.5rem; padding: .15rem .3rem; border: 1px solid var(--border); border-radius: 4px; background: var(--bg-card); color: var(--text); font-size: .8rem; text-align: right; font-variant-numeric: tabular-nums; }
.est-qty:focus { border-color: var(--accent); outline: none; }
.msg-system { align-self: center; background: var(--system-bg); border: none; font-size: .8rem; color: var(--system-text); box-shadow: none; padding: .4rem .8rem; }
.typing { align-self: flex-start; color: var(--text-light); font-style: italic; font-size: .85rem; padding: .4rem 0; }
@@ -1257,17 +1259,28 @@ function addEstimatePanel(data) {
const th = document.createElement('th'); th.textContent = h; thead.appendChild(th);
});
table.appendChild(thead);
const editable = !!(data.positions || []).some(p => p.code); // движок сможет пересчитать
(data.positions || []).forEach((p, i) => {
const tr = document.createElement('tr');
const cells = [i + 1, p.code || '', p.name || '', p.unit || '',
p.qty != null ? p.qty : '', fmtMoney(p.unit_cost), fmtMoney(p.total)];
cells.forEach((c, ci) => {
const td = document.createElement('td');
td.textContent = c;
if (ci >= 4) td.className = 'num'; // числовые колонки — правое выравнивание/tabular
if (ci === 4 && editable && p.code) {
// объём — редактируемый; правка пересчитывается ДВИЖКОМ (не JS)
const inp = document.createElement('input');
inp.type = 'number'; inp.step = 'any'; inp.className = 'est-qty';
inp.value = p.qty != null ? p.qty : '';
inp.setAttribute('aria-label', 'Объём: ' + (p.name || p.code));
inp.dataset.code = p.code; if (p.unit) inp.dataset.unit = p.unit;
td.appendChild(inp); td.className = 'num';
} else {
td.textContent = c;
if (ci >= 4) td.className = 'num';
}
tr.appendChild(td);
});
if (p.unresolved) tr.classList.add('est-unresolved'); // подсветить нерассчитанную позицию
if (p.unresolved) tr.classList.add('est-unresolved');
table.appendChild(tr);
});
scroll.appendChild(table);
@@ -1316,6 +1329,33 @@ function addEstimatePanel(data) {
tableToExcel(panel.querySelector('.est-table'), 'смета.xlsx', title);
};
acts.appendChild(dl);
// Пересчитать движком (срез 6.2): правки объёмов → движок считает заново (не JS)
if (editable) {
const rc = document.createElement('button');
rc.className = 'est-dl'; rc.type = 'button'; rc.textContent = '↻ Пересчитать движком';
rc.onclick = async () => {
const inputs = Array.from(panel.querySelectorAll('.est-qty'));
const positions = inputs.map(inp => {
const o = {code: inp.dataset.code, qty: parseFloat(inp.value)};
if (inp.dataset.unit) o.unit = inp.dataset.unit;
return o;
}).filter(o => o.code && isFinite(o.qty));
if (!positions.length) return;
rc.disabled = true; rc.textContent = '↻ Считаю...';
try {
const r = await authFetch('/api/recalc', {method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({positions, meta: {title: data.title}})});
if (!r.ok) { rc.textContent = httpErrText(r.status); return; }
const upd = await r.json();
const fresh = addEstimatePanel(upd); // новая панель с пересчётом
panel.replaceWith(fresh); // заменить старую
} catch (e) {
rc.textContent = 'Нет связи'; rc.disabled = false;
}
};
acts.appendChild(rc);
}
panel.appendChild(acts);
const ob = document.getElementById('onboarding'); if (ob) ob.remove();
+9
View File
@@ -81,6 +81,15 @@ window.fetch = async (url, opts={}) => {
evs.push('event: done\ndata: {"result":"ok"}\n\n');
return new Response(_sse(evs, opts.signal), {status:200, headers:{'Content-Type':'text/event-stream'}});
}
if (url.includes('/api/recalc')) {
const b = JSON.parse(opts.body || '{}'); const pos = b.positions || [];
// «движок»: total позиции = qty*1000; итог = сумма
const positions = pos.map(p => ({code: p.code, name: 'Позиция ' + p.code, unit: p.unit || 'ед',
qty: p.qty, total: p.qty * 1000}));
const gt = positions.reduce((s, p) => s + p.total, 0);
window._recalc = (window._recalc || 0) + 1;
return _json({title: 'Смета (пересчёт)', positions, totals: {grand_total: gt}, ok: true, missing: []});
}
if (url.includes('/api/feedback')) { window._fb++; return _json({}); }
if (url.includes('/api/history')) return _json([]);
// /api/sessions/{tab}/title (POST)