Save multi-position norm drafts and open public catalog

This commit is contained in:
anor
2026-12-04 05:54:55 +10:00
parent b062214336
commit 7ad5ac0531
10 changed files with 779 additions and 28 deletions
+30
View File
@@ -319,3 +319,33 @@ def test_plain_zone_without_calculable_position_has_no_dead_selector(browser, si
}""")
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()
+121 -1
View File
@@ -164,6 +164,10 @@ def api(tmp_path, monkeypatch):
("post", "/api/norm-finder/calculate"),
("get", "/api/norm-finder/quotes/1"),
("post", "/api/norm-finder/quotes/1"),
("post", "/api/norm-finder/drafts"),
("get", "/api/norm-finder/drafts/1"),
("put", "/api/norm-finder/drafts/1"),
("post", "/api/norm-finder/drafts/1/calculate"),
])
def test_finder_requires_login(api, method, path):
client, _, _ = api
@@ -224,4 +228,120 @@ def test_finder_page_is_reachable_from_site(api):
assert page.status_code == 200
assert "Подбор норм" in page.text
assert 'src="/static/norm-finder.js"' in page.text
assert "/podbor" in client.get("/").text
assert 'href="/podbor">Найти норму без входа</a>' in client.get("/").text
def test_finder_draft_is_scoped_revisioned_and_never_totals_missing_costs(api, monkeypatch):
import auth
import engine_prices
import norm_finder
client, headers, db = api
monkeypatch.setattr(norm_finder, "detail", lambda base, kind, code: {
"base": "ГЭСН-2022", "base_type": kind, "code": code,
"name": "Стяжка " + code, "unit": "100 м2"})
monkeypatch.setattr(norm_finder, "calculate", lambda base, kind, code, qty, unit, zone, period: {
"status": "ok", "complete": code.endswith("-01"),
"total": qty * 100 if code.endswith("-01") else None,
"accounted": None if code.endswith("-01") else qty * 20,
"missing": [] if code.endswith("-01") else [{"reason": "Нет цены ресурса"}]})
monkeypatch.setattr(engine_prices, "basis_options", lambda sid: [{
"zone_id": 118, "name": "Хабаровский край (1 зона)",
"periods": [{"period_id": 428, "name": "4 квартал 2026"}]}] if sid == 264 else [])
positions = [{"base": "2022", "base_type": "ГЭСН", "code": "11-01-011-01",
"unit": "м2", "quantity": 50},
{"base": "2022", "base_type": "ГЭСН", "code": "11-01-011-12",
"unit": "100 м2", "quantity": 2}]
invalid = [{**positions[0], "unit": "м3"}]
assert client.post("/api/norm-finder/drafts", json={"positions": invalid}, headers=headers).status_code == 400
created = client.post("/api/norm-finder/drafts", json={"positions": positions}, headers=headers)
assert created.status_code == 200, created.text
draft = created.json()
assert draft["revision"] == 0 and len(draft["positions"]) == 2
assert db.get_history("finder@x", "tab")[-1]["role"] == "norm_draft"
url = f"/api/norm-finder/drafts/{draft['id']}"
db.create_user("other@x", auth.hash_password("Passw0rd!ok"))
db.admin_verify_user("other@x")
other = {"Authorization": "Bearer " + auth._make_token("other@x"), "X-Tab-Id": "tab"}
wrong_tab = {**headers, "X-Tab-Id": "other-tab"}
assert client.get(url, headers=other).status_code == 404
assert client.get(url, headers=wrong_tab).status_code == 404
assert client.put(url, json={"revision": 0, "positions": positions}, headers=other).status_code == 404
updated = client.put(url, json={"revision": 0, "positions": [
{**positions[0], "quantity": 60}, positions[1]]}, headers=headers)
assert updated.status_code == 200 and updated.json()["revision"] == 1
assert client.put(url, json={"revision": 0, "positions": positions}, headers=headers).status_code == 409
calc = url + "/calculate"
basis = {"revision": 1, "subject_id": 264, "zone_id": 118, "period_id": 428}
assert client.post(calc, json={**basis, "period_id": 999}, headers=headers).status_code == 400
response = client.post(calc, json=basis, headers=headers)
assert response.status_code == 200, response.text
result = response.json()
assert result["revision"] == 2
assert result["calculation"]["complete"] is False
assert result["calculation"]["total"] is None
assert result["calculation"]["accounted"] == 6040
assert client.post(calc, json=basis, headers=headers).status_code == 409
assert client.get(url, headers=headers).json()["calculation"] == result["calculation"]
def test_chat_receives_scoped_draft_context_without_replacing_user_question(api, monkeypatch):
import auth
import main
import norm_draft
import norm_finder
client, headers, db = api
monkeypatch.setattr(norm_finder, "detail", lambda base, kind, code: {
"base": "ГЭСН-2022", "base_type": kind, "code": code,
"name": "Цементная стяжка", "unit": "100 м2"})
position = {"base": "2022", "base_type": "ГЭСН", "code": "11-01-011-01",
"quantity": 50, "unit": "м2"}
draft = client.post("/api/norm-finder/drafts", json={"positions": [position]}, headers=headers).json()
db.create_user("other@x", auth.hash_password("Passw0rd!ok"))
db.admin_verify_user("other@x")
other = {"Authorization": "Bearer " + auth._make_token("other@x"), "X-Tab-Id": "other-tab"}
payload = {"message": "Проверь выбранные работы", "norm_draft_id": draft["id"]}
monkeypatch.setattr(main, "safe_work_dir", lambda *a, **k: None)
monkeypatch.setattr(main, "_trial_state", lambda *a: None)
assert client.post("/api/chat", json=payload, headers=other).status_code == 404
monkeypatch.setattr(main, "_check_rate_limit", lambda *a: None)
monkeypatch.setattr(main, "_refuse_if_read_only", lambda *a: None)
monkeypatch.setattr(main, "_refuse_if_trial_over", lambda *a: None)
async def no_limits(*args):
return None
monkeypatch.setattr(main, "_check_limits", no_limits)
monkeypatch.setattr(db, "get_app_setting", lambda key, default=None: "off")
seen = []
async def fake_stream(message, user, tab, context=""):
seen.append((message, context))
yield 'event: done\ndata: {"result":"ok"}\n\n'
monkeypatch.setattr(main, "_stream_and_save", fake_stream)
response = client.post("/api/chat", json=payload, headers=headers)
assert response.status_code == 200, response.text
assert seen[0][0] == "Проверь выбранные работы"
assert "11-01-011-01" in seen[0][1] and "50.0" in seen[0][1]
assert "ПОДБОРКА" in seen[0][1]
assert "total" not in norm_draft.agent_context({"positions": draft["positions"],
"calculation": {"complete": False, "total": 9999}})
def test_public_norm_catalog_is_read_only_bounded_and_anonymous(api, monkeypatch):
import main
import norm_finder
client, _, _ = api
main._public_finder_rate.clear()
monkeypatch.setattr(norm_finder, "catalog", lambda: [{"base": "ГЭСН-2022", "count": 56192}])
monkeypatch.setattr(norm_finder, "search", lambda q, base, limit: {
"status": "ok", "items": [{"code": "11-01-011-01", "name": "Стяжка"}], "shown": 1})
monkeypatch.setattr(norm_finder, "detail", lambda base, kind, code: {
"base": "ГЭСН-2022", "base_type": kind, "code": code, "name": "Стяжка", "resources": []})
assert client.get("/api/public/norm-finder/catalog").status_code == 200
assert client.get("/api/public/norm-finder/catalog", headers={
"Authorization": "Bearer ", "X-Tab-Id": "guest-tab"}).status_code == 200
assert client.get("/api/public/norm-finder/search?q=стяжка").json()["items"][0]["code"] == "11-01-011-01"
assert client.get("/api/public/norm-finder/detail?base=2022&base_type=ГЭСН&code=11-01-011-01").status_code == 200
assert client.get("/api/public/norm-finder/search?q=стяжка&limit=9").status_code == 400
assert client.post("/api/norm-finder/drafts", json={"positions": []}).status_code == 401
for _ in range(25):
assert client.get("/api/public/norm-finder/search?q=стяжка").status_code == 200
blocked = client.get("/api/public/norm-finder/search?q=стяжка")
assert blocked.status_code == 429 and blocked.headers["Retry-After"] == "60"
+120
View File
@@ -1,11 +1,14 @@
"""The real norm finder lets a person inspect nearby variants in the same table."""
import functools
import http.server
import os
import shutil
import socketserver
import sys
import threading
import json
from pathlib import Path
from urllib.parse import unquote, urlsplit
import pytest
@@ -74,3 +77,120 @@ def test_family_variants_can_be_opened_and_compared_on_phone(browser, site):
assert page.locator('#detail').inner_text().find('100 м2') >= 0
assert page.evaluate('document.documentElement.scrollWidth <= window.innerWidth')
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",
"name": "Цементная стяжка", "unit": "100 м2", "current_price_supported": True}
second = {"base": "ГЭСН-2022", "base_type": "ГЭСН", "code": "06-01-001-01",
"name": "Бетонная работа", "unit": "м3", "current_price_supported": True}
def handle(route):
request = route.request
path = urlsplit(request.url).path
method = request.method
body = request.post_data_json if method in {"POST", "PUT"} else {}
if path.endswith("/catalog"):
data = {"bases": [{"base": "ГЭСН-2022", "count": 56192}],
"subjects": [{"id": 264, "name": "Хабаровский край"}]}
elif path.endswith("/search"):
data = {"items": [second if "бетон" in unquote(request.url) else first]}
elif path.endswith("/detail"):
chosen = second if second["code"] in request.url else first
data = {**chosen, "content": ["Работа"], "resources": [], "provenance": {}}
elif path.endswith("/prices"):
data = {"zones": [{"zone_id": 118, "name": "Хабаровский край (1 зона)",
"periods": [{"period_id": 428, "name": "4 квартал 2026"}]}]}
elif path.endswith("/drafts") and method == "POST":
state["draft"] = {"id": 44, "revision": 0, "positions": body["positions"],
"price_selection": None, "calculation": None}
data = state["draft"]
elif path.endswith("/drafts/44") and method == "GET":
data = state["draft"]
elif path.endswith("/drafts/44") and method == "PUT":
state["draft"] = {**state["draft"], "revision": state["draft"]["revision"] + 1,
"positions": body["positions"], "calculation": None}
data = state["draft"]
elif path.endswith("/drafts/44/calculate"):
assert body["revision"] == state["draft"]["revision"]
state["draft"] = {**state["draft"], "revision": state["draft"]["revision"] + 1,
"price_selection": {"subject_id": 264, "zone_id": 118, "period_id": 428},
"calculation": {"zone": "Хабаровский край (1 зона)",
"period": "4 квартал 2026", "complete": False, "total": None,
"accounted": 1200, "lines": [{"position": p,
"result": {"complete": False, "message": "Нет цены ресурса"}}
for p in state["draft"]["positions"]]}}
data = state["draft"]
else:
route.fulfill(status=404, content_type="application/json", body="{}")
return
route.fulfill(status=200, content_type="application/json", body=json.dumps(data, ensure_ascii=False))
page = browser.new_page(viewport={"width": 390, "height": 844})
page.add_init_script("localStorage.setItem('token', 'x.eyJzdWIiOiJ0ZXN0QHgifQ.y')")
page.route("**/api/norm-finder/**", handle)
page.goto(site)
page.locator('#query').fill('стяжка')
page.locator('#search-form button[type="submit"]').click()
page.locator('button', has_text='Открыть состав').first.click()
page.locator('#qty').fill('50')
page.locator('#add-draft').click()
page.locator('#draft-positions .draft-row').first.wait_for()
assert page.locator('#draft-positions input').input_value() == '50'
page.reload()
page.locator('#draft-positions .draft-row').first.wait_for()
assert page.locator('#draft-positions input').input_value() == '50'
page.locator('#query').fill('бетон')
page.locator('#search-form button[type="submit"]').click()
page.locator('button', has_text='Открыть состав').first.click()
page.locator('#qty').fill('2')
page.locator('#add-draft').click()
page.locator('#draft-positions .draft-row').nth(1).wait_for()
page.locator('#subject').select_option('264')
page.locator('#zone option[value="118"]').wait_for(state="attached")
page.locator('#zone').select_option('118')
page.locator('#period').select_option('428')
page.locator('#draft-calc').click()
page.locator('#draft-result', has_text='Расчёт неполный').wait_for()
assert 'Стоимость только учтённой части' in page.locator('#draft-result').inner_text()
assert 'итог всей подборки: 1 200' not in page.locator('#draft-result').inner_text()
assert page.locator('#draft-chat').get_attribute('href') == '/?norm_draft=44'
screenshot_dir = os.environ.get('NORM_FINDER_SCREENSHOTS')
if screenshot_dir:
page.screenshot(path=str(Path(screenshot_dir) / 'norm-finder-draft-mobile.png'), full_page=True)
page.close()
def test_guest_can_search_and_read_norm_but_not_see_price_controls(browser, site):
page = browser.new_page(viewport={"width": 390, "height": 844})
seen = []
def handle(route):
path = urlsplit(route.request.url).path
seen.append(path)
if path.endswith("/catalog"):
data = {"bases": [{"base": "ГЭСН-2022", "count": 56192}]}
elif path.endswith("/search"):
data = {"items": [{"base": "ГЭСН-2022", "base_type": "ГЭСН",
"code": "11-01-011-01", "name": "Цементная стяжка", "unit": "100 м2"}]}
else:
data = {"base": "ГЭСН-2022", "base_type": "ГЭСН", "code": "11-01-011-01",
"name": "Цементная стяжка", "unit": "100 м2", "content": ["Работа"],
"resources": [], "provenance": {}, "current_price_supported": False}
route.fulfill(status=200, content_type="application/json", body=json.dumps(data, ensure_ascii=False))
page.route("**/api/public/norm-finder/**", handle)
page.goto(site)
page.locator('#auth-notice').wait_for(state="visible")
page.locator('#query').fill('стяжка')
page.locator('#search-form button[type="submit"]').click()
page.locator('button', has_text='Открыть состав').first.click()
page.locator('#detail-title', has_text='11-01-011-01').wait_for()
assert page.locator('#quote-panel').is_hidden()
assert all(path.startswith('/api/public/norm-finder/') for path in seen)
assert page.evaluate('document.documentElement.scrollWidth <= window.innerWidth')
screenshot_dir = os.environ.get('NORM_FINDER_SCREENSHOTS')
if screenshot_dir:
page.screenshot(path=str(Path(screenshot_dir) / 'norm-finder-guest-mobile.png'), full_page=True)
page.close()