From 77bf2d7bdbbb4cd8a45a5d325e368b8963eb5a71 Mon Sep 17 00:00:00 2001 From: Herculino Trotta Date: Fri, 20 Nov 2026 19:43:23 -0300 Subject: [PATCH 1/2] 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 --- app/WYGIWYH/settings.py | 1 + app/WYGIWYH/urls.py | 1 + app/apps/splits/__init__.py | 0 app/apps/splits/admin.py | 54 + app/apps/splits/apps.py | 8 + app/apps/splits/auth.py | 158 ++ app/apps/splits/forms.py | 525 ++++++ app/apps/splits/migrations/0001_initial.py | 188 +++ app/apps/splits/migrations/__init__.py | 0 app/apps/splits/models.py | 513 ++++++ app/apps/splits/services/__init__.py | 0 app/apps/splits/services/membership.py | 18 + app/apps/splits/services/settlement.py | 258 +++ app/apps/splits/services/splitting.py | 183 +++ app/apps/splits/services/wygiwyh_sync.py | 162 ++ app/apps/splits/templatetags/__init__.py | 0 app/apps/splits/templatetags/split_urls.py | 12 + app/apps/splits/tests/__init__.py | 0 app/apps/splits/tests/test_splits.py | 679 ++++++++ app/apps/splits/urls.py | 201 +++ app/apps/splits/views.py | 1441 +++++++++++++++++ app/templates/includes/sidebar.html | 6 + .../fragments/attachments_existing.html | 27 + .../fragments/event/activity_flags.html | 1 + .../splits/fragments/event/activity_item.html | 114 ++ app/templates/splits/fragments/event/add.html | 11 + .../splits/fragments/event/content.html | 188 +++ .../splits/fragments/event/edit.html | 23 + .../splits/fragments/event/export_script.html | 58 + .../splits/fragments/event/list.html | 71 + .../splits/fragments/event/share_menu.html | 34 + .../splits/fragments/expense/form.html | 87 + .../splits/fragments/participants/manage.html | 141 ++ .../splits/fragments/payment/form.html | 32 + app/templates/splits/fragments/sync/form.html | 66 + app/templates/splits/fragments/tx_links.html | 16 + app/templates/splits/pages/event_detail.html | 9 + app/templates/splits/pages/event_index.html | 8 + app/templates/splits/pages/event_report.html | 149 ++ app/templates/splits/pages/external_auth.html | 66 + app/templates/splits/pages/external_base.html | 64 + .../splits/pages/external_disabled.html | 17 + .../splits/pages/external_event_detail.html | 9 + frontend/package-lock.json | 7 + frontend/package.json | 1 + frontend/src/js/screenshot.js | 4 + frontend/src/main.js | 1 + 47 files changed, 5612 insertions(+) create mode 100644 app/apps/splits/__init__.py create mode 100644 app/apps/splits/admin.py create mode 100644 app/apps/splits/apps.py create mode 100644 app/apps/splits/auth.py create mode 100644 app/apps/splits/forms.py create mode 100644 app/apps/splits/migrations/0001_initial.py create mode 100644 app/apps/splits/migrations/__init__.py create mode 100644 app/apps/splits/models.py create mode 100644 app/apps/splits/services/__init__.py create mode 100644 app/apps/splits/services/membership.py create mode 100644 app/apps/splits/services/settlement.py create mode 100644 app/apps/splits/services/splitting.py create mode 100644 app/apps/splits/services/wygiwyh_sync.py create mode 100644 app/apps/splits/templatetags/__init__.py create mode 100644 app/apps/splits/templatetags/split_urls.py create mode 100644 app/apps/splits/tests/__init__.py create mode 100644 app/apps/splits/tests/test_splits.py create mode 100644 app/apps/splits/urls.py create mode 100644 app/apps/splits/views.py create mode 100644 app/templates/splits/fragments/attachments_existing.html create mode 100644 app/templates/splits/fragments/event/activity_flags.html create mode 100644 app/templates/splits/fragments/event/activity_item.html create mode 100644 app/templates/splits/fragments/event/add.html create mode 100644 app/templates/splits/fragments/event/content.html create mode 100644 app/templates/splits/fragments/event/edit.html create mode 100644 app/templates/splits/fragments/event/export_script.html create mode 100644 app/templates/splits/fragments/event/list.html create mode 100644 app/templates/splits/fragments/event/share_menu.html create mode 100644 app/templates/splits/fragments/expense/form.html create mode 100644 app/templates/splits/fragments/participants/manage.html create mode 100644 app/templates/splits/fragments/payment/form.html create mode 100644 app/templates/splits/fragments/sync/form.html create mode 100644 app/templates/splits/fragments/tx_links.html create mode 100644 app/templates/splits/pages/event_detail.html create mode 100644 app/templates/splits/pages/event_index.html create mode 100644 app/templates/splits/pages/event_report.html create mode 100644 app/templates/splits/pages/external_auth.html create mode 100644 app/templates/splits/pages/external_base.html create mode 100644 app/templates/splits/pages/external_disabled.html create mode 100644 app/templates/splits/pages/external_event_detail.html create mode 100644 frontend/src/js/screenshot.js diff --git a/app/WYGIWYH/settings.py b/app/WYGIWYH/settings.py index 2f85a68d..a46268c6 100644 --- a/app/WYGIWYH/settings.py +++ b/app/WYGIWYH/settings.py @@ -79,6 +79,7 @@ INSTALLED_APPS = [ "apps.calendar_view.apps.CalendarViewConfig", "apps.dca.apps.DcaConfig", "apps.investments.apps.InvestmentsConfig", + "apps.splits.apps.SplitsConfig", "pwa", "allauth", "allauth.account", diff --git a/app/WYGIWYH/urls.py b/app/WYGIWYH/urls.py index 49213cb2..f2bb3bdc 100644 --- a/app/WYGIWYH/urls.py +++ b/app/WYGIWYH/urls.py @@ -104,6 +104,7 @@ urlpatterns = [ path("", include("apps.calendar_view.urls")), path("", include("apps.dca.urls")), path("", include("apps.investments.urls")), + path("", include("apps.splits.urls")), path("", include("apps.mini_tools.urls")), path("", include("apps.import_app.urls")), path("", include("apps.export_app.urls")), diff --git a/app/apps/splits/__init__.py b/app/apps/splits/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/app/apps/splits/admin.py b/app/apps/splits/admin.py new file mode 100644 index 00000000..0eb100e4 --- /dev/null +++ b/app/apps/splits/admin.py @@ -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",) diff --git a/app/apps/splits/apps.py b/app/apps/splits/apps.py new file mode 100644 index 00000000..e519eee3 --- /dev/null +++ b/app/apps/splits/apps.py @@ -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") diff --git a/app/apps/splits/auth.py b/app/apps/splits/auth.py new file mode 100644 index 00000000..5e7f4ffa --- /dev/null +++ b/app/apps/splits/auth.py @@ -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, + ) diff --git a/app/apps/splits/forms.py b/app/apps/splits/forms.py new file mode 100644 index 00000000..09055628 --- /dev/null +++ b/app/apps/splits/forms.py @@ -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: + # 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 diff --git a/app/apps/splits/migrations/0001_initial.py b/app/apps/splits/migrations/0001_initial.py new file mode 100644 index 00000000..09df7e4e --- /dev/null +++ b/app/apps/splits/migrations/0001_initial.py @@ -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'), + ), + ] diff --git a/app/apps/splits/migrations/__init__.py b/app/apps/splits/migrations/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/app/apps/splits/models.py b/app/apps/splits/models.py new file mode 100644 index 00000000..abecd20a --- /dev/null +++ b/app/apps/splits/models.py @@ -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}" diff --git a/app/apps/splits/services/__init__.py b/app/apps/splits/services/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/app/apps/splits/services/membership.py b/app/apps/splits/services/membership.py new file mode 100644 index 00000000..e0060e92 --- /dev/null +++ b/app/apps/splits/services/membership.py @@ -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"]) diff --git a/app/apps/splits/services/settlement.py b/app/apps/splits/services/settlement.py new file mode 100644 index 00000000..4b62dad7 --- /dev/null +++ b/app/apps/splits/services/settlement.py @@ -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, + } diff --git a/app/apps/splits/services/splitting.py b/app/apps/splits/services/splitting.py new file mode 100644 index 00000000..f27a7934 --- /dev/null +++ b/app/apps/splits/services/splitting.py @@ -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 + ] + ) diff --git a/app/apps/splits/services/wygiwyh_sync.py b/app/apps/splits/services/wygiwyh_sync.py new file mode 100644 index 00000000..f764a8ae --- /dev/null +++ b/app/apps/splits/services/wygiwyh_sync.py @@ -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 diff --git a/app/apps/splits/templatetags/__init__.py b/app/apps/splits/templatetags/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/app/apps/splits/templatetags/split_urls.py b/app/apps/splits/templatetags/split_urls.py new file mode 100644 index 00000000..1ed36ccd --- /dev/null +++ b/app/apps/splits/templatetags/split_urls.py @@ -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) diff --git a/app/apps/splits/tests/__init__.py b/app/apps/splits/tests/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/app/apps/splits/tests/test_splits.py b/app/apps/splits/tests/test_splits.py new file mode 100644 index 00000000..9894bbcb --- /dev/null +++ b/app/apps/splits/tests/test_splits.py @@ -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") diff --git a/app/apps/splits/urls.py b/app/apps/splits/urls.py new file mode 100644 index 00000000..fec37b4e --- /dev/null +++ b/app/apps/splits/urls.py @@ -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//", views.event_detail, name="split_event_detail"), + path( + "splits//content/", + views.event_content, + name="split_event_content", + ), + path( + "splits//report/", + views.event_report, + name="split_event_report", + ), + path("splits//edit/", views.event_edit, name="split_event_edit"), + path( + "splits//delete/", + views.event_delete, + name="split_event_delete", + ), + path( + "splits//leave/", + views.event_leave, + name="split_event_leave", + ), + # Participant & Share Link Management + path( + "splits//participants/", + views.participants_manage, + name="split_participants_manage", + ), + path( + "splits//participants/add-user/", + views.participant_add_wygiwyh, + name="split_participant_add_wygiwyh", + ), + path( + "splits//participants/add-external/", + views.participant_add_external, + name="split_participant_add_external", + ), + path( + "splits//participants//toggle-active/", + views.participant_toggle_active, + name="split_participant_toggle_active", + ), + path( + "splits//participants//delete/", + views.participant_delete, + name="split_participant_delete", + ), + path( + "splits//participants//reset-password/", + views.participant_reset_password, + name="split_participant_reset_password", + ), + path( + "splits//regenerate-link/", + views.event_regenerate_link, + name="split_event_regenerate_link", + ), + # Expenses, Payments, Attachments (WYGIWYH) + path( + "splits//expenses/add/", + views.expense_add, + name="split_expense_add", + ), + path( + "splits//expenses//edit/", + views.expense_edit, + name="split_expense_edit", + ), + path( + "splits//expenses//delete/", + views.expense_delete, + name="split_expense_delete", + ), + path( + "splits//payments/add/", + views.payment_add, + name="split_payment_add", + ), + path( + "splits//payments//edit/", + views.payment_edit, + name="split_payment_edit", + ), + path( + "splits//payments//delete/", + views.payment_delete, + name="split_payment_delete", + ), + path( + "splits//attachments//download/", + views.attachment_download, + name="split_attachment_download", + ), + path( + "splits//attachments//delete/", + views.attachment_delete, + name="split_attachment_delete", + ), + # WYGIWYH Transaction Sync + path( + "splits//sync/expense//", + views.sync_expense, + name="split_sync_expense", + ), + path( + "splits//sync/payment//", + views.sync_payment, + name="split_sync_payment", + ), + path( + "splits//sync/settlement/", + views.sync_settlement, + name="split_sync_settlement", + ), + path( + "splits//sync/unlink//", + views.sync_unlink, + name="split_sync_unlink", + ), + # External Participant Portal (Shared UUID Link) + path( + "splits/share//", + views.external_auth, + name="split_external_auth", + ), + path( + "splits/share//logout/", + views.external_logout, + name="split_external_logout", + ), + path( + "splits/share//event/", + views.external_event_detail, + name="split_external_event_detail", + ), + path( + "splits/share//event/content/", + views.external_event_content, + name="split_external_event_content", + ), + path( + "splits/share//event/report/", + views.external_event_report, + name="split_external_event_report", + ), + path( + "splits/share//toasts/", + views.external_toasts, + name="split_external_toasts", + ), + path( + "splits/share//expenses/add/", + views.external_expense_add, + name="split_external_expense_add", + ), + path( + "splits/share//expenses//edit/", + views.external_expense_edit, + name="split_external_expense_edit", + ), + path( + "splits/share//expenses//delete/", + views.external_expense_delete, + name="split_external_expense_delete", + ), + path( + "splits/share//payments/add/", + views.external_payment_add, + name="split_external_payment_add", + ), + path( + "splits/share//payments//edit/", + views.external_payment_edit, + name="split_external_payment_edit", + ), + path( + "splits/share//payments//delete/", + views.external_payment_delete, + name="split_external_payment_delete", + ), + path( + "splits/share//attachments//download/", + views.external_attachment_download, + name="split_external_attachment_download", + ), + path( + "splits/share//attachments//delete/", + views.external_attachment_delete, + name="split_external_attachment_delete", + ), +] diff --git a/app/apps/splits/views.py b/app/apps/splits/views.py new file mode 100644 index 00000000..d069eabd --- /dev/null +++ b/app/apps/splits/views.py @@ -0,0 +1,1441 @@ +from decimal import Decimal, InvalidOperation + +from django.contrib import messages +from django.contrib.auth.decorators import login_required +from django.core.exceptions import PermissionDenied +from django.db import transaction as db_transaction +from django.http import FileResponse, Http404, HttpResponse +from django.shortcuts import get_object_or_404, redirect, render +from django.urls import reverse +from django.utils import timezone +from django.utils.translation import gettext_lazy as _ +from django.views.decorators.http import require_http_methods + +from apps.common.decorators.htmx import only_htmx +from apps.splits.auth import ( + SplitActor, + accessible_events, + user_display_name, + clear_external_session, + get_external_actor, + get_external_participant_from_session, + get_wygiwyh_actor, + set_external_session, +) +from apps.splits.forms import ( + AddExternalParticipantForm, + AddWygiwyhParticipantForm, + ExternalAuthForm, + SplitEventForm, + SplitExpenseForm, + SplitPaymentForm, + SplitTransactionSyncForm, +) +from apps.splits.models import ( + SplitAttachment, + SplitEvent, + SplitExpense, + SplitParticipant, + SplitPayment, + SplitTransactionLink, +) +from apps.splits.services.settlement import get_event_settlement_summary +from apps.splits.services.membership import leave_event +from apps.splits.services.splitting import replace_expense_shares +from apps.splits.services.wygiwyh_sync import ( + build_default_sync_description, + create_and_link_transaction, + expected_transaction_type_for_kind, + link_existing_transaction, + settle_pending_links_for_payment, +) + + +def _portal_urls(actor: SplitActor) -> dict: + event = actor.event + if actor.is_external_portal: + tok = event.share_token + return { + "event_detail": reverse("split_external_event_detail", kwargs={"share_token": tok}), + "event_content": reverse("split_external_event_content", kwargs={"share_token": tok}), + "report": reverse("split_external_event_report", kwargs={"share_token": tok}), + "expense_add": reverse("split_external_expense_add", kwargs={"share_token": tok}), + "payment_add": reverse("split_external_payment_add", kwargs={"share_token": tok}), + "expense_edit_name": "split_external_expense_edit", + "expense_delete_name": "split_external_expense_delete", + "payment_edit_name": "split_external_payment_edit", + "payment_delete_name": "split_external_payment_delete", + "attachment_download_name": "split_external_attachment_download", + "attachment_delete_name": "split_external_attachment_delete", + "url_kwarg_key": "share_token", + "url_kwarg_val": tok, + } + return { + "event_detail": reverse("split_event_detail", kwargs={"event_id": event.id}), + "event_content": reverse("split_event_content", kwargs={"event_id": event.id}), + "report": reverse("split_event_report", kwargs={"event_id": event.id}), + "expense_add": reverse("split_expense_add", kwargs={"event_id": event.id}), + "payment_add": reverse("split_payment_add", kwargs={"event_id": event.id}), + "expense_edit_name": "split_expense_edit", + "expense_delete_name": "split_expense_delete", + "payment_edit_name": "split_payment_edit", + "payment_delete_name": "split_payment_delete", + "attachment_download_name": "split_attachment_download", + "attachment_delete_name": "split_attachment_delete", + "url_kwarg_key": "event_id", + "url_kwarg_val": event.id, + } + + +def _build_event_context(request, actor: SplitActor) -> dict: + event = actor.event + summary = get_event_settlement_summary(event) + + expenses = list( + event.expenses.select_related("paid_by", "created_by_participant") + .prefetch_related("shares__participant", "attachments") + .all() + ) + payments = list( + event.payments.select_related( + "from_participant", "to_participant", "created_by_participant" + ) + .prefetch_related("attachments") + .all() + ) + + # Map WYGIWYH transaction links for the current logged-in WYGIWYH user + expense_links: dict[int, list[SplitTransactionLink]] = {} + payment_links: dict[int, list[SplitTransactionLink]] = {} + settlement_out_links: dict[int, list[SplitTransactionLink]] = {} + settlement_in_links: dict[int, list[SplitTransactionLink]] = {} + + if actor.is_wygiwyh_user: + user_links = ( + SplitTransactionLink.objects.filter( + event=event, + user=actor.user, + transaction__deleted=False, + ) + .select_related("transaction", "transaction__account", "transaction__account__currency", "counterparty") + .all() + ) + for link in user_links: + if link.expense_id: + expense_links.setdefault(link.expense_id, []).append(link) + elif link.payment_id: + payment_links.setdefault(link.payment_id, []).append(link) + elif link.kind == SplitTransactionLink.Kind.SETTLEMENT_OUT and link.counterparty_id: + settlement_out_links.setdefault(link.counterparty_id, []).append(link) + elif link.kind == SplitTransactionLink.Kind.SETTLEMENT_IN and link.counterparty_id: + settlement_in_links.setdefault(link.counterparty_id, []).append(link) + + me_id = actor.participant.id if actor.participant else None + # Only money that moved through the user's own accounts can be synced (matches sync views) + sync_id = me_id if actor.is_wygiwyh_user else None + + for exp in expenses: + exp.can_edit = actor.can_edit_item( + created_by_id=exp.created_by_participant_id, + primary_participant_id=exp.paid_by_id, + ) + exp.can_sync = sync_id is not None and exp.paid_by_id == sync_id + exp.user_tx_links = expense_links.get(exp.id, []) + # What this expense means for the viewer: > 0 lent, < 0 borrowed, None not involved + my_share = next((s.amount for s in exp.shares.all() if s.participant_id == me_id), None) + if exp.paid_by_id == me_id: + exp.my_delta = exp.amount - (my_share or 0) + else: + exp.my_delta = -my_share if my_share is not None else None + exp.my_delta_abs = abs(exp.my_delta) if exp.my_delta is not None else None + + for pay in payments: + pay.is_payment = True + pay.can_edit = actor.can_edit_item( + created_by_id=pay.created_by_participant_id, + primary_participant_id=pay.from_participant_id, + ) + pay.can_sync = sync_id is not None and sync_id in ( + pay.from_participant_id, + pay.to_participant_id, + ) + pay.user_tx_links = payment_links.get(pay.id, []) + + activity = sorted( + [*expenses, *payments], key=lambda i: (i.date, i.created_at), reverse=True + ) + + # Diverging bar per person, scaled to the largest balance + max_abs = max((abs(b.net_balance) for b in summary["balances"]), default=0) + balance_rows = [ + { + "balance": b, + "bar": int(abs(b.net_balance) * 50 / max_abs) if max_abs else 0, + } + for b in summary["balances"] + ] + + enriched_transfers = [] + for t in summary["transfers"]: + user_direction = None + counterparty = None + links = [] + if actor.is_wygiwyh_user and actor.participant: + if t.from_participant.id == actor.participant.id: + user_direction = "out" + counterparty = t.to_participant + links = settlement_out_links.get(counterparty.id, []) + elif t.to_participant.id == actor.participant.id: + user_direction = "in" + counterparty = t.from_participant + links = settlement_in_links.get(counterparty.id, []) + enriched_transfers.append( + { + "transfer": t, + "user_direction": user_direction, + "counterparty": counterparty, + "tx_links": links, + "can_record": actor.can_record_payment( + t.from_participant.id, t.to_participant.id + ), + } + ) + + my_balance = ( + summary["balances_by_id"].get(actor.participant.id) + if actor.participant + else None + ) + + share_url = request.build_absolute_uri( + reverse("split_external_auth", kwargs={"share_token": event.share_token}) + ) + + active_participants_count = sum( + 1 for b in summary["balances"] if b.participant.is_active + ) + + return { + "event": event, + "actor": actor, + "urls": _portal_urls(actor), + "balance_rows": balance_rows, + "transfers": enriched_transfers, + "total_spent": summary["total_spent"], + "my_balance": my_balance, + "my_balance_abs": abs(my_balance.net_balance) if my_balance else None, + "me_id": me_id, + "active_participants_count": active_participants_count, + "activity": activity, + "expense_count": len(expenses), + "payment_count": len(payments), + "share_url": share_url, + } + + +def _save_expense_from_form( + form: SplitExpenseForm, + *, + actor: SplitActor, + files, +) -> SplitExpense: + with db_transaction.atomic(): + expense: SplitExpense = form.save(commit=False) + expense.event = actor.event + if not expense.pk: + expense.created_by_participant = actor.participant + expense.save() + + replace_expense_shares(expense, form.computed_shares) + + for f in files: + SplitAttachment.objects.create( + event=actor.event, + expense=expense, + file=f, + original_name=f.name, + content_type=getattr(f, "content_type", ""), + size=f.size, + uploaded_by=actor.participant, + ) + return expense + + +def _save_payment_from_form( + form: SplitPaymentForm, + *, + actor: SplitActor, + files, +) -> SplitPayment: + is_new = not form.instance.pk + with db_transaction.atomic(): + payment: SplitPayment = form.save(commit=False) + payment.event = actor.event + if is_new: + payment.created_by_participant = actor.participant + payment.save() + + for f in files: + SplitAttachment.objects.create( + event=actor.event, + payment=payment, + file=f, + original_name=f.name, + content_type=getattr(f, "content_type", ""), + size=f.size, + uploaded_by=actor.participant, + ) + + if is_new: + settle_pending_links_for_payment(payment) + return payment + + +def _build_expense_form_context( + form: SplitExpenseForm, + actor: SplitActor, + *, + expense: SplitExpense | None = None, + post_url: str, +) -> dict: + # Build per-participant initial state for the share selector UI + if form.is_bound: + selected_ids = set() + for raw in form.data.getlist("share_participants"): + try: + selected_ids.add(int(raw)) + except (TypeError, ValueError): + pass + rows = [] + for p in form.available_participants: + rows.append( + { + "participant": p, + "selected": p.id in selected_ids, + "value": form.data.get(f"share_value_{p.id}", ""), + } + ) + elif expense and expense.pk: + share_map = {s.participant_id: s for s in expense.shares.all()} + rows = [] + for p in form.available_participants: + s = share_map.get(p.id) + val = "" + if s: + if expense.split_type == SplitExpense.SplitType.EXACT: + val = f"{s.amount.normalize():f}" + elif expense.split_type == SplitExpense.SplitType.PERCENTAGE and s.percentage is not None: + val = f"{s.percentage.normalize():f}" + elif expense.split_type == SplitExpense.SplitType.SHARES and s.shares is not None: + val = f"{s.shares.normalize():f}" + rows.append( + { + "participant": p, + "selected": s is not None, + "value": val, + } + ) + else: + rows = [ + { + "participant": p, + "selected": True, + "value": "", + } + for p in form.available_participants + ] + + return { + "form": form, + "event": actor.event, + "actor": actor, + "expense": expense, + "participant_rows": rows, + "post_url": post_url, + "urls": _portal_urls(actor), + } + + +# ============================================================================= +# WYGIWYH User Views +# ============================================================================= + + +@login_required +def event_index(request): + return render(request, "splits/pages/event_index.html") + + +@only_htmx +@login_required +def event_list(request): + show_archived = request.GET.get("archived") == "1" + events_qs = ( + accessible_events(request.user) + .select_related("currency", "creator") + .prefetch_related("participants") + ) + if not show_archived: + events_qs = events_qs.filter(is_archived=False) + + event_cards = [] + for event in events_qs: + summary = get_event_settlement_summary(event) + me = event.get_wygiwyh_participant(request.user) + my_bal = summary["balances_by_id"].get(me.id) if me else None + event_cards.append( + { + "event": event, + "total_spent": summary["total_spent"], + "my_balance": my_bal, + "participant_count": sum( + 1 for p in event.participants.all() if p.is_active + ), + "is_creator": event.can_manage(request.user), + } + ) + + return render( + request, + "splits/fragments/event/list.html", + { + "event_cards": event_cards, + "show_archived": show_archived, + }, + ) + + +@only_htmx +@login_required +def event_add(request): + if request.method == "POST": + form = SplitEventForm(request.POST) + if form.is_valid(): + with db_transaction.atomic(): + event = form.save(commit=False) + event.creator = request.user + event.save() + SplitParticipant.objects.create( + event=event, + user=request.user, + name=user_display_name(request.user), + is_external=False, + is_active=True, + ) + messages.success(request, _("Split event created successfully")) + return HttpResponse( + status=204, + headers={"HX-Trigger": "updated, hide_offcanvas"}, + ) + else: + form = SplitEventForm() + + return render(request, "splits/fragments/event/add.html", {"form": form}) + + +@login_required +def event_detail(request, event_id): + actor = get_wygiwyh_actor(request, event_id) + return render( + request, + "splits/pages/event_detail.html", + { + "event": actor.event, + "actor": actor, + "urls": _portal_urls(actor), + }, + ) + + +@only_htmx +@login_required +def event_content(request, event_id): + actor = get_wygiwyh_actor(request, event_id) + ctx = _build_event_context(request, actor) + return render(request, "splits/fragments/event/content.html", ctx) + + +@login_required +def event_report(request, event_id): + actor = get_wygiwyh_actor(request, event_id) + return render( + request, "splits/pages/event_report.html", _build_event_context(request, actor) + ) + + +@only_htmx +@login_required +def event_edit(request, event_id): + actor = get_wygiwyh_actor(request, event_id) + if not actor.is_creator: + raise PermissionDenied + + if request.method == "POST": + form = SplitEventForm(request.POST, instance=actor.event) + if form.is_valid(): + form.save() + messages.success(request, _("Event updated successfully")) + return HttpResponse( + status=204, + headers={"HX-Trigger": "updated, hide_offcanvas"}, + ) + else: + form = SplitEventForm(instance=actor.event) + + return render( + request, + "splits/fragments/event/edit.html", + {"form": form, "event": actor.event}, + ) + + +@only_htmx +@login_required +@require_http_methods(["DELETE"]) +def event_delete(request, event_id): + actor = get_wygiwyh_actor(request, event_id) + if not actor.is_creator: + raise PermissionDenied + actor.event.delete() + messages.success(request, _("Event deleted successfully")) + return HttpResponse( + status=204, + headers={ + "HX-Redirect": reverse("split_event_index"), + }, + ) + + +@only_htmx +@login_required +@require_http_methods(["POST"]) +def event_leave(request, event_id): + actor = get_wygiwyh_actor(request, event_id) + if actor.is_creator or not actor.participant: + raise PermissionDenied + + leave_event(actor) + + messages.success(request, _("You left %(name)s") % {"name": actor.event.name}) + return HttpResponse( + status=204, + headers={"HX-Redirect": reverse("split_event_index")}, + ) + + +# ============================================================================= +# Participants & Share Link Management (Creator only) +# ============================================================================= + + +def _render_participants_manage(request, actor: SplitActor, wygiwyh_form=None, external_form=None): + event = actor.event + participants = list(event.participants.select_related("user").all()) + for p in participants: + p.has_contribs = p.has_contributions() + p.deletable = p.can_be_deleted() + + share_url = request.build_absolute_uri( + reverse("split_external_auth", kwargs={"share_token": event.share_token}) + ) + return render( + request, + "splits/fragments/participants/manage.html", + { + "event": event, + "participants": participants, + "wygiwyh_form": wygiwyh_form or AddWygiwyhParticipantForm(event=event), + "external_form": external_form or AddExternalParticipantForm(event=event), + "share_url": share_url, + }, + ) + + +@only_htmx +@login_required +def participants_manage(request, event_id): + actor = get_wygiwyh_actor(request, event_id) + if not actor.is_creator: + raise PermissionDenied + return _render_participants_manage(request, actor) + + +@only_htmx +@login_required +@require_http_methods(["POST"]) +def participant_add_wygiwyh(request, event_id): + actor = get_wygiwyh_actor(request, event_id) + if not actor.is_creator: + raise PermissionDenied + + form = AddWygiwyhParticipantForm(request.POST, event=actor.event) + if form.is_valid(): + u = form.cleaned_data["user"] + base_name = user_display_name(u) + name = base_name + suffix = 2 + while actor.event.participants.filter(name__iexact=name).exists(): + name = f"{base_name} ({suffix})" + suffix += 1 + SplitParticipant.objects.create( + event=actor.event, + user=u, + name=name, + is_external=False, + is_active=True, + ) + messages.success(request, _("Added %(name)s to the event") % {"name": name}) + resp = _render_participants_manage(request, actor) + resp["HX-Trigger"] = "updated, toasts" + return resp + + return _render_participants_manage(request, actor, wygiwyh_form=form) + + +@only_htmx +@login_required +@require_http_methods(["POST"]) +def participant_add_external(request, event_id): + actor = get_wygiwyh_actor(request, event_id) + if not actor.is_creator: + raise PermissionDenied + + form = AddExternalParticipantForm(request.POST, event=actor.event) + if form.is_valid(): + name = form.cleaned_data["name"] + SplitParticipant.objects.create( + event=actor.event, + user=None, + name=name, + is_external=True, + is_active=True, + ) + messages.success( + request, + _("Added external participant %(name)s") % {"name": name}, + ) + resp = _render_participants_manage(request, actor) + resp["HX-Trigger"] = "updated, toasts" + return resp + + return _render_participants_manage(request, actor, external_form=form) + + +@only_htmx +@login_required +@require_http_methods(["POST"]) +def participant_toggle_active(request, event_id, participant_id): + actor = get_wygiwyh_actor(request, event_id) + if not actor.is_creator: + raise PermissionDenied + + participant = get_object_or_404( + SplitParticipant, id=participant_id, event=actor.event + ) + if participant.is_creator: + messages.error(request, _("The event creator cannot be deactivated.")) + else: + participant.is_active = not participant.is_active + participant.save(update_fields=["is_active"]) + if participant.is_active: + messages.success( + request, _("Reactivated %(name)s") % {"name": participant.name} + ) + else: + messages.success( + request, + _("Deactivated %(name)s (contributions preserved)") + % {"name": participant.name}, + ) + + resp = _render_participants_manage(request, actor) + resp["HX-Trigger"] = "updated, toasts" + return resp + + +@only_htmx +@login_required +@require_http_methods(["DELETE"]) +def participant_delete(request, event_id, participant_id): + actor = get_wygiwyh_actor(request, event_id) + if not actor.is_creator: + raise PermissionDenied + + participant = get_object_or_404( + SplitParticipant, id=participant_id, event=actor.event + ) + if participant.can_be_deleted(): + name = participant.name + participant.delete() + messages.success(request, _("Removed %(name)s") % {"name": name}) + else: + messages.error( + request, + _( + "%(name)s has existing contributions and cannot be deleted. Deactivate them instead." + ) + % {"name": participant.name}, + ) + + resp = _render_participants_manage(request, actor) + resp["HX-Trigger"] = "updated, toasts" + return resp + + +@only_htmx +@login_required +@require_http_methods(["POST"]) +def participant_reset_password(request, event_id, participant_id): + actor = get_wygiwyh_actor(request, event_id) + if not actor.is_creator: + raise PermissionDenied + + participant = get_object_or_404( + SplitParticipant, id=participant_id, event=actor.event, is_external=True + ) + participant.reset_external_password() + messages.success( + request, + _("Password reset for %(name)s. They can set a new password on next login.") + % {"name": participant.name}, + ) + resp = _render_participants_manage(request, actor) + resp["HX-Trigger"] = "updated, toasts" + return resp + + +@only_htmx +@login_required +@require_http_methods(["POST"]) +def event_regenerate_link(request, event_id): + actor = get_wygiwyh_actor(request, event_id) + if not actor.is_creator: + raise PermissionDenied + + actor.event.regenerate_share_token() + messages.success( + request, + _("Share link regenerated. Existing external sessions have been signed out."), + ) + resp = _render_participants_manage(request, actor) + resp["HX-Trigger"] = "updated, toasts" + return resp + + +# ============================================================================= +# Shared Expense / Payment / Attachment Handlers (WYGIWYH + External) +# ============================================================================= + + +def _handle_expense_add(request, actor: SplitActor): + urls = _portal_urls(actor) + if request.method == "POST": + form = SplitExpenseForm( + request.POST, + request.FILES, + event=actor.event, + default_payer=actor.participant, + ) + if form.is_valid(): + _save_expense_from_form( + form, + actor=actor, + files=form.cleaned_data.get("attachments") or [], + ) + messages.success(request, _("Expense added successfully")) + return HttpResponse( + status=204, + headers={"HX-Trigger": "updated, hide_offcanvas, toasts"}, + ) + else: + form = SplitExpenseForm(event=actor.event, default_payer=actor.participant) + + ctx = _build_expense_form_context(form, actor, post_url=urls["expense_add"]) + return render(request, "splits/fragments/expense/form.html", ctx) + + +def _handle_expense_edit(request, actor: SplitActor, expense_id: int): + expense = get_object_or_404( + SplitExpense.objects.prefetch_related("shares__participant", "attachments"), + id=expense_id, + event=actor.event, + ) + if not actor.can_edit_item( + created_by_id=expense.created_by_participant_id, + primary_participant_id=expense.paid_by_id, + ): + raise PermissionDenied + + urls = _portal_urls(actor) + post_url = reverse( + urls["expense_edit_name"], + kwargs={urls["url_kwarg_key"]: urls["url_kwarg_val"], "expense_id": expense.id}, + ) + + if request.method == "POST": + form = SplitExpenseForm( + request.POST, + request.FILES, + instance=expense, + event=actor.event, + ) + if form.is_valid(): + _save_expense_from_form( + form, + actor=actor, + files=form.cleaned_data.get("attachments") or [], + ) + messages.success(request, _("Expense updated successfully")) + return HttpResponse( + status=204, + headers={"HX-Trigger": "updated, hide_offcanvas, toasts"}, + ) + else: + form = SplitExpenseForm(instance=expense, event=actor.event) + + ctx = _build_expense_form_context(form, actor, expense=expense, post_url=post_url) + return render(request, "splits/fragments/expense/form.html", ctx) + + +def _handle_expense_delete(request, actor: SplitActor, expense_id: int): + expense = get_object_or_404(SplitExpense, id=expense_id, event=actor.event) + if not actor.can_edit_item( + created_by_id=expense.created_by_participant_id, + primary_participant_id=expense.paid_by_id, + ): + raise PermissionDenied + + for att in expense.attachments.all(): + att.file.delete(save=False) + expense.delete() + messages.success(request, _("Expense deleted successfully")) + return HttpResponse( + status=204, + headers={"HX-Trigger": "updated, hide_offcanvas, toasts"}, + ) + + +def _handle_payment_add(request, actor: SplitActor): + urls = _portal_urls(actor) + initial = {} + if request.method == "GET": + if request.GET.get("from"): + initial["from_participant"] = request.GET.get("from") + elif actor.participant: + initial["from_participant"] = actor.participant.id + if request.GET.get("to"): + initial["to_participant"] = request.GET.get("to") + try: + # Settle-up links send a plain "12.34", not the user's number format + initial["amount"] = Decimal(request.GET["amount"]) + except (KeyError, InvalidOperation): + pass + + if request.method == "POST": + form = SplitPaymentForm(request.POST, request.FILES, event=actor.event, actor=actor) + if form.is_valid(): + _save_payment_from_form( + form, + actor=actor, + files=form.cleaned_data.get("attachments") or [], + ) + messages.success(request, _("Payment recorded successfully")) + return HttpResponse( + status=204, + headers={"HX-Trigger": "updated, hide_offcanvas, toasts"}, + ) + else: + form = SplitPaymentForm(event=actor.event, actor=actor, initial=initial) + + return render( + request, + "splits/fragments/payment/form.html", + { + "form": form, + "event": actor.event, + "actor": actor, + "payment": None, + "post_url": urls["payment_add"], + "urls": urls, + }, + ) + + +def _handle_payment_edit(request, actor: SplitActor, payment_id: int): + payment = get_object_or_404( + SplitPayment.objects.prefetch_related("attachments"), + id=payment_id, + event=actor.event, + ) + if not actor.can_edit_item( + created_by_id=payment.created_by_participant_id, + primary_participant_id=payment.from_participant_id, + ): + raise PermissionDenied + + urls = _portal_urls(actor) + post_url = reverse( + urls["payment_edit_name"], + kwargs={urls["url_kwarg_key"]: urls["url_kwarg_val"], "payment_id": payment.id}, + ) + + if request.method == "POST": + form = SplitPaymentForm( + request.POST, request.FILES, instance=payment, event=actor.event, actor=actor + ) + if form.is_valid(): + _save_payment_from_form( + form, + actor=actor, + files=form.cleaned_data.get("attachments") or [], + ) + messages.success(request, _("Payment updated successfully")) + return HttpResponse( + status=204, + headers={"HX-Trigger": "updated, hide_offcanvas, toasts"}, + ) + else: + form = SplitPaymentForm(instance=payment, event=actor.event, actor=actor) + + return render( + request, + "splits/fragments/payment/form.html", + { + "form": form, + "event": actor.event, + "actor": actor, + "payment": payment, + "post_url": post_url, + "urls": urls, + }, + ) + + +def _handle_payment_delete(request, actor: SplitActor, payment_id: int): + payment = get_object_or_404(SplitPayment, id=payment_id, event=actor.event) + if not actor.can_edit_item( + created_by_id=payment.created_by_participant_id, + primary_participant_id=payment.from_participant_id, + ): + raise PermissionDenied + + for att in payment.attachments.all(): + att.file.delete(save=False) + payment.delete() + messages.success(request, _("Payment deleted successfully")) + return HttpResponse( + status=204, + headers={"HX-Trigger": "updated, hide_offcanvas, toasts"}, + ) + + +INLINE_SAFE_CONTENT_TYPES = { + "application/pdf", + "image/gif", + "image/jpeg", + "image/png", + "image/webp", +} + + +def _handle_attachment_download(actor: SplitActor, attachment_id): + att = get_object_or_404(SplitAttachment, id=attachment_id, event=actor.event) + # Anonymous external participants upload these, so never render HTML/SVG inline + return FileResponse( + att.file.open("rb"), + as_attachment=att.content_type not in INLINE_SAFE_CONTENT_TYPES, + filename=att.original_name, + content_type=att.content_type or "application/octet-stream", + ) + + +def _handle_attachment_delete(request, actor: SplitActor, attachment_id): + att = get_object_or_404(SplitAttachment, id=attachment_id, event=actor.event) + can_delete = actor.is_creator or ( + actor.participant and att.uploaded_by_id == actor.participant.id + ) + if not can_delete and att.expense_id: + can_delete = actor.can_edit_item( + created_by_id=att.expense.created_by_participant_id, + primary_participant_id=att.expense.paid_by_id, + ) + if not can_delete and att.payment_id: + can_delete = actor.can_edit_item( + created_by_id=att.payment.created_by_participant_id, + primary_participant_id=att.payment.from_participant_id, + ) + if not can_delete: + raise PermissionDenied + + att.file.delete(save=False) + att.delete() + messages.success(request, _("Attachment deleted")) + return HttpResponse( + status=204, + headers={"HX-Trigger": "updated, toasts"}, + ) + + +# WYGIWYH wrappers +@only_htmx +@login_required +def expense_add(request, event_id): + return _handle_expense_add(request, get_wygiwyh_actor(request, event_id)) + + +@only_htmx +@login_required +def expense_edit(request, event_id, expense_id): + return _handle_expense_edit(request, get_wygiwyh_actor(request, event_id), expense_id) + + +@only_htmx +@login_required +@require_http_methods(["DELETE"]) +def expense_delete(request, event_id, expense_id): + return _handle_expense_delete(request, get_wygiwyh_actor(request, event_id), expense_id) + + +@only_htmx +@login_required +def payment_add(request, event_id): + return _handle_payment_add(request, get_wygiwyh_actor(request, event_id)) + + +@only_htmx +@login_required +def payment_edit(request, event_id, payment_id): + return _handle_payment_edit(request, get_wygiwyh_actor(request, event_id), payment_id) + + +@only_htmx +@login_required +@require_http_methods(["DELETE"]) +def payment_delete(request, event_id, payment_id): + return _handle_payment_delete(request, get_wygiwyh_actor(request, event_id), payment_id) + + +@login_required +@require_http_methods(["GET"]) +def attachment_download(request, event_id, attachment_id): + return _handle_attachment_download(get_wygiwyh_actor(request, event_id), attachment_id) + + +@only_htmx +@login_required +@require_http_methods(["DELETE"]) +def attachment_delete(request, event_id, attachment_id): + return _handle_attachment_delete(request, get_wygiwyh_actor(request, event_id), attachment_id) + + +# ============================================================================= +# WYGIWYH Transaction Integration Views +# ============================================================================= + + +def _handle_sync_view( + request, + *, + actor: SplitActor, + kind: str, + default_amount: Decimal, + default_date, + default_notes: str, + post_url: str, + title: str, + expense: SplitExpense | None = None, + payment: SplitPayment | None = None, + counterparty: SplitParticipant | None = None, + default_is_paid: bool = True, +): + tx_type = expected_transaction_type_for_kind(kind) + default_desc = build_default_sync_description( + event=actor.event, + kind=kind, + expense=expense, + payment=payment, + counterparty=counterparty, + ) + + if request.method == "POST": + form = SplitTransactionSyncForm( + request.POST, + user=actor.user, + event=actor.event, + tx_type=tx_type, + ) + if form.is_valid(): + if form.cleaned_data["mode"] == SplitTransactionSyncForm.Mode.CREATE: + create_and_link_transaction( + user=actor.user, + event=actor.event, + kind=kind, + account=form.cleaned_data["account"], + amount=form.cleaned_data["amount"], + date=form.cleaned_data["date"], + description=form.cleaned_data["description"] or default_desc, + is_paid=form.cleaned_data["is_paid"], + category=form.cleaned_data.get("category"), + tags=form.cleaned_data.get("tags") or [], + entities=form.cleaned_data.get("entities") or [], + notes=form.cleaned_data.get("notes", ""), + expense=expense, + payment=payment, + counterparty=counterparty, + ) + messages.success( + request, _("Transaction created and linked") + ) + else: + link_existing_transaction( + user=actor.user, + event=actor.event, + kind=kind, + tx=form.cleaned_data["existing_transaction"], + expense=expense, + payment=payment, + counterparty=counterparty, + ) + messages.success( + request, _("Transaction linked") + ) + return HttpResponse( + status=204, + headers={"HX-Trigger": "updated, hide_offcanvas, toasts"}, + ) + else: + form = SplitTransactionSyncForm( + user=actor.user, + event=actor.event, + tx_type=tx_type, + initial={ + "mode": SplitTransactionSyncForm.Mode.CREATE, + "amount": default_amount, + "date": default_date, + "description": default_desc, + "is_paid": default_is_paid, + "notes": default_notes, + }, + ) + + return render( + request, + "splits/fragments/sync/form.html", + { + "form": form, + "event": actor.event, + "post_url": post_url, + "title": title, + "tx_type": tx_type, + }, + ) + + +@only_htmx +@login_required +def sync_expense(request, event_id, expense_id): + actor = get_wygiwyh_actor(request, event_id) + # Only the payer's money left one of their accounts + expense = get_object_or_404( + SplitExpense, + id=expense_id, + event=actor.event, + paid_by=actor.participant, + ) + return _handle_sync_view( + request, + actor=actor, + kind=SplitTransactionLink.Kind.EXPENSE, + default_amount=expense.amount, + default_date=expense.date, + default_notes=expense.notes, + post_url=reverse( + "split_sync_expense", + kwargs={"event_id": actor.event.id, "expense_id": expense.id}, + ), + title=_("Add expense to my transactions"), + expense=expense, + default_is_paid=True, + ) + + +@only_htmx +@login_required +def sync_payment(request, event_id, payment_id): + actor = get_wygiwyh_actor(request, event_id) + payment = get_object_or_404( + SplitPayment.objects.select_related("from_participant", "to_participant"), + id=payment_id, + event=actor.event, + ) + me = actor.participant.id if actor.participant else None + if payment.to_participant_id == me: + kind = SplitTransactionLink.Kind.PAYMENT_IN + counterparty = payment.from_participant + title = _("Add received payment to my transactions") + elif payment.from_participant_id == me: + kind = SplitTransactionLink.Kind.PAYMENT_OUT + counterparty = payment.to_participant + title = _("Add sent payment to my transactions") + else: + raise Http404 + + return _handle_sync_view( + request, + actor=actor, + kind=kind, + default_amount=payment.amount, + default_date=payment.date, + default_notes=payment.notes, + post_url=reverse( + "split_sync_payment", + kwargs={"event_id": actor.event.id, "payment_id": payment.id}, + ), + title=title, + payment=payment, + counterparty=counterparty, + default_is_paid=True, + ) + + +@only_htmx +@login_required +def sync_settlement(request, event_id): + actor = get_wygiwyh_actor(request, event_id) + direction = request.GET.get("direction") or request.POST.get("direction") or "out" + counterparty_id = request.GET.get("counterparty") or request.POST.get("counterparty") + raw_amount = request.GET.get("amount") or request.POST.get("amount") or "0" + + counterparty = get_object_or_404( + SplitParticipant, id=counterparty_id, event=actor.event + ) + try: + amount = Decimal(str(raw_amount)) + except InvalidOperation: + amount = Decimal("0") + + if direction == "in": + kind = SplitTransactionLink.Kind.SETTLEMENT_IN + title = _("Expected payment from %(name)s") % { + "name": counterparty.name + } + else: + kind = SplitTransactionLink.Kind.SETTLEMENT_OUT + title = _("Planned payment to %(name)s") % { + "name": counterparty.name + } + + post_url = ( + reverse("split_sync_settlement", kwargs={"event_id": actor.event.id}) + + f"?direction={direction}&counterparty={counterparty.id}&amount={amount}" + ) + return _handle_sync_view( + request, + actor=actor, + kind=kind, + default_amount=amount, + default_date=timezone.localdate(), + default_notes="", + post_url=post_url, + title=title, + counterparty=counterparty, + default_is_paid=False, + ) + + +@only_htmx +@login_required +@require_http_methods(["DELETE"]) +def sync_unlink(request, event_id, link_id): + actor = get_wygiwyh_actor(request, event_id) + link = get_object_or_404( + SplitTransactionLink, + id=link_id, + event=actor.event, + user=actor.user, + ) + link.delete() + messages.success(request, _("Transaction unlinked")) + return HttpResponse( + status=204, + headers={"HX-Trigger": "updated, toasts"}, + ) + + +# ============================================================================= +# External Participant Portal Views (No WYGIWYH Account Required!) +# ============================================================================= + + +def external_auth(request, share_token): + event = get_object_or_404( + SplitEvent.objects.select_related("currency", "creator"), + share_token=share_token, + ) + if not event.allow_external_access: + return render( + request, + "splits/pages/external_disabled.html", + {"event": event}, + status=403, + ) + + existing = get_external_participant_from_session(request, event) + if existing: + return redirect("split_external_event_detail", share_token=event.share_token) + + external_participants = list( + event.participants.filter(is_external=True, is_active=True).order_by( + "name", "id" + ) + ) + + if request.method == "POST": + form = ExternalAuthForm(request.POST, event=event) + if form.is_valid(): + participant: SplitParticipant = form.cleaned_data["participant"] + if not participant.is_claimed: + participant.set_external_password( + form.cleaned_data["password"], + username=form.cleaned_data.get("username", ""), + ) + set_external_session(request, event, participant) + return redirect( + "split_external_event_detail", share_token=event.share_token + ) + else: + form = ExternalAuthForm(event=event) + + return render( + request, + "splits/pages/external_auth.html", + { + "event": event, + "form": form, + "external_participants": external_participants, + "claimed_ids": [p.id for p in external_participants if p.is_claimed], + }, + ) + + +@require_http_methods(["POST"]) +def external_logout(request, share_token): + event = get_object_or_404(SplitEvent, share_token=share_token) + clear_external_session(request, event) + return redirect("split_external_auth", share_token=event.share_token) + + +def external_event_detail(request, share_token): + actor = get_external_actor(request, share_token) + if actor is None: + return redirect("split_external_auth", share_token=share_token) + return render( + request, + "splits/pages/external_event_detail.html", + { + "event": actor.event, + "actor": actor, + "urls": _portal_urls(actor), + }, + ) + + +@only_htmx +def external_event_content(request, share_token): + actor = get_external_actor(request, share_token) + if actor is None: + return HttpResponse( + status=401, + headers={ + "HX-Redirect": reverse( + "split_external_auth", kwargs={"share_token": share_token} + ) + }, + ) + ctx = _build_event_context(request, actor) + return render(request, "splits/fragments/event/content.html", ctx) + + +def external_event_report(request, share_token): + actor = get_external_actor(request, share_token) + if actor is None: + return redirect("split_external_auth", share_token=share_token) + return render( + request, "splits/pages/event_report.html", _build_event_context(request, actor) + ) + + +@only_htmx +@require_http_methods(["GET"]) +def external_toasts(request, share_token): + actor = get_external_actor(request, share_token) + if actor is None: + return HttpResponse(status=204) + return render(request, "common/fragments/toasts.html") + + +@only_htmx +def external_expense_add(request, share_token): + actor = get_external_actor(request, share_token) + if actor is None: + return HttpResponse(status=401) + return _handle_expense_add(request, actor) + + +@only_htmx +def external_expense_edit(request, share_token, expense_id): + actor = get_external_actor(request, share_token) + if actor is None: + return HttpResponse(status=401) + return _handle_expense_edit(request, actor, expense_id) + + +@only_htmx +@require_http_methods(["DELETE"]) +def external_expense_delete(request, share_token, expense_id): + actor = get_external_actor(request, share_token) + if actor is None: + return HttpResponse(status=401) + return _handle_expense_delete(request, actor, expense_id) + + +@only_htmx +def external_payment_add(request, share_token): + actor = get_external_actor(request, share_token) + if actor is None: + return HttpResponse(status=401) + return _handle_payment_add(request, actor) + + +@only_htmx +def external_payment_edit(request, share_token, payment_id): + actor = get_external_actor(request, share_token) + if actor is None: + return HttpResponse(status=401) + return _handle_payment_edit(request, actor, payment_id) + + +@only_htmx +@require_http_methods(["DELETE"]) +def external_payment_delete(request, share_token, payment_id): + actor = get_external_actor(request, share_token) + if actor is None: + return HttpResponse(status=401) + return _handle_payment_delete(request, actor, payment_id) + + +@require_http_methods(["GET"]) +def external_attachment_download(request, share_token, attachment_id): + actor = get_external_actor(request, share_token) + if actor is None: + return redirect("split_external_auth", share_token=share_token) + return _handle_attachment_download(actor, attachment_id) + + +@only_htmx +@require_http_methods(["DELETE"]) +def external_attachment_delete(request, share_token, attachment_id): + actor = get_external_actor(request, share_token) + if actor is None: + return HttpResponse(status=401) + return _handle_attachment_delete(request, actor, attachment_id) diff --git a/app/templates/includes/sidebar.html b/app/templates/includes/sidebar.html index 8d398600..55e6b303 100644 --- a/app/templates/includes/sidebar.html +++ b/app/templates/includes/sidebar.html @@ -126,6 +126,12 @@ active="dca_strategy_index||dca_strategy_detail_index" icon="fa-solid fa-magnifying-glass-chart"> + + + {% for att in item.attachments.all %} + + + {{ att.original_name }} + + + + {% endfor %} + +{% endif %} diff --git a/app/templates/splits/fragments/event/activity_flags.html b/app/templates/splits/fragments/event/activity_flags.html new file mode 100644 index 00000000..8abdedc3 --- /dev/null +++ b/app/templates/splits/fragments/event/activity_flags.html @@ -0,0 +1 @@ +{% load i18n %}{% if item.attachments.all %}{% endif %}{% if item.user_tx_links %}{% endif %} diff --git a/app/templates/splits/fragments/event/activity_item.html b/app/templates/splits/fragments/event/activity_item.html new file mode 100644 index 00000000..5e07334f --- /dev/null +++ b/app/templates/splits/fragments/event/activity_item.html @@ -0,0 +1,114 @@ +{% load i18n %} +{% load split_urls %} +
  • +
    + +
    +
    {{ item.date|date:"M" }}
    +
    {{ item.date|date:"j" }}
    +
    + +
    + {% if item.is_payment %} +
    + + {% if item.from_participant_id == me_id %}{% blocktranslate with to=item.to_participant.name %}You paid {{ to }}{% endblocktranslate %} + {% elif item.to_participant_id == me_id %}{% blocktranslate with from=item.from_participant.name %}{{ from }} paid you{% endblocktranslate %} + {% else %}{% blocktranslate with from=item.from_participant.name to=item.to_participant.name %}{{ from }} paid {{ to }}{% endblocktranslate %}{% endif %} + {% include 'splits/fragments/event/activity_flags.html' %} +
    + {% if item.notes %}
    {{ item.notes }}
    {% endif %} + {% else %} +
    {{ item.description }}{% include 'splits/fragments/event/activity_flags.html' %}
    +
    + {% if item.paid_by_id == me_id %}{% translate 'You paid' %}{% else %}{% blocktranslate with name=item.paid_by.name %}{{ name }} paid{% endblocktranslate %}{% endif %} + +
    + {% endif %} +
    + +
    + {% if item.is_payment %} + + {% elif item.my_delta is None %} +
    {% translate 'not involved' %}
    + {% elif item.my_delta > 0 %} +
    {% translate 'you lent' %}
    + + {% elif item.my_delta < 0 %} +
    {% translate 'you borrowed' %}
    + + {% else %} +
    {% translate 'settled' %}
    + {% endif %} +
    + +
    + +
    +
    + +
    + {% if not item.is_payment %} +
    + {% for s in item.shares.all %} +
    +
    {% if s.participant_id == me_id %}{% translate 'You' %}{% else %}{{ s.participant.name }}{% endif %}
    +
    +
    + {% endfor %} +
    + {% if item.split_type != 'EQUAL' %} +
    {% blocktranslate with mode=item.get_split_type_display %}Split by {{ mode }}{% endblocktranslate %}
    + {% endif %} + {% endif %} + + {% if item.notes %}

    {{ item.notes }}

    {% endif %} + + {% if item.attachments.all or item.user_tx_links %} +
    + {% for att in item.attachments.all %} + + {{ att.original_name }} + + {% endfor %} + {% include 'splits/fragments/tx_links.html' with links=item.user_tx_links %} +
    + {% endif %} + + {% if item.can_sync or item.can_edit %} +
    + {% if item.can_sync %} + + {% endif %} + {% if item.can_edit %} + + + {% endif %} +
    + {% endif %} +
    +
    +
  • diff --git a/app/templates/splits/fragments/event/add.html b/app/templates/splits/fragments/event/add.html new file mode 100644 index 00000000..7f114c88 --- /dev/null +++ b/app/templates/splits/fragments/event/add.html @@ -0,0 +1,11 @@ +{% extends 'extends/offcanvas.html' %} +{% load i18n %} +{% load crispy_forms_tags %} + +{% block title %}{% translate 'Add event' %}{% endblock %} + +{% block body %} +
    + {% crispy form %} +
    +{% endblock %} diff --git a/app/templates/splits/fragments/event/content.html b/app/templates/splits/fragments/event/content.html new file mode 100644 index 00000000..43ffb7aa --- /dev/null +++ b/app/templates/splits/fragments/event/content.html @@ -0,0 +1,188 @@ +{% load i18n %} +{% load l10n %} +{% with c=event.currency %} + + + + + +
    +
    + {% if not actor.is_external_portal %} + + {% endif %} +

    {{ event.name }}

    + {% if event.is_archived %}{% translate 'Archived' %}{% endif %} + {% if actor.is_creator %} + + + {% elif actor.is_wygiwyh_user %} + + {% endif %} + {% include 'splits/fragments/event/share_menu.html' %} +
    +
    + {% blocktranslate count counter=active_participants_count %}{{ counter }} person{% plural %}{{ counter }} people{% endblocktranslate %} + {% if event.description %}
    {{ event.description }}
    {% endif %} +
    + + + + {# The one number people open this page for #} + {% if my_balance %} +
    +
    +
    + {% if not my_balance.net_balance %} +
    {% if transfers %}{% translate 'You are settled up' %}{% else %}{% translate 'Everyone is settled up' %}{% endif %}
    + {% else %} +
    + {% if my_balance.net_balance > 0 %}{% translate 'You are owed' %}{% else %}{% translate 'You owe' %}{% endif %} +
    +
    + {# Show the magnitude; the sentence above carries the direction #} + +
    + {% endif %} +
    +
    +
    {% translate 'Group total' %}
    + +
    +
    +
    + {% endif %} + +
    +
    + {% if transfers %} +
    +
    {% translate 'Settle up' %}
    +
      + {% for item in transfers %}{% with t=item.transfer %} +
    • +
      + + {% if t.from_participant.id == me_id %}{% translate 'You' %}{% else %}{{ t.from_participant.name }}{% endif %} + + {% if t.to_participant.id == me_id %}{% translate 'You' %}{% else %}{{ t.to_participant.name }}{% endif %} + + + + +
      + {% if item.tx_links %} +
      {% include 'splits/fragments/tx_links.html' with links=item.tx_links %}
      + {% endif %} + {% if item.can_record or item.user_direction %} +
      + {% if item.can_record %} + + {% endif %} + {% if item.user_direction %} + + {% endif %} +
      + {% endif %} +
    • + {% endwith %}{% endfor %} +
    +
    + {% endif %} + +
    +
    {% translate 'Balances' %}
    +
      + {% for row in balance_rows %}{% with b=row.balance %} +
    • +
      + + {{ b.participant.name }} + {% if b.participant.id == me_id %}{% translate 'you' %}{% endif %} + {% if not b.participant.is_active %}{% translate 'inactive' %}{% endif %} + + + + +
      + {# Diverging bar: right of center is owed money, left owes #} + +
      + {% translate 'paid' %} + · {% translate 'share' %} +
      +
    • + {% endwith %}{% endfor %} +
    +
    +
    + +
    +
    +
    {% translate 'Activity' %}
    + {% if activity %} +
      + {% for item in activity %} + {% include 'splits/fragments/event/activity_item.html' %} + {% endfor %} +
    + {% else %} + + {% endif %} +
    +
    +
    +
    +{% endwith %} diff --git a/app/templates/splits/fragments/event/edit.html b/app/templates/splits/fragments/event/edit.html new file mode 100644 index 00000000..6c5afaa7 --- /dev/null +++ b/app/templates/splits/fragments/event/edit.html @@ -0,0 +1,23 @@ +{% extends 'extends/offcanvas.html' %} +{% load i18n %} +{% load crispy_forms_tags %} + +{% block title %}{% translate 'Edit event' %}{% endblock %} + +{% block body %} +
    + {% crispy form %} +
    + +
    + +{% endblock %} diff --git a/app/templates/splits/fragments/event/export_script.html b/app/templates/splits/fragments/event/export_script.html new file mode 100644 index 00000000..6a10d67c --- /dev/null +++ b/app/templates/splits/fragments/event/export_script.html @@ -0,0 +1,58 @@ +{% load i18n %} + diff --git a/app/templates/splits/fragments/event/list.html b/app/templates/splits/fragments/event/list.html new file mode 100644 index 00000000..6dd76b7f --- /dev/null +++ b/app/templates/splits/fragments/event/list.html @@ -0,0 +1,71 @@ +{% load i18n %} + + + diff --git a/app/templates/splits/fragments/event/share_menu.html b/app/templates/splits/fragments/event/share_menu.html new file mode 100644 index 00000000..ea01fc7b --- /dev/null +++ b/app/templates/splits/fragments/event/share_menu.html @@ -0,0 +1,34 @@ +{% load i18n %} + diff --git a/app/templates/splits/fragments/expense/form.html b/app/templates/splits/fragments/expense/form.html new file mode 100644 index 00000000..f401623c --- /dev/null +++ b/app/templates/splits/fragments/expense/form.html @@ -0,0 +1,87 @@ +{% extends 'extends/offcanvas.html' %} +{% load i18n %} +{% load crispy_forms_filters %} + +{% block title %} + {% if expense %}{% translate 'Edit expense' %}{% else %}{% translate 'Add expense' %}{% endif %} +{% endblock %} + +{% block body %} +
    + {% if form.non_field_errors %} +
    {{ form.non_field_errors }}
    + {% endif %} + + {{ form.description|as_crispy_field }} +
    + {{ form.amount|as_crispy_field }} + {{ form.date|as_crispy_field }} + {{ form.paid_by|as_crispy_field }} + {{ form.split_type|as_crispy_field }} +
    + +
    + {% translate 'Split between' %} +
    + {% for row in participant_rows %} +
    + + +
    + {% endfor %} +
    +

    +
    + + {{ form.notes|as_crispy_field }} + {{ form.attachments|as_crispy_field }} + {% include 'splits/fragments/attachments_existing.html' with item=expense %} + + +
    + + +{% endblock %} diff --git a/app/templates/splits/fragments/participants/manage.html b/app/templates/splits/fragments/participants/manage.html new file mode 100644 index 00000000..a854da77 --- /dev/null +++ b/app/templates/splits/fragments/participants/manage.html @@ -0,0 +1,141 @@ +{% extends 'extends/offcanvas.html' %} +{% load i18n %} + +{% block title %}{% translate 'People' %}{% endblock %} + +{% block body %} +
    + {% translate 'Share link' %} + {% if event.allow_external_access %} +
    + + {# navigator.clipboard needs HTTPS; self-hosted instances often run on plain HTTP #} + +
    +

    + {% translate 'People without an account open this link, pick their name and set a password the first time.' %} +

    +
    + +
    + {% else %} +

    + {% translate 'Link sharing is off. Turn on "Allow external access" in the event settings to share it.' %} +

    + {% endif %} +
    + +
    + {% translate 'Add person without an account' %} +
    + + +
    + {% if external_form.name.errors %}

    {{ external_form.name.errors.0 }}

    {% endif %} +
    + +{% if wygiwyh_form.fields.user.queryset.exists %} +
    + {% translate 'Add user' %} +
    +
    {{ wygiwyh_form.user }}
    + +
    + {% if wygiwyh_form.user.errors %}

    {{ wygiwyh_form.user.errors.0 }}

    {% endif %} +
    +{% endif %} + +
    + {% translate 'Participants' %} +
      + {% for p in participants %} +
    • +
      +
      {{ p.display_name }}
      +
      + {% if p.is_creator %}{% translate 'Organizer' %}{% endif %} + {% if p.is_external %} + {% if p.is_claimed %} + {% translate 'Password set' %} + {% else %} + {% translate 'Never signed in' %} + {% endif %} + {% endif %} + {% if not p.is_active %}{% translate 'Inactive' %}{% endif %} +
      +
      +
      + {% if p.is_external and p.is_claimed %} + + {% endif %} + {% if not p.is_creator %} + {% if p.is_active %} + + {% else %} + + {% endif %} + {% if p.deletable %} + + {% endif %} + {% endif %} +
      +
    • + {% endfor %} +
    +

    + {% translate "People with expenses or payments can't be removed, only deactivated." %} +

    +
    +{% endblock %} diff --git a/app/templates/splits/fragments/payment/form.html b/app/templates/splits/fragments/payment/form.html new file mode 100644 index 00000000..3e75fd3c --- /dev/null +++ b/app/templates/splits/fragments/payment/form.html @@ -0,0 +1,32 @@ +{% extends 'extends/offcanvas.html' %} +{% load i18n %} +{% load crispy_forms_filters %} + +{% block title %} + {% if payment %}{% translate 'Edit payment' %}{% else %}{% translate 'Record payment' %}{% endif %} +{% endblock %} + +{% block body %} +
    + {% if form.non_field_errors %} +
    {{ form.non_field_errors }}
    + {% endif %} + +
    + {{ form.from_participant|as_crispy_field }} + {{ form.to_participant|as_crispy_field }} + {{ form.amount|as_crispy_field }} + {{ form.date|as_crispy_field }} +
    + {{ form.notes|as_crispy_field }} + {{ form.attachments|as_crispy_field }} + {% include 'splits/fragments/attachments_existing.html' with item=payment %} + + +
    +{% endblock %} diff --git a/app/templates/splits/fragments/sync/form.html b/app/templates/splits/fragments/sync/form.html new file mode 100644 index 00000000..95da0279 --- /dev/null +++ b/app/templates/splits/fragments/sync/form.html @@ -0,0 +1,66 @@ +{% extends 'extends/offcanvas.html' %} +{% load i18n %} +{% load crispy_forms_filters %} + +{% block title %}{{ title }}{% endblock %} + +{% block body %} +
    + {% if form.non_field_errors %} +
    {{ form.non_field_errors }}
    + {% endif %} + +
    + + +
    + +
    +

    + {% if tx_type == 'IN' %} + {% translate 'Creates an income transaction in one of your accounts.' %} + {% else %} + {% translate 'Creates an expense transaction in one of your accounts.' %} + {% endif %} + {% blocktranslate with code=event.currency.code %}Amounts are in {{ code }}.{% endblocktranslate %} +

    + {{ form.account|as_crispy_field }} +
    + {{ form.amount|as_crispy_field }} + {{ form.date|as_crispy_field }} +
    + {{ form.description|as_crispy_field }} + {{ form.is_paid|as_crispy_field }} + {{ form.category|as_crispy_field }} + {{ form.tags|as_crispy_field }} + {{ form.entities|as_crispy_field }} + {{ form.notes|as_crispy_field }} +
    + + + + +
    + + +{% endblock %} diff --git a/app/templates/splits/fragments/tx_links.html b/app/templates/splits/fragments/tx_links.html new file mode 100644 index 00000000..38dccf70 --- /dev/null +++ b/app/templates/splits/fragments/tx_links.html @@ -0,0 +1,16 @@ +{% load i18n %} +{% for link in links %} + + {{ link.transaction.account.name }} + + +{% endfor %} diff --git a/app/templates/splits/pages/event_detail.html b/app/templates/splits/pages/event_detail.html new file mode 100644 index 00000000..9a17252b --- /dev/null +++ b/app/templates/splits/pages/event_detail.html @@ -0,0 +1,9 @@ +{% extends "layouts/base.html" %} +{% load i18n %} + +{% block title %}{{ event.name }} :: {% translate 'Split Expenses' %}{% endblock %} + +{% block content %} +
    +{% include 'splits/fragments/event/export_script.html' %} +{% endblock %} diff --git a/app/templates/splits/pages/event_index.html b/app/templates/splits/pages/event_index.html new file mode 100644 index 00000000..2cd42eff --- /dev/null +++ b/app/templates/splits/pages/event_index.html @@ -0,0 +1,8 @@ +{% extends "layouts/base.html" %} +{% load i18n %} + +{% block title %}{% translate 'Split Expenses' %}{% endblock %} + +{% block content %} +
    +{% endblock %} diff --git a/app/templates/splits/pages/event_report.html b/app/templates/splits/pages/event_report.html new file mode 100644 index 00000000..ac73ab8e --- /dev/null +++ b/app/templates/splits/pages/event_report.html @@ -0,0 +1,149 @@ +{% load i18n %} +{% load title %} +{% with c=event.currency %} + + + + + + {% filter site_title %}{{ event.name }} :: {% translate 'Report' %}{% endfilter %} + {% include 'includes/head/favicons.html' %} + {% include 'includes/styles.html' %} + + + +
    +
    + +
    + +
    +

    {{ event.name }}

    + {% if event.description %}

    {{ event.description }}

    {% endif %} +

    + {% blocktranslate count counter=active_participants_count %}{{ counter }} person{% plural %}{{ counter }} people{% endblocktranslate %} + · {% translate 'Group total' %} + · {% now "SHORT_DATE_FORMAT" %} +

    +
    + +
    +

    {% translate 'Settle up' %}

    + {% if transfers %} + + + {% for item in transfers %}{% with t=item.transfer %} + + + + + {% endwith %}{% endfor %} + +
    {{ t.from_participant.name }} {{ t.to_participant.name }}
    + {% else %} +

    {% translate 'Everyone is settled up.' %}

    + {% endif %} +
    + +
    +

    {% translate 'Balances' %}

    + + + + + + + + + + + + + {% for row in balance_rows %}{% with b=row.balance %} + + + + + + + + + {% endwith %}{% endfor %} + +
    {% translate 'Person' %}{% translate 'Paid' %}{% translate 'Share' %}{% translate 'Sent' %}{% translate 'Received' %}{% translate 'Balance' %}
    {{ b.participant.name }}{% if not b.participant.is_active %} ({% translate 'inactive' %}){% endif %}
    +
    + +
    +

    {% translate 'Expenses' %}

    + + + + + + + + + + {% for item in activity %}{% if not item.is_payment %} + + + + + + {% endif %}{% endfor %} + {% if not expense_count %}{% endif %} + +
    {% translate 'Date' %}{% translate 'Expense' %}{% translate 'Amount' %}
    {{ item.date|date:"SHORT_DATE_FORMAT" }} +
    {{ item.description }}
    +
    + {% blocktranslate with name=item.paid_by.name %}Paid by {{ name }}{% endblocktranslate %} + {% if item.split_type != 'EQUAL' %}· {{ item.get_split_type_display }}{% endif %} +
    +
    + {% for s in item.shares.all %}{{ s.participant.name }} {% if not forloop.last %} · {% endif %}{% endfor %} +
    + {% if item.notes %}
    {{ item.notes }}
    {% endif %} +
    {% translate 'No expenses.' %}
    +
    + +
    +

    {% translate 'Payments' %}

    + + + + + + + + + + {% for item in activity %}{% if item.is_payment %} + + + + + + {% endif %}{% endfor %} + {% if not payment_count %}{% endif %} + +
    {% translate 'Date' %}{% translate 'Payment' %}{% translate 'Amount' %}
    {{ item.date|date:"SHORT_DATE_FORMAT" }} + {{ item.from_participant.name }} {{ item.to_participant.name }} + {% if item.notes %}
    {{ item.notes }}
    {% endif %} +
    {% translate 'No payments.' %}
    +
    +
    + + {% include 'includes/scripts.html' %} + + + +{% endwith %} diff --git a/app/templates/splits/pages/external_auth.html b/app/templates/splits/pages/external_auth.html new file mode 100644 index 00000000..a86c58aa --- /dev/null +++ b/app/templates/splits/pages/external_auth.html @@ -0,0 +1,66 @@ +{% extends "layouts/base_auth.html" %} +{% load i18n %} +{% load crispy_forms_filters %} + +{% block title %}{{ event.name }}{% endblock %} + +{% block content %} +
    +
    +
    +
    +

    {{ event.name }}

    + {% if event.description %} +

    {{ event.description }}

    + {% endif %} + + {% if not external_participants %} +

    + {% translate 'Nobody without an account has been added yet. Ask the organizer to add your name.' %} +

    + {% else %} +
    + {% csrf_token %} + {% if form.non_field_errors %}
    {{ form.non_field_errors }}
    {% endif %} + {{ form.participant|as_crispy_field }} + + + {{ form.password|as_crispy_field }} + + +
    + {{ claimed_ids|json_script:"split-claimed-ids" }} + + {% endif %} +
    +
    +
    +
    +{% endblock %} diff --git a/app/templates/splits/pages/external_base.html b/app/templates/splits/pages/external_base.html new file mode 100644 index 00000000..2e857eaa --- /dev/null +++ b/app/templates/splits/pages/external_base.html @@ -0,0 +1,64 @@ +{% load pwa %} +{% load i18n %} +{% load title %} + + + + + + + {% filter site_title %} + {% block title %}{% translate 'Split Expenses' %}{% endblock title %} + {% endfilter %} + + {% include 'includes/head/favicons.html' %} + {% progressive_web_app_meta %} + {% block extra_styles %}{% endblock %} + {% include 'includes/scripts.html' %} + {% block extra_js_head %}{% endblock %} + + +
    + {% if actor %} + + {% endif %} + +
    +
    + {% block content %}{% endblock content %} +
    + {% include "includes/offcanvas.html" %} + {% if actor %} +
    +
    +
    +
    + {% endif %} +
    +
    + {% block extra_js_body %}{% endblock extra_js_body %} + + diff --git a/app/templates/splits/pages/external_disabled.html b/app/templates/splits/pages/external_disabled.html new file mode 100644 index 00000000..4b62170c --- /dev/null +++ b/app/templates/splits/pages/external_disabled.html @@ -0,0 +1,17 @@ +{% extends "layouts/base_auth.html" %} +{% load i18n %} + +{% block title %}{{ event.name }}{% endblock %} + +{% block content %} +
    +
    +
    +

    {{ event.name }}

    +

    + {% translate 'The organizer turned off link access for this event.' %} +

    +
    +
    +
    +{% endblock %} diff --git a/app/templates/splits/pages/external_event_detail.html b/app/templates/splits/pages/external_event_detail.html new file mode 100644 index 00000000..d1d1c88e --- /dev/null +++ b/app/templates/splits/pages/external_event_detail.html @@ -0,0 +1,9 @@ +{% extends "splits/pages/external_base.html" %} +{% load i18n %} + +{% block title %}{{ event.name }} :: {% translate 'Split Expenses' %}{% endblock %} + +{% block content %} +
    +{% include 'splits/fragments/event/export_script.html' %} +{% endblock %} diff --git a/frontend/package-lock.json b/frontend/package-lock.json index 811d8e0b..db817295 100644 --- a/frontend/package-lock.json +++ b/frontend/package-lock.json @@ -30,6 +30,7 @@ "htmx.org": "^2.0.10", "hyperscript.org": "^0.9.91", "mathjs": "^15.2.0", + "modern-screenshot": "^4.7.0", "postcss": "^8.5.26", "pulltorefreshjs": "^0.1.22", "sass": "^1.100.0", @@ -1812,6 +1813,12 @@ "node": ">= 18" } }, + "node_modules/modern-screenshot": { + "version": "4.7.0", + "resolved": "https://registry.npmjs.org/modern-screenshot/-/modern-screenshot-4.7.0.tgz", + "integrity": "sha512-9YxN+ddPSMMlhylOv25VHzXrl9u67QRxoh7+SEewGtgUw7t6hHTrjptSDJUSne9oG4Xk/h2cwG15nIt4Hc9ujg==", + "license": "MIT" + }, "node_modules/nanoid": { "version": "3.3.20", "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.20.tgz", diff --git a/frontend/package.json b/frontend/package.json index 27a81bae..2625c3f0 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -37,6 +37,7 @@ "htmx.org": "^2.0.10", "hyperscript.org": "^0.9.91", "mathjs": "^15.2.0", + "modern-screenshot": "^4.7.0", "postcss": "^8.5.26", "pulltorefreshjs": "^0.1.22", "sass": "^1.100.0", diff --git a/frontend/src/js/screenshot.js b/frontend/src/js/screenshot.js new file mode 100644 index 00000000..e00f626e --- /dev/null +++ b/frontend/src/js/screenshot.js @@ -0,0 +1,4 @@ +// html2canvas can't parse daisyUI 5's oklch() colors; this renders through the browser instead +import {domToBlob} from 'modern-screenshot'; + +window.domToBlob = domToBlob; diff --git a/frontend/src/main.js b/frontend/src/main.js index 25b6a83d..861f79d8 100644 --- a/frontend/src/main.js +++ b/frontend/src/main.js @@ -12,3 +12,4 @@ import './js/style.js'; import './js/_utils.js'; import './js/hide_amounts.js'; import './js/pulltorefresh.js'; +import './js/screenshot.js'; From fe2e366a7410c0ec9f0b4f2e27d83634d6f2dde8 Mon Sep 17 00:00:00 2001 From: Herculino Trotta Date: Fri, 20 Nov 2026 19:43:23 -0300 Subject: [PATCH 2/2] feat(api): expose split expenses in the REST API and MCP Add /api/splits/ endpoints for events, participants, expenses and payments, plus an event summary (balances and settle-up) and leave action. They share the web UI's access rules and share calculation. MCP reaches them through search_api/call_api, and its instructions now point to them. --- app/apps/api/mcp.py | 4 +- app/apps/api/serializers/__init__.py | 2 +- app/apps/api/serializers/splits.py | 378 +++++++++++++++++++++++++++ app/apps/api/tests/test_splits.py | 121 +++++++++ app/apps/api/urls.py | 4 + app/apps/api/views/__init__.py | 2 +- app/apps/api/views/splits.py | 264 +++++++++++++++++++ 7 files changed, 772 insertions(+), 3 deletions(-) create mode 100644 app/apps/api/serializers/splits.py create mode 100644 app/apps/api/tests/test_splits.py create mode 100644 app/apps/api/views/splits.py diff --git a/app/apps/api/mcp.py b/app/apps/api/mcp.py index 138f8421..f52fb634 100644 --- a/app/apps/api/mcp.py +++ b/app/apps/api/mcp.py @@ -37,7 +37,9 @@ INSTRUCTIONS = ( "transaction counts toward: YYYY-MM in these tools, YYYY-MM-DD for recurring " "transactions and installment plans in call_api. Use summarize_transactions for totals instead " "of adding up search results. Look up ids with list_accounts and " - "list_categories/list_tags/list_entities. For anything else, find the " + "list_categories/list_tags/list_entities. Shared expenses with other people " + "(trips, flats) live under /api/splits/: an event's balances and who should pay " + "whom are at /api/splits/events/{id}/summary/. For anything else, find the " "endpoint with search_api and run it with call_api." ) diff --git a/app/apps/api/serializers/__init__.py b/app/apps/api/serializers/__init__.py index 903fe3b6..2581d9f4 100644 --- a/app/apps/api/serializers/__init__.py +++ b/app/apps/api/serializers/__init__.py @@ -3,4 +3,4 @@ from .accounts import * from .currencies import * from .dca import * from .imports import * - +from .splits import * diff --git a/app/apps/api/serializers/splits.py b/app/apps/api/serializers/splits.py new file mode 100644 index 00000000..66a06788 --- /dev/null +++ b/app/apps/api/serializers/splits.py @@ -0,0 +1,378 @@ +from django.contrib.auth import get_user_model +from django.core.exceptions import ValidationError as DjangoValidationError +from django.db import transaction as db_transaction +from django.urls import reverse +from django.utils.translation import gettext_lazy as _ +from rest_framework import serializers + +from apps.splits.auth import accessible_events, user_display_name, wygiwyh_actor_for +from apps.splits.models import ( + SplitEvent, + SplitExpense, + SplitExpenseShare, + SplitParticipant, + SplitPayment, +) +from apps.splits.services.splitting import compute_expense_shares, replace_expense_shares +from apps.splits.services.wygiwyh_sync import settle_pending_links_for_payment + +User = get_user_model() + + +class AccessibleEventField(serializers.PrimaryKeyRelatedField): + def get_queryset(self): + return accessible_events(self.context["request"].user) + + +class EventParticipantField(serializers.PrimaryKeyRelatedField): + """A participant id; checked against the event in the serializer's validate().""" + + def get_queryset(self): + return SplitParticipant.objects.filter( + event__in=accessible_events(self.context["request"].user) + ) + + +def _check_participants(event, participants, allowed_inactive=()): + for p in participants: + if p.event_id != event.id: + raise serializers.ValidationError( + _("%(name)s is not part of this event.") % {"name": p.name} + ) + if not p.is_active and p.id not in allowed_inactive: + raise serializers.ValidationError( + _("%(name)s is inactive.") % {"name": p.name} + ) + + +class SplitParticipantSerializer(serializers.ModelSerializer): + event = AccessibleEventField() + user = serializers.PrimaryKeyRelatedField( + queryset=User.objects.filter(is_active=True), + required=False, + allow_null=True, + help_text="A WYGIWYH user to add. Leave empty to add a person without an account (give `name`).", + ) + name = serializers.CharField( + max_length=150, + required=False, + help_text="Required for people without an account; defaults to the user's name.", + ) + is_claimed = serializers.BooleanField( + read_only=True, + help_text="For people without an account: whether they set a password through the share link.", + ) + is_creator = serializers.BooleanField(read_only=True) + + class Meta: + model = SplitParticipant + fields = [ + "id", + "event", + "name", + "user", + "is_external", + "is_active", + "is_claimed", + "is_creator", + "created_at", + ] + read_only_fields = ["is_external", "created_at"] + # validate() checks the unique user/name rules with clearer messages, and + # DRF's auto validators would make `name` required when adding a user + validators = [] + + def validate(self, attrs): + if self.instance: + # Who a participant is can't change; only name and is_active + for field in ("event", "user"): + if field in attrs and attrs[field] != getattr(self.instance, field): + raise serializers.ValidationError({field: _("Can't be changed.")}) + if attrs.get("is_active") is False and self.instance.is_creator: + raise serializers.ValidationError( + {"is_active": _("The event creator cannot be deactivated.")} + ) + name = attrs.get("name") + event = self.instance.event + else: + event = attrs["event"] + user = attrs.get("user") + if user: + if event.participants.filter(user=user).exists(): + raise serializers.ValidationError({"user": _("Already in this event.")}) + attrs.setdefault("name", user_display_name(user)) + attrs["is_external"] = False + elif not attrs.get("name", "").strip(): + raise serializers.ValidationError({"name": _("This field is required.")}) + else: + attrs["is_external"] = True + name = attrs["name"] = attrs["name"].strip() + + if name: + clash = event.participants.filter(name__iexact=name) + if self.instance: + clash = clash.exclude(pk=self.instance.pk) + if clash.exists(): + raise serializers.ValidationError( + {"name": _("A participant named '%(name)s' already exists in this event.") % {"name": name}} + ) + return attrs + + +class SplitEventSerializer(serializers.ModelSerializer): + participants = SplitParticipantSerializer(many=True, read_only=True) + is_organizer = serializers.SerializerMethodField() + share_url = serializers.SerializerMethodField( + help_text="Link for people without an account. Only shown to the organizer, and only while external access is on." + ) + + class Meta: + model = SplitEvent + fields = [ + "id", + "name", + "description", + "currency", + "allow_external_access", + "is_archived", + "is_organizer", + "share_url", + "participants", + "created_at", + "updated_at", + ] + read_only_fields = ["created_at", "updated_at"] + + def get_is_organizer(self, obj) -> bool: + return obj.creator_id == self.context["request"].user.id + + def get_share_url(self, obj) -> str | None: + if not (self.get_is_organizer(obj) and obj.allow_external_access): + return None + return self.context["request"].build_absolute_uri( + reverse("split_external_auth", kwargs={"share_token": obj.share_token}) + ) + + def validate_currency(self, value): + event = self.instance + if ( + event + and value != event.currency + and (event.expenses.exists() or event.payments.exists()) + ): + # Stored amounts are not converted + raise serializers.ValidationError( + _("The currency can't be changed after expenses or payments are added.") + ) + return value + + @db_transaction.atomic + def create(self, validated_data): + user = self.context["request"].user + event = SplitEvent.objects.create(creator=user, **validated_data) + SplitParticipant.objects.create( + event=event, user=user, name=user_display_name(user), is_external=False + ) + return event + + +class SplitShareInputSerializer(serializers.Serializer): + participant = serializers.IntegerField() + value = serializers.DecimalField( + max_digits=20, + decimal_places=6, + required=False, + help_text="Ignored for EQUAL. The exact amount for EXACT, the percentage (0-100) for PERCENTAGE, the weight for SHARES.", + ) + + +class SplitExpenseShareSerializer(serializers.ModelSerializer): + class Meta: + model = SplitExpenseShare + fields = ["participant", "amount", "percentage", "shares"] + + +class SplitExpenseSerializer(serializers.ModelSerializer): + event = AccessibleEventField() + paid_by = EventParticipantField() + shares = SplitExpenseShareSerializer(many=True, read_only=True) + split_between = SplitShareInputSerializer( + many=True, + write_only=True, + required=False, + help_text=( + "Who shares the cost. On create, omit it to split equally between every active participant. " + "On update, omit it to keep the current people and values." + ), + ) + + class Meta: + model = SplitExpense + fields = [ + "id", + "event", + "description", + "amount", + "date", + "paid_by", + "split_type", + "split_between", + "shares", + "notes", + "created_by_participant", + "created_at", + "updated_at", + ] + read_only_fields = ["created_by_participant", "created_at", "updated_at"] + + def validate(self, attrs): + instance = self.instance + event = attrs.get("event") or instance.event + if instance and event != instance.event: + raise serializers.ValidationError({"event": _("Can't be changed.")}) + + # People already on the expense may have been deactivated since + existing_ids = ( + set(instance.shares.values_list("participant_id", flat=True)) | {instance.paid_by_id} + if instance + else set() + ) + paid_by = attrs.get("paid_by") or instance.paid_by + _check_participants(event, [paid_by], existing_ids) + + split_type = attrs.get("split_type") or ( + instance.split_type if instance else SplitExpense.SplitType.EQUAL + ) + split_between = attrs.pop("split_between", None) + if split_between is None: + if not instance: + if split_type != SplitExpense.SplitType.EQUAL: + raise serializers.ValidationError( + {"split_between": _("Required unless split_type is EQUAL.")} + ) + split_between = [ + {"participant": p.id} for p in event.participants.filter(is_active=True) + ] + elif split_type != instance.split_type and split_type != SplitExpense.SplitType.EQUAL: + raise serializers.ValidationError( + {"split_between": _("Required when changing split_type.")} + ) + else: + field = { + SplitExpense.SplitType.EXACT: "amount", + SplitExpense.SplitType.PERCENTAGE: "percentage", + SplitExpense.SplitType.SHARES: "shares", + }.get(split_type) + split_between = [ + {"participant": s.participant_id, "value": getattr(s, field) if field else None} + for s in instance.shares.all() + ] + + by_id = {p.id: p for p in event.participants.all()} + participants, values = [], {} + for row in split_between: + p = by_id.get(row["participant"]) + if p is None: + raise serializers.ValidationError( + {"split_between": _("Participant %(id)s is not part of this event.") % {"id": row["participant"]}} + ) + participants.append(p) + if row.get("value") is not None: + values[p.id] = row["value"] + try: + _check_participants(event, participants, existing_ids) + self._computed_shares = compute_expense_shares( + total_amount=attrs.get("amount") or instance.amount, + split_type=split_type, + participants=participants, + decimal_places=event.currency.decimal_places, + values_by_participant_id=values, + ) + except DjangoValidationError as e: + raise serializers.ValidationError({"split_between": e.messages}) + return attrs + + @db_transaction.atomic + def save(self, **kwargs): + expense = super().save(**kwargs) + replace_expense_shares(expense, self._computed_shares) + return expense + + +class SplitPaymentSerializer(serializers.ModelSerializer): + event = AccessibleEventField() + from_participant = EventParticipantField() + to_participant = EventParticipantField() + + class Meta: + model = SplitPayment + fields = [ + "id", + "event", + "from_participant", + "to_participant", + "amount", + "date", + "notes", + "created_by_participant", + "created_at", + "updated_at", + ] + read_only_fields = ["created_by_participant", "created_at", "updated_at"] + + def validate(self, attrs): + instance = self.instance + event = attrs.get("event") or instance.event + if instance and event != instance.event: + raise serializers.ValidationError({"event": _("Can't be changed.")}) + from_p = attrs.get("from_participant") or instance.from_participant + to_p = attrs.get("to_participant") or instance.to_participant + existing = {instance.from_participant_id, instance.to_participant_id} if instance else set() + _check_participants(event, [from_p, to_p], existing) + if from_p == to_p: + raise serializers.ValidationError( + {"to_participant": _("Sender and recipient must be different participants.")} + ) + actor = wygiwyh_actor_for(event, self.context["request"].user) + if not actor.can_record_payment(from_p.id, to_p.id): + raise serializers.ValidationError( + _("You can only record payments you sent or received.") + ) + return attrs + + @db_transaction.atomic + def create(self, validated_data): + payment = super().create(validated_data) + # Marks the payer's and receiver's planned transactions as paid, as the web UI does + settle_pending_links_for_payment(payment) + return payment + + +class SplitBalanceSerializer(serializers.Serializer): + participant = serializers.IntegerField() + name = serializers.CharField() + is_active = serializers.BooleanField() + paid = serializers.DecimalField(max_digits=20, decimal_places=6, help_text="Expenses they paid for.") + share = serializers.DecimalField(max_digits=20, decimal_places=6, help_text="Their part of all expenses.") + sent = serializers.DecimalField(max_digits=20, decimal_places=6, help_text="Payments they made.") + received = serializers.DecimalField(max_digits=20, decimal_places=6, help_text="Payments they got.") + balance = serializers.DecimalField( + max_digits=20, decimal_places=6, help_text="Above 0: others owe them. Below 0: they owe." + ) + + +class SplitTransferSerializer(serializers.Serializer): + from_participant = serializers.IntegerField() + from_name = serializers.CharField() + to_participant = serializers.IntegerField() + to_name = serializers.CharField() + amount = serializers.DecimalField(max_digits=20, decimal_places=6) + + +class SplitSummarySerializer(serializers.Serializer): + currency = serializers.CharField() + total_spent = serializers.DecimalField(max_digits=20, decimal_places=6) + balances = SplitBalanceSerializer(many=True) + settle_up = SplitTransferSerializer( + many=True, help_text="The fewest payments that settle everyone up." + ) diff --git a/app/apps/api/tests/test_splits.py b/app/apps/api/tests/test_splits.py new file mode 100644 index 00000000..3ccdc47c --- /dev/null +++ b/app/apps/api/tests/test_splits.py @@ -0,0 +1,121 @@ +import json +from decimal import Decimal + +from django.contrib.auth import get_user_model +from django.test import override_settings +from rest_framework.test import APITestCase + +from apps.currencies.models import Currency +from apps.splits.models import SplitEvent, SplitExpense, SplitParticipant, SplitPayment +from apps.users.models import APIToken + +User = get_user_model() + + +class SplitsAPITests(APITestCase): + def setUp(self): + self.brl = Currency.objects.create(code="BRL", name="Real", decimal_places=2) + self.alice = User.objects.create_user(email="alice@example.com", password="x", first_name="Alice") + self.bob = User.objects.create_user(email="bob@example.com", password="x", first_name="Bob") + self.stranger = User.objects.create_user(email="eve@example.com", password="x") + + self.client.force_authenticate(self.alice) + event = self.client.post( + "/api/splits/events/", {"name": "Trip", "currency": self.brl.id}, format="json" + ).json() + self.event = SplitEvent.objects.get(id=event["id"]) + self.p_alice = self.event.participants.get(user=self.alice) + self.p_bob = self._post( + "/api/splits/participants/", {"event": self.event.id, "user": self.bob.id} + ).json()["id"] + self.p_ana = self._post( + "/api/splits/participants/", {"event": self.event.id, "name": "Ana"} + ).json()["id"] + + def _post(self, url, data, user=None): + if user: + self.client.force_authenticate(user) + return self.client.post(url, data, format="json") + + def test_event_creation_adds_organizer_and_hides_events_from_strangers(self): + self.assertTrue(self.p_alice.is_creator) + self.assertEqual(self.event.participants.count(), 3) + self.client.force_authenticate(self.stranger) + self.assertEqual(self.client.get("/api/splits/events/").json()["count"], 0) + self.assertEqual(self.client.get(f"/api/splits/events/{self.event.id}/summary/").status_code, 404) + + def test_only_organizer_edits_event_and_people(self): + self.client.force_authenticate(self.bob) + self.assertEqual( + self.client.patch(f"/api/splits/events/{self.event.id}/", {"name": "X"}, format="json").status_code, 403 + ) + self.assertEqual( + self._post("/api/splits/participants/", {"event": self.event.id, "name": "Zed"}).status_code, 403 + ) + + def test_expense_shares_and_summary(self): + # Equal split by default between all three + resp = self._post( + "/api/splits/expenses/", + {"event": self.event.id, "description": "Dinner", "amount": "100", "date": "2026-11-20", "paid_by": self.p_alice.id}, + user=self.bob, # any member can add + ) + self.assertEqual(resp.status_code, 201, resp.content) + self.assertEqual(sorted(Decimal(s["amount"]) for s in resp.json()["shares"]), [Decimal("33.33"), Decimal("33.33"), Decimal("33.34")]) + + # Exact amounts must add up + bad = self._post( + "/api/splits/expenses/", + { + "event": self.event.id, "description": "Taxi", "amount": "30", "date": "2026-11-20", + "paid_by": self.p_bob, "split_type": "EXACT", + "split_between": [{"participant": self.p_bob, "value": "10"}, {"participant": self.p_ana, "value": "10"}], + }, + ) + self.assertEqual(bad.status_code, 400) + self.assertIn("split_between", bad.json()) + + summary = self.client.get(f"/api/splits/events/{self.event.id}/summary/").json() + balances = {b["participant"]: Decimal(b["balance"]) for b in summary["balances"]} + self.assertEqual(balances[self.p_alice.id], Decimal("66.66")) + self.assertEqual(sum(Decimal(t["amount"]) for t in summary["settle_up"]), Decimal("66.66")) + + def test_payment_rules(self): + payment = {"event": self.event.id, "amount": "5", "date": "2026-11-20"} + # Bob can't record a payment between Ana and Alice + resp = self._post("/api/splits/payments/", {**payment, "from_participant": self.p_ana, "to_participant": self.p_alice.id}, user=self.bob) + self.assertEqual(resp.status_code, 400) + # ...but can record his own, and the organizer can record anyone's + resp = self._post("/api/splits/payments/", {**payment, "from_participant": self.p_bob, "to_participant": self.p_alice.id}) + self.assertEqual(resp.status_code, 201) + resp = self._post("/api/splits/payments/", {**payment, "from_participant": self.p_ana, "to_participant": self.p_bob}, user=self.alice) + self.assertEqual(resp.status_code, 201) + self.assertEqual(SplitPayment.objects.count(), 2) + + def test_leave_and_remove(self): + self._post("/api/splits/expenses/", {"event": self.event.id, "description": "x", "amount": "9", "date": "2026-11-20", "paid_by": self.p_ana}) + # Ana has history: can't be removed, only deactivated + self.assertEqual(self.client.delete(f"/api/splits/participants/{self.p_ana}/").status_code, 400) + # Bob leaves; deactivated because he shares in Ana's expense + self.assertEqual(self._post(f"/api/splits/events/{self.event.id}/leave/", {}, user=self.bob).status_code, 204) + self.assertFalse(SplitParticipant.objects.get(id=self.p_bob).is_active) + self.assertEqual(self.client.get("/api/splits/events/").json()["count"], 0) + # The organizer can't leave + self.assertEqual(self._post(f"/api/splits/events/{self.event.id}/leave/", {}, user=self.alice).status_code, 403) + + @override_settings(MCP_ENABLED=True, PUBLIC_BASE_URL="https://money.example") + def test_reachable_over_mcp(self): + _token, raw = APIToken.objects.create_token(user=self.alice, name="mcp") + self.client.force_authenticate(None) + + def tool(name, **arguments): + body = {"jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": {"name": name, "arguments": arguments}} + resp = self.client.post("/mcp", json.dumps(body), content_type="application/json", HTTP_AUTHORIZATION=f"Token {raw}") + result = resp.json()["result"] + return result["isError"], json.loads(result["content"][0]["text"]) + + _err, found = tool("search_api", query="splits summary") + self.assertIn("/api/splits/events/{id}/summary/", [op["path"] for op in found]) + is_error, summary = tool("call_api", method="GET", path=f"/api/splits/events/{self.event.id}/summary/") + self.assertFalse(is_error) + self.assertEqual(summary["currency"], "BRL") diff --git a/app/apps/api/urls.py b/app/apps/api/urls.py index 40d2b95e..442537fe 100644 --- a/app/apps/api/urls.py +++ b/app/apps/api/urls.py @@ -17,6 +17,10 @@ router.register(r"currencies", views.CurrencyViewSet) router.register(r"exchange-rates", views.ExchangeRateViewSet) router.register(r"dca/strategies", views.DCAStrategyViewSet) router.register(r"dca/entries", views.DCAEntryViewSet) +router.register(r"splits/events", views.SplitEventViewSet, basename="split-events") +router.register(r"splits/participants", views.SplitParticipantViewSet, basename="split-participants") +router.register(r"splits/expenses", views.SplitExpenseViewSet, basename="split-expenses") +router.register(r"splits/payments", views.SplitPaymentViewSet, basename="split-payments") router.register(r"import/profiles", views.ImportProfileViewSet, basename="import-profiles") router.register(r"import/runs", views.ImportRunViewSet, basename="import-runs") router.register(r"import/import", views.ImportViewSet, basename="import-import") diff --git a/app/apps/api/views/__init__.py b/app/apps/api/views/__init__.py index 903fe3b6..2581d9f4 100644 --- a/app/apps/api/views/__init__.py +++ b/app/apps/api/views/__init__.py @@ -3,4 +3,4 @@ from .accounts import * from .currencies import * from .dca import * from .imports import * - +from .splits import * diff --git a/app/apps/api/views/splits.py b/app/apps/api/views/splits.py new file mode 100644 index 00000000..f1706a66 --- /dev/null +++ b/app/apps/api/views/splits.py @@ -0,0 +1,264 @@ +from django.utils.translation import gettext_lazy as _ +from drf_spectacular.utils import extend_schema +from rest_framework import status, viewsets +from rest_framework.decorators import action +from rest_framework.exceptions import PermissionDenied, ValidationError +from rest_framework.response import Response + +from apps.api.serializers.splits import ( + SplitEventSerializer, + SplitExpenseSerializer, + SplitParticipantSerializer, + SplitPaymentSerializer, + SplitSummarySerializer, +) +from apps.splits.auth import accessible_events, wygiwyh_actor_for +from apps.splits.models import SplitEvent, SplitExpense, SplitParticipant, SplitPayment +from apps.splits.services.membership import leave_event +from apps.splits.services.settlement import get_event_settlement_summary + + +class SplitsQuerysetMixin: + """Scopes every queryset to events the user can see.""" + + def get_queryset(self): + # drf-spectacular builds the schema without a user + if getattr(self, "swagger_fake_view", False): + return self.queryset + return self.scoped_queryset(accessible_events(self.request.user)) + + +def _require_organizer(event, user): + if event.creator_id != user.id: + raise PermissionDenied(_("Only the event organizer can do this.")) + + +class SplitEventViewSet(SplitsQuerysetMixin, viewsets.ModelViewSet): + """Shared-expense events (trips, flats, dinners) you organize or take part in. + + Only the organizer can edit or delete an event. Creating one makes you its + organizer and first participant.""" + + serializer_class = SplitEventSerializer + filterset_fields = { + "name": ["exact", "icontains"], + "is_archived": ["exact"], + "currency": ["exact"], + } + ordering_fields = ["name", "created_at", "updated_at"] + + queryset = SplitEvent.objects.none() + + def scoped_queryset(self, events): + return ( + events + .select_related("currency") + .prefetch_related("participants__event") + .order_by("-created_at") + ) + + def perform_update(self, serializer): + _require_organizer(serializer.instance, self.request.user) + serializer.save() + + def perform_destroy(self, instance): + _require_organizer(instance, self.request.user) + instance.delete() + + @extend_schema( + summary="Balances and how to settle up", + description=( + "Each person's totals and net balance, and the fewest payments that settle " + "everyone up. Amounts are in the event's currency." + ), + responses=SplitSummarySerializer, + ) + @action(detail=True, methods=["get"]) + def summary(self, request, pk=None): + event = self.get_object() + summary = get_event_settlement_summary(event) + return Response( + SplitSummarySerializer( + { + "currency": event.currency.code, + "total_spent": summary["total_spent"], + "balances": [ + { + "participant": b.participant.id, + "name": b.participant.name, + "is_active": b.participant.is_active, + "paid": b.total_paid, + "share": b.total_owed, + "sent": b.payments_sent, + "received": b.payments_received, + "balance": b.net_balance, + } + for b in summary["balances"] + ], + "settle_up": [ + { + "from_participant": t.from_participant.id, + "from_name": t.from_participant.name, + "to_participant": t.to_participant.id, + "to_name": t.to_participant.name, + "amount": t.amount, + } + for t in summary["transfers"] + ], + } + ).data + ) + + @extend_schema( + summary="Leave an event", + description=( + "Removes you from an event someone else organizes. If you have expenses or " + "payments you're deactivated instead, so everyone else's balances stay right. " + "The organizer can't leave." + ), + request=None, + responses={204: None}, + ) + @action(detail=True, methods=["post"]) + def leave(self, request, pk=None): + event = self.get_object() + actor = wygiwyh_actor_for(event, request.user) + if actor.is_creator or not actor.participant: + raise PermissionDenied(_("The organizer can't leave their own event.")) + leave_event(actor) + return Response(status=status.HTTP_204_NO_CONTENT) + + +class SplitParticipantViewSet(SplitsQuerysetMixin, viewsets.ModelViewSet): + """People in an event: WYGIWYH users (`user` set) or people without an account. + + Only the organizer can add, rename, deactivate (`is_active: false`) or remove + people. Someone with expenses or payments can't be removed, only deactivated.""" + + serializer_class = SplitParticipantSerializer + filterset_fields = {"event": ["exact"], "is_active": ["exact"], "is_external": ["exact"]} + + queryset = SplitParticipant.objects.none() + + def scoped_queryset(self, events): + return SplitParticipant.objects.filter(event__in=events).select_related("event") + + def perform_create(self, serializer): + _require_organizer(serializer.validated_data["event"], self.request.user) + serializer.save() + + def perform_update(self, serializer): + _require_organizer(serializer.instance.event, self.request.user) + serializer.save() + + def perform_destroy(self, instance): + _require_organizer(instance.event, self.request.user) + if not instance.can_be_deleted(): + raise ValidationError( + _("%(name)s has expenses or payments and can't be removed. Deactivate them instead.") + % {"name": instance.name} + ) + instance.delete() + + +def _require_item_editor(event, user, *, created_by_id, primary_participant_id): + actor = wygiwyh_actor_for(event, user) + if not actor.can_edit_item( + created_by_id=created_by_id, primary_participant_id=primary_participant_id + ): + raise PermissionDenied( + _("Only the organizer, whoever added it, or whoever paid can change this.") + ) + return actor + + +class SplitExpenseViewSet(SplitsQuerysetMixin, viewsets.ModelViewSet): + """Expenses in an event and how each one is split. + + Shares are computed from `split_type` and `split_between` and always add up to + the amount. Anyone in the event can add expenses; the organizer, whoever added + it, or whoever paid can change or delete one.""" + + serializer_class = SplitExpenseSerializer + filterset_fields = { + "event": ["exact"], + "paid_by": ["exact"], + "split_type": ["exact"], + "date": ["exact", "gte", "lte", "gt", "lt"], + "description": ["exact", "icontains"], + } + ordering_fields = ["date", "amount", "created_at"] + + queryset = SplitExpense.objects.none() + + def scoped_queryset(self, events): + return ( + SplitExpense.objects.filter(event__in=events) + .select_related("event__currency") + .prefetch_related("shares") + ) + + def perform_create(self, serializer): + actor = wygiwyh_actor_for(serializer.validated_data["event"], self.request.user) + serializer.save(created_by_participant=actor.participant) + + def perform_update(self, serializer): + e = serializer.instance + _require_item_editor( + e.event, self.request.user, created_by_id=e.created_by_participant_id, primary_participant_id=e.paid_by_id + ) + serializer.save() + + def perform_destroy(self, instance): + _require_item_editor( + instance.event, + self.request.user, + created_by_id=instance.created_by_participant_id, + primary_participant_id=instance.paid_by_id, + ) + for attachment in instance.attachments.all(): + attachment.file.delete(save=False) + instance.delete() + + +class SplitPaymentViewSet(SplitsQuerysetMixin, viewsets.ModelViewSet): + """Money that changed hands between two people in an event. + + Only the two people involved or the organizer can record one. Recording a + payment marks matching planned transactions in their accounts as paid.""" + + serializer_class = SplitPaymentSerializer + filterset_fields = { + "event": ["exact"], + "from_participant": ["exact"], + "to_participant": ["exact"], + "date": ["exact", "gte", "lte", "gt", "lt"], + } + ordering_fields = ["date", "amount", "created_at"] + + queryset = SplitPayment.objects.none() + + def scoped_queryset(self, events): + return SplitPayment.objects.filter(event__in=events).select_related("event") + + def perform_create(self, serializer): + actor = wygiwyh_actor_for(serializer.validated_data["event"], self.request.user) + serializer.save(created_by_participant=actor.participant) + + def perform_update(self, serializer): + p = serializer.instance + _require_item_editor( + p.event, self.request.user, created_by_id=p.created_by_participant_id, primary_participant_id=p.from_participant_id + ) + serializer.save() + + def perform_destroy(self, instance): + _require_item_editor( + instance.event, + self.request.user, + created_by_id=instance.created_by_participant_id, + primary_participant_id=instance.from_participant_id, + ) + for attachment in instance.attachments.all(): + attachment.file.delete(save=False) + instance.delete()