Implement source-backed norm finder and saved price previews

This commit is contained in:
anor
2026-12-03 22:56:12 +10:00
parent ed33bd597c
commit 09d092d9b1
12 changed files with 926 additions and 1 deletions
+1
View File
@@ -805,6 +805,7 @@ html { color-scheme: light; }
<div class="account-menu-email" id="account-menu-email"></div>
<button type="button" role="menuitem" onclick="closeAccountMenu(); location.href='/stats'">Статистика</button>
<button type="button" role="menuitem" onclick="closeAccountMenu(); listFiles()">Файлы</button>
<button type="button" role="menuitem" onclick="closeAccountMenu(); location.href='/podbor'">Подбор норм</button>
<button type="button" role="menuitem" id="btn-invite" aria-expanded="false" aria-controls="invite-panel"
onclick="closeAccountMenu(); toggleInvitePanel()">Пригласить коллегу</button>
<button type="button" role="menuitem" id="btn-device"
+105
View File
@@ -0,0 +1,105 @@
<!doctype html>
<html lang="ru">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Подбор норм — Инфосмета</title>
<style>
:root { color-scheme: light; --bg:#f4f2ee; --card:#fff; --text:#272824; --muted:#626760;
--line:#d8d9d2; --accent:#176c63; --bad:#a83c31; --warn:#fff5da; }
* { box-sizing:border-box; }
body { margin:0; background:var(--bg); color:var(--text); font:16px/1.48 system-ui,-apple-system,Arial,sans-serif; }
button,input,select { font:inherit; }
button { cursor:pointer; }
:focus-visible { outline:3px solid #65aba4; outline-offset:2px; }
a { color:var(--accent); }
.wrap { max-width:1240px; margin:auto; padding:24px clamp(16px,3vw,40px) 64px; }
header { display:flex; align-items:center; justify-content:space-between; gap:16px; margin-bottom:32px; }
.brand { font-weight:750; font-size:1.15rem; text-decoration:none; color:var(--text); }
h1 { font-size:clamp(2rem,4vw,3rem); line-height:1.1; margin:0 0 12px; }
h2 { font-size:1.35rem; margin:0 0 12px; }
h3 { font-size:1.05rem; margin:0 0 8px; }
p { margin:0 0 12px; }
.intro { max-width:760px; color:var(--muted); margin-bottom:22px; }
.panel,.card { background:var(--card); border:1px solid var(--line); border-radius:14px; padding:20px; }
.search-row,.controls,.actions { display:flex; gap:10px; align-items:end; flex-wrap:wrap; }
label { display:grid; gap:5px; font-size:.84rem; color:var(--muted); font-weight:600; }
input,select { min-height:42px; padding:8px 11px; color:var(--text); background:var(--card);
border:1px solid var(--line); border-radius:8px; max-width:100%; }
#query { flex:1 1 330px; }
.search-row label:has(#query) { flex:1 1 330px; }
.primary,.secondary { min-height:42px; padding:8px 16px; border-radius:8px; font-weight:650; }
.primary { background:var(--accent); border:1px solid var(--accent); color:#fff; }
.secondary { background:var(--card); border:1px solid var(--line); color:var(--text); }
.small { min-height:34px; padding:5px 10px; font-size:.84rem; }
.examples { display:flex; gap:8px; flex-wrap:wrap; align-items:center; margin-top:14px; color:var(--muted); font-size:.85rem; }
.examples button { border:0; border-bottom:1px dotted var(--accent); background:transparent; color:var(--accent); padding:0; }
.status { min-height:24px; margin:14px 0; color:var(--muted); }
.status.error { color:var(--bad); }
.results { display:grid; grid-template-columns:repeat(auto-fit,minmax(min(100%,340px),1fr)); gap:14px; }
.card { display:flex; flex-direction:column; gap:7px; }
.card-head { display:flex; align-items:start; justify-content:space-between; gap:12px; }
.code { color:var(--accent); font-weight:750; font-variant-numeric:tabular-nums; }
.badge { background:#e9f4f1; color:#155f56; padding:3px 8px; border-radius:999px; font-size:.72rem; white-space:nowrap; }
.meta,.hint { font-size:.82rem; color:var(--muted); }
.card .actions { margin-top:auto; padding-top:7px; }
.section { margin-top:28px; }
.detail-grid { display:grid; grid-template-columns:minmax(0,1.4fr) minmax(270px,.8fr); gap:18px; }
.list { margin:0; padding-left:20px; }
.scroll { max-width:100%; overflow:auto; }
table { border-collapse:collapse; width:100%; font-size:.86rem; }
th,td { border-bottom:1px solid var(--line); text-align:left; padding:8px; vertical-align:top; }
th { color:var(--muted); font-weight:650; }
.num { text-align:right; font-variant-numeric:tabular-nums; white-space:nowrap; }
.comparison { display:grid; grid-template-columns:repeat(3,minmax(0,1fr)); gap:12px; }
.comparison .card { overflow-wrap:anywhere; }
.notice { background:var(--warn); border-radius:9px; padding:10px 12px; font-size:.86rem; }
.result-amount { font-size:1.5rem; font-weight:750; font-variant-numeric:tabular-nums; }
.quote-controls label { min-width:140px; }
.quote-controls #qty { width:125px; }
[hidden] { display:none !important; }
@media (max-width:760px) { .wrap { padding:18px 14px 40px; } header { margin-bottom:24px; }
.detail-grid,.comparison { grid-template-columns:1fr; } .panel,.card { padding:15px; }
.search-row > *, .controls > label { flex:1 1 100%; } .search-row button { width:100%; }
.quote-controls label { min-width:0; } }
</style>
</head>
<body>
<main class="wrap">
<header><a class="brand" href="/">ИНФОСМЕТА</a><a href="/">Вернуться в чат</a></header>
<h1>Подбор норм</h1>
<p class="intro">Найдите работу по названию или шифру, проверьте состав и измеритель, сравните варианты. Цены считаются только по доступной форме выбранной зоны и квартала.</p>
<div id="auth-notice" class="notice" hidden>Чтобы искать нормы, <a href="/">войдите в Инфосмету</a>.</div>
<form id="search-form" class="panel">
<div class="search-row">
<label for="query">Работа или шифр<input id="query" type="search" maxlength="160" placeholder="Например, монтаж пожарного извещателя" required></label>
<label for="base">Нормативная база<select id="base" aria-label="Нормативная база"></select></label>
<button class="primary" type="submit">Найти нормы</button>
</div>
<div class="examples">Примеры: <button type="button" data-query="монтаж извещателя">монтаж извещателя</button>
<button type="button" data-query="устройство стяжки пола">устройство стяжки пола</button>
<button type="button" data-query="10-08-002-02">10-08-002-02</button></div>
</form>
<div id="status" class="status" role="status" aria-live="polite"></div>
<section id="results-section" class="section" hidden><h2>Подходящие нормы</h2><div id="results" class="results"></div></section>
<section id="detail-section" class="section" hidden><div class="detail-grid">
<div class="panel"><h2 id="detail-title">Состав нормы</h2><div id="detail"></div></div>
<div class="panel"><h2>Предварительный расчёт</h2><p class="hint">Объём вводится в выбранной единице. Недостающие цены и затраты будут отмечены.</p>
<div class="controls quote-controls">
<label for="subject">Регион<select id="subject"></select></label>
<label for="zone">Ценовая зона<select id="zone"></select></label>
<label for="period">Квартал<select id="period"></select></label>
<label for="qty">Объём<input id="qty" type="number" min="0.000001" max="1000000" step="any" value="1"></label>
<label for="unit">Единица<select id="unit"></select></label>
</div>
<div class="actions" style="margin-top:16px"><button id="calc" type="button" class="primary">Рассчитать</button>
<button id="to-chat" type="button" class="secondary">Перенести в чат</button></div>
<div id="quote" style="margin-top:16px" aria-live="polite"></div>
</div>
</div></section>
<section id="compare-section" class="section" hidden><h2>Сравнение норм</h2><p id="compare-warning" class="notice" hidden></p>
<div id="comparison" class="comparison"></div></section>
</main>
<script src="/static/norm-finder.js" defer></script>
</body>
</html>
+285
View File
@@ -0,0 +1,285 @@
(() => {
'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 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 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 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 '/api/norm-finder/detail?' + new URLSearchParams({base:baseAlias(item),
base_type:item.base_type, code:item.code});
}
async function detailFor(item) { return api(detailUrl(item)); }
function renderSearchItem(item) {
const card = node('article', null, 'card');
const head = node('div', null, 'card-head');
head.append(node('span', item.code, 'code'), node('span', item.base_type, 'badge'));
card.append(head, node('h3', item.name || 'Без наименования'),
node('p', (item.base || '') + ' · измеритель: ' + (item.unit || 'не указан'), 'meta'));
if (item.section_path) card.append(node('p', item.section_path, 'hint'));
if (item.match_reason) card.append(node('p', item.match_reason, 'hint'));
if (item.provenance?.decree) card.append(node('p', 'Источник: ' + item.provenance.decree, 'hint'));
const actions = node('div', null, 'actions');
const open = node('button', 'Открыть состав', 'primary small');
open.type = 'button'; open.addEventListener('click', () => openDetail(item));
const compare = node('button', compared.has(key(item)) ? 'Убрать из сравнения' : 'Сравнить', 'secondary small');
compare.type = 'button';
compare.addEventListener('click', async () => {
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));
}
compare.textContent = compared.has(key(item)) ? 'Убрать из сравнения' : 'Сравнить';
renderComparison();
} catch (e) { status(e.message, true); }
});
actions.append(open, compare); card.append(actions);
return card;
}
async function search(event) {
event?.preventDefault();
const q = $('query').value.trim(), base = $('base').value;
if (q.length < 2) { status('Введите хотя бы два символа', true); return; }
status('Ищу нормы…');
$('results-section').hidden = true; $('detail-section').hidden = true;
try {
const data = await api('/api/norm-finder/search?' + new URLSearchParams({q,base,limit:'12'}));
const items = data.items || [];
$('results').replaceChildren(...items.map(renderSearchItem));
$('results-section').hidden = !items.length;
status(items.length ? 'Показано ' + items.length + ' подходящих норм. Проверьте состав работ перед расчётом.'
: (data.message || 'Нормы не найдены. Уточните работу или шифр.'));
} catch (e) { status(e.message, true); }
}
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(' · ');
root.append(node('p', source ? 'Источник: ' + source : 'Источник в индексе не указан', 'hint'));
if (item.prices?.cost != null) root.append(node('p', 'Базисная стоимость: ' + money(item.prices.cost) +
' (уровень ' + (item.price_level || 'не указан') + '). Это не цена выбранного квартала.', 'notice'));
}
async function openDetail(item) {
status('Загружаю состав нормы…');
try {
active = await detailFor(item); 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 cards = items.map(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'));
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);
}
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; }
}
function toChat() {
if (!active) return;
const prompt = 'Посчитай ' + ($('qty').value || '1') + ' ' + ($('unit').value || active.unit || '') +
' по норме ' + active.base_type + ' ' + active.code +
(selectedZone() && $('period').value ? ', ' + selectedZone().name + ', ' +
$('period').selectedOptions[0].textContent : '') + '. Проверь состав ресурсов.';
try { localStorage.setItem('draft_' + tabId, prompt); }
catch { status('Не удалось сохранить черновик для чата', true); return; }
location.href = '/';
}
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});
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 (!token || !subject) { $('auth-notice').hidden = false; $('search-form').hidden = true; return; }
try {
const data = await api('/api/norm-finder/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;
subjects = data.subjects || [];
fillSelect($('subject'), subjects, 'id', 'name', 'Выберите регион');
if (!bases.length) status('Нормативная база пока недоступна', true);
await restoreQuote();
} catch (e) { status(e.message, true); }
}
$('search-form').addEventListener('submit', search);
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);
$('to-chat').addEventListener('click', toChat);
init();
})();