feat: add KS-3/payments, tech debt fixes, UI polish, and KS-2 Excel/Word export
Tasks 008-016: KS-6a journal, KS-3 documents, payments with allocations, tech debt cleanup, financial privacy, document tree, storno mechanism, row-click UI, BOQ collapse/sticky header, and KS-2 export to Excel/Word via shared DTO architecture.
This commit is contained in:
@@ -8,6 +8,7 @@ ITEM_WORK_ITEM_MIGRATION = "20260925_agreement_item_work_item_required"
|
||||
WORK_ITEM_OPTIONAL_BOQ_MIGRATION = "20260925_work_item_optional_boq"
|
||||
DAILY_REPORT_OPTIONAL_SYSTEM_MIGRATION = "20260925_daily_report_optional_system"
|
||||
KS2_REPORTING_PERIOD_MIGRATION = "20260925_ks2_reporting_period"
|
||||
PAYMENT_STATUS_MIGRATION = "20260926_payment_status"
|
||||
|
||||
|
||||
def run_migrations(engine):
|
||||
@@ -178,6 +179,13 @@ def run_migrations(engine):
|
||||
connection.execute("ALTER TABLE ks2_documents ADD COLUMN reporting_period_to DATE")
|
||||
connection.execute("INSERT INTO schema_migrations(version, applied_at) VALUES (?, ?)",
|
||||
(KS2_REPORTING_PERIOD_MIGRATION, datetime.now(timezone.utc).isoformat()))
|
||||
if PAYMENT_STATUS_MIGRATION not in applied:
|
||||
payment_cols = {row[1] for row in connection.execute("PRAGMA table_info(payments)")}
|
||||
if "status" not in payment_cols:
|
||||
connection.execute("ALTER TABLE payments ADD COLUMN status VARCHAR NOT NULL DEFAULT 'active'")
|
||||
connection.execute("CREATE INDEX IF NOT EXISTS ix_payments_status ON payments (status)")
|
||||
connection.execute("INSERT INTO schema_migrations(version, applied_at) VALUES (?, ?)",
|
||||
(PAYMENT_STATUS_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]}")
|
||||
|
||||
@@ -0,0 +1,106 @@
|
||||
"""Excel renderer for KS-2 export using openpyxl."""
|
||||
import io
|
||||
from decimal import Decimal
|
||||
|
||||
from openpyxl import Workbook
|
||||
from openpyxl.styles import Alignment, Border, Font, Side
|
||||
from openpyxl.utils import get_column_letter
|
||||
|
||||
from app.exporters.ks2_dto import KS2ExportDocument
|
||||
|
||||
THIN = Side(style="thin")
|
||||
BORDER = Border(left=THIN, right=THIN, top=THIN, bottom=THIN)
|
||||
HEADER_FONT = Font(bold=True, size=11)
|
||||
TITLE_FONT = Font(bold=True, size=14)
|
||||
MONEY_FMT = '#,##0.00'
|
||||
QTY_FMT = '#,##0.0000'
|
||||
|
||||
|
||||
def render_ks2_excel(doc: KS2ExportDocument) -> bytes:
|
||||
wb = Workbook()
|
||||
ws = wb.active
|
||||
ws.title = "КС-2"
|
||||
|
||||
h = doc.header
|
||||
row = 1
|
||||
|
||||
# Title
|
||||
ws.merge_cells(start_row=row, start_column=1, end_row=row, end_column=7)
|
||||
c = ws.cell(row=row, column=1, value=f"Акт КС-2 №{h.ks2_number} от {h.ks2_date.strftime('%d.%m.%Y')}")
|
||||
c.font = TITLE_FONT
|
||||
c.alignment = Alignment(horizontal="center")
|
||||
row += 1
|
||||
|
||||
# Header block
|
||||
header_lines = [
|
||||
("Проект:", h.project_name),
|
||||
("Заказчик:", h.customer),
|
||||
("Договор:", h.contract_number),
|
||||
]
|
||||
if h.period_from and h.period_to:
|
||||
header_lines.append(("Период:", f"{h.period_from.strftime('%d.%m.%Y')} — {h.period_to.strftime('%d.%m.%Y')}"))
|
||||
if h.comment:
|
||||
header_lines.append(("Комментарий:", h.comment))
|
||||
|
||||
for label, value in header_lines:
|
||||
ws.cell(row=row, column=1, value=label).font = HEADER_FONT
|
||||
ws.merge_cells(start_row=row, start_column=2, end_row=row, end_column=7)
|
||||
ws.cell(row=row, column=2, value=value)
|
||||
row += 1
|
||||
|
||||
row += 1 # blank row
|
||||
|
||||
# Table header
|
||||
columns = ["№", "Наименование работ", "№ позиции в ведомости", "Ед. изм.", "Количество", "Цена за ед.", "Стоимость"]
|
||||
for col_idx, col_name in enumerate(columns, start=1):
|
||||
c = ws.cell(row=row, column=col_idx, value=col_name)
|
||||
c.font = HEADER_FONT
|
||||
c.border = BORDER
|
||||
c.alignment = Alignment(horizontal="center", vertical="center", wrap_text=True)
|
||||
header_row = row
|
||||
row += 1
|
||||
|
||||
# Items
|
||||
for item in doc.items:
|
||||
ws.cell(row=row, column=1, value=item.row_number).border = BORDER
|
||||
c = ws.cell(row=row, column=2, value=item.name)
|
||||
c.border = BORDER
|
||||
c.alignment = Alignment(wrap_text=True, vertical="top")
|
||||
ws.cell(row=row, column=3, value=item.source_number).border = BORDER
|
||||
ws.cell(row=row, column=4, value=item.unit).border = BORDER
|
||||
|
||||
c = ws.cell(row=row, column=5, value=float(item.quantity))
|
||||
c.border = BORDER
|
||||
c.number_format = QTY_FMT
|
||||
|
||||
c = ws.cell(row=row, column=6, value=float(item.unit_price))
|
||||
c.border = BORDER
|
||||
c.number_format = MONEY_FMT
|
||||
|
||||
c = ws.cell(row=row, column=7, value=float(item.amount))
|
||||
c.border = BORDER
|
||||
c.number_format = MONEY_FMT
|
||||
row += 1
|
||||
|
||||
# Total row
|
||||
ws.merge_cells(start_row=row, start_column=1, end_row=row, end_column=6)
|
||||
c = ws.cell(row=row, column=1, value="Итого:")
|
||||
c.font = HEADER_FONT
|
||||
c.border = BORDER
|
||||
c.alignment = Alignment(horizontal="right")
|
||||
for col in range(2, 7):
|
||||
ws.cell(row=row, column=col).border = BORDER
|
||||
c = ws.cell(row=row, column=7, value=float(doc.total))
|
||||
c.font = HEADER_FONT
|
||||
c.border = BORDER
|
||||
c.number_format = MONEY_FMT
|
||||
|
||||
# Column widths
|
||||
widths = {1: 5, 2: 40, 3: 15, 4: 10, 5: 12, 6: 14, 7: 14}
|
||||
for col, width in widths.items():
|
||||
ws.column_dimensions[get_column_letter(col)].width = width
|
||||
|
||||
buf = io.BytesIO()
|
||||
wb.save(buf)
|
||||
buf.seek(0)
|
||||
return buf.read()
|
||||
@@ -0,0 +1,68 @@
|
||||
"""Shared document DTOs for export renderers. One source of truth for Excel and Word."""
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import date
|
||||
from decimal import Decimal
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class KS2ExportItem:
|
||||
row_number: int
|
||||
source_number: str
|
||||
name: str
|
||||
unit: str
|
||||
quantity: Decimal
|
||||
unit_price: Decimal
|
||||
amount: Decimal
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class KS2ExportHeader:
|
||||
project_name: str
|
||||
customer: str
|
||||
contract_number: str
|
||||
ks2_number: str
|
||||
ks2_date: date
|
||||
period_from: date | None
|
||||
period_to: date | None
|
||||
comment: str
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class KS2ExportDocument:
|
||||
header: KS2ExportHeader
|
||||
items: list[KS2ExportItem]
|
||||
total: Decimal
|
||||
|
||||
|
||||
def build_ks2_export_dto(db, ks2_document) -> KS2ExportDocument:
|
||||
"""Build the export DTO from a KS2 document. Read-only: does not modify any data."""
|
||||
from decimal import Decimal as D
|
||||
|
||||
project = ks2_document.project
|
||||
items = []
|
||||
total = D("0")
|
||||
for idx, line in enumerate(ks2_document.items, start=1):
|
||||
wi = line.work_item
|
||||
amount = D(str(line.amount or 0))
|
||||
total += amount
|
||||
items.append(KS2ExportItem(
|
||||
row_number=idx,
|
||||
source_number=wi.source_number or "",
|
||||
name=wi.name or "",
|
||||
unit=wi.unit or "",
|
||||
quantity=D(str(line.quantity or 0)),
|
||||
unit_price=D(str(line.unit_price or 0)),
|
||||
amount=amount,
|
||||
))
|
||||
|
||||
header = KS2ExportHeader(
|
||||
project_name=project.name if project else "",
|
||||
customer=project.customer if project and project.customer else "",
|
||||
contract_number=project.contract_number if project and project.contract_number else "",
|
||||
ks2_number=ks2_document.number,
|
||||
ks2_date=ks2_document.date,
|
||||
period_from=ks2_document.reporting_period_from,
|
||||
period_to=ks2_document.reporting_period_to,
|
||||
comment=ks2_document.comment or "",
|
||||
)
|
||||
return KS2ExportDocument(header=header, items=items, total=total)
|
||||
@@ -0,0 +1,84 @@
|
||||
"""Word renderer for KS-2 export using python-docx."""
|
||||
import io
|
||||
|
||||
from docx import Document
|
||||
from docx.shared import Pt, Cm
|
||||
from docx.enum.text import WD_ALIGN_PARAGRAPH
|
||||
from docx.enum.table import WD_TABLE_ALIGNMENT
|
||||
|
||||
from app.exporters.ks2_dto import KS2ExportDocument
|
||||
|
||||
|
||||
def render_ks2_word(doc: KS2ExportDocument) -> bytes:
|
||||
d = Document()
|
||||
h = doc.header
|
||||
|
||||
# Title
|
||||
title = d.add_paragraph()
|
||||
title.alignment = WD_ALIGN_PARAGRAPH.CENTER
|
||||
run = title.add_run(f"Акт КС-2 №{h.ks2_number} от {h.ks2_date.strftime('%d.%m.%Y')}")
|
||||
run.bold = True
|
||||
run.font.size = Pt(14)
|
||||
|
||||
d.add_paragraph()
|
||||
|
||||
# Header block
|
||||
header_lines = [
|
||||
("Проект:", h.project_name),
|
||||
("Заказчик:", h.customer),
|
||||
("Договор:", h.contract_number),
|
||||
]
|
||||
if h.period_from and h.period_to:
|
||||
header_lines.append(("Период:", f"{h.period_from.strftime('%d.%m.%Y')} — {h.period_to.strftime('%d.%m.%Y')}"))
|
||||
if h.comment:
|
||||
header_lines.append(("Комментарий:", h.comment))
|
||||
|
||||
for label, value in header_lines:
|
||||
p = d.add_paragraph()
|
||||
run = p.add_run(label + " ")
|
||||
run.bold = True
|
||||
p.add_run(value)
|
||||
|
||||
d.add_paragraph()
|
||||
|
||||
# Table
|
||||
table = d.add_table(rows=1, cols=7)
|
||||
table.style = "Table Grid"
|
||||
table.alignment = WD_TABLE_ALIGNMENT.CENTER
|
||||
|
||||
columns = ["№", "Наименование работ", "№ поз. в ведомости", "Ед. изм.", "Количество", "Цена за ед.", "Стоимость"]
|
||||
for idx, col_name in enumerate(columns):
|
||||
cell = table.rows[0].cells[idx]
|
||||
cell.text = col_name
|
||||
for paragraph in cell.paragraphs:
|
||||
for run in paragraph.runs:
|
||||
run.bold = True
|
||||
run.font.size = Pt(9)
|
||||
|
||||
for item in doc.items:
|
||||
row = table.add_row()
|
||||
row.cells[0].text = str(item.row_number)
|
||||
row.cells[1].text = item.name
|
||||
row.cells[2].text = item.source_number
|
||||
row.cells[3].text = item.unit
|
||||
row.cells[4].text = f"{item.quantity:.4f}"
|
||||
row.cells[5].text = f"{item.unit_price:.2f}"
|
||||
row.cells[6].text = f"{item.amount:.2f}"
|
||||
|
||||
# Total row
|
||||
total_row = table.add_row()
|
||||
total_row.cells[0].merge(total_row.cells[5])
|
||||
total_row.cells[0].text = "Итого:"
|
||||
for paragraph in total_row.cells[0].paragraphs:
|
||||
paragraph.alignment = WD_ALIGN_PARAGRAPH.RIGHT
|
||||
for run in paragraph.runs:
|
||||
run.bold = True
|
||||
total_row.cells[6].text = f"{doc.total:.2f}"
|
||||
for paragraph in total_row.cells[6].paragraphs:
|
||||
for run in paragraph.runs:
|
||||
run.bold = True
|
||||
|
||||
buf = io.BytesIO()
|
||||
d.save(buf)
|
||||
buf.seek(0)
|
||||
return buf.read()
|
||||
+7
-2
@@ -1,11 +1,11 @@
|
||||
from fastapi import FastAPI
|
||||
from fastapi import FastAPI
|
||||
from fastapi.staticfiles import StaticFiles
|
||||
from fastapi.templating import Jinja2Templates
|
||||
from fastapi.responses import RedirectResponse
|
||||
from pathlib import Path
|
||||
|
||||
# Import routers
|
||||
from app.routers import projects, boq as boq_router, daily_reports, agreements, ks2
|
||||
from app.routers import projects, boq as boq_router, daily_reports, agreements, ks2, ks3, ks6a, payments
|
||||
|
||||
# Import models to ensure they're registered
|
||||
from app.models import project as project_models, boq as boq_models
|
||||
@@ -13,6 +13,8 @@ from app.models import daily_report as daily_report_models
|
||||
from app.models import work_journal as work_journal_models
|
||||
from app.models import agreement as agreement_models
|
||||
from app.models import ks2 as ks2_models
|
||||
from app.models import ks3 as ks3_models
|
||||
from app.models import payment as payment_models
|
||||
|
||||
# Initialize database
|
||||
from app.database.database import engine
|
||||
@@ -43,6 +45,9 @@ app.include_router(boq_router.router, prefix="/boq", tags=["boq"])
|
||||
app.include_router(daily_reports.router, prefix="/projects", tags=["daily-reports"])
|
||||
app.include_router(agreements.router, prefix="/projects", tags=["agreements"])
|
||||
app.include_router(ks2.router, prefix="/projects", tags=["ks2"])
|
||||
app.include_router(ks3.router, prefix="/projects", tags=["ks3"])
|
||||
app.include_router(ks6a.router, prefix="/projects", tags=["ks6a"])
|
||||
app.include_router(payments.router, prefix="/projects", tags=["payments"])
|
||||
|
||||
@app.get("/", include_in_schema=False)
|
||||
async def read_root():
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
from sqlalchemy import Column, Date, DateTime, ForeignKey, Integer, Numeric, String, Text, UniqueConstraint
|
||||
from sqlalchemy.orm import relationship
|
||||
from sqlalchemy.sql import func
|
||||
|
||||
from app.database.database import Base
|
||||
|
||||
|
||||
class KS3(Base):
|
||||
__tablename__ = "ks3_documents"
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
project_id = Column(Integer, ForeignKey("projects.id"), nullable=False, index=True)
|
||||
number = Column(String, nullable=False)
|
||||
date = Column(Date, nullable=False, index=True)
|
||||
reporting_period_from = Column(Date, nullable=True)
|
||||
reporting_period_to = Column(Date, nullable=True)
|
||||
comment = Column(Text)
|
||||
status = Column(String, nullable=False, default="draft", index=True)
|
||||
created_at = Column(DateTime, nullable=False, server_default=func.now())
|
||||
updated_at = Column(DateTime, nullable=False, server_default=func.now(), onupdate=func.now())
|
||||
|
||||
project = relationship("Project")
|
||||
links = relationship("KS3KS2", back_populates="ks3", cascade="all, delete-orphan")
|
||||
|
||||
|
||||
class KS3KS2(Base):
|
||||
__tablename__ = "ks3_ks2_links"
|
||||
__table_args__ = (
|
||||
UniqueConstraint("ks3_id", "ks2_id", name="uq_ks3_ks2_link"),
|
||||
)
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
ks3_id = Column(Integer, ForeignKey("ks3_documents.id", ondelete="CASCADE"), nullable=False, index=True)
|
||||
ks2_id = Column(Integer, ForeignKey("ks2_documents.id"), nullable=False, index=True)
|
||||
|
||||
ks3 = relationship("KS3", back_populates="links")
|
||||
ks2 = relationship("KS2")
|
||||
@@ -0,0 +1,39 @@
|
||||
from sqlalchemy import CheckConstraint, Column, Date, DateTime, ForeignKey, Integer, Numeric, String, Text, UniqueConstraint
|
||||
from sqlalchemy.orm import relationship
|
||||
from sqlalchemy.sql import func
|
||||
|
||||
from app.database.database import Base
|
||||
|
||||
|
||||
class Payment(Base):
|
||||
__tablename__ = "payments"
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
project_id = Column(Integer, ForeignKey("projects.id"), nullable=False, index=True)
|
||||
date = Column(Date, nullable=False, index=True)
|
||||
document_number = Column(String, nullable=True)
|
||||
amount = Column(Numeric(18, 2), nullable=False)
|
||||
currency = Column(String, nullable=False, default="RUB")
|
||||
comment = Column(Text)
|
||||
status = Column(String, nullable=False, default="active", index=True)
|
||||
created_at = Column(DateTime, nullable=False, server_default=func.now())
|
||||
updated_at = Column(DateTime, nullable=False, server_default=func.now(), onupdate=func.now())
|
||||
|
||||
project = relationship("Project")
|
||||
allocations = relationship("PaymentAllocation", back_populates="payment", cascade="all, delete-orphan")
|
||||
|
||||
|
||||
class PaymentAllocation(Base):
|
||||
__tablename__ = "payment_allocations"
|
||||
__table_args__ = (
|
||||
UniqueConstraint("payment_id", "ks3_id", name="uq_payment_ks3"),
|
||||
CheckConstraint("amount > 0", name="ck_payment_alloc_positive"),
|
||||
)
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
payment_id = Column(Integer, ForeignKey("payments.id", ondelete="CASCADE"), nullable=False, index=True)
|
||||
ks3_id = Column(Integer, ForeignKey("ks3_documents.id"), nullable=False, index=True)
|
||||
amount = Column(Numeric(18, 2), nullable=False)
|
||||
|
||||
payment = relationship("Payment", back_populates="allocations")
|
||||
ks3 = relationship("KS3")
|
||||
+65
-1
@@ -1,9 +1,10 @@
|
||||
from fastapi import APIRouter, Depends, HTTPException, Request, Form, UploadFile, File
|
||||
from fastapi.responses import RedirectResponse
|
||||
from sqlalchemy.orm import Session
|
||||
from app.database import database
|
||||
from app.models import project, boq
|
||||
from app.models.daily_report import DailyReport, DailyReportItem
|
||||
from app.importer import excel_importer
|
||||
from typing import List
|
||||
import os
|
||||
from decimal import Decimal
|
||||
from pathlib import Path
|
||||
@@ -11,6 +12,19 @@ from pathlib import Path
|
||||
router = APIRouter()
|
||||
UPLOAD_DIR = Path(__file__).resolve().parents[1] / "uploads"
|
||||
|
||||
|
||||
def _completed_quantities(db, project_id, items):
|
||||
item_ids = [item.id for item in items]
|
||||
if not item_ids:
|
||||
return {}
|
||||
rows = db.query(DailyReportItem.work_item_id, DailyReportItem.completed_quantity).join(
|
||||
DailyReport, DailyReport.id == DailyReportItem.daily_report_id
|
||||
).filter(DailyReport.project_id == project_id, DailyReportItem.work_item_id.in_(item_ids)).all()
|
||||
totals = {}
|
||||
for wid, qty in rows:
|
||||
totals[wid] = totals.get(wid, Decimal("0")) + Decimal(str(qty or 0))
|
||||
return totals
|
||||
|
||||
# Dependency
|
||||
def get_db():
|
||||
db = database.SessionLocal()
|
||||
@@ -79,8 +93,58 @@ async def view_boq_document(request: Request, project_id: int, document_id: int,
|
||||
"document_title": document_title,
|
||||
"systems": tree, "total": total,
|
||||
"unassigned_items": [item for item in items if item.system_id is None or item.section_id is None],
|
||||
"completed_by_item": _completed_quantities(db, project_id, items),
|
||||
"has_history": _has_history(db, items),
|
||||
})
|
||||
|
||||
|
||||
def _has_history(db, items):
|
||||
"""Check if BOQ items participate in DailyReports / KS2 / KS3 / Payments."""
|
||||
item_ids = [i.id for i in items]
|
||||
if not item_ids:
|
||||
return False
|
||||
if db.query(DailyReportItem).filter(DailyReportItem.work_item_id.in_(item_ids)).first():
|
||||
return True
|
||||
from app.models.ks2 import KS2Item
|
||||
if db.query(KS2Item).filter(KS2Item.work_item_id.in_(item_ids)).first():
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
@router.post("/{project_id}/documents/{document_id}/delete")
|
||||
async def delete_boq_document(project_id: int, document_id: int, db: Session = Depends(get_db)):
|
||||
document = db.query(boq.BoqDocument).filter(
|
||||
boq.BoqDocument.id == document_id, boq.BoqDocument.project_id == project_id
|
||||
).first()
|
||||
if document is None:
|
||||
raise HTTPException(status_code=404, detail="Document not found")
|
||||
items = db.query(boq.WorkItem).filter(boq.WorkItem.boq_document_id == document_id).all()
|
||||
if _has_history(db, items):
|
||||
raise HTTPException(status_code=400, detail="Cannot delete document with history. Archive it instead.")
|
||||
try:
|
||||
for item in items:
|
||||
db.delete(item)
|
||||
db.delete(document)
|
||||
db.commit()
|
||||
except Exception:
|
||||
db.rollback()
|
||||
raise HTTPException(status_code=400, detail="Cannot delete document with related data")
|
||||
return RedirectResponse(f"/boq/{project_id}", status_code=303)
|
||||
|
||||
|
||||
@router.post("/{project_id}/documents/{document_id}/archive")
|
||||
async def archive_boq_document(project_id: int, document_id: int, db: Session = Depends(get_db)):
|
||||
document = db.query(boq.BoqDocument).filter(
|
||||
boq.BoqDocument.id == document_id, boq.BoqDocument.project_id == project_id
|
||||
).first()
|
||||
if document is None:
|
||||
raise HTTPException(status_code=404, detail="Document not found")
|
||||
if document.version == "archived":
|
||||
raise HTTPException(status_code=400, detail="Already archived")
|
||||
document.version = "archived"
|
||||
db.commit()
|
||||
return RedirectResponse(f"/boq/{project_id}/documents/{document_id}", status_code=303)
|
||||
|
||||
@router.post("/{project_id}/import/upload")
|
||||
async def upload_excel_file(
|
||||
request: Request,
|
||||
|
||||
@@ -9,6 +9,7 @@ from sqlalchemy.orm import Session
|
||||
from app.database.database import SessionLocal
|
||||
from app.models import boq, project
|
||||
from app.models.daily_report import DailyReport, DailyReportItem
|
||||
from app.models.ks2 import KS2ItemSource
|
||||
from app.services.effective_plan import build_effective_plan
|
||||
|
||||
router = APIRouter()
|
||||
@@ -207,6 +208,15 @@ async def update_daily_report(request: Request, project_id: int, report_id: int,
|
||||
selection = "unclassified" if system_id is None else system_id
|
||||
return _render_form(request, db, project_obj, selection, report, errors)
|
||||
_validate_work_items(db, project_id, system_id, quantities)
|
||||
closed_ids = _ks2_closed_item_ids(db, report.id)
|
||||
if closed_ids:
|
||||
existing = {line.id: line for line in report.items}
|
||||
for line_id in closed_ids:
|
||||
line = existing.get(line_id)
|
||||
if line and line.work_item_id not in quantities:
|
||||
raise HTTPException(status_code=400, detail="Cannot remove quantity closed in KS-2")
|
||||
if line and quantities.get(line.work_item_id) != line.completed_quantity:
|
||||
raise HTTPException(status_code=400, detail="Cannot change quantity closed in KS-2")
|
||||
report.system_id = system_id
|
||||
report.notes = notes.strip() or None
|
||||
db.query(DailyReportItem).filter(DailyReportItem.daily_report_id == report.id).delete()
|
||||
@@ -242,3 +252,23 @@ def _validate_work_items(db, project_id, system_id, quantities):
|
||||
if row.item.system_id == system_id}
|
||||
if effective_ids.intersection(quantities) != set(quantities):
|
||||
raise HTTPException(status_code=400, detail="One or more work items are not part of the selected system effective plan")
|
||||
|
||||
|
||||
def _ks2_closed_item_ids(db, report_id):
|
||||
"""Return DailyReportItem ids already closed via KS-2 for this report."""
|
||||
rows = db.query(KS2ItemSource.daily_report_item_id).join(
|
||||
DailyReportItem, DailyReportItem.id == KS2ItemSource.daily_report_item_id
|
||||
).filter(DailyReportItem.daily_report_id == report_id).distinct().all()
|
||||
return {r[0] for r in rows}
|
||||
|
||||
|
||||
@router.post("/{project_id}/daily-reports/{report_id}/delete")
|
||||
async def delete_daily_report(project_id: int, report_id: int, db: Session = Depends(get_db)):
|
||||
_project_or_404(db, project_id)
|
||||
report = _report_or_404(db, project_id, report_id)
|
||||
closed_ids = _ks2_closed_item_ids(db, report.id)
|
||||
if closed_ids:
|
||||
raise HTTPException(status_code=400, detail="Cannot delete daily report with quantities closed in KS-2")
|
||||
db.delete(report)
|
||||
db.commit()
|
||||
return RedirectResponse(f"/projects/{project_id}/daily-reports", status_code=303)
|
||||
|
||||
+56
-2
@@ -1,9 +1,10 @@
|
||||
from datetime import date
|
||||
from decimal import Decimal
|
||||
from pathlib import Path
|
||||
import re
|
||||
|
||||
from fastapi import APIRouter, Depends, Form, HTTPException, Request
|
||||
from fastapi.responses import RedirectResponse
|
||||
from fastapi.responses import RedirectResponse, Response
|
||||
from fastapi.templating import Jinja2Templates
|
||||
from sqlalchemy.orm import Session, joinedload
|
||||
|
||||
@@ -147,4 +148,57 @@ async def ks2_issue(project_id: int, ks2_id: int, db: Session = Depends(get_db))
|
||||
issue_ks2(db, project_id, ks2_id)
|
||||
except KS2ValidationError as exc:
|
||||
raise HTTPException(status_code=409, detail=str(exc)) from exc
|
||||
return RedirectResponse(f"/projects/{project_id}/ks2/{ks2_id}", status_code=303)
|
||||
return RedirectResponse(f"/projects/{project_id}/ks2/{ks2_id}", status_code=303)
|
||||
|
||||
|
||||
@router.post("/{project_id}/ks2/{ks2_id}/cancel")
|
||||
async def ks2_cancel(project_id: int, ks2_id: int, db: Session = Depends(get_db)):
|
||||
from app.models.ks2 import KS2
|
||||
doc = db.query(KS2).filter(KS2.id == ks2_id, KS2.project_id == project_id).first()
|
||||
if doc is None:
|
||||
raise HTTPException(status_code=404, detail="KS-2 not found")
|
||||
if doc.status == "cancelled":
|
||||
raise HTTPException(status_code=400, detail="KS-2 already cancelled")
|
||||
doc.status = "cancelled"
|
||||
db.commit()
|
||||
return RedirectResponse(f"/projects/{project_id}/ks2/{ks2_id}", status_code=303)
|
||||
|
||||
|
||||
def _safe_filename(number: str, dt) -> str:
|
||||
raw = f"КС-2 №{number} от {dt.strftime('%d.%m.%Y')}"
|
||||
return re.sub(r'[<>:"/\\|?*]', "_", raw)
|
||||
|
||||
|
||||
def _content_disposition(filename: str) -> str:
|
||||
from urllib.parse import quote
|
||||
return f"attachment; filename*=UTF-8''{quote(filename)}"
|
||||
|
||||
|
||||
@router.get("/{project_id}/ks2/{ks2_id}/export/excel")
|
||||
async def ks2_export_excel(project_id: int, ks2_id: int, db: Session = Depends(get_db)):
|
||||
document = _document(db, project_id, ks2_id)
|
||||
from app.exporters.ks2_dto import build_ks2_export_dto
|
||||
from app.exporters.excel.ks2_renderer import render_ks2_excel
|
||||
dto = build_ks2_export_dto(db, document)
|
||||
data = render_ks2_excel(dto)
|
||||
filename = _safe_filename(document.number, document.date) + ".xlsx"
|
||||
return Response(
|
||||
content=data,
|
||||
media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
||||
headers={"Content-Disposition": _content_disposition(filename)},
|
||||
)
|
||||
|
||||
|
||||
@router.get("/{project_id}/ks2/{ks2_id}/export/word")
|
||||
async def ks2_export_word(project_id: int, ks2_id: int, db: Session = Depends(get_db)):
|
||||
document = _document(db, project_id, ks2_id)
|
||||
from app.exporters.ks2_dto import build_ks2_export_dto
|
||||
from app.exporters.word.ks2_renderer import render_ks2_word
|
||||
dto = build_ks2_export_dto(db, document)
|
||||
data = render_ks2_word(dto)
|
||||
filename = _safe_filename(document.number, document.date) + ".docx"
|
||||
return Response(
|
||||
content=data,
|
||||
media_type="application/vnd.openxmlformats-officedocument.wordprocessingml.document",
|
||||
headers={"Content-Disposition": _content_disposition(filename)},
|
||||
)
|
||||
@@ -0,0 +1,167 @@
|
||||
from datetime import date
|
||||
from decimal import Decimal
|
||||
from pathlib import Path
|
||||
|
||||
from fastapi import APIRouter, Depends, Form, HTTPException, Request
|
||||
from fastapi.responses import RedirectResponse
|
||||
from fastapi.templating import Jinja2Templates
|
||||
from sqlalchemy.orm import Session, joinedload
|
||||
|
||||
from app.database.database import get_db
|
||||
from app.models.project import Project
|
||||
from app.models.ks2 import KS2
|
||||
from app.models.ks3 import KS3, KS3KS2
|
||||
from app.services.ks3_service import (
|
||||
KS3ValidationError, available_ks2, issue_ks3, project_ks3_totals, save_draft,
|
||||
)
|
||||
from app.utils.formatters import format_money
|
||||
|
||||
|
||||
def _quantity2(value):
|
||||
try:
|
||||
return f"{Decimal(str(value if value is not None else 0)):.2f}"
|
||||
except Exception:
|
||||
return "0.00"
|
||||
|
||||
|
||||
router = APIRouter()
|
||||
templates = Jinja2Templates(directory=Path(__file__).resolve().parents[1] / "templates")
|
||||
templates.env.filters["money"] = format_money
|
||||
templates.env.filters["quantity2"] = _quantity2
|
||||
|
||||
|
||||
def _project(db, project_id):
|
||||
obj = db.query(Project).filter(Project.id == project_id).first()
|
||||
if obj is None:
|
||||
raise HTTPException(status_code=404, detail="Проект не найден")
|
||||
return obj
|
||||
|
||||
|
||||
def _document(db, project_id, ks3_id):
|
||||
doc = db.query(KS3).options(
|
||||
joinedload(KS3.links).joinedload(KS3KS2.ks2).joinedload(KS2.items)
|
||||
).filter(KS3.id == ks3_id, KS3.project_id == project_id).first()
|
||||
if doc is None:
|
||||
raise HTTPException(status_code=404, detail="КС-3 не найден")
|
||||
return doc
|
||||
|
||||
|
||||
def _ks2_total(ks2):
|
||||
return sum(Decimal(str(item.amount or 0)) for item in ks2.items)
|
||||
|
||||
|
||||
def _render_form(request, db, project, document=None, error=None, status_code=200):
|
||||
available = available_ks2(db, project.id)
|
||||
selected_ids = {link.ks2_id for link in document.links} if document else set()
|
||||
return templates.TemplateResponse(name="ks3/form.html", context={
|
||||
"request": request, "project": project, "document": document,
|
||||
"available_ks2": available, "selected_ids": selected_ids, "error": error,
|
||||
}, status_code=status_code)
|
||||
|
||||
|
||||
@router.get("/{project_id}/ks3")
|
||||
async def ks3_list(request: Request, project_id: int, db: Session = Depends(get_db)):
|
||||
project = _project(db, project_id)
|
||||
rows = project_ks3_totals(db, project_id)
|
||||
return templates.TemplateResponse(name="ks3/list.html", context={
|
||||
"request": request, "project": project, "rows": rows,
|
||||
})
|
||||
|
||||
|
||||
@router.get("/{project_id}/ks3/new")
|
||||
async def ks3_new(request: Request, project_id: int, db: Session = Depends(get_db)):
|
||||
project = _project(db, project_id)
|
||||
return _render_form(request, db, project)
|
||||
|
||||
|
||||
@router.post("/{project_id}/ks3")
|
||||
async def ks3_create(request: Request, project_id: int,
|
||||
number: str = Form(...), document_date: str = Form(...),
|
||||
comment: str = Form(""),
|
||||
reporting_period_from: str = Form(""), reporting_period_to: str = Form(""),
|
||||
db: Session = Depends(get_db)):
|
||||
project = _project(db, project_id)
|
||||
form = await request.form()
|
||||
ks2_ids = [int(v) for k, v in form.multi_items() if k == "ks2_ids"]
|
||||
try:
|
||||
parsed_date = date.fromisoformat(document_date)
|
||||
document = save_draft(
|
||||
db, project_id, number, parsed_date, comment, ks2_ids,
|
||||
reporting_period_from=reporting_period_from or None,
|
||||
reporting_period_to=reporting_period_to or None,
|
||||
)
|
||||
except ValueError as exc:
|
||||
return _render_form(request, db, project, error=str(exc), status_code=400)
|
||||
return RedirectResponse(f"/projects/{project_id}/ks3/{document.id}", status_code=303)
|
||||
|
||||
|
||||
@router.get("/{project_id}/ks3/{ks3_id}")
|
||||
async def ks3_view(request: Request, project_id: int, ks3_id: int, db: Session = Depends(get_db)):
|
||||
project = _project(db, project_id)
|
||||
document = _document(db, project_id, ks3_id)
|
||||
total = Decimal("0")
|
||||
ks2_rows = []
|
||||
for link in document.links:
|
||||
if link.ks2:
|
||||
ks2_total = _ks2_total(link.ks2)
|
||||
total += ks2_total
|
||||
ks2_rows.append({"ks2": link.ks2, "total": ks2_total})
|
||||
return templates.TemplateResponse(name="ks3/view.html", context={
|
||||
"request": request, "project": project, "document": document,
|
||||
"ks2_rows": ks2_rows, "total": total,
|
||||
})
|
||||
|
||||
|
||||
@router.get("/{project_id}/ks3/{ks3_id}/edit")
|
||||
async def ks3_edit(request: Request, project_id: int, ks3_id: int, db: Session = Depends(get_db)):
|
||||
project = _project(db, project_id)
|
||||
document = _document(db, project_id, ks3_id)
|
||||
if document.status != "draft":
|
||||
raise HTTPException(status_code=409, detail="Проведённый КС-3 нельзя редактировать")
|
||||
return _render_form(request, db, project, document)
|
||||
|
||||
|
||||
@router.post("/{project_id}/ks3/{ks3_id}/edit")
|
||||
async def ks3_update(request: Request, project_id: int, ks3_id: int,
|
||||
number: str = Form(...), document_date: str = Form(...),
|
||||
comment: str = Form(""),
|
||||
reporting_period_from: str = Form(""), reporting_period_to: str = Form(""),
|
||||
db: Session = Depends(get_db)):
|
||||
project = _project(db, project_id)
|
||||
form = await request.form()
|
||||
ks2_ids = [int(v) for k, v in form.multi_items() if k == "ks2_ids"]
|
||||
try:
|
||||
parsed_date = date.fromisoformat(document_date)
|
||||
document = save_draft(
|
||||
db, project_id, number, parsed_date, comment, ks2_ids,
|
||||
reporting_period_from=reporting_period_from or None,
|
||||
reporting_period_to=reporting_period_to or None,
|
||||
ks3_id=ks3_id,
|
||||
)
|
||||
except ValueError as exc:
|
||||
db.expire_all()
|
||||
document = _document(db, project_id, ks3_id)
|
||||
return _render_form(request, db, project, document=document, error=str(exc), status_code=400)
|
||||
return RedirectResponse(f"/projects/{project_id}/ks3/{document.id}", status_code=303)
|
||||
|
||||
|
||||
@router.post("/{project_id}/ks3/{ks3_id}/issue")
|
||||
async def ks3_issue(project_id: int, ks3_id: int, db: Session = Depends(get_db)):
|
||||
try:
|
||||
issue_ks3(db, project_id, ks3_id)
|
||||
except KS3ValidationError as exc:
|
||||
raise HTTPException(status_code=409, detail=str(exc)) from exc
|
||||
return RedirectResponse(f"/projects/{project_id}/ks3/{ks3_id}", status_code=303)
|
||||
|
||||
|
||||
@router.post("/{project_id}/ks3/{ks3_id}/cancel")
|
||||
async def ks3_cancel(project_id: int, ks3_id: int, db: Session = Depends(get_db)):
|
||||
from app.models.ks3 import KS3
|
||||
doc = db.query(KS3).filter(KS3.id == ks3_id, KS3.project_id == project_id).first()
|
||||
if doc is None:
|
||||
raise HTTPException(status_code=404, detail="KS-3 not found")
|
||||
if doc.status == "cancelled":
|
||||
raise HTTPException(status_code=400, detail="KS-3 already cancelled")
|
||||
doc.status = "cancelled"
|
||||
db.commit()
|
||||
return RedirectResponse(f"/projects/{project_id}/ks3/{ks3_id}", status_code=303)
|
||||
@@ -0,0 +1,104 @@
|
||||
from datetime import date
|
||||
from decimal import Decimal
|
||||
from pathlib import Path
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Request
|
||||
from fastapi.templating import Jinja2Templates
|
||||
from sqlalchemy.orm import Session, joinedload
|
||||
|
||||
from app.database.database import get_db
|
||||
from app.models.boq import System, WorkItem
|
||||
from app.models.daily_report import DailyReport, DailyReportItem
|
||||
from app.models.project import Project
|
||||
|
||||
|
||||
def _quantity2(value):
|
||||
try:
|
||||
return f"{Decimal(str(value if value is not None else 0)):.2f}"
|
||||
except Exception:
|
||||
return "0.00"
|
||||
|
||||
|
||||
router = APIRouter()
|
||||
templates = Jinja2Templates(directory=Path(__file__).resolve().parents[1] / "templates")
|
||||
templates.env.filters["quantity2"] = _quantity2
|
||||
|
||||
|
||||
def _project(db, project_id):
|
||||
obj = db.query(Project).filter(Project.id == project_id).first()
|
||||
if obj is None:
|
||||
raise HTTPException(status_code=404, detail="Проект не найден")
|
||||
return obj
|
||||
|
||||
|
||||
@router.get("/{project_id}/ks6a")
|
||||
async def ks6a_journal(
|
||||
request: Request,
|
||||
project_id: int,
|
||||
date_from: str = "",
|
||||
date_to: str = "",
|
||||
system_id: str = "",
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
project = _project(db, project_id)
|
||||
systems = db.query(System).filter(
|
||||
System.project_id == project_id
|
||||
).order_by(System.sort_order, System.id).all()
|
||||
|
||||
rows = []
|
||||
total_count = 0
|
||||
parsed_from = None
|
||||
parsed_to = None
|
||||
error = None
|
||||
|
||||
if date_from and date_to:
|
||||
try:
|
||||
parsed_from = date.fromisoformat(date_from)
|
||||
parsed_to = date.fromisoformat(date_to)
|
||||
except ValueError:
|
||||
error = "Неверный формат даты"
|
||||
else:
|
||||
if parsed_to < parsed_from:
|
||||
error = "Дата окончания не может быть раньше даты начала"
|
||||
|
||||
if parsed_from and parsed_to and not error:
|
||||
query = db.query(DailyReportItem).join(
|
||||
DailyReport, DailyReport.id == DailyReportItem.daily_report_id
|
||||
).join(
|
||||
WorkItem, WorkItem.id == DailyReportItem.work_item_id
|
||||
).options(
|
||||
joinedload(DailyReportItem.work_item),
|
||||
joinedload(DailyReportItem.report),
|
||||
).filter(
|
||||
DailyReport.project_id == project_id,
|
||||
DailyReport.report_date >= parsed_from,
|
||||
DailyReport.report_date <= parsed_to,
|
||||
)
|
||||
|
||||
if system_id and system_id != "all":
|
||||
try:
|
||||
sid = int(system_id)
|
||||
except (ValueError, TypeError):
|
||||
error = "Некорректный идентификатор системы"
|
||||
else:
|
||||
query = query.filter(WorkItem.system_id == sid)
|
||||
|
||||
if not error:
|
||||
rows = query.order_by(
|
||||
DailyReport.report_date,
|
||||
DailyReport.id,
|
||||
DailyReportItem.id,
|
||||
).all()
|
||||
total_count = len(rows)
|
||||
|
||||
return templates.TemplateResponse(name="ks6a/journal.html", context={
|
||||
"request": request,
|
||||
"project": project,
|
||||
"systems": systems,
|
||||
"rows": rows,
|
||||
"total_count": total_count,
|
||||
"date_from": date_from,
|
||||
"date_to": date_to,
|
||||
"system_id": system_id,
|
||||
"error": error,
|
||||
})
|
||||
@@ -0,0 +1,176 @@
|
||||
from datetime import date
|
||||
from decimal import Decimal
|
||||
from pathlib import Path
|
||||
|
||||
from fastapi import APIRouter, Depends, Form, HTTPException, Request
|
||||
from fastapi.responses import RedirectResponse
|
||||
from fastapi.templating import Jinja2Templates
|
||||
from sqlalchemy.orm import Session, joinedload
|
||||
|
||||
from app.database.database import get_db
|
||||
from app.models.project import Project
|
||||
from app.models.payment import Payment, PaymentAllocation
|
||||
from app.services.payment_service import (
|
||||
PaymentValidationError, available_ks3_for_payment, delete_payment,
|
||||
project_payments, save_payment,
|
||||
)
|
||||
from app.utils.formatters import format_money
|
||||
|
||||
|
||||
def _quantity2(value):
|
||||
try:
|
||||
return f"{Decimal(str(value if value is not None else 0)):.2f}"
|
||||
except Exception:
|
||||
return "0.00"
|
||||
|
||||
|
||||
router = APIRouter()
|
||||
templates = Jinja2Templates(directory=Path(__file__).resolve().parents[1] / "templates")
|
||||
templates.env.filters["money"] = format_money
|
||||
templates.env.filters["quantity2"] = _quantity2
|
||||
|
||||
|
||||
def _project(db, project_id):
|
||||
obj = db.query(Project).filter(Project.id == project_id).first()
|
||||
if obj is None:
|
||||
raise HTTPException(status_code=404, detail="Проект не найден")
|
||||
return obj
|
||||
|
||||
|
||||
def _payment(db, project_id, payment_id):
|
||||
p = db.query(Payment).options(
|
||||
joinedload(Payment.allocations).joinedload(PaymentAllocation.ks3)
|
||||
).filter(Payment.id == payment_id, Payment.project_id == project_id).first()
|
||||
if p is None:
|
||||
raise HTTPException(status_code=404, detail="Платёж не найден")
|
||||
return p
|
||||
|
||||
|
||||
def _render_form(request, db, project, payment=None, error=None, status_code=200):
|
||||
available = available_ks3_for_payment(db, project.id, exclude_payment_id=payment.id if payment else None)
|
||||
current_allocs = {a.ks3_id: Decimal(str(a.amount)) for a in payment.allocations} if payment else {}
|
||||
return templates.TemplateResponse(name="payments/form.html", context={
|
||||
"request": request, "project": project, "payment": payment,
|
||||
"available_ks3": available, "current_allocs": current_allocs, "error": error,
|
||||
}, status_code=status_code)
|
||||
|
||||
|
||||
@router.get("/{project_id}/payments")
|
||||
async def payment_list(request: Request, project_id: int, db: Session = Depends(get_db)):
|
||||
project = _project(db, project_id)
|
||||
rows = project_payments(db, project_id)
|
||||
return templates.TemplateResponse(name="payments/list.html", context={
|
||||
"request": request, "project": project, "rows": rows,
|
||||
})
|
||||
|
||||
|
||||
@router.get("/{project_id}/payments/new")
|
||||
async def payment_new(request: Request, project_id: int, db: Session = Depends(get_db)):
|
||||
project = _project(db, project_id)
|
||||
return _render_form(request, db, project)
|
||||
|
||||
|
||||
@router.post("/{project_id}/payments")
|
||||
async def payment_create(request: Request, project_id: int,
|
||||
payment_date: str = Form(...),
|
||||
document_number: str = Form(""),
|
||||
amount: str = Form(...), currency: str = Form("RUB"),
|
||||
comment: str = Form(""),
|
||||
db: Session = Depends(get_db)):
|
||||
project = _project(db, project_id)
|
||||
form = await request.form()
|
||||
allocations = []
|
||||
for k, v in form.multi_items():
|
||||
if k.startswith("alloc_") and v.strip():
|
||||
try:
|
||||
ks3_id = int(k.removeprefix("alloc_"))
|
||||
alloc_amount = Decimal(v.strip().replace(",", "."))
|
||||
if alloc_amount > 0:
|
||||
allocations.append({"ks3_id": ks3_id, "amount": alloc_amount})
|
||||
except (ValueError, TypeError):
|
||||
pass
|
||||
try:
|
||||
parsed_date = date.fromisoformat(payment_date)
|
||||
parsed_amount = Decimal(amount.strip().replace(",", "."))
|
||||
payment = save_payment(
|
||||
db, project_id, parsed_date, parsed_amount, currency, comment,
|
||||
allocations, document_number=document_number or None,
|
||||
)
|
||||
except ValueError as exc:
|
||||
return _render_form(request, db, project, error=str(exc), status_code=400)
|
||||
return RedirectResponse(f"/projects/{project_id}/payments/{payment.id}", status_code=303)
|
||||
|
||||
|
||||
@router.get("/{project_id}/payments/{payment_id}")
|
||||
async def payment_view(request: Request, project_id: int, payment_id: int, db: Session = Depends(get_db)):
|
||||
project = _project(db, project_id)
|
||||
payment = _payment(db, project_id, payment_id)
|
||||
allocated = sum(Decimal(str(a.amount)) for a in payment.allocations)
|
||||
unallocated = max(Decimal(str(payment.amount)) - allocated, Decimal("0"))
|
||||
return templates.TemplateResponse(name="payments/view.html", context={
|
||||
"request": request, "project": project, "payment": payment,
|
||||
"allocated": allocated, "unallocated": unallocated,
|
||||
})
|
||||
|
||||
|
||||
@router.get("/{project_id}/payments/{payment_id}/edit")
|
||||
async def payment_edit(request: Request, project_id: int, payment_id: int, db: Session = Depends(get_db)):
|
||||
project = _project(db, project_id)
|
||||
payment = _payment(db, project_id, payment_id)
|
||||
return _render_form(request, db, project, payment)
|
||||
|
||||
|
||||
@router.post("/{project_id}/payments/{payment_id}/edit")
|
||||
async def payment_update(request: Request, project_id: int, payment_id: int,
|
||||
payment_date: str = Form(...),
|
||||
document_number: str = Form(""),
|
||||
amount: str = Form(...), currency: str = Form("RUB"),
|
||||
comment: str = Form(""),
|
||||
db: Session = Depends(get_db)):
|
||||
project = _project(db, project_id)
|
||||
form = await request.form()
|
||||
allocations = []
|
||||
for k, v in form.multi_items():
|
||||
if k.startswith("alloc_") and v.strip():
|
||||
try:
|
||||
ks3_id = int(k.removeprefix("alloc_"))
|
||||
alloc_amount = Decimal(v.strip().replace(",", "."))
|
||||
if alloc_amount > 0:
|
||||
allocations.append({"ks3_id": ks3_id, "amount": alloc_amount})
|
||||
except (ValueError, TypeError):
|
||||
pass
|
||||
try:
|
||||
parsed_date = date.fromisoformat(payment_date)
|
||||
parsed_amount = Decimal(amount.strip().replace(",", "."))
|
||||
payment = save_payment(
|
||||
db, project_id, parsed_date, parsed_amount, currency, comment,
|
||||
allocations, document_number=document_number or None,
|
||||
payment_id=payment_id,
|
||||
)
|
||||
except ValueError as exc:
|
||||
db.expire_all()
|
||||
payment = _payment(db, project_id, payment_id)
|
||||
return _render_form(request, db, project, payment=payment, error=str(exc), status_code=400)
|
||||
return RedirectResponse(f"/projects/{project_id}/payments/{payment.id}", status_code=303)
|
||||
|
||||
|
||||
@router.post("/{project_id}/payments/{payment_id}/delete")
|
||||
async def payment_delete(project_id: int, payment_id: int, db: Session = Depends(get_db)):
|
||||
try:
|
||||
delete_payment(db, project_id, payment_id)
|
||||
except PaymentValidationError as exc:
|
||||
raise HTTPException(status_code=409, detail=str(exc)) from exc
|
||||
return RedirectResponse(f"/projects/{project_id}/payments", status_code=303)
|
||||
|
||||
|
||||
@router.post("/{project_id}/payments/{payment_id}/cancel")
|
||||
async def payment_cancel(project_id: int, payment_id: int, db: Session = Depends(get_db)):
|
||||
from app.models.payment import Payment
|
||||
doc = db.query(Payment).filter(Payment.id == payment_id, Payment.project_id == project_id).first()
|
||||
if doc is None:
|
||||
raise HTTPException(status_code=404, detail="Payment not found")
|
||||
if doc.status == "cancelled":
|
||||
raise HTTPException(status_code=400, detail="Payment already cancelled")
|
||||
doc.status = "cancelled"
|
||||
db.commit()
|
||||
return RedirectResponse(f"/projects/{project_id}/payments/{payment_id}", status_code=303)
|
||||
@@ -8,6 +8,8 @@ from app.services.project_dashboard import build_project_dashboard
|
||||
from app.services.effective_plan import BaseBoqConfigurationError
|
||||
from app.models.daily_report import DailyReport
|
||||
from app.models.ks2 import KS2
|
||||
from app.models.ks3 import KS3
|
||||
from app.models.payment import Payment
|
||||
from app.models.work_journal import WorkJournalEntry
|
||||
from typing import List
|
||||
import os
|
||||
@@ -114,6 +116,24 @@ async def read_project(request: Request, project_id: int, db: Session = Depends(
|
||||
raise HTTPException(status_code=409, detail=str(exc)) from exc
|
||||
daily_reports = db.query(DailyReport).filter(DailyReport.project_id == project_id).count()
|
||||
ks2_count = db.query(KS2).filter(KS2.project_id == project_id).count()
|
||||
ks3_count = db.query(KS3).filter(KS3.project_id == project_id).count()
|
||||
payments_count = db.query(Payment).filter(Payment.project_id == project_id).count()
|
||||
from app.models.agreement import Agreement
|
||||
agreements_count = db.query(Agreement).filter(Agreement.project_id == project_id).count()
|
||||
from app.services.payment_service import ks3_payment_summary
|
||||
payment_summary = ks3_payment_summary(db, project_id)
|
||||
|
||||
# Build document tree: base BOQ docs with scoped agreements + project-wide agreements
|
||||
all_agreements = db.query(Agreement).filter(
|
||||
Agreement.project_id == project_id
|
||||
).order_by(Agreement.id).all()
|
||||
base_docs = [d for d in boq_docs if d.agreement_id is None]
|
||||
doc_tree = []
|
||||
for doc in base_docs:
|
||||
scoped = [a for a in all_agreements if a.boq_document_id == doc.id]
|
||||
doc_tree.append({"doc": doc, "agreements": scoped})
|
||||
project_wide = [a for a in all_agreements if a.boq_document_id is None]
|
||||
|
||||
journal_tasks = db.query(WorkJournalEntry).filter(
|
||||
WorkJournalEntry.project_id == project_id,
|
||||
WorkJournalEntry.type == "task",
|
||||
@@ -131,8 +151,14 @@ async def read_project(request: Request, project_id: int, db: Session = Depends(
|
||||
"boq_docs": boq_docs,
|
||||
"daily_reports_count": daily_reports,
|
||||
"ks2_count": ks2_count,
|
||||
"ks3_count": ks3_count,
|
||||
"payments_count": payments_count,
|
||||
"agreements_count": agreements_count,
|
||||
"payment_summary": payment_summary,
|
||||
"journal_tasks": journal_tasks,
|
||||
"journal_notes": journal_notes,
|
||||
"doc_tree": doc_tree,
|
||||
"project_wide_agreements": project_wide,
|
||||
**dashboard,
|
||||
})
|
||||
|
||||
@@ -242,3 +268,43 @@ async def import_boq(request: Request, project_id: int, db: Session = Depends(ge
|
||||
"request": request,
|
||||
"project": db_project
|
||||
})
|
||||
|
||||
|
||||
def _has_financial_history(db, project_id):
|
||||
"""Check if project has issued KS-2/KS-3 or payments."""
|
||||
from app.models.ks2 import KS2
|
||||
from app.models.ks3 import KS3
|
||||
from app.models.payment import Payment
|
||||
if db.query(KS2).filter(KS2.project_id == project_id, KS2.status == "issued").first():
|
||||
return True
|
||||
if db.query(KS3).filter(KS3.project_id == project_id, KS3.status == "issued").first():
|
||||
return True
|
||||
if db.query(Payment).filter(Payment.project_id == project_id).first():
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
@router.post("/{project_id}/delete")
|
||||
async def delete_project(project_id: int, db: Session = Depends(get_db)):
|
||||
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")
|
||||
if _has_financial_history(db, project_id):
|
||||
raise HTTPException(status_code=400, detail="Cannot delete project with financial history. Archive it instead.")
|
||||
try:
|
||||
db.delete(db_project)
|
||||
db.commit()
|
||||
except Exception:
|
||||
db.rollback()
|
||||
raise HTTPException(status_code=400, detail="Cannot delete project with related data")
|
||||
return RedirectResponse(url="/projects/", status_code=303)
|
||||
|
||||
|
||||
@router.post("/{project_id}/archive")
|
||||
async def archive_project(project_id: int, db: Session = Depends(get_db)):
|
||||
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")
|
||||
db_project.status = "archived"
|
||||
db.commit()
|
||||
return RedirectResponse(url=f"/projects/{project_id}", status_code=303)
|
||||
|
||||
@@ -0,0 +1,174 @@
|
||||
from datetime import date
|
||||
from decimal import Decimal, InvalidOperation
|
||||
|
||||
from sqlalchemy.orm import Session, joinedload
|
||||
|
||||
from app.models.ks2 import KS2, KS2Item
|
||||
from app.models.ks3 import KS3, KS3KS2
|
||||
|
||||
ZERO = Decimal("0")
|
||||
|
||||
|
||||
class KS3ValidationError(ValueError):
|
||||
pass
|
||||
|
||||
|
||||
def _decimal(value):
|
||||
try:
|
||||
return Decimal(str(value)) if value is not None else ZERO
|
||||
except (InvalidOperation, ValueError, TypeError):
|
||||
return ZERO
|
||||
|
||||
|
||||
def _parse_date(value, label):
|
||||
if value is None or (isinstance(value, str) and not value.strip()):
|
||||
return None
|
||||
if isinstance(value, date):
|
||||
return value
|
||||
try:
|
||||
return date.fromisoformat(str(value).strip())
|
||||
except (ValueError, TypeError) as exc:
|
||||
raise KS3ValidationError(f"{label}: неверный формат даты") from exc
|
||||
|
||||
|
||||
def _ks2_total(ks2):
|
||||
return sum(_decimal(item.amount) for item in ks2.items)
|
||||
|
||||
|
||||
def available_ks2(db: Session, project_id: int):
|
||||
"""Return issued KS-2 documents for the project with their totals."""
|
||||
docs = db.query(KS2).options(joinedload(KS2.items)).filter(
|
||||
KS2.project_id == project_id,
|
||||
KS2.status == "issued",
|
||||
).order_by(KS2.date, KS2.id).all()
|
||||
result = []
|
||||
for doc in docs:
|
||||
result.append({
|
||||
"id": doc.id,
|
||||
"number": doc.number,
|
||||
"date": doc.date,
|
||||
"period_from": doc.reporting_period_from,
|
||||
"period_to": doc.reporting_period_to,
|
||||
"total": _ks2_total(doc),
|
||||
})
|
||||
return result
|
||||
|
||||
|
||||
def save_draft(db: Session, project_id: int, number: str, document_date: date,
|
||||
comment: str | None, ks2_ids: list[int],
|
||||
reporting_period_from=None, reporting_period_to=None,
|
||||
ks3_id: int | None = None):
|
||||
"""Create or update a KS-3 draft."""
|
||||
try:
|
||||
number = (number or "").strip()
|
||||
if not number:
|
||||
raise KS3ValidationError("Укажите номер КС-3")
|
||||
|
||||
period_from = _parse_date(reporting_period_from, "Период с")
|
||||
period_to = _parse_date(reporting_period_to, "Период по")
|
||||
if ks3_id is None:
|
||||
if period_from is None:
|
||||
raise KS3ValidationError("Укажите дату начала периода")
|
||||
if period_to is None:
|
||||
raise KS3ValidationError("Укажите дату окончания периода")
|
||||
if period_from is not None and period_to is not None and period_to < period_from:
|
||||
raise KS3ValidationError("Дата окончания периода не может быть раньше даты начала")
|
||||
|
||||
if not ks2_ids:
|
||||
raise KS3ValidationError("Выберите хотя бы один КС-2")
|
||||
if len(ks2_ids) != len(set(ks2_ids)):
|
||||
raise KS3ValidationError("Один и тот же КС-2 не может быть выбран дважды")
|
||||
|
||||
document = None
|
||||
if ks3_id is not None:
|
||||
document = db.query(KS3).filter(
|
||||
KS3.id == ks3_id, KS3.project_id == project_id
|
||||
).first()
|
||||
if document is None:
|
||||
raise KS3ValidationError("КС-3 не найден")
|
||||
if document.status != "draft":
|
||||
raise KS3ValidationError("Проведённый КС-3 нельзя редактировать")
|
||||
else:
|
||||
document = KS3(project_id=project_id, status="draft")
|
||||
db.add(document)
|
||||
|
||||
document.number = number
|
||||
document.date = document_date
|
||||
document.reporting_period_from = period_from
|
||||
document.reporting_period_to = period_to
|
||||
document.comment = comment.strip() or None if comment else None
|
||||
|
||||
# Validate all selected KS-2
|
||||
seen_ks2 = set()
|
||||
for ks2_id in ks2_ids:
|
||||
if ks2_id in seen_ks2:
|
||||
raise KS3ValidationError(f"КС-2 с id={ks2_id} выбран несколько раз")
|
||||
seen_ks2.add(ks2_id)
|
||||
ks2 = db.query(KS2).filter(KS2.id == ks2_id).first()
|
||||
if ks2 is None:
|
||||
raise KS3ValidationError(f"КС-2 с id={ks2_id} не найден")
|
||||
if ks2.project_id != project_id:
|
||||
raise KS3ValidationError(f"КС-2 №{ks2.number} не принадлежит этому проекту")
|
||||
if ks2.status != "issued":
|
||||
raise KS3ValidationError(f"КС-2 №{ks2.number} не проведён")
|
||||
|
||||
# Replace links
|
||||
document.links.clear()
|
||||
for ks2_id in seen_ks2:
|
||||
document.links.append(KS3KS2(ks2_id=ks2_id))
|
||||
|
||||
db.commit()
|
||||
db.refresh(document)
|
||||
return document
|
||||
except Exception:
|
||||
db.rollback()
|
||||
raise
|
||||
|
||||
|
||||
def issue_ks3(db: Session, project_id: int, ks3_id: int):
|
||||
"""Issue a KS-3 draft atomically."""
|
||||
try:
|
||||
document = db.query(KS3).options(
|
||||
joinedload(KS3.links).joinedload(KS3KS2.ks2).joinedload(KS2.items)
|
||||
).filter(KS3.id == ks3_id, KS3.project_id == project_id).first()
|
||||
if document is None:
|
||||
raise KS3ValidationError("КС-3 не найден")
|
||||
if document.status != "draft":
|
||||
raise KS3ValidationError("Можно провести только черновик КС-3")
|
||||
if not document.links:
|
||||
raise KS3ValidationError("В КС-3 нет выбранных КС-2")
|
||||
|
||||
# Re-validate all linked KS-2
|
||||
for link in document.links:
|
||||
ks2 = link.ks2
|
||||
if ks2 is None or ks2.project_id != project_id:
|
||||
raise KS3ValidationError("Один из выбранных КС-2 не найден в проекте")
|
||||
if ks2.status != "issued":
|
||||
raise KS3ValidationError(f"КС-2 №{ks2.number} не проведён")
|
||||
|
||||
document.status = "issued"
|
||||
db.commit()
|
||||
db.refresh(document)
|
||||
return document
|
||||
except Exception:
|
||||
db.rollback()
|
||||
raise
|
||||
|
||||
|
||||
def project_ks3_totals(db: Session, project_id: int):
|
||||
"""Return all KS-3 documents for a project with amounts."""
|
||||
documents = db.query(KS3).options(
|
||||
joinedload(KS3.links).joinedload(KS3KS2.ks2).joinedload(KS2.items)
|
||||
).filter(KS3.project_id == project_id).order_by(KS3.date.desc(), KS3.id.desc()).all()
|
||||
rows = []
|
||||
for doc in documents:
|
||||
total = ZERO
|
||||
for link in doc.links:
|
||||
if link.ks2:
|
||||
total += _ks2_total(link.ks2)
|
||||
rows.append({
|
||||
"document": doc,
|
||||
"ks2_count": len(doc.links),
|
||||
"amount": total,
|
||||
})
|
||||
return rows
|
||||
@@ -0,0 +1,220 @@
|
||||
from datetime import date
|
||||
from decimal import Decimal, InvalidOperation
|
||||
|
||||
from sqlalchemy import func
|
||||
from sqlalchemy.orm import Session, joinedload
|
||||
|
||||
from app.models.ks3 import KS3, KS3KS2
|
||||
from app.models.ks2 import KS2, KS2Item
|
||||
from app.models.payment import Payment, PaymentAllocation
|
||||
|
||||
ZERO = Decimal("0")
|
||||
|
||||
|
||||
class PaymentValidationError(ValueError):
|
||||
pass
|
||||
|
||||
|
||||
def _decimal(value):
|
||||
try:
|
||||
return Decimal(str(value)) if value is not None else ZERO
|
||||
except (InvalidOperation, ValueError, TypeError):
|
||||
return ZERO
|
||||
|
||||
|
||||
def _parse_date(value, label):
|
||||
if value is None or (isinstance(value, str) and not value.strip()):
|
||||
return None
|
||||
if isinstance(value, date):
|
||||
return value
|
||||
try:
|
||||
return date.fromisoformat(str(value).strip())
|
||||
except (ValueError, TypeError) as exc:
|
||||
raise PaymentValidationError(f"{label}: неверный формат даты") from exc
|
||||
|
||||
|
||||
def _ks3_total(ks3_doc):
|
||||
total = ZERO
|
||||
for link in ks3_doc.links:
|
||||
if link.ks2:
|
||||
total += sum(_decimal(item.amount) for item in link.ks2.items)
|
||||
return total
|
||||
|
||||
|
||||
def _ks3_paid(db, ks3_id, exclude_payment_id=None):
|
||||
"""Total paid amount for a KS-3, optionally excluding one payment."""
|
||||
q = db.query(func.coalesce(func.sum(PaymentAllocation.amount), ZERO)).join(
|
||||
Payment, Payment.id == PaymentAllocation.payment_id
|
||||
).filter(
|
||||
PaymentAllocation.ks3_id == ks3_id,
|
||||
Payment.status != "cancelled",
|
||||
)
|
||||
if exclude_payment_id is not None:
|
||||
q = q.filter(PaymentAllocation.payment_id != exclude_payment_id)
|
||||
return Decimal(str(q.scalar()))
|
||||
|
||||
|
||||
def ks3_payment_summary(db: Session, project_id: int):
|
||||
"""Return summary of KS-3 payments for a project."""
|
||||
ks3_docs = db.query(KS3).options(
|
||||
joinedload(KS3.links).joinedload(KS3KS2.ks2).joinedload(KS2.items)
|
||||
).filter(KS3.project_id == project_id, KS3.status == "issued").all()
|
||||
|
||||
total_ks3 = ZERO
|
||||
for doc in ks3_docs:
|
||||
total_ks3 += _ks3_total(doc)
|
||||
|
||||
received = Decimal(str(
|
||||
db.query(func.coalesce(func.sum(Payment.amount), ZERO))
|
||||
.filter(Payment.project_id == project_id, Payment.status != "cancelled")
|
||||
.scalar()
|
||||
))
|
||||
distributed = Decimal(str(
|
||||
db.query(func.coalesce(func.sum(PaymentAllocation.amount), ZERO))
|
||||
.join(Payment, Payment.id == PaymentAllocation.payment_id)
|
||||
.filter(Payment.project_id == project_id, Payment.status != "cancelled")
|
||||
.scalar()
|
||||
))
|
||||
unallocated = max(received - distributed, ZERO)
|
||||
outstanding = total_ks3 - distributed
|
||||
return {
|
||||
"ks3_count": len(ks3_docs),
|
||||
"ks3_total": total_ks3,
|
||||
"received": received,
|
||||
"paid": distributed,
|
||||
"distributed": distributed,
|
||||
"unallocated": unallocated,
|
||||
"outstanding": outstanding,
|
||||
}
|
||||
|
||||
|
||||
def available_ks3_for_payment(db: Session, project_id: int, exclude_payment_id=None):
|
||||
"""Return issued KS-3 with paid/outstanding info."""
|
||||
docs = db.query(KS3).options(
|
||||
joinedload(KS3.links).joinedload(KS3KS2.ks2).joinedload(KS2.items)
|
||||
).filter(KS3.project_id == project_id, KS3.status == "issued").order_by(KS3.date, KS3.id).all()
|
||||
result = []
|
||||
for doc in docs:
|
||||
total = _ks3_total(doc)
|
||||
paid = _ks3_paid(db, doc.id, exclude_payment_id)
|
||||
outstanding = max(total - paid, ZERO)
|
||||
result.append({
|
||||
"id": doc.id,
|
||||
"number": doc.number,
|
||||
"date": doc.date,
|
||||
"period_from": doc.reporting_period_from,
|
||||
"period_to": doc.reporting_period_to,
|
||||
"total": total,
|
||||
"paid": paid,
|
||||
"outstanding": outstanding,
|
||||
})
|
||||
return result
|
||||
|
||||
|
||||
def save_payment(db: Session, project_id: int, payment_date: date,
|
||||
amount: Decimal, currency: str, comment: str | None,
|
||||
allocations: list[dict], document_number: str | None = None,
|
||||
payment_id: int | None = None):
|
||||
"""Create or update a payment with allocations."""
|
||||
try:
|
||||
if amount <= ZERO:
|
||||
raise PaymentValidationError("Сумма платежа должна быть больше нуля")
|
||||
currency = (currency or "").strip()
|
||||
if not currency:
|
||||
raise PaymentValidationError("Укажите валюту")
|
||||
|
||||
# Validate allocations
|
||||
alloc_map = {}
|
||||
total_allocated = ZERO
|
||||
for alloc in allocations:
|
||||
ks3_id = alloc["ks3_id"]
|
||||
alloc_amount = _decimal(alloc["amount"])
|
||||
if alloc_amount <= ZERO:
|
||||
raise PaymentValidationError("Сумма распределения должна быть больше нуля")
|
||||
if ks3_id in alloc_map:
|
||||
raise PaymentValidationError(f"КС-3 с id={ks3_id} указан несколько раз")
|
||||
alloc_map[ks3_id] = alloc_amount
|
||||
total_allocated += alloc_amount
|
||||
|
||||
if total_allocated > amount:
|
||||
raise PaymentValidationError("Сумма распределения превышает сумму платежа")
|
||||
|
||||
# Validate each KS-3
|
||||
for ks3_id, alloc_amount in alloc_map.items():
|
||||
ks3 = db.query(KS3).options(
|
||||
joinedload(KS3.links).joinedload(KS3KS2.ks2).joinedload(KS2.items)
|
||||
).filter(KS3.id == ks3_id).first()
|
||||
if ks3 is None:
|
||||
raise PaymentValidationError(f"КС-3 с id={ks3_id} не найден")
|
||||
if ks3.project_id != project_id:
|
||||
raise PaymentValidationError(f"КС-3 №{ks3.number} не принадлежит этому проекту")
|
||||
if ks3.status != "issued":
|
||||
raise PaymentValidationError(f"КС-3 №{ks3.number} не проведён")
|
||||
total = _ks3_total(ks3)
|
||||
paid = _ks3_paid(db, ks3_id, exclude_payment_id=payment_id)
|
||||
outstanding = max(total - paid, ZERO)
|
||||
if alloc_amount > outstanding:
|
||||
raise PaymentValidationError(
|
||||
f"КС-3 №{ks3.number}: остаток к оплате {outstanding}, запрошено {alloc_amount}"
|
||||
)
|
||||
|
||||
payment = None
|
||||
if payment_id is not None:
|
||||
payment = db.query(Payment).filter(
|
||||
Payment.id == payment_id, Payment.project_id == project_id
|
||||
).first()
|
||||
if payment is None:
|
||||
raise PaymentValidationError("Платёж не найден")
|
||||
else:
|
||||
payment = Payment(project_id=project_id)
|
||||
db.add(payment)
|
||||
|
||||
payment.date = payment_date
|
||||
payment.document_number = (document_number or "").strip() or None
|
||||
payment.amount = amount
|
||||
payment.currency = currency
|
||||
payment.comment = (comment or "").strip() or None
|
||||
|
||||
payment.allocations.clear()
|
||||
for ks3_id, alloc_amount in alloc_map.items():
|
||||
payment.allocations.append(PaymentAllocation(ks3_id=ks3_id, amount=alloc_amount))
|
||||
|
||||
db.commit()
|
||||
db.refresh(payment)
|
||||
return payment
|
||||
except Exception:
|
||||
db.rollback()
|
||||
raise
|
||||
|
||||
|
||||
def delete_payment(db: Session, project_id: int, payment_id: int):
|
||||
"""Delete a payment and its allocations atomically."""
|
||||
try:
|
||||
payment = db.query(Payment).filter(
|
||||
Payment.id == payment_id, Payment.project_id == project_id
|
||||
).first()
|
||||
if payment is None:
|
||||
raise PaymentValidationError("Платёж не найден")
|
||||
db.delete(payment)
|
||||
db.commit()
|
||||
except Exception:
|
||||
db.rollback()
|
||||
raise
|
||||
|
||||
|
||||
def project_payments(db: Session, project_id: int):
|
||||
"""Return all payments for a project with summary."""
|
||||
payments = db.query(Payment).options(
|
||||
joinedload(Payment.allocations).joinedload(PaymentAllocation.ks3)
|
||||
).filter(Payment.project_id == project_id).order_by(Payment.date.desc(), Payment.id.desc()).all()
|
||||
result = []
|
||||
for p in payments:
|
||||
allocated = sum(_decimal(a.amount) for a in p.allocations)
|
||||
unallocated = max(_decimal(p.amount) - allocated, ZERO)
|
||||
result.append({
|
||||
"payment": p,
|
||||
"allocated": allocated,
|
||||
"unallocated": unallocated,
|
||||
"ks3_count": len(p.allocations),
|
||||
})
|
||||
return result
|
||||
+27
-2
@@ -4,11 +4,36 @@
|
||||
<meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>{% block title %}Work Volume Tracker{% endblock %}</title>
|
||||
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
|
||||
<style>
|
||||
.money-value { transition: filter 0.15s; }
|
||||
.money-hidden .money-value { filter: blur(6px); user-select: none; pointer-events: none; }
|
||||
.clickable-row { cursor: pointer; }
|
||||
.clickable-row:hover { background-color: rgba(0,0,0,0.04); }
|
||||
</style>
|
||||
</head>
|
||||
<body class="bg-light">
|
||||
<body class="bg-light money-hidden">
|
||||
<main class="container py-4">
|
||||
<div class="d-flex justify-content-end mb-2">
|
||||
<button type="button" class="btn btn-outline-secondary btn-sm" id="toggleMoney" title="Показать/скрыть финансовые суммы" aria-label="Показать или скрыть финансовые суммы">👁</button>
|
||||
</div>
|
||||
{% block content %}{% endblock %}
|
||||
</main>
|
||||
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
|
||||
<script>
|
||||
(function() {
|
||||
var btn = document.getElementById('toggleMoney');
|
||||
if (btn) btn.addEventListener('click', function() {
|
||||
document.body.classList.toggle('money-hidden');
|
||||
});
|
||||
|
||||
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>
|
||||
</html>
|
||||
|
||||
@@ -27,7 +27,7 @@
|
||||
</thead>
|
||||
<tbody>
|
||||
{% for row in rows %}
|
||||
<tr>
|
||||
<tr class="clickable-row" data-url="/projects/{{ project.id }}/ks2/{{ row.document.id }}">
|
||||
<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>
|
||||
@@ -36,7 +36,7 @@
|
||||
</span>
|
||||
</td>
|
||||
<td>{{ row.item_count }}</td>
|
||||
<td class="text-end text-nowrap">{{ row.amount | money }}</td>
|
||||
<td class="text-end text-nowrap money-value">{{ row.amount | money }}</td>
|
||||
<td>
|
||||
<a href="/projects/{{ project.id }}/ks2/{{ row.document.id }}" class="btn btn-sm btn-outline-primary">Просмотр</a>
|
||||
</td>
|
||||
|
||||
+37
-12
@@ -15,9 +15,13 @@
|
||||
<div class="card mb-3">
|
||||
<div class="card-body">
|
||||
<p><strong>Статус:</strong>
|
||||
<span class="badge bg-{{ 'success' if document.status == 'issued' else 'secondary' }}">
|
||||
{{ 'Проведён' if document.status == 'issued' else 'Черновик' }}
|
||||
</span>
|
||||
{% if document.status == 'cancelled' %}
|
||||
<span class="badge bg-danger">Сторнирован</span>
|
||||
{% elif document.status == 'issued' %}
|
||||
<span class="badge bg-success">Проведён</span>
|
||||
{% else %}
|
||||
<span class="badge bg-secondary">Черновик</span>
|
||||
{% endif %}
|
||||
</p>
|
||||
{% if document.reporting_period_from and document.reporting_period_to %}
|
||||
<p><strong>Период:</strong> {{ document.reporting_period_from.strftime('%d.%m.%Y') }} — {{ document.reporting_period_to.strftime('%d.%m.%Y') }}</p>
|
||||
@@ -25,9 +29,32 @@
|
||||
{% if document.comment %}
|
||||
<p><strong>Комментарий:</strong> {{ document.comment }}</p>
|
||||
{% endif %}
|
||||
<div class="mt-2">
|
||||
<a href="/projects/{{ project.id }}/ks2/{{ document.id }}/export/excel" class="btn btn-outline-success btn-sm">📊 Excel</a>
|
||||
<a href="/projects/{{ project.id }}/ks2/{{ document.id }}/export/word" class="btn btn-outline-primary btn-sm">📄 Word</a>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{% if document.status == 'cancelled' %}
|
||||
<div class="alert alert-danger" role="alert">
|
||||
КС-2 сторнирован. Документ неизменяем, исключён из финансовых агрегатов. История сохранена.
|
||||
</div>
|
||||
<a href="/projects/{{ project.id }}/ks2" class="btn btn-secondary">Назад к списку</a>
|
||||
{% else %}
|
||||
|
||||
{% if document.status == 'issued' %}
|
||||
<div class="alert alert-success" role="alert">
|
||||
КС-2 проведено. Документ не может быть изменён.
|
||||
</div>
|
||||
<div class="mb-3">
|
||||
<form method="post" action="/projects/{{ project.id }}/ks2/{{ document.id }}/cancel" class="d-inline">
|
||||
<button type="submit" class="btn btn-outline-danger"
|
||||
onclick="return confirm('ВНИМАНИЕ: Сторнировать КС-2? Документ будет исключён из финансовых агрегатов. Действие необратимо.')">Сторнировать</button>
|
||||
</form>
|
||||
</div>
|
||||
{% endif %}
|
||||
|
||||
<h4>Позиции</h4>
|
||||
|
||||
<div class="table-responsive">
|
||||
@@ -46,16 +73,16 @@
|
||||
<tr>
|
||||
<td>{{ line.work_item.name }}</td>
|
||||
<td>{{ line.work_item.unit or '' }}</td>
|
||||
<td class="text-end text-nowrap">{{ line.quantity }}</td>
|
||||
<td class="text-end text-nowrap">{{ line.unit_price | money }}</td>
|
||||
<td class="text-end text-nowrap">{{ line.amount | money }}</td>
|
||||
<td class="text-end text-nowrap">{{ line.quantity|quantity2 }}</td>
|
||||
<td class="text-end text-nowrap money-value">{{ line.unit_price | money }}</td>
|
||||
<td class="text-end text-nowrap money-value">{{ line.amount | money }}</td>
|
||||
</tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
<tfoot>
|
||||
<tr>
|
||||
<th colspan="4" class="text-end">Итого</th>
|
||||
<th class="text-end text-nowrap">{{ total | money }}</th>
|
||||
<th class="text-end text-nowrap money-value">{{ total | money }}</th>
|
||||
</tr>
|
||||
</tfoot>
|
||||
</table>
|
||||
@@ -71,9 +98,6 @@
|
||||
<a href="/projects/{{ project.id }}/ks2" class="btn btn-secondary">Назад к списку</a>
|
||||
</div>
|
||||
{% else %}
|
||||
<div class="alert alert-success" role="alert">
|
||||
КС-2 проведено. Документ не может быть изменён.
|
||||
</div>
|
||||
|
||||
<h4>Источники факта</h4>
|
||||
|
||||
@@ -95,7 +119,7 @@
|
||||
<tr>
|
||||
<td></td>
|
||||
<td>{{ source.daily_report_item.report.report_date.strftime('%d.%m.%Y') }}</td>
|
||||
<td>{{ source.quantity }}</td>
|
||||
<td>{{ source.quantity|quantity2 }}</td>
|
||||
</tr>
|
||||
{% endfor %}
|
||||
{% endfor %}
|
||||
@@ -105,7 +129,8 @@
|
||||
|
||||
<a href="/projects/{{ project.id }}/ks2" class="btn btn-secondary">Назад к списку</a>
|
||||
{% endif %}
|
||||
{% endif %}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{% endblock %}
|
||||
{% endblock %}
|
||||
|
||||
@@ -0,0 +1,98 @@
|
||||
{% extends "base.html" %}
|
||||
|
||||
{% block title %}{{ 'Редактирование' if document else 'Создание' }} КС-3{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<div class="container mt-4">
|
||||
<nav class="mb-3">
|
||||
<a href="/projects/{{ project.id }}" class="btn btn-outline-secondary btn-sm">← К проекту</a>
|
||||
</nav>
|
||||
|
||||
<div class="row">
|
||||
<div class="col-12">
|
||||
<h2>{{ 'Редактирование КС-3' if document else 'Создание КС-3' }}</h2>
|
||||
|
||||
{% if error %}
|
||||
<div class="alert alert-danger" role="alert">{{ error }}</div>
|
||||
{% endif %}
|
||||
|
||||
<form method="post" action="/projects/{{ project.id }}/ks3{% if document %}/{{ document.id }}/edit{% endif %}">
|
||||
<div class="row mb-3">
|
||||
<div class="col-md-3">
|
||||
<label for="number" class="form-label">Номер КС-3</label>
|
||||
<input type="text" class="form-control" id="number" name="number" required
|
||||
value="{{ document.number if document else '' }}">
|
||||
</div>
|
||||
<div class="col-md-3">
|
||||
<label for="document_date" class="form-label">Дата</label>
|
||||
<input type="date" class="form-control" id="document_date" name="document_date" required
|
||||
value="{{ document.date.isoformat() if document else '' }}">
|
||||
</div>
|
||||
<div class="col-md-3">
|
||||
<label for="reporting_period_from" class="form-label">Период с</label>
|
||||
<input type="date" class="form-control" id="reporting_period_from" name="reporting_period_from" required
|
||||
value="{{ document.reporting_period_from.isoformat() if document and document.reporting_period_from else '' }}">
|
||||
</div>
|
||||
<div class="col-md-3">
|
||||
<label for="reporting_period_to" class="form-label">Период по</label>
|
||||
<input type="date" class="form-control" id="reporting_period_to" name="reporting_period_to" required
|
||||
value="{{ document.reporting_period_to.isoformat() if document and document.reporting_period_to else '' }}">
|
||||
</div>
|
||||
</div>
|
||||
<div class="row mb-3">
|
||||
<div class="col-md-12">
|
||||
<label for="comment" class="form-label">Комментарий</label>
|
||||
<input type="text" class="form-control" id="comment" name="comment"
|
||||
value="{{ document.comment if document and document.comment else '' }}">
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<h4>Выберите проведённые КС-2</h4>
|
||||
|
||||
{% if available_ks2 %}
|
||||
<div class="table-responsive">
|
||||
<table class="table table-striped table-sm" style="table-layout: fixed;">
|
||||
<colgroup>
|
||||
<col style="width: 40px">
|
||||
<col style="width: 100px">
|
||||
<col style="width: 90px">
|
||||
<col>
|
||||
<col style="width: 120px">
|
||||
</colgroup>
|
||||
<thead>
|
||||
<tr>
|
||||
<th></th>
|
||||
<th>№ КС-2</th>
|
||||
<th>Дата</th>
|
||||
<th>Период</th>
|
||||
<th class="text-end text-nowrap">Сумма</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{% for item in available_ks2 %}
|
||||
<tr>
|
||||
<td>
|
||||
<input type="checkbox" class="form-check-input" name="ks2_ids"
|
||||
value="{{ item.id }}"
|
||||
{% if item.id in selected_ids %}checked{% endif %}>
|
||||
</td>
|
||||
<td>{{ item.number }}</td>
|
||||
<td>{{ item.date.strftime('%d.%m.%Y') }}</td>
|
||||
<td>{% if item.period_from and item.period_to %}{{ item.period_from.strftime('%d.%m.%Y') }} — {{ item.period_to.strftime('%d.%m.%Y') }}{% endif %}</td>
|
||||
<td class="text-end text-nowrap">{{ item.total | money }}</td>
|
||||
</tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
{% else %}
|
||||
<div class="alert alert-info">Нет проведённых КС-2 для выбора.</div>
|
||||
{% endif %}
|
||||
|
||||
<button type="submit" class="btn btn-primary">{{ 'Сохранить' if document else 'Создать' }}</button>
|
||||
<a href="/projects/{{ project.id }}/ks3{% if document %}/{{ document.id }}{% endif %}" class="btn btn-secondary">Отмена</a>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,55 @@
|
||||
{% extends "base.html" %}
|
||||
|
||||
{% block title %}КС-3 проекта {{ project.name }}{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<div class="container mt-4">
|
||||
<nav class="mb-3">
|
||||
<a href="/projects/{{ project.id }}" class="btn btn-outline-secondary btn-sm">← К проекту</a>
|
||||
</nav>
|
||||
|
||||
<div class="row">
|
||||
<div class="col-12">
|
||||
<h2>КС-3 проекта {{ project.name }}</h2>
|
||||
<a href="/projects/{{ project.id }}/ks3/new" class="btn btn-primary mb-3">Создать КС-3</a>
|
||||
|
||||
<div class="table-responsive">
|
||||
<table class="table table-striped">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Номер</th>
|
||||
<th>Дата</th>
|
||||
<th>Период</th>
|
||||
<th>Статус</th>
|
||||
<th>КС-2</th>
|
||||
<th class="text-end text-nowrap">Сумма</th>
|
||||
<th>Действия</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{% for row in rows %}
|
||||
<tr class="clickable-row" data-url="/projects/{{ project.id }}/ks3/{{ row.document.id }}">
|
||||
<td>{{ row.document.number }}</td>
|
||||
<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>
|
||||
</td>
|
||||
<td>{{ row.ks2_count }}</td>
|
||||
<td class="text-end text-nowrap money-value">{{ row.amount | money }}</td>
|
||||
<td>
|
||||
<a href="/projects/{{ project.id }}/ks3/{{ row.document.id }}" class="btn btn-sm btn-outline-primary">Просмотр</a>
|
||||
</td>
|
||||
</tr>
|
||||
{% else %}
|
||||
<tr><td colspan="7" class="text-center text-muted py-4">КС-3 пока нет.</td></tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,100 @@
|
||||
{% extends "base.html" %}
|
||||
|
||||
{% block title %}КС-3 №{{ document.number }} от {{ document.date.strftime('%d.%m.%Y') }}{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<div class="container mt-4">
|
||||
<nav class="mb-3">
|
||||
<a href="/projects/{{ project.id }}" class="btn btn-outline-secondary btn-sm">← К проекту</a>
|
||||
</nav>
|
||||
|
||||
<div class="row">
|
||||
<div class="col-12">
|
||||
<h2>КС-3 №{{ document.number }} от {{ document.date.strftime('%d.%m.%Y') }}</h2>
|
||||
|
||||
<div class="card mb-3">
|
||||
<div class="card-body">
|
||||
<p><strong>Статус:</strong>
|
||||
{% if document.status == 'cancelled' %}
|
||||
<span class="badge bg-danger">Сторнирован</span>
|
||||
{% elif document.status == 'issued' %}
|
||||
<span class="badge bg-success">Проведён</span>
|
||||
{% else %}
|
||||
<span class="badge bg-secondary">Черновик</span>
|
||||
{% endif %}
|
||||
</p>
|
||||
{% if document.reporting_period_from and document.reporting_period_to %}
|
||||
<p><strong>Период:</strong> {{ document.reporting_period_from.strftime('%d.%m.%Y') }} — {{ document.reporting_period_to.strftime('%d.%m.%Y') }}</p>
|
||||
{% endif %}
|
||||
{% if document.comment %}
|
||||
<p><strong>Комментарий:</strong> {{ document.comment }}</p>
|
||||
{% endif %}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{% if document.status == 'cancelled' %}
|
||||
<div class="alert alert-danger" role="alert">
|
||||
КС-3 сторнировано. Документ неизменяем, исключён из финансовых агрегатов. Связанные КС-2 сохранены.
|
||||
</div>
|
||||
<a href="/projects/{{ project.id }}/ks3" class="btn btn-secondary">Назад к списку</a>
|
||||
{% else %}
|
||||
|
||||
<h4>Включённые КС-2</h4>
|
||||
|
||||
<div class="table-responsive">
|
||||
<table class="table table-striped">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>№ КС-2</th>
|
||||
<th>Дата</th>
|
||||
<th>Период</th>
|
||||
<th class="text-end text-nowrap">Сумма</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{% for row in ks2_rows %}
|
||||
<tr>
|
||||
<td>{{ row.ks2.number }}</td>
|
||||
<td>{{ row.ks2.date.strftime('%d.%m.%Y') }}</td>
|
||||
<td>{% if row.ks2.reporting_period_from and row.ks2.reporting_period_to %}{{ row.ks2.reporting_period_from.strftime('%d.%m.%Y') }} — {{ row.ks2.reporting_period_to.strftime('%d.%m.%Y') }}{% endif %}</td>
|
||||
<td class="text-end text-nowrap money-value">{{ row.total | money }}</td>
|
||||
</tr>
|
||||
{% else %}
|
||||
<tr><td colspan="4" class="text-center text-muted">Нет включённых КС-2.</td></tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
<tfoot>
|
||||
<tr>
|
||||
<th colspan="3" class="text-end">Итого</th>
|
||||
<th class="text-end text-nowrap money-value">{{ total | money }}</th>
|
||||
</tr>
|
||||
</tfoot>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
{% if document.status == 'draft' %}
|
||||
<div class="d-flex gap-2 align-items-center">
|
||||
<a href="/projects/{{ project.id }}/ks3/{{ document.id }}/edit" class="btn btn-primary">Редактировать</a>
|
||||
<form method="post" action="/projects/{{ project.id }}/ks3/{{ document.id }}/issue" class="d-inline">
|
||||
<button type="submit" class="btn btn-success"
|
||||
onclick="return confirm('После проведения КС-3 изменить его будет нельзя. Продолжить?')">Провести КС-3</button>
|
||||
</form>
|
||||
<a href="/projects/{{ project.id }}/ks3" class="btn btn-secondary">Назад к списку</a>
|
||||
</div>
|
||||
{% else %}
|
||||
<div class="alert alert-success" role="alert">
|
||||
КС-3 проведено. Документ не может быть изменён.
|
||||
</div>
|
||||
<div class="mb-3">
|
||||
<form method="post" action="/projects/{{ project.id }}/ks3/{{ document.id }}/cancel" class="d-inline">
|
||||
<button type="submit" class="btn btn-outline-danger"
|
||||
onclick="return confirm('ВНИМАНИЕ: Сторнировать КС-3? Документ будет исключён из финансовых агрегатов. Действие необратимо.')">Сторнировать</button>
|
||||
</form>
|
||||
</div>
|
||||
<a href="/projects/{{ project.id }}/ks3" class="btn btn-secondary">Назад к списку</a>
|
||||
{% endif %}
|
||||
{% endif %}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,97 @@
|
||||
{% extends "base.html" %}
|
||||
|
||||
{% block title %}КС-6а — {{ project.name }}{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<div class="container mt-4">
|
||||
<nav class="mb-3">
|
||||
<a href="/projects/{{ project.id }}" class="btn btn-outline-secondary btn-sm">← К проекту</a>
|
||||
</nav>
|
||||
|
||||
<h2>КС-6а — Журнал выполненных работ</h2>
|
||||
<p class="text-muted">{{ project.name }}</p>
|
||||
|
||||
<form method="get" action="/projects/{{ project.id }}/ks6a" class="card card-body mb-3">
|
||||
<div class="row g-3 align-items-end">
|
||||
<div class="col-md-3">
|
||||
<label for="date_from" class="form-label">Дата с</label>
|
||||
<input type="date" class="form-control" id="date_from" name="date_from" required
|
||||
value="{{ date_from }}">
|
||||
</div>
|
||||
<div class="col-md-3">
|
||||
<label for="date_to" class="form-label">Дата по</label>
|
||||
<input type="date" class="form-control" id="date_to" name="date_to" required
|
||||
value="{{ date_to }}">
|
||||
</div>
|
||||
<div class="col-md-4">
|
||||
<label for="system_id" class="form-label">Система</label>
|
||||
<select class="form-select" id="system_id" name="system_id">
|
||||
<option value="all" {% if not system_id or system_id == 'all' %}selected{% endif %}>Все системы</option>
|
||||
{% for system in systems %}
|
||||
<option value="{{ system.id }}" {% if system_id|string == system.id|string %}selected{% endif %}>{{ system.name }}</option>
|
||||
{% endfor %}
|
||||
</select>
|
||||
</div>
|
||||
<div class="col-md-2">
|
||||
<button type="submit" class="btn btn-primary w-100">Сформировать</button>
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
|
||||
{% if error %}
|
||||
<div class="alert alert-danger" role="alert">{{ error }}</div>
|
||||
{% endif %}
|
||||
|
||||
{% if date_from and date_to and not error %}
|
||||
<div class="mb-2 text-muted">
|
||||
Период: {{ date_from }} — {{ date_to }}
|
||||
{% if system_id and system_id != 'all' %}
|
||||
{% for system in systems %}{% if system_id|string == system.id|string %} · Система: {{ system.name }}{% endif %}{% endfor %}
|
||||
{% else %} · Все системы{% endif %}
|
||||
· Строк: {{ total_count }}
|
||||
</div>
|
||||
|
||||
{% if rows %}
|
||||
<div class="table-responsive">
|
||||
<table class="table table-striped table-sm" style="table-layout: fixed;">
|
||||
<colgroup>
|
||||
<col style="width: 88px">
|
||||
<col style="width: 120px">
|
||||
<col style="width: 120px">
|
||||
<col style="width: 70px">
|
||||
<col>
|
||||
<col style="width: 50px">
|
||||
<col style="width: 80px">
|
||||
</colgroup>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Дата</th>
|
||||
<th>Система</th>
|
||||
<th>Раздел</th>
|
||||
<th>№ поз.</th>
|
||||
<th>Наименование</th>
|
||||
<th>Ед.</th>
|
||||
<th class="text-end text-nowrap">Кол-во</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{% for row in rows %}
|
||||
<tr>
|
||||
<td class="text-nowrap">{{ row.report.report_date.strftime('%d.%m.%Y') }}</td>
|
||||
<td style="overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">{{ row.work_item.system.name if row.work_item.system else '—' }}</td>
|
||||
<td style="overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">{{ row.work_item.section.name if row.work_item.section else '—' }}</td>
|
||||
<td>{{ row.work_item.source_number or '' }}</td>
|
||||
<td style="overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">{{ row.work_item.name }}</td>
|
||||
<td>{{ row.work_item.unit or '' }}</td>
|
||||
<td class="text-end text-nowrap">{{ row.completed_quantity|quantity2 }}</td>
|
||||
</tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
{% else %}
|
||||
<div class="alert alert-info">За выбранный период работ не найдено.</div>
|
||||
{% endif %}
|
||||
{% endif %}
|
||||
</div>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,92 @@
|
||||
{% extends "base.html" %}
|
||||
|
||||
{% block title %}{{ 'Редактирование' if payment else 'Новый' }} платёж — {{ project.name }}{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<div class="container mt-4">
|
||||
<nav class="mb-3">
|
||||
<a href="/projects/{{ project.id }}" class="btn btn-outline-secondary btn-sm">← К проекту</a>
|
||||
</nav>
|
||||
|
||||
<h2>{{ 'Редактирование платежа' if payment else 'Новый платёж' }}</h2>
|
||||
|
||||
{% if error %}
|
||||
<div class="alert alert-danger" role="alert">{{ error }}</div>
|
||||
{% endif %}
|
||||
|
||||
<form method="post" action="/projects/{{ project.id }}/payments{% if payment %}/{{ payment.id }}/edit{% endif %}">
|
||||
<div class="row mb-3">
|
||||
<div class="col-md-3">
|
||||
<label for="payment_date" class="form-label">Дата</label>
|
||||
<input type="date" class="form-control" id="payment_date" name="payment_date" required
|
||||
value="{{ payment.date.isoformat() if payment else '' }}">
|
||||
</div>
|
||||
<div class="col-md-3">
|
||||
<label for="document_number" class="form-label">Номер документа</label>
|
||||
<input type="text" class="form-control" id="document_number" name="document_number"
|
||||
value="{{ payment.document_number if payment and payment.document_number else '' }}">
|
||||
</div>
|
||||
<div class="col-md-3">
|
||||
<label for="amount" class="form-label">Сумма</label>
|
||||
<input type="number" class="form-control" id="amount" name="amount" required min="0.01" step="0.01"
|
||||
value="{{ payment.amount if payment else '' }}">
|
||||
</div>
|
||||
<div class="col-md-3">
|
||||
<label for="currency" class="form-label">Валюта</label>
|
||||
<input type="text" class="form-control" id="currency" name="currency" required
|
||||
value="{{ payment.currency if payment else 'RUB' }}">
|
||||
</div>
|
||||
</div>
|
||||
<div class="row mb-3">
|
||||
<div class="col-md-12">
|
||||
<label for="comment" class="form-label">Комментарий</label>
|
||||
<input type="text" class="form-control" id="comment" name="comment"
|
||||
value="{{ payment.comment if payment and payment.comment else '' }}">
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<h4>Распределение по КС-3</h4>
|
||||
<p class="text-muted">Укажите суммы распределения. Можно оставить пустым.</p>
|
||||
|
||||
{% if available_ks3 %}
|
||||
<div class="table-responsive">
|
||||
<table class="table table-striped table-sm">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>№ КС-3</th>
|
||||
<th>Дата</th>
|
||||
<th>Период</th>
|
||||
<th class="text-end text-nowrap">Сумма КС-3</th>
|
||||
<th class="text-end text-nowrap">Оплачено</th>
|
||||
<th class="text-end text-nowrap">Остаток</th>
|
||||
<th>Распределить</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{% for item in available_ks3 %}
|
||||
<tr>
|
||||
<td>{{ item.number }}</td>
|
||||
<td>{{ item.date.strftime('%d.%m.%Y') }}</td>
|
||||
<td>{% if item.period_from and item.period_to %}{{ item.period_from.strftime('%d.%m.%Y') }} — {{ item.period_to.strftime('%d.%m.%Y') }}{% endif %}</td>
|
||||
<td class="text-end text-nowrap">{{ item.total | money }}</td>
|
||||
<td class="text-end text-nowrap">{{ item.paid | money }}</td>
|
||||
<td class="text-end text-nowrap">{{ item.outstanding | money }}</td>
|
||||
<td style="min-width: 120px">
|
||||
<input type="number" class="form-control form-control-sm" name="alloc_{{ item.id }}"
|
||||
min="0" step="0.01" placeholder="0.00"
|
||||
value="{{ current_allocs.get(item.id, '') if current_allocs else '' }}">
|
||||
</td>
|
||||
</tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
{% else %}
|
||||
<div class="alert alert-info">Нет проведённых КС-3 для распределения.</div>
|
||||
{% endif %}
|
||||
|
||||
<button type="submit" class="btn btn-primary">{{ 'Сохранить' if payment else 'Создать' }}</button>
|
||||
<a href="/projects/{{ project.id }}/payments{% if payment %}/{{ payment.id }}{% endif %}" class="btn btn-secondary">Отмена</a>
|
||||
</form>
|
||||
</div>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,59 @@
|
||||
{% extends "base.html" %}
|
||||
|
||||
{% block title %}Платежи — {{ project.name }}{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<div class="container mt-4">
|
||||
<nav class="mb-3">
|
||||
<a href="/projects/{{ project.id }}" class="btn btn-outline-secondary btn-sm">← К проекту</a>
|
||||
</nav>
|
||||
|
||||
<div class="row">
|
||||
<div class="col-12">
|
||||
<h2>Платежи проекта {{ project.name }}</h2>
|
||||
<a href="/projects/{{ project.id }}/payments/new" class="btn btn-primary mb-3">Новый платёж</a>
|
||||
|
||||
<div class="table-responsive">
|
||||
<table class="table table-striped">
|
||||
<thead>
|
||||
<tr>
|
||||
<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>
|
||||
</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>{{ row.payment.document_number or '—' }}</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>
|
||||
<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">
|
||||
<button type="submit" class="btn btn-sm btn-outline-danger" onclick="return confirm('Удалить платёж?')">Удалить</button>
|
||||
</form>
|
||||
</td>
|
||||
</tr>
|
||||
{% else %}
|
||||
<tr><td colspan="9" class="text-center text-muted py-4">Платежей пока нет.</td></tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,87 @@
|
||||
{% extends "base.html" %}
|
||||
|
||||
{% block title %}Платёж — {{ project.name }}{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<div class="container mt-4">
|
||||
<nav class="mb-3">
|
||||
<a href="/projects/{{ project.id }}" class="btn btn-outline-secondary btn-sm">← К проекту</a>
|
||||
</nav>
|
||||
|
||||
<h2>Платёж{% if payment.document_number %} №{{ payment.document_number }}{% endif %} от {{ payment.date.strftime('%d.%m.%Y') }}</h2>
|
||||
|
||||
{% if payment.status == 'cancelled' %}
|
||||
<div class="alert alert-danger" role="alert">
|
||||
Платёж сторнирован. Сумма не считается полученными деньгами, распределения исключены из агрегатов.
|
||||
</div>
|
||||
{% endif %}
|
||||
|
||||
<div class="card mb-3">
|
||||
<div class="card-body">
|
||||
<p><strong>Статус:</strong>
|
||||
{% if payment.status == 'cancelled' %}
|
||||
<span class="badge bg-danger">Сторнирован</span>
|
||||
{% else %}
|
||||
<span class="badge bg-success">Активен</span>
|
||||
{% endif %}
|
||||
</p>
|
||||
<div class="row">
|
||||
<div class="col-md-4">
|
||||
<p><strong>Сумма:</strong> <span class="money-value">{{ payment.amount | money(payment.currency) }}</span></p>
|
||||
</div>
|
||||
<div class="col-md-4">
|
||||
<p><strong>Распределено:</strong> <span class="money-value">{{ allocated | money(payment.currency) }}</span></p>
|
||||
</div>
|
||||
<div class="col-md-4">
|
||||
<p><strong>Не распределено:</strong> <span class="money-value">{{ unallocated | money(payment.currency) }}</span></p>
|
||||
</div>
|
||||
</div>
|
||||
{% if payment.comment %}
|
||||
<p><strong>Комментарий:</strong> {{ payment.comment }}</p>
|
||||
{% endif %}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{% if payment.status != 'cancelled' %}
|
||||
<h4>Распределение по КС-3</h4>
|
||||
|
||||
<div class="table-responsive">
|
||||
<table class="table table-striped">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>№ КС-3</th>
|
||||
<th>Дата КС-3</th>
|
||||
<th class="text-end text-nowrap">Сумма</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{% for alloc in payment.allocations %}
|
||||
<tr>
|
||||
<td>{{ alloc.ks3.number if alloc.ks3 else alloc.ks3_id }}</td>
|
||||
<td>{{ alloc.ks3.date.strftime('%d.%m.%Y') if alloc.ks3 and alloc.ks3.date else '—' }}</td>
|
||||
<td class="text-end text-nowrap money-value">{{ alloc.amount | money(payment.currency) }}</td>
|
||||
</tr>
|
||||
{% else %}
|
||||
<tr><td colspan="3" class="text-center text-muted">Платёж не распределён.</td></tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
{% endif %}
|
||||
|
||||
<div class="d-flex gap-2">
|
||||
{% if payment.status != 'cancelled' %}
|
||||
<a href="/projects/{{ project.id }}/payments/{{ payment.id }}/edit" class="btn btn-primary">Редактировать</a>
|
||||
<form method="post" action="/projects/{{ project.id }}/payments/{{ payment.id }}/cancel" class="d-inline">
|
||||
<button type="submit" class="btn btn-outline-danger"
|
||||
onclick="return confirm('ВНИМАНИЕ: Сторнировать платёж? Сумма перестанет считаться полученной. Действие необратимо.')">Сторнировать платёж</button>
|
||||
</form>
|
||||
<form method="post" action="/projects/{{ project.id }}/payments/{{ payment.id }}/delete" class="d-inline">
|
||||
<button type="submit" class="btn btn-danger"
|
||||
onclick="return confirm('Удалить платёж?')">Удалить</button>
|
||||
</form>
|
||||
{% endif %}
|
||||
<a href="/projects/{{ project.id }}/payments" class="btn btn-secondary">Назад к списку</a>
|
||||
</div>
|
||||
</div>
|
||||
{% endblock %}
|
||||
@@ -5,8 +5,21 @@
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>{{ document_title }} — {{ project.name }}</title>
|
||||
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
|
||||
<style>
|
||||
.money-value { transition: filter 0.15s; }
|
||||
.money-hidden .money-value { filter: blur(6px); user-select: none; pointer-events: none; }
|
||||
.microstat-bar { min-width: 6rem; height: 0.5rem; }
|
||||
.microstat-label { font-size: 0.75rem; white-space: nowrap; }
|
||||
.boq-table { table-layout: fixed; width: 100%; }
|
||||
.boq-table td, .boq-table th { overflow-wrap: anywhere; }
|
||||
.boq-table .money-value { white-space: nowrap; overflow-wrap: normal; }
|
||||
.boq-table thead th { position: sticky; top: 0; z-index: 10; background: #f8f9fa; }
|
||||
.toggle-row { cursor: pointer; user-select: none; }
|
||||
.toggle-row .toggle-icon { display: inline-block; width: 1.2em; transition: transform 0.15s; }
|
||||
.toggle-row.collapsed .toggle-icon { transform: rotate(-90deg); }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<body class="money-hidden">
|
||||
<main class="container my-4">
|
||||
<nav aria-label="Навигация" class="mb-3">
|
||||
<ol class="breadcrumb">
|
||||
@@ -21,47 +34,94 @@
|
||||
<h1>{{ document_title }}</h1>
|
||||
<p class="text-muted mb-0">{{ project.name }}{% if document.source_file %} · {{ document.source_file }}{% endif %}</p>
|
||||
</div>
|
||||
<a class="btn btn-outline-secondary" href="/projects/{{ project.id }}">К проекту</a>
|
||||
<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>
|
||||
</form>
|
||||
{% else %}
|
||||
<form method="post" action="/boq/{{ project.id }}/documents/{{ document.id }}/archive" class="d-inline">
|
||||
<button type="submit" class="btn btn-outline-warning" onclick="return confirm('Архивировать ведомость? Данные будут сохранены.')">Архивировать</button>
|
||||
</form>
|
||||
{% endif %}
|
||||
<a class="btn btn-outline-secondary" href="/projects/{{ project.id }}">К проекту</a>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="table-responsive">
|
||||
<table class="table table-bordered table-sm align-middle">
|
||||
<table class="table table-bordered table-sm align-middle boq-table">
|
||||
<colgroup>
|
||||
<col style="width: 3.5rem">
|
||||
<col>
|
||||
<col style="width: 9rem">
|
||||
<col style="width: 9rem">
|
||||
<col style="width: 4.5rem">
|
||||
<col style="width: 5.5rem">
|
||||
<col style="width: 7.5rem">
|
||||
<col style="width: 8.5rem">
|
||||
<col style="width: 11rem">
|
||||
</colgroup>
|
||||
<thead class="table-light">
|
||||
<tr>
|
||||
<th>№</th><th>Наименование</th><th>Модель / артикул</th><th>Производитель</th>
|
||||
<th>Ед. изм.</th><th class="text-end">Кол-во</th><th class="text-end">Цена за ед.</th><th class="text-end">Сумма</th>
|
||||
<th>Выполнение</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{% for system_node in systems %}
|
||||
<tr class="table-primary">
|
||||
<th colspan="7">Система: {{ system_node.system.name }}</th>
|
||||
<th class="text-end">{{ system_node.total|money(project.currency) }}</th>
|
||||
<tr class="table-primary toggle-row" data-toggle="system-{{ system_node.system.id }}">
|
||||
<th colspan="8"><span class="toggle-icon">▼</span> Система: {{ system_node.system.name }}</th>
|
||||
<th class="text-end money-value">{{ system_node.total|money(project.currency) }}</th>
|
||||
</tr>
|
||||
{% for section_node in system_node.sections %}
|
||||
<tr class="table-success">
|
||||
<th colspan="7">Раздел: {{ section_node.section.name }}</th>
|
||||
<th class="text-end">{{ section_node.total|money(project.currency) }}</th>
|
||||
<tr class="table-success toggle-row" data-toggle="section-{{ section_node.section.id }}" data-parent="system-{{ system_node.system.id }}">
|
||||
<th colspan="8"><span class="toggle-icon">▼</span> Раздел: {{ section_node.section.name }}</th>
|
||||
<th class="text-end money-value">{{ section_node.total|money(project.currency) }}</th>
|
||||
</tr>
|
||||
{% for item in section_node["items"] %}
|
||||
<tr>
|
||||
{% set done = completed_by_item.get(item.id, 0) %}
|
||||
{% set planned = item.quantity if item.quantity is not none else 0 %}
|
||||
{% set pct = (done / planned * 100) if planned else 0 %}
|
||||
<tr data-parent="section-{{ section_node.section.id }}">
|
||||
<td>{{ item.source_number or '' }}</td>
|
||||
<td>{{ item.name }}</td>
|
||||
<td>{{ item.model or '' }}</td>
|
||||
<td>{{ item.manufacturer or '' }}</td>
|
||||
<td>{{ item.unit or '' }}</td>
|
||||
<td class="text-end">{{ item.quantity if item.quantity is not none else '' }}</td>
|
||||
<td class="text-end">{{ item.unit_price|money(project.currency) if item.unit_price is not none else '' }}</td>
|
||||
<td class="text-end">{{ item.amount|money(project.currency) if item.amount is not none else '' }}</td>
|
||||
<td class="text-end money-value">{{ item.unit_price|money(project.currency) if item.unit_price is not none else '' }}</td>
|
||||
<td class="text-end money-value">{{ item.amount|money(project.currency) if item.amount is not none else '' }}</td>
|
||||
<td>
|
||||
{% if planned %}
|
||||
<div class="microstat-label text-muted mb-1">Выполнено: {{ done|round(2) }} / {{ planned }}</div>
|
||||
<div class="progress microstat-bar">
|
||||
{% if pct == 0 %}
|
||||
<div class="progress-bar bg-secondary" style="width: 100%"></div>
|
||||
{% elif pct < 50 %}
|
||||
<div class="progress-bar bg-warning" style="width: {{ pct }}%"></div>
|
||||
{% elif pct < 100 %}
|
||||
<div class="progress-bar bg-primary" style="width: {{ pct }}%"></div>
|
||||
{% elif pct == 100 %}
|
||||
<div class="progress-bar bg-success" style="width: 100%"></div>
|
||||
{% else %}
|
||||
<div class="progress-bar bg-danger" style="width: 100%"></div>
|
||||
{% endif %}
|
||||
</div>
|
||||
{% endif %}
|
||||
</td>
|
||||
</tr>
|
||||
{% endfor %}
|
||||
{% endfor %}
|
||||
{% else %}
|
||||
<tr><td colspan="8" class="text-center text-muted py-4">В документе нет рабочих позиций.</td></tr>
|
||||
<tr><td colspan="9" class="text-center text-muted py-4">В документе нет рабочих позиций.</td></tr>
|
||||
{% endfor %}
|
||||
<tr class="table-dark fw-bold">
|
||||
<td colspan="7">Итого по ведомости</td>
|
||||
<td class="text-end">{{ total|money(project.currency) }}</td>
|
||||
<td colspan="8">Итого по ведомости</td>
|
||||
<td class="text-end money-value">{{ total|money(project.currency) }}</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
@@ -71,5 +131,42 @@
|
||||
<div class="alert alert-warning mt-3">В документе есть {{ unassigned_items|length }} позиций без полной привязки к системе и разделу.</div>
|
||||
{% endif %}
|
||||
</main>
|
||||
<script>
|
||||
(function() {
|
||||
var moneyBtn = document.getElementById('toggleMoney');
|
||||
if (moneyBtn) moneyBtn.addEventListener('click', function() {
|
||||
document.body.classList.toggle('money-hidden');
|
||||
});
|
||||
|
||||
function toggleGroup(id, collapsed) {
|
||||
document.querySelectorAll('[data-parent="' + id + '"]').forEach(function(el) {
|
||||
el.style.display = collapsed ? 'none' : '';
|
||||
if (el.dataset.toggle) toggleGroup(el.dataset.toggle, collapsed);
|
||||
});
|
||||
var header = document.querySelector('[data-toggle="' + id + '"]');
|
||||
if (header) header.classList.toggle('collapsed', collapsed);
|
||||
}
|
||||
|
||||
document.querySelectorAll('.toggle-row').forEach(function(row) {
|
||||
row.addEventListener('click', function() {
|
||||
var id = row.dataset.toggle;
|
||||
if (!id) return;
|
||||
var isCollapsed = row.classList.contains('collapsed');
|
||||
toggleGroup(id, !isCollapsed);
|
||||
});
|
||||
});
|
||||
|
||||
document.getElementById('expandAll').addEventListener('click', function() {
|
||||
document.querySelectorAll('.toggle-row').forEach(function(row) {
|
||||
if (row.dataset.toggle) toggleGroup(row.dataset.toggle, false);
|
||||
});
|
||||
});
|
||||
document.getElementById('collapseAll').addEventListener('click', function() {
|
||||
document.querySelectorAll('.toggle-row').forEach(function(row) {
|
||||
if (row.dataset.toggle) toggleGroup(row.dataset.toggle, true);
|
||||
});
|
||||
});
|
||||
})();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
@@ -11,9 +11,11 @@
|
||||
.system-progress-table .progress-cell { min-width: 14rem; }
|
||||
.system-progress-table .progress-summary { flex-wrap: nowrap; gap: .5rem; }
|
||||
.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; }
|
||||
</style>
|
||||
</head>
|
||||
<body class="bg-light">
|
||||
<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>
|
||||
|
||||
@@ -30,15 +32,32 @@
|
||||
{% 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>
|
||||
<a class="btn btn-outline-secondary" href="/projects/{{ project.id }}/edit">Редактировать</a>
|
||||
<a class="btn btn-outline-primary" href="/boq/{{ project.id }}">Ведомости</a>
|
||||
<a class="btn btn-outline-primary" href="/projects/{{ project.id }}/agreements">Дополнительные соглашения</a>
|
||||
<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>
|
||||
<a class="btn btn-outline-primary" href="/projects/{{ project.id }}/ks2">КС-2{% if ks2_count %} ({{ ks2_count }}){% endif %}</a>
|
||||
<a class="btn btn-primary" href="/projects/{{ project.id }}/daily-reports/new">Создать Daily Report</a>
|
||||
<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>
|
||||
</header>
|
||||
|
||||
{% if project.status != 'archived' %}
|
||||
<div class="mb-3 d-flex gap-2">
|
||||
<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>
|
||||
</div>
|
||||
{% else %}
|
||||
<div class="alert alert-warning mb-3">Проект архивирован. Данные сохранены, проект не считается активным.</div>
|
||||
{% endif %}
|
||||
|
||||
<section class="mt-3" aria-live="polite">
|
||||
{% if over_plan_count %}
|
||||
<div class="alert alert-warning py-2 mb-0">⚠ Проверка плана: {{ over_plan_count }} позиции превышают план · <button type="button" class="btn btn-link p-0 align-baseline" data-bs-toggle="modal" data-bs-target="#planWarningsModal">Подробнее</button></div>
|
||||
@@ -48,14 +67,26 @@
|
||||
<section class="mb-4" aria-labelledby="kpi-heading">
|
||||
<h2 id="kpi-heading" class="h5 mb-3">План и выполнение</h2>
|
||||
<div class="row g-3">
|
||||
<div class="col-6 col-xl-3"><article class="card h-100 border-0 shadow-sm"><div class="card-body"><div class="text-muted small">Плановая стоимость</div><div class="fs-3 fw-semibold">{{ planned_cost|money(project.currency) }}</div><div class="small text-muted">по ведомостям проекта</div></div></article></div>
|
||||
<div class="col-6 col-xl-3"><article class="card h-100 border-0 shadow-sm"><div class="card-body"><div class="text-muted small">Выполнено по Daily Reports</div><div class="fs-3 fw-semibold text-success">{{ performed_cost|money(project.currency) }}</div></div></article></div>
|
||||
<div class="col-6 col-xl-3"><article class="card h-100 border-0 shadow-sm"><div class="card-body"><div class="text-muted small">Остаток</div><div class="fs-3 fw-semibold {% if remaining_cost < 0 %}text-danger{% endif %}">{{ remaining_cost|money(project.currency) }}</div></div></article></div>
|
||||
<div class="col-6 col-xl-3"><article class="card h-100 border-0 shadow-sm"><div class="card-body"><div class="text-muted small">Плановая стоимость</div><div class="fs-3 fw-semibold money-value">{{ planned_cost|money(project.currency) }}</div><div class="small text-muted">по ведомостям проекта</div></div></article></div>
|
||||
<div class="col-6 col-xl-3"><article class="card h-100 border-0 shadow-sm"><div class="card-body"><div class="text-muted small">Выполнено по Daily Reports</div><div class="fs-3 fw-semibold text-success money-value">{{ performed_cost|money(project.currency) }}</div></div></article></div>
|
||||
<div class="col-6 col-xl-3"><article class="card h-100 border-0 shadow-sm"><div class="card-body"><div class="text-muted small">Остаток</div><div class="fs-3 fw-semibold money-value {% if remaining_cost < 0 %}text-danger{% endif %}">{{ remaining_cost|money(project.currency) }}</div></div></article></div>
|
||||
<div class="col-6 col-xl-3"><article class="card h-100 border-0 shadow-sm"><div class="card-body"><div class="text-muted small">Выполнение</div><div class="fs-3 fw-semibold">{{ '%.4f'|format(completion_percent) }}%</div><div class="progress mt-2" role="progressbar" aria-valuenow="{{ '%.4f'|format(completion_percent) }}" aria-valuemin="0" aria-valuemax="100"><div class="progress-bar {% if completion_percent > 100 %}bg-warning{% endif %}" style="width: {{ 100 if completion_percent > 100 else completion_percent }}%"></div></div></div></article></div>
|
||||
</div>
|
||||
{% if not base_boq_documents %}<div class="alert alert-info mt-3 mb-0">Сначала импортируйте ведомость, чтобы сформировать план.</div>{% endif %}
|
||||
</section>
|
||||
|
||||
<section class="mb-4" aria-labelledby="payment-heading">
|
||||
<h2 id="payment-heading" class="h5 mb-3">Оплата по КС-3</h2>
|
||||
<div class="row g-3">
|
||||
<div class="col-6 col-xl-2"><article class="card h-100 border-0 shadow-sm"><div class="card-body"><div class="text-muted small">Всего КС-3</div><div class="fs-3 fw-semibold">{{ payment_summary.ks3_count }}</div></div></article></div>
|
||||
<div class="col-6 col-xl-2"><article class="card h-100 border-0 shadow-sm"><div class="card-body"><div class="text-muted small">Сумма КС-3</div><div class="fs-3 fw-semibold money-value">{{ payment_summary.ks3_total|money(project.currency) }}</div></div></article></div>
|
||||
<div class="col-6 col-xl-2"><article class="card h-100 border-0 shadow-sm"><div class="card-body"><div class="text-muted small">Получено</div><div class="fs-3 fw-semibold money-value">{{ payment_summary.received|money(project.currency) }}</div></div></article></div>
|
||||
<div class="col-6 col-xl-2"><article class="card h-100 border-0 shadow-sm"><div class="card-body"><div class="text-muted small">Распределено</div><div class="fs-3 fw-semibold text-success money-value">{{ payment_summary.distributed|money(project.currency) }}</div></div></article></div>
|
||||
<div class="col-6 col-xl-2"><article class="card h-100 border-0 shadow-sm"><div class="card-body"><div class="text-muted small">Нераспределено</div><div class="fs-3 fw-semibold money-value">{{ payment_summary.unallocated|money(project.currency) }}</div></div></article></div>
|
||||
<div class="col-6 col-xl-2"><article class="card h-100 border-0 shadow-sm"><div class="card-body"><div class="text-muted small">Задолженность</div><div class="fs-3 fw-semibold money-value {% if payment_summary.outstanding > 0 %}text-danger{% endif %}">{{ payment_summary.outstanding|money(project.currency) }}</div></div></article></div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<div class="row g-4">
|
||||
<div class="col-lg-8">
|
||||
<section class="card border-0 shadow-sm h-100">
|
||||
@@ -67,8 +98,8 @@
|
||||
<tbody>{% for row in system_progress %}
|
||||
<tr>
|
||||
<td class="system-name-cell">{{ row.system.name }}</td>
|
||||
<td class="text-end money-cell">{{ row.planned_cost|money(project.currency) }}</td>
|
||||
<td class="text-end money-cell">{{ row.performed_cost|money(project.currency) }}</td>
|
||||
<td class="text-end money-cell money-value">{{ row.planned_cost|money(project.currency) }}</td>
|
||||
<td class="text-end money-cell money-value">{{ row.performed_cost|money(project.currency) }}</td>
|
||||
<td class="progress-cell"><div class="d-flex justify-content-between small mb-1 progress-summary"><span>{{ '%.4f'|format(row.completion_percent) }}%</span>{% if not row.planned_cost %}<span class="text-muted">нет плана</span>{% endif %}</div><div class="progress" role="progressbar" aria-valuenow="{{ '%.4f'|format(row.completion_percent) }}" aria-valuemin="0" aria-valuemax="100"><div class="progress-bar {% if row.completion_percent > 100 %}bg-warning{% endif %}" style="width: {{ 100 if row.completion_percent > 100 else row.completion_percent }}%"></div></div></td>
|
||||
</tr>{% endfor %}</tbody>
|
||||
</table></div>
|
||||
@@ -119,15 +150,49 @@
|
||||
<div class="card-header bg-white d-flex justify-content-between align-items-center"><h2 class="h5 mb-0">Последние Daily Reports</h2><a href="/projects/{{ project.id }}/daily-reports" class="btn btn-sm btn-outline-primary">Все отчёты</a></div>
|
||||
{% if recent_reports %}
|
||||
<div class="table-responsive"><table class="table table-hover mb-0"><thead><tr><th>Дата</th><th>Система</th><th class="text-end">Позиций</th><th class="text-end">Объём отчёта</th><th></th></tr></thead>
|
||||
<tbody>{% for row in recent_reports %}<tr><td>{{ row.report.report_date.strftime('%d.%m.%Y') }}</td><td>{{ row.systems|join(', ') }}</td><td class="text-end">{{ row.item_count }}</td><td class="text-end">{{ row.volume|money(project.currency) }}</td><td class="text-end"><a href="/projects/{{ project.id }}/daily-reports/{{ row.report.id }}" class="btn btn-sm btn-outline-primary">Просмотр</a></td></tr>{% endfor %}</tbody>
|
||||
<tbody>{% for row in recent_reports %}<tr><td>{{ row.report.report_date.strftime('%d.%m.%Y') }}</td><td>{{ row.systems|join(', ') }}</td><td class="text-end">{{ row.item_count }}</td><td class="text-end money-value">{{ row.volume|money(project.currency) }}</td><td class="text-end"><a href="/projects/{{ project.id }}/daily-reports/{{ row.report.id }}" class="btn btn-sm btn-outline-primary">Просмотр</a></td></tr>{% endfor %}</tbody>
|
||||
</table></div>
|
||||
{% else %}<div class="card-body text-muted">Daily Reports ещё не создавались. Выполненные объёмы пока равны нулю.</div>{% endif %}
|
||||
</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>
|
||||
{% if boq_docs %}<ul class="list-group list-group-flush">{% for doc in boq_docs %}<li class="list-group-item d-flex justify-content-between align-items-center"><span>{{ doc.name.replace('BOQ Import - ', 'Импорт ведомости — ').replace('BOQ Import — ', 'Импорт ведомости — ') }} <small class="text-muted">{{ doc.source_file or '' }}</small></span><a class="btn btn-sm btn-outline-primary" href="/boq/{{ project.id }}/documents/{{ doc.id }}">Открыть ведомость</a></li>{% endfor %}</ul>
|
||||
{% else %}<div class="card-body"><span class="text-muted">Ведомость не импортирована.</span> <a href="/projects/{{ project.id }}/import">Импортировать ведомость</a></div>{% endif %}
|
||||
<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-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 — ', 'Импорт ведомости — ') }}
|
||||
</a>
|
||||
{% if node.agreements %}
|
||||
<div class="ms-4 mt-1">
|
||||
{% for agr in node.agreements %}
|
||||
<div class="small">
|
||||
<a href="/projects/{{ project.id }}/agreements/{{ agr.id }}" class="text-decoration-none">
|
||||
📋 ДС №{{ agr.number or agr.id }} — {{ agr.name or '' }}
|
||||
<span class="badge bg-{{ 'success' if agr.status == 'approved' else 'secondary' }} ms-1">{{ 'Утверждено' if agr.status == 'approved' else 'Черновик' }}</span>
|
||||
</a>
|
||||
</div>
|
||||
{% endfor %}
|
||||
</div>
|
||||
{% endif %}
|
||||
</div>
|
||||
{% endfor %}
|
||||
{% if project_wide_agreements %}
|
||||
<div class="mt-3 mb-2 fw-semibold">Дополнительные работы проекта</div>
|
||||
{% for agr in project_wide_agreements %}
|
||||
<div class="ms-3 small">
|
||||
<a href="/projects/{{ project.id }}/agreements/{{ agr.id }}" class="text-decoration-none">
|
||||
📋 ДС №{{ agr.number or agr.id }} — {{ agr.name or '' }}
|
||||
<span class="badge bg-{{ 'success' if agr.status == 'approved' else 'secondary' }} ms-1">{{ 'Утверждено' if agr.status == 'approved' else 'Черновик' }}</span>
|
||||
</a>
|
||||
</div>
|
||||
{% endfor %}
|
||||
{% endif %}
|
||||
{% if not doc_tree and not project_wide_agreements %}
|
||||
<div class="text-muted">Документы ещё не добавлены. <a href="/projects/{{ project.id }}/import">Импортировать ведомость</a></div>
|
||||
{% endif %}
|
||||
</div>
|
||||
</section>
|
||||
<div class="modal fade" id="journalModal" tabindex="-1" aria-labelledby="journalModalTitle" aria-hidden="true">
|
||||
<div class="modal-dialog"><form class="modal-content" id="journal-form" method="post">
|
||||
@@ -232,6 +297,9 @@
|
||||
button.disabled = false;
|
||||
}
|
||||
}));
|
||||
document.getElementById('toggleMoney').addEventListener('click', () => {
|
||||
document.body.classList.toggle('money-hidden');
|
||||
});
|
||||
})();
|
||||
</script>
|
||||
</body>
|
||||
|
||||
Reference in New Issue
Block a user