feat(splits): add split expenses for shared group costs

Track expenses shared with other people (trips, flats, dinners) and settle
up with the fewest payments.

- Events with WYGIWYH users and people without an account, who join through
  a share link and pick a password on first sign-in
- Equal, exact, percentage and share-weight splits that always add up
- Balances, a minimal settle-up plan and an activity feed showing what each
  item means for you
- Link items to your own transactions; recording a payment marks planned
  ones as paid
- Share menu: printable PDF report and PNG images of the summary, settle-up
  and balances (adds modern-screenshot)
- Only the two people involved or the organizer can record a payment;
  members can leave events they don't organize
This commit is contained in:
Herculino Trotta committed 2026-11-20 19:43:23 -03:00
1 parent f558d52ac6
commit 77bf2d7bdb
47 files changed
+5612

No files matched your search

Whitespace-only changes.
+18
View File
@@ -0,0 +1,18 @@
from django.db import transaction as db_transaction
from apps.splits.auth import SplitActor
from apps.splits.models import SplitTransactionLink
@db_transaction.atomic
def leave_event(actor: SplitActor):
"""A non-organizer WYGIWYH user leaves: removed if they have no history, else deactivated."""
# Their own links only; the linked transactions stay in their accounts
SplitTransactionLink.objects.filter(event=actor.event, user=actor.user).delete()
participant = actor.participant
if participant.can_be_deleted():
participant.delete()
else:
# Keep their expenses and payments so everyone else's balances stay right
participant.is_active = False
participant.save(update_fields=["is_active"])
+258
View File
@@ -0,0 +1,258 @@
from dataclasses import dataclass
from decimal import Decimal, ROUND_HALF_UP
from django.db.models import Sum
from apps.splits.models import (
SplitEvent,
SplitExpense,
SplitExpenseShare,
SplitParticipant,
SplitPayment,
)
from apps.splits.services.splitting import quantize_unit
@dataclass(frozen=True)
class ParticipantBalance:
participant: SplitParticipant
total_paid: Decimal
total_owed: Decimal
payments_sent: Decimal
payments_received: Decimal
net_balance: Decimal # > 0 means others owe this participant; < 0 means this participant owes others
@dataclass(frozen=True)
class SettlementTransfer:
from_participant: SplitParticipant
to_participant: SplitParticipant
amount: Decimal
def calculate_event_balances(event: SplitEvent) -> list[ParticipantBalance]:
"""Compute exact per-participant balances for an event.
net_balance = total_paid - total_owed + payments_sent - payments_received
> 0 => participant is owed money (creditor)
< 0 => participant owes money (debtor)
= 0 => settled
"""
unit = quantize_unit(event.currency.decimal_places)
zero = Decimal("0").quantize(unit)
participants = list(event.participants.all().order_by("-is_active", "name", "id"))
if not participants:
return []
paid_map = {
row["paid_by_id"]: row["total"] or zero
for row in SplitExpense.objects.filter(event=event)
.values("paid_by_id")
.annotate(total=Sum("amount"))
}
owed_map = {
row["participant_id"]: row["total"] or zero
for row in SplitExpenseShare.objects.filter(expense__event=event)
.values("participant_id")
.annotate(total=Sum("amount"))
}
sent_map = {
row["from_participant_id"]: row["total"] or zero
for row in SplitPayment.objects.filter(event=event)
.values("from_participant_id")
.annotate(total=Sum("amount"))
}
received_map = {
row["to_participant_id"]: row["total"] or zero
for row in SplitPayment.objects.filter(event=event)
.values("to_participant_id")
.annotate(total=Sum("amount"))
}
balances: list[ParticipantBalance] = []
for p in participants:
paid = paid_map.get(p.id, zero).quantize(unit, rounding=ROUND_HALF_UP)
owed = owed_map.get(p.id, zero).quantize(unit, rounding=ROUND_HALF_UP)
sent = sent_map.get(p.id, zero).quantize(unit, rounding=ROUND_HALF_UP)
received = received_map.get(p.id, zero).quantize(unit, rounding=ROUND_HALF_UP)
net = (paid - owed + sent - received).quantize(unit, rounding=ROUND_HALF_UP)
balances.append(
ParticipantBalance(
participant=p,
total_paid=paid,
total_owed=owed,
payments_sent=sent,
payments_received=received,
net_balance=net,
)
)
return balances
def simplify_debts(
balances: list[ParticipantBalance],
decimal_places: int = 2,
) -> list[SettlementTransfer]:
"""Find a minimal-roundtrip set of settlement transfers.
Strategy:
1. Drop zero-balance participants.
2. Eliminate exact 1-to-1 debtor/creditor matches first (each removes 2
participants in 1 transfer — strictly optimal).
3. For small remaining groups (<= 14 non-zero participants), find the
maximum number of disjoint zero-sum subsets via DP/bitmask to achieve
the provably minimum number of transfers (N - K transfers for K subsets).
4. Within each zero-sum subset (or for larger groups directly), greedily
match largest debtor to largest creditor so there are zero roundtrips.
"""
unit = quantize_unit(decimal_places)
zero = Decimal("0").quantize(unit)
# Map to integer minor units for exact subset-sum math
scale = int(Decimal("1") / unit)
debtors: list[list] = [] # [participant, int_amount_owed]
creditors: list[list] = [] # [participant, int_amount_owed_to_them]
for b in balances:
val = int((b.net_balance * scale).to_integral_value(rounding=ROUND_HALF_UP))
if val < 0:
debtors.append([b.participant, -val])
elif val > 0:
creditors.append([b.participant, val])
transfers: list[SettlementTransfer] = []
# Step 1: Exact 1-to-1 matches (strictly optimal)
remaining_debtors: list[list] = []
for d in debtors:
matched_idx = next(
(i for i, c in enumerate(creditors) if c[1] == d[1]),
None,
)
if matched_idx is not None:
c = creditors.pop(matched_idx)
transfers.append(
SettlementTransfer(
from_participant=d[0],
to_participant=c[0],
amount=(Decimal(d[1]) * unit).quantize(unit),
)
)
else:
remaining_debtors.append(d)
debtors = remaining_debtors
# Combine remaining signed items for subset decomposition
items: list[tuple[SplitParticipant, int]] = [
(d[0], -d[1]) for d in debtors
] + [(c[0], c[1]) for c in creditors]
if not items:
return transfers
def _greedy_settle(subset: list[tuple[SplitParticipant, int]]) -> list[SettlementTransfer]:
sub_debtors = sorted(
[[p, -amt] for p, amt in subset if amt < 0],
key=lambda x: (-x[1], x[0].id),
)
sub_creditors = sorted(
[[p, amt] for p, amt in subset if amt > 0],
key=lambda x: (-x[1], x[0].id),
)
out: list[SettlementTransfer] = []
i = j = 0
while i < len(sub_debtors) and j < len(sub_creditors):
d = sub_debtors[i]
c = sub_creditors[j]
pay = min(d[1], c[1])
if pay > 0:
out.append(
SettlementTransfer(
from_participant=d[0],
to_participant=c[0],
amount=(Decimal(pay) * unit).quantize(unit),
)
)
d[1] -= pay
c[1] -= pay
if d[1] == 0:
i += 1
if c[1] == 0:
j += 1
return out
# Step 2: Optimal zero-sum subset partition for <= 14 remaining participants
n = len(items)
if 3 <= n <= 14:
full_mask = (1 << n) - 1
subset_sum = [0] * (1 << n)
for mask in range(1, 1 << n):
lsb = mask & -mask
idx = lsb.bit_length() - 1
subset_sum[mask] = subset_sum[mask ^ lsb] + items[idx][1]
# dp[mask] = max number of disjoint non-empty zero-sum subsets partitioning mask
dp = [-1] * (1 << n)
parent = [0] * (1 << n)
dp[0] = 0
zero_masks = [m for m in range(1, 1 << n) if subset_sum[m] == 0]
# Minimal zero-sum subsets (no proper non-empty zero-sum submask)
for mask in zero_masks:
best = 1
best_sub = mask
sub = (mask - 1) & mask
while sub > 0:
if subset_sum[sub] == 0 and dp[mask ^ sub] > 0:
cand = dp[sub] + dp[mask ^ sub]
if cand > best:
best = cand
best_sub = sub
sub = (sub - 1) & mask
dp[mask] = best
parent[mask] = best_sub
if dp[full_mask] > 0:
# Reconstruct disjoint zero-sum subsets
partitions: list[int] = []
stack = [full_mask]
while stack:
m = stack.pop()
sub = parent[m]
if sub == m:
partitions.append(m)
else:
stack.append(sub)
stack.append(m ^ sub)
for part_mask in partitions:
subset = [items[i] for i in range(n) if part_mask & (1 << i)]
transfers.extend(_greedy_settle(subset))
else:
transfers.extend(_greedy_settle(items))
else:
transfers.extend(_greedy_settle(items))
# Deterministic display order: largest transfer first, then names
transfers.sort(
key=lambda t: (-t.amount, t.from_participant.name.lower(), t.to_participant.name.lower())
)
return transfers
def get_event_settlement_summary(event: SplitEvent) -> dict:
balances = calculate_event_balances(event)
transfers = simplify_debts(balances, decimal_places=event.currency.decimal_places)
total_spent = sum(
(b.total_paid for b in balances),
Decimal("0").quantize(quantize_unit(event.currency.decimal_places)),
)
return {
"balances": balances,
"balances_by_id": {b.participant.id: b for b in balances},
"transfers": transfers,
"total_spent": total_spent,
}
+183
View File
@@ -0,0 +1,183 @@
from dataclasses import dataclass
from decimal import Decimal, ROUND_DOWN, ROUND_HALF_UP
from typing import Iterable
from django.core.exceptions import ValidationError
from django.utils.formats import number_format
from django.utils.translation import gettext_lazy as _
from apps.splits.models import SplitExpense, SplitExpenseShare, SplitParticipant
@dataclass(frozen=True)
class ComputedShare:
participant: SplitParticipant
amount: Decimal
percentage: Decimal | None = None
shares: Decimal | None = None
def quantize_unit(decimal_places: int) -> Decimal:
places = max(0, min(int(decimal_places), 6))
return Decimal("1").scaleb(-places)
def _distribute_remainder(
total: Decimal,
raw_amounts: list[Decimal],
unit: Decimal,
) -> list[Decimal]:
"""Quantize each raw amount down to `unit` and distribute leftover units
by largest fractional remainder (Hamilton / largest-remainder method).
Guarantees sum(result) == total quantized to `unit`.
"""
quantized_total = total.quantize(unit, rounding=ROUND_HALF_UP)
floored = [amt.quantize(unit, rounding=ROUND_DOWN) for amt in raw_amounts]
remainder = quantized_total - sum(floored, Decimal("0"))
if remainder == 0:
return floored
steps = int((remainder / unit).to_integral_value(rounding=ROUND_HALF_UP))
step_sign = unit if steps > 0 else -unit
steps = abs(steps)
# Order indices by largest fractional remainder (tie-break by original index)
remainders = [
(raw - flr, -idx, idx)
for idx, (raw, flr) in enumerate(zip(raw_amounts, floored))
]
remainders.sort(reverse=True)
result = list(floored)
for i in range(steps):
target_idx = remainders[i % len(remainders)][2]
result[target_idx] += step_sign
return result
def compute_expense_shares(
*,
total_amount: Decimal,
split_type: str,
participants: Iterable[SplitParticipant],
decimal_places: int = 2,
values_by_participant_id: dict[int, Decimal] | None = None,
) -> list[ComputedShare]:
"""Compute exact, penny-balanced shares for a SplitExpense.
`values_by_participant_id` maps participant.id -> Decimal:
- EQUAL: ignored (all provided participants split equally)
- EXACT: exact amount per participant
- PERCENTAGE: percentage (0..100) per participant, must sum to 100
- SHARES: positive share weight per participant
"""
participant_list = list(participants)
if not participant_list:
raise ValidationError(_("Select at least one participant for this expense."))
unit = quantize_unit(decimal_places)
total = Decimal(total_amount).quantize(unit, rounding=ROUND_HALF_UP)
if total <= 0:
raise ValidationError(_("Expense amount must be greater than zero."))
values = values_by_participant_id or {}
if split_type == SplitExpense.SplitType.EQUAL:
count = Decimal(len(participant_list))
raw = [total / count for _ in participant_list]
amounts = _distribute_remainder(total, raw, unit)
return [
ComputedShare(participant=p, amount=amt)
for p, amt in zip(participant_list, amounts)
]
if split_type == SplitExpense.SplitType.EXACT:
amounts: list[Decimal] = []
for p in participant_list:
val = values.get(p.id, Decimal("0"))
if val < 0:
raise ValidationError(
_("Exact amount for %(name)s cannot be negative.")
% {"name": p.name}
)
amounts.append(Decimal(val).quantize(unit, rounding=ROUND_HALF_UP))
total_entered = sum(amounts, Decimal("0"))
if total_entered != total:
raise ValidationError(
_(
"Exact amounts sum to %(entered)s, but the expense total is %(total)s."
)
% {"entered": number_format(total_entered), "total": number_format(total)}
)
return [
ComputedShare(participant=p, amount=amt)
for p, amt in zip(participant_list, amounts)
]
if split_type == SplitExpense.SplitType.PERCENTAGE:
percentages: list[Decimal] = []
for p in participant_list:
pct = values.get(p.id, Decimal("0"))
if pct < 0:
raise ValidationError(
_("Percentage for %(name)s cannot be negative.")
% {"name": p.name}
)
percentages.append(Decimal(pct))
pct_sum = sum(percentages, Decimal("0"))
if abs(pct_sum - Decimal("100")) > Decimal("0.01"):
raise ValidationError(
_("Percentages must sum to 100%% (currently %(sum)s%%).")
% {"sum": number_format(pct_sum)}
)
raw = [total * (pct / Decimal("100")) for pct in percentages]
amounts = _distribute_remainder(total, raw, unit)
return [
ComputedShare(
participant=p,
amount=amt,
percentage=pct.quantize(Decimal("0.0001"), rounding=ROUND_HALF_UP),
)
for p, amt, pct in zip(participant_list, amounts, percentages)
]
if split_type == SplitExpense.SplitType.SHARES:
share_weights: list[Decimal] = []
for p in participant_list:
w = values.get(p.id, Decimal("0"))
if w < 0:
raise ValidationError(
_("Shares for %(name)s cannot be negative.") % {"name": p.name}
)
share_weights.append(Decimal(w))
weight_sum = sum(share_weights, Decimal("0"))
if weight_sum <= 0:
raise ValidationError(_("Total shares must be greater than zero."))
raw = [total * (w / weight_sum) for w in share_weights]
amounts = _distribute_remainder(total, raw, unit)
return [
ComputedShare(
participant=p,
amount=amt,
shares=w.quantize(Decimal("0.0001"), rounding=ROUND_HALF_UP),
)
for p, amt, w in zip(participant_list, amounts, share_weights)
]
raise ValidationError(_("Unsupported split type: %(type)s") % {"type": split_type})
def replace_expense_shares(expense: SplitExpense, computed: list[ComputedShare]):
expense.shares.all().delete()
SplitExpenseShare.objects.bulk_create(
[
SplitExpenseShare(
expense=expense,
participant=cs.participant,
amount=cs.amount,
percentage=cs.percentage,
shares=cs.shares,
)
for cs in computed
]
)
+162
View File
@@ -0,0 +1,162 @@
from decimal import Decimal
from django.db import transaction as db_transaction
from django.utils import timezone
from apps.accounts.models import Account
from apps.splits.models import (
SplitEvent,
SplitExpense,
SplitParticipant,
SplitPayment,
SplitTransactionLink,
)
from apps.transactions.models import Transaction, TransactionCategory
def expected_transaction_type_for_kind(kind: str) -> str:
if kind in (
SplitTransactionLink.Kind.PAYMENT_IN,
SplitTransactionLink.Kind.SETTLEMENT_IN,
):
return Transaction.Type.INCOME
return Transaction.Type.EXPENSE
def build_default_sync_description(
*,
event: SplitEvent,
kind: str,
expense: SplitExpense | None = None,
payment: SplitPayment | None = None,
counterparty: SplitParticipant | None = None,
) -> str:
if expense is not None:
return f"[{event.name}] {expense.description}"
if payment is not None:
if kind == SplitTransactionLink.Kind.PAYMENT_IN:
return f"[{event.name}] Payment from {payment.from_participant.name}"
return f"[{event.name}] Payment to {payment.to_participant.name}"
if counterparty is not None:
if kind == SplitTransactionLink.Kind.SETTLEMENT_IN:
return f"[{event.name}] Receive from {counterparty.name}"
return f"[{event.name}] Pay {counterparty.name}"
return f"[{event.name}] Split transaction"
@db_transaction.atomic
def create_and_link_transaction(
*,
user,
event: SplitEvent,
kind: str,
account: Account,
amount: Decimal,
date,
description: str,
is_paid: bool = True,
category: TransactionCategory | None = None,
tags=(),
entities=(),
notes: str = "",
expense: SplitExpense | None = None,
payment: SplitPayment | None = None,
counterparty: SplitParticipant | None = None,
) -> SplitTransactionLink:
tx_type = expected_transaction_type_for_kind(kind)
tx = Transaction(
owner=user,
account=account,
type=tx_type,
is_paid=is_paid,
date=date or timezone.localdate(),
amount=amount,
description=description[:500],
notes=notes,
category=category,
)
tx.save()
tx.tags.set(tags)
tx.entities.set(entities)
return SplitTransactionLink.objects.create(
event=event,
user=user,
transaction=tx,
kind=kind,
expense=expense,
payment=payment,
counterparty=counterparty,
)
@db_transaction.atomic
def link_existing_transaction(
*,
user,
event: SplitEvent,
kind: str,
tx: Transaction,
expense: SplitExpense | None = None,
payment: SplitPayment | None = None,
counterparty: SplitParticipant | None = None,
) -> SplitTransactionLink:
return SplitTransactionLink.objects.create(
event=event,
user=user,
transaction=tx,
kind=kind,
expense=expense,
payment=payment,
counterparty=counterparty,
)
@db_transaction.atomic
def settle_pending_links_for_payment(payment: SplitPayment) -> int:
"""When a SplitPayment is recorded, find any unpaid SETTLEMENT_OUT/SETTLEMENT_IN
WYGIWYH transaction links for the sender or recipient matching this counterparty,
mark those WYGIWYH transactions as paid, and attach them to this payment.
"""
updated = 0
# Sender's planned outgoing settlement to recipient
if payment.from_participant.user_id:
out_links = SplitTransactionLink.objects.select_related("transaction").filter(
event=payment.event,
user_id=payment.from_participant.user_id,
kind=SplitTransactionLink.Kind.SETTLEMENT_OUT,
counterparty=payment.to_participant,
payment__isnull=True,
)
for link in out_links:
tx = link.transaction
if not tx.deleted and not tx.is_paid:
tx.is_paid = True
tx.date = payment.date
tx.save()
link.kind = SplitTransactionLink.Kind.PAYMENT_OUT
link.payment = payment
link.save(update_fields=["kind", "payment"])
updated += 1
# Recipient's planned incoming settlement from sender
if payment.to_participant.user_id:
in_links = SplitTransactionLink.objects.select_related("transaction").filter(
event=payment.event,
user_id=payment.to_participant.user_id,
kind=SplitTransactionLink.Kind.SETTLEMENT_IN,
counterparty=payment.from_participant,
payment__isnull=True,
)
for link in in_links:
tx = link.transaction
if not tx.deleted and not tx.is_paid:
tx.is_paid = True
tx.date = payment.date
tx.save()
link.kind = SplitTransactionLink.Kind.PAYMENT_IN
link.payment = payment
link.save(update_fields=["kind", "payment"])
updated += 1
return updated