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.
This commit is contained in:
+10
-6
@@ -11,8 +11,8 @@ 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, cancel_payment, delete_payment,
|
||||
project_payments, save_payment,
|
||||
PaymentValidationError, _parse_money, available_ks3_for_payment, cancel_payment,
|
||||
delete_payment, project_payments, save_payment,
|
||||
)
|
||||
from app.utils.formatters import format_money
|
||||
|
||||
@@ -84,14 +84,16 @@ async def payment_create(request: Request, project_id: int,
|
||||
if k.startswith("alloc_") and v.strip():
|
||||
try:
|
||||
ks3_id = int(k.removeprefix("alloc_"))
|
||||
alloc_amount = Decimal(v.strip().replace(",", "."))
|
||||
alloc_amount = _parse_money(v, f"Распределение КС-3 {ks3_id}")
|
||||
if alloc_amount > 0:
|
||||
allocations.append({"ks3_id": ks3_id, "amount": alloc_amount})
|
||||
except PaymentValidationError:
|
||||
raise
|
||||
except (ValueError, TypeError):
|
||||
pass
|
||||
try:
|
||||
parsed_date = date.fromisoformat(payment_date)
|
||||
parsed_amount = Decimal(amount.strip().replace(",", "."))
|
||||
parsed_amount = _parse_money(amount, "Сумма платежа")
|
||||
payment = save_payment(
|
||||
db, project_id, parsed_date, parsed_amount, currency, comment,
|
||||
allocations, document_number=document_number or None,
|
||||
@@ -136,14 +138,16 @@ async def payment_update(request: Request, project_id: int, payment_id: int,
|
||||
if k.startswith("alloc_") and v.strip():
|
||||
try:
|
||||
ks3_id = int(k.removeprefix("alloc_"))
|
||||
alloc_amount = Decimal(v.strip().replace(",", "."))
|
||||
alloc_amount = _parse_money(v, f"Распределение КС-3 {ks3_id}")
|
||||
if alloc_amount > 0:
|
||||
allocations.append({"ks3_id": ks3_id, "amount": alloc_amount})
|
||||
except PaymentValidationError:
|
||||
raise
|
||||
except (ValueError, TypeError):
|
||||
pass
|
||||
try:
|
||||
parsed_date = date.fromisoformat(payment_date)
|
||||
parsed_amount = Decimal(amount.strip().replace(",", "."))
|
||||
parsed_amount = _parse_money(amount, "Сумма платежа")
|
||||
payment = save_payment(
|
||||
db, project_id, parsed_date, parsed_amount, currency, comment,
|
||||
allocations, document_number=document_number or None,
|
||||
|
||||
@@ -22,6 +22,17 @@ def _decimal(value):
|
||||
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
|
||||
@@ -117,6 +128,11 @@ def save_payment(db: Session, project_id: int, payment_date: date,
|
||||
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()
|
||||
@@ -129,6 +145,8 @@ def save_payment(db: Session, project_id: int, payment_date: date,
|
||||
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:
|
||||
@@ -177,9 +195,19 @@ def save_payment(db: Session, project_id: int, payment_date: date,
|
||||
payment.currency = currency
|
||||
payment.comment = (comment or "").strip() or None
|
||||
|
||||
payment.allocations.clear()
|
||||
# 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():
|
||||
payment.allocations.append(PaymentAllocation(ks3_id=ks3_id, amount=alloc_amount))
|
||||
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)
|
||||
|
||||
Reference in New Issue
Block a user