Revise plain estimate answers from inline price zones

This commit is contained in:
anor
2026-12-02 23:21:25 +10:00
parent 2a3cdf8bd8
commit d908d183d5
8 changed files with 534 additions and 28 deletions
+119 -1
View File
@@ -362,6 +362,12 @@ button { font-family: inherit; }
.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; }
.inline-basis-trigger { border: 0; border-bottom: 1px dotted currentColor; padding: 0; background: transparent; color: var(--accent); font: inherit; cursor: pointer; }
.inline-basis-trigger:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
.inline-basis-picker { display: inline-flex; flex-wrap: wrap; align-items: center; gap: .35rem; padding: .2rem; border: 1px solid var(--border); border-radius: 6px; background: var(--bg-card); max-width: 100%; }
.inline-basis-picker select, .inline-basis-picker button { max-width: 100%; min-width: 0; padding: .2rem .35rem; font: inherit; color: var(--text); background: var(--bg-card); border: 1px solid var(--border); border-radius: 5px; }
.inline-basis-picker .inline-basis-apply { color: var(--accent); cursor: pointer; }
.inline-basis-picker .est-basis-error { flex-basis: 100%; }
.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; }
@@ -2225,6 +2231,109 @@ function replaceEstimateAnswer(host, text) {
host._rawText = text;
enhanceTables(body); typografAI(body); externalizeLinks(body);
}
// В обычном ответе названия ценовых зон остаются частью текста. Нажатие открывает
// допустимые формы, а пересчёт заменяет этот же ответ, без нового пузыря.
function bindFreeformBasis(host) {
if (!host || !host._messageId || viewOwner || host.classList.contains('has-estimate')) return;
const raw = host._rawText || '';
if (!/\d{2}-\d{2}-\d{3}-\d{2}/.test(raw)
|| !/\d+(?:[.,]\d+)?\s+(?:(?:[а-яё-]+\s+){0,3})?(?:извещател[а-яё]*|шт\.?|штук)(?=$|[^а-яё])/i.test(raw)) return;
const body = estimateAnswerBody(host);
const pattern = /[А-ЯЁ][А-ЯЁа-яё-]*(?:\s+[А-ЯЁа-яё-]+){0,5}\s*\(\d+\s+зона\)/g;
const walker = document.createTreeWalker(body, NodeFilter.SHOW_TEXT);
const nodes = [];
while (walker.nextNode()) {
const node = walker.currentNode;
if (node.parentElement && !node.parentElement.closest('button, a, select, .inline-basis-picker')
&& pattern.test(node.textContent)) nodes.push(node);
pattern.lastIndex = 0;
}
nodes.forEach(node => {
const fragment = document.createDocumentFragment();
let start = 0;
for (const match of node.textContent.matchAll(pattern)) {
fragment.append(document.createTextNode(node.textContent.slice(start, match.index)));
const button = document.createElement('button');
button.type = 'button'; button.className = 'inline-basis-trigger';
button.textContent = match[0];
button.title = 'Выбрать ценовую зону и квартал для этого ответа';
button.onclick = () => openFreeformBasis(button, host, match[0]);
fragment.append(button);
start = match.index + match[0].length;
}
fragment.append(document.createTextNode(node.textContent.slice(start)));
node.replaceWith(fragment);
});
}
async function openFreeformBasis(button, host, label) {
if (!host._messageId || viewOwner) return;
const requestTab = tabId;
button.disabled = true;
try {
const url = API + '/api/messages/' + host._messageId + '/basis';
const r = await authFetch(url + '?label=' + encodeURIComponent(label));
if (!r.ok) throw new Error(await reasonOrText(r));
const options = await r.json();
if (requestTab !== tabId || !button.isConnected) return;
const zones = options.zones || [];
const picker = document.createElement('span'); picker.className = 'inline-basis-picker';
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); });
const currentZone = zones.find(z => z.name === label);
if (currentZone) zoneSelect.value = String(currentZone.zone_id);
const periodSelect = document.createElement('select'); periodSelect.setAttribute('aria-label', 'Квартал цен');
const fillPeriods = () => {
periodSelect.replaceChildren();
const placeholder = document.createElement('option'); placeholder.value = '';
placeholder.textContent = 'Выберите квартал'; periodSelect.appendChild(placeholder);
const zone = zones.find(z => String(z.zone_id) === zoneSelect.value);
(zone ? zone.periods : []).forEach(p => { const o = document.createElement('option');
o.value = String(p.period_id); o.textContent = p.name; periodSelect.appendChild(o); });
const named = (zone ? zone.periods : []).find(p => (host._rawText || '').includes(p.name));
if (named) periodSelect.value = String(named.period_id);
};
fillPeriods(); zoneSelect.onchange = fillPeriods;
const apply = document.createElement('button'); apply.type = 'button';
apply.className = 'inline-basis-apply'; apply.textContent = 'Пересчитать';
const cancel = document.createElement('button'); cancel.type = 'button'; cancel.textContent = 'Отмена';
cancel.onclick = () => picker.replaceWith(button);
apply.onclick = async () => {
if (!periodSelect.value) { periodSelect.focus(); return; }
picker.querySelectorAll('button, select').forEach(el => { el.disabled = true; });
apply.textContent = 'Пересчитываю…';
try {
const response = await authFetch(url, {method: 'POST', headers: {'Content-Type':'application/json'},
body: JSON.stringify({label, zone_id:Number(zoneSelect.value),
period_id:Number(periodSelect.value), revision:options.revision})});
if (!response.ok) throw new Error(await reasonOrText(response));
const updated = await response.json();
if (requestTab !== tabId || !picker.isConnected) return;
replaceEstimateAnswer(host, updated.answer);
bindFreeformBasis(host);
if (updated.spend) attachCost(host, updated.spend);
if (updated.balance) renderBalance(updated.balance);
srAnnounce('Ответ пересчитан в текущем сообщении');
} catch (e) {
if (!picker.isConnected) return;
const err = document.createElement('span'); err.className = 'est-basis-error';
err.setAttribute('role', 'alert'); err.textContent = e.message || 'Не удалось пересчитать';
picker.appendChild(err);
picker.querySelectorAll('button, select').forEach(el => { el.disabled = false; });
apply.textContent = 'Пересчитать';
}
};
picker.append(zoneSelect, periodSelect, apply, cancel);
button.replaceWith(picker); zoneSelect.focus();
} catch (e) {
button.disabled = false;
const err = document.createElement('span'); err.className = 'est-basis-error';
err.setAttribute('role', 'alert'); err.textContent = e.message || 'Нет доступных цен';
button.after(err);
}
}
function addTyping() {
const div = document.createElement('div');
div.className = 'typing';
@@ -3059,6 +3168,8 @@ async function runChat(text, retried, готовыйПоток, внешнийCt
// Цена ответа и остаток — без перезагрузки страницы.
if (aiDiv && data.answer) attachCost(aiDiv, data.answer);
if (data.balance) renderBalance(data.balance);
} else if (eventType === 'assistant_id') {
if (aiDiv && data.id) { aiDiv._messageId = data.id; bindFreeformBasis(aiDiv); }
} else if (eventType === 'files') {
// Агент подготовил файлы — кнопки скачивания прямо в чате
if (data.files && data.files.length) addFilesMsg(data.files);
@@ -3391,6 +3502,9 @@ function addEstimatePanel(data, prevData, host) {
const ob = document.getElementById('onboarding'); if (ob) ob.remove();
if (host) {
host.querySelectorAll('.inline-basis-trigger').forEach(button => {
button.replaceWith(document.createTextNode(button.textContent));
});
estimateAnswerBody(host);
host.classList.add('has-estimate');
host.appendChild(panel);
@@ -3645,14 +3759,18 @@ async function loadHistory() {
if (history.length === 0) { showOnboarding(); updateQuickActions(); return; }
msgs.innerHTML = '';
let lastAi = null;
const aiById = new Map();
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);
lastAi._messageId = m.id;
aiById.set(m.id, lastAi);
bindFreeformBasis(lastAi);
}
else if (m.role === 'spend') {
try { attachCost(lastAi, JSON.parse(m.content)); } catch {}
try { const cost = JSON.parse(m.content);
attachCost(cost._assistant_id ? aiById.get(cost._assistant_id) : lastAi, cost); } catch {}
}
else if (m.role === 'system') addMsg('system', m.content, m.timestamp);
else if (m.role === 'files') {