Open-source personal finance manager. Self-hosted, privacy-first.
fix(groups): compute balances from who actually paid (#1198)
Shayn Hornik9665fb6654d7
diff --git a/backend/app/services/balance_service.py b/backend/app/services/balance_service.pyindex fcdb91d8..76697d21 100644--- a/backend/app/services/balance_service.py+++ b/backend/app/services/balance_service.py@@ -1,16 +1,20 @@"""Group balance computation.-The model assumes the group owner is the implicit payer of every-transaction with splits — i.e. the `is_self` member of the group is the-one whose bank account holds the parent transaction.--For each non-self member M, we compute, per currency:- + sum of M's split shares on owner-paid transactions (M owes self)- + settlements where from=self, to=M (self lent to M)- - settlements where from=M, to=self (M paid self back)--A positive value means M owes the owner; negative means the owner owes M.-Mixed currencies are kept as separate lines — no FX conversion in v1.+Each split transaction was paid by one member: the member linked to the+Securo user who recorded it (`Transaction.user_id`), falling back to the+group's stored `is_self` member and then to the member linked to the group+owner. Every other member's split share is a debt from that member to the+payer. Settlements reduce the debt of `from` towards `to`.++That gives one pairwise ledger per group, the same for everyone. The+response projects it onto the caller (`self_member`, the caller's own+member): for each other member M, per currency, a positive amount means M+owes the caller and a negative amount means the caller owes M. Pairs that+don't involve the caller are left out, and so are a member's pairs with+an owner who isn't a member of the group.++Mixed currencies are kept as separate lines (each line also carries its+amount in the group's default currency)."""import uuid@@ -26,6 +30,9 @@ from app.models.group_settlement import GroupSettlementfrom app.models.transaction import Transactionfrom app.models.transaction_split import TransactionSplit+# Stands in for a group owner who isn't one of the group's members.+_GROUP_OWNER = uuid.UUID(int=0)+async def compute_balances(session: AsyncSession,@@ -46,41 +53,80 @@ async def compute_balances(select(GroupMember).where(GroupMember.group_id == group_id))members = list(members_result.scalars().all())- self_member = next((m for m in members if m.is_self), None)- # member_id -> currency -> Decimal- totals: dict[uuid.UUID, dict[str, Decimal]] = defaultdict(+ # get_group_visible projects `is_self` onto the caller in memory, so+ # read the stored flag with a column select (it bypasses the identity+ # map): it marks the owner's own member.+ stored_self_ids = set(+ (+ await session.execute(+ select(GroupMember.id).where(+ GroupMember.group_id == group_id,+ GroupMember.is_self.is_(True),+ )+ )+ ).scalars().all()+ )+ member_by_user = {m.linked_user_id: m.id for m in members if m.linked_user_id is not None}+ owner_self = next((m for m in members if m.id in stored_self_ids), None)++ # The caller's own member, by the same rule as group_service's "(you)"+ # tag: the member linked to the caller, else the owner's stored+ # unlinked self member when the caller is the owner.+ self_member = next((m for m in members if m.linked_user_id == user_id), None)+ if self_member is None and user_id == group.user_id and owner_self is not None:+ if owner_self.linked_user_id is None:+ self_member = owner_self++ default_payer = owner_self.id if owner_self is not None else None+ if default_payer is None:+ default_payer = member_by_user.get(group.user_id)+ if default_payer is None:+ # The owner recorded it but isn't a member of the group: the shares+ # are owed to the owner, who sees them as before.+ default_payer = _GROUP_OWNER++ # (debtor, creditor) -> currency -> Decimal+ owed: dict[tuple[uuid.UUID, uuid.UUID], dict[str, Decimal]] = defaultdict(lambda: defaultdict(lambda: Decimal("0")))- # Splits — each non-self member's share of an owner-paid transaction- # is what they owe the self member.+ # Splits: each member's share of a transaction someone else paid is+ # what they owe the payer.splits_result = await session.execute(- select(TransactionSplit, Transaction.currency)+ select(TransactionSplit, Transaction.currency, Transaction.user_id).join(Transaction, TransactionSplit.transaction_id == Transaction.id).join(GroupMember, TransactionSplit.group_member_id == GroupMember.id).where(GroupMember.group_id == group_id))- for split, currency in splits_result.all():- if self_member is not None and split.group_member_id == self_member.id:+ for split, currency, recorder_id in splits_result.all():+ payer = member_by_user.get(recorder_id, default_payer)+ if split.group_member_id == payer:continue- totals[split.group_member_id][currency] += Decimal(str(split.share_amount))-- # Settlements — adjust the pairwise balance with the self member.- if self_member is not None:- settlements_result = await session.execute(- select(GroupSettlement).where(GroupSettlement.group_id == group_id)- )- for s in settlements_result.scalars().all():- amount = Decimal(str(s.amount))- if s.from_member_id == self_member.id:- # Self lent to the other party — increases what they owe.- totals[s.to_member_id][s.currency] += amount- elif s.to_member_id == self_member.id:- # Other party paid self back — reduces what they owe.- totals[s.from_member_id][s.currency] -= amount- # Cross-member settlements (neither side is self) don't affect- # the owner's balance ledger and are ignored here.+ owed[(split.group_member_id, payer)][currency] += Decimal(str(split.share_amount))++ # Settlements: `from` paid `to`, which reduces what `from` owes `to`.+ settlements_result = await session.execute(+ select(GroupSettlement).where(GroupSettlement.group_id == group_id)+ )+ for s in settlements_result.scalars().all():+ owed[(s.from_member_id, s.to_member_id)][s.currency] -= Decimal(str(s.amount))++ # Project onto the caller: member_id -> currency -> what they owe the caller.+ totals: dict[uuid.UUID, dict[str, Decimal]] = defaultdict(+ lambda: defaultdict(lambda: Decimal("0"))+ )+ caller = self_member.id if self_member is not None else _GROUP_OWNER+ for (debtor, creditor), by_currency in owed.items():+ # A member can't be shown a debt to or from an owner who has no+ # member row: there is no name or GroupMember id to show it under.+ if self_member is not None and _GROUP_OWNER in (debtor, creditor):+ continue+ for currency, amount in by_currency.items():+ if creditor == caller:+ totals[debtor][currency] += amount+ elif debtor == caller:+ totals[creditor][currency] -= amount# FX-convert each line to the group's default currency so the# frontend can roll cross-currency lines up into a single KPIdiff --git a/backend/tests/test_group_visibility.py b/backend/tests/test_group_visibility.pyindex 4f2e091f..c6c0c5d8 100644--- a/backend/tests/test_group_visibility.py+++ b/backend/tests/test_group_visibility.py@@ -10,14 +10,18 @@ import bcryptimport pytestfrom sqlalchemy.ext.asyncio import AsyncSession+from app.models.account import Account+from app.models.transaction import Transactionfrom app.models.user import Userfrom app.models.workspace import Workspacefrom app.schemas.group import GroupCreate, GroupMemberCreatefrom app.schemas.group_settlement import GroupSettlementCreate+from app.schemas.transaction_split import TransactionSplitInput, TransactionSplitsInputfrom app.services import (balance_service,group_service,settlement_service,+ split_service,workspace_service,)@@ -302,3 +306,146 @@ async def test_linked_member_cannot_settle_someone_elses_debt(date=date.today(),),)+++async def _record_split_expense(session, user, workspace, members, amount):+ """`user` pays `amount` from an account in `workspace`, split equally."""+ account = Account(+ id=uuid.uuid4(), user_id=user.id, workspace_id=workspace.id, name="Wallet",+ type="checking", balance=Decimal("0"), currency="USD",+ )+ session.add(account)+ await session.flush()+ tx = Transaction(+ id=uuid.uuid4(), user_id=user.id, workspace_id=workspace.id, account_id=account.id,+ description="Dinner", amount=Decimal(amount), currency="USD", date=date.today(),+ type="debit", source="manual",+ )+ session.add(tx)+ await session.flush()+ await split_service.replace_splits(+ session,+ tx,+ TransactionSplitsInput(+ share_type="equal",+ splits=[TransactionSplitInput(group_member_id=m.id) for m in members],+ ),+ user.id,+ )+ await session.commit()+++async def _ledger(session, group_id, workspace_id, user_id):+ balances = await balance_service.compute_balances(session, group_id, workspace_id, user_id)+ assert balances is not None+ return {ln["member_id"]: ln["amount"] for ln in balances["lines"]}+++async def test_balances_follow_the_member_who_paid(+ session: AsyncSession, test_user, test_workspace+):+ """Issue #1062: B, linked from their own workspace, pays two split+ expenses. A owes B 15.00 in both views; before, each saw the other as+ the debtor."""+ other, other_ws = await _make_user_with_workspace(session, "[email protected]")+ group = await group_service.create_group(+ session, test_workspace.id, test_user.id, GroupCreate(name="Flat")+ )+ a = await group_service.create_member(+ session, group.id, test_workspace.id, GroupMemberCreate(name="A", email=test_user.email)+ )+ b = await group_service.create_member(+ session, group.id, test_workspace.id, GroupMemberCreate(name="B", email="[email protected]")+ )+ assert a is not None and b is not None+ assert a.linked_user_id == test_user.id and b.linked_user_id == other.id++ await _record_split_expense(session, other, other_ws, [a, b], "10.00")+ await _record_split_expense(session, other, other_ws, [a, b], "20.00")++ # B's view: A owes B.+ assert await _ledger(session, group.id, other_ws.id, other.id) == {a.id: Decimal("15.00")}+ # A's view: A owes B (negative), not the mirror image.+ assert await _ledger(session, group.id, test_workspace.id, test_user.id) == {+ b.id: Decimal("-15.00")+ }+++async def test_balances_net_expenses_paid_by_both_sides(+ session: AsyncSession, test_user, test_workspace+):+ """The owner's own member is the stored, unlinked `is_self` row. The+ owner pays 40.00 and B pays 10.00, both split equally: B owes 15.00+ net, seen the same way from both sides, and a settlement from B to the+ owner reduces it for both."""+ other, other_ws = await _make_user_with_workspace(session, "[email protected]")+ group = await group_service.create_group(+ session, test_workspace.id, test_user.id, GroupCreate(name="Trip")+ )+ me = await group_service.create_member(+ session, group.id, test_workspace.id, GroupMemberCreate(name="Me", is_self=True)+ )+ b = await group_service.create_member(+ session, group.id, test_workspace.id, GroupMemberCreate(name="B", email="[email protected]")+ )+ assert me is not None and b is not None++ await _record_split_expense(session, test_user, test_workspace, [me, b], "40.00")+ await _record_split_expense(session, other, other_ws, [me, b], "10.00")++ assert await _ledger(session, group.id, test_workspace.id, test_user.id) == {+ b.id: Decimal("15.00")+ }+ assert await _ledger(session, group.id, other_ws.id, other.id) == {me.id: Decimal("-15.00")}++ await settlement_service.create_settlement(+ session,+ group.id,+ other_ws.id,+ other.id,+ GroupSettlementCreate(+ from_member_id=b.id, to_member_id=me.id, amount=Decimal("5.00"),+ currency="USD", date=date.today(),+ ),+ )+ await session.commit()++ assert await _ledger(session, group.id, test_workspace.id, test_user.id) == {+ b.id: Decimal("10.00")+ }+ assert await _ledger(session, group.id, other_ws.id, other.id) == {me.id: Decimal("-10.00")}+++async def test_owner_without_member_row_is_not_shown_to_members(+ session: AsyncSession, test_user, test_workspace+):+ """The owner isn't a member of the group and pays 30.00 split between B+ and C; B then pays 20.00 split the same way. The owner sees both debts+ to them. B sees only C's debt: the owner has no member row, so there is+ no name or id to show B's debt to them under."""+ other, other_ws = await _make_user_with_workspace(session, "[email protected]")+ group = await group_service.create_group(+ session, test_workspace.id, test_user.id, GroupCreate(name="Trip")+ )+ b = await group_service.create_member(+ session, group.id, test_workspace.id, GroupMemberCreate(name="B", email="[email protected]")+ )+ c = await group_service.create_member(+ session, group.id, test_workspace.id, GroupMemberCreate(name="C")+ )+ assert b is not None and c is not None++ await _record_split_expense(session, test_user, test_workspace, [b, c], "30.00")+ await _record_split_expense(session, other, other_ws, [b, c], "20.00")++ assert await _ledger(session, group.id, test_workspace.id, test_user.id) == {+ b.id: Decimal("15.00"),+ c.id: Decimal("15.00"),+ }+ b_view = await balance_service.compute_balances(session, group.id, other_ws.id, other.id)+ assert b_view is not None+ assert b_view["self_member_id"] == b.id+ assert {ln["member_id"]: ln["amount"] for ln in b_view["lines"]} == {c.id: Decimal("10.00")}