feat: enforce KS-2/KS-3 stornation integrity

This commit is contained in:
Арсентьев Александр
2026-09-27 18:12:19 +03:00
parent 80b7d4732e
commit 9992a435b2
15 changed files with 947 additions and 20 deletions
+7
View File
@@ -37,6 +37,13 @@ def render_ks2_excel(doc: KS2ExportDocument) -> bytes:
c.alignment = Alignment(horizontal="center")
row += 1
if h.status == "cancelled":
ws.merge_cells(start_row=row, start_column=1, end_row=row, end_column=col_count)
c = ws.cell(row=row, column=1, value="СТОРНИРОВАН")
c.font = Font(bold=True, size=12, color="C00000")
c.alignment = Alignment(horizontal="center")
row += 1
# Unified project requisites
header_lines = project_requisite_lines(
project_name=h.project_name,
+7
View File
@@ -35,6 +35,13 @@ def render_ks3_excel(doc: KS3ExportDocument) -> bytes:
c.alignment = Alignment(horizontal="center")
row += 1
if h.status == "cancelled":
ws.merge_cells(start_row=row, start_column=1, end_row=row, end_column=col_count)
c = ws.cell(row=row, column=1, value="СТОРНИРОВАН")
c.font = Font(bold=True, size=12, color="C00000")
c.alignment = Alignment(horizontal="center")
row += 1
header_lines = project_requisite_lines(
project_name=h.project_name,
customer=h.customer,
+2
View File
@@ -27,6 +27,7 @@ class KS2ExportHeader:
period_from: date | None
period_to: date | None
comment: str
status: str
@dataclass(frozen=True)
@@ -68,5 +69,6 @@ def build_ks2_export_dto(db, ks2_document) -> KS2ExportDocument:
period_from=ks2_document.reporting_period_from,
period_to=ks2_document.reporting_period_to,
comment=ks2_document.comment or "",
status=ks2_document.status or "",
)
return KS2ExportDocument(header=header, items=items, total=total)
+2
View File
@@ -26,6 +26,7 @@ class KS3ExportHeader:
period_from: date | None
period_to: date | None
comment: str
status: str
@dataclass(frozen=True)
@@ -68,5 +69,6 @@ def build_ks3_export_dto(db, ks3_document) -> KS3ExportDocument:
period_from=ks3_document.reporting_period_from,
period_to=ks3_document.reporting_period_to,
comment=ks3_document.comment or "",
status=ks3_document.status or "",
)
return KS3ExportDocument(header=header, items=items, total=total)
+9 -1
View File
@@ -5,7 +5,7 @@ from docx import Document
from docx.enum.section import WD_ORIENT
from docx.enum.table import WD_TABLE_ALIGNMENT
from docx.enum.text import WD_ALIGN_PARAGRAPH
from docx.shared import Pt
from docx.shared import Pt, RGBColor
from app.exporters.common import MONEY_TEXT, QTY_TEXT, format_period, project_requisite_lines
from app.exporters.ks2_dto import KS2ExportDocument
@@ -26,6 +26,14 @@ def render_ks2_word(doc: KS2ExportDocument) -> bytes:
run.bold = True
run.font.size = Pt(14)
if h.status == "cancelled":
mark = d.add_paragraph()
mark.alignment = WD_ALIGN_PARAGRAPH.CENTER
run = mark.add_run("СТОРНИРОВАН")
run.bold = True
run.font.size = Pt(12)
run.font.color.rgb = RGBColor(0xC0, 0x00, 0x00)
d.add_paragraph()
header_lines = project_requisite_lines(
+9 -1
View File
@@ -5,7 +5,7 @@ from docx import Document
from docx.enum.section import WD_ORIENT
from docx.enum.table import WD_TABLE_ALIGNMENT
from docx.enum.text import WD_ALIGN_PARAGRAPH
from docx.shared import Pt
from docx.shared import Pt, RGBColor
from app.exporters.common import MONEY_TEXT, format_date, format_period, project_requisite_lines
from app.exporters.ks3_dto import KS3ExportDocument
@@ -26,6 +26,14 @@ def render_ks3_word(doc: KS3ExportDocument) -> bytes:
run.bold = True
run.font.size = Pt(14)
if h.status == "cancelled":
mark = d.add_paragraph()
mark.alignment = WD_ALIGN_PARAGRAPH.CENTER
run = mark.add_run("СТОРНИРОВАН")
run.bold = True
run.font.size = Pt(12)
run.font.color.rgb = RGBColor(0xC0, 0x00, 0x00)
d.add_paragraph()
header_lines = project_requisite_lines(
+8 -8
View File
@@ -131,8 +131,11 @@ async def ks2_view(request: Request, project_id: int, ks2_id: int, db: Session =
line.sources.sort(key=lambda source: (source.daily_report_item.report.report_date,
source.daily_report_item.report.id,
source.daily_report_item.id))
from app.services.ks2_service import ks2_cancel_block_reason
cancel_reason = ks2_cancel_block_reason(db, project_id, ks2_id) if document.status != "cancelled" else None
return templates.TemplateResponse(name="ks2/view.html", context={
"request": request, "project": project, "document": document, "total": total,
"cancel_blocked_reason": cancel_reason,
})
@@ -179,14 +182,11 @@ async def ks2_issue(project_id: int, ks2_id: int, db: Session = Depends(get_db))
@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()
from app.services.ks2_service import KS2ValidationError, cancel_ks2
try:
cancel_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)
+8 -8
View File
@@ -128,9 +128,12 @@ async def ks3_view(request: Request, project_id: int, ks3_id: int, db: Session =
ks2_total = _ks2_total(link.ks2)
total += ks2_total
ks2_rows.append({"ks2": link.ks2, "total": ks2_total})
from app.services.ks3_service import ks3_cancel_block_reason
cancel_reason = ks3_cancel_block_reason(db, project_id, ks3_id) if document.status != "cancelled" else None
return templates.TemplateResponse(name="ks3/view.html", context={
"request": request, "project": project, "document": document,
"ks2_rows": ks2_rows, "total": total,
"cancel_blocked_reason": cancel_reason,
})
@@ -180,14 +183,11 @@ async def ks3_issue(project_id: int, ks3_id: int, db: Session = Depends(get_db))
@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()
from app.services.ks3_service import KS3ValidationError, cancel_ks3
try:
cancel_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)
+44 -1
View File
@@ -220,4 +220,47 @@ def project_ks2_totals(db: Session, project_id: int):
for document in documents:
rows.append({"document": document, "item_count": len(document.items),
"amount": sum((_decimal(line.amount) for line in document.items), ZERO)})
return rows
return rows
def ks2_cancel_block_reason(db: Session, project_id: int, ks2_id: int) -> str | None:
"""Return why KS-2 cannot be cancelled, or None if cancellation is allowed."""
from app.models.ks3 import KS3, KS3KS2
document = db.query(KS2).filter(KS2.id == ks2_id, KS2.project_id == project_id).first()
if document is None:
return "КС-2 не найден"
if document.status == "cancelled":
return "КС-2 уже сторнирован"
active_link = db.query(KS3KS2).join(KS3, KS3.id == KS3KS2.ks3_id).filter(
KS3KS2.ks2_id == ks2_id,
KS3.project_id == project_id,
KS3.status == "issued",
).first()
if active_link is not None:
ks3_doc = db.query(KS3).filter(KS3.id == active_link.ks3_id).first()
number = ks3_doc.number if ks3_doc else active_link.ks3_id
return f"КС-2 включён в действующий КС-3 №{number}. Сначала сторнируйте КС-3."
return None
def cancel_ks2(db: Session, project_id: int, ks2_id: int):
"""Cancel a KS-2 atomically. Blocked when linked to an issued KS-3."""
try:
reason = ks2_cancel_block_reason(db, project_id, ks2_id)
if reason is not None:
raise KS2ValidationError(reason)
document = db.query(KS2).filter(
KS2.id == ks2_id, KS2.project_id == project_id
).with_for_update().first()
if document is None:
raise KS2ValidationError("КС-2 не найден")
if document.status == "cancelled":
raise KS2ValidationError("КС-2 уже сторнирован")
document.status = "cancelled"
db.commit()
db.refresh(document)
return document
except Exception:
db.rollback()
raise
+47 -1
View File
@@ -1,6 +1,7 @@
from datetime import date
from decimal import Decimal, InvalidOperation
from sqlalchemy import func
from sqlalchemy.orm import Session, joinedload
from app.models.ks2 import KS2, KS2Item
@@ -176,4 +177,49 @@ def project_ks3_totals(db: Session, project_id: int):
"ks2_count": len(doc.links),
"amount": total,
})
return rows
return rows
def ks3_cancel_block_reason(db: Session, project_id: int, ks3_id: int) -> str | None:
"""Return why KS-3 cannot be cancelled, or None if cancellation is allowed."""
from decimal import Decimal as D
from app.models.payment import Payment, PaymentAllocation
document = db.query(KS3).filter(KS3.id == ks3_id, KS3.project_id == project_id).first()
if document is None:
return "КС-3 не найден"
if document.status == "cancelled":
return "КС-3 уже сторнирован"
paid = 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",
PaymentAllocation.amount > 0,
).scalar()
if D(str(paid or 0)) > 0:
return "На КС-3 распределены платежи. Сначала отмените распределения платежей."
return None
def cancel_ks3(db: Session, project_id: int, ks3_id: int):
"""Cancel a KS-3 atomically. Blocked when payment allocations exist."""
try:
reason = ks3_cancel_block_reason(db, project_id, ks3_id)
if reason is not None:
raise KS3ValidationError(reason)
document = db.query(KS3).filter(
KS3.id == ks3_id, KS3.project_id == project_id
).with_for_update().first()
if document is None:
raise KS3ValidationError("КС-3 не найден")
if document.status == "cancelled":
raise KS3ValidationError("КС-3 уже сторнирован")
document.status = "cancelled"
db.commit()
db.refresh(document)
return document
except Exception:
db.rollback()
raise
+6
View File
@@ -47,6 +47,11 @@
<div class="alert alert-success" role="alert">
КС-2 проведено. Документ не может быть изменён.
</div>
{% if cancel_blocked_reason %}
<div class="alert alert-warning" role="alert">
Сторнирование недоступно: {{ cancel_blocked_reason }}
</div>
{% else %}
<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"
@@ -54,6 +59,7 @@
</form>
</div>
{% endif %}
{% endif %}
<h4>Позиции</h4>
+6
View File
@@ -89,12 +89,18 @@
<div class="alert alert-success" role="alert">
КС-3 проведено. Документ не может быть изменён.
</div>
{% if cancel_blocked_reason %}
<div class="alert alert-warning" role="alert">
Сторнирование недоступно: {{ cancel_blocked_reason }}
</div>
{% else %}
<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>
{% endif %}
<a href="/projects/{{ project.id }}/ks3" class="btn btn-secondary">Назад к списку</a>
{% endif %}
{% endif %}