finance_balance.py 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. """Canonical definition and synchronization of a user's personal balance."""
  2. from sqlalchemy import and_, func, or_, select
  3. from sqlalchemy.ext.asyncio import AsyncSession
  4. from backend.app.models.finance import CostCenter, UserWallet, WalletTransaction
  5. def transaction_affects_personal_balance(
  6. user_id: int,
  7. cost_center_id: int | None,
  8. *,
  9. is_private: bool = False,
  10. owner_user_id: int | None = None,
  11. ) -> bool:
  12. """Apply the canonical definition to already-loaded transaction data."""
  13. return cost_center_id is None or (is_private and owner_user_id == user_id)
  14. def personal_balance_condition(user_id: int):
  15. """Return the SQL condition for transactions in a personal wallet.
  16. Unassigned transactions and transactions assigned to the user's own
  17. private cost center are personal. Shared cost centers are not.
  18. """
  19. return or_(
  20. WalletTransaction.cost_center_id.is_(None),
  21. and_(CostCenter.is_private.is_(True), CostCenter.owner_user_id == user_id),
  22. )
  23. async def calculate_personal_balance(db: AsyncSession, user_id: int) -> float:
  24. result = await db.execute(
  25. select(func.coalesce(func.sum(WalletTransaction.amount), 0.0))
  26. .select_from(WalletTransaction)
  27. .outerjoin(CostCenter, WalletTransaction.cost_center_id == CostCenter.id)
  28. .where(WalletTransaction.user_id == user_id, personal_balance_condition(user_id))
  29. )
  30. return round(float(result.scalar_one() or 0.0), 2)
  31. async def is_personal_transaction(db: AsyncSession, user_id: int, cost_center_id: int | None) -> bool:
  32. if cost_center_id is None:
  33. return True
  34. result = await db.execute(
  35. select(CostCenter.is_private, CostCenter.owner_user_id).where(CostCenter.id == cost_center_id)
  36. )
  37. center = result.one_or_none()
  38. if center is None:
  39. return False
  40. return transaction_affects_personal_balance(
  41. user_id,
  42. cost_center_id,
  43. is_private=bool(center.is_private),
  44. owner_user_id=center.owner_user_id,
  45. )
  46. async def sync_personal_wallet_balance(db: AsyncSession, wallet: UserWallet) -> float:
  47. balance = await calculate_personal_balance(db, wallet.user_id)
  48. wallet.balance = balance
  49. db.add(wallet)
  50. return balance