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:
Арсентьев Александр
2026-10-08 20:24:48 +03:00
parent e7abc7c86c
commit 1af2a70406
5 changed files with 780 additions and 8 deletions
+30 -2
View File
@@ -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)