diff --git a/app/database/migrations.py b/app/database/migrations.py index d22dc7f..23105ac 100644 --- a/app/database/migrations.py +++ b/app/database/migrations.py @@ -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]}") diff --git a/app/importer/excel_importer.py b/app/importer/excel_importer.py index c4d4582..d9d1743 100644 --- a/app/importer/excel_importer.py +++ b/app/importer/excel_importer.py @@ -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} diff --git a/app/models/boq.py b/app/models/boq.py index b963cf7..bd68a9f 100644 --- a/app/models/boq.py +++ b/app/models/boq.py @@ -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"" diff --git a/app/routers/agreements.py b/app/routers/agreements.py index fa173a4..03f8f2d 100644 --- a/app/routers/agreements.py +++ b/app/routers/agreements.py @@ -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): diff --git a/app/routers/boq.py b/app/routers/boq.py index 533229e..ba733a8 100644 --- a/app/routers/boq.py +++ b/app/routers/boq.py @@ -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() @@ -159,19 +162,23 @@ async def upload_excel_file( filename = Path(file.filename or "upload.xlsx").name UPLOAD_DIR.mkdir(parents=True, exist_ok=True) file_location = UPLOAD_DIR / filename - + with open(file_location, "wb+") as file_object: file_object.write(file.file.read()) - + # Get the sheets from the Excel file sheets = excel_importer.get_excel_sheets(file_location) - + return request.app.templates.TemplateResponse("projects/import_sheet_selection.html", { "request": request, "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,22 +189,26 @@ 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 file_path = UPLOAD_DIR / Path(filename).name - + # Import and preview data try: preview_data = excel_importer.preview_excel_data(file_path, sheet_name, header_row, start_row) except (ValueError, OSError) as exc: raise HTTPException(status_code=400, detail=str(exc)) from exc - + # Get project db_project = db.query(project.Project).filter(project.Project.id == project_id).first() if db_project is None: raise HTTPException(status_code=404, detail="Project not found") - + return request.app.templates.TemplateResponse("projects/import_preview.html", { "request": request, "project": db_project, @@ -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,20 +238,34 @@ 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 file_path = UPLOAD_DIR / Path(filename).name - + # Import data into database db_project = db.query(project.Project).filter(project.Project.id == project_id).first() 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 - + # Get project return request.app.templates.TemplateResponse("projects/import_confirm.html", { "request": request, diff --git a/app/templates/agreements/detail.html b/app/templates/agreements/detail.html index 19a326f..06f2e18 100644 --- a/app/templates/agreements/detail.html +++ b/app/templates/agreements/detail.html @@ -1,18 +1,18 @@ -ДС №{{ agreement.number }} — {{ project.name }}
+ДС №{{ agreement.number }} — {{ project.name }}
{% if error %}{% endif %}

ДС №{{ agreement.number }} — {{ agreement.title }}

{{ agreement.date.strftime('%d.%m.%Y') }} · {{ scope_label }}
К списку{% if agreement.status == 'approved' %}Утверждено{% else %}Черновик{% endif %}
{% if agreement.status == 'draft' %}

Реквизиты ДС

-
+
{% else %}
Номер: {{ agreement.number }}
Дата: {{ agreement.date.strftime('%d.%m.%Y') }}
Область: {{ scope_label }}
Описание: {{ agreement.description or '—' }}
{% endif %}

Позиции ДС

{{ line_rows|length }} поз.
{% for row in line_rows %} {% if agreement.status == 'draft' %}{% endif %} {% else %}{% endfor %}
Тип№ / ПозицияЕд.Базовое / текущееИзменениеПосле ДССумма изменения
{% if row.line.change_type == 'new_position' %}Новая{% elif row.line.change_type == 'decrease' %}Уменьшение{% else %}Увеличение{% endif %}
{{ row.item.source_number or '' }} {{ row.item.name }}
{{ row.item.model or '' }}{% if row.item.manufacturer %} · {{ row.item.manufacturer }}{% endif %}
{{ row.item.unit or '—' }}{{ row.before_quantity }}{{ row.line.quantity_delta }}{{ row.after_quantity }}{{ row.amount_delta|money(project.currency) }}{% if agreement.status == 'draft' %}
{% endif %}
{% if row.line.change_type == 'new_position' %}
{% endif %}
Позиции ещё не добавлены.
{% if agreement.status == 'draft' %}

Добавить существующую позицию

Позиция не выбрана
Для уменьшения укажите отрицательное число. Сумма рассчитается по цене позиции.
{% if not selectable_items %}
В этой области нет недобавленных позиц.
{% endif %}
-

Добавить новую позицию

+

Добавить новую позицию

{% else %}
ДС утверждено. Изменения недоступны.
{% endif %} diff --git a/app/templates/agreements/list.html b/app/templates/agreements/list.html index adf4b35..ec6ad31 100644 --- a/app/templates/agreements/list.html +++ b/app/templates/agreements/list.html @@ -1,5 +1,53 @@ -Дополнительные соглашения — {{ project.name }}
- -

Дополнительные соглашения

{{ project.name }}
+ Создать ДС
-
-{% for row in rows %}{% else %}{% endfor %}
НомерДатаНаименованиеОбластьСтатусПозиций
{{ row.agreement.number }}{{ row.agreement.date.strftime('%d.%m.%Y') }}{{ row.agreement.title }}{{ row.scope_label }}{% if row.agreement.status == 'approved' %}Утверждено{% else %}Черновик{% endif %}{{ row.item_count }}Открыть
ДС пока нет.
+ + + + + + Дополнительные соглашения — {{ project.name }} + + + + +
+ +
+

Дополнительные соглашения

{{ project.name }}
+ + Создать ДС +
+
+
+ + + + {% for row in rows %} + + + + + + + + + + {% else %} + + {% endfor %} + +
НомерДатаНаименованиеОбластьСтатусПозиций
{{ row.agreement.number }}{{ row.agreement.date.strftime('%d.%m.%Y') }}{{ row.agreement.title }}{{ row.scope_label }}{% if row.agreement.status == 'approved' %}Утверждено{% else %}Черновик{% endif %}{{ row.item_count }}Открыть
ДС пока нет.
+
+
+
+ + + diff --git a/app/templates/agreements/new.html b/app/templates/agreements/new.html index ab82c61..7be1263 100644 --- a/app/templates/agreements/new.html +++ b/app/templates/agreements/new.html @@ -1,6 +1,6 @@ -Новое ДС — {{ project.name }}
+Новое ДС — {{ project.name }}

Создать ДС

{% if error %}
{{ error }}
{% endif %}
-
+
{% if not boq_documents %}
В проекте нет Ведомостей. Можно выбрать область «Весь проект».
{% endif %}
diff --git a/app/templates/base.html b/app/templates/base.html index 6e44939..e8273f2 100644 --- a/app/templates/base.html +++ b/app/templates/base.html @@ -13,7 +13,8 @@
-
+
+ Финансовые суммы
{% block content %}{% endblock %} diff --git a/app/templates/ks2/list.html b/app/templates/ks2/list.html index d0b8671..9f4d4ff 100644 --- a/app/templates/ks2/list.html +++ b/app/templates/ks2/list.html @@ -31,9 +31,13 @@ {{ row.document.number }} {{ row.document.date.strftime('%d.%m.%Y') }}{% 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 %} - - {{ 'Проведён' if row.document.status == 'issued' else 'Черновик' }} - + {% if row.document.status == 'cancelled' %} + Сторнирован + {% elif row.document.status == 'issued' %} + Проведён + {% else %} + Черновик + {% endif %} {{ row.item_count }} {{ row.amount | money }} diff --git a/app/templates/ks3/list.html b/app/templates/ks3/list.html index 21cf85c..aa3daa0 100644 --- a/app/templates/ks3/list.html +++ b/app/templates/ks3/list.html @@ -33,9 +33,13 @@ {{ row.document.date.strftime('%d.%m.%Y') }} {% 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 %} - - {{ 'Проведён' if row.document.status == 'issued' else 'Черновик' }} - + {% if row.document.status == 'cancelled' %} + Сторнирован + {% elif row.document.status == 'issued' %} + Проведён + {% else %} + Черновик + {% endif %} {{ row.ks2_count }} {{ row.amount | money }} diff --git a/app/templates/payments/list.html b/app/templates/payments/list.html index 8035244..c8838c9 100644 --- a/app/templates/payments/list.html +++ b/app/templates/payments/list.html @@ -14,41 +14,63 @@ Новый платёж
- +
+ + + + + + + + + + + + + - + {% for row in rows %} - + + - {% else %} - + {% endfor %}
Дата Номер документаСтатус Сумма Валюта Распределено Не распределено КС-3 КомментарийДействияДействия
{{ row.payment.date.strftime('%d.%m.%Y') }}{{ row.payment.date.strftime('%d.%m.%Y') }} {{ row.payment.document_number or '—' }} + {% if row.payment.status == 'cancelled' %} + Сторнирован + {% else %} + Активный + {% endif %} + {{ row.payment.amount | money(row.payment.currency) }} {{ row.payment.currency }} {{ row.allocated | money(row.payment.currency) }} {{ row.unallocated | money(row.payment.currency) }} {{ row.ks3_count }} {{ row.payment.comment or '' }} - Просмотр - Редактировать -
- -
+
+ + Просмотр + Редактировать +
+ +
+
Платежей пока нет.
Платежей пока нет.
diff --git a/app/templates/projects/boq_document.html b/app/templates/projects/boq_document.html index fcb07e0..52126fd 100644 --- a/app/templates/projects/boq_document.html +++ b/app/templates/projects/boq_document.html @@ -47,15 +47,23 @@ -
+

{{ document_title }}

-

{{ project.name }}{% if document.source_file %} · {{ document.source_file }}{% endif %}

+

+ {{ project.name }}{% if document.source_file %} · {{ document.source_file }}{% endif %} +

+ {% if document.document_number or document.document_date or document.contract %} +

+ {% if document.document_number %}№ {{ document.document_number }}{% endif %} + {% if document.document_date %}от {{ document.document_date.strftime('%d.%m.%Y') }}{% endif %} + {% if document.contract %}Договор: {{ document.contract }}{% endif %} +

+ {% endif %}
- {% if not has_history %}
@@ -68,6 +76,10 @@ К проекту
+
+ Финансовые суммы + +
diff --git a/app/templates/projects/boq_list.html b/app/templates/projects/boq_list.html index 2c06ff5..4493fc8 100644 --- a/app/templates/projects/boq_list.html +++ b/app/templates/projects/boq_list.html @@ -23,7 +23,7 @@
{% for document in documents %} - {{ document.name.replace('BOQ Import - ', 'Импорт ведомости — ').replace('BOQ Import — ', 'Импорт ведомости — ') }}
{{ document.source_file or 'Источник не указан' }} · {{ document.created_at.strftime('%d.%m.%Y %H:%M') if document.created_at else 'Дата не указана' }}
+ {{ document.display_name }}
{{ document.source_file or 'Источник не указан' }} · {{ document.created_at.strftime('%d.%m.%Y %H:%M') if document.created_at else 'Дата не указана' }}
Открыть
{% endfor %} diff --git a/app/templates/projects/detail.html b/app/templates/projects/detail.html index a37eb01..561c274 100644 --- a/app/templates/projects/detail.html +++ b/app/templates/projects/detail.html @@ -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; + }
-
-
-

{{ project.name }}

-
- Договор: {{ project.contract_number or 'не указан' }} - Заказчик: {{ project.customer or 'не указан' }} - Валюта: {{ project.currency or 'RUB' }} - Период: {{ project.start_date.strftime('%d.%m.%Y') if project.start_date else '—' }} — {{ project.end_date.strftime('%d.%m.%Y') if project.end_date else '—' }} - Статус: {{ project.status or 'не указан' }} -
- {% if base_boq_documents|length == 1 %}
Ведомость проекта: {{ base_boq_documents[0].name.replace('BOQ Import - ', 'Импорт ведомости — ').replace('BOQ Import — ', 'Импорт ведомости — ') }}
{% elif base_boq_documents|length > 1 %}
Ведомостей проекта: {{ base_boq_documents|length }}
{% endif %} -
-
- Создать Daily Report - +
+ +

{{ project.name }}

+ + + +
+
+
Договор
+
{{ project.contract_number or 'не указан' }}
+
+
+
Заказчик
+
{{ project.customer or 'не указан' }}
+
+
+
Валюта
+
{{ project.currency or 'RUB' }}
+
+
+
Период
+
{{ project.start_date.strftime('%d.%m.%Y') if project.start_date else '—' }} — {{ project.end_date.strftime('%d.%m.%Y') if project.end_date else '—' }}
+
+
+
Статус
+ {% 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')) %} +
{{ status_pair[0] }}
+
+
+ + {% if base_boq_documents|length == 1 %}
Ведомость проекта: {{ base_boq_documents[0].display_name }}
{% elif base_boq_documents|length > 1 %}
Ведомостей проекта: {{ base_boq_documents|length }}
{% endif %} + +
+
{% if project.status != 'archived' %} @@ -50,8 +100,8 @@ -
- + +
{% else %} @@ -64,6 +114,11 @@ {% else %}
✓ Проверка плана: превышений нет
{% endif %} +
+ Финансовые суммы + +
+

План и выполнение

@@ -184,8 +239,8 @@
-
- +
+
@@ -202,13 +257,19 @@
-

Дерево документов

Ведомости
+
+

Дерево документов

+ +
+