Files
work-volume-tracker/app/services/payment_service.py
T
Арсентьев Александр 9cfb341774 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.
2026-09-27 13:38:45 +03:00

220 lines
8.1 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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