Compare commits
3
Commits
8ccbe73d3a
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
add8b4bee2 | ||
|
|
beda783439 | ||
|
|
f93c0e50b2 |
Binary file not shown.
|
After Width: | Height: | Size: 37 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 61 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 62 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 34 KiB |
@@ -62,6 +62,21 @@ prod_ext=${prod_ext:-$prod_data/_external}
|
||||
stage_ext=${stage_ext:-$stage_data/_external}
|
||||
test "${prod_ext#/}" != "$prod_ext" && test "${stage_ext#/}" != "$stage_ext"
|
||||
test "$(readlink -f "$prod_ext")" != "$(readlink -f "$stage_ext")"
|
||||
# Инлайн-выбор ценовой зоны и /podbor читают собранные формы из derived.
|
||||
# Без их изолированной копии dev показывает зоны в ответе ИИ, но на каждое
|
||||
# нажатие отвечает «нет в каталоге». Синхронизируем только производные цены,
|
||||
# не личные файлы и не исходные письма ФГИС. rsync повторно копирует лишь дельту.
|
||||
price_src="$prod_ext/derived/engine_prices"
|
||||
price_dst="$stage_ext/derived/engine_prices"
|
||||
test ! -L "$price_src" && test ! -L "$price_dst"
|
||||
test "$(readlink -f "$price_src")" != "$(readlink -f "$price_dst")"
|
||||
"$python_bin" "$stage/scripts/shadow/verify_engine_prices.py" "$price_src"
|
||||
mkdir -p "$price_dst"
|
||||
price_catalog_sha=$(sha256sum "$price_src/catalog.json" | cut -d' ' -f1)
|
||||
rsync -a --delete "$price_src/" "$price_dst/"
|
||||
test "$price_catalog_sha" = "$(sha256sum "$price_src/catalog.json" | cut -d' ' -f1)"
|
||||
test "$price_catalog_sha" = "$(sha256sum "$price_dst/catalog.json" | cut -d' ' -f1)"
|
||||
"$python_bin" "$stage/scripts/shadow/verify_engine_prices.py" "$price_dst"
|
||||
"$python_bin" -c 'import sys, public_documents; public_documents.export_summary(sys.argv[1], sys.argv[2])' \
|
||||
"$prod_ext" "$stage_ext/landing_documents.json"
|
||||
export SMETA_PROJECT_DIR="$stage-norms"
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
"""Check that an isolated price snapshot can serve every listed zone and period."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
import sys
|
||||
|
||||
|
||||
def validate(root: Path) -> int:
|
||||
root = Path(root)
|
||||
if root.is_symlink() or not root.is_dir():
|
||||
raise ValueError("Каталог ценовых форм отсутствует или является ссылкой")
|
||||
base = root.resolve()
|
||||
catalog = root / "catalog.json"
|
||||
if catalog.is_symlink() or not catalog.is_file():
|
||||
raise ValueError("Каталог ценовых зон не найден")
|
||||
try:
|
||||
zones = json.loads(catalog.read_text(encoding="utf-8"))["zones"]
|
||||
except (OSError, ValueError, KeyError, TypeError) as exc:
|
||||
raise ValueError("Каталог ценовых зон не читается") from exc
|
||||
if not isinstance(zones, list) or not zones:
|
||||
raise ValueError("Каталог ценовых зон пуст")
|
||||
seen = set()
|
||||
for entry in zones:
|
||||
if not isinstance(entry, dict):
|
||||
raise ValueError("Некорректная запись ценовой зоны")
|
||||
ids = tuple(entry.get(key) for key in ("subject_id", "zone_id", "period_id"))
|
||||
if any(not isinstance(value, int) or isinstance(value, bool) or value < 1 for value in ids):
|
||||
raise ValueError("Некорректный код ценовой зоны или квартала")
|
||||
if ids in seen:
|
||||
raise ValueError("Повтор ценовой зоны и квартала")
|
||||
seen.add(ids)
|
||||
if not all(isinstance(entry.get(key), str) and entry[key].strip()
|
||||
for key in ("zone_name", "period_label")):
|
||||
raise ValueError("Нет названия зоны или квартала")
|
||||
name = entry.get("file")
|
||||
if not isinstance(name, str) or not name:
|
||||
raise ValueError("Нет файла ценовой формы")
|
||||
relative = Path(name)
|
||||
if (relative.is_absolute() or ".." in relative.parts or relative.suffix != ".json"
|
||||
or len(relative.parts) != 3):
|
||||
raise ValueError("Путь ценовой формы вне снимка")
|
||||
path = root / relative
|
||||
if path.is_symlink() or base not in path.resolve().parents:
|
||||
raise ValueError("Путь ценовой формы вне снимка")
|
||||
if not path.is_file() or path.stat().st_size == 0:
|
||||
raise ValueError(f"Ценовая форма не найдена: {name}")
|
||||
return len(zones)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
count = validate(Path(sys.argv[1]))
|
||||
except (IndexError, ValueError) as error:
|
||||
raise SystemExit(str(error)) from error
|
||||
print(f"Ценовых форм в изолированном снимке: {count}")
|
||||
+85
-12
@@ -364,6 +364,10 @@ button { font-family: inherit; }
|
||||
.file-compare-status { padding: .4rem .9rem; color: var(--text-muted); font-size: .82rem; }
|
||||
.file-compare-status[role="alert"] { color: var(--error, #ad3434); }
|
||||
.file-compare-pages { display: flex; gap: .5rem; align-items: center; padding: .5rem .9rem; }
|
||||
.file-compare-panel .est-scroll { overflow-x: auto; }
|
||||
.file-compare-panel .est-table { min-width: 850px; table-layout: auto; }
|
||||
.file-compare-panel .est-table th, .file-compare-panel .est-table td { min-width: 80px; word-break: normal; overflow-wrap: normal; }
|
||||
.file-compare-panel .est-table th:nth-child(2), .file-compare-panel .est-table td:nth-child(2) { min-width: 150px; }
|
||||
.est-basis-picker { display: inline-flex; gap: .35rem; align-items: center; flex-wrap: wrap; }
|
||||
.est-basis-picker button, .est-basis-picker select { max-width: 100%; font: inherit; color: var(--text); background: var(--bg-card); border: 1px solid var(--border); border-radius: 6px; padding: .25rem .4rem; cursor: pointer; }
|
||||
.est-basis-picker button:hover, .est-basis-picker select:focus-visible { border-color: var(--accent); }
|
||||
@@ -372,6 +376,9 @@ button { font-family: inherit; }
|
||||
.inline-basis-trigger:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
|
||||
.inline-basis-picker { display: inline-flex; flex-wrap: wrap; align-items: center; gap: .35rem; padding: .2rem; border: 1px solid var(--border); border-radius: 6px; background: var(--bg-card); max-width: 100%; }
|
||||
.inline-basis-picker select, .inline-basis-picker button, .inline-basis-picker input { max-width: 100%; min-width: 0; padding: .2rem .35rem; font: inherit; color: var(--text); background: var(--bg-card); border: 1px solid var(--border); border-radius: 5px; }
|
||||
.inline-basis-note { flex-basis: 100%; font-size: .78rem; color: var(--text-muted); }
|
||||
.inline-basis-note[role="alert"] { color: var(--danger); }
|
||||
.inline-basis-picker select[aria-invalid="true"] { border-color: var(--danger); }
|
||||
.inline-basis-picker .inline-norm-select { max-width: min(28rem, 100%); }
|
||||
.inline-basis-picker .inline-quantity { width: 6rem; }
|
||||
.inline-basis-picker .inline-basis-apply { color: var(--accent); cursor: pointer; }
|
||||
@@ -415,7 +422,7 @@ button { font-family: inherit; }
|
||||
/* Таблица живёт в своём окне с ограничением высоты: иначе её горизонтальная полоса
|
||||
оказывалась внизу длинной таблицы, и до неё надо было прокрутить всю ленту
|
||||
(сказал Хозяин 18.11). С max-height обе полосы всегда у края видимой рамки. */
|
||||
.msg-ai .table-wrap { overflow-y: auto; overflow-x: hidden; max-height: min(60vh, 560px); overscroll-behavior: contain; -webkit-overflow-scrolling: touch; margin: .5rem 0; border: 1px solid var(--border); border-radius: 8px; scrollbar-width: thin; scrollbar-color: var(--text-muted) transparent; }
|
||||
.msg-ai .table-wrap { overflow-y: auto; overflow-x: hidden; max-height: min(60vh, 560px); -webkit-overflow-scrolling: touch; margin: .5rem 0; border: 1px solid var(--border); border-radius: 8px; scrollbar-width: thin; scrollbar-color: var(--text-muted) transparent; }
|
||||
/* Полоса прокрутки у таблицы должна быть видна в обеих темах: общий «тихий»
|
||||
скроллбар в тёмной теме сливался с фоном, и казалось, что таблица обрезана
|
||||
(жалоба Хозяина 18.11). */
|
||||
@@ -540,6 +547,16 @@ button { font-family: inherit; }
|
||||
.msg-ai.has-estimate .est-actions .est-dl {
|
||||
width: 100%; min-height: 2.5rem; word-break: normal; overflow-wrap: normal;
|
||||
}
|
||||
/* Сверка файлов остаётся таблицей с горизонтальной прокруткой. Карточная
|
||||
раскладка сметы выше растягивает её строки и ломает селекторы. */
|
||||
.msg-ai.has-estimate .file-compare-panel .est-table { display: table; width: 100%; }
|
||||
.msg-ai.has-estimate .file-compare-panel .est-table tbody { display: table-row-group; width: auto; }
|
||||
.msg-ai.has-estimate .file-compare-panel .est-table tr { display: table-row; width: auto; padding: 0; }
|
||||
.msg-ai.has-estimate .file-compare-panel .est-table td {
|
||||
display: table-cell; width: auto; max-width: 360px; border: 1px solid var(--border-light);
|
||||
padding: .35rem .55rem; white-space: normal; overflow-wrap: normal;
|
||||
}
|
||||
.msg-ai.has-estimate .file-compare-panel .est-table td::before { content: none; }
|
||||
}
|
||||
/* Меряем колонку переписки, а не окно: при открытой панели диалогов колонка узкая и на
|
||||
широком экране. От названия в узкой колонке остаётся «Сметн…» — место нужнее дате сметы
|
||||
@@ -1095,6 +1112,7 @@ function enhanceTables(container) {
|
||||
}
|
||||
const wrap = document.createElement('div');
|
||||
wrap.className = 'table-wrap';
|
||||
wrap.addEventListener('wheel', passTableWheelAtEdge, {passive: false});
|
||||
table.parentNode.insertBefore(wrap, table);
|
||||
wrap.appendChild(table);
|
||||
// панель с кнопкой выгрузки
|
||||
@@ -1112,6 +1130,26 @@ function enhanceTables(container) {
|
||||
});
|
||||
}
|
||||
|
||||
// Когда таблица дошла до края, прокручиваем саму ленту. Chromium иногда
|
||||
// оставляет колесо во вложенном скролле даже без overscroll-behavior: contain.
|
||||
function passTableWheelAtEdge(event) {
|
||||
if (event.shiftKey || Math.abs(event.deltaY) <= Math.abs(event.deltaX)) return;
|
||||
const table = event.currentTarget;
|
||||
const chat = document.getElementById('messages');
|
||||
if (!chat) return;
|
||||
const down = event.deltaY > 0;
|
||||
const tableAtEdge = down
|
||||
? table.scrollTop + table.clientHeight >= table.scrollHeight - 2
|
||||
: table.scrollTop <= 2;
|
||||
const chatCanScroll = down
|
||||
? chat.scrollTop + chat.clientHeight < chat.scrollHeight - 1
|
||||
: chat.scrollTop > 1;
|
||||
if (!tableAtEdge || !chatCanScroll) return;
|
||||
event.preventDefault();
|
||||
const factor = event.deltaMode === 1 ? 16 : event.deltaMode === 2 ? chat.clientHeight : 1;
|
||||
chat.scrollTop += event.deltaY * factor;
|
||||
}
|
||||
|
||||
// Обновляет подсказки у всех таблиц: нужна и после вставки, и после смены ширины окна —
|
||||
// иначе на узком окне таблица молча обрезается без объяснения (жалоба Хозяина 18.11).
|
||||
function updateTableHeights() {
|
||||
@@ -2306,6 +2344,7 @@ function bindFreeformBasis(host) {
|
||||
'Изменить объём для этого расчёта');
|
||||
}
|
||||
|
||||
let inlineBasisNoteSequence = 0;
|
||||
async function openFreeformBasis(button, host, label) {
|
||||
if (!host._messageId || viewOwner) return;
|
||||
const requestTab = tabId;
|
||||
@@ -2324,6 +2363,14 @@ async function openFreeformBasis(button, host, label) {
|
||||
const currentZone = zones.find(z => z.name === label);
|
||||
if (currentZone) zoneSelect.value = String(currentZone.zone_id);
|
||||
const periodSelect = document.createElement('select'); periodSelect.setAttribute('aria-label', 'Квартал цен');
|
||||
const periodNote = document.createElement('span'); periodNote.className = 'inline-basis-note';
|
||||
periodNote.id = 'inline-basis-period-note-' + ++inlineBasisNoteSequence;
|
||||
periodSelect.setAttribute('aria-describedby', periodNote.id);
|
||||
const quarterMention = (host._rawText || '').match(/\b(IV|III|II|I|[1-4])\s*квартал[а-яё]*\s+(20\d{2})/i);
|
||||
const roman = {I:1, II:2, III:3, IV:4};
|
||||
const mentionedPeriod = quarterMention
|
||||
? String(roman[quarterMention[1].toUpperCase()] || Number(quarterMention[1])) + ' квартал ' + quarterMention[2]
|
||||
: '';
|
||||
const fillPeriods = () => {
|
||||
periodSelect.replaceChildren();
|
||||
const placeholder = document.createElement('option'); placeholder.value = '';
|
||||
@@ -2331,10 +2378,22 @@ async function openFreeformBasis(button, host, label) {
|
||||
const zone = zones.find(z => String(z.zone_id) === zoneSelect.value);
|
||||
(zone ? zone.periods : []).forEach(p => { const o = document.createElement('option');
|
||||
o.value = String(p.period_id); o.textContent = p.name; periodSelect.appendChild(o); });
|
||||
const named = (zone ? zone.periods : []).find(p => (host._rawText || '').includes(p.name));
|
||||
const named = (zone ? zone.periods : []).find(p => p.name === mentionedPeriod)
|
||||
|| (zone ? zone.periods : []).find(p => (host._rawText || '').includes(p.name));
|
||||
if (named) periodSelect.value = String(named.period_id);
|
||||
periodSelect.removeAttribute('aria-invalid');
|
||||
periodNote.removeAttribute('role');
|
||||
periodNote.textContent = quarterMention && !named
|
||||
? 'Квартал из ответа не загружен. Выберите доступный квартал для нового расчёта.'
|
||||
: 'Выберите квартал цен для пересчёта.';
|
||||
periodNote.hidden = !!periodSelect.value;
|
||||
};
|
||||
fillPeriods(); zoneSelect.onchange = fillPeriods;
|
||||
periodSelect.onchange = () => {
|
||||
periodSelect.removeAttribute('aria-invalid');
|
||||
periodNote.removeAttribute('role');
|
||||
periodNote.hidden = !!periodSelect.value;
|
||||
};
|
||||
const normRows = options.norms || [];
|
||||
const position = options.position;
|
||||
const normSelect = document.createElement('select');
|
||||
@@ -2353,7 +2412,14 @@ async function openFreeformBasis(button, host, label) {
|
||||
const cancel = document.createElement('button'); cancel.type = 'button'; cancel.textContent = 'Отмена';
|
||||
cancel.onclick = () => picker.replaceWith(button);
|
||||
apply.onclick = async () => {
|
||||
if (!periodSelect.value) { periodSelect.focus(); return; }
|
||||
if (!periodSelect.value) {
|
||||
periodSelect.setAttribute('aria-invalid', 'true');
|
||||
periodNote.textContent = 'Выберите квартал цен перед пересчётом.';
|
||||
periodNote.hidden = false;
|
||||
periodNote.setAttribute('role', 'alert');
|
||||
periodSelect.focus();
|
||||
return;
|
||||
}
|
||||
if (normRows.length && (!quantity.value || !quantity.checkValidity()
|
||||
|| !Number.isFinite(Number(quantity.value)) || Number(quantity.value) <= 0)) {
|
||||
quantity.focus(); return;
|
||||
@@ -2383,7 +2449,7 @@ async function openFreeformBasis(button, host, label) {
|
||||
}
|
||||
};
|
||||
if (normRows.length) picker.append(normSelect, quantity);
|
||||
picker.append(zoneSelect, periodSelect, apply, cancel);
|
||||
picker.append(zoneSelect, periodSelect, apply, cancel, periodNote);
|
||||
button.replaceWith(picker); zoneSelect.focus();
|
||||
} catch (e) {
|
||||
button.disabled = false;
|
||||
@@ -3583,6 +3649,7 @@ function addFileComparePanel(initial, host) {
|
||||
host.classList.add('has-estimate');
|
||||
host.appendChild(panel);
|
||||
let state = initial, workbooks = [], page = 0;
|
||||
let pending = Promise.resolve();
|
||||
const modeNames = {ka_lsr: 'КА ↔ ЛСР: цены', vor_lsr: 'ВОР ↔ ЛСР: объёмы', ka_kp: 'КА ↔ КП: цены'};
|
||||
const sideNames = {ka_lsr: ['Конъюнктурный анализ', 'Локальная смета'],
|
||||
vor_lsr: ['Ведомость объёмов', 'Локальная смета'],
|
||||
@@ -3602,14 +3669,20 @@ function addFileComparePanel(initial, host) {
|
||||
state = data; page = nextPage;
|
||||
render();
|
||||
}
|
||||
async function update(change) {
|
||||
const r = await authFetch(endpoint, {method: 'POST',
|
||||
headers: {'Content-Type': 'application/json'},
|
||||
body: JSON.stringify({revision: state._revision, ...change})});
|
||||
const data = await r.json().catch(() => ({}));
|
||||
if (!r.ok) throw new Error(data.detail || 'Не удалось пересчитать сверку');
|
||||
state = data; page = 0;
|
||||
render();
|
||||
function update(change) {
|
||||
// Быстрые изменения двух селекторов идут последовательно: каждый POST
|
||||
// получает ревизию после предыдущего, иначе второй законно вернёт 409.
|
||||
const operation = pending.catch(() => {}).then(async () => {
|
||||
const r = await authFetch(endpoint, {method: 'POST',
|
||||
headers: {'Content-Type': 'application/json'},
|
||||
body: JSON.stringify({revision: state._revision, ...change})});
|
||||
const data = await r.json().catch(() => ({}));
|
||||
if (!r.ok) throw new Error(data.detail || 'Не удалось пересчитать сверку');
|
||||
state = data; page = 0;
|
||||
render();
|
||||
});
|
||||
pending = operation;
|
||||
return operation;
|
||||
}
|
||||
function showError(message) {
|
||||
let status = panel.querySelector('.file-compare-status');
|
||||
|
||||
@@ -144,11 +144,13 @@ def test_plain_answer_zone_changes_inside_its_bubble(browser, site):
|
||||
}
|
||||
return oldFetch(url,opts);
|
||||
};
|
||||
const answer = addMsg('ai','Норма ГЭСНм 10-08-002-02, объём работ = 100 шт.\\nВыберите ценовую зону:\\n1. Хабаровский край (1 зона)\\n2. Хабаровский край (2 зона)');
|
||||
const answer = addMsg('ai','Норма ГЭСНм 10-08-002-02, объём работ = 100 шт.\\nУровень цен: III квартал 2025.\\nВыберите ценовую зону:\\n1. Хабаровский край (1 зона)\\n2. Хабаровский край (2 зона)');
|
||||
answer._messageId = 30;
|
||||
bindFreeformBasis(answer);
|
||||
}""")
|
||||
page.locator(".inline-basis-trigger").first.click()
|
||||
assert page.locator('select[aria-label="Квартал цен"]').input_value() == ""
|
||||
assert "не загружен" in page.locator('.inline-basis-picker').inner_text()
|
||||
screenshot_dir = os.environ.get("INLINE_FREEFORM_SCREENSHOTS")
|
||||
if screenshot_dir:
|
||||
page.screenshot(path=str(Path(screenshot_dir) / "inline-freeform-picker.png"))
|
||||
@@ -165,6 +167,146 @@ def test_plain_answer_zone_changes_inside_its_bubble(browser, site):
|
||||
page.close()
|
||||
|
||||
|
||||
def test_plain_answer_explains_required_quarter_before_recalculate(browser, site):
|
||||
page = browser.new_page(viewport={"width": 980, "height": 700})
|
||||
page.goto(site)
|
||||
page.evaluate("""() => {
|
||||
window._basisPosts = [];
|
||||
const oldFetch = window.fetch;
|
||||
window.fetch = async (url, opts={}) => {
|
||||
if (String(url).includes('/api/messages/30/basis')) {
|
||||
if (opts.method === 'POST') {
|
||||
window._basisPosts.push(JSON.parse(opts.body));
|
||||
return new Response(JSON.stringify({answer:'Пересчитано: 280 ₽.'}),
|
||||
{status:200,headers:{'Content-Type':'application/json'}});
|
||||
}
|
||||
return new Response(JSON.stringify({revision:'old-hash',zones:[
|
||||
{zone_id:118,name:'Хабаровский край (1 зона)',periods:[
|
||||
{period_id:428,name:'4 квартал 2026'}]},
|
||||
{zone_id:225,name:'Хабаровский край (3 зона)',periods:[
|
||||
{period_id:428,name:'4 квартал 2026'}]}
|
||||
]}), {status:200,headers:{'Content-Type':'application/json'}});
|
||||
}
|
||||
return oldFetch(url,opts);
|
||||
};
|
||||
const answer = addMsg('ai','Норма ГЭСНм 10-08-002-02, объём работ = 100 шт.\\n'
|
||||
+ 'Период цен: III квартал 2025.\\nХабаровский край (1 зона)');
|
||||
answer._messageId = 30;
|
||||
bindFreeformBasis(answer);
|
||||
}""")
|
||||
page.locator(".inline-basis-trigger").first.click()
|
||||
page.locator('select[aria-label="Ценовая зона"]').select_option("225")
|
||||
quarter = page.locator('select[aria-label="Квартал цен"]')
|
||||
assert quarter.input_value() == ""
|
||||
page.locator(".inline-basis-apply").click()
|
||||
assert "Выберите квартал" in page.locator('.inline-basis-picker [role="alert"]').inner_text(timeout=2000)
|
||||
assert quarter.get_attribute("aria-invalid") == "true"
|
||||
assert quarter.evaluate("el => document.activeElement === el")
|
||||
assert page.evaluate("window._basisPosts.length") == 0
|
||||
screenshot_dir = os.environ.get("INLINE_CHAT_UX_SCREENSHOTS")
|
||||
if screenshot_dir:
|
||||
page.screenshot(path=str(Path(screenshot_dir) / "quarter-required.png"))
|
||||
quarter.select_option("428")
|
||||
assert quarter.get_attribute("aria-invalid") != "true"
|
||||
page.locator(".inline-basis-apply").click()
|
||||
page.locator(".msg-ai .ai-body", has_text="280 ₽").wait_for(timeout=10000)
|
||||
assert page.evaluate("window._basisPosts.length") == 1
|
||||
assert page.evaluate("window._basisPosts[0].zone_id") == 225
|
||||
assert page.locator("#messages .msg-ai").count() == 1
|
||||
page.close()
|
||||
|
||||
|
||||
def test_wheel_over_short_answer_table_scrolls_chat(browser, site):
|
||||
page = browser.new_page(viewport={"width": 980, "height": 700})
|
||||
page.goto(site)
|
||||
page.evaluate("""() => {
|
||||
const answer = addMsg('ai','Таблица');
|
||||
const table = document.createElement('table');
|
||||
table.innerHTML = '<tr><th>Работа</th><th>Цена</th></tr><tr><td>Монтаж</td><td>100</td></tr>';
|
||||
answer.appendChild(table);
|
||||
enhanceTables(answer);
|
||||
for (let i = 0; i < 24; i++) addMsg('system','Следующее сообщение ' + i);
|
||||
}""")
|
||||
table = page.locator(".msg-ai .table-wrap").first
|
||||
assert table.count() == 1
|
||||
assert table.evaluate("el => el.scrollHeight <= el.clientHeight")
|
||||
table.hover()
|
||||
page.evaluate("document.querySelector('#messages').scrollTop = 0")
|
||||
page.mouse.wheel(0, 360)
|
||||
page.wait_for_timeout(200)
|
||||
assert page.evaluate("document.querySelector('#messages').scrollTop") > 0
|
||||
page.close()
|
||||
|
||||
|
||||
def test_wheel_at_tall_answer_table_edge_scrolls_chat(browser, site):
|
||||
page = browser.new_page(viewport={"width": 980, "height": 700})
|
||||
page.goto(site)
|
||||
page.evaluate("""() => {
|
||||
const answer = addMsg('ai','Длинная таблица');
|
||||
const table = document.createElement('table');
|
||||
table.innerHTML = '<tr><th>Работа</th><th>Цена</th></tr>'
|
||||
+ Array.from({length:50}, (_,i) => `<tr><td>Позиция ${i}</td><td>100</td></tr>`).join('');
|
||||
answer.appendChild(table);
|
||||
enhanceTables(answer);
|
||||
for (let i = 0; i < 24; i++) addMsg('system','Следующее сообщение ' + i);
|
||||
}""")
|
||||
table = page.locator(".msg-ai .table-wrap").first
|
||||
table.hover()
|
||||
assert table.evaluate("el => el.scrollHeight > el.clientHeight")
|
||||
page.evaluate("""() => {
|
||||
document.querySelector('.msg-ai .table-wrap').scrollTop = 0;
|
||||
document.querySelector('#messages').scrollTop = 0;
|
||||
}""")
|
||||
box = table.bounding_box()
|
||||
x, y = box["x"] + 20, box["y"] + 20
|
||||
page.mouse.move(x, y)
|
||||
assert page.evaluate("([x,y]) => !!document.elementFromPoint(x,y)?.closest('.table-wrap')", [x,y])
|
||||
page.mouse.wheel(0, 160)
|
||||
page.wait_for_timeout(100)
|
||||
assert table.evaluate("el => el.scrollTop") > 0
|
||||
assert page.evaluate("document.querySelector('#messages').scrollTop") == 0
|
||||
page.evaluate("""() => {
|
||||
document.querySelector('.msg-ai .table-wrap').scrollTop = 100000;
|
||||
document.querySelector('#messages').scrollTop = 0;
|
||||
}""")
|
||||
box = table.bounding_box()
|
||||
x, y = box["x"] + 20, box["y"] + 20
|
||||
page.mouse.move(x, y)
|
||||
assert page.evaluate("([x,y]) => !!document.elementFromPoint(x,y)?.closest('.table-wrap')", [x,y])
|
||||
page.mouse.wheel(0, 360)
|
||||
page.wait_for_timeout(200)
|
||||
assert page.evaluate("document.querySelector('#messages').scrollTop") > 0
|
||||
page.close()
|
||||
|
||||
|
||||
def test_wheel_at_estimate_panel_edge_scrolls_chat(browser, site):
|
||||
page = browser.new_page(viewport={"width": 980, "height": 700})
|
||||
page.goto(site)
|
||||
page.evaluate("""() => {
|
||||
const answer = addMsg('ai','Смета');
|
||||
const panel = document.createElement('div'); panel.className = 'est-panel';
|
||||
const scroll = document.createElement('div'); scroll.className = 'est-scroll';
|
||||
scroll.innerHTML = Array.from({length:50}, (_,i) => `<p>Позиция ${i}: 100 ₽</p>`).join('');
|
||||
panel.appendChild(scroll); answer.appendChild(panel);
|
||||
for (let i = 0; i < 24; i++) addMsg('system','Следующее сообщение ' + i);
|
||||
}""")
|
||||
panel = page.locator(".msg-ai .est-scroll").first
|
||||
panel.hover()
|
||||
assert panel.evaluate("el => el.scrollHeight > el.clientHeight")
|
||||
page.evaluate("""() => {
|
||||
document.querySelector('.msg-ai .est-scroll').scrollTop = 100000;
|
||||
document.querySelector('#messages').scrollTop = 0;
|
||||
}""")
|
||||
box = panel.bounding_box()
|
||||
x, y = box["x"] + 20, box["y"] + 20
|
||||
page.mouse.move(x, y)
|
||||
assert page.evaluate("([x,y]) => !!document.elementFromPoint(x,y)?.closest('.est-scroll')", [x,y])
|
||||
page.mouse.wheel(0, 360)
|
||||
page.wait_for_timeout(200)
|
||||
assert page.evaluate("document.querySelector('#messages').scrollTop") > 0
|
||||
page.close()
|
||||
|
||||
|
||||
def test_plain_zone_without_calculable_position_has_no_dead_selector(browser, site):
|
||||
page = browser.new_page()
|
||||
page.goto(site)
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
"""An isolated dev price snapshot must contain every catalogued form."""
|
||||
import json
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
def _catalog(root, name="264/118/428.json"):
|
||||
root.mkdir(parents=True, exist_ok=True)
|
||||
(root / "catalog.json").write_text(json.dumps({"zones": [{
|
||||
"subject_id": 264, "zone_id": 118, "period_id": 428,
|
||||
"zone_name": "Хабаровский край (1 зона)",
|
||||
"period_label": "4 квартал 2026", "file": name}]}), encoding="utf-8")
|
||||
|
||||
|
||||
def test_snapshot_validation_accepts_complete_catalog(tmp_path):
|
||||
from scripts.shadow.verify_engine_prices import validate
|
||||
_catalog(tmp_path)
|
||||
form = tmp_path / "264" / "118" / "428.json"
|
||||
form.parent.mkdir(parents=True)
|
||||
form.write_text("{}", encoding="utf-8")
|
||||
assert validate(tmp_path) == 1
|
||||
|
||||
|
||||
def test_snapshot_validation_rejects_missing_or_escaping_form(tmp_path):
|
||||
from scripts.shadow.verify_engine_prices import validate
|
||||
_catalog(tmp_path)
|
||||
with pytest.raises(ValueError, match="не найдена"):
|
||||
validate(tmp_path)
|
||||
_catalog(tmp_path, "../outside.json")
|
||||
with pytest.raises(ValueError, match="вне"):
|
||||
validate(tmp_path)
|
||||
|
||||
|
||||
def test_snapshot_validation_rejects_symlink_outside_snapshot(tmp_path):
|
||||
from scripts.shadow.verify_engine_prices import validate
|
||||
root = tmp_path / "snapshot"
|
||||
_catalog(root, "264/118/428.json")
|
||||
outside = tmp_path / "outside.json"
|
||||
outside.write_text("{}", encoding="utf-8")
|
||||
link = root / "264" / "118" / "428.json"
|
||||
link.parent.mkdir(parents=True)
|
||||
link.symlink_to(outside)
|
||||
with pytest.raises(ValueError, match="вне"):
|
||||
validate(root)
|
||||
Reference in New Issue
Block a user