315 lines
12 KiB
Python
315 lines
12 KiB
Python
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
|
||
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 _taken_ks2_ids(db: Session, project_id: int, exclude_ks3_id: int | None = None) -> set[int]:
|
||
"""KS-2 ids already linked to an issued KS-3 of this project.
|
||
|
||
Draft and cancelled KS-3 do not claim KS-2. exclude_ks3_id keeps the
|
||
current document's own selection available while editing.
|
||
"""
|
||
query = (
|
||
db.query(KS3KS2.ks2_id)
|
||
.join(KS3, KS3.id == KS3KS2.ks3_id)
|
||
.filter(KS3.project_id == project_id, KS3.status == "issued")
|
||
)
|
||
if exclude_ks3_id is not None:
|
||
query = query.filter(KS3.id != exclude_ks3_id)
|
||
return {row[0] for row in query.all()}
|
||
|
||
|
||
def _reject_if_taken_by_other_issued_ks3(db: Session, project_id: int, ks2_id: int,
|
||
ks2_number: str, exclude_ks3_id: int | None = None) -> None:
|
||
query = (
|
||
db.query(KS3KS2, KS3)
|
||
.join(KS3, KS3.id == KS3KS2.ks3_id)
|
||
.filter(
|
||
KS3KS2.ks2_id == ks2_id,
|
||
KS3.project_id == project_id,
|
||
KS3.status == "issued",
|
||
)
|
||
)
|
||
if exclude_ks3_id is not None:
|
||
query = query.filter(KS3.id != exclude_ks3_id)
|
||
taken = query.first()
|
||
if taken is not None:
|
||
_, other = taken
|
||
raise KS3ValidationError(
|
||
f"КС-2 №{ks2_number} уже включён в проведённый КС-3 №{other.number}"
|
||
)
|
||
|
||
|
||
def available_ks2(db: Session, project_id: int, exclude_ks3_id: int | None = None):
|
||
"""Return issued KS-2 documents available for inclusion in a KS-3.
|
||
|
||
KS-2 already linked to another issued KS-3 is excluded. Draft/cancelled
|
||
KS-3 do not block. exclude_ks3_id keeps the document's own KS-2 visible.
|
||
"""
|
||
taken = _taken_ks2_ids(db, project_id, exclude_ks3_id=exclude_ks3_id)
|
||
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:
|
||
if doc.id in taken:
|
||
continue
|
||
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")
|
||
conflict = db.query(KS3).filter(KS3.project_id == project_id, KS3.number == number)
|
||
if ks3_id is not None:
|
||
conflict = conflict.filter(KS3.id != ks3_id)
|
||
if conflict.first():
|
||
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} не проведён")
|
||
# Server-side guard: a KS-2 can belong to only one issued KS-3.
|
||
_reject_if_taken_by_other_issued_ks3(
|
||
db, project_id, ks2_id, ks2.number, exclude_ks3_id=ks3_id,
|
||
)
|
||
|
||
# Replace links: delete old rows first so re-selecting the same KS-2
|
||
# does not hit the unique constraint during the autoflush below.
|
||
document.links.clear()
|
||
db.flush()
|
||
for ks2_id in seen_ks2:
|
||
document.links.append(KS3KS2(ks2_id=ks2_id))
|
||
|
||
# Successful draft change invalidates existing draft artifacts (same tx).
|
||
if ks3_id is not None:
|
||
from app.services.document_artifact_service import invalidate_artifacts
|
||
invalidate_artifacts(
|
||
db,
|
||
project_id=project_id,
|
||
document_type="KS3",
|
||
document_id=document.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."""
|
||
artifact = None
|
||
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} не проведён")
|
||
_reject_if_taken_by_other_issued_ks3(
|
||
db, project_id, ks2.id, ks2.number, exclude_ks3_id=document.id,
|
||
)
|
||
|
||
document.status = "issued"
|
||
|
||
# Generate and persist the official artifact inside this transaction.
|
||
# KS-3 issue must NOT touch KS-2 artifacts.
|
||
from app.exporters.ks3_dto import build_ks3_export_dto
|
||
from app.exporters.word.ks3_renderer import (
|
||
TEMPLATE_TYPE as KS3_TEMPLATE_TYPE,
|
||
TEMPLATE_VERSION as KS3_TEMPLATE_VERSION,
|
||
render_ks3_word,
|
||
)
|
||
from app.services.document_artifact_service import persist_artifact, remove_artifact_file
|
||
|
||
dto = build_ks3_export_dto(db, document)
|
||
content = render_ks3_word(dto)
|
||
artifact = persist_artifact(
|
||
db,
|
||
project_id=project_id,
|
||
document_type="KS3",
|
||
document_id=document.id,
|
||
format="docx",
|
||
template_type=KS3_TEMPLATE_TYPE,
|
||
template_version=KS3_TEMPLATE_VERSION,
|
||
content=content,
|
||
dto=dto,
|
||
)
|
||
|
||
db.commit()
|
||
db.refresh(document)
|
||
return document
|
||
except Exception:
|
||
db.rollback()
|
||
if artifact is not None:
|
||
remove_artifact_file(artifact)
|
||
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
|
||
|
||
|
||
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 |