Files
smeta-web/static/norm-finder.js
T

721 lines
38 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
(() => {
'use strict';
const $ = id => document.getElementById(id);
const token = (() => { try { return localStorage.getItem('token') || ''; } catch { return ''; } })();
const subject = (() => {
try { return JSON.parse(atob(token.split('.')[1].replace(/-/g, '+').replace(/_/g, '/'))).sub || ''; }
catch { return ''; }
})();
const publicMode = !token || !subject;
const tabKey = 'tabId:' + subject;
const tabId = (() => {
try {
let id = localStorage.getItem(tabKey);
if (!id) { id = crypto.randomUUID(); localStorage.setItem(tabKey, id); }
return id;
} catch { return crypto.randomUUID(); }
})();
let active = null;
let savedQuote = null;
let draft = null;
let searchPage = null;
let browsePage = null;
let catalogRows = [];
let requestSeq = 0;
let detailSeq = 0;
let lastFamily = '';
let subjects = [];
let priceZones = [];
const compared = new Map();
const money = n => new Intl.NumberFormat('ru-RU', {minimumFractionDigits:2, maximumFractionDigits:2}).format(n) + ' ₽';
function node(tag, value, className) {
const el = document.createElement(tag);
if (value != null) el.textContent = String(value);
if (className) el.className = className;
return el;
}
function status(message, error=false) {
$('status').textContent = message;
$('status').classList.toggle('error', error);
}
async function api(path, options={}) {
const response = await fetch(path, { ...options, headers: {
Authorization: 'Bearer ' + token, 'X-Tab-Id': tabId,
...(options.body ? {'Content-Type':'application/json'} : {}), ...(options.headers || {})
}});
const data = await response.json().catch(() => ({}));
if (!response.ok) throw new Error(typeof data.detail === 'string' ? data.detail : 'Запрос не выполнен');
return data;
}
function readPath(action) {
return (publicMode ? '/api/public/norm-finder/' : '/api/norm-finder/') + action;
}
function fillSelect(select, rows, valueKey, nameKey, placeholder) {
select.replaceChildren();
select.append(node('option', placeholder));
select.options[0].value = '';
for (const row of rows) {
const option = node('option', row[nameKey]);
option.value = String(row[valueKey]); select.append(option);
}
}
function selectedZone() { return priceZones.find(z => String(z.zone_id) === $('zone').value); }
function setUnits(normUnit) {
const unit = String(normUnit || '').trim();
const match = unit.match(/^(\d+)\s*(.+)$/);
const units = match && Number(match[1]) > 1 ? [match[2], unit] : [unit];
fillSelect($('unit'), units.filter(Boolean).map(value => ({value, name:value})),
'value', 'name', 'Выберите единицу');
if (units[0]) $('unit').value = units[0];
}
function fillPeriods() {
fillSelect($('period'), selectedZone()?.periods || [], 'period_id', 'name', 'Выберите квартал');
if ($('period').options.length === 2) $('period').selectedIndex = 1;
}
async function loadPrices() {
priceZones = [];
fillSelect($('zone'), [], 'zone_id', 'name', 'Выберите зону'); fillPeriods();
if (!$('subject').value) return;
const data = await api('/api/norm-finder/prices?subject_id=' + encodeURIComponent($('subject').value));
priceZones = data.zones || [];
fillSelect($('zone'), priceZones, 'zone_id', 'name', 'Выберите зону');
if (priceZones.length === 1) { $('zone').selectedIndex = 1; fillPeriods(); }
}
function key(item) { return [item.base, item.base_type, item.code].join('|'); }
function baseAlias(item) { return item.base === 'ФЕР-2020' ? '2020' : '2022'; }
function detailUrl(item) {
return readPath('detail') + '?' + new URLSearchParams({base:baseAlias(item),
base_type:item.base_type, code:item.code});
}
async function detailFor(item) { return api(detailUrl(item)); }
async function toggleCompare(item) {
try {
if (compared.has(key(item))) compared.delete(key(item));
else {
if (compared.size >= 3) { status('Сравнить можно не более трёх норм', true); return; }
compared.set(key(item), await detailFor(item));
}
document.querySelectorAll('[data-compare-key]').forEach(control => {
control.textContent = compared.has(control.dataset.compareKey) ? 'Убрать из сравнения' : 'Сравнить';
});
renderComparison();
} catch (e) { status(e.message, true); }
}
function detachDetail() {
$('detail-section').hidden = true;
}
function familyKey(item) {
return [item.base,item.base_type,String(item.code || '').replace(/-\d+$/, '')].join('|');
}
function familyTitle(items) {
const names = items.map(item => String(item.name || '')).filter(Boolean);
if (names.length > 1) {
let common = names[0];
for (const name of names.slice(1)) {
while (common && !name.startsWith(common)) common = common.slice(0, -1);
}
const colon = common.lastIndexOf(':');
const comma = common.lastIndexOf(',');
const end = colon > 25 ? colon : comma > 25 ? comma : -1;
if (end > 0) return common.slice(0, end).trim();
}
return String(items[0]?.section_path || '').split(' > ').at(-1) || names[0] || 'Нормы';
}
function tableRow(className, cells) {
const row = node('tr', null, className);
for (const [value, className] of cells) {
const cell = node('td', value, className);
if (value != null) cell.title = String(value);
row.append(cell);
}
return row;
}
function sectionHeading(label) {
return tableRow('norm-section-heading', [['',''],[label,''],['',''],['',''],['','']]);
}
function selectVariant(row) {
showRows([row]); browsePage = null; searchPage = null; $('more-results').hidden = true;
$('results-title').textContent = 'Вариант таблицы';
$('breadcrumb').textContent = row.base_type + ' › ' + row.code;
document.querySelector('#results .norm-toggle')?.click();
}
function renderSearchItem(item, familyName) {
const row = tableRow('norm-row', [['','norm-code-cell'],['','norm-name'],[item.unit || '—',''],['','num'],
[item.cost != null ? money(item.cost).replace(' ₽', '') : '—','num']]);
row.dataset.key = key(item);
row.cells[4].title = item.cost != null
? 'Базисная стоимость, уровень ' + (item.price_level || 'не указан')
: 'Прямые затраты для этой нормы в индексе не указаны';
const codeCell = row.cells[0];
const workToggle = node('button', '▸', 'norm-toggle');
const resourceToggle = node('button', '▸', 'norm-toggle');
for (const [button, label] of [[workToggle,'состав работ'],[resourceToggle,'состав норматива']]) {
button.type = 'button';
button.setAttribute('aria-label', 'Показать ' + label + ' для ' + item.code);
button.title = 'Показать ' + label;
button.setAttribute('aria-expanded', 'false');
}
codeCell.append(workToggle, resourceToggle, node('span', item.code, 'norm-code'));
const fullName = String(item.name || 'Без наименования');
const shortName = fullName.startsWith(familyName)
? fullName.slice(familyName.length).replace(/^[\s,:;—-]+/, '') || fullName
: fullName;
row.cells[1].textContent = shortName; row.cells[1].title = fullName;
let detailPromise = null, detail = null;
let workOpen = false, resourceOpen = false;
let workRows = [], resourceRows = [];
async function getDetail() {
if (detail) return detail;
if (!detailPromise) detailPromise = detailFor(item).catch(error => { detailPromise = null; throw error; });
detail = await detailPromise;
return detail;
}
function toolsRow() {
const toolRow = tableRow('norm-tools-row', [['',''],['',''],['',''],['',''],['','']]);
const cell = toolRow.cells[1]; cell.colSpan = 4;
while (toolRow.cells.length > 2) toolRow.deleteCell(2);
const tools = node('div', null, 'norm-tools');
const compare = node('button', compared.has(key(item)) ? 'Убрать из сравнения' : 'Сравнить', 'secondary');
compare.type = 'button'; compare.dataset.compareKey = key(item);
compare.addEventListener('click', () => toggleCompare(item));
const variants = node('button', 'Варианты таблицы', 'secondary'); variants.type = 'button';
variants.setAttribute('aria-expanded', 'false');
const variantList = node('div', null, 'variant-list'); variantList.hidden = true;
variants.addEventListener('click', async () => {
if (!variantList.hidden) {
variantList.hidden = true; variants.setAttribute('aria-expanded', 'false'); return;
}
variants.disabled = true;
try {
const familyCode = String(item.code || '').replace(/-\d+$/, '');
const found = await api(readPath('search') + '?' + new URLSearchParams({
q:familyCode, base:baseAlias(item), limit:publicMode ? '8' : '30'}));
const family = (found.items || []).filter(candidate => candidate.base_type === item.base_type
&& candidate.code.startsWith(familyCode + '-'));
variantList.replaceChildren();
for (const candidate of family) {
const line = node('div', null, 'variant-row');
const choice = node('button', candidate.code + ' — ' + candidate.name, 'variant-option');
choice.type = 'button'; choice.addEventListener('click', () => selectVariant(candidate));
const compareVariant = node('button', compared.has(key(candidate)) ? 'Убрать из сравнения' : 'Сравнить',
'secondary small');
compareVariant.type = 'button'; compareVariant.dataset.compareKey = key(candidate);
compareVariant.addEventListener('click', () => toggleCompare(candidate));
line.append(choice, compareVariant); variantList.append(line);
}
if (!family.length) variantList.append(node('p', 'Варианты в каталоге не найдены.', 'hint'));
variantList.hidden = false; variants.setAttribute('aria-expanded', 'true');
} catch (error) { status(error.message, true); }
finally { variants.disabled = false; }
});
tools.append(compare, variants);
if (!publicMode) {
const quoteButton = node('button', 'Расчёт и подборка', 'secondary');
quoteButton.type = 'button'; quoteButton.addEventListener('click', () => openDetail(item));
tools.append(quoteButton);
}
const source = detail?.provenance || {};
if (source.file || source.decree) {
const disclosure = node('details');
disclosure.append(node('summary', 'Источник нормы'));
disclosure.append(node('span', [source.decree,source.file].filter(Boolean).join(' · '), 'hint'));
tools.append(disclosure);
}
tools.append(variantList); cell.append(tools);
return toolRow;
}
function mount() {
for (const child of [...workRows,...resourceRows]) child.remove();
row.after(...(workOpen ? workRows : []), ...(resourceOpen ? resourceRows : []));
}
async function toggle(which) {
const button = which === 'work' ? workToggle : resourceToggle;
const current = which === 'work' ? workOpen : resourceOpen;
if (!current) {
button.disabled = true;
try {
const data = await getDetail();
if (!row.isConnected) return;
if (which === 'work' && !workRows.length) {
workRows = [sectionHeading('Состав работ')];
for (const [index, line] of (data.content || []).entries())
workRows.push(tableRow('norm-work-row', [[index + 1,'num'],[line,''],['',''],['',''],['','']]));
if (workRows.length === 1) workRows.push(tableRow('norm-work-row', [['',''],['Состав работ в индексе не указан',''],['',''],['',''],['','']]));
}
if (which === 'resource' && !resourceRows.length) {
resourceRows = [sectionHeading('Состав норматива')];
for (const resource of data.resources || []) {
const quantity = resource.quantity_note || (resource.quantity ?? '—');
const price = !resource.quantity_note && Number.isFinite(resource.quantity)
&& Number.isFinite(resource.base_price?.cost)
? money(resource.quantity * resource.base_price.cost).replace(' ₽','') : '—';
resourceRows.push(tableRow('norm-resource-row', [[resource.code || '—',''],
[resource.name || '—',''],[resource.unit || '—',''],[quantity,'num'],[price,'num']]));
}
if (resourceRows.length === 1) resourceRows.push(tableRow('norm-resource-row', [['',''],['Ресурсы в индексе не указаны',''],['',''],['',''],['','']]));
resourceRows.push(toolsRow());
}
} catch (error) { status(error.message, true); return; }
finally { button.disabled = false; }
}
if (which === 'work') workOpen = !workOpen;
else resourceOpen = !resourceOpen;
const expanded = which === 'work' ? workOpen : resourceOpen;
button.textContent = expanded ? '▾' : '▸';
button.setAttribute('aria-expanded', String(expanded));
button.setAttribute('aria-label', (expanded ? 'Скрыть ' : 'Показать ')
+ (which === 'work' ? 'состав работ' : 'состав норматива') + ' для ' + item.code);
mount();
}
workToggle.addEventListener('click', () => toggle('work'));
resourceToggle.addEventListener('click', () => toggle('resource'));
return row;
}
function showRows(items, append=false) {
if (!append) { detachDetail(); $('results').replaceChildren(); lastFamily = ''; }
const groups = new Map();
for (const item of items) {
const family = familyKey(item);
if (!groups.has(family)) groups.set(family, []);
groups.get(family).push(item);
}
for (const item of items) {
const family = familyKey(item);
const title = familyTitle(groups.get(family));
if (family !== lastFamily) {
$('results').append(tableRow('norm-family-row', [[String(item.code || '').replace(/-\d+$/, ''),''],
[title,''],['',''],['',''],['','']]));
lastFamily = family;
}
$('results').append(renderSearchItem(item, title));
}
}
function fillBaseTypes() {
const base = $('base').value === '2020' ? 'ФЕР-2020' : 'ГЭСН-2022';
const types = catalogRows.filter(row => row.base === base && row.base_type)
.map(row => ({id:row.base_type,name:row.base_type + ' · ' + row.count + ' норм'}));
if (!types.length) types.push({id:base === 'ФЕР-2020' ? 'ФЕР' : 'ГЭСН',name:'Основной сборник'});
fillSelect($('base-type'), types, 'id', 'name', 'Выберите сборник');
$('base-type').selectedIndex = 1;
}
function treeNode(child) {
const li = node('li');
const button = node('button'); button.type = 'button';
button.append(node('span', '▸', 'tree-arrow'), node('span', child.name));
button.setAttribute('aria-expanded', 'false');
button.addEventListener('click', () => {
if (button.getAttribute('aria-expanded') === 'true') {
const list = li.querySelector(':scope > ul');
if (list) list.hidden = true;
button.setAttribute('aria-expanded', 'false');
button.querySelector('.tree-arrow').textContent = '▸';
} else loadBrowse(child.path, li);
});
li.append(button);
return li;
}
async function loadBrowse(path='', treeItem=null, nextPage=false) {
const base = $('base').value, baseType = $('base-type').value;
if (!base || !baseType) return;
const offset = nextPage ? browsePage?.offset || 0 : 0;
const seq = ++requestSeq;
status('Загружаю нормы сборника…');
$('more-results').disabled = true;
try {
const data = await api(readPath('browse') + '?' + new URLSearchParams({
base,base_type:baseType,path,limit:publicMode ? '20' : '40',offset:String(offset)}));
if (seq !== requestSeq) return;
if (!nextPage) {
searchPage = null;
showRows(data.items || []);
$('results-title').textContent = path ? path.split(' > ').at(-1) : baseType + ' · все нормы';
$('breadcrumb').textContent = [baseType,path].filter(Boolean).join(' › ');
} else showRows(data.items || [], true);
browsePage = {base,baseType,path,offset:offset + (data.items || []).length};
$('result-count').textContent = 'Показано ' + browsePage.offset;
$('more-results').hidden = !data.has_more;
if (treeItem) {
const button = treeItem.querySelector('button');
button.setAttribute('aria-expanded', 'true');
button.querySelector('.tree-arrow').textContent = '▾';
document.querySelectorAll('#tree-root button[aria-current]').forEach(x => x.removeAttribute('aria-current'));
button.setAttribute('aria-current', 'true');
let list = treeItem.querySelector(':scope > ul');
if (!list) { list = node('ul', null, 'tree-list'); treeItem.append(list); }
list.hidden = false;
list.replaceChildren(...(data.children || []).map(treeNode));
} else if (!path) {
const list = node('ul', null, 'tree-list');
list.replaceChildren(...(data.children || []).map(treeNode));
const top = node('div');
const root = node('button', '▾ ' + baseType + ' · разделы', 'tree-root-toggle');
root.type = 'button'; root.setAttribute('aria-expanded', 'true');
root.addEventListener('click', () => {
list.hidden = !list.hidden;
root.setAttribute('aria-expanded', String(!list.hidden));
root.textContent = (list.hidden ? '▸ ' : '▾ ') + baseType + ' · разделы';
});
top.append(root, list);
$('tree-root').replaceChildren(top);
}
status('Откройте строку для состава работ и ресурсов.');
} catch (e) { if (seq === requestSeq) status(e.message, true); }
finally { $('more-results').disabled = false; }
}
async function search(event, nextPage=false) {
event?.preventDefault();
const q = nextPage ? searchPage?.q : $('query').value.trim();
const base = nextPage ? searchPage?.base : $('base').value;
const offset = nextPage ? searchPage?.offset || 0 : 0;
if (q.length < 2) { status('Введите хотя бы два символа', true); return; }
status('Ищу нормы…');
const seq = ++requestSeq;
if (!nextPage) {
searchPage = null;
$('more-results').hidden = true;
}
$('more-results').disabled = true;
try {
const data = await api(readPath('search') + '?' +
new URLSearchParams({q,base,limit:publicMode ? '8' : '12',offset:String(offset)}));
if (seq !== requestSeq) return;
const items = data.items || [];
showRows(items, nextPage);
browsePage = null;
$('results-title').textContent = 'Результаты поиска';
$('breadcrumb').textContent = q;
searchPage = {q, base, offset:offset + items.length};
$('result-count').textContent = 'Показано ' + searchPage.offset;
$('more-results').hidden = !data.has_more || !items.length;
const correction = data.interpreted_query && data.interpreted_query !== q
? 'Поиск по уточнённой формулировке: «' + data.interpreted_query + '». ' : '';
status(items.length ? correction + 'Показано ' + searchPage.offset + ' подходящих норм. Проверьте состав работ перед расчётом.'
: (data.message || 'Нормы не найдены. Уточните работу или шифр.'));
} catch (e) { status(e.message, true); }
finally { $('more-results').disabled = false; }
}
function renderDetail(item) {
$('detail-title').textContent = item.code + ' — ' + (item.name || 'Норма');
const root = $('detail'); root.replaceChildren();
root.append(node('p', item.base + ' · ' + item.base_type + ' · измеритель: ' + (item.unit || '—'), 'meta'));
if (item.section_path) root.append(node('p', item.section_path, 'hint'));
if (item.content?.length) {
root.append(node('h3', 'Состав работ'));
const list = node('ol', null, 'list');
for (const line of item.content) list.append(node('li', line));
root.append(list);
}
root.append(node('h3', 'Ресурсы'));
const scroll = node('div', null, 'scroll');
const table = node('table');
const thead = node('thead'); const tr = node('tr');
for (const label of ['Код','Ресурс','Единица','Расход на измеритель']) tr.append(node('th', label));
thead.append(tr); table.append(thead);
const tbody = node('tbody');
for (const r of item.resources || []) {
const row = node('tr');
row.append(node('td', r.code || '—'), node('td', r.name || '—'), node('td', r.unit || '—'),
node('td', r.quantity_note || (r.quantity ?? 'не задан'), 'num'));
tbody.append(row);
}
table.append(tbody); scroll.append(table); root.append(scroll);
const provenance = item.provenance || {};
const source = [provenance.decree, provenance.file].filter(Boolean).join(' · ');
const sourcePanel = node('details');
sourcePanel.append(node('summary', 'Источник нормы'));
sourcePanel.append(node('p', source || 'Источник в индексе не указан', 'hint'));
if (provenance.dataset) sourcePanel.append(node('p', 'Набор данных: ' + provenance.dataset, 'hint'));
if (provenance.url) {
try {
const url = new URL(provenance.url);
if (url.protocol === 'https:' && url.hostname === 'fgiscs.minstroyrf.ru') {
const link = node('a', 'Открыть официальный набор данных');
link.href = url.href; link.target = '_blank'; link.rel = 'noopener noreferrer';
sourcePanel.append(link);
}
} catch {}
}
root.append(sourcePanel);
if (item.prices?.cost != null) root.append(node('p', 'Базисная стоимость: ' + money(item.prices.cost) +
' (уровень ' + (item.price_level || 'не указан') + '). Это не цена выбранного квартала.', 'notice'));
}
async function openDetail(item) {
const seq = ++detailSeq;
const listing = requestSeq;
status('Загружаю состав нормы…');
try {
const loaded = await detailFor(item);
if (seq !== detailSeq || listing !== requestSeq) return;
active = loaded; savedQuote = null;
$('quote').replaceChildren(); renderDetail(active);
setUnits(active.unit);
$('calc').disabled = !active.current_price_supported;
if (active.calculation_limitation) $('quote').append(node('p', active.calculation_limitation, 'notice'));
$('detail-section').hidden = false;
$('detail-section').scrollIntoView({behavior:'smooth', block:'start'});
status('Состав нормы загружен. Сверьте измеритель и ресурсы.');
} catch (e) { status(e.message, true); }
}
function renderComparison() {
$('compare-section').hidden = compared.size === 0;
const items = [...compared.values()];
const units = new Set(items.map(i => i.unit || ''));
$('compare-warning').hidden = units.size < 2;
$('compare-warning').textContent = 'Измерители различаются. Сравнение стоимости без явного приведения объёма некорректно.';
const resourceSets = items.map(item => new Set((item.resources || []).map(row => row.code).filter(Boolean)));
const cards = items.map(item => {
const current = resourceSets[items.indexOf(item)];
const card = node('article', null, 'card');
card.append(node('div', item.code, 'code'), node('h3', item.name),
node('p', item.base + ' · ' + item.base_type + ' · ' + (item.unit || 'без измерителя'), 'meta'));
if (item.content?.length) card.append(node('p', 'Состав: ' + item.content.join('; '), 'hint'));
card.append(node('p', 'Ресурсов: ' + (item.resources || []).length, 'hint'));
if (items.length > 1) {
const distinct = [...current].filter(code => resourceSets.some(other => other !== current && !other.has(code)));
card.append(node('p', distinct.length
? 'Отличающиеся ресурсы: ' + distinct.join(', ')
: 'Все ресурсы этой нормы встречаются и в выбранных вариантах.', 'notice'));
}
for (const row of item.resources || []) card.append(node('p', (row.code || '—') + ' · ' +
(row.name || '—') + ' · ' + (row.quantity_note || (row.quantity ?? '—')), 'hint'));
return card;
});
$('comparison').replaceChildren(...cards);
}
function renderQuote(data) {
savedQuote = data;
const result = data.result || {};
const root = $('quote'); root.replaceChildren();
root.append(node('p', [result.code, result.quantity != null ? result.quantity + ' ' + (result.unit || '') : '',
result.zone, result.period].filter(Boolean).join(' · '), 'meta'));
if (result.complete && result.total != null) {
root.append(node('p', 'Предварительный итог', 'meta'), node('div', money(result.total), 'result-amount'));
} else {
root.append(node('p', 'Расчёт неполный — готовую смету по этим данным получить нельзя.', 'notice'));
if (result.accounted != null) root.append(node('p', 'Учтённая часть', 'meta'),
node('div', money(result.accounted), 'result-amount'));
}
if (result.message) root.append(node('p', result.message, 'notice'));
for (const missing of result.missing || []) root.append(node('p', 'Не рассчитано: ' +
(missing.reason || missing.code || 'позиция'), 'hint'));
if (result.unpriced?.length) root.append(node('p', 'Часть ресурсов без цены в выбранной форме.', 'hint'));
if (result.limits_note) root.append(node('p', result.limits_note, 'hint'));
const link = node('a', 'Ссылка на этот расчёт');
link.href = '/podbor?quote=' + encodeURIComponent(data.id);
root.append(link);
}
function draftPosition(item) {
const quantity = Number($('qty').value);
if (!Number.isFinite(quantity) || quantity <= 0 || !$('qty').checkValidity() || !$('unit').value)
throw new Error('Укажите положительный объём и измеритель нормы');
return {base:baseAlias(item),base_type:item.base_type,code:item.code,
quantity,unit:$('unit').value};
}
function renderDraft() {
$('draft-section').hidden = !draft;
const root = $('draft-positions'); root.replaceChildren();
if (!draft) return;
for (const [index, position] of draft.positions.entries()) {
const row = node('div', null, 'draft-row');
row.append(node('span', position.base_type + ' ' + position.code + ' — ' + (position.name || position.code),
'draft-name'));
const label = node('label', null);
label.append(node('span', 'Объём · ' + position.unit));
const input = node('input'); input.type = 'number'; input.min = '0.000001';
input.max = '1000000'; input.step = 'any'; input.value = String(position.quantity);
input.setAttribute('aria-label', 'Объём для ' + position.code);
input.addEventListener('change', async () => {
const quantity = Number(input.value);
if (!input.checkValidity() || !Number.isFinite(quantity) || quantity <= 0) {
input.value = String(position.quantity); status('Укажите положительный объём', true); return;
}
try { await saveDraft(draft.positions.map((p, i) => i === index ? {...p,quantity} : p)); }
catch (e) { renderDraft(); status(e.message, true); }
});
label.append(input); row.append(label);
const remove = node('button', 'Убрать', 'secondary small'); remove.type = 'button';
remove.disabled = draft.positions.length === 1;
remove.addEventListener('click', async () => {
try { await saveDraft(draft.positions.filter((_, i) => i !== index)); }
catch (e) { status(e.message, true); }
});
row.append(remove); root.append(row);
}
$('draft-chat').href = '/?norm_draft=' + encodeURIComponent(draft.id);
const output = $('draft-result'); output.replaceChildren();
const calculation = draft.calculation;
if (!calculation) return;
output.append(node('p', calculation.zone + ' · ' + calculation.period, 'meta'));
if (calculation.complete && calculation.total != null)
output.append(node('p', 'Предварительный итог всей подборки', 'meta'),
node('div', money(calculation.total), 'result-amount'));
else {
output.append(node('p', 'Расчёт неполный: итог всей подборки не определён.', 'notice'));
if (calculation.accounted != null)
output.append(node('p', 'Стоимость только учтённой части', 'meta'),
node('div', money(calculation.accounted), 'result-amount'));
}
for (const line of calculation.lines || []) {
const result = line.result || {};
output.append(node('p', line.position.code + ' · ' +
(result.complete && result.total != null ? money(result.total)
: result.message || 'Часть ресурсов не оценена'), 'hint'));
}
}
async function saveDraft(positions) {
const path = draft ? '/api/norm-finder/drafts/' + draft.id : '/api/norm-finder/drafts';
const data = await api(path, {method:draft ? 'PUT' : 'POST',
body:JSON.stringify({positions,...(draft ? {revision:draft.revision} : {})})});
draft = data;
try { localStorage.setItem('normDraftId:' + tabId, String(data.id)); } catch {}
history.replaceState(null, '', '/podbor?draft=' + encodeURIComponent(data.id));
renderDraft();
status('Подборка сохранена: ' + data.positions.length + ' поз.');
return data;
}
async function addToDraft() {
if (!active) throw new Error('Сначала откройте норму');
const position = draftPosition(active);
const rows = draft ? [...draft.positions] : [];
const current = rows.findIndex(row => row.base === position.base
&& row.base_type === position.base_type && row.code === position.code);
if (current >= 0) rows[current] = position;
else rows.push(position);
return saveDraft(rows);
}
async function calculateDraft() {
if (!draft) return;
if (!$('subject').value || !$('zone').value || !$('period').value) {
status('Для подборки выберите регион, зону и квартал выше', true); return;
}
$('draft-calc').disabled = true; status('Считаю подборку…');
try {
draft = await api('/api/norm-finder/drafts/' + draft.id + '/calculate', {
method:'POST', body:JSON.stringify({revision:draft.revision,
subject_id:Number($('subject').value),zone_id:Number($('zone').value),
period_id:Number($('period').value)})});
renderDraft(); status('Подборка пересчитана по выбранным ценам.');
} catch (e) { status(e.message, true); }
finally { $('draft-calc').disabled = false; }
}
async function calculate() {
if (!active) return;
const quantity = Number($('qty').value);
if (!Number.isFinite(quantity) || quantity <= 0 || !$('qty').checkValidity()
|| !$('subject').value || !$('zone').value || !$('period').value) {
status('Укажите регион, зону, квартал и положительный объём', true); return;
}
const selection = {base:baseAlias(active),base_type:active.base_type,code:active.code,
quantity,unit:$('unit').value,subject_id:Number($('subject').value),
zone_id:Number($('zone').value),period_id:Number($('period').value)};
$('calc').disabled = true; status('Считаю по выбранной форме…');
try {
const path = savedQuote ? '/api/norm-finder/quotes/' + savedQuote.id : '/api/norm-finder/calculate';
const body = {...selection, ...(savedQuote ? {revision:savedQuote.revision} : {})};
const data = await api(path, {method:'POST', body:JSON.stringify(body)});
renderQuote(data);
history.replaceState(null, '', '/podbor?quote=' + encodeURIComponent(data.id));
status('Расчёт обновлён в этой карточке.');
} catch (e) { status(e.message, true); }
finally { $('calc').disabled = false; }
}
async function toChat() {
try { const saved = draft || await addToDraft(); location.href = '/?norm_draft=' + encodeURIComponent(saved.id); }
catch (e) { status(e.message, true); }
}
async function restoreDraft() {
const fromUrl = new URLSearchParams(location.search).get('draft');
const savedId = (() => { try { return localStorage.getItem('normDraftId:' + tabId); } catch { return ''; } })();
const id = Number(fromUrl || savedId);
if (!Number.isSafeInteger(id) || id < 1) return false;
try {
draft = await api('/api/norm-finder/drafts/' + id);
renderDraft();
const first = draft.positions?.[0];
if (first) {
const row = {base:first.base === '2020' ? 'ФЕР-2020' : 'ГЭСН-2022',
base_type:first.base_type,code:first.code,name:first.name,unit:first.unit};
showRows([row]);
await openDetail(row);
}
if (first) { $('qty').value = String(first.quantity); $('unit').value = first.unit; }
const selection = draft.price_selection || {};
if (selection.subject_id) {
$('subject').value = String(selection.subject_id);
await loadPrices(); $('zone').value = String(selection.zone_id); fillPeriods();
$('period').value = String(selection.period_id);
}
status('Сохранённая подборка загружена.');
return true;
} catch (e) {
if (!fromUrl) { try { localStorage.removeItem('normDraftId:' + tabId); } catch {} }
else status(e.message, true);
return false;
}
}
async function restoreQuote() {
const id = Number(new URLSearchParams(location.search).get('quote'));
if (!Number.isSafeInteger(id) || id < 1) return;
try {
const data = await api('/api/norm-finder/quotes/' + id);
const selection = data.selection || {};
active = await detailFor({base:selection.base === '2020' ? 'ФЕР-2020' : 'ГЭСН-2022',
base_type:selection.base_type, code:selection.code});
showRows([active]);
renderDetail(active); $('detail-section').hidden = false;
$('calc').disabled = !active.current_price_supported;
$('qty').value = String(selection.quantity); setUnits(active.unit); $('unit').value = selection.unit;
$('subject').value = String(selection.subject_id);
await loadPrices(); $('zone').value = String(selection.zone_id); fillPeriods();
$('period').value = String(selection.period_id); renderQuote(data);
status('Сохранённый расчёт загружен.');
} catch (e) { status(e.message, true); }
}
async function init() {
if (publicMode) { $('auth-notice').hidden = false; $('quote-panel').hidden = true; }
try {
const data = await api(readPath('catalog'));
const bases = [...new Set((data.bases || []).map(x => x.base))];
fillSelect($('base'), bases.map(b => ({id:b === 'ФЕР-2020' ? '2020' : '2022',name:b})),
'id', 'name', 'Выберите базу');
if (bases.length) $('base').selectedIndex = 1;
catalogRows = data.bases || [];
fillBaseTypes();
subjects = data.subjects || [];
if (!publicMode) fillSelect($('subject'), subjects, 'id', 'name', 'Выберите регион');
if (!bases.length) status('Нормативная база пока недоступна', true);
await loadBrowse();
if (!publicMode && !(await restoreDraft())) await restoreQuote();
} catch (e) { status(e.message, true); }
}
$('search-form').addEventListener('submit', search);
$('more-results').addEventListener('click', event => browsePage
? loadBrowse(browsePage.path, null, true) : search(event, true));
$('base').addEventListener('change', () => { fillBaseTypes(); loadBrowse(); });
$('base-type').addEventListener('change', () => loadBrowse());
$('catalog-mobile').addEventListener('click', () => {
const tree = $('catalog-tree');
tree.hidden = !tree.hidden;
$('catalog-mobile').setAttribute('aria-expanded', String(!tree.hidden));
});
if (matchMedia('(max-width:760px)').matches) $('catalog-tree').hidden = true;
document.querySelectorAll('[data-query]').forEach(button => button.addEventListener('click', () => {
$('query').value = button.dataset.query; $('search-form').requestSubmit();
}));
$('subject').addEventListener('change', () => loadPrices().catch(e => status(e.message, true)));
$('zone').addEventListener('change', fillPeriods);
for (const id of ['subject', 'zone', 'period', 'qty', 'unit']) {
$(id).addEventListener('change', () => {
if (savedQuote) status('Параметры изменены. Нажмите «Рассчитать», чтобы обновить сумму.');
});
}
$('calc').addEventListener('click', calculate);
$('add-draft').addEventListener('click', () => addToDraft().catch(e => status(e.message, true)));
$('draft-calc').addEventListener('click', calculateDraft);
$('to-chat').addEventListener('click', toChat);
init();
})();