feat: UI/UX cleanup V1 with header, import requisites, and status fixes
This commit is contained in:
@@ -10,6 +10,7 @@ DAILY_REPORT_OPTIONAL_SYSTEM_MIGRATION = "20260925_daily_report_optional_system"
|
||||
KS2_REPORTING_PERIOD_MIGRATION = "20260925_ks2_reporting_period"
|
||||
PAYMENT_STATUS_MIGRATION = "20260926_payment_status"
|
||||
KS3_NUMBER_UNIQUE_MIGRATION = "20260927_ks3_number_unique"
|
||||
BOQ_DOCUMENT_REQUISITES_MIGRATION = "20260928_boq_document_requisites"
|
||||
|
||||
|
||||
def run_migrations(engine):
|
||||
@@ -198,6 +199,16 @@ def run_migrations(engine):
|
||||
)
|
||||
connection.execute("INSERT INTO schema_migrations(version, applied_at) VALUES (?, ?)",
|
||||
(KS3_NUMBER_UNIQUE_MIGRATION, datetime.now(timezone.utc).isoformat()))
|
||||
if BOQ_DOCUMENT_REQUISITES_MIGRATION not in applied:
|
||||
doc_cols = {row[1] for row in connection.execute("PRAGMA table_info(boq_documents)")}
|
||||
if "document_number" not in doc_cols:
|
||||
connection.execute("ALTER TABLE boq_documents ADD COLUMN document_number VARCHAR")
|
||||
if "document_date" not in doc_cols:
|
||||
connection.execute("ALTER TABLE boq_documents ADD COLUMN document_date DATE")
|
||||
if "contract" not in doc_cols:
|
||||
connection.execute("ALTER TABLE boq_documents ADD COLUMN contract VARCHAR")
|
||||
connection.execute("INSERT INTO schema_migrations(version, applied_at) VALUES (?, ?)",
|
||||
(BOQ_DOCUMENT_REQUISITES_MIGRATION, datetime.now(timezone.utc).isoformat()))
|
||||
violations = connection.execute("PRAGMA foreign_key_check").fetchall()
|
||||
if violations:
|
||||
raise RuntimeError(f"Foreign key violations after agreement migration: {violations[:10]}")
|
||||
|
||||
@@ -161,13 +161,32 @@ def preview_excel_data(file_path: str, sheet_name: str, header_row: int, start_r
|
||||
return parsed
|
||||
|
||||
|
||||
def import_excel_data(db: Session, file_path: str, sheet_name: str, header_row: int, start_row: int, project_id: int) -> Dict[str, Any]:
|
||||
def import_excel_data(
|
||||
db: Session,
|
||||
file_path: str,
|
||||
sheet_name: str,
|
||||
header_row: int,
|
||||
start_row: int,
|
||||
project_id: int,
|
||||
document_name: Optional[str] = None,
|
||||
document_number: Optional[str] = None,
|
||||
document_date: Optional[Any] = None,
|
||||
contract: Optional[str] = None,
|
||||
) -> Dict[str, Any]:
|
||||
parsed = parse_excel_data(file_path, sheet_name, header_row, start_row)
|
||||
if parsed["errors"]:
|
||||
raise ValueError("\n".join(parsed["errors"]))
|
||||
name = (document_name or "").strip() or f"Импорт ведомости — {sheet_name}"
|
||||
try:
|
||||
doc = boq.BoqDocument(project_id=project_id, name=f"Импорт ведомости — {sheet_name}",
|
||||
source_file=Path(file_path).name, version="1.0")
|
||||
doc = boq.BoqDocument(
|
||||
project_id=project_id,
|
||||
name=name,
|
||||
source_file=Path(file_path).name,
|
||||
version="1.0",
|
||||
document_number=(document_number or "").strip() or None,
|
||||
document_date=document_date,
|
||||
contract=(contract or "").strip() or None,
|
||||
)
|
||||
db.add(doc)
|
||||
db.flush()
|
||||
systems: Dict[str, boq.System] = {}
|
||||
@@ -202,7 +221,8 @@ def import_excel_data(db: Session, file_path: str, sheet_name: str, header_row:
|
||||
).scalar()
|
||||
db_total_display = Decimal(str(db_total or 0)).quantize(Decimal("0.01"))
|
||||
excel_total_display = parsed["excel_total"].quantize(Decimal("0.01"))
|
||||
return {"status": "success", "document_id": doc.id, "systems": len(systems), "sections": len(sections),
|
||||
return {"status": "success", "document_id": doc.id, "document_name": doc.display_name,
|
||||
"systems": len(systems), "sections": len(sections),
|
||||
"work_items": parsed["work_items_count"], "total_amount": db_total_display,
|
||||
"db_total": db_total_display, "excel_total": excel_total_display,
|
||||
"difference": db_total_display - excel_total_display}
|
||||
|
||||
@@ -14,12 +14,35 @@ class BoqDocument(Base):
|
||||
name = Column(String, nullable=False)
|
||||
version = Column(String)
|
||||
source_file = Column(String)
|
||||
document_number = Column(String)
|
||||
document_date = Column(Date)
|
||||
contract = Column(String)
|
||||
created_at = Column(DateTime, default=func.now())
|
||||
|
||||
# Relationship to project
|
||||
project = relationship("Project", back_populates="boq_documents")
|
||||
agreement = relationship("Agreement", back_populates="boq_documents", foreign_keys=[agreement_id])
|
||||
|
||||
_TECHNICAL_PREFIXES = (
|
||||
"BOQ Import - ",
|
||||
"BOQ Import — ",
|
||||
"BOQ Import —",
|
||||
"BOQ Import -",
|
||||
"Импорт ведомости — ",
|
||||
"Импорт ведомости - ",
|
||||
"Импорт ведомости —",
|
||||
"Импорт ведомости -",
|
||||
)
|
||||
|
||||
@property
|
||||
def display_name(self) -> str:
|
||||
name = (self.name or "").strip()
|
||||
for prefix in self._TECHNICAL_PREFIXES:
|
||||
if name.startswith(prefix):
|
||||
name = name[len(prefix):].strip(" —-–")
|
||||
break
|
||||
return name or f"Ведомость #{self.id}"
|
||||
|
||||
def __repr__(self):
|
||||
return f"<BoqDocument(id={self.id}, name='{self.name}')>"
|
||||
|
||||
|
||||
@@ -61,7 +61,7 @@ def _scope_label(agreement, docs):
|
||||
if agreement.boq_document_id is None:
|
||||
return "Весь проект"
|
||||
doc = next((doc for doc in docs if doc.id == agreement.boq_document_id), None)
|
||||
return doc.name if doc else f"Ведомость #{agreement.boq_document_id}"
|
||||
return doc.display_name if doc else f"Ведомость #{agreement.boq_document_id}"
|
||||
|
||||
|
||||
def _parse_scope(db, project_id, scope):
|
||||
|
||||
+42
-6
@@ -6,6 +6,7 @@ from app.models import project, boq
|
||||
from app.models.daily_report import DailyReport, DailyReportItem
|
||||
from app.importer import excel_importer
|
||||
import os
|
||||
from datetime import date
|
||||
from decimal import Decimal
|
||||
from pathlib import Path
|
||||
|
||||
@@ -59,9 +60,7 @@ async def view_boq_document(request: Request, project_id: int, document_id: int,
|
||||
).first()
|
||||
if document is None:
|
||||
raise HTTPException(status_code=404, detail="BOQ document not found")
|
||||
document_title = document.name.replace("BOQ Import - ", "Импорт ведомости — ").replace(
|
||||
"BOQ Import — ", "Импорт ведомости — "
|
||||
)
|
||||
document_title = document.display_name
|
||||
|
||||
items = db.query(boq.WorkItem).filter(
|
||||
boq.WorkItem.boq_document_id == document_id,
|
||||
@@ -150,6 +149,10 @@ async def upload_excel_file(
|
||||
request: Request,
|
||||
project_id: int,
|
||||
file: UploadFile = File(...),
|
||||
document_name: str = Form(""),
|
||||
document_number: str = Form(""),
|
||||
document_date: str = Form(""),
|
||||
contract: str = Form(""),
|
||||
db: Session = Depends(get_db)
|
||||
):
|
||||
db_project = db.query(project.Project).filter(project.Project.id == project_id).first()
|
||||
@@ -171,7 +174,11 @@ async def upload_excel_file(
|
||||
"project": db_project,
|
||||
"project_id": project_id,
|
||||
"filename": filename,
|
||||
"sheets": sheets
|
||||
"sheets": sheets,
|
||||
"document_name": document_name,
|
||||
"document_number": document_number,
|
||||
"document_date": document_date,
|
||||
"contract": contract,
|
||||
})
|
||||
|
||||
@router.post("/{project_id}/import/preview")
|
||||
@@ -182,6 +189,10 @@ async def preview_import(
|
||||
sheet_name: str = Form(...),
|
||||
header_row: int = Form(...),
|
||||
start_row: int = Form(...),
|
||||
document_name: str = Form(""),
|
||||
document_number: str = Form(""),
|
||||
document_date: str = Form(""),
|
||||
contract: str = Form(""),
|
||||
db: Session = Depends(get_db)
|
||||
):
|
||||
# Get the file path
|
||||
@@ -205,9 +216,20 @@ async def preview_import(
|
||||
"filename": filename,
|
||||
"sheet_name": sheet_name,
|
||||
"header_row": header_row,
|
||||
"start_row": start_row
|
||||
"start_row": start_row,
|
||||
"document_name": document_name or sheet_name,
|
||||
"document_number": document_number,
|
||||
"document_date": document_date,
|
||||
"contract": contract or (db_project.contract_number or ""),
|
||||
})
|
||||
|
||||
def _parse_optional_date(value: str):
|
||||
value = (value or "").strip()
|
||||
if not value:
|
||||
return None
|
||||
return date.fromisoformat(value)
|
||||
|
||||
|
||||
@router.post("/{project_id}/import/confirm")
|
||||
async def confirm_import(
|
||||
request: Request,
|
||||
@@ -216,6 +238,10 @@ async def confirm_import(
|
||||
sheet_name: str = Form(...),
|
||||
header_row: int = Form(...),
|
||||
start_row: int = Form(...),
|
||||
document_name: str = Form(""),
|
||||
document_number: str = Form(""),
|
||||
document_date: str = Form(""),
|
||||
contract: str = Form(""),
|
||||
db: Session = Depends(get_db)
|
||||
):
|
||||
# Get the file path
|
||||
@@ -226,7 +252,17 @@ async def confirm_import(
|
||||
if db_project is None:
|
||||
raise HTTPException(status_code=404, detail="Project not found")
|
||||
try:
|
||||
result = excel_importer.import_excel_data(db, file_path, sheet_name, header_row, start_row, project_id)
|
||||
parsed_date = _parse_optional_date(document_date)
|
||||
except ValueError as exc:
|
||||
raise HTTPException(status_code=400, detail="Дата ведомости должна быть в формате ГГГГ-ММ-ДД") from exc
|
||||
try:
|
||||
result = excel_importer.import_excel_data(
|
||||
db, file_path, sheet_name, header_row, start_row, project_id,
|
||||
document_name=document_name,
|
||||
document_number=document_number,
|
||||
document_date=parsed_date,
|
||||
contract=contract,
|
||||
)
|
||||
except (ValueError, OSError) as exc:
|
||||
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
||||
|
||||
|
||||
@@ -1,18 +1,18 @@
|
||||
<!doctype html><html lang="ru"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>ДС №{{ agreement.number }} — {{ project.name }}</title><link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet"><style>.numeric{font-variant-numeric:tabular-nums;white-space:nowrap}.item-name{min-width:16rem}</style></head><body class="bg-light"><main class="container-fluid container-xxl py-4">
|
||||
<!doctype html><html lang="ru"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>ДС №{{ agreement.number }} — {{ project.name }}</title><link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet"><style>.numeric{font-variant-numeric:tabular-nums;white-space:nowrap}.item-name{min-width:16rem}</style></head><body class="bg-light"><main class="container-fluid container-xxl py-4">
|
||||
<nav><ol class="breadcrumb"><li class="breadcrumb-item"><a href="/projects/">Проекты</a></li><li class="breadcrumb-item"><a href="/projects/{{ project.id }}">{{ project.name }}</a></li><li class="breadcrumb-item"><a href="/projects/{{ project.id }}/agreements">ДС</a></li><li class="breadcrumb-item active">№{{ agreement.number }}</li></ol></nav>
|
||||
{% if error %}<div class="alert alert-danger" role="alert">{{ error }}</div>{% endif %}
|
||||
<header class="d-flex flex-wrap justify-content-between align-items-start gap-3 mb-4"><div><h1 class="h2 mb-1">ДС №{{ agreement.number }} — {{ agreement.title }}</h1><div class="text-muted">{{ agreement.date.strftime('%d.%m.%Y') }} · {{ scope_label }}</div></div><div class="d-flex gap-2"><a class="btn btn-outline-secondary" href="/projects/{{ project.id }}/agreements">К списку</a>{% if agreement.status == 'approved' %}<span class="badge text-bg-success align-self-center">Утверждено</span>{% else %}<span class="badge text-bg-secondary align-self-center">Черновик</span>{% endif %}</div></header>
|
||||
{% if agreement.status == 'draft' %}
|
||||
<section class="card border-0 shadow-sm mb-4"><div class="card-header bg-white"><h2 class="h5 mb-0">Реквизиты ДС</h2></div><form method="post" action="/projects/{{ project.id }}/agreements/{{ agreement.id }}/update"><div class="card-body row g-3">
|
||||
<div class="col-md-3"><label class="form-label">Номер</label><input class="form-control" name="number" value="{{ agreement.number }}" required></div><div class="col-md-3"><label class="form-label">Дата</label><input class="form-control" type="date" name="agreement_date" value="{{ agreement.date.isoformat() }}" required></div><div class="col-md-6"><label class="form-label">Наименование</label><input class="form-control" name="title" value="{{ agreement.title }}" required></div><div class="col-12"><label class="form-label">Описание</label><textarea class="form-control" name="description" rows="2">{{ agreement.description or '' }}</textarea></div>
|
||||
<div class="col-md-7"><label class="form-label">Область применения</label><select class="form-select" name="scope" required><option value="project" {% if agreement.boq_document_id is none %}selected{% endif %}>Весь проект</option>{% for doc in boq_documents %}<option value="boq:{{ doc.id }}" {% if agreement.boq_document_id == doc.id %}selected{% endif %}>{{ doc.name }}</option>{% endfor %}</select></div></div><div class="card-footer bg-white"><button class="btn btn-outline-primary" type="submit">Сохранить реквизиты</button></div></form></section>
|
||||
<div class="col-md-7"><label class="form-label">Область применения</label><select class="form-select" name="scope" required><option value="project" {% if agreement.boq_document_id is none %}selected{% endif %}>Весь проект</option>{% for doc in boq_documents %}<option value="boq:{{ doc.id }}" {% if agreement.boq_document_id == doc.id %}selected{% endif %}>{{ doc.display_name }}</option>{% endfor %}</select></div></div><div class="card-footer bg-white"><button class="btn btn-outline-primary" type="submit">Сохранить реквизиты</button></div></form></section>
|
||||
{% else %}<section class="card border-0 shadow-sm mb-4"><div class="card-body row g-3"><div class="col-md-3"><span class="text-muted">Номер:</span> <strong>{{ agreement.number }}</strong></div><div class="col-md-3"><span class="text-muted">Дата:</span> {{ agreement.date.strftime('%d.%m.%Y') }}</div><div class="col-md-6"><span class="text-muted">Область:</span> {{ scope_label }}</div><div class="col-12"><span class="text-muted">Описание:</span> {{ agreement.description or '—' }}</div></div></section>{% endif %}
|
||||
<section class="card border-0 shadow-sm mb-4"><div class="card-header bg-white d-flex justify-content-between"><h2 class="h5 mb-0">Позиции ДС</h2><span>{{ line_rows|length }} поз.</span></div><div class="table-responsive"><table class="table table-hover align-middle mb-0"><thead><tr><th>Тип</th><th>№ / Позиция</th><th>Ед.</th><th class="text-end">Базовое / текущее</th><th class="text-end">Изменение</th><th class="text-end">После ДС</th><th class="text-end">Сумма изменения</th><th></th></tr></thead><tbody>
|
||||
{% for row in line_rows %}<tr><td>{% if row.line.change_type == 'new_position' %}<span class="badge text-bg-info">Новая</span>{% elif row.line.change_type == 'decrease' %}<span class="badge text-bg-warning">Уменьшение</span>{% else %}<span class="badge text-bg-primary">Увеличение</span>{% endif %}</td><td class="item-name"><div class="fw-semibold">{{ row.item.source_number or '' }} {{ row.item.name }}</div><small class="text-muted">{{ row.item.model or '' }}{% if row.item.manufacturer %} · {{ row.item.manufacturer }}{% endif %}</small></td><td>{{ row.item.unit or '—' }}</td><td class="text-end numeric">{{ row.before_quantity }}</td><td class="text-end numeric">{{ row.line.quantity_delta }}</td><td class="text-end numeric">{{ row.after_quantity }}</td><td class="text-end numeric">{{ row.amount_delta|money(project.currency) }}</td><td class="text-end">{% if agreement.status == 'draft' %}<button class="btn btn-sm btn-outline-secondary" type="button" data-bs-toggle="collapse" data-bs-target="#edit-line-{{ row.line.id }}">Править</button><form class="d-inline" method="post" action="/projects/{{ project.id }}/agreements/{{ agreement.id }}/items/{{ row.line.id }}/delete" onsubmit="return confirm('Удалить позицию из черновика?')"><button class="btn btn-sm btn-outline-danger">×</button></form>{% endif %}</td></tr>
|
||||
{% if agreement.status == 'draft' %}<tr class="collapse" id="edit-line-{{ row.line.id }}"><td colspan="8"><form class="row g-2" method="post" action="/projects/{{ project.id }}/agreements/{{ agreement.id }}/items/{{ row.line.id }}/edit"><div class="col-md-2"><label class="form-label">Δ кол-во</label><input class="form-control" type="number" step="0.0001" name="quantity_delta" value="{{ row.line.quantity_delta }}" required></div>{% if row.line.change_type == 'new_position' %}<div class="col-md-2"><label class="form-label">Имя</label><input class="form-control" name="name" value="{{ row.item.name }}" required></div><div class="col-md-2"><label class="form-label">Модель</label><input class="form-control" name="model" value="{{ row.item.model or '' }}"></div><div class="col-md-2"><label class="form-label">Произв.</label><input class="form-control" name="manufacturer" value="{{ row.item.manufacturer or '' }}"></div><div class="col-md-2"><label class="form-label">Ед.</label><input class="form-control" name="unit" value="{{ row.item.unit or '' }}"></div><div class="col-md-2"><label class="form-label">Цена</label><input class="form-control" type="number" step="0.000000000001" name="unit_price" value="{{ row.item.unit_price }}" required></div><div class="col-md-3"><label class="form-label">Система</label><select class="form-select system-select" name="system_id" required>{% for system in systems %}<option value="{{ system.id }}" {% if row.item.system_id == system.id %}selected{% endif %}>{{ system.name }}</option>{% endfor %}</select></div><div class="col-md-3"><label class="form-label">Раздел</label><select class="form-select section-select" name="section_id" required>{% for section in sections %}<option value="{{ section.id }}" data-system="{{ section.system_id }}" {% if row.item.section_id == section.id %}selected{% endif %}>{{ section.name }}</option>{% endfor %}</select></div>{% endif %}<div class="col-md-2 align-self-end"><button class="btn btn-primary">Сохранить</button></div></form></td></tr>{% endif %}
|
||||
{% else %}<tr><td colspan="8" class="text-center text-muted py-4">Позиции ещё не добавлены.</td></tr>{% endfor %}</tbody></table></div><div class="card-footer bg-white d-flex justify-content-between"><span class="text-muted">Сумма изменения плана</span><strong>{{ change_amount|money(project.currency) }}</strong></div></section>
|
||||
{% if agreement.status == 'draft' %}<div class="row g-4"><div class="col-xl-6"><section class="card border-0 shadow-sm h-100"><div class="card-header bg-white"><h2 class="h5 mb-0">Добавить существующую позицию</h2></div><form method="post" action="/projects/{{ project.id }}/agreements/{{ agreement.id }}/items/existing"><div class="card-body"><div class="mb-3 position-relative" data-position-picker><label class="form-label" for="existing-position-search">Позиция проекта</label><div class="input-group"><input id="existing-position-search" class="form-control" type="search" autocomplete="off" placeholder="Поиск по номеру, наименованию, модели, системе..." aria-expanded="false" aria-controls="existing-position-results" required><button class="btn btn-outline-secondary" type="button" data-clear-position>Очистить</button></div><input type="hidden" name="work_item_id" data-work-item-id><div class="form-text" data-selected-position aria-live="polite">Позиция не выбрана</div><div id="existing-position-results" class="list-group position-absolute shadow bg-white" role="listbox" style="z-index:1050;max-height:18rem;overflow-y:auto;min-width:min(100%,40rem);display:none">{% for row in selectable_items %}<button type="button" class="list-group-item list-group-item-action autocomplete-position" role="option" data-id="{{ row.item.id }}" data-search="{{ row.item.source_number or '' }} {{ row.item.name }} {{ row.item.model or '' }} {{ row.item.manufacturer or '' }} {{ row.item.system.name if row.item.system else '' }} {{ row.item.section.name if row.item.section else '' }}" data-label="{{ row.item.system.name if row.item.system else '' }} ? {{ row.item.section.name if row.item.section else '' }} ? ?{{ row.item.source_number or '' }} ? {{ row.item.name }}{% if row.item.model %} ? {{ row.item.model }}{% endif %} ? {{ row.quantity }} {{ row.item.unit or '' }}"><span class="fw-semibold">{{ row.item.system.name if row.item.system else '' }} ? {{ row.item.section.name if row.item.section else '' }} ? ?{{ row.item.source_number or '?' }}</span><br>{{ row.item.name }}{% if row.item.model %} ? {{ row.item.model }}{% endif %}<small class="d-block text-muted">{{ row.item.manufacturer or '' }}{% if row.item.manufacturer %} ? {% endif %}{{ row.quantity }} {{ row.item.unit or '' }}</small></button>{% endfor %}<div class="list-group-item text-muted d-none" data-no-results>Ничего не найдено.</div><div class="list-group-item text-muted d-none" data-more-results>Показаны первые 20 результатов. Уточните поиск.</div></div></div><div class="mb-3"><label class="form-label">Δ количество (+ / −)</label><input class="form-control" type="number" step="0.0001" name="quantity_delta" required><div class="form-text">Для уменьшения укажите отрицательное число. Сумма рассчитается по цене позиции.</div></div>{% if not selectable_items %}<div class="text-muted small mb-3">В этой области нет недобавленных позиц.</div>{% endif %}</div><div class="card-footer bg-white"><button class="btn btn-outline-primary" {% if not selectable_items %}disabled{% endif %}>Добавить позицию</button></div></form></section></div>
|
||||
<div class="col-xl-6"><section class="card border-0 shadow-sm h-100"><div class="card-header bg-white"><h2 class="h5 mb-0">Добавить новую позицию</h2></div><form method="post" action="/projects/{{ project.id }}/agreements/{{ agreement.id }}/items/new" data-new-item-form data-system-url="/projects/{{ project.id }}/agreements/{{ agreement.id }}/systems" data-section-url="/projects/{{ project.id }}/agreements/{{ agreement.id }}/sections"><div class="card-body row g-3"><div class="col-12"><label class="form-label">Ведомость (необязательно)</label><select class="form-select" name="source_boq_document_id"><option value="">Без ведомости</option>{% for doc in boq_documents %}<option value="{{ doc.id }}" {% if agreement.boq_document_id == doc.id %}selected{% endif %}>{{ doc.name }}</option>{% endfor %}</select></div><div class="col-md-6"><label class="form-label">Наименование</label><input class="form-control" name="name" required></div><div class="col-md-6"><label class="form-label">Модель / артикул</label><input class="form-control" name="model"></div><div class="col-md-6"><label class="form-label">Производитель</label><input class="form-control" name="manufacturer"></div><div class="col-md-3"><label class="form-label">Единица</label><input class="form-control" name="unit"></div><div class="col-md-3"><label class="form-label">Δ кол-во</label><input class="form-control" type="number" min="0.0001" step="0.0001" name="quantity_delta" required></div><div class="col-md-6"><label class="form-label">Цена за единицу</label><input class="form-control" type="number" min="0" step="0.000000000001" name="unit_price" required></div><div class="col-md-6"><label class="form-label">Система</label><select class="form-select system-select" name="system_id" data-system-select><option value="">Без системы</option>{% for system in systems %}<option value="{{ system.id }}">{{ system.name }}</option>{% endfor %}<option value="__new__">+ Новая система...</option></select><div class="input-group mt-2 d-none" data-new-system-panel><input class="form-control" maxlength="255" placeholder="Название системы"><button type="button" class="btn btn-outline-primary" data-create-system>Создать</button></div></div><div class="col-md-6"><label class="form-label">Раздел</label><select class="form-select section-select" name="section_id" data-section-select><option value="">Без раздела</option>{% for section in sections %}<option value="{{ section.id }}" data-system="{{ section.system_id }}">{{ section.name }}</option>{% endfor %}<option value="__new__">+ Новый раздел...</option></select><div class="input-group mt-2 d-none" data-new-section-panel><input class="form-control" maxlength="255" placeholder="Название раздела"><button type="button" class="btn btn-outline-primary" data-create-section>Создать</button></div></div><div class="col-12 text-danger small" data-association-error role="alert"></div></div><div class="card-footer bg-white"><button class="btn btn-outline-primary">Добавить новую позицию</button></div></form></section></div></div>
|
||||
<div class="col-xl-6"><section class="card border-0 shadow-sm h-100"><div class="card-header bg-white"><h2 class="h5 mb-0">Добавить новую позицию</h2></div><form method="post" action="/projects/{{ project.id }}/agreements/{{ agreement.id }}/items/new" data-new-item-form data-system-url="/projects/{{ project.id }}/agreements/{{ agreement.id }}/systems" data-section-url="/projects/{{ project.id }}/agreements/{{ agreement.id }}/sections"><div class="card-body row g-3"><div class="col-12"><label class="form-label">Ведомость (необязательно)</label><select class="form-select" name="source_boq_document_id"><option value="">Без ведомости</option>{% for doc in boq_documents %}<option value="{{ doc.id }}" {% if agreement.boq_document_id == doc.id %}selected{% endif %}>{{ doc.display_name }}</option>{% endfor %}</select></div><div class="col-md-6"><label class="form-label">Наименование</label><input class="form-control" name="name" required></div><div class="col-md-6"><label class="form-label">Модель / артикул</label><input class="form-control" name="model"></div><div class="col-md-6"><label class="form-label">Производитель</label><input class="form-control" name="manufacturer"></div><div class="col-md-3"><label class="form-label">Единица</label><input class="form-control" name="unit"></div><div class="col-md-3"><label class="form-label">Δ кол-во</label><input class="form-control" type="number" min="0.0001" step="0.0001" name="quantity_delta" required></div><div class="col-md-6"><label class="form-label">Цена за единицу</label><input class="form-control" type="number" min="0" step="0.000000000001" name="unit_price" required></div><div class="col-md-6"><label class="form-label">Система</label><select class="form-select system-select" name="system_id" data-system-select><option value="">Без системы</option>{% for system in systems %}<option value="{{ system.id }}">{{ system.name }}</option>{% endfor %}<option value="__new__">+ Новая система...</option></select><div class="input-group mt-2 d-none" data-new-system-panel><input class="form-control" maxlength="255" placeholder="Название системы"><button type="button" class="btn btn-outline-primary" data-create-system>Создать</button></div></div><div class="col-md-6"><label class="form-label">Раздел</label><select class="form-select section-select" name="section_id" data-section-select><option value="">Без раздела</option>{% for section in sections %}<option value="{{ section.id }}" data-system="{{ section.system_id }}">{{ section.name }}</option>{% endfor %}<option value="__new__">+ Новый раздел...</option></select><div class="input-group mt-2 d-none" data-new-section-panel><input class="form-control" maxlength="255" placeholder="Название раздела"><button type="button" class="btn btn-outline-primary" data-create-section>Создать</button></div></div><div class="col-12 text-danger small" data-association-error role="alert"></div></div><div class="card-footer bg-white"><button class="btn btn-outline-primary">Добавить новую позицию</button></div></form></section></div></div>
|
||||
<section class="d-flex justify-content-end mt-4"><button class="btn btn-success" data-bs-toggle="modal" data-bs-target="#approveModal" {% if not line_rows %}disabled{% endif %}>Утвердить</button></section>
|
||||
<div class="modal fade" id="approveModal" tabindex="-1"><div class="modal-dialog"><div class="modal-content"><div class="modal-header"><h2 class="modal-title fs-5">Подтвердите утверждение</h2><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div><div class="modal-body"><div><strong>ДС №{{ agreement.number }}</strong></div><div>Область: {{ scope_label }}</div><div>Количество позиций: {{ line_rows|length }}</div><p class="text-warning mt-3 mb-0">После утверждения изменения нельзя редактировать.</p></div><div class="modal-footer"><button class="btn btn-outline-secondary" data-bs-dismiss="modal">Отмена</button><form method="post" action="/projects/{{ project.id }}/agreements/{{ agreement.id }}/approve"><button class="btn btn-success">Утвердить ДС</button></form></div></div></div></div>
|
||||
{% else %}<div class="alert alert-info">ДС утверждено. Изменения недоступны.</div>{% endif %}
|
||||
|
||||
@@ -1,5 +1,53 @@
|
||||
<!doctype html><html lang="ru"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>Дополнительные соглашения — {{ project.name }}</title><link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet"></head><body class="bg-light"><main class="container py-4">
|
||||
<nav><ol class="breadcrumb"><li class="breadcrumb-item"><a href="/projects/">Проекты</a></li><li class="breadcrumb-item"><a href="/projects/{{ project.id }}">{{ project.name }}</a></li><li class="breadcrumb-item active">Дополнительные соглашения</li></ol></nav>
|
||||
<header class="d-flex flex-wrap justify-content-between align-items-center gap-2 mb-4"><div><h1 class="h2 mb-1">Дополнительные соглашения</h1><div class="text-muted">{{ project.name }}</div></div><a class="btn btn-primary" href="/projects/{{ project.id }}/agreements/new">+ Создать ДС</a></header>
|
||||
<section class="card border-0 shadow-sm"><div class="table-responsive"><table class="table align-middle mb-0"><thead><tr><th>Номер</th><th>Дата</th><th>Наименование</th><th>Область</th><th>Статус</th><th class="text-end">Позиций</th><th></th></tr></thead><tbody>
|
||||
{% for row in rows %}<tr><td class="fw-semibold">{{ row.agreement.number }}</td><td>{{ row.agreement.date.strftime('%d.%m.%Y') }}</td><td>{{ row.agreement.title }}</td><td>{{ row.scope_label }}</td><td>{% if row.agreement.status == 'approved' %}<span class="badge text-bg-success">Утверждено</span>{% else %}<span class="badge text-bg-secondary">Черновик</span>{% endif %}</td><td class="text-end">{{ row.item_count }}</td><td class="text-end"><a class="btn btn-sm btn-outline-primary" href="/projects/{{ project.id }}/agreements/{{ row.agreement.id }}">Открыть</a></td></tr>{% else %}<tr><td colspan="7" class="text-center text-muted py-5">ДС пока нет.</td></tr>{% endfor %}</tbody></table></div></section></main></body></html>
|
||||
<!doctype html>
|
||||
<html lang="ru">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>Дополнительные соглашения — {{ project.name }}</title>
|
||||
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
|
||||
<style>
|
||||
.clickable-row { cursor: pointer; }
|
||||
.clickable-row:hover { background-color: rgba(0,0,0,0.04); }
|
||||
</style>
|
||||
</head>
|
||||
<body class="bg-light">
|
||||
<main class="container py-4">
|
||||
<nav><ol class="breadcrumb"><li class="breadcrumb-item"><a href="/projects/">Проекты</a></li><li class="breadcrumb-item"><a href="/projects/{{ project.id }}">{{ project.name }}</a></li><li class="breadcrumb-item active">Дополнительные соглашения</li></ol></nav>
|
||||
<header class="d-flex flex-wrap justify-content-between align-items-center gap-2 mb-4">
|
||||
<div><h1 class="h2 mb-1">Дополнительные соглашения</h1><div class="text-muted">{{ project.name }}</div></div>
|
||||
<a class="btn btn-primary" href="/projects/{{ project.id }}/agreements/new">+ Создать ДС</a>
|
||||
</header>
|
||||
<section class="card border-0 shadow-sm">
|
||||
<div class="table-responsive">
|
||||
<table class="table align-middle mb-0">
|
||||
<thead><tr><th>Номер</th><th>Дата</th><th>Наименование</th><th>Область</th><th>Статус</th><th class="text-end">Позиций</th><th></th></tr></thead>
|
||||
<tbody>
|
||||
{% for row in rows %}
|
||||
<tr class="clickable-row" data-url="/projects/{{ project.id }}/agreements/{{ row.agreement.id }}">
|
||||
<td class="fw-semibold">{{ row.agreement.number }}</td>
|
||||
<td>{{ row.agreement.date.strftime('%d.%m.%Y') }}</td>
|
||||
<td>{{ row.agreement.title }}</td>
|
||||
<td>{{ row.scope_label }}</td>
|
||||
<td>{% if row.agreement.status == 'approved' %}<span class="badge text-bg-success">Утверждено</span>{% else %}<span class="badge text-bg-secondary">Черновик</span>{% endif %}</td>
|
||||
<td class="text-end">{{ row.item_count }}</td>
|
||||
<td class="text-end"><a class="btn btn-sm btn-outline-primary" href="/projects/{{ project.id }}/agreements/{{ row.agreement.id }}">Открыть</a></td>
|
||||
</tr>
|
||||
{% else %}
|
||||
<tr><td colspan="7" class="text-center text-muted py-5">ДС пока нет.</td></tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</section>
|
||||
</main>
|
||||
<script>
|
||||
document.querySelectorAll('.clickable-row').forEach(function(row) {
|
||||
row.addEventListener('click', function(e) {
|
||||
if (e.target.closest('a, button, form, input, select, textarea')) return;
|
||||
var url = row.dataset.url;
|
||||
if (url) window.location.href = url;
|
||||
});
|
||||
});
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
<!doctype html><html lang="ru"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>Новое ДС — {{ project.name }}</title><link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet"></head><body class="bg-light"><main class="container py-4">
|
||||
<!doctype html><html lang="ru"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>Новое ДС — {{ project.name }}</title><link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet"></head><body class="bg-light"><main class="container py-4">
|
||||
<nav><ol class="breadcrumb"><li class="breadcrumb-item"><a href="/projects/">Проекты</a></li><li class="breadcrumb-item"><a href="/projects/{{ project.id }}">{{ project.name }}</a></li><li class="breadcrumb-item"><a href="/projects/{{ project.id }}/agreements">ДС</a></li><li class="breadcrumb-item active">Создать</li></ol></nav><h1 class="h2 mb-4">Создать ДС</h1>
|
||||
{% if error %}<div class="alert alert-danger">{{ error }}</div>{% endif %}<form class="card border-0 shadow-sm" method="post" action="/projects/{{ project.id }}/agreements"><div class="card-body row g-3">
|
||||
<div class="col-md-4"><label class="form-label" for="number">Номер</label><input class="form-control" id="number" name="number" required maxlength="100"></div><div class="col-md-4"><label class="form-label" for="agreement_date">Дата</label><input class="form-control" type="date" id="agreement_date" name="agreement_date" value="{{ today }}" required></div><div class="col-md-4"><label class="form-label" for="title">Наименование</label><input class="form-control" id="title" name="title" required maxlength="255"></div>
|
||||
<div class="col-12"><label class="form-label" for="description">Описание</label><textarea class="form-control" id="description" name="description" rows="3"></textarea></div><div class="col-md-7"><label class="form-label" for="scope">Область применения</label><select class="form-select" id="scope" name="scope" required><option value="project">Весь проект</option>{% for doc in boq_documents %}<option value="boq:{{ doc.id }}">{{ doc.name }}</option>{% endfor %}</select></div>
|
||||
<div class="col-12"><label class="form-label" for="description">Описание</label><textarea class="form-control" id="description" name="description" rows="3"></textarea></div><div class="col-md-7"><label class="form-label" for="scope">Область применения</label><select class="form-select" id="scope" name="scope" required><option value="project">Весь проект</option>{% for doc in boq_documents %}<option value="boq:{{ doc.id }}">{{ doc.display_name }}</option>{% endfor %}</select></div>
|
||||
{% if not boq_documents %}<div class="col-12"><div class="alert alert-warning mb-0">В проекте нет Ведомостей. Можно выбрать область «Весь проект».</div></div>{% endif %}</div><div class="card-footer bg-white d-flex gap-2"><button class="btn btn-primary" type="submit">Создать черновик</button><a class="btn btn-outline-secondary" href="/projects/{{ project.id }}/agreements">Отмена</a></div></form></main></body></html>
|
||||
|
||||
@@ -13,7 +13,8 @@
|
||||
</head>
|
||||
<body class="bg-light money-hidden">
|
||||
<main class="container py-4">
|
||||
<div class="d-flex justify-content-end mb-2">
|
||||
<div class="d-flex justify-content-end align-items-center gap-2 mb-2">
|
||||
<span class="text-muted small">Финансовые суммы</span>
|
||||
<button type="button" class="btn btn-outline-secondary btn-sm" id="toggleMoney" title="Показать/скрыть финансовые суммы" aria-label="Показать или скрыть финансовые суммы">👁</button>
|
||||
</div>
|
||||
{% block content %}{% endblock %}
|
||||
|
||||
@@ -31,9 +31,13 @@
|
||||
<td>{{ row.document.number }}</td>
|
||||
<td>{{ row.document.date.strftime('%d.%m.%Y') }}{% if row.document.reporting_period_from and row.document.reporting_period_to %}<br><small class="text-muted">{{ row.document.reporting_period_from.strftime('%d.%m.%Y') }} — {{ row.document.reporting_period_to.strftime('%d.%m.%Y') }}</small>{% endif %}</td>
|
||||
<td>
|
||||
<span class="badge bg-{{ 'success' if row.document.status == 'issued' else 'secondary' }}">
|
||||
{{ 'Проведён' if row.document.status == 'issued' else 'Черновик' }}
|
||||
</span>
|
||||
{% if row.document.status == 'cancelled' %}
|
||||
<span class="badge bg-danger">Сторнирован</span>
|
||||
{% elif row.document.status == 'issued' %}
|
||||
<span class="badge bg-success">Проведён</span>
|
||||
{% else %}
|
||||
<span class="badge bg-secondary">Черновик</span>
|
||||
{% endif %}
|
||||
</td>
|
||||
<td>{{ row.item_count }}</td>
|
||||
<td class="text-end text-nowrap money-value">{{ row.amount | money }}</td>
|
||||
|
||||
@@ -33,9 +33,13 @@
|
||||
<td>{{ row.document.date.strftime('%d.%m.%Y') }}</td>
|
||||
<td>{% if row.document.reporting_period_from and row.document.reporting_period_to %}{{ row.document.reporting_period_from.strftime('%d.%m.%Y') }} — {{ row.document.reporting_period_to.strftime('%d.%m.%Y') }}{% endif %}</td>
|
||||
<td>
|
||||
<span class="badge bg-{{ 'success' if row.document.status == 'issued' else 'secondary' }}">
|
||||
{{ 'Проведён' if row.document.status == 'issued' else 'Черновик' }}
|
||||
</span>
|
||||
{% if row.document.status == 'cancelled' %}
|
||||
<span class="badge bg-danger">Сторнирован</span>
|
||||
{% elif row.document.status == 'issued' %}
|
||||
<span class="badge bg-success">Проведён</span>
|
||||
{% else %}
|
||||
<span class="badge bg-secondary">Черновик</span>
|
||||
{% endif %}
|
||||
</td>
|
||||
<td>{{ row.ks2_count }}</td>
|
||||
<td class="text-end text-nowrap money-value">{{ row.amount | money }}</td>
|
||||
|
||||
@@ -14,41 +14,63 @@
|
||||
<a href="/projects/{{ project.id }}/payments/new" class="btn btn-primary mb-3">Новый платёж</a>
|
||||
|
||||
<div class="table-responsive">
|
||||
<table class="table table-striped">
|
||||
<table class="table table-striped align-middle">
|
||||
<colgroup>
|
||||
<col style="width: 6.5rem">
|
||||
<col style="width: 8rem">
|
||||
<col style="width: 7.5rem">
|
||||
<col style="width: 8rem">
|
||||
<col style="width: 4.5rem">
|
||||
<col style="width: 8rem">
|
||||
<col style="width: 8.5rem">
|
||||
<col style="width: 4.5rem">
|
||||
<col>
|
||||
<col style="width: 17rem">
|
||||
</colgroup>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Дата</th>
|
||||
<th>Номер документа</th>
|
||||
<th>Статус</th>
|
||||
<th class="text-end text-nowrap">Сумма</th>
|
||||
<th>Валюта</th>
|
||||
<th class="text-end text-nowrap">Распределено</th>
|
||||
<th class="text-end text-nowrap">Не распределено</th>
|
||||
<th>КС-3</th>
|
||||
<th>Комментарий</th>
|
||||
<th>Действия</th>
|
||||
<th class="text-nowrap">Действия</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{% for row in rows %}
|
||||
<tr class="clickable-row" data-url="/projects/{{ project.id }}/payments/{{ row.payment.id }}">
|
||||
<td>{{ row.payment.date.strftime('%d.%m.%Y') }}</td>
|
||||
<td class="text-nowrap">{{ row.payment.date.strftime('%d.%m.%Y') }}</td>
|
||||
<td>{{ row.payment.document_number or '—' }}</td>
|
||||
<td>
|
||||
{% if row.payment.status == 'cancelled' %}
|
||||
<span class="badge bg-danger">Сторнирован</span>
|
||||
{% else %}
|
||||
<span class="badge bg-success">Активный</span>
|
||||
{% endif %}
|
||||
</td>
|
||||
<td class="text-end text-nowrap money-value">{{ row.payment.amount | money(row.payment.currency) }}</td>
|
||||
<td>{{ row.payment.currency }}</td>
|
||||
<td class="text-end text-nowrap money-value">{{ row.allocated | money(row.payment.currency) }}</td>
|
||||
<td class="text-end text-nowrap money-value">{{ row.unallocated | money(row.payment.currency) }}</td>
|
||||
<td>{{ row.ks3_count }}</td>
|
||||
<td>{{ row.payment.comment or '' }}</td>
|
||||
<td>
|
||||
<td class="text-nowrap payments-actions">
|
||||
<span class="d-inline-flex gap-1 align-items-center">
|
||||
<a href="/projects/{{ project.id }}/payments/{{ row.payment.id }}" class="btn btn-sm btn-outline-primary">Просмотр</a>
|
||||
<a href="/projects/{{ project.id }}/payments/{{ row.payment.id }}/edit" class="btn btn-sm btn-outline-secondary">Редактировать</a>
|
||||
<form method="post" action="/projects/{{ project.id }}/payments/{{ row.payment.id }}/delete" class="d-inline">
|
||||
<form method="post" action="/projects/{{ project.id }}/payments/{{ row.payment.id }}/delete" class="d-inline m-0">
|
||||
<button type="submit" class="btn btn-sm btn-outline-danger" onclick="return confirm('Удалить платёж?')">Удалить</button>
|
||||
</form>
|
||||
</span>
|
||||
</td>
|
||||
</tr>
|
||||
{% else %}
|
||||
<tr><td colspan="9" class="text-center text-muted py-4">Платежей пока нет.</td></tr>
|
||||
<tr><td colspan="10" class="text-center text-muted py-4">Платежей пока нет.</td></tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
</table>
|
||||
|
||||
@@ -47,15 +47,23 @@
|
||||
<li class="breadcrumb-item active" aria-current="page">Ведомость</li>
|
||||
</ol>
|
||||
</nav>
|
||||
<div class="d-flex justify-content-between align-items-start mb-4">
|
||||
<div class="d-flex justify-content-between align-items-start mb-2">
|
||||
<div>
|
||||
<h1>{{ document_title }}</h1>
|
||||
<p class="text-muted mb-0">{{ project.name }}{% if document.source_file %} · {{ document.source_file }}{% endif %}</p>
|
||||
<p class="text-muted mb-0">
|
||||
{{ project.name }}{% if document.source_file %} · {{ document.source_file }}{% endif %}
|
||||
</p>
|
||||
{% if document.document_number or document.document_date or document.contract %}
|
||||
<p class="text-muted small mb-0">
|
||||
{% if document.document_number %}<span>№ {{ document.document_number }}</span>{% endif %}
|
||||
{% if document.document_date %}<span class="ms-2">от {{ document.document_date.strftime('%d.%m.%Y') }}</span>{% endif %}
|
||||
{% if document.contract %}<span class="ms-2">Договор: {{ document.contract }}</span>{% endif %}
|
||||
</p>
|
||||
{% endif %}
|
||||
</div>
|
||||
<div class="d-flex gap-2">
|
||||
<button type="button" class="btn btn-outline-secondary btn-sm" id="expandAll">Развернуть всё</button>
|
||||
<button type="button" class="btn btn-outline-secondary btn-sm" id="collapseAll">Свернуть всё</button>
|
||||
<button type="button" class="btn btn-outline-secondary" id="toggleMoney" title="Показать/скрыть финансовые суммы" aria-label="Показать или скрыть финансовые суммы">👁</button>
|
||||
{% if not has_history %}
|
||||
<form method="post" action="/boq/{{ project.id }}/documents/{{ document.id }}/delete" class="d-inline">
|
||||
<button type="submit" class="btn btn-outline-danger" onclick="return confirm('Удалить ведомость и все её позиции? Это действие необратимо.')">Удалить ведомость</button>
|
||||
@@ -68,6 +76,10 @@
|
||||
<a class="btn btn-outline-secondary" href="/projects/{{ project.id }}">К проекту</a>
|
||||
</div>
|
||||
</div>
|
||||
<div class="d-flex justify-content-end align-items-center gap-2 mb-3">
|
||||
<span class="text-muted small">Финансовые суммы</span>
|
||||
<button type="button" class="btn btn-outline-secondary btn-sm" id="toggleMoney" title="Показать/скрыть финансовые суммы" aria-label="Показать или скрыть финансовые суммы">👁</button>
|
||||
</div>
|
||||
|
||||
<div class="boq-table-wrap">
|
||||
<table class="table table-bordered table-sm align-middle boq-table">
|
||||
|
||||
@@ -23,7 +23,7 @@
|
||||
<div class="list-group shadow-sm">
|
||||
{% for document in documents %}
|
||||
<a class="list-group-item list-group-item-action d-flex justify-content-between align-items-center gap-3" href="/boq/{{ project.id }}/documents/{{ document.id }}">
|
||||
<span><strong>{{ document.name.replace('BOQ Import - ', 'Импорт ведомости — ').replace('BOQ Import — ', 'Импорт ведомости — ') }}</strong><br><small class="text-muted">{{ document.source_file or 'Источник не указан' }} · {{ document.created_at.strftime('%d.%m.%Y %H:%M') if document.created_at else 'Дата не указана' }}</small></span>
|
||||
<span><strong>{{ document.display_name }}</strong><br><small class="text-muted">{{ document.source_file or 'Источник не указан' }} · {{ document.created_at.strftime('%d.%m.%Y %H:%M') if document.created_at else 'Дата не указана' }}</small></span>
|
||||
<span class="btn btn-sm btn-outline-primary">Открыть</span>
|
||||
</a>
|
||||
{% endfor %}
|
||||
|
||||
@@ -13,28 +13,78 @@
|
||||
.system-progress-table .progress-summary > * { white-space: nowrap; }
|
||||
.money-value { transition: filter 0.15s; }
|
||||
.money-hidden .money-value { filter: blur(6px); user-select: none; pointer-events: none; }
|
||||
/*
|
||||
* Document navigation: one horizontal row, no horizontal scroll.
|
||||
* Buttons never wrap to a second row; long labels wrap inside the button.
|
||||
* Equal height via stretch + flex centering of button content.
|
||||
*/
|
||||
.doc-nav {
|
||||
display: flex;
|
||||
flex-wrap: nowrap;
|
||||
align-items: stretch;
|
||||
gap: .5rem;
|
||||
}
|
||||
.doc-nav .btn {
|
||||
flex: 1 1 0;
|
||||
min-width: 0;
|
||||
white-space: normal;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
text-align: center;
|
||||
line-height: 1.25;
|
||||
padding-left: .5rem;
|
||||
padding-right: .5rem;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body class="bg-light money-hidden">
|
||||
<main class="container-fluid container-xxl py-4">
|
||||
<nav class="mb-3"><ol class="breadcrumb"><li class="breadcrumb-item"><a href="/projects/">Проекты</a></li><li class="breadcrumb-item active">{{ project.name }}</li></ol></nav>
|
||||
|
||||
<header class="d-flex flex-wrap justify-content-between align-items-start gap-3 mb-4">
|
||||
<div>
|
||||
<header class="mb-4">
|
||||
<!-- Block 1: project title -->
|
||||
<h1 class="h2 mb-2">{{ project.name }}</h1>
|
||||
<div class="d-flex flex-wrap gap-3 text-secondary">
|
||||
<span>Договор: <strong class="text-dark">{{ project.contract_number or 'не указан' }}</strong></span>
|
||||
<span>Заказчик: <strong class="text-dark">{{ project.customer or 'не указан' }}</strong></span>
|
||||
<span>Валюта: <strong class="text-dark">{{ project.currency or 'RUB' }}</strong></span>
|
||||
<span>Период: <strong class="text-dark">{{ project.start_date.strftime('%d.%m.%Y') if project.start_date else '—' }} — {{ project.end_date.strftime('%d.%m.%Y') if project.end_date else '—' }}</strong></span>
|
||||
<span>Статус: <span class="badge text-bg-secondary">{{ project.status or 'не указан' }}</span></span>
|
||||
</div>
|
||||
{% if base_boq_documents|length == 1 %}<div class="small text-muted mt-2">Ведомость проекта: {{ base_boq_documents[0].name.replace('BOQ Import - ', 'Импорт ведомости — ').replace('BOQ Import — ', 'Импорт ведомости — ') }}</div>{% elif base_boq_documents|length > 1 %}<div class="small text-muted mt-2">Ведомостей проекта: {{ base_boq_documents|length }}</div>{% endif %}
|
||||
</div>
|
||||
<div class="d-flex flex-wrap gap-2">
|
||||
<a class="btn btn-primary" href="/projects/{{ project.id }}/daily-reports/new">Создать Daily Report</a>
|
||||
<button type="button" class="btn btn-outline-secondary" id="toggleMoney" title="Показать/скрыть финансовые суммы" aria-label="Показать или скрыть финансовые суммы">👁</button>
|
||||
<!-- Block 2: project actions (under title) -->
|
||||
<div class="d-flex flex-wrap gap-2 mb-3">
|
||||
<a class="btn btn-primary" href="/projects/{{ project.id }}/daily-reports/new">Дневной отчёт</a>
|
||||
<a class="btn btn-outline-secondary" href="/projects/{{ project.id }}/edit">Редактировать</a>
|
||||
</div>
|
||||
<!-- Requisites -->
|
||||
<div class="row g-3 g-md-4 align-items-start mb-2">
|
||||
<div class="col-6 col-sm-4 col-md-auto">
|
||||
<div class="text-muted small mb-1">Договор</div>
|
||||
<div class="fw-semibold text-dark">{{ project.contract_number or 'не указан' }}</div>
|
||||
</div>
|
||||
<div class="col-6 col-sm-4 col-md-auto">
|
||||
<div class="text-muted small mb-1">Заказчик</div>
|
||||
<div class="fw-semibold text-dark">{{ project.customer or 'не указан' }}</div>
|
||||
</div>
|
||||
<div class="col-6 col-sm-4 col-md-auto">
|
||||
<div class="text-muted small mb-1">Валюта</div>
|
||||
<div class="fw-semibold text-dark">{{ project.currency or 'RUB' }}</div>
|
||||
</div>
|
||||
<div class="col-6 col-sm-4 col-md-auto">
|
||||
<div class="text-muted small mb-1">Период</div>
|
||||
<div class="fw-semibold text-dark">{{ project.start_date.strftime('%d.%m.%Y') if project.start_date else '—' }} — {{ project.end_date.strftime('%d.%m.%Y') if project.end_date else '—' }}</div>
|
||||
</div>
|
||||
<div class="col-6 col-sm-4 col-md-auto">
|
||||
<div class="text-muted small mb-1">Статус</div>
|
||||
{% set status = project.status or 'active' %}
|
||||
{% set status_map = {
|
||||
'active': ('Активный', 'success'),
|
||||
'completed': ('Завершён', 'primary'),
|
||||
'on_hold': ('Приостановлен', 'warning'),
|
||||
'archived': ('Архивирован', 'secondary')
|
||||
} %}
|
||||
{% set status_pair = status_map.get(status, (status, 'secondary')) %}
|
||||
<div><span class="badge text-bg-{{ status_pair[1] }}">{{ status_pair[0] }}</span></div>
|
||||
</div>
|
||||
</div>
|
||||
<!-- BOQ document -->
|
||||
{% if base_boq_documents|length == 1 %}<div class="small text-muted mb-3">Ведомость проекта: {{ base_boq_documents[0].display_name }}</div>{% elif base_boq_documents|length > 1 %}<div class="small text-muted mb-3">Ведомостей проекта: {{ base_boq_documents|length }}</div>{% endif %}
|
||||
<!-- Document navigation: single left-aligned row, no h-scroll -->
|
||||
<nav class="doc-nav mb-3" aria-label="Документы проекта">
|
||||
<a class="btn btn-outline-primary" href="/boq/{{ project.id }}">Ведомости{% if base_boq_documents %} ({{ base_boq_documents|length }}){% endif %}</a>
|
||||
<a class="btn btn-outline-primary" href="/projects/{{ project.id }}/agreements">Дополнительные соглашения{% if agreements_count %} ({{ agreements_count }}){% endif %}</a>
|
||||
<a class="btn btn-outline-primary" href="/projects/{{ project.id }}/daily-reports">Daily Reports{% if daily_reports_count %} ({{ daily_reports_count }}){% endif %}</a>
|
||||
@@ -42,7 +92,7 @@
|
||||
<a class="btn btn-outline-primary" href="/projects/{{ project.id }}/ks3">КС-3{% if ks3_count %} ({{ ks3_count }}){% endif %}</a>
|
||||
<a class="btn btn-outline-primary" href="/projects/{{ project.id }}/ks6a">КС-6а</a>
|
||||
<a class="btn btn-outline-primary" href="/projects/{{ project.id }}/payments">Платежи{% if payments_count %} ({{ payments_count }}){% endif %}</a>
|
||||
</div>
|
||||
</nav>
|
||||
</header>
|
||||
|
||||
{% if project.status != 'archived' %}
|
||||
@@ -50,8 +100,8 @@
|
||||
<form method="post" action="/projects/{{ project.id }}/archive" class="d-inline">
|
||||
<button type="submit" class="btn btn-outline-warning btn-sm" onclick="return confirm('Архивировать проект? Данные будут сохранены.')">Архивировать</button>
|
||||
</form>
|
||||
<form method="post" action="/projects/{{ project.id }}/delete" class="d-inline">
|
||||
<button type="submit" class="btn btn-outline-danger btn-sm" onclick="return confirm('ВНИМАНИЕ: Проект будет физически удалён вместе со связанными данными. Это действие необратимо. Продолжить?')">Удалить проект</button>
|
||||
<form method="post" action="/projects/{{ project.id }}/delete" class="d-inline" id="delete-project-form">
|
||||
<button type="submit" class="btn btn-outline-danger btn-sm">Удалить проект</button>
|
||||
</form>
|
||||
</div>
|
||||
{% else %}
|
||||
@@ -64,6 +114,11 @@
|
||||
{% else %}<div class="text-success small py-2">✓ Проверка плана: превышений нет</div>{% endif %}
|
||||
</section>
|
||||
|
||||
<div class="d-flex justify-content-end align-items-center gap-2 mb-3">
|
||||
<span class="text-muted small">Финансовые суммы</span>
|
||||
<button type="button" class="btn btn-outline-secondary btn-sm" id="toggleMoney" title="Показать/скрыть финансовые суммы" aria-label="Показать или скрыть финансовые суммы">👁</button>
|
||||
</div>
|
||||
|
||||
<section class="mb-4" aria-labelledby="kpi-heading">
|
||||
<h2 id="kpi-heading" class="h5 mb-3">План и выполнение</h2>
|
||||
<div class="row g-3">
|
||||
@@ -184,8 +239,8 @@
|
||||
<option value="word">Word</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="col-md-2">
|
||||
<button type="submit" class="btn btn-primary w-100">Сформировать комплект</button>
|
||||
<div class="col-md-2 d-flex align-items-end">
|
||||
<button type="submit" class="btn btn-primary text-nowrap w-auto">Сформировать комплект</button>
|
||||
</div>
|
||||
</form>
|
||||
<div id="package-error" class="alert alert-danger mt-3 mb-0" role="alert" hidden></div>
|
||||
@@ -202,13 +257,19 @@
|
||||
</section>
|
||||
|
||||
<section class="card border-0 shadow-sm mt-4">
|
||||
<div class="card-header bg-white d-flex justify-content-between align-items-center"><h2 class="h5 mb-0">Дерево документов</h2><a href="/boq/{{ project.id }}" class="btn btn-sm btn-outline-primary">Ведомости</a></div>
|
||||
<div class="card-header bg-white d-flex justify-content-between align-items-center">
|
||||
<h2 class="h5 mb-0">Дерево документов</h2>
|
||||
<div class="d-flex gap-2">
|
||||
<a href="/boq/{{ project.id }}" class="btn btn-sm btn-outline-primary">Ведомости</a>
|
||||
<a href="/projects/{{ project.id }}/agreements" class="btn btn-sm btn-outline-primary">Дополнительные соглашения</a>
|
||||
</div>
|
||||
</div>
|
||||
<div class="card-body">
|
||||
<div class="mb-2 fw-semibold">План и ведомости</div>
|
||||
{% for node in doc_tree %}
|
||||
<div class="ms-3 mb-2">
|
||||
<a href="/boq/{{ project.id }}/documents/{{ node.doc.id }}" class="text-decoration-none">
|
||||
📄 {{ node.doc.name.replace('BOQ Import - ', 'Импорт ведомости — ').replace('BOQ Import — ', 'Импорт ведомости — ') }}
|
||||
📄 {{ node.doc.display_name }}
|
||||
</a>
|
||||
{% if node.agreements %}
|
||||
<div class="ms-4 mt-1">
|
||||
@@ -263,6 +324,26 @@
|
||||
</table></div></div>
|
||||
</div></div>
|
||||
</div>
|
||||
<div class="modal fade" id="deleteBlockedModal" tabindex="-1" aria-labelledby="deleteBlockedTitle" aria-hidden="true">
|
||||
<div class="modal-dialog">
|
||||
<div class="modal-content">
|
||||
<div class="modal-header">
|
||||
<h2 class="modal-title fs-5" id="deleteBlockedTitle">Проект нельзя удалить</h2>
|
||||
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Закрыть"></button>
|
||||
</div>
|
||||
<div class="modal-body">
|
||||
<p>В проекте есть связанные данные: ведомости, отчёты или документы. Удаление невозможно, чтобы не нарушить историю проекта.</p>
|
||||
<p class="mb-0"><strong>Рекомендуется архивировать проект.</strong></p>
|
||||
</div>
|
||||
<div class="modal-footer">
|
||||
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Отмена</button>
|
||||
<form method="post" action="/projects/{{ project.id }}/archive" class="d-inline">
|
||||
<button type="submit" class="btn btn-warning">Архивировать проект</button>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</main>
|
||||
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
|
||||
<script>
|
||||
@@ -346,6 +427,25 @@
|
||||
document.getElementById('toggleMoney').addEventListener('click', () => {
|
||||
document.body.classList.toggle('money-hidden');
|
||||
});
|
||||
const deleteForm = document.getElementById('delete-project-form');
|
||||
if (deleteForm) {
|
||||
deleteForm.addEventListener('submit', async event => {
|
||||
event.preventDefault();
|
||||
if (!window.confirm('ВНИМАНИЕ: Проект будет физически удалён вместе со связанными данными. Это действие необратимо. Продолжить?')) return;
|
||||
try {
|
||||
const response = await fetch(deleteForm.getAttribute('action'), {method: 'POST'});
|
||||
if (response.ok) {
|
||||
window.location.href = '/projects/';
|
||||
return;
|
||||
}
|
||||
const modal = new bootstrap.Modal(document.getElementById('deleteBlockedModal'));
|
||||
modal.show();
|
||||
} catch {
|
||||
const modal = new bootstrap.Modal(document.getElementById('deleteBlockedModal'));
|
||||
modal.show();
|
||||
}
|
||||
});
|
||||
}
|
||||
const packageForm = document.querySelector('form[action*="/export/package"]');
|
||||
const packageError = document.getElementById('package-error');
|
||||
if (packageForm) {
|
||||
|
||||
@@ -19,6 +19,25 @@
|
||||
<label for="file" class="form-label">Выберите Excel файл</label>
|
||||
<input class="form-control" type="file" id="file" name="file" accept=".xlsx,.xls" required>
|
||||
</div>
|
||||
<h6 class="card-subtitle mb-3">Реквизиты ведомости</h6>
|
||||
<div class="row g-3 mb-3">
|
||||
<div class="col-md-6">
|
||||
<label for="document_name" class="form-label">Название ведомости</label>
|
||||
<input class="form-control" type="text" id="document_name" name="document_name" maxlength="255" placeholder="Например: Основная ведомость">
|
||||
</div>
|
||||
<div class="col-md-3">
|
||||
<label for="document_number" class="form-label">Номер</label>
|
||||
<input class="form-control" type="text" id="document_number" name="document_number" maxlength="100">
|
||||
</div>
|
||||
<div class="col-md-3">
|
||||
<label for="document_date" class="form-label">Дата</label>
|
||||
<input class="form-control" type="date" id="document_date" name="document_date">
|
||||
</div>
|
||||
<div class="col-md-6">
|
||||
<label for="contract" class="form-label">Договор</label>
|
||||
<input class="form-control" type="text" id="contract" name="contract" maxlength="255" value="{{ project.contract_number or '' }}">
|
||||
</div>
|
||||
</div>
|
||||
<button type="submit" class="btn btn-primary">Загрузить</button>
|
||||
<a href="/projects/{{ project.id }}" class="btn btn-secondary">Отмена</a>
|
||||
</form>
|
||||
|
||||
@@ -12,6 +12,7 @@
|
||||
<p><strong>Проект:</strong> {{ project.name }}</p>
|
||||
<p><strong>Файл:</strong> {{ filename }}</p>
|
||||
<p><strong>Лист:</strong> {{ sheet_name }}</p>
|
||||
{% if import_result.document_name %}<p><strong>Ведомость:</strong> {{ import_result.document_name }}</p>{% endif %}
|
||||
|
||||
<div class="card">
|
||||
<div class="card-body">
|
||||
|
||||
@@ -95,7 +95,30 @@
|
||||
</div>
|
||||
|
||||
<div class="mt-4">
|
||||
<form method="post" action="/boq/{{ project.id }}/import/confirm">
|
||||
<form method="post" action="/boq/{{ project.id }}/import/confirm" id="import-confirm-form">
|
||||
<div class="card mb-3">
|
||||
<div class="card-body">
|
||||
<h5 class="card-title">Реквизиты ведомости</h5>
|
||||
<div class="row g-3">
|
||||
<div class="col-md-6">
|
||||
<label class="form-label" for="document_name">Название ведомости</label>
|
||||
<input class="form-control" type="text" id="document_name" name="document_name" value="{{ document_name or sheet_name }}" required maxlength="255">
|
||||
</div>
|
||||
<div class="col-md-3">
|
||||
<label class="form-label" for="document_number">Номер</label>
|
||||
<input class="form-control" type="text" id="document_number" name="document_number" value="{{ document_number or '' }}" maxlength="100">
|
||||
</div>
|
||||
<div class="col-md-3">
|
||||
<label class="form-label" for="document_date">Дата</label>
|
||||
<input class="form-control" type="date" id="document_date" name="document_date" value="{{ document_date or '' }}">
|
||||
</div>
|
||||
<div class="col-md-6">
|
||||
<label class="form-label" for="contract">Договор</label>
|
||||
<input class="form-control" type="text" id="contract" name="contract" value="{{ contract or '' }}" maxlength="255">
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<input type="hidden" name="filename" value="{{ filename }}">
|
||||
<input type="hidden" name="sheet_name" value="{{ sheet_name }}">
|
||||
<input type="hidden" name="header_row" value="{{ header_row }}">
|
||||
|
||||
@@ -35,6 +35,10 @@
|
||||
<input type="hidden" name="sheet_name" value="{{ sheet }}">
|
||||
<input type="hidden" name="header_row" value="5">
|
||||
<input type="hidden" name="start_row" value="6">
|
||||
<input type="hidden" name="document_name" value="{{ document_name or '' }}">
|
||||
<input type="hidden" name="document_number" value="{{ document_number or '' }}">
|
||||
<input type="hidden" name="document_date" value="{{ document_date or '' }}">
|
||||
<input type="hidden" name="contract" value="{{ contract or '' }}">
|
||||
<button type="submit" class="btn btn-sm btn-primary">Выбрать</button>
|
||||
</form>
|
||||
</td>
|
||||
|
||||
@@ -0,0 +1,114 @@
|
||||
# Implementation Report — 023-fix-ui-followup
|
||||
|
||||
### Status
|
||||
|
||||
DONE
|
||||
|
||||
### What was done
|
||||
|
||||
Follow-up к 023 после визуальной проверки. Исправлены 5 обнаруженных расхождений, без нового редизайна.
|
||||
|
||||
#### 1. Дерево документов — кнопка «Дополнительные соглашения»
|
||||
В card-header блока «Дерево документов» рядом с «Ведомости» добавлена кнопка «Дополнительные соглашения» → `/projects/{id}/agreements`. Маршруты не дублируются, существующие ссылки на ДС не тронуты.
|
||||
|
||||
#### 2. Кнопка «Сформировать комплект»
|
||||
- добавлен `text-nowrap w-auto` — текст не переносится, кнопка не растягивается;
|
||||
- обёртка `d-flex align-items-end` — выравнивание по нижнему краю формы без увеличения высоты.
|
||||
- Текст, endpoint, ZIP-логика не менялись.
|
||||
- Browser: высота ≈ 38px, `btn btn-primary text-nowrap w-auto`.
|
||||
|
||||
#### 3. Шапка проекта
|
||||
Перераскладка по целевому принципу:
|
||||
- **Верхняя строка:** слева `h1` название, справа «Дневной отчёт» + «Редактировать»;
|
||||
- **Под названием:** компактная строка реквизитов (Договор, Заказчик, Валюта, Период, Статус-badge);
|
||||
- **Следующей строкой:** «Ведомость проекта».
|
||||
- Bootstrap 5 сохранён, большого редизайна нет.
|
||||
|
||||
#### 4. Импорт ведомости — реквизиты
|
||||
Проверено фактическое состояние после 023: поля модели/миграция уже были, реквизиты были только на preview. Замкнут разрыв — форма `/boq/import` и весь flow:
|
||||
- `import.html` — 4 поля: Название, Номер, Дата, Договор (Договор по умолчанию = `project.contract_number`);
|
||||
- `POST /import/upload` принимает и прокидывает реквизиты в sheet selection;
|
||||
- `import_sheet_selection.html` — hidden-поля до preview;
|
||||
- `import_preview.html` — реквизиты внутри формы confirm (редактируемы);
|
||||
- `import/confirm` → `import_excel_data` сохраняет в `BoqDocument` (без параллельной модели);
|
||||
- после импорта имя показывается в `import_confirm` и как `display_name`.
|
||||
- Сценарий Excel → лист → настройка → preview → подтверждение не сломан.
|
||||
|
||||
#### 5. Статус в списках КС-2 / КС-3 / Платежей
|
||||
- **КС-2 и КС-3:** badge с тремя статусами — `Черновик` (secondary), `Проведён` (success), `Сторнирован` (danger). Раньше «Сторнирован» отображался как «Черновик».
|
||||
- **Платежи:** добавлена колонка «Статус» — `Активный` (success) / `Сторнирован` (danger для `cancelled`).
|
||||
- Текст статуса обязателен, не только цвет. Row-click и action-кнопки сохранены.
|
||||
|
||||
### Changed files
|
||||
|
||||
| Файл | Что |
|
||||
|---|---|
|
||||
| `app/templates/projects/detail.html` | шапка, дерево документов, кнопка комплекта |
|
||||
| `app/templates/projects/import.html` | поля реквизитов |
|
||||
| `app/templates/projects/import_sheet_selection.html` | hidden-реквизиты |
|
||||
| `app/templates/projects/import_preview.html` | реквизиты внутри формы confirm |
|
||||
| `app/routers/boq.py` | upload принимает/прокидывает реквизиты |
|
||||
| `app/templates/ks2/list.html` | 3-статусный badge |
|
||||
| `app/templates/ks3/list.html` | 3-статусный badge |
|
||||
| `app/templates/payments/list.html` | колонка «Статус» + badge |
|
||||
| `tests/test_task023fix_ui_followup.py` | новые тесты (9 шт.) |
|
||||
| `docs/tasks/023-fix-ui-followup.md` | task-файл |
|
||||
|
||||
### Tests
|
||||
|
||||
`tests/test_task023fix_ui_followup.py` — 9 тестов:
|
||||
|
||||
1. `test_document_tree_has_boq_and_agreements_buttons` — обе кнопки в дереве
|
||||
2. `test_import_form_shows_all_four_requisites` — 4 поля на `/import`
|
||||
3. `test_import_requisites_pass_upload_to_confirm` — upload → preview → confirm, сохранение в БД
|
||||
4. `test_display_name_used_in_agreement_scope` — display_name без `BOQ Import`
|
||||
5. `test_ks2_list_shows_all_statuses` — Черновик/Проведён/Сторнирован
|
||||
6. `test_ks3_list_shows_all_statuses` — то же
|
||||
7. `test_payments_list_shows_status` — Активный/Сторнирован
|
||||
8. `test_project_header_layout_and_package_button` — шапка + `w-auto`/`text-nowrap`
|
||||
9. `test_eye_toggle_and_agreement_create_not_broken` — регрессии
|
||||
|
||||
Результат `pytest -q`:
|
||||
|
||||
```
|
||||
225 passed, 272 warnings in 21.78s
|
||||
```
|
||||
|
||||
(Все существующие тесты проходят.)
|
||||
|
||||
Результат `git diff --check`:
|
||||
|
||||
```
|
||||
(без ошибок; LF→CRLF warnings — Windows-рабочая копия)
|
||||
```
|
||||
|
||||
### Browser-check
|
||||
|
||||
Playwright/Chromium, viewport 1280×900, реальный проект `/projects/2` (ведомость, ДС, КС-2 с сторно, платежи). **32/32 + import e2e passed.**
|
||||
|
||||
| Проверка | Результат |
|
||||
|---|---|
|
||||
| Шапка: Дневной отчёт + Редактировать в верхней строке | title_y=64, btn_y=64 (одна строка) |
|
||||
| Реквизиты проекта читаются, статус виден | да |
|
||||
| Дерево: «Ведомости» и «Дополнительные соглашения» | обе кнопки, обе кликабельны |
|
||||
| Кнопка комплекта нормальной высоты | h≈38px, без `w-100` |
|
||||
| Импорт: 4 реквизита на форме | все поля есть |
|
||||
| Импорт с реквизитами end-to-end | upload → preview → confirm, имя сохранено |
|
||||
| КС-2 статусы | badge + «Сторнирован» (bg-danger) |
|
||||
| КС-3 статусы | badge |
|
||||
| Платежи статус | колонка «Статус», «Активный»/«Сторнирован» |
|
||||
| Row-click | КС-2/КС-3/Платежи/ДС |
|
||||
| Eye-toggle | работает |
|
||||
| Создание ДС / display_name | форма работает, `['Весь проект', 'Ведомость ОВ']` |
|
||||
|
||||
Скриншоты: `output/playwright/023fix-*.png`.
|
||||
|
||||
### Deviations
|
||||
|
||||
None.
|
||||
|
||||
### Follow-up / Open Questions
|
||||
|
||||
- `_tmp_verify_023fix*.py` и `output/playwright/023fix-*.png` — артефакты browser-check, не production-код.
|
||||
- На preview название ведомости по умолчанию = имя листа, если пользователь не заполнил его на первом шаге.
|
||||
- Warning `declarative_base` / openpyxl `utcnow` — существующий техдолг, вне scope.
|
||||
@@ -0,0 +1,86 @@
|
||||
# Implementation Report — 023-fix2-ui-header-payments
|
||||
|
||||
### Status
|
||||
|
||||
DONE
|
||||
|
||||
### What was done
|
||||
|
||||
Точечная правка UI по двум дефектам после визуальной проверки 023-FIX. Только HTML/CSS/layout.
|
||||
|
||||
#### 1. Шапка проекта
|
||||
|
||||
Структура приведена к трём явным строкам:
|
||||
|
||||
1. **Первая строка:** слева `h1` название, справа «Дневной отчёт» + «Редактировать».
|
||||
2. **Вторая строка:** реквизиты как **отдельные блоки** Bootstrap grid (`row g-3 g-md-4` + `col-md-auto`): у каждого блока своя метка (`Договор` / `Заказчик` / `Валюта` / `Период` / `Статус`) и значение под ней. Раньше это был один inline-ряд `gap-x-4` без визуального разделения.
|
||||
3. **Третья строка:** «Ведомость проекта».
|
||||
|
||||
Между блоками реквизитов горизонтальный интервал ~24px (gutter `g-4`), элементы не слипаются. Данные и функциональность сохранены. Большого редизайна нет.
|
||||
|
||||
#### 2. Таблица платежей — блок действий
|
||||
|
||||
- контейнер действий `d-inline-flex gap-1 text-nowrap` — «Просмотр», «Редактировать», «Удалить» в одной строке, без переноса;
|
||||
- колонке «Действия» задана ширина `17rem` через `colgroup`;
|
||||
- общий `table-responsive` сохранён — горизонтальная прокрутка на узком экране допустима;
|
||||
- row-click и маршруты не менялись.
|
||||
|
||||
### Changed files
|
||||
|
||||
| Файл | Что |
|
||||
|---|---|
|
||||
| `app/templates/projects/detail.html` | шапка: 3 строки, реквизиты как отдельные grid-блоки |
|
||||
| `app/templates/payments/list.html` | colgroup + nowrap-контейнер действий |
|
||||
| `tests/test_task023fix2_layout.py` | 2 layout-теста |
|
||||
| `docs/tasks/023-fix2-ui-header-payments.md` | task-файл |
|
||||
|
||||
Не менялись: бизнес-логика, модели БД, расчёты, статусы, финансы, импорт, экспорт, маршруты, структура документов.
|
||||
|
||||
### Tests
|
||||
|
||||
`tests/test_task023fix2_layout.py` (2):
|
||||
- `test_project_header_requisites_are_separate_blocks` — метки в отдельных блоках, `row g-3 g-md-4`, верхняя строка с кнопками;
|
||||
- `test_payments_actions_are_nowrap_inline` — `payments-actions` / `text-nowrap` / `d-inline-flex`, ширина колонки, 3 действия, статус, row-click.
|
||||
|
||||
Результат `pytest -q`:
|
||||
|
||||
```
|
||||
227 passed, 272 warnings in 23.21s
|
||||
```
|
||||
|
||||
(225 существующих + 2 новых; все прежние тесты проходят.)
|
||||
|
||||
Результат `git diff --check`:
|
||||
|
||||
```
|
||||
(без ошибок; LF→CRLF warnings — Windows-рабочая копия)
|
||||
```
|
||||
|
||||
### Browser-check
|
||||
|
||||
Playwright/Chromium, viewport 1280×900. Проект `/projects/2` (полные данные, сторнированный платёж) и `/projects/5` (обычный без сторно). **20/20 passed.**
|
||||
|
||||
| Проверка | Результат |
|
||||
|---|---|
|
||||
| Название и 2 кнопки в одной верхней строке | title_y=64, daily_y=64, edit_y=64 |
|
||||
| Реквизиты отдельными блоками (5 шт.) | `['Договор','Заказчик','Валюта','Период','Статус']` |
|
||||
| Интервалы между блоками | gaps ≈ 24px между метками |
|
||||
| Блоки не слипаются, высота ~49px (метка+значение) | да |
|
||||
| «Ведомость проекта» отдельной строкой | boq_y=175, реквизиты y=118 |
|
||||
| Платежи: 3 действия в одной строке | ys идентичны |
|
||||
| Кнопки не переносятся | `text-nowrap` + `d-inline-flex` |
|
||||
| Строка сторнированного платежа | badge + 3 действия, та же строка |
|
||||
| Горизонтальная прокрутка | работает |
|
||||
| Обычный проект без сторно | шапка и платежи в порядке |
|
||||
|
||||
Скриншоты: `output/playwright/023fix2-*.png`.
|
||||
|
||||
### Deviations
|
||||
|
||||
None.
|
||||
|
||||
### Follow-up / Open Questions
|
||||
|
||||
- `_tmp_verify_023fix2.py` и screenshots — артефакты browser-check, не production-код.
|
||||
- Ширина колонки «Действия» (17rem) подобрана под текущие три `btn-sm`; при добавлении действий нужно будет пересмотреть.
|
||||
- 023-FIX остаётся под review до приёмки этой browser-check (по условию task).
|
||||
@@ -0,0 +1,117 @@
|
||||
# Implementation Report — 023-fix3-project-header-layout
|
||||
|
||||
### Status
|
||||
|
||||
DONE
|
||||
|
||||
### What was done
|
||||
|
||||
Переразметка верхней части страницы проекта по целевой визуальной схеме. Только HTML/CSS/layout.
|
||||
|
||||
#### Итоговая структура верхней части
|
||||
|
||||
```text
|
||||
Проекты / Саудовская Аравия (breadcrumb)
|
||||
|
||||
Саудовская Аравия (h1)
|
||||
[Дневной отчёт] [Редактировать] (действия под заголовком, слева)
|
||||
|
||||
Договор | Заказчик | Валюта | Период | Статус (отдельные grid-блоки)
|
||||
|
||||
Ведомость проекта: Ведомость ОВ (отдельная строка)
|
||||
|
||||
[Ведомости] [Дополнительные соглашения] [Daily Reports] [КС-2] [КС-3] [КС-6а] [Платежи]
|
||||
(один ряд, по левому краю)
|
||||
|
||||
[Архивировать] [Удалить проект]
|
||||
|
||||
✓ Проверка плана: превышений нет
|
||||
|
||||
Финансовые суммы [глаз]
|
||||
|
||||
План и выполнение
|
||||
```
|
||||
|
||||
#### 1–3. Заголовок, реквизиты, ведомость
|
||||
- Кнопки «Дневной отчёт» / «Редактировать» **перемещены из правого верхнего угла** в блок под заголовком.
|
||||
- Реквизиты остались отдельными grid-блоками с промежутками (`row g-3 g-md-4` + `col-md-auto`).
|
||||
- «Ведомость проекта» — отдельной строкой.
|
||||
|
||||
#### 4. Ряд навигации — главное изменение
|
||||
|
||||
Все 7 кнопок в одном `nav.doc-nav`:
|
||||
- `display: flex; flex-wrap: nowrap` — кнопки **не переносятся** на вторую строку;
|
||||
- **нет** `overflow-x: auto` / горизонтального scroll — ряд всегда вписывается;
|
||||
- `flex: 1 1 0; min-width: 0` — кнопки сжимаются по ширине, текст переносится внутри кнопки (`white-space: normal`);
|
||||
- `align-items: stretch` — одинаковая высота всех кнопок (54px на 1280px и 1024px);
|
||||
- `display: flex; align-items: center; justify-content: center` — содержимое кнопок по центру;
|
||||
- ряд выровнен по левому краю (`x0=12`).
|
||||
|
||||
#### 5. Финансовый переключатель
|
||||
|
||||
Блок «Финансовые суммы [глаз]» **вынесен из навигации** и расположен **непосредственно перед «План и выполнение»**, справа. Поведение eye-toggle не менялось.
|
||||
|
||||
### Changed files
|
||||
|
||||
| Файл | Что |
|
||||
|---|---|
|
||||
| `app/templates/projects/detail.html` | композиция шапки, `.doc-nav` CSS, перенос eye-toggle |
|
||||
| `tests/test_task023fix3_header_layout.py` | 3 layout-теста |
|
||||
| `docs/tasks/023-fix3-project-header-layout.md` | task-файл |
|
||||
|
||||
Не менялись: маршруты, бизнес-логика, модели БД, расчёты, статусы, документы, импорт, экспорт, платежная логика, поведение eye-toggle.
|
||||
|
||||
### Tests
|
||||
|
||||
`tests/test_task023fix3_header_layout.py` (3):
|
||||
- `test_doc_nav_has_all_seven_buttons_in_one_row` — 7 кнопок и все href в `doc-nav`;
|
||||
- `test_doc_nav_has_no_horizontal_scroll_wrapper` — нет `overflow`/`table-responsive`, CSS `flex-wrap: nowrap`, без `overflow-x`;
|
||||
- test `test_header_order_and_eye_toggle_separate` — порядок блоков, eye-toggle после nav и перед «План и выполнение», реквизиты, архив/удаление.
|
||||
|
||||
Результат `pytest -q`:
|
||||
|
||||
```
|
||||
230 passed, 272 warnings in 23.85s
|
||||
```
|
||||
|
||||
(227 существующих + 3 новых; все прежние тесты проходят.)
|
||||
|
||||
Результат `git diff --check`:
|
||||
|
||||
```
|
||||
(без ошибок; LF→CRLF warnings — Windows-рабочая копия)
|
||||
```
|
||||
|
||||
### Browser-check
|
||||
|
||||
Playwright/Chromium. Проекты `/projects/2` (реальные данные, сторно) и `/projects/5` (обычный), viewport 1280 и 1024. **45/45 passed.**
|
||||
|
||||
| Проверка | Результат |
|
||||
|---|---|
|
||||
| Заголовок проекта | h1, отдельный блок |
|
||||
| Дневной отчёт / Редактировать | под заголовком, слева (y=110 vs title y=64) |
|
||||
| Реквизиты отдельными блоками | 5 блоков с метками |
|
||||
| Ведомость проекта | отдельная строка |
|
||||
| 7 кнопок навигации | все присутствуют |
|
||||
| Один ряд, без переноса кнопок | все y одинаковы (Δ<5px) |
|
||||
| Одинаковая высота | все h=54px |
|
||||
| Выравнивание по левому краю | x0=12 |
|
||||
| Нет горизонтального scroll | `overflow-x: visible`, nav и body в пределах viewport |
|
||||
| Перенос текста внутри кнопок | `white-space: normal`; «Дополнительные соглашения» помещается в 2 строки |
|
||||
| 1024px | ряд остаётся одним, 7×136px, без overflow |
|
||||
| Eye-toggle отдельно | после nav (y=420), перед «План и выполнение» (y=467), не внутри nav |
|
||||
| Eye-toggle работает | toggle money-hidden |
|
||||
| Архивирование/удаление | присутствуют |
|
||||
| Обычный проект (без сторно) | в порядке |
|
||||
|
||||
Скриншоты: `output/playwright/023fix3-*.png`.
|
||||
|
||||
### Deviations
|
||||
|
||||
None.
|
||||
|
||||
### Follow-up / Open Questions
|
||||
|
||||
- `_tmp_verify_023fix3.py` и screenshots — артефакты browser-check, не production-код.
|
||||
- На очень узких экранах (< ~900px) текст в кнопках станет более многострочным; горизонтального scroll нет по требованиям.
|
||||
- Ширина кнопок выровнена через `flex: 1 1 0` — при желании можно вернуть «контентную» ширину, сохранив nowrap-ряд.
|
||||
@@ -0,0 +1,126 @@
|
||||
# Implementation Report — 023-ui-ux-cleanup-v1
|
||||
|
||||
### Status
|
||||
|
||||
DONE
|
||||
|
||||
### What was done
|
||||
|
||||
Один проход UI/UX-очистки после основного функционального контура. Bootstrap 5 + Jinja UI и бизнес-логика сохранены.
|
||||
|
||||
#### 1. Кнопка «Дневной отчёт»
|
||||
Кнопка вынесена в правый верхний блок рядом со статусом проекта и является главным действием (`btn-primary`). URL `/projects/{id}/daily-reports/new` не менялся.
|
||||
|
||||
#### 2. Статус проекта
|
||||
Цветовой badge по значениям: `active` → success «Активный», `completed` → primary «Завершён», `on_hold` → warning «Приостановлен», `archived` → secondary «Архивирован». Значения статусов и бизнес-логика не менялись.
|
||||
|
||||
#### 3. Финансовый eye-toggle
|
||||
Вынесен в отдельную строку-утилиту с подписью «Финансовые суммы» — на странице проекта, в ведомости и в `base.html` (Dashboard, КС-2, КС-3, Платежи). Не смешан с бизнес-навигацией. Поведение сохранено: суммы скрыты по умолчанию, количество/проценты не скрываются, состояние не персистится.
|
||||
|
||||
#### 4. Точки входа «Ведомости» и «Дополнительные соглашения»
|
||||
Две смежные кнопки в отдельной строке на странице проекта. Маршруты и функциональность сохранены, ДС не удалён.
|
||||
|
||||
#### 5. Кнопка «Сформировать комплект»
|
||||
Убран `w-100`, обычная кнопка нормального размера. Механизм ZIP не менялся.
|
||||
|
||||
#### 6. ДС — line-click
|
||||
Строки списка ДС кликабельны (`clickable-row` + `data-url`), клик по action-кнопке/ссылке не срабатывает как переход строки (фильтр `e.target.closest('a, button, form, input, select, textarea')`).
|
||||
|
||||
#### 7. Название ведомости в выборе области ДС
|
||||
Добавлен `BoqDocument.display_name` — убирает технические префиксы (`BOQ Import - `, `Импорт ведомости — ` и т.п.). Используется в: селекторе области ДС, селекторе «Ведомость» при добавлении позиции, списке ведомостей, дереве документов, заголовке страницы ведомости, `_scope_label`. Пример: `BOQ Import - Ведомость ОВ` → `Ведомость ОВ`.
|
||||
|
||||
#### 8. Реквизиты BoqDocument при импорте
|
||||
В модель `BoqDocument` добавлены поля (с миграцией `20260928_boq_document_requisites`):
|
||||
- `document_number` (String)
|
||||
- `document_date` (Date)
|
||||
- `contract` (String)
|
||||
|
||||
Параллельной сущности не создавалось. На шаге preview пользователь задаёт:
|
||||
- Название ведомости (сохраняется в существующий `name`)
|
||||
- Номер
|
||||
- Дату
|
||||
- Договор (по умолчанию подставляется `project.contract_number`, но может быть изменён)
|
||||
|
||||
Import flow не сломан: upload → sheet → preview (с реквизитами) → confirm (транзакционно).
|
||||
|
||||
#### 9. Удаление проекта с зависимыми данными
|
||||
Бизнес-правило удаления не менялось (API по-прежнему возвращает 400 JSON для API-клиентов). Для браузерного действия форма перехватывается JS: POST через fetch, при 400 показывается Bootstrap modal «Проект нельзя удалить» с объяснением и кнопками «Отмена» / «Архивировать проект» (существующий `/archive`).
|
||||
|
||||
### Changed files
|
||||
|
||||
- `app/models/boq.py` — поля реквизитов + `display_name`
|
||||
- `app/database/migrations.py` — миграция реквизитов
|
||||
- `app/importer/excel_importer.py` — приём/сохранение реквизитов
|
||||
- `app/routers/boq.py` — форма реквизитов в preview/confirm
|
||||
- `app/routers/agreements.py` — `display_name` в `_scope_label`
|
||||
- `app/templates/projects/detail.html` — статус badge, кнопка «Дневной отчёт», eye-toggle, точки входа, размер кнопки комплекта, modal удаления, JS delete
|
||||
- `app/templates/projects/boq_document.html` — реквизиты в шапке, eye-toggle
|
||||
- `app/templates/projects/boq_list.html` — `display_name`
|
||||
- `app/templates/projects/import_preview.html` — поля реквизитов
|
||||
- `app/templates/projects/import_confirm.html` — имя ведомости в результате
|
||||
- `app/templates/agreements/list.html` — clickable rows
|
||||
- `app/templates/agreements/new.html` — `display_name`
|
||||
- `app/templates/agreements/detail.html` — `display_name`
|
||||
- `app/templates/base.html` — подпись eye-toggle
|
||||
- `tests/test_task023_ui_ux_cleanup.py` — новые тесты (11 шт.)
|
||||
- `docs/tasks/023-ui-ux-cleanup-v1.md` — task-файл
|
||||
|
||||
### Tests
|
||||
|
||||
Новые тесты `tests/test_task023_ui_ux_cleanup.py` (11):
|
||||
|
||||
1. `test_agreement_list_rows_are_clickable` — row-click + фильтр action-кнопок
|
||||
2. `test_agreement_scope_shows_display_name_not_technical` — нет `BOQ Import` в селекторе
|
||||
3. `test_boq_display_name_property` — очистка технических префиксов
|
||||
4. `test_import_excel_saves_document_requisites` — реквизиты сохраняются
|
||||
5. `test_import_preview_exposes_requisites_fields` — поля формы на preview
|
||||
6. `test_delete_project_blocked_keeps_api_json_and_page_has_modal` — API 400 JSON + modal на странице
|
||||
7. `test_delete_project_without_related_data_still_works` — удаление чистого проекта
|
||||
8. `test_import_confirm_flow_still_works` — import flow не сломан
|
||||
9. `test_eye_toggle_present_on_project_and_base_pages` — eye-toggle на всех страницах
|
||||
10. `test_project_page_status_badge_and_package_button` — badge + размер кнопки
|
||||
11. `test_boq_document_shows_requisites` — реквизиты отображаются
|
||||
|
||||
Результат `pytest -q`:
|
||||
|
||||
```
|
||||
216 passed, 264 warnings in 18.76s
|
||||
```
|
||||
|
||||
(Все существующие тесты продолжают проходить; warning'и — существующие deprecation openpyxl/sqlalchemy.)
|
||||
|
||||
Результат `git diff --check`:
|
||||
|
||||
```
|
||||
(без ошибок; предупреждения LF→CRLF — Windows-рабочая копия)
|
||||
```
|
||||
|
||||
### Browser-check
|
||||
|
||||
Playwright/Chromium, viewport 1280×900, реальный проект (`/projects/2` с ведомостью, ДС, Daily Reports). **25/25 passed.**
|
||||
|
||||
| Проверка | Результат |
|
||||
|---|---|
|
||||
| Кнопка «Дневной отчёт» вверху, видима | y≈179 |
|
||||
| Статус визуально различим (badge) | да |
|
||||
| Eye-toggle отделён, работает | да |
|
||||
| «Ведомости» и «ДС» доступны рядом | да |
|
||||
| «Сформировать комплект» обычного размера | `btn btn-primary` без `w-100` |
|
||||
| Удаление с зависимыми данными → modal, не JSON | modal «Проект нельзя удалить» + «Архивировать проект» |
|
||||
| Строка ДС кликабельна | навигация на страницу ДС |
|
||||
| Action-кнопка ДС не ломает row-click | переходит на страницу ДС |
|
||||
| В выборе области ДС — название, не `BOQ Import` | `['Весь проект', 'Ведомость ОВ']` |
|
||||
| Eye-toggle на BOQ / КС-2 / КС-3 / Payments | везде есть |
|
||||
|
||||
Скриншоты: `output/playwright/023-*.png`.
|
||||
|
||||
### Deviations
|
||||
|
||||
None.
|
||||
|
||||
### Follow-up / Open Questions
|
||||
|
||||
- `_tmp_verify_023.py` и `output/playwright/023-*.png` — артефакты browser-check, не production-код (по требованию task не включены в код).
|
||||
- `BoqDocument.display_name` можно позже вынести в Jinja-фильтр, если появятся другие сущности с техническими именами.
|
||||
- Кнопка «Удалить проект» при не-400 ошибках сети тоже показывает modal «нельзя удалить» — при желании можно разделить тексты ошибок.
|
||||
- Warning `declarative_base` (SQLAlchemy 2.0) и `datetime.utcnow` (openpyxl) — существующий техдолг, вне scope.
|
||||
@@ -0,0 +1,243 @@
|
||||
# Задача 023-FIX — Доработка UI/UX после проверки
|
||||
|
||||
## Статус
|
||||
|
||||
Это follow-up к задаче 023. Задачу 023 пока НЕ считать закрытой.
|
||||
|
||||
По результатам визуальной проверки на реальном проекте часть заявленных изменений фактически не дошла до интерфейса. Исправить именно обнаруженные расхождения, не расширяя задачу новым редизайном.
|
||||
|
||||
Обязательна browser-проверка после исправлений.
|
||||
|
||||
---
|
||||
|
||||
## 1. Дерево документов — кнопка «Дополнительные соглашения»
|
||||
|
||||
В блоке «Дерево документов» сейчас сверху есть кнопка:
|
||||
|
||||
- «Ведомости»
|
||||
|
||||
Но отдельной кнопки/точки входа для «Дополнительных соглашений» там нет.
|
||||
|
||||
Нужно добавить рядом:
|
||||
|
||||
- **Ведомости**
|
||||
- **Дополнительные соглашения**
|
||||
|
||||
Обе кнопки должны вести на соответствующие существующие списки.
|
||||
|
||||
Важно: не дублировать лишние маршруты и не ломать существующие ссылки на ДС.
|
||||
|
||||
---
|
||||
|
||||
## 2. Кнопка «Сформировать комплект»
|
||||
|
||||
По визуальной проверке кнопка всё ещё слишком высокая/широкая и занимает непропорционально много места.
|
||||
|
||||
Нужно привести её к обычному размеру, сопоставимому с другими кнопками действий.
|
||||
|
||||
Не менять:
|
||||
- текст;
|
||||
- endpoint;
|
||||
- формат ZIP;
|
||||
- логику выбора документов.
|
||||
|
||||
После изменения проверить в браузере.
|
||||
|
||||
---
|
||||
|
||||
## 3. Шапка проекта
|
||||
|
||||
Текущая шапка страницы проекта визуально сверстана неудачно:
|
||||
|
||||
- элементы реквизитов проекта расположены неравномерно;
|
||||
- верхняя область выглядит разрозненно;
|
||||
- кнопки действий и реквизиты не образуют аккуратную структуру.
|
||||
|
||||
Нужно аккуратно переразложить текущие элементы.
|
||||
|
||||
Целевой принцип:
|
||||
|
||||
### Верхняя строка
|
||||
Слева:
|
||||
- название проекта.
|
||||
|
||||
Справа:
|
||||
- **Дневной отчёт**
|
||||
- **Редактировать**
|
||||
|
||||
### Под названием
|
||||
В компактной строке/блоке:
|
||||
- Договор;
|
||||
- Заказчик;
|
||||
- Валюта;
|
||||
- Период;
|
||||
- Статус.
|
||||
|
||||
Следующей строкой:
|
||||
- Ведомость проекта.
|
||||
|
||||
Не делать большой редизайн.
|
||||
|
||||
Сохранить текущую Bootstrap 5 стилистику.
|
||||
|
||||
Проверить нормальное отображение на ширине текущего приложения.
|
||||
|
||||
---
|
||||
|
||||
## 4. Импорт ведомости — реквизиты всё ещё отсутствуют
|
||||
|
||||
По визуальной проверке форма `/boq/import` всё ещё показывает только:
|
||||
|
||||
- выбор Excel файла;
|
||||
- загрузку.
|
||||
|
||||
Реквизиты ведомости, заявленные в 023, фактически отсутствуют.
|
||||
|
||||
Нужно реализовать/довести до рабочего состояния:
|
||||
|
||||
- **Название ведомости**
|
||||
- **Номер**
|
||||
- **Дата**
|
||||
- **Договор**
|
||||
|
||||
Эти значения должны:
|
||||
|
||||
1. отображаться в форме импорта;
|
||||
2. вводиться пользователем;
|
||||
3. передаваться при создании `BoqDocument`;
|
||||
4. сохраняться в БД;
|
||||
5. отображаться после импорта в интерфейсе ведомости;
|
||||
6. использоваться как пользовательское `display_name`.
|
||||
|
||||
Не создавать вторую параллельную модель.
|
||||
|
||||
Сначала проверить фактическое состояние `BoqDocument`, migration и importer после 023. Если поля/миграция уже есть, но форма/роутер их не передает — исправить именно этот разрыв.
|
||||
|
||||
### Важно
|
||||
|
||||
Не сломать существующий сценарий:
|
||||
|
||||
Excel → выбор листа → настройка → preview → подтверждение импорта.
|
||||
|
||||
---
|
||||
|
||||
## 5. Статус в списках КС-2 / КС-3 / Платежей
|
||||
|
||||
Сейчас в списках документов статус не виден.
|
||||
|
||||
Из-за этого пользователь видит документ, но не понимает, что он сторнирован, пока не откроет карточку.
|
||||
|
||||
Нужно добавить явный статус в таблицы/списки:
|
||||
|
||||
### КС-2
|
||||
Для каждого документа показывать:
|
||||
- `Черновик`
|
||||
- `Проведён`
|
||||
- `Сторнирован`
|
||||
|
||||
Использовать Bootstrap badge.
|
||||
|
||||
### КС-3
|
||||
То же:
|
||||
- `Черновик`
|
||||
- `Проведён`
|
||||
- `Сторнирован`
|
||||
|
||||
### Платежи
|
||||
Показывать:
|
||||
- текущий статус платежа;
|
||||
- если используется существующий `cancelled` — отображать как **«Сторнирован»**.
|
||||
|
||||
Не менять модель статусов без необходимости.
|
||||
|
||||
### Визуально
|
||||
|
||||
Например:
|
||||
|
||||
- Черновик — нейтральный badge;
|
||||
- Проведён — зелёный;
|
||||
- Сторнирован — красный/опасный.
|
||||
|
||||
Не использовать только цвет — текст статуса обязателен.
|
||||
|
||||
Существующие row-click и action-кнопки не должны сломаться.
|
||||
|
||||
---
|
||||
|
||||
## 6. Проверка после исправлений
|
||||
|
||||
Обязательный browser-check на реальном проекте.
|
||||
|
||||
Проверить:
|
||||
|
||||
### Проект
|
||||
- шапка выглядит аккуратно;
|
||||
- Дневной отчёт и Редактировать находятся в верхней строке;
|
||||
- реквизиты проекта читаются;
|
||||
- статус проекта виден.
|
||||
|
||||
### Дерево документов
|
||||
- есть «Ведомости»;
|
||||
- рядом есть «Дополнительные соглашения»;
|
||||
- обе кнопки работают.
|
||||
|
||||
### Комплект
|
||||
- кнопка нормального размера;
|
||||
- формирование ZIP не изменилось.
|
||||
|
||||
### Импорт
|
||||
- все 4 реквизита доступны;
|
||||
- импорт с ними проходит;
|
||||
- после импорта название ведомости отображается корректно.
|
||||
|
||||
### Документы
|
||||
Проверить списки:
|
||||
- КС-2;
|
||||
- КС-3;
|
||||
- Платежи.
|
||||
|
||||
В каждом статус виден без открытия документа.
|
||||
|
||||
### Регрессия
|
||||
Проверить:
|
||||
- row-click;
|
||||
- eye-toggle;
|
||||
- создание ДС;
|
||||
- импорт ведомости;
|
||||
- существующие действия КС-2/КС-3/платежей.
|
||||
|
||||
---
|
||||
|
||||
## 7. Тесты
|
||||
|
||||
Добавить/обновить автоматические тесты там, где это разумно.
|
||||
|
||||
Минимум:
|
||||
|
||||
1. Кнопка ДС присутствует в дереве документов.
|
||||
2. Реквизиты `BoqDocument` передаются и сохраняются.
|
||||
3. `display_name` ведомости корректно используется в UI.
|
||||
4. Статус КС-2 отображается в списке.
|
||||
5. Статус КС-3 отображается в списке.
|
||||
6. Статус платежа отображается в списке.
|
||||
7. Существующие тесты продолжают проходить.
|
||||
|
||||
Для layout-проверок основной критерий — browser-check.
|
||||
|
||||
---
|
||||
|
||||
## 8. Результат
|
||||
|
||||
В отчёте указать:
|
||||
|
||||
- что из 5 замечаний исправлено;
|
||||
- какие файлы изменены;
|
||||
- какие поля/маршруты/шаблоны затронуты;
|
||||
- результаты тестов;
|
||||
- browser-check;
|
||||
- `git diff --check`;
|
||||
- deviations/open questions.
|
||||
|
||||
Временные Playwright-скрипты и screenshots не включать в production-код.
|
||||
|
||||
Commit/push автоматически не выполнять.
|
||||
@@ -0,0 +1,139 @@
|
||||
# Задача 023-FIX2 — точечная правка UI
|
||||
|
||||
## Статус
|
||||
|
||||
Follow-up к 023-FIX. Исправить два дефекта, обнаруженных при визуальной проверке.
|
||||
|
||||
Не считать предыдущую 023-FIX принятой до browser-check этой задачи.
|
||||
|
||||
---
|
||||
|
||||
## 1. Шапка проекта
|
||||
|
||||
Текущая реализация всё ещё выглядит криво: реквизиты проекта слипаются в одну строку без нормальных промежутков.
|
||||
|
||||
### Сделать структуру
|
||||
|
||||
**Первая строка:**
|
||||
|
||||
Слева:
|
||||
- название проекта
|
||||
|
||||
Справа:
|
||||
- Дневной отчёт
|
||||
- Редактировать
|
||||
|
||||
**Вторая строка:**
|
||||
|
||||
Отдельные аккуратно разделённые блоки:
|
||||
- Договор
|
||||
- Заказчик
|
||||
- Валюта
|
||||
- Период
|
||||
- Статус
|
||||
|
||||
Использовать Bootstrap grid/flex с нормальными `gap`/отступами.
|
||||
|
||||
Важно: элементы второй строки не должны визуально сливаться друг с другом даже при текущей ширине окна.
|
||||
|
||||
**Третья строка:**
|
||||
- Ведомость проекта
|
||||
|
||||
Не пытаться уместить все реквизиты второй строки в один текстовый inline-блок.
|
||||
|
||||
Сохранить текущие данные и функциональность.
|
||||
|
||||
Не делать большой редизайн страницы.
|
||||
|
||||
---
|
||||
|
||||
## 2. Таблица платежей — блок действий
|
||||
|
||||
На странице списка платежей сейчас кнопки действий переносятся:
|
||||
|
||||
- «Просмотр»
|
||||
- «Редактировать»
|
||||
- «Удалить»
|
||||
|
||||
Нужно сделать action-блок аккуратным.
|
||||
|
||||
Требования:
|
||||
|
||||
- кнопки не должны переноситься на несколько строк;
|
||||
- «Просмотр», «Редактировать», «Удалить» должны находиться в одной строке;
|
||||
- колонке «Действия» дать достаточную ширину;
|
||||
- использовать `white-space: nowrap` для контейнера действий или эквивалентное решение;
|
||||
- не ломать row-click;
|
||||
- не менять существующие маршруты и действия.
|
||||
|
||||
Если таблица на узком экране действительно требует горизонтальной прокрутки — это допустимо. Не нужно уменьшать кнопки до нечитаемого размера ради вписывания.
|
||||
|
||||
---
|
||||
|
||||
## 3. Что не менять
|
||||
|
||||
Не менять:
|
||||
|
||||
- бизнес-логику;
|
||||
- модели БД;
|
||||
- расчёты;
|
||||
- статусы;
|
||||
- финансовую логику;
|
||||
- импорт;
|
||||
- экспорт;
|
||||
- маршруты;
|
||||
- структуру документов.
|
||||
|
||||
Только HTML/CSS/layout, если иное не требуется для корректного отображения.
|
||||
|
||||
---
|
||||
|
||||
## 4. Browser-check
|
||||
|
||||
Обязательно проверить на реальном проекте:
|
||||
|
||||
### Шапка
|
||||
- название и две кнопки действий находятся в одной верхней строке;
|
||||
- реквизиты расположены отдельными блоками;
|
||||
- между Договором, Заказчиком, Валютой, Периодом и Статусом есть нормальные интервалы;
|
||||
- ничего не слипается;
|
||||
- Ведомость проекта находится отдельной строкой.
|
||||
|
||||
### Платежи
|
||||
- открыть список платежей;
|
||||
- проверить строку с существующим сторнированным платежом;
|
||||
- все три действия находятся в одной строке;
|
||||
- кнопки не переносятся;
|
||||
- горизонтальная прокрутка, если нужна, работает нормально.
|
||||
|
||||
После изменений проверить также обычный проект без сторнирования.
|
||||
|
||||
---
|
||||
|
||||
## 5. Тесты
|
||||
|
||||
Автоматические тесты добавлять только если для изменения есть разумная проверка.
|
||||
|
||||
Основной критерий для этой задачи — browser-check.
|
||||
|
||||
Обязательно:
|
||||
- существующие тесты проходят;
|
||||
- `git diff --check` чистый.
|
||||
|
||||
---
|
||||
|
||||
## 6. Результат
|
||||
|
||||
В отчёте указать:
|
||||
|
||||
- что изменено в шапке;
|
||||
- что изменено в таблице платежей;
|
||||
- изменённые файлы;
|
||||
- результат browser-check;
|
||||
- результаты тестов;
|
||||
- `git diff --check`;
|
||||
- deviations/open questions.
|
||||
|
||||
Временные Playwright-скрипты и screenshots не включать в production-код.
|
||||
|
||||
Commit/push автоматически не выполнять.
|
||||
@@ -0,0 +1,257 @@
|
||||
# Задача 023-FIX3 — переразметка шапки проекта
|
||||
|
||||
## Статус
|
||||
|
||||
Follow-up к 023-FIX.
|
||||
|
||||
Цель — переразложить верхнюю часть страницы проекта по визуальной схеме пользователя. Это не новый редизайн всей страницы, а точечная перестройка композиции существующих блоков.
|
||||
|
||||
Обязательна browser-проверка.
|
||||
|
||||
---
|
||||
|
||||
## 1. Целевая композиция
|
||||
|
||||
Ориентироваться на предоставленный пользователем screenshot как на визуальный референс.
|
||||
|
||||
Верхняя часть страницы должна быть организована примерно так:
|
||||
|
||||
### Блок 1 — название проекта
|
||||
|
||||
Слева:
|
||||
|
||||
**Саудовская Аравия**
|
||||
|
||||
Название проекта остаётся главным заголовком.
|
||||
|
||||
### Блок 2 — действия проекта
|
||||
|
||||
Кнопки:
|
||||
|
||||
- **Дневной отчёт**
|
||||
- **Редактировать**
|
||||
|
||||
Не держать их в текущем правом верхнем положении, как сейчас.
|
||||
|
||||
Переместить их в отдельный блок в соответствии с визуальной схемой screenshot — в область под/рядом с заголовком проекта.
|
||||
|
||||
Кнопки должны оставаться обычными компактными Bootstrap-кнопками.
|
||||
|
||||
---
|
||||
|
||||
## 2. Реквизиты проекта
|
||||
|
||||
Реквизиты:
|
||||
|
||||
- Договор
|
||||
- Заказчик
|
||||
- Валюта
|
||||
- Период
|
||||
- Статус
|
||||
|
||||
Оставить отдельным информационным блоком.
|
||||
|
||||
Не сливать их в одну строку без интервалов.
|
||||
|
||||
Использовать нормальную grid/flex-композицию с визуальными промежутками.
|
||||
|
||||
---
|
||||
|
||||
## 3. Ведомость проекта
|
||||
|
||||
`Ведомость проекта: ...`
|
||||
|
||||
Оставить отдельной строкой после основных реквизитов.
|
||||
|
||||
---
|
||||
|
||||
## 4. Навигация по документам — главное изменение
|
||||
|
||||
Кнопки:
|
||||
|
||||
1. **Ведомости**
|
||||
2. **Дополнительные соглашения**
|
||||
3. **Daily Reports**
|
||||
4. **КС-2**
|
||||
5. **КС-3**
|
||||
6. **КС-6а**
|
||||
7. **Платежи**
|
||||
|
||||
должны находиться **в одном горизонтальном логическом ряду**, с выравниванием всего ряда **по левому краю**.
|
||||
|
||||
### Жёсткие требования
|
||||
|
||||
**Горизонтальная прокрутка — НЕТ.**
|
||||
|
||||
Не использовать:
|
||||
- `overflow-x: auto`;
|
||||
- горизонтальный scroll;
|
||||
- скрывание кнопок за пределами viewport.
|
||||
|
||||
Также **не переносить сами кнопки на вторую строку**.
|
||||
|
||||
Если доступной ширины недостаточно:
|
||||
|
||||
- разрешён перенос текста ВНУТРИ кнопки;
|
||||
- длинная надпись может стать двухстрочной;
|
||||
- все кнопки ряда должны иметь **одинаковую высоту**;
|
||||
- высота определяется самой высокой кнопкой;
|
||||
- содержимое кнопок вертикально центрировано;
|
||||
- текст кнопки может переноситься по словам;
|
||||
- остальные кнопки не должны становиться выше/ниже друг друга;
|
||||
- весь ряд остаётся выровнен по левому краю.
|
||||
|
||||
Пример:
|
||||
|
||||
```text
|
||||
[Ведомости] [Дополнительные [Daily Reports] [КС-2] [КС-3] [КС-6а] [Платежи]
|
||||
соглашения]
|
||||
```
|
||||
|
||||
Это иллюстрация поведения, а не требование конкретной ширины.
|
||||
|
||||
### Важно
|
||||
|
||||
Не уменьшать шрифт до нечитабельного размера.
|
||||
|
||||
Не делать горизонтальный scroll ради сохранения однострочного текста.
|
||||
|
||||
Не переносить группу кнопок целиком на вторую строку.
|
||||
|
||||
---
|
||||
|
||||
## 5. Финансовый переключатель
|
||||
|
||||
Блок:
|
||||
|
||||
**Финансовые суммы [глаз]**
|
||||
|
||||
переместить отдельно от навигации по документам.
|
||||
|
||||
Согласно визуальной схеме пользователя, разместить его в области непосредственно перед блоком:
|
||||
|
||||
**План и выполнение**
|
||||
|
||||
Он не должен визуально смешиваться с навигационными кнопками.
|
||||
|
||||
Существующее поведение сохранить:
|
||||
|
||||
- суммы скрыты по умолчанию;
|
||||
- глаз показывает/скрывает суммы;
|
||||
- количественные показатели и проценты не скрываются.
|
||||
|
||||
---
|
||||
|
||||
## 6. Порядок верхней части
|
||||
|
||||
Итоговая логика должна быть примерно:
|
||||
|
||||
```text
|
||||
Проекты / Саудовская Аравия
|
||||
|
||||
Саудовская Аравия
|
||||
[Дневной отчёт] [Редактировать]
|
||||
|
||||
Договор | Заказчик | Валюта | Период | Статус
|
||||
|
||||
Ведомость проекта: Ведомость ОВ
|
||||
|
||||
[Ведомости] [Дополнительные соглашения] [Daily Reports] [КС-2] [КС-3] [КС-6а] [Платежи]
|
||||
|
||||
[Архивировать] [Удалить проект]
|
||||
|
||||
✓ Проверка плана: превышений нет
|
||||
|
||||
Финансовые суммы [глаз]
|
||||
|
||||
План и выполнение
|
||||
```
|
||||
|
||||
Это схема расположения, а не требование дословно повторить ASCII.
|
||||
|
||||
---
|
||||
|
||||
## 7. Что не менять
|
||||
|
||||
Не менять:
|
||||
|
||||
- маршруты;
|
||||
- бизнес-логику;
|
||||
- модели БД;
|
||||
- расчёты;
|
||||
- статусы;
|
||||
- документы;
|
||||
- импорт;
|
||||
- экспорт;
|
||||
- платежную логику;
|
||||
- существующее поведение eye-toggle.
|
||||
|
||||
Не делать новый дизайн всего приложения.
|
||||
|
||||
---
|
||||
|
||||
## 8. Browser-check
|
||||
|
||||
Обязательно проверить на реальном проекте.
|
||||
|
||||
Проверить минимум:
|
||||
|
||||
### Верхняя часть
|
||||
- заголовок проекта;
|
||||
- кнопки Дневной отчёт / Редактировать;
|
||||
- реквизиты;
|
||||
- ведомость проекта;
|
||||
- навигация;
|
||||
- архивирование/удаление.
|
||||
|
||||
### Навигация
|
||||
Проверить на текущей ширине окна:
|
||||
|
||||
- все 7 кнопок присутствуют;
|
||||
- весь ряд начинается слева;
|
||||
- горизонтального scroll нет;
|
||||
- сами кнопки не переходят на вторую строку;
|
||||
- текст внутри длинных кнопок при необходимости переносится;
|
||||
- все кнопки одинаковой высоты;
|
||||
- содержимое кнопок вертикально центрировано.
|
||||
|
||||
### Финансы
|
||||
- eye-toggle расположен отдельно;
|
||||
- работает как раньше;
|
||||
- не смешан с навигацией.
|
||||
|
||||
Проверить также обычный проект и текущий проект со сторнированными документами.
|
||||
|
||||
---
|
||||
|
||||
## 9. Тесты
|
||||
|
||||
Добавить автоматические layout-тесты только там, где это разумно.
|
||||
|
||||
Минимально проверить:
|
||||
|
||||
- наличие всех семи навигационных кнопок;
|
||||
- отсутствие `overflow-x`/scroll-контейнера у блока навигации;
|
||||
- сохранение существующих маршрутов;
|
||||
- сохранение eye-toggle.
|
||||
|
||||
Основной критерий приёмки — browser-check.
|
||||
|
||||
---
|
||||
|
||||
## 10. Результат
|
||||
|
||||
В отчёте указать:
|
||||
|
||||
- итоговую структуру верхней части;
|
||||
- как реализован ряд навигации без горизонтального scroll;
|
||||
- как реализован перенос текста внутри кнопок;
|
||||
- какие файлы изменены;
|
||||
- результаты тестов;
|
||||
- browser-check;
|
||||
- `git diff --check`;
|
||||
- deviations/open questions.
|
||||
|
||||
Временные Playwright-скрипты и screenshots не включать в production-код.
|
||||
|
||||
Commit/push автоматически не выполнять.
|
||||
@@ -0,0 +1,292 @@
|
||||
# Задача 023 — UI/UX cleanup V1
|
||||
|
||||
## Цель
|
||||
|
||||
Одним проходом закрыть накопившийся UI/UX-долг после завершения основного функционального контура.
|
||||
|
||||
Это не редизайн приложения. Сохраняем текущий Bootstrap 5 + Jinja UI и существующую логику. Исправляем конкретные неудобства, навигацию и пользовательские ошибки.
|
||||
|
||||
Для UI-задач обязательна browser-проверка после реализации.
|
||||
|
||||
---
|
||||
|
||||
# 1. Страница проекта — кнопка «Дневной отчёт»
|
||||
|
||||
Сейчас основное действие Daily Report расположено недостаточно заметно.
|
||||
|
||||
Нужно:
|
||||
|
||||
- перенести/расположить кнопку **«Дневной отчёт»** выше, рядом с блоком статуса проекта;
|
||||
- сделать её главным рабочим действием страницы проекта;
|
||||
- не менять URL и существующую функциональность создания отчёта.
|
||||
|
||||
Не делать большую кнопку на всю ширину.
|
||||
|
||||
---
|
||||
|
||||
# 2. Статус проекта
|
||||
|
||||
На странице проекта статус должен иметь визуальное различие в зависимости от текущего значения.
|
||||
|
||||
Использовать существующие Bootstrap-подходы (`badge`, contextual classes и т.п.).
|
||||
|
||||
Не менять значения статусов и бизнес-логику.
|
||||
|
||||
Цель — чтобы статус было видно с первого взгляда.
|
||||
|
||||
---
|
||||
|
||||
# 3. Финансовый переключатель «глаз»
|
||||
|
||||
Сейчас переключатель скрытия финансовых сумм находится в бизнес-навигации неудачно.
|
||||
|
||||
Нужно:
|
||||
|
||||
- вынести eye-toggle в отдельную понятную область интерфейса;
|
||||
- не смешивать его с действиями типа «Ведомости», «ДС», «КС-2», «КС-3», «Платежи»;
|
||||
- сохранить текущее поведение:
|
||||
- суммы скрыты по умолчанию;
|
||||
- глаз показывает/скрывает суммы;
|
||||
- количество, проценты и рабочая информация не скрываются;
|
||||
- состояние не сохраняется глобально.
|
||||
|
||||
Не превращать это в механизм безопасности — это только защита от случайного просмотра финансовых сумм.
|
||||
|
||||
Проверить страницы, где toggle уже используется:
|
||||
- Dashboard;
|
||||
- BOQ;
|
||||
- КС-2;
|
||||
- КС-3;
|
||||
- Платежи.
|
||||
|
||||
---
|
||||
|
||||
# 4. Документы проекта: «Ведомости» и «Дополнительные соглашения»
|
||||
|
||||
На странице проекта сейчас навигация по документам выглядит недостаточно логично.
|
||||
|
||||
Сделать две понятные точки входа рядом:
|
||||
|
||||
- **Ведомости**
|
||||
- **Дополнительные соглашения**
|
||||
|
||||
Не удалять кнопку/раздел ДС ради Ведомостей.
|
||||
|
||||
Сохранить существующие маршруты и функциональность.
|
||||
|
||||
---
|
||||
|
||||
# 5. Комплект документов
|
||||
|
||||
Кнопка **«Сформировать комплект»** сейчас визуально слишком крупная.
|
||||
|
||||
Сделать её обычной кнопкой нормального размера, соответствующей остальным действиям.
|
||||
|
||||
Не менять механизм формирования ZIP.
|
||||
|
||||
---
|
||||
|
||||
# 6. ДС — line-click
|
||||
|
||||
Строка дополнительного соглашения должна быть кликабельной целиком.
|
||||
|
||||
Ожидаемое поведение:
|
||||
|
||||
- клик по строке → страница просмотра ДС;
|
||||
- если внутри строки есть отдельные action-кнопки, их клики не должны срабатывать как переход строки;
|
||||
- поведение должно быть аналогично уже реализованной навигации строк в других списках.
|
||||
|
||||
Проверить как минимум:
|
||||
- клик по названию;
|
||||
- клик по пустой области строки;
|
||||
- клик по action-кнопке.
|
||||
|
||||
---
|
||||
|
||||
# 7. ДС — нормальное название ведомости
|
||||
|
||||
В выборе области применения ДС сейчас отображается техническое имя вроде:
|
||||
|
||||
`BOQ Import - Ведомость ОВ`
|
||||
|
||||
Техническое `BOQ Import` пользователю не нужно.
|
||||
|
||||
Нужно отображать нормальное пользовательское название ведомости.
|
||||
|
||||
Например:
|
||||
|
||||
`Основная ведомость — Ведомость объема работ и материалов`
|
||||
|
||||
Конкретный формат выбрать по существующей модели/данным так, чтобы:
|
||||
|
||||
- название было информативным;
|
||||
- технические внутренние названия не торчали наружу;
|
||||
- если пользовательское название ведомости уже существует — использовать его;
|
||||
- не ломать выбор области применения.
|
||||
|
||||
---
|
||||
|
||||
# 8. Импорт ведомости — реквизиты BoqDocument
|
||||
|
||||
При импорте Excel ведомости пользователь должен иметь возможность задать реквизиты самой ведомости.
|
||||
|
||||
Минимум:
|
||||
|
||||
- **Название ведомости**
|
||||
- **Номер**
|
||||
- **Дата**
|
||||
- **Договор**
|
||||
|
||||
Эти данные должны сохраняться у `BoqDocument`.
|
||||
|
||||
## Важно
|
||||
|
||||
Сначала изучить текущую модель `BoqDocument` и существующий importer/import flow.
|
||||
|
||||
Не создавать параллельную сущность только ради UI.
|
||||
|
||||
Если для хранения реквизитов нужны миграция и поля модели — добавить их штатно.
|
||||
|
||||
Импорт должен по-прежнему:
|
||||
- загружать Excel;
|
||||
- выбирать лист;
|
||||
- настраивать параметры импорта;
|
||||
- показывать preview;
|
||||
- подтверждать импорт транзакционно.
|
||||
|
||||
Реквизиты ведомости не должны ломать существующий import flow.
|
||||
|
||||
Если для «Договор» логичнее использовать существующий реквизит проекта, не дублировать данные без необходимости. Но пользователь должен иметь возможность задать/сохранить требуемый реквизит ведомости в соответствии с текущей архитектурой.
|
||||
|
||||
---
|
||||
|
||||
# 9. Удаление проекта с зависимыми данными — вместо JSON
|
||||
|
||||
Сейчас при попытке удалить проект с зависимыми данными пользователь получает голый API JSON:
|
||||
|
||||
`{"detail":"Cannot delete project with related data"}`
|
||||
|
||||
Это нужно заменить нормальным пользовательским интерфейсом.
|
||||
|
||||
## Требование
|
||||
|
||||
При попытке удаления проекта, если физическое удаление запрещено существующими бизнес-правилами:
|
||||
|
||||
- не показывать пользователю JSON;
|
||||
- показать Bootstrap modal/alert;
|
||||
- объяснить причину;
|
||||
- предложить архивировать проект.
|
||||
|
||||
Пример текста:
|
||||
|
||||
**Проект нельзя удалить**
|
||||
|
||||
В проекте есть связанные данные: ведомости, отчёты или документы. Удаление невозможно, чтобы не нарушить историю проекта.
|
||||
|
||||
**Рекомендуется архивировать проект.**
|
||||
|
||||
Кнопки:
|
||||
- Отмена
|
||||
- Архивировать проект
|
||||
|
||||
## Важно
|
||||
|
||||
Не менять существующее бизнес-правило удаления:
|
||||
|
||||
- физически удалять проект можно только если это разрешено текущей логикой;
|
||||
- при наличии зависимых/закрытых данных проект должен архивироваться, а не удаляться.
|
||||
|
||||
Архивация должна использовать существующий механизм, если он уже реализован.
|
||||
|
||||
Не возвращать JSON пользователю через обычный UI-сценарий.
|
||||
|
||||
Если API endpoint используется также для AJAX/API-клиентов, не ломать API-контракт без необходимости. Для обычного браузерного действия обработать ошибку на уровне UI.
|
||||
|
||||
---
|
||||
|
||||
# 10. Что НЕ менять
|
||||
|
||||
Не менять:
|
||||
|
||||
- расчёты Dashboard;
|
||||
- Daily Reports;
|
||||
- KS-2/KS-3;
|
||||
- Payments;
|
||||
- сторнирование;
|
||||
- импортную бизнес-логику кроме добавления реквизитов BoqDocument;
|
||||
- экспорт;
|
||||
- DB-структуры, не связанные непосредственно с реквизитами BoqDocument;
|
||||
- текущую цветовую/Bootstrap-систему без необходимости.
|
||||
|
||||
Не делать полноценный визуальный редизайн.
|
||||
|
||||
---
|
||||
|
||||
# 11. Browser-check
|
||||
|
||||
После реализации обязательно проверить приложение в браузере на реальном проекте.
|
||||
|
||||
Минимум:
|
||||
|
||||
## Проект
|
||||
- кнопка «Дневной отчёт» находится в ожидаемой верхней области;
|
||||
- статус визуально различим;
|
||||
- глаз работает;
|
||||
- «Ведомости» и «Дополнительные соглашения» доступны рядом;
|
||||
- «Сформировать комплект» имеет нормальный размер;
|
||||
- удаление проекта с зависимыми данными показывает нормальное сообщение/modal и не отдаёт голый JSON.
|
||||
|
||||
## ДС
|
||||
- строка ДС кликабельна;
|
||||
- action-кнопки не ломают row-click;
|
||||
- в выборе области применения отображается название ведомости, а не `BOQ Import`;
|
||||
- создание ДС продолжает работать.
|
||||
|
||||
## Ведомость
|
||||
- импорт позволяет задать название/номер/дату/договор;
|
||||
- реквизиты сохраняются;
|
||||
- после импорта ведомость отображается с нормальным названием;
|
||||
- существующий preview/import не сломан.
|
||||
|
||||
## Финансы
|
||||
Проверить eye-toggle на Dashboard, BOQ, КС-2, КС-3 и Payments.
|
||||
|
||||
---
|
||||
|
||||
# 12. Тесты
|
||||
|
||||
Добавить/обновить автоматические тесты там, где это разумно.
|
||||
|
||||
Минимально проверить:
|
||||
|
||||
1. Row-click ДС ведёт на страницу ДС.
|
||||
2. Action-кнопки строки ДС не вызывают row-click.
|
||||
3. Название ведомости используется в выборе области применения ДС.
|
||||
4. Реквизиты BoqDocument сохраняются при импорте.
|
||||
5. Удаление проекта с зависимыми данными обрабатывается браузерным UI-сценарием, а не голым JSON.
|
||||
6. Существующий import flow продолжает работать.
|
||||
7. Существующий финансовый eye-toggle не сломан.
|
||||
8. Существующие тесты проекта продолжают проходить.
|
||||
|
||||
Для чисто визуальных CSS-проверок не создавать искусственные тесты ради покрытия — обязательна browser-проверка.
|
||||
|
||||
---
|
||||
|
||||
# 13. Результат
|
||||
|
||||
В конце предоставить:
|
||||
|
||||
- краткий отчёт;
|
||||
- список изменённых файлов;
|
||||
- какие UI-проблемы исправлены;
|
||||
- какие поля добавлены в `BoqDocument`;
|
||||
- описание обработки ошибки удаления проекта;
|
||||
- результаты автоматических тестов;
|
||||
- результат browser-check;
|
||||
- `git diff --check`;
|
||||
- screenshots/артефакты browser-check, если они создавались;
|
||||
- deviations/open questions.
|
||||
|
||||
Временные Playwright-скрипты и screenshots не включать в production-код.
|
||||
|
||||
Commit/push автоматически не выполнять.
|
||||
@@ -0,0 +1,443 @@
|
||||
"""Regression tests for task 023: UI/UX cleanup V1."""
|
||||
import shutil
|
||||
from datetime import date
|
||||
from decimal import Decimal
|
||||
|
||||
from fastapi.testclient import TestClient
|
||||
from sqlalchemy import create_engine
|
||||
from sqlalchemy.orm import sessionmaker
|
||||
|
||||
from app.database.database import Base, DATABASE_PATH
|
||||
from app.importer.excel_importer import import_excel_data
|
||||
from app.main import app
|
||||
from app.models.project import Project
|
||||
from app.models.boq import BoqDocument, System, Section, WorkItem
|
||||
from app.models.agreement import Agreement
|
||||
from app.models.daily_report import DailyReport, DailyReportItem
|
||||
from app.routers import (
|
||||
projects as project_router,
|
||||
boq as boq_router,
|
||||
agreements as agreement_router,
|
||||
daily_reports,
|
||||
ks2 as ks2_router,
|
||||
ks3 as ks3_router,
|
||||
payments as payments_router,
|
||||
)
|
||||
|
||||
|
||||
def _make_session(tmp_path):
|
||||
db_path = tmp_path / "t023-copy.db"
|
||||
shutil.copy2(DATABASE_PATH, db_path)
|
||||
engine = create_engine(f"sqlite:///{db_path.as_posix()}", connect_args={"check_same_thread": False})
|
||||
Base.metadata.create_all(bind=engine)
|
||||
return engine, sessionmaker(bind=engine, autoflush=False, autocommit=False)
|
||||
|
||||
|
||||
def _override(*deps):
|
||||
# Use the first dep's session factory via closure over module-level Session
|
||||
pass
|
||||
|
||||
|
||||
def _bind_session(Session, *deps):
|
||||
def override_db():
|
||||
s = Session()
|
||||
try:
|
||||
yield s
|
||||
finally:
|
||||
s.close()
|
||||
for dep in deps:
|
||||
app.dependency_overrides[dep] = override_db
|
||||
|
||||
|
||||
def _clear(*deps):
|
||||
for dep in deps:
|
||||
app.dependency_overrides.pop(dep, None)
|
||||
|
||||
|
||||
ALL_DEPS = (
|
||||
project_router.get_db,
|
||||
boq_router.get_db,
|
||||
agreement_router.get_db,
|
||||
daily_reports.get_db,
|
||||
ks2_router.get_db,
|
||||
ks3_router.get_db,
|
||||
payments_router.get_db,
|
||||
)
|
||||
|
||||
|
||||
def _seed_project(Session):
|
||||
with Session() as s:
|
||||
p = Project(name="UI cleanup", status="active", contract_number="D-1")
|
||||
s.add(p)
|
||||
s.flush()
|
||||
doc = BoqDocument(project_id=p.id, name="BOQ Import - Ведомость ОВ")
|
||||
s.add(doc)
|
||||
s.flush()
|
||||
system = System(project_id=p.id, name="Система", sort_order=1)
|
||||
s.add(system)
|
||||
s.flush()
|
||||
section = Section(system_id=system.id, name="Раздел", sort_order=1)
|
||||
s.add(section)
|
||||
s.flush()
|
||||
item = WorkItem(
|
||||
project_id=p.id, boq_document_id=doc.id, system_id=system.id, section_id=section.id,
|
||||
source_number="1", name="Позиция", unit="шт", quantity=10,
|
||||
unit_price=Decimal("100"), amount=Decimal("1000"),
|
||||
)
|
||||
s.add(item)
|
||||
s.commit()
|
||||
return p.id, doc.id, item.id
|
||||
|
||||
|
||||
# --- 1/2. Agreements row-click markup ---
|
||||
|
||||
def test_agreement_list_rows_are_clickable(tmp_path):
|
||||
engine, Session = _make_session(tmp_path)
|
||||
_bind_session(Session, *ALL_DEPS)
|
||||
try:
|
||||
pid, doc_id, _ = _seed_project(Session)
|
||||
with Session() as s:
|
||||
agr = Agreement(
|
||||
project_id=pid, number="A-1", date=date(2026, 1, 1),
|
||||
title="ДС", status="draft",
|
||||
)
|
||||
s.add(agr)
|
||||
s.commit()
|
||||
agr_id = agr.id
|
||||
with TestClient(app) as client:
|
||||
resp = client.get(f"/projects/{pid}/agreements")
|
||||
assert resp.status_code == 200
|
||||
html = resp.text
|
||||
assert f'data-url="/projects/{pid}/agreements/{agr_id}"' in html
|
||||
assert "clickable-row" in html
|
||||
# Action button must not fall through to row navigation
|
||||
assert "e.target.closest('a, button, form, input, select, textarea')" in html
|
||||
assert f'href="/projects/{pid}/agreements/{agr_id}"' in html
|
||||
finally:
|
||||
_clear(*ALL_DEPS)
|
||||
engine.dispose()
|
||||
|
||||
|
||||
# --- 3. BOQ display name in agreement scope selector ---
|
||||
|
||||
def test_agreement_scope_shows_display_name_not_technical(tmp_path):
|
||||
engine, Session = _make_session(tmp_path)
|
||||
_bind_session(Session, *ALL_DEPS)
|
||||
try:
|
||||
pid, doc_id, _ = _seed_project(Session)
|
||||
with TestClient(app) as client:
|
||||
resp = client.get(f"/projects/{pid}/agreements/new")
|
||||
assert resp.status_code == 200
|
||||
html = resp.text
|
||||
assert "Ведомость ОВ" in html
|
||||
assert "BOQ Import" not in html
|
||||
finally:
|
||||
_clear(*ALL_DEPS)
|
||||
engine.dispose()
|
||||
|
||||
|
||||
def test_boq_display_name_property():
|
||||
doc = BoqDocument(id=1, project_id=1, name="BOQ Import - Ведомость ОВ")
|
||||
assert doc.display_name == "Ведомость ОВ"
|
||||
doc2 = BoqDocument(id=2, project_id=1, name="Импорт ведомости — Лист 1")
|
||||
assert doc2.display_name == "Лист 1"
|
||||
doc3 = BoqDocument(id=3, project_id=1, name="Основная ведомость")
|
||||
assert doc3.display_name == "Основная ведомость"
|
||||
|
||||
|
||||
# --- 4. Import requisites ---
|
||||
|
||||
def test_import_excel_saves_document_requisites(tmp_path):
|
||||
import openpyxl
|
||||
path = tmp_path / "boq.xlsx"
|
||||
wb = openpyxl.Workbook()
|
||||
ws = wb.active
|
||||
ws.title = "Ведомость ОВ"
|
||||
for _ in range(4):
|
||||
ws.append([None])
|
||||
ws.append(["№", "Наименование", "Модель", "Производитель", "Ед", "Кол-во", "Цена", "Сумма"])
|
||||
ws.append([1, "Работа", None, None, "шт", 2, 10, 20])
|
||||
wb.save(path)
|
||||
|
||||
engine = create_engine("sqlite:///:memory:")
|
||||
Base.metadata.create_all(engine)
|
||||
session = sessionmaker(bind=engine)()
|
||||
project = Project(name="Import requisites")
|
||||
session.add(project)
|
||||
session.commit()
|
||||
|
||||
result = import_excel_data(
|
||||
session, str(path), "Ведомость ОВ", 5, 6, project.id,
|
||||
document_name="Основная ведомость",
|
||||
document_number="БО-01",
|
||||
document_date=date(2026, 3, 1),
|
||||
contract="Договор 42",
|
||||
)
|
||||
doc = session.get(BoqDocument, result["document_id"])
|
||||
assert doc.name == "Основная ведомость"
|
||||
assert doc.document_number == "БО-01"
|
||||
assert doc.document_date == date(2026, 3, 1)
|
||||
assert doc.contract == "Договор 42"
|
||||
assert doc.display_name == "Основная ведомость"
|
||||
session.close()
|
||||
|
||||
|
||||
def test_import_preview_exposes_requisites_fields(tmp_path):
|
||||
import openpyxl
|
||||
path = tmp_path / "boq.xlsx"
|
||||
wb = openpyxl.Workbook()
|
||||
ws = wb.active
|
||||
ws.title = "Лист1"
|
||||
for _ in range(4):
|
||||
ws.append([None])
|
||||
ws.append(["№", "Наименование", "Модель", "Производитель", "Ед", "Кол-во", "Цена", "Сумма"])
|
||||
ws.append([1, "Работа", None, None, "шт", 1, 5, 5])
|
||||
upload_dir = tmp_path / "uploads"
|
||||
upload_dir.mkdir()
|
||||
saved = upload_dir / "boq.xlsx"
|
||||
wb.save(saved)
|
||||
|
||||
engine, Session = _make_session(tmp_path)
|
||||
_bind_session(Session, boq_router.get_db, project_router.get_db)
|
||||
try:
|
||||
with Session() as s:
|
||||
p = Project(name="Import UI", contract_number="PC-9")
|
||||
s.add(p)
|
||||
s.commit()
|
||||
pid = p.id
|
||||
# Point UPLOAD_DIR at temp
|
||||
import app.routers.boq as boq_mod
|
||||
old_upload = boq_mod.UPLOAD_DIR
|
||||
boq_mod.UPLOAD_DIR = upload_dir
|
||||
try:
|
||||
with TestClient(app) as client:
|
||||
resp = client.post(f"/boq/{pid}/import/preview", data={
|
||||
"filename": "boq.xlsx",
|
||||
"sheet_name": "Лист1",
|
||||
"header_row": "5",
|
||||
"start_row": "6",
|
||||
})
|
||||
assert resp.status_code == 200
|
||||
html = resp.text
|
||||
assert 'name="document_name"' in html
|
||||
assert 'name="document_number"' in html
|
||||
assert 'name="document_date"' in html
|
||||
assert 'name="contract"' in html
|
||||
assert "Реквизиты ведомости" in html
|
||||
# Default name comes from sheet
|
||||
assert "Лист1" in html
|
||||
finally:
|
||||
boq_mod.UPLOAD_DIR = old_upload
|
||||
finally:
|
||||
_clear(boq_router.get_db, project_router.get_db)
|
||||
engine.dispose()
|
||||
|
||||
|
||||
# --- 5. Delete project blocked → UI modal, not raw JSON to browser ---
|
||||
|
||||
def test_delete_project_blocked_keeps_api_json_and_page_has_modal(tmp_path):
|
||||
engine, Session = _make_session(tmp_path)
|
||||
_bind_session(Session, *ALL_DEPS)
|
||||
try:
|
||||
with Session() as s:
|
||||
p = Project(name="Has history")
|
||||
s.add(p)
|
||||
s.flush()
|
||||
doc = BoqDocument(project_id=p.id, name="BOQ")
|
||||
s.add(doc)
|
||||
s.flush()
|
||||
item = WorkItem(project_id=p.id, boq_document_id=doc.id, name="I", quantity=1)
|
||||
s.add(item)
|
||||
s.flush()
|
||||
dr = DailyReport(project_id=p.id, report_date=date(2026, 1, 1))
|
||||
s.add(dr)
|
||||
s.flush()
|
||||
s.add(DailyReportItem(daily_report_id=dr.id, work_item_id=item.id, completed_quantity=1))
|
||||
s.commit()
|
||||
pid = p.id
|
||||
|
||||
with TestClient(app) as client:
|
||||
# API contract preserved for non-browser clients
|
||||
resp = client.post(f"/projects/{pid}/delete", follow_redirects=False)
|
||||
assert resp.status_code == 400
|
||||
assert resp.json()["detail"]
|
||||
|
||||
# Browser UI: page contains modal + JS handler, not a bare form post
|
||||
page = client.get(f"/projects/{pid}")
|
||||
html = page.text
|
||||
assert 'id="deleteBlockedModal"' in html
|
||||
assert "Проект нельзя удалить" in html
|
||||
assert "Рекомендуется архивировать проект" in html
|
||||
assert "Архивировать проект" in html
|
||||
assert 'id="delete-project-form"' in html
|
||||
assert "bootstrap.Modal" in html
|
||||
# Status badge is visually distinct
|
||||
assert "text-bg-success" in html # active
|
||||
# Daily report button near top / status block
|
||||
assert "Дневной отчёт" in html
|
||||
# Package button is not full-width
|
||||
assert "Сформировать комплект" in html
|
||||
assert "btn-primary w-100" not in html or "Сформировать комплект" not in html.split("btn-primary w-100")[0][-50:]
|
||||
# Eye toggle is separated from business nav
|
||||
assert "Финансовые суммы" in html
|
||||
# BOQ and DS are adjacent entry points
|
||||
assert "Ведомости" in html and "Дополнительные соглашения" in html
|
||||
finally:
|
||||
_clear(*ALL_DEPS)
|
||||
engine.dispose()
|
||||
|
||||
|
||||
def test_delete_project_without_related_data_still_works(tmp_path):
|
||||
engine, Session = _make_session(tmp_path)
|
||||
_bind_session(Session, *ALL_DEPS)
|
||||
try:
|
||||
with Session() as s:
|
||||
p = Project(name="Clean")
|
||||
s.add(p)
|
||||
s.commit()
|
||||
pid = p.id
|
||||
with TestClient(app) as client:
|
||||
resp = client.post(f"/projects/{pid}/delete", follow_redirects=False)
|
||||
assert resp.status_code == 303
|
||||
with Session() as s:
|
||||
assert s.get(Project, pid) is None
|
||||
finally:
|
||||
_clear(*ALL_DEPS)
|
||||
engine.dispose()
|
||||
|
||||
|
||||
# --- 6. Existing import flow still works ---
|
||||
|
||||
def test_import_confirm_flow_still_works(tmp_path):
|
||||
import openpyxl
|
||||
path = tmp_path / "boq.xlsx"
|
||||
wb = openpyxl.Workbook()
|
||||
ws = wb.active
|
||||
ws.title = "Ведомость"
|
||||
for _ in range(4):
|
||||
ws.append([None])
|
||||
ws.append(["№", "Наименование", "Модель", "Производитель", "Ед", "Кол-во", "Цена", "Сумма"])
|
||||
ws.append([1, "Работа", None, None, "шт", 1, 5, 5])
|
||||
upload_dir = tmp_path / "uploads"
|
||||
upload_dir.mkdir()
|
||||
wb.save(upload_dir / "boq.xlsx")
|
||||
|
||||
engine, Session = _make_session(tmp_path)
|
||||
_bind_session(Session, boq_router.get_db, project_router.get_db)
|
||||
try:
|
||||
with Session() as s:
|
||||
p = Project(name="Import flow")
|
||||
s.add(p)
|
||||
s.commit()
|
||||
pid = p.id
|
||||
import app.routers.boq as boq_mod
|
||||
old_upload = boq_mod.UPLOAD_DIR
|
||||
boq_mod.UPLOAD_DIR = upload_dir
|
||||
try:
|
||||
with TestClient(app) as client:
|
||||
resp = client.post(f"/boq/{pid}/import/confirm", data={
|
||||
"filename": "boq.xlsx",
|
||||
"sheet_name": "Ведомость",
|
||||
"header_row": "5",
|
||||
"start_row": "6",
|
||||
"document_name": "Моя ведомость",
|
||||
"document_number": "12",
|
||||
"document_date": "2026-02-02",
|
||||
"contract": "К-1",
|
||||
})
|
||||
assert resp.status_code == 200
|
||||
assert "Импорт завершен" in resp.text
|
||||
assert "Моя ведомость" in resp.text
|
||||
finally:
|
||||
boq_mod.UPLOAD_DIR = old_upload
|
||||
with Session() as s:
|
||||
doc = s.query(BoqDocument).filter_by(project_id=pid).one()
|
||||
assert doc.name == "Моя ведомость"
|
||||
assert doc.document_number == "12"
|
||||
assert doc.document_date == date(2026, 2, 2)
|
||||
assert doc.contract == "К-1"
|
||||
items = s.query(WorkItem).filter_by(boq_document_id=doc.id).all()
|
||||
assert len(items) == 1
|
||||
finally:
|
||||
_clear(boq_router.get_db, project_router.get_db)
|
||||
engine.dispose()
|
||||
|
||||
|
||||
# --- 7. Eye toggle not broken ---
|
||||
|
||||
def test_eye_toggle_present_on_project_and_base_pages(tmp_path):
|
||||
engine, Session = _make_session(tmp_path)
|
||||
_bind_session(Session, *ALL_DEPS)
|
||||
try:
|
||||
pid, doc_id, _ = _seed_project(Session)
|
||||
with TestClient(app) as client:
|
||||
project_page = client.get(f"/projects/{pid}")
|
||||
assert "id=\"toggleMoney\"" in project_page.text
|
||||
assert "money-hidden" in project_page.text
|
||||
assert "classList.toggle('money-hidden')" in project_page.text
|
||||
|
||||
boq_page = client.get(f"/boq/{pid}/documents/{doc_id}")
|
||||
assert "id=\"toggleMoney\"" in boq_page.text
|
||||
assert "money-hidden" in boq_page.text
|
||||
|
||||
# KS-2 / KS-3 / Payments pages extend base.html
|
||||
for path in (f"/projects/{pid}/ks2", f"/projects/{pid}/ks3", f"/projects/{pid}/payments"):
|
||||
page = client.get(path)
|
||||
assert page.status_code == 200
|
||||
assert "id=\"toggleMoney\"" in page.text
|
||||
assert "money-hidden" in page.text
|
||||
finally:
|
||||
_clear(*ALL_DEPS)
|
||||
engine.dispose()
|
||||
|
||||
|
||||
# --- Status badge + package button + requisites shown ---
|
||||
|
||||
def test_project_page_status_badge_and_package_button(tmp_path):
|
||||
engine, Session = _make_session(tmp_path)
|
||||
_bind_session(Session, *ALL_DEPS)
|
||||
try:
|
||||
with Session() as s:
|
||||
p = Project(name="Status", status="on_hold")
|
||||
s.add(p)
|
||||
s.commit()
|
||||
pid = p.id
|
||||
with TestClient(app) as client:
|
||||
html = client.get(f"/projects/{pid}").text
|
||||
assert "text-bg-warning" in html # on_hold
|
||||
assert "Приостановлен" in html
|
||||
# Package button is normal size (no w-100 on that button)
|
||||
import re
|
||||
match = re.search(r'<button type="submit" class="([^"]*)">Сформировать комплект</button>', html)
|
||||
assert match
|
||||
assert "w-100" not in match.group(1)
|
||||
finally:
|
||||
_clear(*ALL_DEPS)
|
||||
engine.dispose()
|
||||
|
||||
|
||||
def test_boq_document_shows_requisites(tmp_path):
|
||||
engine, Session = _make_session(tmp_path)
|
||||
_bind_session(Session, *ALL_DEPS)
|
||||
try:
|
||||
with Session() as s:
|
||||
p = Project(name="Req display")
|
||||
s.add(p)
|
||||
s.flush()
|
||||
doc = BoqDocument(
|
||||
project_id=p.id, name="Основная ведомость",
|
||||
document_number="БО-7", document_date=date(2026, 5, 5),
|
||||
contract="Договор 1",
|
||||
)
|
||||
s.add(doc)
|
||||
s.commit()
|
||||
pid, did = p.id, doc.id
|
||||
with TestClient(app) as client:
|
||||
html = client.get(f"/boq/{pid}/documents/{did}").text
|
||||
assert "Основная ведомость" in html
|
||||
assert "БО-7" in html
|
||||
assert "Договор 1" in html
|
||||
assert "05.05.2026" in html
|
||||
finally:
|
||||
_clear(*ALL_DEPS)
|
||||
engine.dispose()
|
||||
@@ -0,0 +1,106 @@
|
||||
"""Layout regression tests for task 023-FIX2: project header + payments actions."""
|
||||
import re
|
||||
import shutil
|
||||
|
||||
from fastapi.testclient import TestClient
|
||||
from sqlalchemy import create_engine
|
||||
from sqlalchemy.orm import sessionmaker
|
||||
|
||||
from app.database.database import Base, DATABASE_PATH
|
||||
from app.main import app
|
||||
from app.models.project import Project
|
||||
from app.models.payment import Payment
|
||||
from app.routers import (
|
||||
projects as project_router,
|
||||
payments as payments_router,
|
||||
boq as boq_router,
|
||||
ks2 as ks2_router,
|
||||
ks3 as ks3_router,
|
||||
)
|
||||
|
||||
|
||||
def _make_session(tmp_path):
|
||||
db_path = tmp_path / "t023fix2.db"
|
||||
shutil.copy2(DATABASE_PATH, db_path)
|
||||
engine = create_engine(f"sqlite:///{db_path.as_posix()}", connect_args={"check_same_thread": False})
|
||||
Base.metadata.create_all(bind=engine)
|
||||
return engine, sessionmaker(bind=engine, autoflush=False, autocommit=False)
|
||||
|
||||
|
||||
DEPS = (
|
||||
project_router.get_db,
|
||||
payments_router.get_db,
|
||||
boq_router.get_db,
|
||||
ks2_router.get_db,
|
||||
ks3_router.get_db,
|
||||
)
|
||||
|
||||
|
||||
def _bind(Session):
|
||||
def override_db():
|
||||
s = Session()
|
||||
try:
|
||||
yield s
|
||||
finally:
|
||||
s.close()
|
||||
for dep in DEPS:
|
||||
app.dependency_overrides[dep] = override_db
|
||||
|
||||
|
||||
def _clear():
|
||||
for dep in DEPS:
|
||||
app.dependency_overrides.pop(dep, None)
|
||||
|
||||
|
||||
def test_project_header_requisites_are_separate_blocks(tmp_path):
|
||||
engine, Session = _make_session(tmp_path)
|
||||
_bind(Session)
|
||||
try:
|
||||
with Session() as s:
|
||||
p = Project(name="Header FIX2", contract_number="D-1", customer="Cust", status="active")
|
||||
s.add(p)
|
||||
s.commit()
|
||||
pid = p.id
|
||||
with TestClient(app) as client:
|
||||
html = client.get(f"/projects/{pid}").text
|
||||
# Each requisite is its own labeled block, not one inline string
|
||||
for label in ("Договор", "Заказчик", "Валюта", "Период", "Статус"):
|
||||
assert f'class="text-muted small mb-1">{label}</div>' in html
|
||||
# Bootstrap row with gaps on requisites container
|
||||
assert re.search(r'class="row g-3 g-md-4', html)
|
||||
# Top row still has name + actions
|
||||
assert "Дневной отчёт" in html and "Редактировать" in html
|
||||
finally:
|
||||
_clear()
|
||||
engine.dispose()
|
||||
|
||||
|
||||
def test_payments_actions_are_nowrap_inline(tmp_path):
|
||||
from datetime import date
|
||||
from decimal import Decimal
|
||||
engine, Session = _make_session(tmp_path)
|
||||
_bind(Session)
|
||||
try:
|
||||
with Session() as s:
|
||||
p = Project(name="Pay FIX2")
|
||||
s.add(p)
|
||||
s.flush()
|
||||
s.add(Payment(project_id=p.id, date=date(2026, 1, 1), amount=Decimal("10"),
|
||||
currency="RUB", status="cancelled"))
|
||||
s.commit()
|
||||
pid = p.id
|
||||
with TestClient(app) as client:
|
||||
html = client.get(f"/projects/{pid}/payments").text
|
||||
# Actions cell keeps all three actions on one line
|
||||
assert "payments-actions" in html
|
||||
assert "text-nowrap" in html
|
||||
assert "d-inline-flex" in html
|
||||
# Column width reserved
|
||||
assert re.search(r'<col style="width: 17rem">', html)
|
||||
# Three actions + storno badge + row-click preserved
|
||||
assert "Просмотр" in html and "Редактировать" in html and "Удалить" in html
|
||||
assert "Сторнирован" in html
|
||||
assert "clickable-row" in html
|
||||
finally:
|
||||
_clear()
|
||||
engine.dispose()
|
||||
@@ -0,0 +1,146 @@
|
||||
"""Layout tests for task 023-FIX3: project header composition + doc nav row."""
|
||||
import re
|
||||
import shutil
|
||||
|
||||
from fastapi.testclient import TestClient
|
||||
from sqlalchemy import create_engine
|
||||
from sqlalchemy.orm import sessionmaker
|
||||
|
||||
from app.database.database import Base, DATABASE_PATH
|
||||
from app.main import app
|
||||
from app.models.project import Project
|
||||
from app.models.boq import BoqDocument
|
||||
from app.routers import (
|
||||
projects as project_router,
|
||||
boq as boq_router,
|
||||
agreements as agreement_router,
|
||||
daily_reports,
|
||||
ks2 as ks2_router,
|
||||
ks3 as ks3_router,
|
||||
payments as payments_router,
|
||||
)
|
||||
|
||||
|
||||
def _make_session(tmp_path):
|
||||
db_path = tmp_path / "t023fix3.db"
|
||||
shutil.copy2(DATABASE_PATH, db_path)
|
||||
engine = create_engine(f"sqlite:///{db_path.as_posix()}", connect_args={"check_same_thread": False})
|
||||
Base.metadata.create_all(bind=engine)
|
||||
return engine, sessionmaker(bind=engine, autoflush=False, autocommit=False)
|
||||
|
||||
|
||||
DEPS = (
|
||||
project_router.get_db,
|
||||
boq_router.get_db,
|
||||
agreement_router.get_db,
|
||||
daily_reports.get_db,
|
||||
ks2_router.get_db,
|
||||
ks3_router.get_db,
|
||||
payments_router.get_db,
|
||||
)
|
||||
|
||||
|
||||
def _bind(Session):
|
||||
def override_db():
|
||||
s = Session()
|
||||
try:
|
||||
yield s
|
||||
finally:
|
||||
s.close()
|
||||
for dep in DEPS:
|
||||
app.dependency_overrides[dep] = override_db
|
||||
|
||||
|
||||
def _clear():
|
||||
for dep in DEPS:
|
||||
app.dependency_overrides.pop(dep, None)
|
||||
|
||||
|
||||
def _seed(Session):
|
||||
with Session() as s:
|
||||
p = Project(name="FIX3", status="active")
|
||||
s.add(p)
|
||||
s.flush()
|
||||
s.add(BoqDocument(project_id=p.id, name="Ведомость ОВ"))
|
||||
s.commit()
|
||||
return p.id
|
||||
|
||||
|
||||
NAV_HREFS = [
|
||||
"/boq/{pid}",
|
||||
"/projects/{pid}/agreements",
|
||||
"/projects/{pid}/daily-reports",
|
||||
"/projects/{pid}/ks2",
|
||||
"/projects/{pid}/ks3",
|
||||
"/projects/{pid}/ks6a",
|
||||
"/projects/{pid}/payments",
|
||||
]
|
||||
|
||||
|
||||
def test_doc_nav_has_all_seven_buttons_in_one_row(tmp_path):
|
||||
engine, Session = _make_session(tmp_path)
|
||||
_bind(Session)
|
||||
try:
|
||||
pid = _seed(Session)
|
||||
with TestClient(app) as client:
|
||||
html = client.get(f"/projects/{pid}").text
|
||||
nav = re.search(r'<nav class="doc-nav[^"]*"[^>]*>(.*?)</nav>', html, re.S)
|
||||
assert nav, "doc-nav block missing"
|
||||
block = nav.group(1)
|
||||
for href in NAV_HREFS:
|
||||
assert f'href="{href.format(pid=pid)}"' in block, href
|
||||
# Exactly 7 nav buttons in the block
|
||||
assert block.count('class="btn btn-outline-primary"') == 7
|
||||
finally:
|
||||
_clear()
|
||||
engine.dispose()
|
||||
|
||||
|
||||
def test_doc_nav_has_no_horizontal_scroll_wrapper(tmp_path):
|
||||
engine, Session = _make_session(tmp_path)
|
||||
_bind(Session)
|
||||
try:
|
||||
pid = _seed(Session)
|
||||
with TestClient(app) as client:
|
||||
html = client.get(f"/projects/{pid}").text
|
||||
nav = re.search(r'<nav class="doc-nav([^"]*)"', html)
|
||||
assert nav
|
||||
classes = nav.group(1)
|
||||
assert "overflow" not in classes
|
||||
assert "table-responsive" not in classes
|
||||
# CSS: nowrap flex, no overflow-x
|
||||
assert ".doc-nav" in html
|
||||
assert "flex-wrap: nowrap" in html
|
||||
assert "overflow-x" not in html
|
||||
finally:
|
||||
_clear()
|
||||
engine.dispose()
|
||||
|
||||
|
||||
def test_header_order_and_eye_toggle_separate(tmp_path):
|
||||
engine, Session = _make_session(tmp_path)
|
||||
_bind(Session)
|
||||
try:
|
||||
pid = _seed(Session)
|
||||
with TestClient(app) as client:
|
||||
html = client.get(f"/projects/{pid}").text
|
||||
# Actions under title, not in a justify-content-between top row
|
||||
assert "Дневной отчёт" in html
|
||||
assert "Редактировать" in html
|
||||
# Requisites remain separate blocks
|
||||
for label in ("Договор", "Заказчик", "Валюта", "Период", "Статус"):
|
||||
assert f'class="text-muted small mb-1">{label}</div>' in html
|
||||
# BOQ line
|
||||
assert "Ведомость проекта:" in html
|
||||
# Eye toggle is outside doc-nav and before План и выполнение
|
||||
nav_end = html.find("</nav>")
|
||||
plan_pos = html.find("План и выполнение")
|
||||
eye_pos = html.find('id="toggleMoney"')
|
||||
assert 0 < nav_end < eye_pos < plan_pos
|
||||
assert "Финансовые суммы" in html
|
||||
# Archive / delete still present
|
||||
assert "Архивировать" in html or "Проект архивирован" in html
|
||||
assert "delete-project-form" in html or "Проект архивирован" in html
|
||||
finally:
|
||||
_clear()
|
||||
engine.dispose()
|
||||
@@ -0,0 +1,372 @@
|
||||
"""Regression tests for task 023-FIX: UI/UX follow-up after visual review."""
|
||||
import re
|
||||
import shutil
|
||||
from datetime import date
|
||||
from decimal import Decimal
|
||||
|
||||
from fastapi.testclient import TestClient
|
||||
from sqlalchemy import create_engine
|
||||
from sqlalchemy.orm import sessionmaker
|
||||
|
||||
from app.database.database import Base, DATABASE_PATH
|
||||
from app.main import app
|
||||
from app.models.project import Project
|
||||
from app.models.boq import BoqDocument, System, Section, WorkItem
|
||||
from app.models.agreement import Agreement
|
||||
from app.models.ks2 import KS2
|
||||
from app.models.ks3 import KS3
|
||||
from app.models.payment import Payment
|
||||
from app.routers import (
|
||||
projects as project_router,
|
||||
boq as boq_router,
|
||||
agreements as agreement_router,
|
||||
daily_reports,
|
||||
ks2 as ks2_router,
|
||||
ks3 as ks3_router,
|
||||
payments as payments_router,
|
||||
)
|
||||
|
||||
|
||||
def _make_session(tmp_path):
|
||||
db_path = tmp_path / "t023fix-copy.db"
|
||||
shutil.copy2(DATABASE_PATH, db_path)
|
||||
engine = create_engine(f"sqlite:///{db_path.as_posix()}", connect_args={"check_same_thread": False})
|
||||
Base.metadata.create_all(bind=engine)
|
||||
return engine, sessionmaker(bind=engine, autoflush=False, autocommit=False)
|
||||
|
||||
|
||||
ALL_DEPS = (
|
||||
project_router.get_db,
|
||||
boq_router.get_db,
|
||||
agreement_router.get_db,
|
||||
daily_reports.get_db,
|
||||
ks2_router.get_db,
|
||||
ks3_router.get_db,
|
||||
payments_router.get_db,
|
||||
)
|
||||
|
||||
|
||||
def _bind_session(Session, *deps):
|
||||
def override_db():
|
||||
s = Session()
|
||||
try:
|
||||
yield s
|
||||
finally:
|
||||
s.close()
|
||||
for dep in deps:
|
||||
app.dependency_overrides[dep] = override_db
|
||||
|
||||
|
||||
def _clear(*deps):
|
||||
for dep in deps:
|
||||
app.dependency_overrides.pop(dep, None)
|
||||
|
||||
|
||||
# 1. Document tree has both entry points
|
||||
|
||||
def test_document_tree_has_boq_and_agreements_buttons(tmp_path):
|
||||
engine, Session = _make_session(tmp_path)
|
||||
_bind_session(Session, *ALL_DEPS)
|
||||
try:
|
||||
with Session() as s:
|
||||
p = Project(name="Tree buttons")
|
||||
s.add(p)
|
||||
s.flush()
|
||||
doc = BoqDocument(project_id=p.id, name="Ведомость")
|
||||
s.add(doc)
|
||||
s.flush()
|
||||
agr = Agreement(project_id=p.id, number="A-1", date=date(2026, 1, 1), title="ДС", status="draft")
|
||||
s.add(agr)
|
||||
s.commit()
|
||||
pid, doc_id, agr_id = p.id, doc.id, agr.id
|
||||
with TestClient(app) as client:
|
||||
html = client.get(f"/projects/{pid}").text
|
||||
# Both buttons present in the document-tree card header
|
||||
tree_block = html.split("Дерево документов", 1)[-1].split("</section>", 1)[0]
|
||||
assert f'href="/boq/{pid}"' in tree_block
|
||||
assert f'href="/projects/{pid}/agreements"' in tree_block
|
||||
assert "Дополнительные соглашения" in tree_block
|
||||
assert "Ведомости" in tree_block
|
||||
finally:
|
||||
_clear(*ALL_DEPS)
|
||||
engine.dispose()
|
||||
|
||||
|
||||
# 2. Import requisites are on the initial import form and pass through
|
||||
|
||||
def test_import_form_shows_all_four_requisites(tmp_path):
|
||||
engine, Session = _make_session(tmp_path)
|
||||
_bind_session(Session, *ALL_DEPS)
|
||||
try:
|
||||
with Session() as s:
|
||||
p = Project(name="Import form", contract_number="PC-1")
|
||||
s.add(p)
|
||||
s.commit()
|
||||
pid = p.id
|
||||
with TestClient(app) as client:
|
||||
html = client.get(f"/projects/{pid}/import").text
|
||||
assert 'name="document_name"' in html
|
||||
assert 'name="document_number"' in html
|
||||
assert 'name="document_date"' in html
|
||||
assert 'name="contract"' in html
|
||||
assert "Реквизиты ведомости" in html
|
||||
finally:
|
||||
_clear(*ALL_DEPS)
|
||||
engine.dispose()
|
||||
|
||||
|
||||
def test_import_requisites_pass_upload_to_confirm(tmp_path):
|
||||
import openpyxl
|
||||
wb = openpyxl.Workbook()
|
||||
ws = wb.active
|
||||
ws.title = "Лист А"
|
||||
for _ in range(4):
|
||||
ws.append([None])
|
||||
ws.append(["№", "Наименование", "Модель", "Производитель", "Ед", "Кол-во", "Цена", "Сумма"])
|
||||
ws.append([1, "Работа", None, None, "шт", 1, 5, 5])
|
||||
upload_dir = tmp_path / "uploads"
|
||||
upload_dir.mkdir()
|
||||
wb.save(upload_dir / "file.xlsx")
|
||||
|
||||
engine, Session = _make_session(tmp_path)
|
||||
_bind_session(Session, *ALL_DEPS)
|
||||
try:
|
||||
with Session() as s:
|
||||
p = Project(name="Flow")
|
||||
s.add(p)
|
||||
s.commit()
|
||||
pid = p.id
|
||||
import app.routers.boq as boq_mod
|
||||
old_upload = boq_mod.UPLOAD_DIR
|
||||
boq_mod.UPLOAD_DIR = upload_dir
|
||||
try:
|
||||
with TestClient(app) as client:
|
||||
# upload carries requisites into sheet selection
|
||||
with open(upload_dir / "file.xlsx", "rb") as fh:
|
||||
up = client.post(
|
||||
f"/boq/{pid}/import/upload",
|
||||
files={"file": ("file.xlsx", fh, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")},
|
||||
data={
|
||||
"document_name": "Ведомость А",
|
||||
"document_number": "N-1",
|
||||
"document_date": "2026-04-01",
|
||||
"contract": "Д-9",
|
||||
},
|
||||
)
|
||||
assert up.status_code == 200
|
||||
assert 'value="Ведомость А"' in up.text
|
||||
assert 'value="N-1"' in up.text
|
||||
assert 'value="Д-9"' in up.text
|
||||
|
||||
# preview shows requisites
|
||||
prev = client.post(f"/boq/{pid}/import/preview", data={
|
||||
"filename": "file.xlsx",
|
||||
"sheet_name": "Лист А",
|
||||
"header_row": "5",
|
||||
"start_row": "6",
|
||||
"document_name": "Ведомость А",
|
||||
"document_number": "N-1",
|
||||
"document_date": "2026-04-01",
|
||||
"contract": "Д-9",
|
||||
})
|
||||
assert prev.status_code == 200
|
||||
assert "Реквизиты ведомости" in prev.text
|
||||
assert "Ведомость А" in prev.text
|
||||
assert "N-1" in prev.text
|
||||
|
||||
# confirm saves
|
||||
conf = client.post(f"/boq/{pid}/import/confirm", data={
|
||||
"filename": "file.xlsx",
|
||||
"sheet_name": "Лист А",
|
||||
"header_row": "5",
|
||||
"start_row": "6",
|
||||
"document_name": "Ведомость А",
|
||||
"document_number": "N-1",
|
||||
"document_date": "2026-04-01",
|
||||
"contract": "Д-9",
|
||||
})
|
||||
assert conf.status_code == 200
|
||||
assert "Ведомость А" in conf.text
|
||||
finally:
|
||||
boq_mod.UPLOAD_DIR = old_upload
|
||||
with Session() as s:
|
||||
doc = s.query(BoqDocument).filter_by(project_id=pid).one()
|
||||
assert doc.name == "Ведомость А"
|
||||
assert doc.document_number == "N-1"
|
||||
assert doc.document_date == date(2026, 4, 1)
|
||||
assert doc.contract == "Д-9"
|
||||
assert doc.display_name == "Ведомость А"
|
||||
finally:
|
||||
_clear(*ALL_DEPS)
|
||||
engine.dispose()
|
||||
|
||||
|
||||
# 3. display_name used in UI
|
||||
|
||||
def test_display_name_used_in_agreement_scope(tmp_path):
|
||||
engine, Session = _make_session(tmp_path)
|
||||
_bind_session(Session, *ALL_DEPS)
|
||||
try:
|
||||
with Session() as s:
|
||||
p = Project(name="DN")
|
||||
s.add(p)
|
||||
s.flush()
|
||||
doc = BoqDocument(project_id=p.id, name="BOQ Import - Ведомость ОВ")
|
||||
s.add(doc)
|
||||
s.commit()
|
||||
pid = p.id
|
||||
with TestClient(app) as client:
|
||||
html = client.get(f"/projects/{pid}/agreements/new").text
|
||||
assert "Ведомость ОВ" in html
|
||||
assert "BOQ Import" not in html
|
||||
finally:
|
||||
_clear(*ALL_DEPS)
|
||||
engine.dispose()
|
||||
|
||||
|
||||
# 4-6. Status in KS-2 / KS-3 / Payments lists
|
||||
|
||||
def _seed_ks_and_payments(Session):
|
||||
with Session() as s:
|
||||
p = Project(name="Status lists")
|
||||
s.add(p)
|
||||
s.flush()
|
||||
doc = BoqDocument(project_id=p.id, name="BOQ")
|
||||
s.add(doc)
|
||||
s.flush()
|
||||
wi = WorkItem(project_id=p.id, boq_document_id=doc.id, name="W", quantity=Decimal("1"), amount=Decimal("10"))
|
||||
s.add(wi)
|
||||
s.flush()
|
||||
ks2_draft = KS2(project_id=p.id, number="K2-1", date=date(2026, 1, 1), status="draft")
|
||||
ks2_issued = KS2(project_id=p.id, number="K2-2", date=date(2026, 1, 2), status="issued")
|
||||
ks2_cancelled = KS2(project_id=p.id, number="K2-3", date=date(2026, 1, 3), status="cancelled")
|
||||
s.add_all([ks2_draft, ks2_issued, ks2_cancelled])
|
||||
s.flush()
|
||||
ks3_draft = KS3(project_id=p.id, number="K3-1", date=date(2026, 2, 1), status="draft")
|
||||
ks3_issued = KS3(project_id=p.id, number="K3-2", date=date(2026, 2, 2), status="issued")
|
||||
ks3_cancelled = KS3(project_id=p.id, number="K3-3", date=date(2026, 2, 3), status="cancelled")
|
||||
s.add_all([ks3_draft, ks3_issued, ks3_cancelled])
|
||||
s.flush()
|
||||
pay_active = Payment(project_id=p.id, date=date(2026, 3, 1), amount=Decimal("5"), currency="RUB", status="active")
|
||||
pay_cancelled = Payment(project_id=p.id, date=date(2026, 3, 2), amount=Decimal("5"), currency="RUB", status="cancelled")
|
||||
s.add_all([pay_active, pay_cancelled])
|
||||
s.commit()
|
||||
return p.id
|
||||
|
||||
|
||||
def test_ks2_list_shows_all_statuses(tmp_path):
|
||||
engine, Session = _make_session(tmp_path)
|
||||
_bind_session(Session, *ALL_DEPS)
|
||||
try:
|
||||
pid = _seed_ks_and_payments(Session)
|
||||
with TestClient(app) as client:
|
||||
html = client.get(f"/projects/{pid}/ks2").text
|
||||
assert "Черновик" in html
|
||||
assert "Проведён" in html
|
||||
assert "Сторнирован" in html
|
||||
assert "badge" in html
|
||||
assert "bg-danger" in html
|
||||
assert "bg-success" in html
|
||||
assert "bg-secondary" in html
|
||||
# row-click preserved
|
||||
assert "clickable-row" in html
|
||||
finally:
|
||||
_clear(*ALL_DEPS)
|
||||
engine.dispose()
|
||||
|
||||
|
||||
def test_ks3_list_shows_all_statuses(tmp_path):
|
||||
engine, Session = _make_session(tmp_path)
|
||||
_bind_session(Session, *ALL_DEPS)
|
||||
try:
|
||||
pid = _seed_ks_and_payments(Session)
|
||||
with TestClient(app) as client:
|
||||
html = client.get(f"/projects/{pid}/ks3").text
|
||||
assert "Черновик" in html
|
||||
assert "Проведён" in html
|
||||
assert "Сторнирован" in html
|
||||
assert "badge" in html
|
||||
assert "clickable-row" in html
|
||||
finally:
|
||||
_clear(*ALL_DEPS)
|
||||
engine.dispose()
|
||||
|
||||
|
||||
def test_payments_list_shows_status(tmp_path):
|
||||
engine, Session = _make_session(tmp_path)
|
||||
_bind_session(Session, *ALL_DEPS)
|
||||
try:
|
||||
pid = _seed_ks_and_payments(Session)
|
||||
with TestClient(app) as client:
|
||||
html = client.get(f"/projects/{pid}/payments").text
|
||||
assert "Сторнирован" in html
|
||||
assert "Активный" in html
|
||||
assert "Статус" in html
|
||||
assert "badge" in html
|
||||
assert "clickable-row" in html
|
||||
finally:
|
||||
_clear(*ALL_DEPS)
|
||||
engine.dispose()
|
||||
|
||||
|
||||
# 7. Existing tests + regressions: header layout, package button
|
||||
|
||||
def test_project_header_layout_and_package_button(tmp_path):
|
||||
engine, Session = _make_session(tmp_path)
|
||||
_bind_session(Session, *ALL_DEPS)
|
||||
try:
|
||||
with Session() as s:
|
||||
p = Project(name="Header", status="active", contract_number="D-1", customer="Cust")
|
||||
s.add(p)
|
||||
s.commit()
|
||||
pid = p.id
|
||||
with TestClient(app) as client:
|
||||
html = client.get(f"/projects/{pid}").text
|
||||
# Top row: project name and primary actions
|
||||
assert "Дневной отчёт" in html
|
||||
assert "Редактировать" in html
|
||||
# Requisites readable
|
||||
assert "D-1" in html
|
||||
assert "Cust" in html
|
||||
assert "Активный" in html
|
||||
# Package button is not full-width / not stretched
|
||||
match = re.search(r'<button type="submit" class="([^"]*)">Сформировать комплект</button>', html)
|
||||
assert match, "package button not found"
|
||||
assert "w-100" not in match.group(1)
|
||||
assert "w-auto" in match.group(1)
|
||||
assert "text-nowrap" in match.group(1)
|
||||
finally:
|
||||
_clear(*ALL_DEPS)
|
||||
engine.dispose()
|
||||
|
||||
|
||||
def test_eye_toggle_and_agreement_create_not_broken(tmp_path):
|
||||
engine, Session = _make_session(tmp_path)
|
||||
_bind_session(Session, *ALL_DEPS)
|
||||
try:
|
||||
with Session() as s:
|
||||
p = Project(name="Regressions")
|
||||
s.add(p)
|
||||
s.flush()
|
||||
BoqDocument(project_id=p.id, name="BOQ Import - Ведомость ОВ")
|
||||
s.commit()
|
||||
pid = p.id
|
||||
with TestClient(app) as client:
|
||||
page = client.get(f"/projects/{pid}")
|
||||
assert 'id="toggleMoney"' in page.text
|
||||
assert "money-hidden" in page.text
|
||||
|
||||
form = client.get(f"/projects/{pid}/agreements/new")
|
||||
assert form.status_code == 200
|
||||
created = client.post(f"/projects/{pid}/agreements", data={
|
||||
"number": "A-1", "agreement_date": "2026-01-01",
|
||||
"title": "Тест", "description": "", "scope": "project",
|
||||
}, follow_redirects=False)
|
||||
assert created.status_code == 303
|
||||
|
||||
# agreement list row-click
|
||||
listing = client.get(f"/projects/{pid}/agreements")
|
||||
assert "clickable-row" in listing.text
|
||||
finally:
|
||||
_clear(*ALL_DEPS)
|
||||
engine.dispose()
|
||||
Reference in New Issue
Block a user