feat: simplify KS-2 volume selection

This commit is contained in:
Арсентьев Александр
2026-10-15 17:24:53 +03:00
parent 3a3e481750
commit 9b67ace944
4 changed files with 615 additions and 42 deletions
@@ -0,0 +1,357 @@
"""REQ-KS2 quantity-only volume fill: no checkboxes, per-row and global fill buttons.
Протокол include_* на submit (без чекбоксов) — см. JS в form.html; серверный
контракт routers/ks2.py::_entries_from_form не менялся.
"""
import datetime
import re
from decimal import Decimal
from fastapi.testclient import TestClient
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.pool import StaticPool
from app.database.database import Base
from app.main import app
from app.models import boq
from app.models.project import Project
from app.models.daily_report import DailyReport, DailyReportItem
from app.models.ks2 import KS2, KS2Item, KS2ItemSource
from app.routers import projects as project_router, ks2 as ks2_router
def _make_env():
engine = create_engine("sqlite://", connect_args={"check_same_thread": False}, poolclass=StaticPool)
Base.metadata.create_all(engine)
TestingSession = sessionmaker(bind=engine, expire_on_commit=False)
with TestingSession() as db:
project = Project(name="REQ KS2 quantity fill")
db.add(project)
db.flush()
system = boq.System(project_id=project.id, name="Система A", code="A", sort_order=1)
db.add(system)
db.flush()
section = boq.Section(system_id=system.id, name="Раздел A")
db.add(section)
db.flush()
boq_doc = boq.BoqDocument(project_id=project.id, name="Ведомость")
db.add(boq_doc)
db.flush()
def add_wi(num, name, plan):
wi = boq.WorkItem(
project_id=project.id, boq_document_id=boq_doc.id,
system_id=system.id, section_id=section.id,
source_number=num, name=name, unit="м",
quantity=Decimal(plan), unit_price=Decimal("100"),
amount=Decimal(plan) * 100,
)
db.add(wi)
db.flush()
return wi
wi_full = add_wi("1", "Полностью доступна", "50")
wi_part = add_wi("2", "Частично закрыта", "40")
wi_zero = add_wi("3", "Без остатка", "10")
dr = DailyReport(project_id=project.id, report_date=datetime.date(2026, 1, 10))
db.add(dr)
db.flush()
dri = {}
for wi, qty in ((wi_full, "50"), (wi_part, "30"), (wi_zero, "10")):
item = DailyReportItem(daily_report_id=dr.id, work_item_id=wi.id,
completed_quantity=Decimal(qty))
db.add(item)
db.flush()
dri[wi.id] = item
ks2 = KS2(project_id=project.id, number="1", date=datetime.date(2026, 1, 15),
status="issued",
reporting_period_from=datetime.date(2026, 1, 1),
reporting_period_to=datetime.date(2026, 1, 31))
db.add(ks2)
db.flush()
for wi, qty in ((wi_zero, Decimal("10")), (wi_part, Decimal("10"))):
item = KS2Item(ks2_id=ks2.id, work_item_id=wi.id, quantity=qty,
unit_price=Decimal("100"), amount=qty * 100)
db.add(item)
db.flush()
db.add(KS2ItemSource(ks2_item_id=item.id, daily_report_item_id=dri[wi.id].id,
quantity=qty))
db.commit()
return {
"engine": engine,
"Session": TestingSession,
"pid": project.id,
"wi_full": wi_full.id,
"wi_part": wi_part.id,
"wi_zero": wi_zero.id,
}
def _with_client(env, fn):
def override_db():
db = env["Session"]()
try:
yield db
finally:
db.close()
for dep in (project_router.get_db, ks2_router.get_db):
app.dependency_overrides[dep] = override_db
try:
with TestClient(app) as client:
return fn(client)
finally:
for dep in (project_router.get_db, ks2_router.get_db):
app.dependency_overrides.pop(dep, None)
env["engine"].dispose()
def test_no_checkboxes_no_master_no_include_markup():
"""Чекбоксы, мастер-выбор и include_* в разметке формы отсутствуют."""
env = _make_env()
def check(client):
html = client.get(f"/projects/{env['pid']}/ks2/new").text
form = html.split('<form method="post"')[1].split('</form>')[0]
assert 'type="checkbox"' not in form
assert 'id="include-all"' not in form
assert 'include-check' not in form
assert 'name="include_' not in form
# JS-логика выбора удалена
assert 'selectAllAvailable' not in html
assert 'clearSelection' not in html
assert 'updateMasterState' not in html
assert 'bulkChange' not in html
_with_client(env, check)
def test_per_row_fill_button_present_and_not_submit():
"""В каждой строке — кнопка «Весь объём», type=button."""
env = _make_env()
def check(client):
html = client.get(f"/projects/{env['pid']}/ks2/new").text
# Кнопка в каждой видимой строке
assert html.count('class="btn btn-outline-success btn-sm fill-row"') >= 2
assert "Весь объём" in html
m = re.search(r'<button[^>]*class="[^"]*fill-row[^"]*"[^>]*>', html)
assert m
assert 'type="button"' in m.group(0)
# У строки без остатка кнопка disabled (строка с available<=0 на create скрыта
# сервером — правило проверяем по шаблону и edit).
template = open("app/templates/ks2/form.html", encoding="utf-8").read()
assert "{% if available <= 0 %}disabled{% endif %}" in template
_with_client(env, check)
def test_global_fill_button_present_and_not_submit():
"""Глобальная «Учесть весь объём» — type=button, не отправляет форму."""
env = _make_env()
def check(client):
html = client.get(f"/projects/{env['pid']}/ks2/new").text
m = re.search(r'<button[^>]*id="fill-available"[^>]*>', html)
assert m
assert 'type="button"' in m.group(0)
assert "Учесть весь объём" in html
_with_client(env, check)
def test_quantity_always_enabled_and_independent():
"""Количество всегда доступно для ввода и не зависит от кнопок."""
env = _make_env()
def check(client):
html = client.get(f"/projects/{env['pid']}/ks2/new").text
for wi_id in (env["wi_full"], env["wi_part"]):
m = re.search(rf'<input type="number"[^>]*name="quantity_{wi_id}"[^>]*>', html)
assert m, f"quantity input for {wi_id} missing"
assert "disabled" not in m.group(0)
# value подтягивается из form_values / selected
assert f'name="quantity_{wi_id}"' in html
# Ручной ввод: только пересчёт суммы
assert "updateAmount" in html
assert "this.checked" not in html
_with_client(env, check)
def test_js_fill_targets_available_and_submits_includes():
"""JS заполняет data-available; include_* собираются только на submit."""
env = _make_env()
def check(client):
html = client.get(f"/projects/{env['pid']}/ks2/new").text
# data-available в строках
assert f'data-available="50' in html or 'data-available="50.00"' in html
assert 'data-available="20' in html or 'data-available="20.00"' in html
# Запись в поле количества
assert "input.value = available" in html
# Протокол include_* на submit (не в разметке)
assert "include_" in html # код, создающий hidden на submit
assert "form.appendChild" in html
assert "submit" in html
# Не для «выбора», а для строк с количеством > 0
assert "qty > 0" in html
_with_client(env, check)
def test_values_restored_from_form_values_on_error():
"""При ошибке серверной валидации количество и поля формы восстанавливаются."""
env = _make_env()
def check(client):
resp = client.post(f"/projects/{env['pid']}/ks2", data={
"number": "KEEP-1",
"document_date": "2026-02-01",
"comment": "сохранить меня",
"reporting_period_from": "2026-01-01",
"reporting_period_to": "2026-01-31",
f"include_{env['wi_full']}": "1",
f"quantity_{env['wi_full']}": "999",
}, follow_redirects=False)
assert resp.status_code == 400
html = resp.text
assert re.search(rf'name="quantity_{env["wi_full"]}"[^>]*value="999"', html)
assert "сохранить меня" in html
# Чекбокс-логика не возвращается
assert 'type="checkbox"' not in html.split('<form method="post"')[1]
_with_client(env, check)
def test_server_rejects_exceeding_available():
"""Сервер: количество больше доступного остатка — отказ."""
env = _make_env()
def check(client):
resp = client.post(f"/projects/{env['pid']}/ks2", data={
"number": "OVER-1",
"document_date": "2026-02-01",
"comment": "",
"reporting_period_from": "2026-01-01",
"reporting_period_to": "2026-01-31",
f"include_{env['wi_part']}": "1",
f"quantity_{env['wi_part']}": "60",
}, follow_redirects=False)
assert resp.status_code == 400
list_page = client.get(f"/projects/{env['pid']}/ks2")
assert "OVER-1" not in list_page.text
_with_client(env, check)
def test_server_rejects_empty_selection_and_zero_quantity():
"""Сервер: без позиций и с нулевым количеством — отказ (правила не ослаблены)."""
env = _make_env()
def check(client):
empty = client.post(f"/projects/{env['pid']}/ks2", data={
"number": "EMPTY-1",
"document_date": "2026-02-01",
"comment": "",
"reporting_period_from": "2026-01-01",
"reporting_period_to": "2026-01-31",
}, follow_redirects=False)
assert empty.status_code == 400
zero = client.post(f"/projects/{env['pid']}/ks2", data={
"number": "ZERO-1",
"document_date": "2026-02-01",
"comment": "",
"reporting_period_from": "2026-01-01",
"reporting_period_to": "2026-01-31",
f"include_{env['wi_full']}": "1",
f"quantity_{env['wi_full']}": "0",
}, follow_redirects=False)
assert zero.status_code == 400
_with_client(env, check)
def test_server_rejects_double_close_of_same_volume():
"""Повторное закрытие уже закрытого объёма невозможно."""
env = _make_env()
def check(client):
ok = client.post(f"/projects/{env['pid']}/ks2", data={
"number": "CLOSE-1",
"document_date": "2026-02-01",
"comment": "",
"reporting_period_from": "2026-01-01",
"reporting_period_to": "2026-01-31",
f"include_{env['wi_part']}": "1",
f"quantity_{env['wi_part']}": "20",
}, follow_redirects=False)
assert ok.status_code == 303
ks2_id = int(ok.headers["location"].rsplit("/", 1)[1])
issue = client.post(f"/projects/{env['pid']}/ks2/{ks2_id}/issue",
follow_redirects=False)
assert issue.status_code == 303
again = client.post(f"/projects/{env['pid']}/ks2", data={
"number": "CLOSE-2",
"document_date": "2026-02-02",
"comment": "",
"reporting_period_from": "2026-01-01",
"reporting_period_to": "2026-01-31",
f"include_{env['wi_part']}": "1",
f"quantity_{env['wi_part']}": "5",
}, follow_redirects=False)
assert again.status_code == 400
_with_client(env, check)
def test_partial_close_still_works():
"""Частичное закрытие — полноценный сценарий."""
env = _make_env()
def check(client):
resp = client.post(f"/projects/{env['pid']}/ks2", data={
"number": "PART-1",
"document_date": "2026-02-01",
"comment": "",
"reporting_period_from": "2026-01-01",
"reporting_period_to": "2026-01-31",
f"include_{env['wi_part']}": "1",
f"quantity_{env['wi_part']}": "7.5",
}, follow_redirects=False)
assert resp.status_code == 303
view = client.get(resp.headers["location"])
assert "PART-1" in view.text
assert "7.50" in view.text or "7,50" in view.text
_with_client(env, check)
def test_edit_form_prefills_document_quantities():
"""В режиме редактирования количество строк документа подставлено, поля активны."""
env = _make_env()
def check(client):
created = client.post(f"/projects/{env['pid']}/ks2", data={
"number": "EDIT-1",
"document_date": "2026-02-01",
"comment": "",
"reporting_period_from": "2026-01-01",
"reporting_period_to": "2026-01-31",
f"include_{env['wi_full']}": "1",
f"quantity_{env['wi_full']}": "12",
}, follow_redirects=False)
assert created.status_code == 303
ks2_id = int(created.headers["location"].rsplit("/", 1)[1])
html = client.get(f"/projects/{env['pid']}/ks2/{ks2_id}/edit").text
assert re.search(rf'name="quantity_{env["wi_full"]}"[^>]*value="12', html)
m = re.search(rf'<input type="number"[^>]*name="quantity_{env["wi_full"]}"[^>]*>', html)
assert m and "disabled" not in m.group(0)
_with_client(env, check)