Add source-linked inline comparison for uploaded estimates
This commit is contained in:
@@ -358,6 +358,12 @@ button { font-family: inherit; }
|
||||
.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; }
|
||||
.file-compare-controls { display: flex; flex-wrap: wrap; gap: .6rem; padding: .7rem .9rem; }
|
||||
.file-compare-controls label { display: grid; gap: .25rem; min-width: min(100%, 220px); font-size: .8rem; }
|
||||
.file-compare-controls select, .file-compare-panel select { max-width: 100%; padding: .35rem; border: 1px solid var(--border); border-radius: 6px; background: var(--bg-card); color: var(--text); }
|
||||
.file-compare-status { padding: .4rem .9rem; color: var(--text-muted); font-size: .82rem; }
|
||||
.file-compare-status[role="alert"] { color: var(--error, #ad3434); }
|
||||
.file-compare-pages { display: flex; gap: .5rem; align-items: center; padding: .5rem .9rem; }
|
||||
.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); }
|
||||
@@ -3228,6 +3234,8 @@ async function runChat(text, retried, готовыйПоток, внешнийCt
|
||||
} else if (eventType === 'estimate') {
|
||||
// Смета живёт в том же ответе, который её породил.
|
||||
if (data && data.positions) addEstimatePanel(data, null, aiDiv);
|
||||
} else if (eventType === 'file_compare') {
|
||||
if (data && data._message_id && aiDiv) addFileComparePanel(data, aiDiv);
|
||||
} else if (eventType === 'ka_form') {
|
||||
// Конъюнктурный анализ — панель офферов (срез 7)
|
||||
if (data && data.rows) addKaPanel(data);
|
||||
@@ -3565,6 +3573,165 @@ function addEstimatePanel(data, prevData, host) {
|
||||
return panel;
|
||||
}
|
||||
|
||||
// --- Сверка собственных файлов внутри того же ответа ---
|
||||
function addFileComparePanel(initial, host) {
|
||||
if (!host) return;
|
||||
const panel = document.createElement('section');
|
||||
panel.className = 'est-panel file-compare-panel';
|
||||
panel.setAttribute('role', 'region');
|
||||
panel.setAttribute('aria-label', 'Сверка файлов');
|
||||
host.classList.add('has-estimate');
|
||||
host.appendChild(panel);
|
||||
let state = initial, workbooks = [], page = 0;
|
||||
const modeNames = {ka_lsr: 'КА ↔ ЛСР: цены', vor_lsr: 'ВОР ↔ ЛСР: объёмы', ka_kp: 'КА ↔ КП: цены'};
|
||||
const sideNames = {ka_lsr: ['Конъюнктурный анализ', 'Локальная смета'],
|
||||
vor_lsr: ['Ведомость объёмов', 'Локальная смета'],
|
||||
ka_kp: ['Конъюнктурный анализ', 'Коммерческое предложение']};
|
||||
const id = initial._message_id;
|
||||
const endpoint = '/api/file-compare/' + encodeURIComponent(id);
|
||||
const node = (tag, cls, value) => {
|
||||
const el = document.createElement(tag);
|
||||
if (cls) el.className = cls;
|
||||
if (value != null) el.textContent = String(value);
|
||||
return el;
|
||||
};
|
||||
async function load(nextPage=0) {
|
||||
const r = await authFetch(endpoint + '?page=' + nextPage);
|
||||
const data = await r.json().catch(() => ({}));
|
||||
if (!r.ok) throw new Error(data.detail || 'Не удалось прочитать сверку');
|
||||
state = data; page = nextPage;
|
||||
render();
|
||||
}
|
||||
async function update(change) {
|
||||
const r = await authFetch(endpoint, {method: 'POST',
|
||||
headers: {'Content-Type': 'application/json'},
|
||||
body: JSON.stringify({revision: state._revision, ...change})});
|
||||
const data = await r.json().catch(() => ({}));
|
||||
if (!r.ok) throw new Error(data.detail || 'Не удалось пересчитать сверку');
|
||||
state = data; page = 0;
|
||||
render();
|
||||
}
|
||||
function showError(message) {
|
||||
let status = panel.querySelector('.file-compare-status');
|
||||
if (!status) { status = node('div', 'file-compare-status'); panel.appendChild(status); }
|
||||
status.setAttribute('role', 'alert');
|
||||
status.textContent = message;
|
||||
}
|
||||
function fileChoice(side, title, controls) {
|
||||
const label = node('label', '', title);
|
||||
const file = node('select');
|
||||
file.setAttribute('aria-label', title + ': файл');
|
||||
file.add(new Option('Выберите файл', ''));
|
||||
workbooks.forEach(w => file.add(new Option(w.filename, w.filename)));
|
||||
file.value = state[side]?.file || '';
|
||||
const sheet = node('select');
|
||||
sheet.setAttribute('aria-label', title + ': лист');
|
||||
function sheets(selected) {
|
||||
sheet.replaceChildren();
|
||||
const selectedBook = workbooks.find(w => w.filename === file.value);
|
||||
(selectedBook?.sheets || []).forEach(name => sheet.add(new Option(name, name)));
|
||||
sheet.value = selected || selectedBook?.sheets?.[0] || '';
|
||||
}
|
||||
sheets(state[side]?.sheet);
|
||||
async function apply() {
|
||||
if (!file.value || !sheet.value) return;
|
||||
try { await update({[side]: {file: file.value, sheet: sheet.value}}); }
|
||||
catch (e) { showError(e.message); }
|
||||
}
|
||||
file.onchange = () => { sheets(); apply(); };
|
||||
sheet.onchange = apply;
|
||||
if (viewOwner) { file.disabled = true; sheet.disabled = true; }
|
||||
label.append(file, sheet); controls.appendChild(label);
|
||||
}
|
||||
function render() {
|
||||
if (!panel.isConnected) return;
|
||||
panel.replaceChildren(node('div', 'est-head', modeNames[state.mode] || 'Сверка файлов'));
|
||||
const controls = node('div', 'file-compare-controls');
|
||||
const titles = sideNames[state.mode] || ['Первый файл', 'Второй файл'];
|
||||
fileChoice('left', titles[0], controls);
|
||||
fileChoice('right', titles[1], controls);
|
||||
panel.appendChild(controls);
|
||||
const comparison = state.comparison;
|
||||
if (!workbooks.length) {
|
||||
panel.appendChild(node('div', 'file-compare-status', 'Загрузите книги xlsx в этот диалог.'));
|
||||
return;
|
||||
}
|
||||
if (!comparison) {
|
||||
panel.appendChild(node('div', 'file-compare-status', 'Выберите исходные файлы и листы для сверки.'));
|
||||
return;
|
||||
}
|
||||
panel.appendChild(node('div', 'file-compare-status',
|
||||
`Строк: ${comparison.total_rows}; требуют проверки: ${comparison.unmatched}; ` +
|
||||
`только во втором файле: ${comparison.unmatched_right || 0}. ` +
|
||||
(comparison.complete ? 'Сверка завершена.' : 'Сверка неполная; проверьте строки и исходные файлы.')));
|
||||
panel.appendChild(node('div', 'file-compare-status', 'Таблицу можно прокручивать по горизонтали.'));
|
||||
const scroll = node('div', 'est-scroll');
|
||||
const table = node('table', 'est-table');
|
||||
const header = node('tr');
|
||||
['Источник', 'Код / наименование', 'Ед.', 'Значение', 'Соответствие', 'Разница'].forEach(text =>
|
||||
header.appendChild(node('th', '', text)));
|
||||
table.appendChild(header);
|
||||
(comparison.rows || []).forEach(row => {
|
||||
const tr = node('tr', row.warning ? 'est-unresolved' : '');
|
||||
const left = row.left;
|
||||
tr.appendChild(node('td', '', `${left.file} · ${left.sheet} · строка ${left.row}`));
|
||||
tr.appendChild(node('td', '', [left.code, left.name].filter(Boolean).join(' · ')));
|
||||
tr.appendChild(node('td', '', left.unit));
|
||||
const valueCell = node('td');
|
||||
if (state.mode !== 'vor_lsr' && comparison.left.fields?.length) {
|
||||
const price = node('select');
|
||||
const names = {price_no_vat: 'Без НДС', price_with_vat: 'С НДС'};
|
||||
comparison.left.fields.filter(f => names[f]).forEach(f =>
|
||||
price.add(new Option(`${names[f]}: ${left.values[f] ?? '—'}`, f)));
|
||||
price.value = row.left_field;
|
||||
price.disabled = !!viewOwner;
|
||||
price.onchange = async () => {
|
||||
const fields = {...state.price_fields, [row.index]: price.value};
|
||||
try { await update({price_fields: fields}); } catch (e) { showError(e.message); }
|
||||
};
|
||||
valueCell.appendChild(price);
|
||||
} else valueCell.textContent = left.values[row.left_field] ?? '—';
|
||||
tr.appendChild(valueCell);
|
||||
const matchCell = node('td');
|
||||
const match = node('select');
|
||||
match.setAttribute('aria-label', `Соответствие для строки ${left.row}`);
|
||||
match.add(new Option('Нет подтверждённого совпадения', '-1'));
|
||||
(row.candidates || []).forEach(c => match.add(new Option(
|
||||
`${c.file} · ${c.sheet} · ${c.row}: ${c.code} ${c.name} (${c.unit})`, String(c.index))));
|
||||
match.value = row.match_index == null ? '-1' : String(row.match_index);
|
||||
match.disabled = !!viewOwner;
|
||||
match.onchange = async () => {
|
||||
const choices = {...state.choices, [row.index]: Number(match.value)};
|
||||
try { await update({choices}); } catch (e) { showError(e.message); }
|
||||
};
|
||||
matchCell.appendChild(match);
|
||||
if (row.right) matchCell.appendChild(node('small', '',
|
||||
` ${row.right.file} · ${row.right.sheet} · строка ${row.right.row}; ${row.right.values[row.right_field] ?? '—'}`));
|
||||
tr.appendChild(matchCell);
|
||||
tr.appendChild(node('td', '', row.difference ?? row.warning ?? '—'));
|
||||
table.appendChild(tr);
|
||||
});
|
||||
scroll.appendChild(table); panel.appendChild(scroll);
|
||||
const pages = node('div', 'file-compare-pages');
|
||||
const prev = node('button', '', 'Назад'), next = node('button', '', 'Далее');
|
||||
prev.disabled = page === 0; next.disabled = (page + 1) * 50 >= comparison.total_rows;
|
||||
prev.onclick = () => load(page - 1).catch(e => showError(e.message));
|
||||
next.onclick = () => load(page + 1).catch(e => showError(e.message));
|
||||
pages.append(prev, node('span', '', `Страница ${page + 1}`), next);
|
||||
panel.appendChild(pages);
|
||||
}
|
||||
(async () => {
|
||||
try {
|
||||
const r = await authFetch('/api/file-compare/workbooks');
|
||||
const data = await r.json().catch(() => ({}));
|
||||
if (!r.ok) throw new Error(data.detail || 'Не удалось получить список файлов');
|
||||
workbooks = data.workbooks || [];
|
||||
await load();
|
||||
} catch (e) { showError(e.message); }
|
||||
})();
|
||||
return panel;
|
||||
}
|
||||
|
||||
// --- Панель конъюнктурного анализа (срез 7): офферы таблицей + принятая цена ---
|
||||
function addKaPanel(form) {
|
||||
const panel = document.createElement('div');
|
||||
@@ -3836,6 +4003,13 @@ async function loadHistory() {
|
||||
addEstimatePanel({...estimate, _message_id: m.id}, null, host);
|
||||
} catch {}
|
||||
}
|
||||
else if (m.role === 'file_compare') {
|
||||
try {
|
||||
const data = JSON.parse(m.content);
|
||||
const host = aiById.get(data._assistant_id);
|
||||
if (host) addFileComparePanel({...data, _message_id: m.id}, host);
|
||||
} catch {}
|
||||
}
|
||||
else if (m.role === 'ka_form') {
|
||||
try { addKaPanel(JSON.parse(m.content)); } catch {}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user