From 04cb1a5c74af03409720d5e27fd7bc614983c8ce Mon Sep 17 00:00:00 2001 From: anor Date: Fri, 17 Jul 2026 23:57:23 +1000 Subject: [PATCH] =?UTF-8?q?feat(ui/core):=20=D1=81=D1=80=D0=B5=D0=B7=206.2?= =?UTF-8?q?=20=E2=80=94=20=D0=BF=D1=80=D0=B0=D0=B2=D0=BA=D0=B0=20=D1=81?= =?UTF-8?q?=D0=BC=D0=B5=D1=82=D1=8B=20=E2=86=92=20=D0=BF=D0=B5=D1=80=D0=B5?= =?UTF-8?q?=D1=81=D1=87=D1=91=D1=82=20=D0=94=D0=92=D0=98=D0=96=D0=9A=D0=9E?= =?UTF-8?q?=D0=9C=20(=D0=BD=D0=B5=20JS)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Объёмы в панели редактируемы (input); «Пересчитать движком» → POST /api/recalc → estimate_contract.calc_estimate в threadpool (не блокирует сервер) → новая панель с детерминир. пересчётом. JS не считает — только движок. Браузер-verified (100→250 → итог пересчитан). APP_VERSION 2026-07-17r. --- main.py | 31 +++++++++++++++++++++++++- static/chat.html | 46 ++++++++++++++++++++++++++++++++++++--- tests/ui_smoke_harness.py | 9 ++++++++ 3 files changed, 82 insertions(+), 4 deletions(-) diff --git a/main.py b/main.py index 4ed04c4..635b5b0 100644 --- a/main.py +++ b/main.py @@ -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): """Удалить свой диалог ЦЕЛИКОМ (история в БД + загруженные файлы на диске). diff --git a/static/chat.html b/static/chat.html index eb6b0f6..f7f1cb7 100644 --- a/static/chat.html +++ b/static/chat.html @@ -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(); diff --git a/tests/ui_smoke_harness.py b/tests/ui_smoke_harness.py index 90998f6..f6e6f04 100644 --- a/tests/ui_smoke_harness.py +++ b/tests/ui_smoke_harness.py @@ -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)