Add inline price basis switching to saved estimate answers

This commit is contained in:
anor
2026-12-02 21:56:06 +10:00
parent 7e4d4f841c
commit 856dbebdd1
9 changed files with 696 additions and 16 deletions
+168 -10
View File
@@ -356,6 +356,12 @@ button { font-family: inherit; }
.est-tot-row .num { font-variant-numeric: tabular-nums; }
.est-tot-strong { font-weight: 700; color: var(--text); font-size: .95rem; }
.est-basis { padding: .35rem .9rem; font-size: .78rem; color: var(--text-muted); border-bottom: 1px solid var(--border); overflow-wrap: anywhere; }
.msg-ai.has-estimate { width: 100%; max-width: 100%; }
.msg-ai .est-panel { width: 100%; box-sizing: border-box; }
.est-basis-picker { display: inline-flex; gap: .35rem; align-items: center; flex-wrap: wrap; }
.est-basis-picker button, .est-basis-picker select { max-width: 100%; font: inherit; color: var(--text); background: var(--bg-card); border: 1px solid var(--border); border-radius: 6px; padding: .25rem .4rem; cursor: pointer; }
.est-basis-picker button:hover, .est-basis-picker select:focus-visible { border-color: var(--accent); }
.est-basis-error { color: var(--danger); display: block; margin-top: .3rem; }
.est-input { color: var(--text-muted); font-size: .85em; }
.est-warn { padding: .5rem .9rem; border-top: 1px solid var(--border); background: var(--error-bg); color: var(--error-text, var(--text)); font-size: .8rem; display: flex; flex-direction: column; gap: .25rem; }
.ka-sub { padding: .3rem .9rem; font-size: .72rem; color: var(--text-muted); font-family: monospace; border-bottom: 1px solid var(--border-light, var(--border)); word-break: break-all; }
@@ -417,6 +423,28 @@ button { font-family: inherit; }
.msg-ai .table-wrap .num, .msg-ai .table-wrap th.num { white-space: normal; overflow-wrap: anywhere; }
.msg-ai .table-wrap th, .msg-ai .table-wrap td { min-width: 0; }
.msg-ai .table-wrap thead th { position: sticky; top: 0; background: var(--ai-bg); z-index: 1; }
@media (max-width: 600px) {
.msg-ai.has-estimate .est-table, .msg-ai.has-estimate .est-table tbody,
.msg-ai.has-estimate .est-table tr { display: block; width: 100%; }
.msg-ai.has-estimate .est-table .est-header-row { display: none; }
.msg-ai.has-estimate .est-table tr { padding: .45rem; border-bottom: 1px solid var(--border); }
.msg-ai.has-estimate .est-table td {
display: grid; grid-template-columns: minmax(7.3rem, 42%) minmax(0, 1fr);
gap: .35rem; width: 100%; max-width: none; box-sizing: border-box;
border: 0; padding: .2rem .35rem; white-space: normal; overflow-wrap: anywhere;
}
.msg-ai.has-estimate .est-table td::before {
content: attr(data-label); color: var(--text-muted); font-weight: 600;
}
.msg-ai.has-estimate .est-table td.num { text-align: left; white-space: normal; }
.msg-ai.has-estimate .est-table td input { min-width: 0; max-width: 100%; box-sizing: border-box; }
.msg-ai.has-estimate .est-actions {
display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: .4rem;
}
.msg-ai.has-estimate .est-actions .est-dl {
width: 100%; min-height: 2.5rem; word-break: normal; overflow-wrap: normal;
}
}
.msg-ai th, .msg-ai td { border: 1px solid var(--border-light); padding: .35rem .6rem; text-align: left; vertical-align: top; white-space: normal; max-width: 360px; }
.msg-ai th { background: var(--bg); font-weight: 600; position: sticky; top: 0; }
.msg-ai td.num, .msg-ai th.num { white-space: nowrap; text-align: right; font-variant-numeric: tabular-nums; }
@@ -2175,6 +2203,28 @@ function addMsg(type, text, ts) {
scrollIfPinned();
return div;
}
// Структурированная смета приходит после done. Отделяем текст ответа от кнопок,
// стоимости и панели, чтобы пересчёт заменял содержимое ЭТОГО пузыря.
function estimateAnswerBody(host) {
let body = host.querySelector(':scope > .ai-body');
if (body) return body;
body = document.createElement('div'); body.className = 'ai-body';
for (const child of Array.from(host.childNodes)) {
if (child.nodeType === 1 && child.matches('.msg-time, .copy-btn, .msg-cost, .est-panel, .fb-form')) continue;
body.appendChild(child);
}
const time = host.querySelector(':scope > .msg-time');
if (time) time.after(body); else host.prepend(body);
return body;
}
function replaceEstimateAnswer(host, text) {
const body = estimateAnswerBody(host);
body.innerHTML = renderMarkdown(text);
host._rawText = text;
enhanceTables(body); typografAI(body); externalizeLinks(body);
}
function addTyping() {
const div = document.createElement('div');
div.className = 'typing';
@@ -3013,8 +3063,8 @@ async function runChat(text, retried, готовыйПоток, внешнийCt
// Агент подготовил файлы — кнопки скачивания прямо в чате
if (data.files && data.files.length) addFilesMsg(data.files);
} else if (eventType === 'estimate') {
// Структурированная смета — панель с таблицей (срез 6.1, JS НЕ считает)
if (data && data.positions) addEstimatePanel(data);
// Смета живёт в том же ответе, который её породил.
if (data && data.positions) addEstimatePanel(data, null, aiDiv);
} else if (eventType === 'ka_form') {
// Конъюнктурный анализ — панель офферов (срез 7)
if (data && data.rows) addKaPanel(data);
@@ -3058,7 +3108,7 @@ function fmtMoney(v) {
if (typeof v !== 'number' || !isFinite(v)) return v == null ? '' : String(v);
return v.toLocaleString('ru-RU', {minimumFractionDigits: 2, maximumFractionDigits: 2});
}
function addEstimatePanel(data, prevData) {
function addEstimatePanel(data, prevData, host) {
const panel = document.createElement('div');
panel.className = 'est-panel';
panel.setAttribute('role', 'region');
@@ -3076,12 +3126,93 @@ function addEstimatePanel(data, prevData) {
// По какой форме посчитано: зона места стройки и уровень цен — подпись итога не должна
// приписать числа чужому региону (инцидент 01.08.2026).
const ap = data.applied;
async function applyLinked(zoneId, periodId, positions) {
if (!data._message_id || !host) return;
const requestTab = tabId;
panel.querySelectorAll('button, select, input').forEach(el => { el.disabled = true; });
let error = panel.querySelector('.est-basis-error');
if (error) error.remove();
try {
const r = await authFetch('/api/estimates/' + data._message_id + '/basis', {
method: 'POST', headers: {'Content-Type': 'application/json'},
body: JSON.stringify({zone_id: zoneId, period_id: periodId,
revision: data._revision || 0, positions})});
if (!r.ok) throw new Error(await reasonOrText(r));
const updated = await r.json();
if (requestTab !== tabId || !panel.isConnected) return;
replaceEstimateAnswer(host, updated.answer);
addEstimatePanel(updated.estimate, data, host);
panel.remove();
srAnnounce('Смета пересчитана в текущем ответе');
} catch (e) {
if (!panel.isConnected) return;
error = document.createElement('span'); error.className = 'est-basis-error';
error.setAttribute('role', 'alert');
error.textContent = e.message || 'Не удалось пересчитать';
(panel.querySelector('.est-basis') || panel.querySelector('.est-head')).appendChild(error);
panel.querySelectorAll('button, select, input').forEach(el => { el.disabled = false; });
}
}
if (ap && ap.zone) {
const basis = document.createElement('div');
basis.className = 'est-basis';
basis.textContent = 'Цены: ' + ap.zone + ', ' + (ap.period || '')
+ (ap.period_default ? ' (последний доступный период)' : '')
+ (ap.letter ? ' · ' + ap.letter : '');
if (data._message_id && data._assistant_id && host && !viewOwner && ap.subject_id != null) {
const picker = document.createElement('span'); picker.className = 'est-basis-picker';
const open = document.createElement('button'); open.type = 'button';
open.textContent = 'Цены: ' + ap.zone + ', ' + (ap.period || '') + ' ▾';
open.setAttribute('aria-label', 'Изменить ценовую зону или квартал');
open.onclick = async () => {
open.disabled = true; open.textContent = 'Загружаю доступные цены…';
try {
const r = await authFetch('/api/estimates/' + data._message_id + '/basis');
if (!r.ok) throw new Error(await reasonOrText(r));
const options = await r.json();
if (!panel.isConnected) return;
const zones = options.zones || [];
const zoneSelect = document.createElement('select');
zoneSelect.setAttribute('aria-label', 'Ценовая зона');
zones.forEach(z => { const o = document.createElement('option');
o.value = String(z.zone_id); o.textContent = z.name; zoneSelect.appendChild(o); });
zoneSelect.value = String(ap.zone_id);
const periodSelect = document.createElement('select');
periodSelect.setAttribute('aria-label', 'Квартал цен');
const fillPeriods = () => {
periodSelect.replaceChildren();
const selected = zones.find(z => String(z.zone_id) === zoneSelect.value);
const periods = selected ? selected.periods : [];
periods.forEach(p => { const o = document.createElement('option');
o.value = String(p.period_id); o.textContent = p.name; periodSelect.appendChild(o); });
if ([...periodSelect.options].some(o => o.value === String(ap.period_id)))
periodSelect.value = String(ap.period_id);
else if (periods.length) periodSelect.value = String(periods[periods.length - 1].period_id);
};
fillPeriods();
const submit = () => {
if (Number(zoneSelect.value) === ap.zone_id && Number(periodSelect.value) === ap.period_id) return;
const inputs = Array.from(panel.querySelectorAll('.est-qty'));
const positions = inputs.map(inp => ({code: inp.dataset.code, unit: inp.dataset.unit || '',
qty: parseFloat(inp.value)}));
applyLinked(Number(zoneSelect.value), Number(periodSelect.value), positions);
};
zoneSelect.onchange = () => { fillPeriods(); submit(); };
periodSelect.onchange = submit;
picker.replaceChildren(zoneSelect, periodSelect);
zoneSelect.focus();
} catch (e) {
open.disabled = false; open.textContent = 'Цены: ' + ap.zone + ', ' + (ap.period || '') + ' ▾';
const err = document.createElement('span'); err.className = 'est-basis-error';
err.setAttribute('role', 'alert'); err.textContent = e.message || 'Нет связи';
basis.appendChild(err);
}
};
picker.appendChild(open); basis.appendChild(picker);
if (ap.letter) { const letter = document.createElement('span');
letter.textContent = ' · ' + ap.letter; basis.appendChild(letter); }
} else {
basis.textContent = 'Цены: ' + ap.zone + ', ' + (ap.period || '')
+ (ap.period_default ? ' (последний доступный период)' : '')
+ (ap.letter ? ' · ' + ap.letter : '');
}
panel.appendChild(basis);
}
@@ -3090,6 +3221,7 @@ function addEstimatePanel(data, prevData) {
const table = document.createElement('table');
table.className = 'est-table';
const thead = document.createElement('tr');
thead.className = 'est-header-row';
['№', 'Код', 'Наименование', 'Ед.', 'Кол-во', 'Цена/ед', 'Стоимость'].forEach(h => {
const th = document.createElement('th'); th.textContent = h; thead.appendChild(th);
});
@@ -3101,6 +3233,7 @@ function addEstimatePanel(data, prevData) {
p.qty != null ? p.qty : '', fmtMoney(p.unit_cost), fmtMoney(p.total)];
cells.forEach((c, ci) => {
const td = document.createElement('td');
td.dataset.label = ['№', 'Код', 'Наименование', 'Ед.', 'Кол-во', 'Цена/ед', 'Стоимость'][ci];
if (ci === 4 && editable && p.code) {
// объём — редактируемый; правка пересчитывается ДВИЖКОМ (не JS)
const inp = document.createElement('input');
@@ -3196,6 +3329,10 @@ function addEstimatePanel(data, prevData) {
return;
}
if (!positions.length) return;
if (data._message_id && host && ap && ap.zone_id != null && ap.period_id != null) {
await applyLinked(ap.zone_id, ap.period_id, positions);
return;
}
rc.disabled = true; rc.textContent = '↻ Считаю...';
try {
const r = await authFetch('/api/recalc', {method: 'POST',
@@ -3221,7 +3358,14 @@ function addEstimatePanel(data, prevData) {
if (prevData) {
const un = document.createElement('button');
un.className = 'est-dl'; un.type = 'button'; un.textContent = '↩ Отменить пересчёт';
un.onclick = () => { const back = addEstimatePanel(prevData); panel.replaceWith(back); };
un.onclick = () => {
if (data._message_id && host && prevData.applied) {
applyLinked(prevData.applied.zone_id, prevData.applied.period_id,
(prevData.positions || []).map(p => ({code: p.code, unit: p.unit || '', qty: p.qty})));
} else {
const back = addEstimatePanel(prevData); panel.replaceWith(back);
}
};
acts.appendChild(un);
}
// Утвердить смету (срез 6.4): человек фиксирует смету — блокируем правки, метка
@@ -3230,6 +3374,8 @@ function addEstimatePanel(data, prevData) {
appr.onclick = () => {
panel.classList.add('est-approved');
panel.querySelectorAll('.est-qty').forEach(i => { i.readOnly = true; i.tabIndex = -1; });
panel.querySelectorAll('.est-basis-picker button, .est-basis-picker select')
.forEach(el => { el.disabled = true; });
acts.querySelectorAll('button').forEach(b => { if (b !== dl) b.disabled = true; });
const badge = document.createElement('span');
badge.className = 'est-badge'; badge.textContent = '✓ Утверждено';
@@ -3240,7 +3386,11 @@ function addEstimatePanel(data, prevData) {
panel.appendChild(acts);
const ob = document.getElementById('onboarding'); if (ob) ob.remove();
msgs.appendChild(panel);
if (host) {
estimateAnswerBody(host);
host.classList.add('has-estimate');
host.appendChild(panel);
} else msgs.appendChild(panel);
scrollIfPinned();
return panel;
}
@@ -3493,7 +3643,10 @@ async function loadHistory() {
let lastAi = null;
for (const m of history) {
if (m.role === 'user') addMsg('user', m.content, m.timestamp);
else if (m.role === 'assistant') lastAi = addMsg('ai', m.content, m.timestamp);
else if (m.role === 'assistant') {
lastAi = addMsg('ai', m.content, m.timestamp);
lastAi._messageId = m.id;
}
else if (m.role === 'spend') {
try { attachCost(lastAi, JSON.parse(m.content)); } catch {}
}
@@ -3502,7 +3655,12 @@ async function loadHistory() {
try { addFilesMsg(JSON.parse(m.content), m.timestamp); } catch {}
}
else if (m.role === 'estimate') {
try { addEstimatePanel(JSON.parse(m.content)); } catch {}
try {
const estimate = JSON.parse(m.content);
const host = !estimate._assistant_id || lastAi && lastAi._messageId === estimate._assistant_id
? lastAi : null;
addEstimatePanel({...estimate, _message_id: m.id}, null, host);
} catch {}
}
else if (m.role === 'ka_form') {
try { addKaPanel(JSON.parse(m.content)); } catch {}