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

View File
Whitespace-only changes.
+54
View File
@@ -0,0 +1,54 @@
from django.contrib import admin
from apps.splits.models import (
SplitAttachment,
SplitEvent,
SplitExpense,
SplitExpenseShare,
SplitParticipant,
SplitPayment,
SplitTransactionLink,
)
@admin.register(SplitEvent)
class SplitEventAdmin(admin.ModelAdmin):
list_display = ("name", "currency", "creator", "allow_external_access", "is_archived", "created_at")
list_filter = ("is_archived", "allow_external_access", "currency")
search_fields = ("name", "description")
@admin.register(SplitParticipant)
class SplitParticipantAdmin(admin.ModelAdmin):
list_display = ("name", "event", "is_external", "user", "is_active", "external_claimed_at")
list_filter = ("is_external", "is_active")
search_fields = ("name", "external_username", "event__name")
@admin.register(SplitExpense)
class SplitExpenseAdmin(admin.ModelAdmin):
list_display = ("description", "event", "paid_by", "amount", "split_type", "date")
list_filter = ("split_type", "date")
search_fields = ("description", "notes", "event__name")
@admin.register(SplitExpenseShare)
class SplitExpenseShareAdmin(admin.ModelAdmin):
list_display = ("expense", "participant", "amount", "percentage", "shares")
@admin.register(SplitPayment)
class SplitPaymentAdmin(admin.ModelAdmin):
list_display = ("event", "from_participant", "to_participant", "amount", "date")
list_filter = ("date",)
@admin.register(SplitAttachment)
class SplitAttachmentAdmin(admin.ModelAdmin):
list_display = ("original_name", "event", "expense", "payment", "size", "created_at")
@admin.register(SplitTransactionLink)
class SplitTransactionLinkAdmin(admin.ModelAdmin):
list_display = ("event", "user", "kind", "transaction", "created_at")
list_filter = ("kind",)
+8
View File
@@ -0,0 +1,8 @@
from django.apps import AppConfig
from django.utils.translation import gettext_lazy as _
class SplitsConfig(AppConfig):
default_auto_field = "django.db.models.BigAutoField"
name = "apps.splits"
verbose_name = _("Split Expenses")
+158
View File
@@ -0,0 +1,158 @@
from dataclasses import dataclass
from django.core.exceptions import PermissionDenied
from django.db.models import Q
from django.utils.crypto import constant_time_compare, salted_hmac
from django.http import Http404
from django.shortcuts import get_object_or_404
from apps.splits.models import SplitEvent, SplitParticipant
EXTERNAL_SESSION_KEY = "split_external_auth"
def _password_fingerprint(participant: SplitParticipant) -> str:
# Binds the session to the current password, so a reset signs out old sessions
return salted_hmac(
"splits.external_session", participant.external_password_hash
).hexdigest()
@dataclass(frozen=True)
class SplitActor:
event: SplitEvent
participant: SplitParticipant | None
user: object | None # Django User or None for external participants
is_external_portal: bool
@property
def is_creator(self) -> bool:
return bool(
not self.is_external_portal
and self.user is not None
and self.event.can_manage(self.user)
)
@property
def is_wygiwyh_user(self) -> bool:
return bool(not self.is_external_portal and self.user is not None)
def can_record_payment(self, from_id: int | None, to_id: int | None) -> bool:
# Only the two people involved (or the organizer) can say money changed hands
if self.is_creator:
return True
return bool(self.participant and self.participant.id in (from_id, to_id))
def can_edit_item(self, *, created_by_id: int | None, primary_participant_id: int | None) -> bool:
if self.is_creator:
return True
if not self.participant or not self.participant.is_active:
return False
return self.participant.id in {created_by_id, primary_participant_id}
def user_display_name(user) -> str:
full = f"{user.first_name} {user.last_name}".strip()
return full or user.email
def accessible_events(user):
"""Events a WYGIWYH user organizes or actively takes part in."""
return SplitEvent.objects.filter(
Q(creator=user) | Q(participants__user=user, participants__is_active=True)
).distinct()
def wygiwyh_actor_for(event: SplitEvent, user) -> SplitActor:
return SplitActor(
event=event,
participant=event.get_wygiwyh_participant(user),
user=user,
is_external_portal=False,
)
def set_external_session(request, event: SplitEvent, participant: SplitParticipant):
auth_map = dict(request.session.get(EXTERNAL_SESSION_KEY, {}))
auth_map[str(event.id)] = {
"participant_id": participant.id,
"share_token": str(event.share_token),
"password": _password_fingerprint(participant),
}
request.session[EXTERNAL_SESSION_KEY] = auth_map
request.session.modified = True
def clear_external_session(request, event: SplitEvent):
auth_map = dict(request.session.get(EXTERNAL_SESSION_KEY, {}))
if str(event.id) in auth_map:
del auth_map[str(event.id)]
request.session[EXTERNAL_SESSION_KEY] = auth_map
request.session.modified = True
def get_external_participant_from_session(
request, event: SplitEvent
) -> SplitParticipant | None:
if not event.allow_external_access:
return None
auth_map = request.session.get(EXTERNAL_SESSION_KEY, {})
entry = auth_map.get(str(event.id))
if not isinstance(entry, dict):
return None
if entry.get("share_token") != str(event.share_token):
return None
participant_id = entry.get("participant_id")
if not participant_id:
return None
participant = (
SplitParticipant.objects.filter(
id=participant_id,
event=event,
is_external=True,
is_active=True,
)
.exclude(external_password_hash="")
.first()
)
if participant and constant_time_compare(
entry.get("password", ""), _password_fingerprint(participant)
):
return participant
return None
def get_wygiwyh_actor(request, event_id: int) -> SplitActor:
if not request.user.is_authenticated:
raise PermissionDenied
event = get_object_or_404(
SplitEvent.objects.select_related("currency", "creator"),
id=event_id,
)
if not event.is_accessible_by_user(request.user):
raise Http404
participant = event.get_wygiwyh_participant(request.user)
return SplitActor(
event=event,
participant=participant,
user=request.user,
is_external_portal=False,
)
def get_external_actor(request, share_token) -> SplitActor | None:
event = get_object_or_404(
SplitEvent.objects.select_related("currency", "creator"),
share_token=share_token,
)
if not event.allow_external_access:
raise Http404
participant = get_external_participant_from_session(request, event)
if not participant:
return None
return SplitActor(
event=event,
participant=participant,
user=None,
is_external_portal=True,
)
+525
View File
@@ -0,0 +1,525 @@
from decimal import Decimal, InvalidOperation
from crispy_forms.bootstrap import FormActions
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Column, Layout, Row
from django import forms
from django.contrib.auth import get_user_model
from django.core.exceptions import ValidationError
from django.db import models
from django.utils import timezone
from django.utils.translation import gettext_lazy as _
from apps.accounts.models import Account
from apps.common.widgets.crispy.daisyui import Switch
from apps.common.widgets.crispy.submit import NoClassSubmit
from apps.common.widgets.datepicker import AirDatePickerInput
from apps.common.widgets.decimal import ArbitraryDecimalDisplayNumberInput
from apps.common.fields.forms.dynamic_select import (
DynamicModelChoiceField,
DynamicModelMultipleChoiceField,
)
from apps.common.widgets.tom_select import TomSelect, TransactionSelect
from apps.currencies.models import Currency
from apps.splits.models import (
SplitAttachment,
SplitEvent,
SplitExpense,
SplitParticipant,
SplitPayment,
SplitTransactionLink,
)
from apps.splits.services.splitting import compute_expense_shares
from apps.transactions.forms import MultipleFileField
from apps.transactions.models import (
Transaction,
TransactionCategory,
TransactionEntity,
TransactionTag,
)
User = get_user_model()
def _participant_label(p: SplitParticipant) -> str:
return p.name if p.is_active else _("%(name)s (inactive)") % {"name": p.name}
class SplitEventForm(forms.ModelForm):
class Meta:
model = SplitEvent
fields = [
"name",
"currency",
"description",
"allow_external_access",
"is_archived",
]
widgets = {
"currency": TomSelect(clear_button=False),
"description": forms.Textarea(attrs={"rows": 3}),
}
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields["currency"].queryset = Currency.objects.filter(
is_archived=False
).order_by("name")
if self.instance and self.instance.pk:
# Allow keeping current currency even if archived
self.fields["currency"].queryset = Currency.objects.filter(
is_archived=False
) | Currency.objects.filter(pk=self.instance.currency_id)
# Stored amounts are not converted, so changing currency would corrupt them
if self.instance.expenses.exists() or self.instance.payments.exists():
self.fields["currency"].disabled = True
self.fields["currency"].help_text = _(
"The currency can't be changed after expenses or payments are added."
)
self.helper = FormHelper()
self.helper.form_tag = False
fields_layout = [
"name",
"currency",
"description",
Switch("allow_external_access"),
]
if self.instance and self.instance.pk:
fields_layout.append(Switch("is_archived"))
fields_layout.append(
FormActions(
NoClassSubmit("submit", _("Update"), css_class="btn btn-primary")
)
)
else:
self.fields.pop("is_archived", None)
fields_layout.append(
FormActions(
NoClassSubmit("submit", _("Add"), css_class="btn btn-primary")
)
)
self.helper.layout = Layout(*fields_layout)
class AddWygiwyhParticipantForm(forms.Form):
user = forms.ModelChoiceField(
queryset=User.objects.none(),
label=_("WYGIWYH User"),
widget=TomSelect(clear_button=False),
)
def __init__(self, *args, event: SplitEvent, **kwargs):
super().__init__(*args, **kwargs)
existing_user_ids = event.participants.filter(
user__isnull=False
).values_list("user_id", flat=True)
self.fields["user"].queryset = (
User.objects.filter(is_active=True)
.exclude(id__in=existing_user_ids)
.order_by("first_name", "last_name", "email")
)
self.fields["user"].label_from_instance = self._user_label
@staticmethod
def _user_label(u):
full = f"{u.first_name} {u.last_name}".strip()
return f"{full} ({u.email})" if full else u.email
class AddExternalParticipantForm(forms.Form):
name = forms.CharField(
max_length=150,
label=_("Name"),
widget=forms.TextInput(attrs={"placeholder": _("e.g. Alex")}),
)
def __init__(self, *args, event: SplitEvent, **kwargs):
super().__init__(*args, **kwargs)
self.event = event
def clean_name(self):
name = self.cleaned_data["name"].strip()
if not name:
raise ValidationError(_("Name cannot be empty."))
if self.event.participants.filter(name__iexact=name).exists():
raise ValidationError(
_("A participant named '%(name)s' already exists in this event.")
% {"name": name}
)
return name
class SplitExpenseForm(forms.ModelForm):
attachments = MultipleFileField(
required=False,
label=_("Attachments"),
help_text=_("Optional receipts or files."),
)
class Meta:
model = SplitExpense
fields = ["description", "amount", "date", "paid_by", "split_type", "notes"]
widgets = {
"date": AirDatePickerInput(),
"notes": forms.Textarea(attrs={"rows": 2}),
}
def __init__(self, *args, event: SplitEvent, default_payer: SplitParticipant | None = None, **kwargs):
super().__init__(*args, **kwargs)
self.event = event
# Include active participants, plus any inactive participant already referenced on this expense
active_qs = event.participants.filter(is_active=True)
if self.instance and self.instance.pk:
referenced_ids = list(
self.instance.shares.values_list("participant_id", flat=True)
) + [self.instance.paid_by_id]
self.available_participants = list(
event.participants.filter(
id__in=referenced_ids
).union(active_qs).order_by("-is_active", "name", "id")
)
payer_qs = event.participants.filter(
id__in=[p.id for p in self.available_participants]
).order_by("-is_active", "name", "id")
else:
self.available_participants = list(active_qs.order_by("name", "id"))
payer_qs = active_qs.order_by("name", "id")
self.fields["paid_by"].queryset = payer_qs
self.fields["paid_by"].label_from_instance = _participant_label
self.fields["paid_by"].empty_label = None
self.fields["amount"].widget = ArbitraryDecimalDisplayNumberInput(
decimal_places=event.currency.decimal_places,
attrs={"inputmode": "decimal"},
)
self.fields["amount"].label = _("Amount (%(code)s)") % {"code": event.currency.code}
if not self.instance.pk:
self.fields["date"].initial = timezone.localdate()
if default_payer and payer_qs.filter(pk=default_payer.pk).exists():
self.fields["paid_by"].initial = default_payer
self.computed_shares = []
def clean(self):
cleaned = super().clean()
amount = cleaned.get("amount")
split_type = cleaned.get("split_type")
if amount is None or not split_type:
return cleaned
# Parse selected participants and per-participant split values from POST data
selected_ids = self.data.getlist("share_participants")
selected_id_set = set()
for raw_id in selected_ids:
try:
selected_id_set.add(int(raw_id))
except (TypeError, ValueError):
pass
participants_by_id = {p.id: p for p in self.available_participants}
selected_participants = [
participants_by_id[pid]
for pid in participants_by_id
if pid in selected_id_set
]
values_by_id: dict[int, Decimal] = {}
if split_type != SplitExpense.SplitType.EQUAL:
for p in selected_participants:
raw_val = (self.data.get(f"share_value_{p.id}") or "").strip()
if raw_val == "":
values_by_id[p.id] = Decimal("0")
else:
try:
# <input type=number> always posts "12.5", never the locale format
values_by_id[p.id] = Decimal(raw_val)
except InvalidOperation:
raise ValidationError(
_("Invalid split value for %(name)s.") % {"name": p.name}
)
self.computed_shares = compute_expense_shares(
total_amount=amount,
split_type=split_type,
participants=selected_participants,
decimal_places=self.event.currency.decimal_places,
values_by_participant_id=values_by_id,
)
return cleaned
class SplitPaymentForm(forms.ModelForm):
attachments = MultipleFileField(
required=False,
label=_("Attachments"),
help_text=_("Optional proof of payment."),
)
class Meta:
model = SplitPayment
fields = ["from_participant", "to_participant", "amount", "date", "notes"]
widgets = {
"date": AirDatePickerInput(),
"notes": forms.Textarea(attrs={"rows": 2}),
}
def __init__(self, *args, event: SplitEvent, actor=None, **kwargs):
super().__init__(*args, **kwargs)
self.event = event
self.actor = actor
qs = event.participants.filter(is_active=True).order_by("name", "id")
if self.instance and self.instance.pk:
qs = event.participants.filter(
id__in=list(qs.values_list("id", flat=True))
+ [self.instance.from_participant_id, self.instance.to_participant_id]
).order_by("-is_active", "name", "id")
for name in ("from_participant", "to_participant"):
self.fields[name].queryset = qs
self.fields[name].label_from_instance = _participant_label
self.fields["amount"].widget = ArbitraryDecimalDisplayNumberInput(
decimal_places=event.currency.decimal_places,
attrs={"inputmode": "decimal"},
)
self.fields["amount"].label = _("Amount (%(code)s)") % {"code": event.currency.code}
if not self.instance.pk:
self.fields["date"].initial = timezone.localdate()
def clean(self):
cleaned = super().clean()
from_p = cleaned.get("from_participant")
to_p = cleaned.get("to_participant")
if from_p and to_p and from_p == to_p:
self.add_error(
"to_participant",
_("Sender and recipient must be different participants."),
)
if (
self.actor
and from_p
and to_p
and not self.actor.can_record_payment(from_p.id, to_p.id)
):
raise ValidationError(
_("You can only record payments you sent or received.")
)
return cleaned
class SplitAttachmentUploadForm(forms.Form):
attachments = MultipleFileField(
required=True,
label=_("Attachments"),
)
def save(self, *, event: SplitEvent, uploaded_by: SplitParticipant | None, expense=None, payment=None):
created = []
for f in self.cleaned_data.get("attachments") or []:
created.append(
SplitAttachment.objects.create(
event=event,
expense=expense,
payment=payment,
file=f,
original_name=f.name,
content_type=getattr(f, "content_type", ""),
size=f.size,
uploaded_by=uploaded_by,
)
)
return created
class SplitTransactionSyncForm(forms.Form):
class Mode(models.TextChoices):
CREATE = "create", _("Create new WYGIWYH transaction")
LINK = "link", _("Link existing WYGIWYH transaction")
mode = forms.ChoiceField(
choices=Mode.choices,
initial=Mode.CREATE,
widget=forms.RadioSelect,
label=_("Action"),
)
# Create mode fields
account = forms.ModelChoiceField(
queryset=Account.objects.none(),
required=False,
label=_("Account"),
widget=TomSelect(clear_button=False, group_by="group"),
)
category = DynamicModelChoiceField(
create_field="name",
model=TransactionCategory,
required=False,
label=_("Category"),
queryset=TransactionCategory.objects.none(),
)
tags = DynamicModelMultipleChoiceField(
model=TransactionTag,
to_field_name="name",
create_field="name",
required=False,
label=_("Tags"),
queryset=TransactionTag.objects.none(),
)
entities = DynamicModelMultipleChoiceField(
model=TransactionEntity,
to_field_name="name",
create_field="name",
required=False,
label=_("Entities"),
queryset=TransactionEntity.objects.none(),
)
amount = forms.DecimalField(
max_digits=20,
decimal_places=6,
required=False,
label=_("Amount"),
)
date = forms.DateField(
required=False,
label=_("Date"),
widget=AirDatePickerInput(),
)
description = forms.CharField(
max_length=500,
required=False,
label=_("Description"),
)
is_paid = forms.BooleanField(
required=False,
initial=True,
label=_("Mark as paid"),
)
notes = forms.CharField(
required=False,
label=_("Notes"),
widget=forms.Textarea(attrs={"rows": 2}),
)
# Link mode field
existing_transaction = DynamicModelChoiceField(
model=Transaction,
to_field_name="id",
required=False,
label=_("Transaction"),
queryset=Transaction.objects.none(),
widget=TransactionSelect(clear_button=True),
help_text=_("Type to search for a transaction to link"),
)
def __init__(self, *args, user, event: SplitEvent, tx_type: str, **kwargs):
super().__init__(*args, **kwargs)
self.user = user
self.event = event
self.tx_type = tx_type
accounts = Account.objects.filter(is_archived=False).order_by("name")
self.fields["account"].queryset = accounts
# Amounts are in the event currency, so only preselect a same-currency account
same_currency = accounts.filter(currency=event.currency)
default_acc = getattr(getattr(user, "settings", None), "default_account", None)
if default_acc and same_currency.filter(pk=default_acc.pk).exists():
self.fields["account"].initial = default_acc
else:
self.fields["account"].initial = same_currency.first()
self.fields["category"].queryset = TransactionCategory.objects.filter(active=True)
self.fields["tags"].queryset = TransactionTag.objects.filter(active=True)
self.fields["entities"].queryset = TransactionEntity.objects.filter(active=True)
self.fields["amount"].widget = ArbitraryDecimalDisplayNumberInput(
decimal_places=event.currency.decimal_places,
attrs={"inputmode": "decimal"},
)
# Search only transactions of the matching type in the event currency
picker = self.fields["existing_transaction"]
picker.widget.load_income = tx_type == Transaction.Type.INCOME
picker.widget.load_expense = tx_type == Transaction.Type.EXPENSE
picker.widget.filters = {"currency": event.currency_id}
selected = self.data.get("existing_transaction") if self.is_bound else None
# Only the selected one: the picker loads the rest by search
picker.queryset = Transaction.objects.filter(
id=selected if str(selected or "").isdigit() else None
)
def clean(self):
cleaned = super().clean()
mode = cleaned.get("mode")
if mode == self.Mode.CREATE:
if not cleaned.get("account"):
self.add_error("account", _("Please select an account."))
if not cleaned.get("amount") or cleaned["amount"] <= 0:
self.add_error("amount", _("Amount must be greater than zero."))
if not cleaned.get("date"):
cleaned["date"] = timezone.localdate()
elif mode == self.Mode.LINK:
tx = cleaned.get("existing_transaction")
if not tx:
self.add_error(
"existing_transaction",
_("Please select a transaction to link."),
)
elif tx.type != self.tx_type or tx.account.currency_id != self.event.currency_id:
self.add_error(
"existing_transaction",
_("Pick a %(type)s in %(currency)s.")
% {
"type": Transaction.Type(self.tx_type).label.lower(),
"currency": self.event.currency.name,
},
)
return cleaned
class ExternalAuthForm(forms.Form):
participant = forms.ModelChoiceField(
queryset=SplitParticipant.objects.none(),
label=_("Who are you?"),
)
username = forms.CharField(
max_length=150,
required=False,
label=_("Username / nickname (optional)"),
)
password = forms.CharField(
widget=forms.PasswordInput(attrs={"autocomplete": "current-password"}),
min_length=4,
label=_("Password"),
)
password_confirm = forms.CharField(
widget=forms.PasswordInput(attrs={"autocomplete": "new-password"}),
required=False,
label=_("Confirm password"),
)
def __init__(self, *args, event: SplitEvent, **kwargs):
super().__init__(*args, **kwargs)
self.event = event
self.fields["participant"].queryset = event.participants.filter(
is_external=True,
is_active=True,
).order_by("name", "id")
def clean(self):
cleaned = super().clean()
participant: SplitParticipant | None = cleaned.get("participant")
password = cleaned.get("password") or ""
password_confirm = cleaned.get("password_confirm") or ""
if not participant:
return cleaned
if participant.is_claimed:
if not participant.check_external_password(password):
self.add_error("password", _("Incorrect password."))
else:
if len(password) < 4:
self.add_error(
"password", _("Password must be at least 4 characters long.")
)
elif password != password_confirm:
self.add_error("password_confirm", _("Passwords do not match."))
return cleaned
+188
View File
@@ -0,0 +1,188 @@
# Generated by Django 5.2.17 on 2026-11-20 20:26
import apps.splits.models
import apps.transactions.storage
import django.core.validators
import django.db.models.deletion
import django.utils.timezone
import uuid
from decimal import Decimal
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
('currencies', '0028_currency_show_exchanged_amounts'),
('transactions', '0056_filterpreset_is_default'),
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='SplitEvent',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=255, verbose_name='Name')),
('description', models.TextField(blank=True, verbose_name='Description')),
('share_token', models.UUIDField(db_index=True, default=uuid.uuid4, unique=True, verbose_name='Share token')),
('allow_external_access', models.BooleanField(default=True, help_text='Allow external participants to access this event via the shared link.', verbose_name='Allow external access')),
('is_archived', models.BooleanField(default=False, verbose_name='Archived')),
('created_at', models.DateTimeField(auto_now_add=True)),
('updated_at', models.DateTimeField(auto_now=True)),
('creator', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='created_split_events', to=settings.AUTH_USER_MODEL, verbose_name='Creator')),
('currency', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='split_events', to='currencies.currency', verbose_name='Currency')),
],
options={
'verbose_name': 'Split Event',
'verbose_name_plural': 'Split Events',
'db_table': 'split_events',
'ordering': ['-created_at', 'name'],
},
),
migrations.CreateModel(
name='SplitExpense',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('description', models.CharField(max_length=255, verbose_name='Description')),
('amount', models.DecimalField(decimal_places=6, max_digits=20, validators=[django.core.validators.MinValueValidator(Decimal('0.000001'))], verbose_name='Amount')),
('date', models.DateField(default=django.utils.timezone.localdate, verbose_name='Date')),
('split_type', models.CharField(choices=[('EQUAL', 'Equal'), ('EXACT', 'Exact amounts'), ('PERCENTAGE', 'Percentages'), ('SHARES', 'Shares')], default='EQUAL', max_length=16, verbose_name='Split type')),
('notes', models.TextField(blank=True, verbose_name='Notes')),
('created_at', models.DateTimeField(auto_now_add=True)),
('updated_at', models.DateTimeField(auto_now=True)),
('event', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='expenses', to='splits.splitevent', verbose_name='Event')),
],
options={
'verbose_name': 'Split Expense',
'verbose_name_plural': 'Split Expenses',
'db_table': 'split_expenses',
'ordering': ['-date', '-created_at', '-id'],
},
),
migrations.CreateModel(
name='SplitParticipant',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=150, verbose_name='Name')),
('is_external', models.BooleanField(default=False, verbose_name='External')),
('is_active', models.BooleanField(default=True, verbose_name='Active')),
('external_username', models.CharField(blank=True, max_length=150, verbose_name='External username')),
('external_password_hash', models.CharField(blank=True, max_length=255, verbose_name='External password hash')),
('external_claimed_at', models.DateTimeField(blank=True, null=True, verbose_name='Claimed at')),
('created_at', models.DateTimeField(auto_now_add=True)),
('event', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='participants', to='splits.splitevent', verbose_name='Event')),
('user', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='split_participations', to=settings.AUTH_USER_MODEL, verbose_name='WYGIWYH User')),
],
options={
'verbose_name': 'Split Participant',
'verbose_name_plural': 'Split Participants',
'db_table': 'split_participants',
'ordering': ['-is_active', 'name', 'id'],
},
),
migrations.CreateModel(
name='SplitExpenseShare',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('amount', models.DecimalField(decimal_places=6, max_digits=20, validators=[django.core.validators.MinValueValidator(Decimal('0'))], verbose_name='Amount')),
('percentage', models.DecimalField(blank=True, decimal_places=4, max_digits=7, null=True, verbose_name='Percentage')),
('shares', models.DecimalField(blank=True, decimal_places=4, max_digits=12, null=True, verbose_name='Shares')),
('expense', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='shares', to='splits.splitexpense', verbose_name='Expense')),
('participant', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='expense_shares', to='splits.splitparticipant', verbose_name='Participant')),
],
options={
'verbose_name': 'Split Expense Share',
'verbose_name_plural': 'Split Expense Shares',
'db_table': 'split_expense_shares',
'ordering': ['participant__name', 'id'],
},
),
migrations.AddField(
model_name='splitexpense',
name='created_by_participant',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='expenses_created', to='splits.splitparticipant', verbose_name='Created by'),
),
migrations.AddField(
model_name='splitexpense',
name='paid_by',
field=models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='expenses_paid', to='splits.splitparticipant', verbose_name='Paid by'),
),
migrations.CreateModel(
name='SplitPayment',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('amount', models.DecimalField(decimal_places=6, max_digits=20, validators=[django.core.validators.MinValueValidator(Decimal('0.000001'))], verbose_name='Amount')),
('date', models.DateField(default=django.utils.timezone.localdate, verbose_name='Date')),
('notes', models.TextField(blank=True, verbose_name='Notes')),
('created_at', models.DateTimeField(auto_now_add=True)),
('updated_at', models.DateTimeField(auto_now=True)),
('created_by_participant', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='payments_created', to='splits.splitparticipant', verbose_name='Created by')),
('event', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='payments', to='splits.splitevent', verbose_name='Event')),
('from_participant', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='payments_sent', to='splits.splitparticipant', verbose_name='From')),
('to_participant', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='payments_received', to='splits.splitparticipant', verbose_name='To')),
],
options={
'verbose_name': 'Split Payment',
'verbose_name_plural': 'Split Payments',
'db_table': 'split_payments',
'ordering': ['-date', '-created_at', '-id'],
},
),
migrations.CreateModel(
name='SplitAttachment',
fields=[
('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)),
('file', models.FileField(storage=apps.transactions.storage.PrivateMediaStorage(), upload_to=apps.splits.models.split_attachment_path, verbose_name='File')),
('original_name', models.CharField(max_length=255, verbose_name='Original Name')),
('content_type', models.CharField(blank=True, max_length=255, verbose_name='Content Type')),
('size', models.PositiveBigIntegerField(default=0, verbose_name='Size')),
('created_at', models.DateTimeField(auto_now_add=True)),
('event', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='attachments', to='splits.splitevent', verbose_name='Event')),
('expense', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='attachments', to='splits.splitexpense', verbose_name='Expense')),
('uploaded_by', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='uploaded_attachments', to='splits.splitparticipant', verbose_name='Uploaded By')),
('payment', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='attachments', to='splits.splitpayment', verbose_name='Payment')),
],
options={
'verbose_name': 'Split Attachment',
'verbose_name_plural': 'Split Attachments',
'db_table': 'split_attachments',
'ordering': ['-created_at', 'original_name'],
},
),
migrations.CreateModel(
name='SplitTransactionLink',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('kind', models.CharField(choices=[('EXPENSE', 'Expense paid'), ('PAYMENT_OUT', 'Payment sent'), ('PAYMENT_IN', 'Payment received'), ('SETTLEMENT_OUT', 'Planned payment to send'), ('SETTLEMENT_IN', 'Planned payment to receive')], max_length=24, verbose_name='Kind')),
('created_at', models.DateTimeField(auto_now_add=True)),
('counterparty', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='counterparty_transaction_links', to='splits.splitparticipant', verbose_name='Counterparty')),
('event', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='transaction_links', to='splits.splitevent', verbose_name='Event')),
('expense', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='transaction_links', to='splits.splitexpense', verbose_name='Expense')),
('payment', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='transaction_links', to='splits.splitpayment', verbose_name='Payment')),
('transaction', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='split_links', to='transactions.transaction', verbose_name='Transaction')),
('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='split_transaction_links', to=settings.AUTH_USER_MODEL, verbose_name='User')),
],
options={
'verbose_name': 'Split Transaction Link',
'verbose_name_plural': 'Split Transaction Links',
'db_table': 'split_transaction_links',
'ordering': ['-created_at'],
},
),
migrations.AddConstraint(
model_name='splitparticipant',
constraint=models.UniqueConstraint(condition=models.Q(('user__isnull', False)), fields=('event', 'user'), name='unique_split_participant_user_per_event'),
),
migrations.AddConstraint(
model_name='splitparticipant',
constraint=models.UniqueConstraint(fields=('event', 'name'), name='unique_split_participant_name_per_event'),
),
migrations.AddConstraint(
model_name='splitexpenseshare',
constraint=models.UniqueConstraint(fields=('expense', 'participant'), name='unique_share_per_expense_participant'),
),
]
Whitespace-only changes.
+513
View File
@@ -0,0 +1,513 @@
import uuid
from decimal import Decimal
from pathlib import Path
from apps.transactions.storage import PrivateMediaStorage
from django.conf import settings
from django.contrib.auth.hashers import check_password, make_password
from django.core.exceptions import ValidationError
from django.core.validators import MinValueValidator
from django.db import models
from django.db.models import Q
from django.utils import timezone
from django.utils.translation import gettext_lazy as _
def split_attachment_path(instance, filename):
extension = Path(filename).suffix
return f"split_attachments/{instance.event_id}/{instance.id}{extension}"
class SplitEvent(models.Model):
name = models.CharField(max_length=255, verbose_name=_("Name"))
description = models.TextField(blank=True, verbose_name=_("Description"))
currency = models.ForeignKey(
"currencies.Currency",
on_delete=models.PROTECT,
related_name="split_events",
verbose_name=_("Currency"),
)
creator = models.ForeignKey(
settings.AUTH_USER_MODEL,
on_delete=models.CASCADE,
related_name="created_split_events",
verbose_name=_("Creator"),
)
share_token = models.UUIDField(
default=uuid.uuid4,
unique=True,
db_index=True,
verbose_name=_("Share token"),
)
allow_external_access = models.BooleanField(
default=True,
verbose_name=_("Allow external access"),
help_text=_(
"Allow external participants to access this event via the shared link."
),
)
is_archived = models.BooleanField(default=False, verbose_name=_("Archived"))
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
class Meta:
verbose_name = _("Split Event")
verbose_name_plural = _("Split Events")
db_table = "split_events"
ordering = ["-created_at", "name"]
def __str__(self):
return self.name
def can_manage(self, user) -> bool:
return bool(user and user.is_authenticated and self.creator_id == user.id)
def get_wygiwyh_participant(self, user):
if not user or not user.is_authenticated:
return None
return self.participants.filter(user=user).first()
def is_accessible_by_user(self, user) -> bool:
if not user or not user.is_authenticated:
return False
if self.creator_id == user.id:
return True
return self.participants.filter(user=user, is_active=True).exists()
def regenerate_share_token(self):
self.share_token = uuid.uuid4()
self.save(update_fields=["share_token", "updated_at"])
return self.share_token
class SplitParticipant(models.Model):
event = models.ForeignKey(
SplitEvent,
on_delete=models.CASCADE,
related_name="participants",
verbose_name=_("Event"),
)
user = models.ForeignKey(
settings.AUTH_USER_MODEL,
on_delete=models.SET_NULL,
null=True,
blank=True,
related_name="split_participations",
verbose_name=_("WYGIWYH User"),
)
name = models.CharField(max_length=150, verbose_name=_("Name"))
is_external = models.BooleanField(default=False, verbose_name=_("External"))
is_active = models.BooleanField(default=True, verbose_name=_("Active"))
external_username = models.CharField(
max_length=150,
blank=True,
verbose_name=_("External username"),
)
external_password_hash = models.CharField(
max_length=255,
blank=True,
verbose_name=_("External password hash"),
)
external_claimed_at = models.DateTimeField(
null=True,
blank=True,
verbose_name=_("Claimed at"),
)
created_at = models.DateTimeField(auto_now_add=True)
class Meta:
verbose_name = _("Split Participant")
verbose_name_plural = _("Split Participants")
db_table = "split_participants"
ordering = ["-is_active", "name", "id"]
constraints = [
models.UniqueConstraint(
fields=["event", "user"],
condition=Q(user__isnull=False),
name="unique_split_participant_user_per_event",
),
models.UniqueConstraint(
fields=["event", "name"],
name="unique_split_participant_name_per_event",
),
]
def __str__(self):
return self.display_name
@property
def display_name(self) -> str:
if self.external_username:
return f"{self.name} (@{self.external_username})"
return self.name
@property
def is_claimed(self) -> bool:
return bool(self.is_external and self.external_password_hash)
@property
def is_creator(self) -> bool:
return bool(self.user_id and self.user_id == self.event.creator_id)
def set_external_password(self, raw_password: str, username: str = ""):
self.external_password_hash = make_password(raw_password)
if username:
self.external_username = username.strip()
if not self.external_claimed_at:
self.external_claimed_at = timezone.now()
self.save(
update_fields=[
"external_password_hash",
"external_username",
"external_claimed_at",
]
)
def check_external_password(self, raw_password: str) -> bool:
if not self.external_password_hash:
return False
return check_password(raw_password, self.external_password_hash)
def reset_external_password(self):
self.external_password_hash = ""
self.external_claimed_at = None
self.save(update_fields=["external_password_hash", "external_claimed_at"])
def has_contributions(self) -> bool:
return (
self.expenses_paid.exists()
or self.expense_shares.exists()
or self.payments_sent.exists()
or self.payments_received.exists()
)
def can_be_deleted(self) -> bool:
return not self.is_creator and not self.has_contributions()
def clean(self):
super().clean()
if self.is_external and self.user_id is not None:
raise ValidationError(
_("An external participant cannot be linked to a WYGIWYH user.")
)
if not self.is_external and self.user_id is None:
raise ValidationError(
_("A non-external participant must be linked to a WYGIWYH user.")
)
class SplitExpense(models.Model):
class SplitType(models.TextChoices):
EQUAL = "EQUAL", _("Equal")
EXACT = "EXACT", _("Exact amounts")
PERCENTAGE = "PERCENTAGE", _("Percentages")
SHARES = "SHARES", _("Shares")
event = models.ForeignKey(
SplitEvent,
on_delete=models.CASCADE,
related_name="expenses",
verbose_name=_("Event"),
)
paid_by = models.ForeignKey(
SplitParticipant,
on_delete=models.PROTECT,
related_name="expenses_paid",
verbose_name=_("Paid by"),
)
created_by_participant = models.ForeignKey(
SplitParticipant,
on_delete=models.SET_NULL,
null=True,
blank=True,
related_name="expenses_created",
verbose_name=_("Created by"),
)
description = models.CharField(max_length=255, verbose_name=_("Description"))
amount = models.DecimalField(
max_digits=20,
decimal_places=6,
validators=[MinValueValidator(Decimal("0.000001"))],
verbose_name=_("Amount"),
)
date = models.DateField(default=timezone.localdate, verbose_name=_("Date"))
split_type = models.CharField(
max_length=16,
choices=SplitType.choices,
default=SplitType.EQUAL,
verbose_name=_("Split type"),
)
notes = models.TextField(blank=True, verbose_name=_("Notes"))
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
class Meta:
verbose_name = _("Split Expense")
verbose_name_plural = _("Split Expenses")
db_table = "split_expenses"
ordering = ["-date", "-created_at", "-id"]
def __str__(self):
return f"{self.description} ({self.amount})"
def clean(self):
super().clean()
if self.paid_by_id and self.event_id and self.paid_by.event_id != self.event_id:
raise ValidationError(
{"paid_by": _("Payer must be a participant of this event.")}
)
class SplitExpenseShare(models.Model):
expense = models.ForeignKey(
SplitExpense,
on_delete=models.CASCADE,
related_name="shares",
verbose_name=_("Expense"),
)
participant = models.ForeignKey(
SplitParticipant,
on_delete=models.PROTECT,
related_name="expense_shares",
verbose_name=_("Participant"),
)
amount = models.DecimalField(
max_digits=20,
decimal_places=6,
validators=[MinValueValidator(Decimal("0"))],
verbose_name=_("Amount"),
)
percentage = models.DecimalField(
max_digits=7,
decimal_places=4,
null=True,
blank=True,
verbose_name=_("Percentage"),
)
shares = models.DecimalField(
max_digits=12,
decimal_places=4,
null=True,
blank=True,
verbose_name=_("Shares"),
)
class Meta:
verbose_name = _("Split Expense Share")
verbose_name_plural = _("Split Expense Shares")
db_table = "split_expense_shares"
ordering = ["participant__name", "id"]
constraints = [
models.UniqueConstraint(
fields=["expense", "participant"],
name="unique_share_per_expense_participant",
),
]
def __str__(self):
return f"{self.participant.name}: {self.amount}"
class SplitPayment(models.Model):
event = models.ForeignKey(
SplitEvent,
on_delete=models.CASCADE,
related_name="payments",
verbose_name=_("Event"),
)
from_participant = models.ForeignKey(
SplitParticipant,
on_delete=models.PROTECT,
related_name="payments_sent",
verbose_name=_("From"),
)
to_participant = models.ForeignKey(
SplitParticipant,
on_delete=models.PROTECT,
related_name="payments_received",
verbose_name=_("To"),
)
created_by_participant = models.ForeignKey(
SplitParticipant,
on_delete=models.SET_NULL,
null=True,
blank=True,
related_name="payments_created",
verbose_name=_("Created by"),
)
amount = models.DecimalField(
max_digits=20,
decimal_places=6,
validators=[MinValueValidator(Decimal("0.000001"))],
verbose_name=_("Amount"),
)
date = models.DateField(default=timezone.localdate, verbose_name=_("Date"))
notes = models.TextField(blank=True, verbose_name=_("Notes"))
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
class Meta:
verbose_name = _("Split Payment")
verbose_name_plural = _("Split Payments")
db_table = "split_payments"
ordering = ["-date", "-created_at", "-id"]
def __str__(self):
return f"{self.from_participant.name} -> {self.to_participant.name}: {self.amount}"
def clean(self):
super().clean()
errors = {}
if (
self.from_participant_id
and self.to_participant_id
and self.from_participant_id == self.to_participant_id
):
errors["to_participant"] = _(
"Sender and recipient must be different participants."
)
if self.event_id:
if (
self.from_participant_id
and self.from_participant.event_id != self.event_id
):
errors["from_participant"] = _(
"Sender must be a participant of this event."
)
if (
self.to_participant_id
and self.to_participant.event_id != self.event_id
):
errors["to_participant"] = _(
"Recipient must be a participant of this event."
)
if errors:
raise ValidationError(errors)
class SplitAttachment(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
event = models.ForeignKey(
SplitEvent,
on_delete=models.CASCADE,
related_name="attachments",
verbose_name=_("Event"),
)
expense = models.ForeignKey(
SplitExpense,
on_delete=models.CASCADE,
null=True,
blank=True,
related_name="attachments",
verbose_name=_("Expense"),
)
payment = models.ForeignKey(
SplitPayment,
on_delete=models.CASCADE,
null=True,
blank=True,
related_name="attachments",
verbose_name=_("Payment"),
)
file = models.FileField(
upload_to=split_attachment_path,
storage=PrivateMediaStorage(),
verbose_name=_("File"),
)
original_name = models.CharField(max_length=255, verbose_name=_("Original Name"))
content_type = models.CharField(
max_length=255, blank=True, verbose_name=_("Content Type")
)
size = models.PositiveBigIntegerField(default=0, verbose_name=_("Size"))
uploaded_by = models.ForeignKey(
SplitParticipant,
on_delete=models.SET_NULL,
null=True,
blank=True,
related_name="uploaded_attachments",
verbose_name=_("Uploaded By"),
)
created_at = models.DateTimeField(auto_now_add=True)
class Meta:
verbose_name = _("Split Attachment")
verbose_name_plural = _("Split Attachments")
db_table = "split_attachments"
ordering = ["-created_at", "original_name"]
def __str__(self):
return self.original_name
def clean(self):
super().clean()
if bool(self.expense_id) == bool(self.payment_id):
raise ValidationError(
_("An attachment must belong to either an expense or a payment.")
)
class SplitTransactionLink(models.Model):
class Kind(models.TextChoices):
EXPENSE = "EXPENSE", _("Expense paid")
PAYMENT_OUT = "PAYMENT_OUT", _("Payment sent")
PAYMENT_IN = "PAYMENT_IN", _("Payment received")
SETTLEMENT_OUT = "SETTLEMENT_OUT", _("Planned payment to send")
SETTLEMENT_IN = "SETTLEMENT_IN", _("Planned payment to receive")
event = models.ForeignKey(
SplitEvent,
on_delete=models.CASCADE,
related_name="transaction_links",
verbose_name=_("Event"),
)
user = models.ForeignKey(
settings.AUTH_USER_MODEL,
on_delete=models.CASCADE,
related_name="split_transaction_links",
verbose_name=_("User"),
)
transaction = models.ForeignKey(
"transactions.Transaction",
on_delete=models.CASCADE,
related_name="split_links",
verbose_name=_("Transaction"),
)
kind = models.CharField(
max_length=24,
choices=Kind.choices,
verbose_name=_("Kind"),
)
expense = models.ForeignKey(
SplitExpense,
on_delete=models.SET_NULL,
null=True,
blank=True,
related_name="transaction_links",
verbose_name=_("Expense"),
)
payment = models.ForeignKey(
SplitPayment,
on_delete=models.SET_NULL,
null=True,
blank=True,
related_name="transaction_links",
verbose_name=_("Payment"),
)
counterparty = models.ForeignKey(
SplitParticipant,
on_delete=models.SET_NULL,
null=True,
blank=True,
related_name="counterparty_transaction_links",
verbose_name=_("Counterparty"),
)
created_at = models.DateTimeField(auto_now_add=True)
class Meta:
verbose_name = _("Split Transaction Link")
verbose_name_plural = _("Split Transaction Links")
db_table = "split_transaction_links"
ordering = ["-created_at"]
def __str__(self):
return f"{self.get_kind_display()} -> Tx #{self.transaction_id}"
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
Whitespace-only changes.
@@ -0,0 +1,12 @@
from django import template
from django.urls import reverse
register = template.Library()
@register.simple_tag
def split_portal_url(urls_dict, name_key, **extra_kwargs):
url_name = urls_dict[name_key]
kwargs = {urls_dict["url_kwarg_key"]: urls_dict["url_kwarg_val"]}
kwargs.update(extra_kwargs)
return reverse(url_name, kwargs=kwargs)
View File
Whitespace-only changes.
+679
View File
@@ -0,0 +1,679 @@
from decimal import Decimal
import tempfile
from unittest.mock import patch
from django.contrib.auth import get_user_model
from django.core.exceptions import ValidationError
from django.core.files.uploadedfile import SimpleUploadedFile
from django.test import TestCase, override_settings
from django.urls import reverse
from django.utils import timezone
from apps.accounts.models import Account
from apps.currencies.models import Currency
from apps.splits.models import (
SplitAttachment,
SplitEvent,
SplitExpense,
SplitExpenseShare,
SplitParticipant,
SplitPayment,
SplitTransactionLink,
)
from apps.splits.services.settlement import (
ParticipantBalance,
calculate_event_balances,
get_event_settlement_summary,
simplify_debts,
)
from apps.splits.services.splitting import compute_expense_shares
from apps.transactions.models import Transaction
User = get_user_model()
@override_settings(
STORAGES={
"default": {"BACKEND": "django.core.files.storage.FileSystemStorage"},
"staticfiles": {
"BACKEND": "django.contrib.staticfiles.storage.StaticFilesStorage"
},
}
)
class SplitTestBase(TestCase):
def setUp(self):
self.currency = Currency.objects.create(
code="USD", name="US Dollar", decimal_places=2, prefix="$"
)
self.creator = User.objects.create_user(
email="creator@example.com",
password="password123",
first_name="Alice",
last_name="Creator",
)
self.other_user = User.objects.create_user(
email="bob@example.com",
password="password123",
first_name="Bob",
last_name="Member",
)
self.account = Account.objects.create(
owner=self.creator,
name="Checking",
currency=self.currency,
)
self.event = SplitEvent.objects.create(
name="Beach Trip",
currency=self.currency,
creator=self.creator,
)
self.p_alice = SplitParticipant.objects.create(
event=self.event,
user=self.creator,
name="Alice Creator",
is_external=False,
)
self.p_bob = SplitParticipant.objects.create(
event=self.event,
user=self.other_user,
name="Bob Member",
is_external=False,
)
self.p_charlie = SplitParticipant.objects.create(
event=self.event,
user=None,
name="Charlie",
is_external=True,
)
class SplittingAlgorithmTests(SplitTestBase):
def test_equal_split_distributes_remainder_pennies(self):
shares = compute_expense_shares(
total_amount=Decimal("10.00"),
split_type=SplitExpense.SplitType.EQUAL,
participants=[self.p_alice, self.p_bob, self.p_charlie],
decimal_places=2,
)
amounts = [s.amount for s in shares]
self.assertEqual(sum(amounts), Decimal("10.00"))
self.assertEqual(sorted(amounts), [Decimal("3.33"), Decimal("3.33"), Decimal("3.34")])
def test_exact_split_valid_and_invalid(self):
shares = compute_expense_shares(
total_amount=Decimal("100.00"),
split_type=SplitExpense.SplitType.EXACT,
participants=[self.p_alice, self.p_bob],
decimal_places=2,
values_by_participant_id={
self.p_alice.id: Decimal("30.00"),
self.p_bob.id: Decimal("70.00"),
},
)
self.assertEqual([s.amount for s in shares], [Decimal("30.00"), Decimal("70.00")])
with self.assertRaises(ValidationError):
compute_expense_shares(
total_amount=Decimal("100.00"),
split_type=SplitExpense.SplitType.EXACT,
participants=[self.p_alice, self.p_bob],
decimal_places=2,
values_by_participant_id={
self.p_alice.id: Decimal("30.00"),
self.p_bob.id: Decimal("60.00"),
},
)
def test_percentage_split_valid_and_invalid(self):
shares = compute_expense_shares(
total_amount=Decimal("200.00"),
split_type=SplitExpense.SplitType.PERCENTAGE,
participants=[self.p_alice, self.p_bob],
decimal_places=2,
values_by_participant_id={
self.p_alice.id: Decimal("25"),
self.p_bob.id: Decimal("75"),
},
)
self.assertEqual([s.amount for s in shares], [Decimal("50.00"), Decimal("150.00")])
with self.assertRaises(ValidationError):
compute_expense_shares(
total_amount=Decimal("200.00"),
split_type=SplitExpense.SplitType.PERCENTAGE,
participants=[self.p_alice, self.p_bob],
decimal_places=2,
values_by_participant_id={
self.p_alice.id: Decimal("25"),
self.p_bob.id: Decimal("50"),
},
)
def test_shares_split(self):
shares = compute_expense_shares(
total_amount=Decimal("100.00"),
split_type=SplitExpense.SplitType.SHARES,
participants=[self.p_alice, self.p_bob, self.p_charlie],
decimal_places=2,
values_by_participant_id={
self.p_alice.id: Decimal("2"),
self.p_bob.id: Decimal("1"),
self.p_charlie.id: Decimal("1"),
},
)
self.assertEqual(
[s.amount for s in shares],
[Decimal("50.00"), Decimal("25.00"), Decimal("25.00")],
)
class DebtSimplificationTests(SplitTestBase):
def test_chain_collapses_roundtrip(self):
"""X pays Y's share, Y pays Z's share -> Z pays X directly (1 transfer, no roundtrip)."""
# Alice pays $30 for Bob only -> Bob owes Alice $30
e1 = SplitExpense.objects.create(
event=self.event, paid_by=self.p_alice, description="Dinner", amount=Decimal("30.00")
)
SplitExpenseShare.objects.create(expense=e1, participant=self.p_bob, amount=Decimal("30.00"))
# Bob pays $30 for Charlie only -> Charlie owes Bob $30
e2 = SplitExpense.objects.create(
event=self.event, paid_by=self.p_bob, description="Drinks", amount=Decimal("30.00")
)
SplitExpenseShare.objects.create(expense=e2, participant=self.p_charlie, amount=Decimal("30.00"))
summary = get_event_settlement_summary(self.event)
transfers = summary["transfers"]
self.assertEqual(len(transfers), 1)
self.assertEqual(transfers[0].from_participant, self.p_charlie)
self.assertEqual(transfers[0].to_participant, self.p_alice)
self.assertEqual(transfers[0].amount, Decimal("30.00"))
def test_disjoint_zero_sum_subsets_minimizes_transfers(self):
p_dave = SplitParticipant.objects.create(
event=self.event, name="Dave", is_external=True
)
p_eve = SplitParticipant.objects.create(
event=self.event, name="Eve", is_external=True
)
# Subset 1: Alice +30, Bob -10, Charlie -20 (2 transfers)
# Subset 2: Dave +15, Eve -15 (1 transfer)
# Optimal total: 3 transfers (not 4!)
zero = Decimal("0.00")
balances = [
ParticipantBalance(self.p_alice, zero, zero, zero, zero, Decimal("30.00")),
ParticipantBalance(self.p_bob, zero, zero, zero, zero, Decimal("-10.00")),
ParticipantBalance(self.p_charlie, zero, zero, zero, zero, Decimal("-20.00")),
ParticipantBalance(p_dave, zero, zero, zero, zero, Decimal("15.00")),
ParticipantBalance(p_eve, zero, zero, zero, zero, Decimal("-15.00")),
]
transfers = simplify_debts(balances, decimal_places=2)
self.assertEqual(len(transfers), 3)
# Verify applying transfers settles everyone to exactly 0
net = {b.participant.id: b.net_balance for b in balances}
for t in transfers:
net[t.from_participant.id] += t.amount
net[t.to_participant.id] -= t.amount
for bal in net.values():
self.assertEqual(bal, Decimal("0.00"))
class ExternalParticipantAndPortalTests(SplitTestBase):
def test_external_claim_login_and_isolation(self):
auth_url = reverse("split_external_auth", kwargs={"share_token": self.event.share_token})
detail_url = reverse("split_external_event_detail", kwargs={"share_token": self.event.share_token})
# Unauthenticated external user redirected to auth
resp = self.client.get(detail_url)
self.assertRedirects(resp, auth_url)
# Auth page loads cleanly without firing login-protected /toasts/ HTMX request
auth_page = self.client.get(auth_url)
self.assertEqual(auth_page.status_code, 200)
self.assertNotContains(auth_page, reverse("toasts"))
# First-time claim: mismatching password rejected
resp = self.client.post(
auth_url,
{
"participant": self.p_charlie.id,
"username": "chaz",
"password": "secret123",
"password_confirm": "wrong",
},
)
self.assertEqual(resp.status_code, 200)
self.p_charlie.refresh_from_db()
self.assertFalse(self.p_charlie.is_claimed)
# First-time claim: matching password succeeds
resp = self.client.post(
auth_url,
{
"participant": self.p_charlie.id,
"username": "chaz",
"password": "secret123",
"password_confirm": "secret123",
},
)
self.assertRedirects(resp, detail_url)
self.p_charlie.refresh_from_db()
self.assertTrue(self.p_charlie.is_claimed)
self.assertEqual(self.p_charlie.external_username, "chaz")
# External user is NOT a WYGIWYH user and cannot access WYGIWYH routes
wygiwyh_resp = self.client.get(reverse("split_event_index"))
self.assertEqual(wygiwyh_resp.status_code, 302)
self.assertIn("/login/", wygiwyh_resp["Location"])
# External user can render the event content fragment
ext_content_resp = self.client.get(
reverse(
"split_external_event_content",
kwargs={"share_token": self.event.share_token},
),
HTTP_HX_REQUEST="true",
)
self.assertEqual(ext_content_resp.status_code, 200)
self.assertContains(ext_content_resp, "Beach Trip")
# External user can add an expense with notes & attachment
tmp_dir = tempfile.mkdtemp()
storage = SplitAttachment._meta.get_field("file").storage
orig_location = storage._location
storage._location = tmp_dir
storage.__dict__.pop("location", None)
try:
add_url = reverse(
"split_external_expense_add",
kwargs={"share_token": self.event.share_token},
)
receipt = SimpleUploadedFile("receipt.txt", b"grocery receipt", content_type="text/plain")
resp = self.client.post(
add_url,
{
"description": "Groceries",
"amount": "90.00",
"date": str(timezone.localdate()),
"paid_by": self.p_charlie.id,
"split_type": SplitExpense.SplitType.EQUAL,
"share_participants": [self.p_alice.id, self.p_bob.id, self.p_charlie.id],
"notes": "Bought snacks and drinks",
"attachments": receipt,
},
HTTP_HX_REQUEST="true",
)
self.assertEqual(resp.status_code, 204)
expense = SplitExpense.objects.get(event=self.event, description="Groceries")
self.assertEqual(expense.notes, "Bought snacks and drinks")
self.assertEqual(expense.shares.count(), 3)
self.assertEqual(expense.attachments.count(), 1)
# External user can download the attachment
att = expense.attachments.first()
dl_url = reverse(
"split_external_attachment_download",
kwargs={"share_token": self.event.share_token, "attachment_id": att.id},
)
dl_resp = self.client.get(dl_url)
self.assertEqual(dl_resp.status_code, 200)
self.assertEqual(b"".join(dl_resp.streaming_content), b"grocery receipt")
finally:
storage._location = orig_location
storage.__dict__.pop("location", None)
# Deactivating Charlie preserves contributions but immediately revokes portal access
self.p_charlie.is_active = False
self.p_charlie.save()
self.assertFalse(self.p_charlie.can_be_deleted())
resp = self.client.get(detail_url)
self.assertRedirects(resp, auth_url)
# Balances still include Charlie's $90 contribution
balances = {b.participant.id: b for b in calculate_event_balances(self.event)}
self.assertEqual(balances[self.p_charlie.id].net_balance, Decimal("60.00"))
class WygiwyhSyncTests(SplitTestBase):
def test_settlement_sync_and_auto_paid_on_payment(self):
self.client.force_login(self.creator)
# Bob pays $100 split equally between Alice and Bob -> Alice owes Bob $50
exp = SplitExpense.objects.create(
event=self.event,
paid_by=self.p_bob,
description="Hotel",
amount=Decimal("100.00"),
)
SplitExpenseShare.objects.create(expense=exp, participant=self.p_alice, amount=Decimal("50.00"))
SplitExpenseShare.objects.create(expense=exp, participant=self.p_bob, amount=Decimal("50.00"))
# Alice creates a planned unpaid WYGIWYH transaction to pay Bob $50
sync_url = (
reverse("split_sync_settlement", kwargs={"event_id": self.event.id})
+ f"?direction=out&counterparty={self.p_bob.id}&amount=50.00"
)
resp = self.client.post(
sync_url,
{
"mode": "create",
"account": self.account.id,
"amount": "50.00",
"date": str(timezone.localdate()),
"description": "Pay Bob for Beach Trip",
# is_paid omitted -> False (unpaid)
},
HTTP_HX_REQUEST="true",
)
self.assertEqual(resp.status_code, 204)
link = SplitTransactionLink.objects.get(event=self.event, user=self.creator)
self.assertEqual(link.kind, SplitTransactionLink.Kind.SETTLEMENT_OUT)
self.assertFalse(link.transaction.is_paid)
self.assertEqual(link.transaction.type, Transaction.Type.EXPENSE)
self.assertEqual(link.transaction.amount, Decimal("50.00"))
# Now Alice records the payment to Bob -> linked WYGIWYH transaction auto-marks as paid!
pay_url = reverse("split_payment_add", kwargs={"event_id": self.event.id})
resp = self.client.post(
pay_url,
{
"from_participant": self.p_alice.id,
"to_participant": self.p_bob.id,
"amount": "50.00",
"date": str(timezone.localdate()),
"notes": "Settled!",
},
HTTP_HX_REQUEST="true",
)
self.assertEqual(resp.status_code, 204)
link.refresh_from_db()
link.transaction.refresh_from_db()
self.assertTrue(link.transaction.is_paid)
self.assertEqual(link.kind, SplitTransactionLink.Kind.PAYMENT_OUT)
self.assertIsNotNone(link.payment_id)
# Event is now completely settled
summary = get_event_settlement_summary(self.event)
self.assertEqual(summary["transfers"], [])
def test_link_existing_transaction_and_unlink(self):
self.client.force_login(self.creator)
exp = SplitExpense.objects.create(
event=self.event,
paid_by=self.p_alice,
description="Fuel",
amount=Decimal("40.00"),
)
SplitExpenseShare.objects.create(expense=exp, participant=self.p_alice, amount=Decimal("20.00"))
SplitExpenseShare.objects.create(expense=exp, participant=self.p_bob, amount=Decimal("20.00"))
existing_tx = Transaction.objects.create(
owner=self.creator,
account=self.account,
type=Transaction.Type.EXPENSE,
amount=Decimal("40.00"),
date=timezone.localdate(),
description="Gas station",
)
sync_url = reverse(
"split_sync_expense",
kwargs={"event_id": self.event.id, "expense_id": exp.id},
)
resp = self.client.post(
sync_url,
{
"mode": "link",
"existing_transaction": existing_tx.id,
},
HTTP_HX_REQUEST="true",
)
self.assertEqual(resp.status_code, 204)
link = SplitTransactionLink.objects.get(event=self.event, expense=exp)
self.assertEqual(link.transaction_id, existing_tx.id)
# Unlinking removes the link but keeps the WYGIWYH transaction intact
unlink_url = reverse(
"split_sync_unlink",
kwargs={"event_id": self.event.id, "link_id": link.id},
)
resp = self.client.delete(unlink_url, HTTP_HX_REQUEST="true")
self.assertEqual(resp.status_code, 204)
self.assertFalse(SplitTransactionLink.objects.filter(id=link.id).exists())
self.assertTrue(Transaction.objects.filter(id=existing_tx.id).exists())
def test_creator_can_remove_unused_or_deactivate_used_participant(self):
self.client.force_login(self.creator)
unused = SplitParticipant.objects.create(
event=self.event, name="Unused Guest", is_external=True
)
del_url = reverse(
"split_participant_delete",
kwargs={"event_id": self.event.id, "participant_id": unused.id},
)
resp = self.client.delete(del_url, HTTP_HX_REQUEST="true")
self.assertEqual(resp.status_code, 200)
self.assertFalse(SplitParticipant.objects.filter(id=unused.id).exists())
# Regenerating share link updates UUID
old_token = self.event.share_token
regen_url = reverse("split_event_regenerate_link", kwargs={"event_id": self.event.id})
resp = self.client.post(regen_url, HTTP_HX_REQUEST="true")
self.assertEqual(resp.status_code, 200)
self.event.refresh_from_db()
self.assertNotEqual(self.event.share_token, old_token)
# WYGIWYH user can render event list and event content fragments
list_resp = self.client.get(reverse("split_event_list"), HTTP_HX_REQUEST="true")
self.assertEqual(list_resp.status_code, 200)
self.assertContains(list_resp, "Beach Trip")
content_resp = self.client.get(
reverse("split_event_content", kwargs={"event_id": self.event.id}),
HTTP_HX_REQUEST="true",
)
self.assertEqual(content_resp.status_code, 200)
self.assertContains(content_resp, "Beach Trip")
self.assertNotContains(content_resp, 'data-original-amount="ERR"')
# Expense form uses Alpine x-mask on amount input
exp_form_resp = self.client.get(
reverse("split_expense_add", kwargs={"event_id": self.event.id}),
HTTP_HX_REQUEST="true",
)
self.assertEqual(exp_form_resp.status_code, 200)
self.assertContains(exp_form_resp, "x-mask:dynamic")
class RegressionTests(SplitTestBase):
def test_password_reset_signs_out_existing_external_sessions(self):
token = self.event.share_token
self.p_charlie.set_external_password("secret123")
self.client.post(
reverse("split_external_auth", kwargs={"share_token": token}),
{"participant": self.p_charlie.id, "password": "secret123"},
)
detail_url = reverse("split_external_event_detail", kwargs={"share_token": token})
self.assertEqual(self.client.get(detail_url).status_code, 200)
# Organizer resets, the real Charlie claims again: the old session must stay dead
self.p_charlie.reset_external_password()
self.p_charlie.set_external_password("newpass99")
self.assertEqual(self.client.get(detail_url).status_code, 302)
def test_untrusted_attachment_types_are_downloaded_not_rendered(self):
self.client.force_login(self.creator)
expense = SplitExpense.objects.create(
event=self.event, paid_by=self.p_charlie, description="x", amount=Decimal("1")
)
storage = SplitAttachment._meta.get_field("file").storage
orig_location = storage._location
storage._location = tempfile.mkdtemp()
storage.__dict__.pop("location", None)
try:
for content_type, inline in (
("text/html", False),
("image/svg+xml", False),
("image/png", True),
):
att = SplitAttachment.objects.create(
event=self.event,
expense=expense,
file=SimpleUploadedFile("f", b"x", content_type=content_type),
original_name="f",
content_type=content_type,
)
resp = self.client.get(
reverse(
"split_attachment_download",
kwargs={"event_id": self.event.id, "attachment_id": att.id},
)
)
self.assertEqual(
resp["Content-Disposition"].startswith("inline"), inline, content_type
)
finally:
storage._location = orig_location
storage.__dict__.pop("location", None)
def test_split_values_ignore_locale_thousand_separator(self):
self.client.force_login(self.creator)
pt_br = {"THOUSAND_SEPARATOR": ".", "DECIMAL_SEPARATOR": ","}
with patch("apps.common.widgets.decimal.get_format", side_effect=pt_br.get):
resp = self.client.post(
reverse("split_expense_add", kwargs={"event_id": self.event.id}),
{
"description": "Dinner",
"amount": "20",
"date": str(timezone.localdate()),
"paid_by": self.p_alice.id,
"split_type": SplitExpense.SplitType.EXACT,
"share_participants": [self.p_alice.id, self.p_bob.id],
f"share_value_{self.p_alice.id}": "12.5",
f"share_value_{self.p_bob.id}": "7.5",
},
HTTP_HX_REQUEST="true",
)
self.assertEqual(resp.status_code, 204)
shares = SplitExpenseShare.objects.filter(expense__description="Dinner")
self.assertEqual(
{s.participant_id: s.amount for s in shares},
{self.p_alice.id: Decimal("12.5"), self.p_bob.id: Decimal("7.5")},
)
def test_cannot_sync_money_that_did_not_move_through_your_accounts(self):
self.client.force_login(self.creator)
payment = SplitPayment.objects.create(
event=self.event,
from_participant=self.p_bob,
to_participant=self.p_charlie,
amount=Decimal("5"),
)
expense = SplitExpense.objects.create(
event=self.event, paid_by=self.p_bob, description="x", amount=Decimal("5")
)
for url in (
reverse("split_sync_payment", kwargs={"event_id": self.event.id, "payment_id": payment.id}),
reverse("split_sync_expense", kwargs={"event_id": self.event.id, "expense_id": expense.id}),
):
self.assertEqual(self.client.get(url, HTTP_HX_REQUEST="true").status_code, 404)
def test_currency_locked_once_event_has_expenses(self):
from apps.splits.forms import SplitEventForm
self.assertFalse(SplitEventForm(instance=self.event).fields["currency"].disabled)
SplitExpense.objects.create(
event=self.event, paid_by=self.p_alice, description="x", amount=Decimal("5")
)
self.assertTrue(SplitEventForm(instance=self.event).fields["currency"].disabled)
class LeaveEventTests(SplitTestBase):
def _leave(self, user):
self.client.force_login(user)
return self.client.post(
reverse("split_event_leave", kwargs={"event_id": self.event.id}),
HTTP_HX_REQUEST="true",
)
def test_member_without_contributions_is_removed(self):
resp = self._leave(self.other_user)
self.assertEqual(resp.status_code, 204)
self.assertFalse(SplitParticipant.objects.filter(id=self.p_bob.id).exists())
self.assertFalse(self.event.is_accessible_by_user(self.other_user))
def test_member_with_contributions_is_deactivated_and_balances_kept(self):
exp = SplitExpense.objects.create(
event=self.event, paid_by=self.p_bob, description="x", amount=Decimal("10")
)
SplitExpenseShare.objects.create(expense=exp, participant=self.p_alice, amount=Decimal("10"))
self._leave(self.other_user)
self.p_bob.refresh_from_db()
self.assertFalse(self.p_bob.is_active)
self.assertFalse(self.event.is_accessible_by_user(self.other_user))
balances = {b.participant.id: b for b in calculate_event_balances(self.event)}
self.assertEqual(balances[self.p_bob.id].net_balance, Decimal("10.00"))
def test_organizer_cannot_leave(self):
self.assertEqual(self._leave(self.creator).status_code, 403)
class SyncLinkPickerTests(SplitTestBase):
def test_link_rejects_wrong_type_or_currency(self):
self.client.force_login(self.creator)
exp = SplitExpense.objects.create(
event=self.event, paid_by=self.p_alice, description="x", amount=Decimal("5")
)
income = Transaction.objects.create(
owner=self.creator, account=self.account, type=Transaction.Type.INCOME,
amount=Decimal("5"), date=timezone.localdate(),
)
resp = self.client.post(
reverse("split_sync_expense", kwargs={"event_id": self.event.id, "expense_id": exp.id}),
{"mode": "link", "existing_transaction": income.id},
HTTP_HX_REQUEST="true",
)
self.assertEqual(resp.status_code, 200)
self.assertFalse(SplitTransactionLink.objects.exists())
class PaymentPermissionAndReportTests(SplitTestBase):
def _record(self, user, from_p, to_p):
self.client.force_login(user)
return self.client.post(
reverse("split_payment_add", kwargs={"event_id": self.event.id}),
{
"from_participant": from_p.id,
"to_participant": to_p.id,
"amount": "5",
"date": str(timezone.localdate()),
},
HTTP_HX_REQUEST="true",
)
def test_only_involved_people_or_organizer_can_record_payment(self):
# Bob is neither sender nor recipient, nor the organizer
self.assertEqual(self._record(self.other_user, self.p_charlie, self.p_alice).status_code, 200)
self.assertFalse(SplitPayment.objects.exists())
# Bob paying someone is fine
self.assertEqual(self._record(self.other_user, self.p_bob, self.p_charlie).status_code, 204)
# The organizer can record a payment between two others
self.assertEqual(self._record(self.creator, self.p_charlie, self.p_bob).status_code, 204)
def test_report_renders_for_members_and_external_participants(self):
self.client.force_login(self.creator)
resp = self.client.get(reverse("split_event_report", kwargs={"event_id": self.event.id}))
self.assertContains(resp, "Beach Trip")
self.client.logout()
token = self.event.share_token
self.p_charlie.set_external_password("secret123")
self.client.post(
reverse("split_external_auth", kwargs={"share_token": token}),
{"participant": self.p_charlie.id, "password": "secret123"},
)
resp = self.client.get(reverse("split_external_event_report", kwargs={"share_token": token}))
self.assertContains(resp, "Beach Trip")
+201
View File
@@ -0,0 +1,201 @@
from django.urls import path
from apps.splits import views
urlpatterns = [
# WYGIWYH User Routes
path("splits/", views.event_index, name="split_event_index"),
path("splits/list/", views.event_list, name="split_event_list"),
path("splits/add/", views.event_add, name="split_event_add"),
path("splits/<int:event_id>/", views.event_detail, name="split_event_detail"),
path(
"splits/<int:event_id>/content/",
views.event_content,
name="split_event_content",
),
path(
"splits/<int:event_id>/report/",
views.event_report,
name="split_event_report",
),
path("splits/<int:event_id>/edit/", views.event_edit, name="split_event_edit"),
path(
"splits/<int:event_id>/delete/",
views.event_delete,
name="split_event_delete",
),
path(
"splits/<int:event_id>/leave/",
views.event_leave,
name="split_event_leave",
),
# Participant & Share Link Management
path(
"splits/<int:event_id>/participants/",
views.participants_manage,
name="split_participants_manage",
),
path(
"splits/<int:event_id>/participants/add-user/",
views.participant_add_wygiwyh,
name="split_participant_add_wygiwyh",
),
path(
"splits/<int:event_id>/participants/add-external/",
views.participant_add_external,
name="split_participant_add_external",
),
path(
"splits/<int:event_id>/participants/<int:participant_id>/toggle-active/",
views.participant_toggle_active,
name="split_participant_toggle_active",
),
path(
"splits/<int:event_id>/participants/<int:participant_id>/delete/",
views.participant_delete,
name="split_participant_delete",
),
path(
"splits/<int:event_id>/participants/<int:participant_id>/reset-password/",
views.participant_reset_password,
name="split_participant_reset_password",
),
path(
"splits/<int:event_id>/regenerate-link/",
views.event_regenerate_link,
name="split_event_regenerate_link",
),
# Expenses, Payments, Attachments (WYGIWYH)
path(
"splits/<int:event_id>/expenses/add/",
views.expense_add,
name="split_expense_add",
),
path(
"splits/<int:event_id>/expenses/<int:expense_id>/edit/",
views.expense_edit,
name="split_expense_edit",
),
path(
"splits/<int:event_id>/expenses/<int:expense_id>/delete/",
views.expense_delete,
name="split_expense_delete",
),
path(
"splits/<int:event_id>/payments/add/",
views.payment_add,
name="split_payment_add",
),
path(
"splits/<int:event_id>/payments/<int:payment_id>/edit/",
views.payment_edit,
name="split_payment_edit",
),
path(
"splits/<int:event_id>/payments/<int:payment_id>/delete/",
views.payment_delete,
name="split_payment_delete",
),
path(
"splits/<int:event_id>/attachments/<uuid:attachment_id>/download/",
views.attachment_download,
name="split_attachment_download",
),
path(
"splits/<int:event_id>/attachments/<uuid:attachment_id>/delete/",
views.attachment_delete,
name="split_attachment_delete",
),
# WYGIWYH Transaction Sync
path(
"splits/<int:event_id>/sync/expense/<int:expense_id>/",
views.sync_expense,
name="split_sync_expense",
),
path(
"splits/<int:event_id>/sync/payment/<int:payment_id>/",
views.sync_payment,
name="split_sync_payment",
),
path(
"splits/<int:event_id>/sync/settlement/",
views.sync_settlement,
name="split_sync_settlement",
),
path(
"splits/<int:event_id>/sync/unlink/<int:link_id>/",
views.sync_unlink,
name="split_sync_unlink",
),
# External Participant Portal (Shared UUID Link)
path(
"splits/share/<uuid:share_token>/",
views.external_auth,
name="split_external_auth",
),
path(
"splits/share/<uuid:share_token>/logout/",
views.external_logout,
name="split_external_logout",
),
path(
"splits/share/<uuid:share_token>/event/",
views.external_event_detail,
name="split_external_event_detail",
),
path(
"splits/share/<uuid:share_token>/event/content/",
views.external_event_content,
name="split_external_event_content",
),
path(
"splits/share/<uuid:share_token>/event/report/",
views.external_event_report,
name="split_external_event_report",
),
path(
"splits/share/<uuid:share_token>/toasts/",
views.external_toasts,
name="split_external_toasts",
),
path(
"splits/share/<uuid:share_token>/expenses/add/",
views.external_expense_add,
name="split_external_expense_add",
),
path(
"splits/share/<uuid:share_token>/expenses/<int:expense_id>/edit/",
views.external_expense_edit,
name="split_external_expense_edit",
),
path(
"splits/share/<uuid:share_token>/expenses/<int:expense_id>/delete/",
views.external_expense_delete,
name="split_external_expense_delete",
),
path(
"splits/share/<uuid:share_token>/payments/add/",
views.external_payment_add,
name="split_external_payment_add",
),
path(
"splits/share/<uuid:share_token>/payments/<int:payment_id>/edit/",
views.external_payment_edit,
name="split_external_payment_edit",
),
path(
"splits/share/<uuid:share_token>/payments/<int:payment_id>/delete/",
views.external_payment_delete,
name="split_external_payment_delete",
),
path(
"splits/share/<uuid:share_token>/attachments/<uuid:attachment_id>/download/",
views.external_attachment_download,
name="split_external_attachment_download",
),
path(
"splits/share/<uuid:share_token>/attachments/<uuid:attachment_id>/delete/",
views.external_attachment_delete,
name="split_external_attachment_delete",
),
]
File diff suppressed because it is too large. Load diff