31 lines
1.2 KiB
Python
31 lines
1.2 KiB
Python
"""A player's balance, derived from the ledger (DAT-78) — never stored beside it."""
|
|||
|
|
|
||
|
|
from dataclasses import dataclass
|
||
|
|
|
||
|
|
from django.db.models import Q, Sum
|
||
|
|
|
||
|
|
from .models import Movement
|
||
|
|
|
||
|
|
|
||
|
|
@dataclass(frozen=True)
|
||
|
|
class Balance:
|
||
|
|
spendable_sats: int # confirmed funds, minus whatever a pending operation has already reserved
|
||
|
|
incoming_sats: int # funds in confirmation: pending credits, not spendable yet (WEB-21)
|
||
|
|
|
||
|
|
@property
|
||
|
|
def total_sats(self) -> int:
|
||
|
|
return self.spendable_sats + self.incoming_sats
|
||
|
|
|
||
|
|
|
||
|
|
def balance_of(user) -> Balance:
|
||
|
|
"""Spendable = confirmed lines + pending debits (a bet or withdrawal in flight reserves its
|
||
|
|
amount at once). Incoming = pending credits. Failed lines count for nothing."""
|
||
|
|
totals = Movement.objects.filter(user=user).aggregate(
|
||
|
|
confirmed=Sum("amount_sats", filter=Q(status=Movement.Status.CONFIRMED)),
|
||
|
|
pending_debits=Sum("amount_sats", filter=Q(status=Movement.Status.PENDING, amount_sats__lt=0)),
|
||
|
|
pending_credits=Sum("amount_sats", filter=Q(status=Movement.Status.PENDING, amount_sats__gt=0)),
|
||
|
|
)
|
||
|
|
return Balance(
|
||
|
|
spendable_sats=(totals["confirmed"] or 0) + (totals["pending_debits"] or 0),
|
||
|
|
incoming_sats=totals["pending_credits"] or 0,
|
||
|
|
)
|