363 lines
18 KiB
Python
363 lines
18 KiB
Python
"""The price selector edits the current answer bubble in a real browser."""
|
|
import functools
|
|
import http.server
|
|
import os
|
|
import socketserver
|
|
import sys
|
|
import threading
|
|
from pathlib import Path
|
|
|
|
import pytest
|
|
|
|
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
|
pytest.importorskip("playwright.sync_api")
|
|
import ui_smoke_harness # noqa: E402
|
|
from test_password_reset_ui import browser # noqa: E402,F401
|
|
|
|
|
|
@pytest.fixture(scope="module")
|
|
def site(tmp_path_factory):
|
|
directory = tmp_path_factory.mktemp("inline-estimate")
|
|
ui_smoke_harness.build_stub(directory / "index.html", logged_in=True)
|
|
handler = functools.partial(http.server.SimpleHTTPRequestHandler, directory=str(directory))
|
|
|
|
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]}/index.html"
|
|
server.shutdown()
|
|
|
|
|
|
def test_choice_replaces_current_answer_without_new_bubble(browser, site):
|
|
page = browser.new_page(viewport={"width": 390, "height": 844})
|
|
page.goto(site)
|
|
page.wait_for_timeout(500)
|
|
page.evaluate("""() => {
|
|
const oldFetch = window.fetch;
|
|
window._basisPosts = [];
|
|
const old = {title:'Смета', _message_id:31, _assistant_id:30, _revision:0, ok:true,
|
|
positions:[{code:'ГЭСН 01-01-001-01',name:'Работа',unit:'м3',qty:2,total:100}],
|
|
totals:{grand_total:100}, applied:{subject:'Тестовый край',subject_id:1,
|
|
zone:'Тестовый край (1 зона)',zone_id:11,period:'3 квартал 2026',period_id:403}};
|
|
window.fetch = async (url, opts={}) => {
|
|
if (String(url).includes('/api/estimates/31/basis')) {
|
|
if (opts.method === 'POST') {
|
|
window._basisPosts.push(JSON.parse(opts.body));
|
|
return new Response(JSON.stringify({answer:'Итого: 240 ₽ · 4 квартал 2026',
|
|
estimate:{...old,_revision:1,
|
|
positions:[{...old.positions[0],total:240}],totals:{grand_total:240},
|
|
applied:{...old.applied,zone:'Тестовый край (2 зона)',zone_id:12,
|
|
period:'4 квартал 2026',period_id:404}}}),
|
|
{status:200,headers:{'Content-Type':'application/json'}});
|
|
}
|
|
return new Response(JSON.stringify({revision:0,zones:[
|
|
{zone_id:11,name:'Тестовый край (1 зона)',periods:[{period_id:403,name:'3 квартал 2026'}]},
|
|
{zone_id:12,name:'Тестовый край (2 зона)',periods:[
|
|
{period_id:402,name:'2 квартал 2026'},
|
|
{period_id:404,name:'4 квартал 2026'}]}]}),
|
|
{status:200,headers:{'Content-Type':'application/json'}});
|
|
}
|
|
return oldFetch(url,opts);
|
|
};
|
|
const answer = addMsg('ai','Исходный ответ: 100 ₽');
|
|
addEstimatePanel(old,null,answer);
|
|
window._answer = answer;
|
|
}""")
|
|
page.locator(".est-basis-picker button").click()
|
|
page.locator('select[aria-label="Ценовая зона"]').select_option("12")
|
|
page.wait_for_function("window._basisPosts.length === 1 && window._answer.innerText.includes('240')")
|
|
state = page.evaluate("""() => ({
|
|
bubbles: document.querySelectorAll('#messages .msg-ai').length,
|
|
within: !!window._answer.querySelector('.est-panel'),
|
|
text: window._answer.innerText,
|
|
posts: window._basisPosts,
|
|
cssWidth: window.innerWidth,
|
|
headDisplay: getComputedStyle(window._answer.querySelector('.est-header-row')).display,
|
|
hostClass: window._answer.className,
|
|
unitPrice: window._answer.querySelector('.est-table tr:not(.est-header-row) td:nth-child(6)')?.textContent,
|
|
horizontalOverflow: document.documentElement.scrollWidth > window.innerWidth
|
|
})""")
|
|
screenshot_dir = os.environ.get("INLINE_ESTIMATE_SCREENSHOTS")
|
|
if screenshot_dir:
|
|
page.evaluate("document.querySelector('#messages').scrollTop = 0")
|
|
page.screenshot(path=str(Path(screenshot_dir) / "inline-estimate-mobile.png"))
|
|
page.evaluate("document.querySelector('#messages').scrollTop = document.querySelector('#messages').scrollHeight")
|
|
page.screenshot(path=str(Path(screenshot_dir) / "inline-estimate-mobile-bottom.png"))
|
|
page.set_viewport_size({"width": 1280, "height": 800})
|
|
page.screenshot(path=str(Path(screenshot_dir) / "inline-estimate-desktop.png"))
|
|
page.close()
|
|
assert state["bubbles"] == 1 and state["within"]
|
|
assert "Исходный ответ: 100" not in state["text"]
|
|
assert "240" in state["text"] and "4 квартал 2026" in state["text"]
|
|
assert state["posts"][0]["zone_id"] == 12
|
|
assert state["posts"][0]["period_id"] == 404
|
|
assert state["unitPrice"] == "120,00"
|
|
assert state["headDisplay"] == "none", state
|
|
assert not state["horizontalOverflow"]
|
|
|
|
|
|
def test_norm_finder_entry_is_visible_after_login_on_desktop_and_phone(browser, site):
|
|
for width in (1280, 390):
|
|
page = browser.new_page(viewport={"width": width, "height": 800})
|
|
page.goto(site)
|
|
link = page.locator('#chat-screen .header-actions a[href="/podbor"]')
|
|
link.wait_for(state="visible")
|
|
assert link.inner_text() == "Подбор норм"
|
|
assert link.evaluate("el => el.getBoundingClientRect().width > 0")
|
|
page.close()
|
|
|
|
|
|
def test_saved_revision_reopens_inside_same_bubble(browser, site):
|
|
page = browser.new_page(viewport={"width": 390, "height": 844})
|
|
page.goto(site)
|
|
page.wait_for_timeout(500)
|
|
state = page.evaluate("""async () => {
|
|
const oldFetch = window.fetch;
|
|
window.fetch = async (url, opts={}) => {
|
|
if (String(url).includes('/api/history')) return new Response(JSON.stringify([
|
|
{id:30,role:'assistant',content:'Итого по локальной смете: 240 ₽',timestamp:1},
|
|
{id:31,role:'estimate',timestamp:2,content:JSON.stringify({
|
|
_assistant_id:30,_revision:1,title:'Смета',ok:true,
|
|
positions:[{code:'ГЭСН 01-01-001-01',name:'Работа',unit:'м3',qty:2,total:240}],
|
|
totals:{grand_total:240},applied:{subject:'Тестовый край',subject_id:1,
|
|
zone:'Тестовый край (2 зона)',zone_id:12,period:'4 квартал 2026',period_id:404}})}
|
|
]),{status:200,headers:{'Content-Type':'application/json'}});
|
|
return oldFetch(url,opts);
|
|
};
|
|
await loadHistory();
|
|
return {bubbles:document.querySelectorAll('#messages .msg-ai').length,
|
|
inside:!!document.querySelector('#messages .msg-ai .est-panel'),
|
|
text:document.querySelector('#messages .msg-ai')?.innerText || ''};
|
|
}""")
|
|
page.close()
|
|
assert state["bubbles"] == 1 and state["inside"]
|
|
assert "240" in state["text"] and "4 квартал 2026" in state["text"]
|
|
|
|
|
|
def test_plain_answer_zone_changes_inside_its_bubble(browser, site):
|
|
page = browser.new_page(viewport={"width": 390, "height": 844})
|
|
page.goto(site)
|
|
page.wait_for_timeout(500)
|
|
page.evaluate("""() => {
|
|
const oldFetch = window.fetch;
|
|
window.fetch = async (url, opts={}) => {
|
|
if (String(url).includes('/api/messages/30/basis')) {
|
|
if (opts.method === 'POST') return new Response(JSON.stringify({
|
|
answer:'Норма 10-08-002-02. Объём 100 шт. Ценовая зона: Хабаровский край (2 зона), 4 квартал 2026. Стоимость учтённой части: 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:179,name:'Хабаровский край (2 зона)',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Выберите ценовую зону:\\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"))
|
|
page.locator('select[aria-label="Ценовая зона"]').select_option("179")
|
|
page.locator('select[aria-label="Квартал цен"]').select_option("428")
|
|
page.locator(".inline-basis-apply").click()
|
|
page.locator(".msg-ai .ai-body", has_text="280 ₽").wait_for(timeout=10000)
|
|
assert page.locator("#messages .msg-ai").count() == 1
|
|
assert "Выберите ценовую зону" not in page.locator(".msg-ai").inner_text()
|
|
assert page.locator(".inline-basis-trigger").count() >= 1
|
|
assert page.evaluate("document.documentElement.scrollWidth <= window.innerWidth")
|
|
if screenshot_dir:
|
|
page.screenshot(path=str(Path(screenshot_dir) / "inline-freeform-updated.png"))
|
|
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)
|
|
page.wait_for_timeout(500)
|
|
count = page.evaluate("""() => {
|
|
const answer = addMsg('ai','Выберите ценовую зону: Хабаровский край (1 зона).');
|
|
answer._messageId = 40;
|
|
bindFreeformBasis(answer);
|
|
return answer.querySelectorAll('.inline-basis-trigger').length;
|
|
}""")
|
|
page.close()
|
|
assert count == 0
|
|
|
|
|
|
def test_saved_norm_draft_is_visible_and_sent_as_id_from_chat(browser, site):
|
|
page = browser.new_page(viewport={"width": 390, "height": 844})
|
|
page.goto(site)
|
|
state = page.evaluate("""async () => {
|
|
const oldFetch = window.fetch;
|
|
window._draftSent = [];
|
|
window.fetch = async (url, opts={}) => {
|
|
if (String(url).includes('/api/norm-finder/drafts/44'))
|
|
return new Response(JSON.stringify({id:44,revision:0,positions:[
|
|
{base:'2022',base_type:'ГЭСН',code:'11-01-011-01',
|
|
name:'Цементная стяжка',quantity:50,unit:'м2'}]}),
|
|
{status:200,headers:{'Content-Type':'application/json'}});
|
|
if (String(url).includes('/api/chat')) window._draftSent.push(JSON.parse(opts.body));
|
|
return oldFetch(url,opts);
|
|
};
|
|
history.replaceState(null,'','?norm_draft=44');
|
|
await loadNormDraftFromUrl();
|
|
return {visible:!document.getElementById('norm-draft-banner').hidden,
|
|
text:document.getElementById('norm-draft-summary').textContent,
|
|
link:document.getElementById('norm-draft-open').getAttribute('href')};
|
|
}""")
|
|
assert state["visible"] and '11-01-011-01' in state["text"]
|
|
assert state["link"] == '/podbor?draft=44'
|
|
page.evaluate("runChat('Проверь выбранные работы')")
|
|
assert page.evaluate('window._draftSent[0].norm_draft_id') == 44
|
|
page.evaluate('newChat()')
|
|
assert page.locator('#norm-draft-banner').is_hidden()
|
|
page.close()
|