Show norm cost breakdown and reference rates in finder

This commit is contained in:
anor
2026-12-04 22:51:01 +10:00
parent 4bb95e757f
commit 011c57df9e
9 changed files with 261 additions and 39 deletions
+1
View File
@@ -405,6 +405,7 @@ def find_works(*, query: str, base: str | None = None,
"price_level": r["price_level"], "section_path": r["section_path"],
"content": r["content"],
"cost": r["cost"], "salary": r["salary"],
"salary_mach": r["salary_mach"],
"machines": r["machines"], "materials": r["materials"],
"provenance": _provenance(srcs.get(r["source_id"]))}
for r in diverse]
+6 -4
View File
@@ -555,7 +555,7 @@ MAX_MESSAGE_LEN = 10_000
# ⚠️ Версия UI — единый источник. БАМПАТЬ ПРИ КАЖДОМ ДЕПЛОЕ (формат: YYYY-MM-DD + буква).
# Фронт берёт её через GET /api/version (chat.html + admin.html, элемент .app-version).
APP_VERSION = "2026-12-04g"
APP_VERSION = "2026-12-04h"
# Audit: path → action name mapping
_AUDIT_MAP = [
@@ -2420,8 +2420,9 @@ async def norm_finder_catalog(request: Request):
sid = row.get("subject_id")
if isinstance(sid, int) and not isinstance(sid, bool):
subjects[sid] = row.get("subject_name") or f"Субъект {sid}"
return {"bases": bases, "subjects": [{"id": sid, "name": name}
for sid, name in sorted(subjects.items(), key=lambda x: x[1])]}
return {"bases": bases, "rates": await asyncio.to_thread(norm_finder.rate_catalog),
"subjects": [{"id": sid, "name": name}
for sid, name in sorted(subjects.items(), key=lambda x: x[1])]}
_public_finder_rate: dict[str, list[float]] = {}
@@ -2449,7 +2450,8 @@ def _check_public_finder_rate(request: Request) -> None:
async def public_norm_finder_catalog(request: Request):
_check_public_finder_rate(request)
import norm_finder
return {"bases": await asyncio.to_thread(norm_finder.catalog)}
return {"bases": await asyncio.to_thread(norm_finder.catalog),
"rates": await asyncio.to_thread(norm_finder.rate_catalog)}
@app.get("/api/public/norm-finder/browse")
+17 -1
View File
@@ -86,6 +86,21 @@ def catalog() -> list[dict]:
con.close()
def rate_catalog() -> list[dict]:
"""НР/СП by explicit work type from the project's loaded source tables."""
try:
import estimate_contract # noqa: F401 — registers the sibling package path
from smeta_railway.data.nr_sp_tables import NR_TABLE, SP_TABLE
except ImportError:
return []
shared = sorted(NR_TABLE.keys() & SP_TABLE.keys(),
key=lambda key: (tuple(int(part) for part in re.findall(r"\d+", key)), key))
return [{"id": key, "name": NR_TABLE[key][0],
"nr_code": f"812/пр, п.{key}", "nr_pct": NR_TABLE[key][1],
"sp_code": f"774/пр, п.{key}", "sp_pct": SP_TABLE[key][1]}
for key in shared]
@lru_cache(maxsize=32)
def _section_paths(db_key: tuple[str, int, int], base: str, base_type: str) -> tuple[tuple[str, str], ...]:
"""Cache section paths and their first norm codes; a rebuilt DB gets a new key."""
@@ -140,7 +155,8 @@ def browse(base: str, base_type: str, path: str = "", limit: int = 40,
clause = ""
params = (BASES[base], base_type)
rows = con.execute(
"SELECT code,name,unit,cost,price_level,section_path FROM works "
"SELECT code,name,unit,cost,salary,machines,salary_mach,materials,"
"price_level,section_path FROM works "
f"WHERE base=? AND base_type=? {clause} ORDER BY code,name LIMIT ? OFFSET ?",
(*params, limit + 1, offset)).fetchall()
finally:
+8 -7
View File
@@ -1,4 +1,12 @@
[
{
"version": "2026-12-04h",
"date": "2026-12-04",
"changes": [
"В подборе норм показана разбивка базисной стоимости ФЕР: ПЗ, ОТ, ЭМ, ОТм и материалы",
"Добавлен отдельный просмотр ставок НР/СП по выбранному виду работ и коэффициентов; отсутствующие значения помечены"
]
},
{
"version": "2026-12-04g",
"date": "2026-12-04",
@@ -26,12 +34,5 @@
"changes": [
"После обновления подбора норм браузер сразу получает новую версию интерфейса"
]
},
{
"version": "2026-12-04c",
"date": "2026-12-04",
"changes": [
"Таблица ресурсов в подборе норм теперь прокручивается внутри карточки и не растягивает страницу телефона"
]
}
]
+42 -7
View File
@@ -85,9 +85,17 @@
.table-panel h2 { margin:0; }
.table-heading { display:flex; justify-content:space-between; align-items:center; gap:12px; margin-bottom:12px; }
.norm-scroll { max-width:100%; overflow-x:auto; }
.norm-table { min-width:720px; table-layout:fixed; font-size:.78rem; line-height:1.28; }
.norm-table { min-width:1420px; table-layout:fixed; font-size:.78rem; line-height:1.28; }
.norm-table th,.norm-table td { border:1px solid #d9e0e2; padding:4px 6px; vertical-align:middle; }
.norm-table th { background:#eef2f4; position:sticky; top:0; z-index:1; }
.norm-table tr > :first-child { position:sticky; left:0; z-index:2; background:#fff; }
.norm-table thead th:first-child { z-index:3; background:#eef2f4; }
.norm-table .norm-family-row td:first-child { background:#e8f0f3; }
.norm-table .norm-section-heading td:first-child,
.norm-table .norm-tools-row td:first-child { background:#f7fafb; }
.norm-table .norm-tools-row td:first-child { position:static; }
.norm-table .norm-work-row td:first-child,
.norm-table .norm-resource-row td:first-child { background:#fbfcfc; }
.norm-table .norm-row:hover { background:#f2f7f7; }
.norm-table .norm-row td,.norm-table .norm-resource-row td,
.norm-table .norm-work-row td { white-space:nowrap; overflow:hidden; text-overflow:ellipsis; }
@@ -107,7 +115,15 @@
.norm-tools { display:flex; gap:6px; align-items:center; flex-wrap:wrap; }
.norm-tools .secondary { min-height:26px; padding:2px 8px; font-size:.75rem; }
.norm-tools .variant-list { width:100%; }
.table-mobile-hint { display:none; }
.rate-panel { border:1px solid var(--line); border-radius:8px; padding:9px 12px; margin:4px 0 12px; }
.rate-panel summary { cursor:pointer; font-weight:650; }
.rate-panel[open] summary { margin-bottom:10px; }
.rate-panel label { max-width:620px; margin:12px 0; }
.rate-panel .scroll { margin:8px 0 14px; }
.rate-panel table { min-width:650px; }
.rate-panel th,.rate-panel td { border:1px solid var(--line); }
.rate-panel input { width:100%; min-width:88px; }
.table-scroll-hint { margin:2px 0 8px; }
.breadcrumb { color:var(--muted); font-size:.84rem; overflow-wrap:anywhere; }
.catalog-mobile { display:none; }
[hidden] { display:none !important; }
@@ -118,8 +134,7 @@
.catalog-mobile { display:block; margin-bottom:10px; }
.catalog-tree { position:static; max-height:45vh; margin-bottom:12px; }
.catalog-tree[hidden] { display:none !important; }
.table-mobile-hint { display:block; }
.norm-table { min-width:760px; }
.norm-table { min-width:1420px; }
}
</style>
</head>
@@ -147,8 +162,28 @@
<section id="results-section" class="panel table-panel" aria-label="Нормы сборника">
<div class="table-heading"><h2 id="results-title">Нормы сборника</h2><span id="result-count" class="hint"></span></div>
<p id="breadcrumb" class="breadcrumb"></p>
<p class="hint table-mobile-hint">Таблица прокручивается по горизонтали.</p>
<div class="norm-scroll"><table class="norm-table"><colgroup><col style="width:18%"><col style="width:47%"><col style="width:12%"><col style="width:10%"><col style="width:13%"></colgroup><thead><tr><th>Шифр</th><th>Наименование</th><th>Ед. изм.</th><th class="num">Расход</th><th class="num">ПЗ, руб.</th></tr></thead><tbody id="results"></tbody></table></div>
<details id="rate-panel" class="rate-panel">
<summary>НР, СП и коэффициенты</summary>
<p class="hint">Ставки НР и СП зависят от вида работ. Выберите пункт загруженного справочника 812/пр и 774/пр; по одному номеру сборника ставка не назначается.</p>
<label for="rate-type">Вид работ для НР и СП<select id="rate-type"><option value="">Выберите вид работ</option></select></label>
<div class="scroll"><table><thead><tr><th>НР, код</th><th class="num">НР, %</th><th class="num">НР, % (МРК)</th><th class="num">НР, % (РКС)</th><th>СП, код</th><th class="num">СП, %</th></tr></thead><tbody><tr id="rate-values"><td>—</td><td class="num">—</td><td class="num">—</td><td class="num">—</td><td>—</td><td class="num">—</td></tr></tbody></table></div>
<p class="hint">Отдельные значения для МРК и РКС в загруженном справочнике отсутствуют. Коэффициенты к НР и СП указывайте только при наличии основания.</p>
<div class="scroll"><table><thead><tr><th>НР, К</th><th>СП, К</th></tr></thead><tbody><tr>
<td><input id="coef-nr" type="number" min="0.01" max="100" step="any" inputmode="decimal" aria-label="Коэффициент НР" placeholder="1,00"></td>
<td><input id="coef-sp" type="number" min="0.01" max="100" step="any" inputmode="decimal" aria-label="Коэффициент СП" placeholder="1,00"></td>
</tr></tbody></table></div>
<p class="hint">Коэффициенты задаются условиями проекта. Введите их вручную для справки: они не меняют базисные суммы таблицы.</p>
<div class="scroll"><table><thead><tr><th>ОТ</th><th>ЗТ</th><th>ЭМ</th><th>ОТм</th><th>ЗТм</th><th>МАТ</th></tr></thead><tbody><tr>
<td><input id="coef-ot" type="number" min="0.01" max="100" step="any" inputmode="decimal" aria-label="Коэффициент ОТ" placeholder="1,00"></td>
<td><input id="coef-zt" type="number" min="0.01" max="100" step="any" inputmode="decimal" aria-label="Коэффициент ЗТ" placeholder="1,00"></td>
<td><input id="coef-em" type="number" min="0.01" max="100" step="any" inputmode="decimal" aria-label="Коэффициент ЭМ" placeholder="1,00"></td>
<td><input id="coef-otm" type="number" min="0.01" max="100" step="any" inputmode="decimal" aria-label="Коэффициент ОТм" placeholder="1,00"></td>
<td><input id="coef-ztm" type="number" min="0.01" max="100" step="any" inputmode="decimal" aria-label="Коэффициент ЗТм" placeholder="1,00"></td>
<td><input id="coef-mat" type="number" min="0.01" max="100" step="any" inputmode="decimal" aria-label="Коэффициент МАТ" placeholder="1,00"></td>
</tr></tbody></table></div>
</details>
<p class="hint table-scroll-hint">Прокрутите таблицу вправо для разбивки затрат; шифр останется виден. ОТм входит в ЭМ. В ГЭСН указаны нормы расхода без готовой единичной цены. Суммы ФЕР-2020 — базис на 01.01.2000, не текущие цены.</p>
<div class="norm-scroll"><table class="norm-table"><colgroup><col style="width:13%"><col style="width:31%"><col style="width:9%"><col style="width:7%"><col style="width:8%"><col style="width:8%"><col style="width:8%"><col style="width:8%"><col style="width:8%"></colgroup><thead><tr><th>Шифр</th><th>Наименование</th><th>Ед. изм.</th><th class="num">Расход</th><th class="num">ПЗ, руб.</th><th class="num" title="Оплата труда рабочих">ОТ, руб.</th><th class="num" title="Эксплуатация машин">ЭМ, руб.</th><th class="num" title="Оплата труда машинистов входит в ЭМ, второй раз к ПЗ не прибавляется">ОТм, руб.</th><th class="num" title="Материалы">МАТ, руб.</th></tr></thead><tbody id="results"></tbody></table></div>
<div class="actions" style="margin-top:16px"><button id="more-results" type="button" class="secondary" hidden>Показать ещё нормы</button></div>
</section>
</div>
@@ -179,6 +214,6 @@
<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?v=2026-12-04g" defer></script>
<script src="/static/norm-finder.js?v=2026-12-04h" defer></script>
</body>
</html>
+42 -15
View File
@@ -21,6 +21,7 @@
let searchPage = null;
let browsePage = null;
let catalogRows = [];
let rateRows = [];
let requestSeq = 0;
let detailSeq = 0;
let lastFamily = '';
@@ -28,6 +29,8 @@
let priceZones = [];
const compared = new Map();
const money = n => new Intl.NumberFormat('ru-RU', {minimumFractionDigits:2, maximumFractionDigits:2}).format(n) + ' ₽';
const amount = n => Number.isFinite(n) ? money(n).replace(' ₽', '') : '—';
const emptyTableCells = count => Array.from({length:count}, () => ['','']);
function node(tag, value, className) {
const el = document.createElement(tag);
@@ -134,7 +137,7 @@
return row;
}
function sectionHeading(label) {
return tableRow('norm-section-heading', [['',''],[label,''],['',''],['',''],['','']]);
return tableRow('norm-section-heading', [['',''],[label,''],...emptyTableCells(7)]);
}
function selectVariant(row) {
showRows([row]); browsePage = null; searchPage = null; $('more-results').hidden = true;
@@ -144,11 +147,15 @@
}
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']]);
...[item.cost,item.salary,item.machines,item.salary_mach,item.materials]
.map(value => [amount(value),'num'])]);
row.dataset.key = key(item);
row.cells[4].title = item.cost != null
? 'Базисная стоимость, уровень ' + (item.price_level || 'не указан')
: 'Прямые затраты для этой нормы в индексе не указаны';
for (let index = 4; index < row.cells.length; index++) {
row.cells[index].title = item.cost != null
? 'Базисная стоимость ФЕР, уровень ' + (item.price_level || 'не указан')
: 'В этой норме нет готовой единичной цены';
}
row.cells[7].title += '. ОТм входит в ЭМ, к ПЗ повторно не прибавляется';
const codeCell = row.cells[0];
const workToggle = node('button', '▸', 'norm-toggle');
const resourceToggle = node('button', '▸', 'norm-toggle');
@@ -174,8 +181,8 @@
return detail;
}
function toolsRow() {
const toolRow = tableRow('norm-tools-row', [['',''],['',''],['',''],['',''],['','']]);
const cell = toolRow.cells[1]; cell.colSpan = 4;
const toolRow = tableRow('norm-tools-row', emptyTableCells(9));
const cell = toolRow.cells[1]; cell.colSpan = 8;
while (toolRow.cells.length > 2) toolRow.deleteCell(2);
const tools = node('div', null, 'norm-tools');
const compare = node('button', compared.has(key(item)) ? 'Убрать из сравнения' : 'Сравнить', 'secondary');
@@ -242,20 +249,28 @@
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', [['',''],['Состав работ в индексе не указан',''],['',''],['',''],['','']]));
workRows.push(tableRow('norm-work-row', [[index + 1,'num'],[line,''],...emptyTableCells(7)]));
if (workRows.length === 1) workRows.push(tableRow('norm-work-row',
[['',''],['Состав работ в индексе не указан',''],...emptyTableCells(7)]));
}
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(' ₽','') : '—';
const numeric = !resource.quantity_note && Number.isFinite(resource.quantity);
const price = numeric && Number.isFinite(resource.base_price?.cost)
? amount(resource.quantity * resource.base_price.cost) : '—';
const machinist = numeric && Number.isFinite(resource.base_price?.cost)
&& Number.isFinite(resource.base_price?.salary_mach)
? amount(resource.quantity * resource.base_price.salary_mach) : '—';
const machine = /^91\./.test(String(resource.code || ''));
const material = /^\d{2}\./.test(String(resource.code || '')) && !machine;
resourceRows.push(tableRow('norm-resource-row', [[resource.code || '—',''],
[resource.name || '—',''],[resource.unit || '—',''],[quantity,'num'],[price,'num']]));
[resource.name || '—',''],[resource.unit || '—',''],[quantity,'num'],[price,'num'],
['—','num'],[machine ? price : '—','num'],[machinist,'num'],[material ? price : '—','num']]));
}
if (resourceRows.length === 1) resourceRows.push(tableRow('norm-resource-row', [['',''],['Ресурсы в индексе не указаны',''],['',''],['',''],['','']]));
if (resourceRows.length === 1) resourceRows.push(tableRow('norm-resource-row',
[['',''],['Ресурсы в индексе не указаны',''],...emptyTableCells(7)]));
resourceRows.push(toolsRow());
}
} catch (error) { status(error.message, true); return; }
@@ -287,7 +302,7 @@
const title = familyTitle(groups.get(family));
if (family !== lastFamily) {
$('results').append(tableRow('norm-family-row', [[String(item.code || '').replace(/-\d+$/, ''),''],
[title,''],['',''],['',''],['','']]));
[title,''],...emptyTableCells(7)]));
lastFamily = family;
}
$('results').append(renderSearchItem(item, title));
@@ -683,6 +698,11 @@
'id', 'name', 'Выберите базу');
if (bases.length) $('base').selectedIndex = 1;
catalogRows = data.bases || [];
rateRows = data.rates || [];
fillSelect($('rate-type'), rateRows.map(row => ({id:row.id,
name:row.id + ' · ' + row.name})), 'id', 'name', 'Выберите вид работ');
$('rate-type').disabled = !rateRows.length;
if (!rateRows.length) $('rate-type').options[0].textContent = 'Справочник НР/СП недоступен';
fillBaseTypes();
subjects = data.subjects || [];
if (!publicMode) fillSelect($('subject'), subjects, 'id', 'name', 'Выберите регион');
@@ -696,6 +716,13 @@
? loadBrowse(browsePage.path, null, true) : search(event, true));
$('base').addEventListener('change', () => { fillBaseTypes(); loadBrowse(); });
$('base-type').addEventListener('change', () => loadBrowse());
$('rate-type').addEventListener('change', () => {
const selected = rateRows.find(row => row.id === $('rate-type').value);
const values = selected
? [selected.nr_code, selected.nr_pct + ' %', '—', '—', selected.sp_code, selected.sp_pct + ' %']
: ['—', '—', '—', '—', '—', '—'];
[...$('rate-values').cells].forEach((cell, index) => { cell.textContent = values[index]; });
});
$('catalog-mobile').addEventListener('click', () => {
const tree = $('catalog-tree');
tree.hidden = !tree.hidden;
+8
View File
@@ -338,6 +338,14 @@ def test_composition_by_code_both_bases(ref_env):
assert fbp["cost"] == 79.07 and fbp["price_level"] == "01.01.2000"
def test_search_exposes_fer_machinist_salary_from_source(ref_env):
out = fsnb_ref.find_works(query="01-01-001-01", base="2020", limit=5)
assert out["status"] == "ok"
fer = next(row for row in out["works"] if row["base_type"] == "ФЕР")
assert fer["cost"] == 2968.03
assert fer["salary_mach"] == 87.84
def test_composition_exact_code_not_cut_by_limit(ref_env):
"""Точное совпадение шифра отдаётся ЦЕЛИКОМ: обрезка лимитом спрятала бы
одноимённый шифр другого типа сборника (ГЭСН vs ГЭСНп vs ФЕР)."""
+58 -4
View File
@@ -12,8 +12,10 @@ def test_browse_keeps_sections_and_base_types_separate(tmp_path, monkeypatch):
with sqlite3.connect(db) as con:
con.execute("CREATE TABLE sources (source_id INTEGER)")
con.execute("CREATE TABLE works (base TEXT, base_type TEXT, code TEXT, name TEXT, "
"unit TEXT, cost REAL, price_level TEXT, section_path TEXT)")
con.executemany("INSERT INTO works VALUES (?,?,?,?,?,?,?,?)", [
"unit TEXT, cost REAL, price_level TEXT, section_path TEXT, "
"salary REAL, machines REAL, salary_mach REAL, materials REAL)")
con.executemany("INSERT INTO works (base,base_type,code,name,unit,cost,price_level,section_path) "
"VALUES (?,?,?,?,?,?,?,?)", [
("ГЭСН-2022", "ГЭСН", "01-01-001-01", "Разработка грунта", "1000 м3", None,
"норма", "Земляные работы > Раздел 1 > Таблица 1"),
("ГЭСН-2022", "ГЭСН", "01-01-001-02", "Разработка грунта 2", "1000 м3", None,
@@ -43,8 +45,10 @@ def test_browse_orders_collections_and_sections_by_norm_code(tmp_path, monkeypat
with sqlite3.connect(db) as con:
con.execute("CREATE TABLE sources (source_id INTEGER)")
con.execute("CREATE TABLE works (base TEXT, base_type TEXT, code TEXT, name TEXT, "
"unit TEXT, cost REAL, price_level TEXT, section_path TEXT)")
con.executemany("INSERT INTO works VALUES (?,?,?,?,?,?,?,?)", [
"unit TEXT, cost REAL, price_level TEXT, section_path TEXT, "
"salary REAL, machines REAL, salary_mach REAL, materials REAL)")
con.executemany("INSERT INTO works (base,base_type,code,name,unit,cost,price_level,section_path) "
"VALUES (?,?,?,?,?,?,?,?)", [
("ГЭСН-2022", "ГЭСН", "06-01-001-01", "Бетон", "м3", None,
"норма", "Бетонные работы > Раздел 1"),
("ГЭСН-2022", "ГЭСН", "02-01-001-01", "Горные работы", "м3", None,
@@ -62,6 +66,42 @@ def test_browse_orders_collections_and_sections_by_norm_code(tmp_path, monkeypat
assert [row["name"] for row in sections["children"]] == ["Раздел 2", "Раздел 10"]
def test_browse_exposes_only_its_own_base_cost_components(tmp_path, monkeypatch):
import norm_finder
import fsnb_ref
db = tmp_path / "costs.sqlite"
with sqlite3.connect(db) as con:
con.execute("CREATE TABLE sources (source_id INTEGER)")
con.execute("CREATE TABLE works (base TEXT, base_type TEXT, code TEXT, name TEXT, "
"unit TEXT, cost REAL, price_level TEXT, section_path TEXT, "
"salary REAL, machines REAL, salary_mach REAL, materials REAL)")
con.executemany("INSERT INTO works VALUES (?,?,?,?,?,?,?,?,?,?,?,?)", [
("ГЭСН-2022", "ГЭСН", "01-01-001-01", "Земляные работы", "1000 м3", None,
"01.01.2022", "Земляные работы", None, None, None, None),
("ФЕР-2020", "ФЕР", "01-01-001-01", "Земляные работы", "1000 м3", 2968.03,
"01.01.2000", "Земляные работы", 14.48, 2953.55, 87.84, 0.0),
])
monkeypatch.setattr(fsnb_ref, "db_path", lambda: db)
fer = norm_finder.browse("2020", "ФЕР")["items"][0]
assert {field: fer[field] for field in ("cost", "salary", "machines", "salary_mach", "materials")} == {
"cost": 2968.03, "salary": 14.48, "machines": 2953.55,
"salary_mach": 87.84, "materials": 0.0}
gesn = norm_finder.browse("2022", "ГЭСН")["items"][0]
assert all(gesn[field] is None for field in
("cost", "salary", "machines", "salary_mach", "materials"))
def test_rate_catalog_uses_source_table_item_without_assigning_it_to_norm():
import norm_finder
rows = norm_finder.rate_catalog()
earthwork = next(row for row in rows if row["id"] == "1.1")
assert earthwork["nr_pct"] == 92
assert earthwork["sp_pct"] == 46
assert earthwork["nr_code"] == "812/пр, п.1.1"
assert earthwork["sp_code"] == "774/пр, п.1.1"
assert all("code" not in row for row in rows)
def test_search_rejects_empty_query_and_uses_existing_fsnb(monkeypatch):
import fsnb_ref
import norm_finder
@@ -253,6 +293,20 @@ def test_finder_requires_login(api, method, path):
assert getattr(client, method)(path).status_code == 401
def test_catalog_exposes_rate_choices_without_automatic_norm_assignment(api, monkeypatch):
import norm_finder
client, headers, _ = api
monkeypatch.setattr(norm_finder, "catalog", lambda: [])
for path, auth_headers in (("/api/public/norm-finder/catalog", {}),
("/api/norm-finder/catalog", headers)):
response = client.get(path, headers=auth_headers)
assert response.status_code == 200
rates = response.json()["rates"]
selected = next(row for row in rates if row["id"] == "1.1")
assert selected["nr_pct"] == 92 and selected["sp_pct"] == 46
assert "norm_code" not in selected
def test_finder_api_search_detail_and_catalog(api, monkeypatch):
import norm_finder
client, headers, _ = api
+79 -1
View File
@@ -145,7 +145,8 @@ def test_video_table_has_two_triangle_toggles_and_inline_grid_rows(browser, site
})()""")
page.goto(site)
assert page.locator('.norm-table thead th').all_text_contents() == [
'Шифр', 'Наименование', 'Ед. изм.', 'Расход', 'ПЗ, руб.']
'Шифр', 'Наименование', 'Ед. изм.', 'Расход', 'ПЗ, руб.',
'ОТ, руб.', 'ЭМ, руб.', 'ОТм, руб.', 'МАТ, руб.']
family = page.locator('#results .norm-family-row').first
family.wait_for()
assert '01-01-001' in family.inner_text()
@@ -179,6 +180,83 @@ def test_video_table_has_two_triangle_toggles_and_inline_grid_rows(browser, site
page.close()
def test_cost_columns_show_fer_components_and_gesn_missing_values(browser, site):
page = browser.new_page(viewport={"width": 1360, "height": 800})
page.add_init_script("""(() => {
const base = {code:'01-01-001-01',name:'Земляные работы',unit:'1000 м3',section_path:'Земляные работы'};
window.fetch = async url => {
const u = new URL(url, location.href);
const fer = u.searchParams.get('base') === '2020';
let value = {};
if (u.pathname.endsWith('/catalog')) value={bases:[
{base:'ГЭСН-2022',base_type:'ГЭСН',count:1},
{base:'ФЕР-2020',base_type:'ФЕР',count:1}]};
if (u.pathname.endsWith('/browse')) value={items:[{...base,
base:fer?'ФЕР-2020':'ГЭСН-2022',base_type:fer?'ФЕР':'ГЭСН',
price_level:fer?'01.01.2000':'01.01.2022',
cost:fer?2968.03:null,salary:fer?14.48:null,machines:fer?2953.55:null,
salary_mach:fer?87.84:null,materials:fer?0:null}],children:[],has_more:false};
if (u.pathname.endsWith('/detail')) value={...base,content:[],resources:[{
code:'91.01.01-035',name:'Бульдозер',unit:'маш.-ч',quantity:1.6,
base_price:{cost:fer?79.07:null,salary_mach:fer?13.5:451.93}}]};
return new Response(JSON.stringify(value),{status:200,headers:{'Content-Type':'application/json'}});
};
})()""")
page.goto(site)
assert page.locator('.norm-table thead th').all_text_contents() == [
'Шифр', 'Наименование', 'Ед. изм.', 'Расход', 'ПЗ, руб.',
'ОТ, руб.', 'ЭМ, руб.', 'ОТм, руб.', 'МАТ, руб.']
row = page.locator('#results .norm-row').first
row.wait_for()
assert row.locator('td').all_text_contents()[4:] == ['—'] * 5
row.locator('.norm-toggle').nth(1).click()
unpriced_resource = page.locator('#results .norm-resource-row').first
unpriced_resource.wait_for()
assert unpriced_resource.locator('td').all_text_contents()[4:] == ['—'] * 5
page.locator('#base').select_option('2020')
page.wait_for_function("document.querySelector('#results .norm-row')?.dataset.key?.startsWith('ФЕР-2020')")
amounts = [value.replace('\u00a0', ' ').replace('\u202f', ' ')
for value in row.locator('td').all_text_contents()[4:]]
assert amounts == ['2 968,03', '14,48', '2 953,55', '87,84', '0,00']
row.locator('.norm-toggle').nth(1).click()
resource = page.locator('#results .norm-resource-row').first
resource.wait_for()
assert resource.locator('td').all_text_contents()[4:] == [
'126,51', '—', '126,51', '21,60', '—']
code_x = row.locator('td').first.bounding_box()['x']
page.locator('.norm-scroll').evaluate('el => { el.scrollLeft = el.scrollWidth; }')
assert abs(row.locator('td').first.bounding_box()['x'] - code_x) < 2
assert page.evaluate('document.documentElement.scrollWidth <= window.innerWidth')
page.close()
def test_rate_and_coefficient_panel_requires_explicit_values(browser, site):
page = browser.new_page(viewport={"width": 1360, "height": 800})
page.add_init_script("""(() => {
window.fetch = async url => {
const u = new URL(url, location.href);
const value = u.pathname.endsWith('/catalog') ? {bases:[
{base:'ФЕР-2020',base_type:'ФЕР',count:1}],rates:[
{id:'1.1',name:'Земляные работы механизированным способом',
nr_code:'812/пр, п.1.1',nr_pct:92,sp_code:'774/пр, п.1.1',sp_pct:46}]
} : {items:[],children:[],has_more:false};
return new Response(JSON.stringify(value),{status:200,headers:{'Content-Type':'application/json'}});
};
})()""")
page.goto(site)
page.locator('#rate-panel summary').click()
assert page.locator('#rate-values td').all_text_contents() == ['—'] * 6
assert page.locator('#coef-em').input_value() == ''
assert page.locator('#coef-nr').input_value() == ''
page.locator('#rate-type').select_option('1.1')
assert page.locator('#rate-values td').all_text_contents() == [
'812/пр, п.1.1', '92 %', '—', '—', '774/пр, п.1.1', '46 %']
page.locator('#coef-em').fill('1.2')
assert page.locator('#coef-em').input_value() == '1.2'
assert 'не меняют базисные суммы' in page.locator('#rate-panel').inner_text()
page.close()
def test_saved_multi_position_draft_survives_reload_and_marks_incomplete_price(browser, site):
state = {"draft": None}
first = {"base": "ГЭСН-2022", "base_type": "ГЭСН", "code": "11-01-011-01",