Files
work-volume-tracker/app/services/payment_service.py
T
Арсентьев Александр 1af2a70406 fix: payments validation and in-place allocation edits
Close the KS-2 -> KS-3 -> Payment -> allocation -> aggregates chain for V1.
Two real defects fixed:

- NaN/Infinity payment or allocation amounts raised InvalidOperation (500)
  or were silently stored; they are now finite-value validation errors (400)
  via _parse_money / is_finite checks.
- Editing an allocation to the same KS-3 hit uq_payment_ks3 because
  clear() deferred the DELETE past the new INSERT; allocations are now
  updated in place.

Financial semantics unchanged: full active payment counts as received,
storno keeps historical allocations while excluding the payment from
active aggregates. Decimal arithmetic preserved.
2026-10-08 20:24:48 +03:00

277 lines
11 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_money(value, label):
"""Parse a user-supplied money value; reject NaN/Infinity and bad input."""
try:
amount = Decimal(str(value).strip().replace(",", ".")) if value is not None else None
except (InvalidOperation, ValueError, TypeError) as exc:
raise PaymentValidationError(f"{label}: неверное число") from exc
if amount is None or not amount.is_finite():
raise PaymentValidationError(f"{label}: неверное число")
return amount
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:
amount = _decimal(amount) if not isinstance(amount, Decimal) else amount
# Decimal('NaN')/('Infinity') make comparisons raise or pass silently —
# reject them explicitly so the form gets 400, not 500 / a bad row.
if not amount.is_finite():
raise PaymentValidationError("Сумма платежа должна быть конечным числом")
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 not alloc_amount.is_finite():
raise PaymentValidationError("Сумма распределения должна быть конечным числом")
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("Платёж не найден")
if payment.status == "cancelled":
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
# Update allocations in place: clearing + re-adding the same KS-3 would
# INSERT before the deferred DELETE and hit uq_payment_ks3.
existing = {a.ks3_id: a for a in payment.allocations}
for ks3_id, alloc_amount in alloc_map.items():
if ks3_id in existing:
existing[ks3_id].amount = alloc_amount
else:
payment.allocations.append(
PaymentAllocation(ks3_id=ks3_id, amount=alloc_amount)
)
for ks3_id, alloc in existing.items():
if ks3_id not in alloc_map:
payment.allocations.remove(alloc)
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. Blocked for cancelled payments."""
try:
payment = db.query(Payment).filter(
Payment.id == payment_id, Payment.project_id == project_id
).first()
if payment is None:
raise PaymentValidationError("Платёж не найден")
if payment.status == "cancelled":
raise PaymentValidationError("Сторнированный платёж нельзя удалить")
db.delete(payment)
db.commit()
except Exception:
db.rollback()
raise
def cancel_payment(db: Session, project_id: int, payment_id: int):
"""
Storno a payment atomically.
The payment is kept in history with status=cancelled. Its allocations are
preserved as historical records but excluded from active payment aggregates
(received / distributed / unallocated / outstanding) via status filters.
"""
try:
payment = db.query(Payment).filter(
Payment.id == payment_id, Payment.project_id == project_id
).first()
if payment is None:
raise PaymentValidationError("Платёж не найден")
if payment.status == "cancelled":
raise PaymentValidationError("Платёж уже сторнирован")
payment.status = "cancelled"
db.commit()
db.refresh(payment)
return payment
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