Expose and compare variants of selected norm tables
This commit is contained in:
@@ -43,6 +43,11 @@
|
||||
.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; }
|
||||
.variant-list { display:grid; gap:5px; border-top:1px solid var(--line); padding-top:10px; }
|
||||
.variant-row { display:flex; flex-wrap:wrap; gap:5px; align-items:start; }
|
||||
.variant-option { flex:1 1 220px; text-align:left; border:1px solid var(--line); border-radius:8px;
|
||||
background:var(--card); padding:8px 10px; color:var(--text); font-size:.84rem; }
|
||||
.variant-option:hover,.variant-option:focus-visible { border-color:var(--accent); background:#e9f4f1; }
|
||||
.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; }
|
||||
|
||||
+58
-9
@@ -79,6 +79,20 @@
|
||||
}
|
||||
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 renderSearchItem(item) {
|
||||
const card = node('article', null, 'card');
|
||||
const head = node('div', null, 'card-head');
|
||||
@@ -93,18 +107,43 @@
|
||||
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 () => {
|
||||
compare.dataset.compareKey = key(item);
|
||||
compare.addEventListener('click', () => toggleCompare(item));
|
||||
const familyCode = String(item.code || '').replace(/-\d{2}$/, '');
|
||||
const variants = node('button', 'Варианты таблицы', 'secondary small');
|
||||
variants.type = 'button';
|
||||
variants.setAttribute('aria-expanded', 'false');
|
||||
const variantList = node('div', null, 'variant-list');
|
||||
variantList.hidden = true;
|
||||
variants.addEventListener('click', async () => {
|
||||
if (variants.getAttribute('aria-expanded') === 'true') {
|
||||
variantList.hidden = true; variants.setAttribute('aria-expanded', 'false'); return;
|
||||
}
|
||||
variants.disabled = true;
|
||||
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));
|
||||
const found = await api('/api/norm-finder/search?' + new URLSearchParams({
|
||||
q:familyCode, base:baseAlias(item), limit:'30'}));
|
||||
const family = (found.items || []).filter(row => row.base_type === item.base_type
|
||||
&& row.code.startsWith(familyCode + '-'));
|
||||
variantList.replaceChildren();
|
||||
if (!family.length) variantList.append(node('p', 'Варианты в каталоге не найдены.', 'hint'));
|
||||
for (const row of family) {
|
||||
const line = node('div', null, 'variant-row');
|
||||
const button = node('button', row.code + ' — ' + row.name + ' · ' + (row.unit || 'измеритель не указан'),
|
||||
'variant-option');
|
||||
button.type = 'button'; button.addEventListener('click', () => openDetail(row));
|
||||
const compareVariant = node('button', compared.has(key(row)) ? 'Убрать из сравнения' : 'Сравнить',
|
||||
'secondary small');
|
||||
compareVariant.type = 'button';
|
||||
compareVariant.dataset.compareKey = key(row);
|
||||
compareVariant.addEventListener('click', () => toggleCompare(row));
|
||||
line.append(button, compareVariant); variantList.append(line);
|
||||
}
|
||||
compare.textContent = compared.has(key(item)) ? 'Убрать из сравнения' : 'Сравнить';
|
||||
renderComparison();
|
||||
variantList.hidden = false; variants.setAttribute('aria-expanded', 'true');
|
||||
} catch (e) { status(e.message, true); }
|
||||
finally { variants.disabled = false; }
|
||||
});
|
||||
actions.append(open, compare); card.append(actions);
|
||||
actions.append(open, compare, variants); card.append(actions, variantList);
|
||||
return card;
|
||||
}
|
||||
async function search(event) {
|
||||
@@ -118,7 +157,9 @@
|
||||
const items = data.items || [];
|
||||
$('results').replaceChildren(...items.map(renderSearchItem));
|
||||
$('results-section').hidden = !items.length;
|
||||
status(items.length ? 'Показано ' + items.length + ' подходящих норм. Проверьте состав работ перед расчётом.'
|
||||
const correction = data.interpreted_query && data.interpreted_query !== q
|
||||
? 'Поиск по уточнённой формулировке: «' + data.interpreted_query + '». ' : '';
|
||||
status(items.length ? correction + 'Показано ' + items.length + ' подходящих норм. Проверьте состав работ перед расчётом.'
|
||||
: (data.message || 'Нормы не найдены. Уточните работу или шифр.'));
|
||||
} catch (e) { status(e.message, true); }
|
||||
}
|
||||
@@ -172,12 +213,20 @@
|
||||
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;
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
"""The real norm finder lets a person inspect nearby variants in the same table."""
|
||||
import functools
|
||||
import http.server
|
||||
import shutil
|
||||
import socketserver
|
||||
import sys
|
||||
import threading
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
pytest.importorskip("playwright.sync_api")
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
||||
from test_password_reset_ui import browser # noqa: E402,F401
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def site(tmp_path_factory):
|
||||
root = tmp_path_factory.mktemp("norm-finder-ui")
|
||||
static = root / "static"
|
||||
static.mkdir()
|
||||
finder = root / "podbor"
|
||||
finder.mkdir()
|
||||
source = Path(__file__).resolve().parents[1] / "static"
|
||||
shutil.copy2(source / "norm-finder.html", finder / "index.html")
|
||||
shutil.copy2(source / "norm-finder.js", static / "norm-finder.js")
|
||||
handler = functools.partial(http.server.SimpleHTTPRequestHandler, directory=str(root))
|
||||
|
||||
class Quiet(socketserver.ThreadingTCPServer):
|
||||
allow_reuse_address = True
|
||||
daemon_threads = True
|
||||
|
||||
server = Quiet(("127.0.0.1", 0), handler)
|
||||
threading.Thread(target=server.serve_forever, daemon=True).start()
|
||||
yield f"http://127.0.0.1:{server.server_address[1]}/podbor/"
|
||||
server.shutdown()
|
||||
|
||||
|
||||
def test_family_variants_can_be_opened_and_compared_on_phone(browser, site):
|
||||
page = browser.new_page(viewport={"width": 390, "height": 844})
|
||||
page.add_init_script("""(() => {
|
||||
localStorage.setItem('token', 'x.eyJzdWIiOiJ0ZXN0QHgifQ.y');
|
||||
const base = {base:'ГЭСН-2022',base_type:'ГЭСН',unit:'100 м2'};
|
||||
const a = {...base,code:'11-01-011-12',name:'Полусухая цементно-песчаная стяжка'};
|
||||
const b = {...base,code:'11-01-011-01',name:'Цементная стяжка толщиной 20 мм'};
|
||||
window.fetch = async url => {
|
||||
const u = new URL(url, location.href);
|
||||
let value;
|
||||
if (u.pathname.endsWith('/catalog')) value={bases:[{base:'ГЭСН-2022',count:56192}],subjects:[]};
|
||||
else if (u.pathname.endsWith('/search')) value={items:u.searchParams.get('q')==='11-01-011'?[a,b]:[a]};
|
||||
else if (u.pathname.endsWith('/detail')) {
|
||||
const chosen=u.searchParams.get('code')===a.code?a:b;
|
||||
value={...chosen,content:['Устройство стяжки'],resources:[{
|
||||
code:chosen===a?'A-1':'B-1',name:'Ресурс',unit:'шт',quantity:1}],
|
||||
provenance:{decree:'Источник'},current_price_supported:false};
|
||||
}
|
||||
else value={};
|
||||
return new Response(JSON.stringify(value),{status:200,headers:{'Content-Type':'application/json'}});
|
||||
};
|
||||
})()""")
|
||||
page.goto(site)
|
||||
page.locator('#query').fill('стяжка пола')
|
||||
page.locator('#search-form button[type="submit"]').click()
|
||||
page.locator('button', has_text='Варианты таблицы').click()
|
||||
options = page.locator('.variant-option')
|
||||
options.first.wait_for()
|
||||
assert options.count() == 2
|
||||
page.locator('.variant-row').nth(0).locator('button').last.click()
|
||||
page.locator('.variant-row').nth(1).locator('button').last.click()
|
||||
page.locator('#comparison .card').nth(1).wait_for()
|
||||
assert 'Отличающиеся ресурсы' in page.locator('#comparison').inner_text()
|
||||
options.filter(has_text='11-01-011-01').click()
|
||||
page.locator('#detail-title', has_text='11-01-011-01').wait_for()
|
||||
assert page.locator('#detail').inner_text().find('100 м2') >= 0
|
||||
assert page.evaluate('document.documentElement.scrollWidth <= window.innerWidth')
|
||||
page.close()
|
||||
Reference in New Issue
Block a user