180 lines
9.3 KiB
Python
180 lines
9.3 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_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Выберите ценовую зону:\\n1. Хабаровский край (1 зона)\\n2. Хабаровский край (2 зона)');
|
|
answer._messageId = 30;
|
|
bindFreeformBasis(answer);
|
|
}""")
|
|
page.locator(".inline-basis-trigger").first.click()
|
|
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_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
|