mirror of
https://github.com/eitchtee/WYGIWYH.git
synced 2026-11-22 00:21:50 +01:00
Merge pull request #698 from eitchtee/expense-share-tracker
feat: split expenses for shared group costs
This commit is contained in:
54 files changed
+6384
-3
No files matched your search
@@ -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",
|
||||
|
||||
@@ -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")),
|
||||
|
||||
+3
-1
@@ -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."
|
||||
)
|
||||
|
||||
|
||||
@@ -3,4 +3,4 @@ from .accounts import *
|
||||
from .currencies import *
|
||||
from .dca import *
|
||||
from .imports import *
|
||||
|
||||
from .splits import *
|
||||
@@ -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."
|
||||
)
|
||||
@@ -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")
|
||||
@@ -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")
|
||||
|
||||
@@ -3,4 +3,4 @@ from .accounts import *
|
||||
from .currencies import *
|
||||
from .dca import *
|
||||
from .imports import *
|
||||
|
||||
from .splits import *
|
||||
@@ -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()
|
||||
Whitespace-only changes.
@@ -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",)
|
||||
@@ -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")
|
||||
@@ -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,
|
||||
)
|
||||
@@ -0,0 +1,525 @@
|
||||
from decimal import Decimal, InvalidOperation
|
||||
|
||||
from crispy_forms.bootstrap import FormActions
|
||||
from crispy_forms.helper import FormHelper
|
||||
from crispy_forms.layout import Column, Layout, Row
|
||||
from django import forms
|
||||
from django.contrib.auth import get_user_model
|
||||
from django.core.exceptions import ValidationError
|
||||
from django.db import models
|
||||
from django.utils import timezone
|
||||
from django.utils.translation import gettext_lazy as _
|
||||
|
||||
from apps.accounts.models import Account
|
||||
from apps.common.widgets.crispy.daisyui import Switch
|
||||
from apps.common.widgets.crispy.submit import NoClassSubmit
|
||||
from apps.common.widgets.datepicker import AirDatePickerInput
|
||||
from apps.common.widgets.decimal import ArbitraryDecimalDisplayNumberInput
|
||||
from apps.common.fields.forms.dynamic_select import (
|
||||
DynamicModelChoiceField,
|
||||
DynamicModelMultipleChoiceField,
|
||||
)
|
||||
from apps.common.widgets.tom_select import TomSelect, TransactionSelect
|
||||
from apps.currencies.models import Currency
|
||||
from apps.splits.models import (
|
||||
SplitAttachment,
|
||||
SplitEvent,
|
||||
SplitExpense,
|
||||
SplitParticipant,
|
||||
SplitPayment,
|
||||
SplitTransactionLink,
|
||||
)
|
||||
from apps.splits.services.splitting import compute_expense_shares
|
||||
from apps.transactions.forms import MultipleFileField
|
||||
from apps.transactions.models import (
|
||||
Transaction,
|
||||
TransactionCategory,
|
||||
TransactionEntity,
|
||||
TransactionTag,
|
||||
)
|
||||
|
||||
User = get_user_model()
|
||||
|
||||
|
||||
def _participant_label(p: SplitParticipant) -> str:
|
||||
return p.name if p.is_active else _("%(name)s (inactive)") % {"name": p.name}
|
||||
|
||||
|
||||
class SplitEventForm(forms.ModelForm):
|
||||
class Meta:
|
||||
model = SplitEvent
|
||||
fields = [
|
||||
"name",
|
||||
"currency",
|
||||
"description",
|
||||
"allow_external_access",
|
||||
"is_archived",
|
||||
]
|
||||
widgets = {
|
||||
"currency": TomSelect(clear_button=False),
|
||||
"description": forms.Textarea(attrs={"rows": 3}),
|
||||
}
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
self.fields["currency"].queryset = Currency.objects.filter(
|
||||
is_archived=False
|
||||
).order_by("name")
|
||||
if self.instance and self.instance.pk:
|
||||
# Allow keeping current currency even if archived
|
||||
self.fields["currency"].queryset = Currency.objects.filter(
|
||||
is_archived=False
|
||||
) | Currency.objects.filter(pk=self.instance.currency_id)
|
||||
# Stored amounts are not converted, so changing currency would corrupt them
|
||||
if self.instance.expenses.exists() or self.instance.payments.exists():
|
||||
self.fields["currency"].disabled = True
|
||||
self.fields["currency"].help_text = _(
|
||||
"The currency can't be changed after expenses or payments are added."
|
||||
)
|
||||
|
||||
self.helper = FormHelper()
|
||||
self.helper.form_tag = False
|
||||
fields_layout = [
|
||||
"name",
|
||||
"currency",
|
||||
"description",
|
||||
Switch("allow_external_access"),
|
||||
]
|
||||
if self.instance and self.instance.pk:
|
||||
fields_layout.append(Switch("is_archived"))
|
||||
fields_layout.append(
|
||||
FormActions(
|
||||
NoClassSubmit("submit", _("Update"), css_class="btn btn-primary")
|
||||
)
|
||||
)
|
||||
else:
|
||||
self.fields.pop("is_archived", None)
|
||||
fields_layout.append(
|
||||
FormActions(
|
||||
NoClassSubmit("submit", _("Add"), css_class="btn btn-primary")
|
||||
)
|
||||
)
|
||||
self.helper.layout = Layout(*fields_layout)
|
||||
|
||||
|
||||
class AddWygiwyhParticipantForm(forms.Form):
|
||||
user = forms.ModelChoiceField(
|
||||
queryset=User.objects.none(),
|
||||
label=_("WYGIWYH User"),
|
||||
widget=TomSelect(clear_button=False),
|
||||
)
|
||||
|
||||
def __init__(self, *args, event: SplitEvent, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
existing_user_ids = event.participants.filter(
|
||||
user__isnull=False
|
||||
).values_list("user_id", flat=True)
|
||||
self.fields["user"].queryset = (
|
||||
User.objects.filter(is_active=True)
|
||||
.exclude(id__in=existing_user_ids)
|
||||
.order_by("first_name", "last_name", "email")
|
||||
)
|
||||
self.fields["user"].label_from_instance = self._user_label
|
||||
|
||||
@staticmethod
|
||||
def _user_label(u):
|
||||
full = f"{u.first_name} {u.last_name}".strip()
|
||||
return f"{full} ({u.email})" if full else u.email
|
||||
|
||||
|
||||
class AddExternalParticipantForm(forms.Form):
|
||||
name = forms.CharField(
|
||||
max_length=150,
|
||||
label=_("Name"),
|
||||
widget=forms.TextInput(attrs={"placeholder": _("e.g. Alex")}),
|
||||
)
|
||||
|
||||
def __init__(self, *args, event: SplitEvent, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
self.event = event
|
||||
|
||||
def clean_name(self):
|
||||
name = self.cleaned_data["name"].strip()
|
||||
if not name:
|
||||
raise ValidationError(_("Name cannot be empty."))
|
||||
if self.event.participants.filter(name__iexact=name).exists():
|
||||
raise ValidationError(
|
||||
_("A participant named '%(name)s' already exists in this event.")
|
||||
% {"name": name}
|
||||
)
|
||||
return name
|
||||
|
||||
|
||||
class SplitExpenseForm(forms.ModelForm):
|
||||
attachments = MultipleFileField(
|
||||
required=False,
|
||||
label=_("Attachments"),
|
||||
help_text=_("Optional receipts or files."),
|
||||
)
|
||||
|
||||
class Meta:
|
||||
model = SplitExpense
|
||||
fields = ["description", "amount", "date", "paid_by", "split_type", "notes"]
|
||||
widgets = {
|
||||
"date": AirDatePickerInput(),
|
||||
"notes": forms.Textarea(attrs={"rows": 2}),
|
||||
}
|
||||
|
||||
def __init__(self, *args, event: SplitEvent, default_payer: SplitParticipant | None = None, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
self.event = event
|
||||
|
||||
# Include active participants, plus any inactive participant already referenced on this expense
|
||||
active_qs = event.participants.filter(is_active=True)
|
||||
if self.instance and self.instance.pk:
|
||||
referenced_ids = list(
|
||||
self.instance.shares.values_list("participant_id", flat=True)
|
||||
) + [self.instance.paid_by_id]
|
||||
self.available_participants = list(
|
||||
event.participants.filter(
|
||||
id__in=referenced_ids
|
||||
).union(active_qs).order_by("-is_active", "name", "id")
|
||||
)
|
||||
payer_qs = event.participants.filter(
|
||||
id__in=[p.id for p in self.available_participants]
|
||||
).order_by("-is_active", "name", "id")
|
||||
else:
|
||||
self.available_participants = list(active_qs.order_by("name", "id"))
|
||||
payer_qs = active_qs.order_by("name", "id")
|
||||
|
||||
self.fields["paid_by"].queryset = payer_qs
|
||||
self.fields["paid_by"].label_from_instance = _participant_label
|
||||
self.fields["paid_by"].empty_label = None
|
||||
self.fields["amount"].widget = ArbitraryDecimalDisplayNumberInput(
|
||||
decimal_places=event.currency.decimal_places,
|
||||
attrs={"inputmode": "decimal"},
|
||||
)
|
||||
self.fields["amount"].label = _("Amount (%(code)s)") % {"code": event.currency.code}
|
||||
if not self.instance.pk:
|
||||
self.fields["date"].initial = timezone.localdate()
|
||||
if default_payer and payer_qs.filter(pk=default_payer.pk).exists():
|
||||
self.fields["paid_by"].initial = default_payer
|
||||
|
||||
self.computed_shares = []
|
||||
|
||||
def clean(self):
|
||||
cleaned = super().clean()
|
||||
amount = cleaned.get("amount")
|
||||
split_type = cleaned.get("split_type")
|
||||
if amount is None or not split_type:
|
||||
return cleaned
|
||||
|
||||
# Parse selected participants and per-participant split values from POST data
|
||||
selected_ids = self.data.getlist("share_participants")
|
||||
selected_id_set = set()
|
||||
for raw_id in selected_ids:
|
||||
try:
|
||||
selected_id_set.add(int(raw_id))
|
||||
except (TypeError, ValueError):
|
||||
pass
|
||||
|
||||
participants_by_id = {p.id: p for p in self.available_participants}
|
||||
selected_participants = [
|
||||
participants_by_id[pid]
|
||||
for pid in participants_by_id
|
||||
if pid in selected_id_set
|
||||
]
|
||||
|
||||
values_by_id: dict[int, Decimal] = {}
|
||||
if split_type != SplitExpense.SplitType.EQUAL:
|
||||
for p in selected_participants:
|
||||
raw_val = (self.data.get(f"share_value_{p.id}") or "").strip()
|
||||
if raw_val == "":
|
||||
values_by_id[p.id] = Decimal("0")
|
||||
else:
|
||||
try:
|
||||
# <input type=number> always posts "12.5", never the locale format
|
||||
values_by_id[p.id] = Decimal(raw_val)
|
||||
except InvalidOperation:
|
||||
raise ValidationError(
|
||||
_("Invalid split value for %(name)s.") % {"name": p.name}
|
||||
)
|
||||
|
||||
self.computed_shares = compute_expense_shares(
|
||||
total_amount=amount,
|
||||
split_type=split_type,
|
||||
participants=selected_participants,
|
||||
decimal_places=self.event.currency.decimal_places,
|
||||
values_by_participant_id=values_by_id,
|
||||
)
|
||||
return cleaned
|
||||
|
||||
|
||||
class SplitPaymentForm(forms.ModelForm):
|
||||
attachments = MultipleFileField(
|
||||
required=False,
|
||||
label=_("Attachments"),
|
||||
help_text=_("Optional proof of payment."),
|
||||
)
|
||||
|
||||
class Meta:
|
||||
model = SplitPayment
|
||||
fields = ["from_participant", "to_participant", "amount", "date", "notes"]
|
||||
widgets = {
|
||||
"date": AirDatePickerInput(),
|
||||
"notes": forms.Textarea(attrs={"rows": 2}),
|
||||
}
|
||||
|
||||
def __init__(self, *args, event: SplitEvent, actor=None, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
self.event = event
|
||||
self.actor = actor
|
||||
qs = event.participants.filter(is_active=True).order_by("name", "id")
|
||||
if self.instance and self.instance.pk:
|
||||
qs = event.participants.filter(
|
||||
id__in=list(qs.values_list("id", flat=True))
|
||||
+ [self.instance.from_participant_id, self.instance.to_participant_id]
|
||||
).order_by("-is_active", "name", "id")
|
||||
for name in ("from_participant", "to_participant"):
|
||||
self.fields[name].queryset = qs
|
||||
self.fields[name].label_from_instance = _participant_label
|
||||
self.fields["amount"].widget = ArbitraryDecimalDisplayNumberInput(
|
||||
decimal_places=event.currency.decimal_places,
|
||||
attrs={"inputmode": "decimal"},
|
||||
)
|
||||
self.fields["amount"].label = _("Amount (%(code)s)") % {"code": event.currency.code}
|
||||
if not self.instance.pk:
|
||||
self.fields["date"].initial = timezone.localdate()
|
||||
|
||||
def clean(self):
|
||||
cleaned = super().clean()
|
||||
from_p = cleaned.get("from_participant")
|
||||
to_p = cleaned.get("to_participant")
|
||||
if from_p and to_p and from_p == to_p:
|
||||
self.add_error(
|
||||
"to_participant",
|
||||
_("Sender and recipient must be different participants."),
|
||||
)
|
||||
if (
|
||||
self.actor
|
||||
and from_p
|
||||
and to_p
|
||||
and not self.actor.can_record_payment(from_p.id, to_p.id)
|
||||
):
|
||||
raise ValidationError(
|
||||
_("You can only record payments you sent or received.")
|
||||
)
|
||||
return cleaned
|
||||
|
||||
|
||||
class SplitAttachmentUploadForm(forms.Form):
|
||||
attachments = MultipleFileField(
|
||||
required=True,
|
||||
label=_("Attachments"),
|
||||
)
|
||||
|
||||
def save(self, *, event: SplitEvent, uploaded_by: SplitParticipant | None, expense=None, payment=None):
|
||||
created = []
|
||||
for f in self.cleaned_data.get("attachments") or []:
|
||||
created.append(
|
||||
SplitAttachment.objects.create(
|
||||
event=event,
|
||||
expense=expense,
|
||||
payment=payment,
|
||||
file=f,
|
||||
original_name=f.name,
|
||||
content_type=getattr(f, "content_type", ""),
|
||||
size=f.size,
|
||||
uploaded_by=uploaded_by,
|
||||
)
|
||||
)
|
||||
return created
|
||||
|
||||
|
||||
class SplitTransactionSyncForm(forms.Form):
|
||||
class Mode(models.TextChoices):
|
||||
CREATE = "create", _("Create new WYGIWYH transaction")
|
||||
LINK = "link", _("Link existing WYGIWYH transaction")
|
||||
|
||||
mode = forms.ChoiceField(
|
||||
choices=Mode.choices,
|
||||
initial=Mode.CREATE,
|
||||
widget=forms.RadioSelect,
|
||||
label=_("Action"),
|
||||
)
|
||||
# Create mode fields
|
||||
account = forms.ModelChoiceField(
|
||||
queryset=Account.objects.none(),
|
||||
required=False,
|
||||
label=_("Account"),
|
||||
widget=TomSelect(clear_button=False, group_by="group"),
|
||||
)
|
||||
category = DynamicModelChoiceField(
|
||||
create_field="name",
|
||||
model=TransactionCategory,
|
||||
required=False,
|
||||
label=_("Category"),
|
||||
queryset=TransactionCategory.objects.none(),
|
||||
)
|
||||
tags = DynamicModelMultipleChoiceField(
|
||||
model=TransactionTag,
|
||||
to_field_name="name",
|
||||
create_field="name",
|
||||
required=False,
|
||||
label=_("Tags"),
|
||||
queryset=TransactionTag.objects.none(),
|
||||
)
|
||||
entities = DynamicModelMultipleChoiceField(
|
||||
model=TransactionEntity,
|
||||
to_field_name="name",
|
||||
create_field="name",
|
||||
required=False,
|
||||
label=_("Entities"),
|
||||
queryset=TransactionEntity.objects.none(),
|
||||
)
|
||||
amount = forms.DecimalField(
|
||||
max_digits=20,
|
||||
decimal_places=6,
|
||||
required=False,
|
||||
label=_("Amount"),
|
||||
)
|
||||
date = forms.DateField(
|
||||
required=False,
|
||||
label=_("Date"),
|
||||
widget=AirDatePickerInput(),
|
||||
)
|
||||
description = forms.CharField(
|
||||
max_length=500,
|
||||
required=False,
|
||||
label=_("Description"),
|
||||
)
|
||||
is_paid = forms.BooleanField(
|
||||
required=False,
|
||||
initial=True,
|
||||
label=_("Mark as paid"),
|
||||
)
|
||||
notes = forms.CharField(
|
||||
required=False,
|
||||
label=_("Notes"),
|
||||
widget=forms.Textarea(attrs={"rows": 2}),
|
||||
)
|
||||
|
||||
# Link mode field
|
||||
existing_transaction = DynamicModelChoiceField(
|
||||
model=Transaction,
|
||||
to_field_name="id",
|
||||
required=False,
|
||||
label=_("Transaction"),
|
||||
queryset=Transaction.objects.none(),
|
||||
widget=TransactionSelect(clear_button=True),
|
||||
help_text=_("Type to search for a transaction to link"),
|
||||
)
|
||||
|
||||
def __init__(self, *args, user, event: SplitEvent, tx_type: str, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
self.user = user
|
||||
self.event = event
|
||||
self.tx_type = tx_type
|
||||
|
||||
accounts = Account.objects.filter(is_archived=False).order_by("name")
|
||||
self.fields["account"].queryset = accounts
|
||||
# Amounts are in the event currency, so only preselect a same-currency account
|
||||
same_currency = accounts.filter(currency=event.currency)
|
||||
default_acc = getattr(getattr(user, "settings", None), "default_account", None)
|
||||
if default_acc and same_currency.filter(pk=default_acc.pk).exists():
|
||||
self.fields["account"].initial = default_acc
|
||||
else:
|
||||
self.fields["account"].initial = same_currency.first()
|
||||
|
||||
self.fields["category"].queryset = TransactionCategory.objects.filter(active=True)
|
||||
self.fields["tags"].queryset = TransactionTag.objects.filter(active=True)
|
||||
self.fields["entities"].queryset = TransactionEntity.objects.filter(active=True)
|
||||
self.fields["amount"].widget = ArbitraryDecimalDisplayNumberInput(
|
||||
decimal_places=event.currency.decimal_places,
|
||||
attrs={"inputmode": "decimal"},
|
||||
)
|
||||
|
||||
# Search only transactions of the matching type in the event currency
|
||||
picker = self.fields["existing_transaction"]
|
||||
picker.widget.load_income = tx_type == Transaction.Type.INCOME
|
||||
picker.widget.load_expense = tx_type == Transaction.Type.EXPENSE
|
||||
picker.widget.filters = {"currency": event.currency_id}
|
||||
selected = self.data.get("existing_transaction") if self.is_bound else None
|
||||
# Only the selected one: the picker loads the rest by search
|
||||
picker.queryset = Transaction.objects.filter(
|
||||
id=selected if str(selected or "").isdigit() else None
|
||||
)
|
||||
|
||||
def clean(self):
|
||||
cleaned = super().clean()
|
||||
mode = cleaned.get("mode")
|
||||
if mode == self.Mode.CREATE:
|
||||
if not cleaned.get("account"):
|
||||
self.add_error("account", _("Please select an account."))
|
||||
if not cleaned.get("amount") or cleaned["amount"] <= 0:
|
||||
self.add_error("amount", _("Amount must be greater than zero."))
|
||||
if not cleaned.get("date"):
|
||||
cleaned["date"] = timezone.localdate()
|
||||
elif mode == self.Mode.LINK:
|
||||
tx = cleaned.get("existing_transaction")
|
||||
if not tx:
|
||||
self.add_error(
|
||||
"existing_transaction",
|
||||
_("Please select a transaction to link."),
|
||||
)
|
||||
elif tx.type != self.tx_type or tx.account.currency_id != self.event.currency_id:
|
||||
self.add_error(
|
||||
"existing_transaction",
|
||||
_("Pick a %(type)s in %(currency)s.")
|
||||
% {
|
||||
"type": Transaction.Type(self.tx_type).label.lower(),
|
||||
"currency": self.event.currency.name,
|
||||
},
|
||||
)
|
||||
return cleaned
|
||||
|
||||
|
||||
class ExternalAuthForm(forms.Form):
|
||||
participant = forms.ModelChoiceField(
|
||||
queryset=SplitParticipant.objects.none(),
|
||||
label=_("Who are you?"),
|
||||
)
|
||||
username = forms.CharField(
|
||||
max_length=150,
|
||||
required=False,
|
||||
label=_("Username / nickname (optional)"),
|
||||
)
|
||||
password = forms.CharField(
|
||||
widget=forms.PasswordInput(attrs={"autocomplete": "current-password"}),
|
||||
min_length=4,
|
||||
label=_("Password"),
|
||||
)
|
||||
password_confirm = forms.CharField(
|
||||
widget=forms.PasswordInput(attrs={"autocomplete": "new-password"}),
|
||||
required=False,
|
||||
label=_("Confirm password"),
|
||||
)
|
||||
|
||||
def __init__(self, *args, event: SplitEvent, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
self.event = event
|
||||
self.fields["participant"].queryset = event.participants.filter(
|
||||
is_external=True,
|
||||
is_active=True,
|
||||
).order_by("name", "id")
|
||||
|
||||
def clean(self):
|
||||
cleaned = super().clean()
|
||||
participant: SplitParticipant | None = cleaned.get("participant")
|
||||
password = cleaned.get("password") or ""
|
||||
password_confirm = cleaned.get("password_confirm") or ""
|
||||
|
||||
if not participant:
|
||||
return cleaned
|
||||
|
||||
if participant.is_claimed:
|
||||
if not participant.check_external_password(password):
|
||||
self.add_error("password", _("Incorrect password."))
|
||||
else:
|
||||
if len(password) < 4:
|
||||
self.add_error(
|
||||
"password", _("Password must be at least 4 characters long.")
|
||||
)
|
||||
elif password != password_confirm:
|
||||
self.add_error("password_confirm", _("Passwords do not match."))
|
||||
return cleaned
|
||||
@@ -0,0 +1,188 @@
|
||||
# Generated by Django 5.2.17 on 2026-11-20 20:26
|
||||
|
||||
import apps.splits.models
|
||||
import apps.transactions.storage
|
||||
import django.core.validators
|
||||
import django.db.models.deletion
|
||||
import django.utils.timezone
|
||||
import uuid
|
||||
from decimal import Decimal
|
||||
from django.conf import settings
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
initial = True
|
||||
|
||||
dependencies = [
|
||||
('currencies', '0028_currency_show_exchanged_amounts'),
|
||||
('transactions', '0056_filterpreset_is_default'),
|
||||
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.CreateModel(
|
||||
name='SplitEvent',
|
||||
fields=[
|
||||
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||
('name', models.CharField(max_length=255, verbose_name='Name')),
|
||||
('description', models.TextField(blank=True, verbose_name='Description')),
|
||||
('share_token', models.UUIDField(db_index=True, default=uuid.uuid4, unique=True, verbose_name='Share token')),
|
||||
('allow_external_access', models.BooleanField(default=True, help_text='Allow external participants to access this event via the shared link.', verbose_name='Allow external access')),
|
||||
('is_archived', models.BooleanField(default=False, verbose_name='Archived')),
|
||||
('created_at', models.DateTimeField(auto_now_add=True)),
|
||||
('updated_at', models.DateTimeField(auto_now=True)),
|
||||
('creator', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='created_split_events', to=settings.AUTH_USER_MODEL, verbose_name='Creator')),
|
||||
('currency', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='split_events', to='currencies.currency', verbose_name='Currency')),
|
||||
],
|
||||
options={
|
||||
'verbose_name': 'Split Event',
|
||||
'verbose_name_plural': 'Split Events',
|
||||
'db_table': 'split_events',
|
||||
'ordering': ['-created_at', 'name'],
|
||||
},
|
||||
),
|
||||
migrations.CreateModel(
|
||||
name='SplitExpense',
|
||||
fields=[
|
||||
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||
('description', models.CharField(max_length=255, verbose_name='Description')),
|
||||
('amount', models.DecimalField(decimal_places=6, max_digits=20, validators=[django.core.validators.MinValueValidator(Decimal('0.000001'))], verbose_name='Amount')),
|
||||
('date', models.DateField(default=django.utils.timezone.localdate, verbose_name='Date')),
|
||||
('split_type', models.CharField(choices=[('EQUAL', 'Equal'), ('EXACT', 'Exact amounts'), ('PERCENTAGE', 'Percentages'), ('SHARES', 'Shares')], default='EQUAL', max_length=16, verbose_name='Split type')),
|
||||
('notes', models.TextField(blank=True, verbose_name='Notes')),
|
||||
('created_at', models.DateTimeField(auto_now_add=True)),
|
||||
('updated_at', models.DateTimeField(auto_now=True)),
|
||||
('event', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='expenses', to='splits.splitevent', verbose_name='Event')),
|
||||
],
|
||||
options={
|
||||
'verbose_name': 'Split Expense',
|
||||
'verbose_name_plural': 'Split Expenses',
|
||||
'db_table': 'split_expenses',
|
||||
'ordering': ['-date', '-created_at', '-id'],
|
||||
},
|
||||
),
|
||||
migrations.CreateModel(
|
||||
name='SplitParticipant',
|
||||
fields=[
|
||||
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||
('name', models.CharField(max_length=150, verbose_name='Name')),
|
||||
('is_external', models.BooleanField(default=False, verbose_name='External')),
|
||||
('is_active', models.BooleanField(default=True, verbose_name='Active')),
|
||||
('external_username', models.CharField(blank=True, max_length=150, verbose_name='External username')),
|
||||
('external_password_hash', models.CharField(blank=True, max_length=255, verbose_name='External password hash')),
|
||||
('external_claimed_at', models.DateTimeField(blank=True, null=True, verbose_name='Claimed at')),
|
||||
('created_at', models.DateTimeField(auto_now_add=True)),
|
||||
('event', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='participants', to='splits.splitevent', verbose_name='Event')),
|
||||
('user', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='split_participations', to=settings.AUTH_USER_MODEL, verbose_name='WYGIWYH User')),
|
||||
],
|
||||
options={
|
||||
'verbose_name': 'Split Participant',
|
||||
'verbose_name_plural': 'Split Participants',
|
||||
'db_table': 'split_participants',
|
||||
'ordering': ['-is_active', 'name', 'id'],
|
||||
},
|
||||
),
|
||||
migrations.CreateModel(
|
||||
name='SplitExpenseShare',
|
||||
fields=[
|
||||
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||
('amount', models.DecimalField(decimal_places=6, max_digits=20, validators=[django.core.validators.MinValueValidator(Decimal('0'))], verbose_name='Amount')),
|
||||
('percentage', models.DecimalField(blank=True, decimal_places=4, max_digits=7, null=True, verbose_name='Percentage')),
|
||||
('shares', models.DecimalField(blank=True, decimal_places=4, max_digits=12, null=True, verbose_name='Shares')),
|
||||
('expense', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='shares', to='splits.splitexpense', verbose_name='Expense')),
|
||||
('participant', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='expense_shares', to='splits.splitparticipant', verbose_name='Participant')),
|
||||
],
|
||||
options={
|
||||
'verbose_name': 'Split Expense Share',
|
||||
'verbose_name_plural': 'Split Expense Shares',
|
||||
'db_table': 'split_expense_shares',
|
||||
'ordering': ['participant__name', 'id'],
|
||||
},
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='splitexpense',
|
||||
name='created_by_participant',
|
||||
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='expenses_created', to='splits.splitparticipant', verbose_name='Created by'),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='splitexpense',
|
||||
name='paid_by',
|
||||
field=models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='expenses_paid', to='splits.splitparticipant', verbose_name='Paid by'),
|
||||
),
|
||||
migrations.CreateModel(
|
||||
name='SplitPayment',
|
||||
fields=[
|
||||
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||
('amount', models.DecimalField(decimal_places=6, max_digits=20, validators=[django.core.validators.MinValueValidator(Decimal('0.000001'))], verbose_name='Amount')),
|
||||
('date', models.DateField(default=django.utils.timezone.localdate, verbose_name='Date')),
|
||||
('notes', models.TextField(blank=True, verbose_name='Notes')),
|
||||
('created_at', models.DateTimeField(auto_now_add=True)),
|
||||
('updated_at', models.DateTimeField(auto_now=True)),
|
||||
('created_by_participant', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='payments_created', to='splits.splitparticipant', verbose_name='Created by')),
|
||||
('event', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='payments', to='splits.splitevent', verbose_name='Event')),
|
||||
('from_participant', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='payments_sent', to='splits.splitparticipant', verbose_name='From')),
|
||||
('to_participant', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='payments_received', to='splits.splitparticipant', verbose_name='To')),
|
||||
],
|
||||
options={
|
||||
'verbose_name': 'Split Payment',
|
||||
'verbose_name_plural': 'Split Payments',
|
||||
'db_table': 'split_payments',
|
||||
'ordering': ['-date', '-created_at', '-id'],
|
||||
},
|
||||
),
|
||||
migrations.CreateModel(
|
||||
name='SplitAttachment',
|
||||
fields=[
|
||||
('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)),
|
||||
('file', models.FileField(storage=apps.transactions.storage.PrivateMediaStorage(), upload_to=apps.splits.models.split_attachment_path, verbose_name='File')),
|
||||
('original_name', models.CharField(max_length=255, verbose_name='Original Name')),
|
||||
('content_type', models.CharField(blank=True, max_length=255, verbose_name='Content Type')),
|
||||
('size', models.PositiveBigIntegerField(default=0, verbose_name='Size')),
|
||||
('created_at', models.DateTimeField(auto_now_add=True)),
|
||||
('event', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='attachments', to='splits.splitevent', verbose_name='Event')),
|
||||
('expense', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='attachments', to='splits.splitexpense', verbose_name='Expense')),
|
||||
('uploaded_by', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='uploaded_attachments', to='splits.splitparticipant', verbose_name='Uploaded By')),
|
||||
('payment', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='attachments', to='splits.splitpayment', verbose_name='Payment')),
|
||||
],
|
||||
options={
|
||||
'verbose_name': 'Split Attachment',
|
||||
'verbose_name_plural': 'Split Attachments',
|
||||
'db_table': 'split_attachments',
|
||||
'ordering': ['-created_at', 'original_name'],
|
||||
},
|
||||
),
|
||||
migrations.CreateModel(
|
||||
name='SplitTransactionLink',
|
||||
fields=[
|
||||
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||
('kind', models.CharField(choices=[('EXPENSE', 'Expense paid'), ('PAYMENT_OUT', 'Payment sent'), ('PAYMENT_IN', 'Payment received'), ('SETTLEMENT_OUT', 'Planned payment to send'), ('SETTLEMENT_IN', 'Planned payment to receive')], max_length=24, verbose_name='Kind')),
|
||||
('created_at', models.DateTimeField(auto_now_add=True)),
|
||||
('counterparty', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='counterparty_transaction_links', to='splits.splitparticipant', verbose_name='Counterparty')),
|
||||
('event', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='transaction_links', to='splits.splitevent', verbose_name='Event')),
|
||||
('expense', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='transaction_links', to='splits.splitexpense', verbose_name='Expense')),
|
||||
('payment', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='transaction_links', to='splits.splitpayment', verbose_name='Payment')),
|
||||
('transaction', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='split_links', to='transactions.transaction', verbose_name='Transaction')),
|
||||
('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='split_transaction_links', to=settings.AUTH_USER_MODEL, verbose_name='User')),
|
||||
],
|
||||
options={
|
||||
'verbose_name': 'Split Transaction Link',
|
||||
'verbose_name_plural': 'Split Transaction Links',
|
||||
'db_table': 'split_transaction_links',
|
||||
'ordering': ['-created_at'],
|
||||
},
|
||||
),
|
||||
migrations.AddConstraint(
|
||||
model_name='splitparticipant',
|
||||
constraint=models.UniqueConstraint(condition=models.Q(('user__isnull', False)), fields=('event', 'user'), name='unique_split_participant_user_per_event'),
|
||||
),
|
||||
migrations.AddConstraint(
|
||||
model_name='splitparticipant',
|
||||
constraint=models.UniqueConstraint(fields=('event', 'name'), name='unique_split_participant_name_per_event'),
|
||||
),
|
||||
migrations.AddConstraint(
|
||||
model_name='splitexpenseshare',
|
||||
constraint=models.UniqueConstraint(fields=('expense', 'participant'), name='unique_share_per_expense_participant'),
|
||||
),
|
||||
]
|
||||
Whitespace-only changes.
@@ -0,0 +1,513 @@
|
||||
import uuid
|
||||
from decimal import Decimal
|
||||
from pathlib import Path
|
||||
|
||||
from apps.transactions.storage import PrivateMediaStorage
|
||||
from django.conf import settings
|
||||
from django.contrib.auth.hashers import check_password, make_password
|
||||
from django.core.exceptions import ValidationError
|
||||
from django.core.validators import MinValueValidator
|
||||
from django.db import models
|
||||
from django.db.models import Q
|
||||
from django.utils import timezone
|
||||
from django.utils.translation import gettext_lazy as _
|
||||
|
||||
|
||||
def split_attachment_path(instance, filename):
|
||||
extension = Path(filename).suffix
|
||||
return f"split_attachments/{instance.event_id}/{instance.id}{extension}"
|
||||
|
||||
|
||||
class SplitEvent(models.Model):
|
||||
name = models.CharField(max_length=255, verbose_name=_("Name"))
|
||||
description = models.TextField(blank=True, verbose_name=_("Description"))
|
||||
currency = models.ForeignKey(
|
||||
"currencies.Currency",
|
||||
on_delete=models.PROTECT,
|
||||
related_name="split_events",
|
||||
verbose_name=_("Currency"),
|
||||
)
|
||||
creator = models.ForeignKey(
|
||||
settings.AUTH_USER_MODEL,
|
||||
on_delete=models.CASCADE,
|
||||
related_name="created_split_events",
|
||||
verbose_name=_("Creator"),
|
||||
)
|
||||
share_token = models.UUIDField(
|
||||
default=uuid.uuid4,
|
||||
unique=True,
|
||||
db_index=True,
|
||||
verbose_name=_("Share token"),
|
||||
)
|
||||
allow_external_access = models.BooleanField(
|
||||
default=True,
|
||||
verbose_name=_("Allow external access"),
|
||||
help_text=_(
|
||||
"Allow external participants to access this event via the shared link."
|
||||
),
|
||||
)
|
||||
is_archived = models.BooleanField(default=False, verbose_name=_("Archived"))
|
||||
created_at = models.DateTimeField(auto_now_add=True)
|
||||
updated_at = models.DateTimeField(auto_now=True)
|
||||
|
||||
class Meta:
|
||||
verbose_name = _("Split Event")
|
||||
verbose_name_plural = _("Split Events")
|
||||
db_table = "split_events"
|
||||
ordering = ["-created_at", "name"]
|
||||
|
||||
def __str__(self):
|
||||
return self.name
|
||||
|
||||
def can_manage(self, user) -> bool:
|
||||
return bool(user and user.is_authenticated and self.creator_id == user.id)
|
||||
|
||||
def get_wygiwyh_participant(self, user):
|
||||
if not user or not user.is_authenticated:
|
||||
return None
|
||||
return self.participants.filter(user=user).first()
|
||||
|
||||
def is_accessible_by_user(self, user) -> bool:
|
||||
if not user or not user.is_authenticated:
|
||||
return False
|
||||
if self.creator_id == user.id:
|
||||
return True
|
||||
return self.participants.filter(user=user, is_active=True).exists()
|
||||
|
||||
def regenerate_share_token(self):
|
||||
self.share_token = uuid.uuid4()
|
||||
self.save(update_fields=["share_token", "updated_at"])
|
||||
return self.share_token
|
||||
|
||||
|
||||
class SplitParticipant(models.Model):
|
||||
event = models.ForeignKey(
|
||||
SplitEvent,
|
||||
on_delete=models.CASCADE,
|
||||
related_name="participants",
|
||||
verbose_name=_("Event"),
|
||||
)
|
||||
user = models.ForeignKey(
|
||||
settings.AUTH_USER_MODEL,
|
||||
on_delete=models.SET_NULL,
|
||||
null=True,
|
||||
blank=True,
|
||||
related_name="split_participations",
|
||||
verbose_name=_("WYGIWYH User"),
|
||||
)
|
||||
name = models.CharField(max_length=150, verbose_name=_("Name"))
|
||||
is_external = models.BooleanField(default=False, verbose_name=_("External"))
|
||||
is_active = models.BooleanField(default=True, verbose_name=_("Active"))
|
||||
external_username = models.CharField(
|
||||
max_length=150,
|
||||
blank=True,
|
||||
verbose_name=_("External username"),
|
||||
)
|
||||
external_password_hash = models.CharField(
|
||||
max_length=255,
|
||||
blank=True,
|
||||
verbose_name=_("External password hash"),
|
||||
)
|
||||
external_claimed_at = models.DateTimeField(
|
||||
null=True,
|
||||
blank=True,
|
||||
verbose_name=_("Claimed at"),
|
||||
)
|
||||
created_at = models.DateTimeField(auto_now_add=True)
|
||||
|
||||
class Meta:
|
||||
verbose_name = _("Split Participant")
|
||||
verbose_name_plural = _("Split Participants")
|
||||
db_table = "split_participants"
|
||||
ordering = ["-is_active", "name", "id"]
|
||||
constraints = [
|
||||
models.UniqueConstraint(
|
||||
fields=["event", "user"],
|
||||
condition=Q(user__isnull=False),
|
||||
name="unique_split_participant_user_per_event",
|
||||
),
|
||||
models.UniqueConstraint(
|
||||
fields=["event", "name"],
|
||||
name="unique_split_participant_name_per_event",
|
||||
),
|
||||
]
|
||||
|
||||
def __str__(self):
|
||||
return self.display_name
|
||||
|
||||
@property
|
||||
def display_name(self) -> str:
|
||||
if self.external_username:
|
||||
return f"{self.name} (@{self.external_username})"
|
||||
return self.name
|
||||
|
||||
@property
|
||||
def is_claimed(self) -> bool:
|
||||
return bool(self.is_external and self.external_password_hash)
|
||||
|
||||
@property
|
||||
def is_creator(self) -> bool:
|
||||
return bool(self.user_id and self.user_id == self.event.creator_id)
|
||||
|
||||
def set_external_password(self, raw_password: str, username: str = ""):
|
||||
self.external_password_hash = make_password(raw_password)
|
||||
if username:
|
||||
self.external_username = username.strip()
|
||||
if not self.external_claimed_at:
|
||||
self.external_claimed_at = timezone.now()
|
||||
self.save(
|
||||
update_fields=[
|
||||
"external_password_hash",
|
||||
"external_username",
|
||||
"external_claimed_at",
|
||||
]
|
||||
)
|
||||
|
||||
def check_external_password(self, raw_password: str) -> bool:
|
||||
if not self.external_password_hash:
|
||||
return False
|
||||
return check_password(raw_password, self.external_password_hash)
|
||||
|
||||
def reset_external_password(self):
|
||||
self.external_password_hash = ""
|
||||
self.external_claimed_at = None
|
||||
self.save(update_fields=["external_password_hash", "external_claimed_at"])
|
||||
|
||||
def has_contributions(self) -> bool:
|
||||
return (
|
||||
self.expenses_paid.exists()
|
||||
or self.expense_shares.exists()
|
||||
or self.payments_sent.exists()
|
||||
or self.payments_received.exists()
|
||||
)
|
||||
|
||||
def can_be_deleted(self) -> bool:
|
||||
return not self.is_creator and not self.has_contributions()
|
||||
|
||||
def clean(self):
|
||||
super().clean()
|
||||
if self.is_external and self.user_id is not None:
|
||||
raise ValidationError(
|
||||
_("An external participant cannot be linked to a WYGIWYH user.")
|
||||
)
|
||||
if not self.is_external and self.user_id is None:
|
||||
raise ValidationError(
|
||||
_("A non-external participant must be linked to a WYGIWYH user.")
|
||||
)
|
||||
|
||||
|
||||
class SplitExpense(models.Model):
|
||||
class SplitType(models.TextChoices):
|
||||
EQUAL = "EQUAL", _("Equal")
|
||||
EXACT = "EXACT", _("Exact amounts")
|
||||
PERCENTAGE = "PERCENTAGE", _("Percentages")
|
||||
SHARES = "SHARES", _("Shares")
|
||||
|
||||
event = models.ForeignKey(
|
||||
SplitEvent,
|
||||
on_delete=models.CASCADE,
|
||||
related_name="expenses",
|
||||
verbose_name=_("Event"),
|
||||
)
|
||||
paid_by = models.ForeignKey(
|
||||
SplitParticipant,
|
||||
on_delete=models.PROTECT,
|
||||
related_name="expenses_paid",
|
||||
verbose_name=_("Paid by"),
|
||||
)
|
||||
created_by_participant = models.ForeignKey(
|
||||
SplitParticipant,
|
||||
on_delete=models.SET_NULL,
|
||||
null=True,
|
||||
blank=True,
|
||||
related_name="expenses_created",
|
||||
verbose_name=_("Created by"),
|
||||
)
|
||||
description = models.CharField(max_length=255, verbose_name=_("Description"))
|
||||
amount = models.DecimalField(
|
||||
max_digits=20,
|
||||
decimal_places=6,
|
||||
validators=[MinValueValidator(Decimal("0.000001"))],
|
||||
verbose_name=_("Amount"),
|
||||
)
|
||||
date = models.DateField(default=timezone.localdate, verbose_name=_("Date"))
|
||||
split_type = models.CharField(
|
||||
max_length=16,
|
||||
choices=SplitType.choices,
|
||||
default=SplitType.EQUAL,
|
||||
verbose_name=_("Split type"),
|
||||
)
|
||||
notes = models.TextField(blank=True, verbose_name=_("Notes"))
|
||||
created_at = models.DateTimeField(auto_now_add=True)
|
||||
updated_at = models.DateTimeField(auto_now=True)
|
||||
|
||||
class Meta:
|
||||
verbose_name = _("Split Expense")
|
||||
verbose_name_plural = _("Split Expenses")
|
||||
db_table = "split_expenses"
|
||||
ordering = ["-date", "-created_at", "-id"]
|
||||
|
||||
def __str__(self):
|
||||
return f"{self.description} ({self.amount})"
|
||||
|
||||
def clean(self):
|
||||
super().clean()
|
||||
if self.paid_by_id and self.event_id and self.paid_by.event_id != self.event_id:
|
||||
raise ValidationError(
|
||||
{"paid_by": _("Payer must be a participant of this event.")}
|
||||
)
|
||||
|
||||
|
||||
class SplitExpenseShare(models.Model):
|
||||
expense = models.ForeignKey(
|
||||
SplitExpense,
|
||||
on_delete=models.CASCADE,
|
||||
related_name="shares",
|
||||
verbose_name=_("Expense"),
|
||||
)
|
||||
participant = models.ForeignKey(
|
||||
SplitParticipant,
|
||||
on_delete=models.PROTECT,
|
||||
related_name="expense_shares",
|
||||
verbose_name=_("Participant"),
|
||||
)
|
||||
amount = models.DecimalField(
|
||||
max_digits=20,
|
||||
decimal_places=6,
|
||||
validators=[MinValueValidator(Decimal("0"))],
|
||||
verbose_name=_("Amount"),
|
||||
)
|
||||
percentage = models.DecimalField(
|
||||
max_digits=7,
|
||||
decimal_places=4,
|
||||
null=True,
|
||||
blank=True,
|
||||
verbose_name=_("Percentage"),
|
||||
)
|
||||
shares = models.DecimalField(
|
||||
max_digits=12,
|
||||
decimal_places=4,
|
||||
null=True,
|
||||
blank=True,
|
||||
verbose_name=_("Shares"),
|
||||
)
|
||||
|
||||
class Meta:
|
||||
verbose_name = _("Split Expense Share")
|
||||
verbose_name_plural = _("Split Expense Shares")
|
||||
db_table = "split_expense_shares"
|
||||
ordering = ["participant__name", "id"]
|
||||
constraints = [
|
||||
models.UniqueConstraint(
|
||||
fields=["expense", "participant"],
|
||||
name="unique_share_per_expense_participant",
|
||||
),
|
||||
]
|
||||
|
||||
def __str__(self):
|
||||
return f"{self.participant.name}: {self.amount}"
|
||||
|
||||
|
||||
class SplitPayment(models.Model):
|
||||
event = models.ForeignKey(
|
||||
SplitEvent,
|
||||
on_delete=models.CASCADE,
|
||||
related_name="payments",
|
||||
verbose_name=_("Event"),
|
||||
)
|
||||
from_participant = models.ForeignKey(
|
||||
SplitParticipant,
|
||||
on_delete=models.PROTECT,
|
||||
related_name="payments_sent",
|
||||
verbose_name=_("From"),
|
||||
)
|
||||
to_participant = models.ForeignKey(
|
||||
SplitParticipant,
|
||||
on_delete=models.PROTECT,
|
||||
related_name="payments_received",
|
||||
verbose_name=_("To"),
|
||||
)
|
||||
created_by_participant = models.ForeignKey(
|
||||
SplitParticipant,
|
||||
on_delete=models.SET_NULL,
|
||||
null=True,
|
||||
blank=True,
|
||||
related_name="payments_created",
|
||||
verbose_name=_("Created by"),
|
||||
)
|
||||
amount = models.DecimalField(
|
||||
max_digits=20,
|
||||
decimal_places=6,
|
||||
validators=[MinValueValidator(Decimal("0.000001"))],
|
||||
verbose_name=_("Amount"),
|
||||
)
|
||||
date = models.DateField(default=timezone.localdate, verbose_name=_("Date"))
|
||||
notes = models.TextField(blank=True, verbose_name=_("Notes"))
|
||||
created_at = models.DateTimeField(auto_now_add=True)
|
||||
updated_at = models.DateTimeField(auto_now=True)
|
||||
|
||||
class Meta:
|
||||
verbose_name = _("Split Payment")
|
||||
verbose_name_plural = _("Split Payments")
|
||||
db_table = "split_payments"
|
||||
ordering = ["-date", "-created_at", "-id"]
|
||||
|
||||
def __str__(self):
|
||||
return f"{self.from_participant.name} -> {self.to_participant.name}: {self.amount}"
|
||||
|
||||
def clean(self):
|
||||
super().clean()
|
||||
errors = {}
|
||||
if (
|
||||
self.from_participant_id
|
||||
and self.to_participant_id
|
||||
and self.from_participant_id == self.to_participant_id
|
||||
):
|
||||
errors["to_participant"] = _(
|
||||
"Sender and recipient must be different participants."
|
||||
)
|
||||
if self.event_id:
|
||||
if (
|
||||
self.from_participant_id
|
||||
and self.from_participant.event_id != self.event_id
|
||||
):
|
||||
errors["from_participant"] = _(
|
||||
"Sender must be a participant of this event."
|
||||
)
|
||||
if (
|
||||
self.to_participant_id
|
||||
and self.to_participant.event_id != self.event_id
|
||||
):
|
||||
errors["to_participant"] = _(
|
||||
"Recipient must be a participant of this event."
|
||||
)
|
||||
if errors:
|
||||
raise ValidationError(errors)
|
||||
|
||||
|
||||
class SplitAttachment(models.Model):
|
||||
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
|
||||
event = models.ForeignKey(
|
||||
SplitEvent,
|
||||
on_delete=models.CASCADE,
|
||||
related_name="attachments",
|
||||
verbose_name=_("Event"),
|
||||
)
|
||||
expense = models.ForeignKey(
|
||||
SplitExpense,
|
||||
on_delete=models.CASCADE,
|
||||
null=True,
|
||||
blank=True,
|
||||
related_name="attachments",
|
||||
verbose_name=_("Expense"),
|
||||
)
|
||||
payment = models.ForeignKey(
|
||||
SplitPayment,
|
||||
on_delete=models.CASCADE,
|
||||
null=True,
|
||||
blank=True,
|
||||
related_name="attachments",
|
||||
verbose_name=_("Payment"),
|
||||
)
|
||||
file = models.FileField(
|
||||
upload_to=split_attachment_path,
|
||||
storage=PrivateMediaStorage(),
|
||||
verbose_name=_("File"),
|
||||
)
|
||||
original_name = models.CharField(max_length=255, verbose_name=_("Original Name"))
|
||||
content_type = models.CharField(
|
||||
max_length=255, blank=True, verbose_name=_("Content Type")
|
||||
)
|
||||
size = models.PositiveBigIntegerField(default=0, verbose_name=_("Size"))
|
||||
uploaded_by = models.ForeignKey(
|
||||
SplitParticipant,
|
||||
on_delete=models.SET_NULL,
|
||||
null=True,
|
||||
blank=True,
|
||||
related_name="uploaded_attachments",
|
||||
verbose_name=_("Uploaded By"),
|
||||
)
|
||||
created_at = models.DateTimeField(auto_now_add=True)
|
||||
|
||||
class Meta:
|
||||
verbose_name = _("Split Attachment")
|
||||
verbose_name_plural = _("Split Attachments")
|
||||
db_table = "split_attachments"
|
||||
ordering = ["-created_at", "original_name"]
|
||||
|
||||
def __str__(self):
|
||||
return self.original_name
|
||||
|
||||
def clean(self):
|
||||
super().clean()
|
||||
if bool(self.expense_id) == bool(self.payment_id):
|
||||
raise ValidationError(
|
||||
_("An attachment must belong to either an expense or a payment.")
|
||||
)
|
||||
|
||||
|
||||
class SplitTransactionLink(models.Model):
|
||||
class Kind(models.TextChoices):
|
||||
EXPENSE = "EXPENSE", _("Expense paid")
|
||||
PAYMENT_OUT = "PAYMENT_OUT", _("Payment sent")
|
||||
PAYMENT_IN = "PAYMENT_IN", _("Payment received")
|
||||
SETTLEMENT_OUT = "SETTLEMENT_OUT", _("Planned payment to send")
|
||||
SETTLEMENT_IN = "SETTLEMENT_IN", _("Planned payment to receive")
|
||||
|
||||
event = models.ForeignKey(
|
||||
SplitEvent,
|
||||
on_delete=models.CASCADE,
|
||||
related_name="transaction_links",
|
||||
verbose_name=_("Event"),
|
||||
)
|
||||
user = models.ForeignKey(
|
||||
settings.AUTH_USER_MODEL,
|
||||
on_delete=models.CASCADE,
|
||||
related_name="split_transaction_links",
|
||||
verbose_name=_("User"),
|
||||
)
|
||||
transaction = models.ForeignKey(
|
||||
"transactions.Transaction",
|
||||
on_delete=models.CASCADE,
|
||||
related_name="split_links",
|
||||
verbose_name=_("Transaction"),
|
||||
)
|
||||
kind = models.CharField(
|
||||
max_length=24,
|
||||
choices=Kind.choices,
|
||||
verbose_name=_("Kind"),
|
||||
)
|
||||
expense = models.ForeignKey(
|
||||
SplitExpense,
|
||||
on_delete=models.SET_NULL,
|
||||
null=True,
|
||||
blank=True,
|
||||
related_name="transaction_links",
|
||||
verbose_name=_("Expense"),
|
||||
)
|
||||
payment = models.ForeignKey(
|
||||
SplitPayment,
|
||||
on_delete=models.SET_NULL,
|
||||
null=True,
|
||||
blank=True,
|
||||
related_name="transaction_links",
|
||||
verbose_name=_("Payment"),
|
||||
)
|
||||
counterparty = models.ForeignKey(
|
||||
SplitParticipant,
|
||||
on_delete=models.SET_NULL,
|
||||
null=True,
|
||||
blank=True,
|
||||
related_name="counterparty_transaction_links",
|
||||
verbose_name=_("Counterparty"),
|
||||
)
|
||||
created_at = models.DateTimeField(auto_now_add=True)
|
||||
|
||||
class Meta:
|
||||
verbose_name = _("Split Transaction Link")
|
||||
verbose_name_plural = _("Split Transaction Links")
|
||||
db_table = "split_transaction_links"
|
||||
ordering = ["-created_at"]
|
||||
|
||||
def __str__(self):
|
||||
return f"{self.get_kind_display()} -> Tx #{self.transaction_id}"
|
||||
Whitespace-only changes.
@@ -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"])
|
||||
@@ -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,
|
||||
}
|
||||
@@ -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
|
||||
]
|
||||
)
|
||||
@@ -0,0 +1,162 @@
|
||||
from decimal import Decimal
|
||||
|
||||
from django.db import transaction as db_transaction
|
||||
from django.utils import timezone
|
||||
|
||||
from apps.accounts.models import Account
|
||||
from apps.splits.models import (
|
||||
SplitEvent,
|
||||
SplitExpense,
|
||||
SplitParticipant,
|
||||
SplitPayment,
|
||||
SplitTransactionLink,
|
||||
)
|
||||
from apps.transactions.models import Transaction, TransactionCategory
|
||||
|
||||
|
||||
def expected_transaction_type_for_kind(kind: str) -> str:
|
||||
if kind in (
|
||||
SplitTransactionLink.Kind.PAYMENT_IN,
|
||||
SplitTransactionLink.Kind.SETTLEMENT_IN,
|
||||
):
|
||||
return Transaction.Type.INCOME
|
||||
return Transaction.Type.EXPENSE
|
||||
|
||||
|
||||
def build_default_sync_description(
|
||||
*,
|
||||
event: SplitEvent,
|
||||
kind: str,
|
||||
expense: SplitExpense | None = None,
|
||||
payment: SplitPayment | None = None,
|
||||
counterparty: SplitParticipant | None = None,
|
||||
) -> str:
|
||||
if expense is not None:
|
||||
return f"[{event.name}] {expense.description}"
|
||||
if payment is not None:
|
||||
if kind == SplitTransactionLink.Kind.PAYMENT_IN:
|
||||
return f"[{event.name}] Payment from {payment.from_participant.name}"
|
||||
return f"[{event.name}] Payment to {payment.to_participant.name}"
|
||||
if counterparty is not None:
|
||||
if kind == SplitTransactionLink.Kind.SETTLEMENT_IN:
|
||||
return f"[{event.name}] Receive from {counterparty.name}"
|
||||
return f"[{event.name}] Pay {counterparty.name}"
|
||||
return f"[{event.name}] Split transaction"
|
||||
|
||||
|
||||
@db_transaction.atomic
|
||||
def create_and_link_transaction(
|
||||
*,
|
||||
user,
|
||||
event: SplitEvent,
|
||||
kind: str,
|
||||
account: Account,
|
||||
amount: Decimal,
|
||||
date,
|
||||
description: str,
|
||||
is_paid: bool = True,
|
||||
category: TransactionCategory | None = None,
|
||||
tags=(),
|
||||
entities=(),
|
||||
notes: str = "",
|
||||
expense: SplitExpense | None = None,
|
||||
payment: SplitPayment | None = None,
|
||||
counterparty: SplitParticipant | None = None,
|
||||
) -> SplitTransactionLink:
|
||||
tx_type = expected_transaction_type_for_kind(kind)
|
||||
tx = Transaction(
|
||||
owner=user,
|
||||
account=account,
|
||||
type=tx_type,
|
||||
is_paid=is_paid,
|
||||
date=date or timezone.localdate(),
|
||||
amount=amount,
|
||||
description=description[:500],
|
||||
notes=notes,
|
||||
category=category,
|
||||
)
|
||||
tx.save()
|
||||
tx.tags.set(tags)
|
||||
tx.entities.set(entities)
|
||||
|
||||
return SplitTransactionLink.objects.create(
|
||||
event=event,
|
||||
user=user,
|
||||
transaction=tx,
|
||||
kind=kind,
|
||||
expense=expense,
|
||||
payment=payment,
|
||||
counterparty=counterparty,
|
||||
)
|
||||
|
||||
|
||||
@db_transaction.atomic
|
||||
def link_existing_transaction(
|
||||
*,
|
||||
user,
|
||||
event: SplitEvent,
|
||||
kind: str,
|
||||
tx: Transaction,
|
||||
expense: SplitExpense | None = None,
|
||||
payment: SplitPayment | None = None,
|
||||
counterparty: SplitParticipant | None = None,
|
||||
) -> SplitTransactionLink:
|
||||
return SplitTransactionLink.objects.create(
|
||||
event=event,
|
||||
user=user,
|
||||
transaction=tx,
|
||||
kind=kind,
|
||||
expense=expense,
|
||||
payment=payment,
|
||||
counterparty=counterparty,
|
||||
)
|
||||
|
||||
|
||||
@db_transaction.atomic
|
||||
def settle_pending_links_for_payment(payment: SplitPayment) -> int:
|
||||
"""When a SplitPayment is recorded, find any unpaid SETTLEMENT_OUT/SETTLEMENT_IN
|
||||
WYGIWYH transaction links for the sender or recipient matching this counterparty,
|
||||
mark those WYGIWYH transactions as paid, and attach them to this payment.
|
||||
"""
|
||||
updated = 0
|
||||
# Sender's planned outgoing settlement to recipient
|
||||
if payment.from_participant.user_id:
|
||||
out_links = SplitTransactionLink.objects.select_related("transaction").filter(
|
||||
event=payment.event,
|
||||
user_id=payment.from_participant.user_id,
|
||||
kind=SplitTransactionLink.Kind.SETTLEMENT_OUT,
|
||||
counterparty=payment.to_participant,
|
||||
payment__isnull=True,
|
||||
)
|
||||
for link in out_links:
|
||||
tx = link.transaction
|
||||
if not tx.deleted and not tx.is_paid:
|
||||
tx.is_paid = True
|
||||
tx.date = payment.date
|
||||
tx.save()
|
||||
link.kind = SplitTransactionLink.Kind.PAYMENT_OUT
|
||||
link.payment = payment
|
||||
link.save(update_fields=["kind", "payment"])
|
||||
updated += 1
|
||||
|
||||
# Recipient's planned incoming settlement from sender
|
||||
if payment.to_participant.user_id:
|
||||
in_links = SplitTransactionLink.objects.select_related("transaction").filter(
|
||||
event=payment.event,
|
||||
user_id=payment.to_participant.user_id,
|
||||
kind=SplitTransactionLink.Kind.SETTLEMENT_IN,
|
||||
counterparty=payment.from_participant,
|
||||
payment__isnull=True,
|
||||
)
|
||||
for link in in_links:
|
||||
tx = link.transaction
|
||||
if not tx.deleted and not tx.is_paid:
|
||||
tx.is_paid = True
|
||||
tx.date = payment.date
|
||||
tx.save()
|
||||
link.kind = SplitTransactionLink.Kind.PAYMENT_IN
|
||||
link.payment = payment
|
||||
link.save(update_fields=["kind", "payment"])
|
||||
updated += 1
|
||||
|
||||
return updated
|
||||
Whitespace-only changes.
@@ -0,0 +1,12 @@
|
||||
from django import template
|
||||
from django.urls import reverse
|
||||
|
||||
register = template.Library()
|
||||
|
||||
|
||||
@register.simple_tag
|
||||
def split_portal_url(urls_dict, name_key, **extra_kwargs):
|
||||
url_name = urls_dict[name_key]
|
||||
kwargs = {urls_dict["url_kwarg_key"]: urls_dict["url_kwarg_val"]}
|
||||
kwargs.update(extra_kwargs)
|
||||
return reverse(url_name, kwargs=kwargs)
|
||||
Whitespace-only changes.
@@ -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")
|
||||
@@ -0,0 +1,201 @@
|
||||
from django.urls import path
|
||||
|
||||
from apps.splits import views
|
||||
|
||||
urlpatterns = [
|
||||
# WYGIWYH User Routes
|
||||
path("splits/", views.event_index, name="split_event_index"),
|
||||
path("splits/list/", views.event_list, name="split_event_list"),
|
||||
path("splits/add/", views.event_add, name="split_event_add"),
|
||||
path("splits/<int:event_id>/", views.event_detail, name="split_event_detail"),
|
||||
path(
|
||||
"splits/<int:event_id>/content/",
|
||||
views.event_content,
|
||||
name="split_event_content",
|
||||
),
|
||||
path(
|
||||
"splits/<int:event_id>/report/",
|
||||
views.event_report,
|
||||
name="split_event_report",
|
||||
),
|
||||
path("splits/<int:event_id>/edit/", views.event_edit, name="split_event_edit"),
|
||||
path(
|
||||
"splits/<int:event_id>/delete/",
|
||||
views.event_delete,
|
||||
name="split_event_delete",
|
||||
),
|
||||
path(
|
||||
"splits/<int:event_id>/leave/",
|
||||
views.event_leave,
|
||||
name="split_event_leave",
|
||||
),
|
||||
# Participant & Share Link Management
|
||||
path(
|
||||
"splits/<int:event_id>/participants/",
|
||||
views.participants_manage,
|
||||
name="split_participants_manage",
|
||||
),
|
||||
path(
|
||||
"splits/<int:event_id>/participants/add-user/",
|
||||
views.participant_add_wygiwyh,
|
||||
name="split_participant_add_wygiwyh",
|
||||
),
|
||||
path(
|
||||
"splits/<int:event_id>/participants/add-external/",
|
||||
views.participant_add_external,
|
||||
name="split_participant_add_external",
|
||||
),
|
||||
path(
|
||||
"splits/<int:event_id>/participants/<int:participant_id>/toggle-active/",
|
||||
views.participant_toggle_active,
|
||||
name="split_participant_toggle_active",
|
||||
),
|
||||
path(
|
||||
"splits/<int:event_id>/participants/<int:participant_id>/delete/",
|
||||
views.participant_delete,
|
||||
name="split_participant_delete",
|
||||
),
|
||||
path(
|
||||
"splits/<int:event_id>/participants/<int:participant_id>/reset-password/",
|
||||
views.participant_reset_password,
|
||||
name="split_participant_reset_password",
|
||||
),
|
||||
path(
|
||||
"splits/<int:event_id>/regenerate-link/",
|
||||
views.event_regenerate_link,
|
||||
name="split_event_regenerate_link",
|
||||
),
|
||||
# Expenses, Payments, Attachments (WYGIWYH)
|
||||
path(
|
||||
"splits/<int:event_id>/expenses/add/",
|
||||
views.expense_add,
|
||||
name="split_expense_add",
|
||||
),
|
||||
path(
|
||||
"splits/<int:event_id>/expenses/<int:expense_id>/edit/",
|
||||
views.expense_edit,
|
||||
name="split_expense_edit",
|
||||
),
|
||||
path(
|
||||
"splits/<int:event_id>/expenses/<int:expense_id>/delete/",
|
||||
views.expense_delete,
|
||||
name="split_expense_delete",
|
||||
),
|
||||
path(
|
||||
"splits/<int:event_id>/payments/add/",
|
||||
views.payment_add,
|
||||
name="split_payment_add",
|
||||
),
|
||||
path(
|
||||
"splits/<int:event_id>/payments/<int:payment_id>/edit/",
|
||||
views.payment_edit,
|
||||
name="split_payment_edit",
|
||||
),
|
||||
path(
|
||||
"splits/<int:event_id>/payments/<int:payment_id>/delete/",
|
||||
views.payment_delete,
|
||||
name="split_payment_delete",
|
||||
),
|
||||
path(
|
||||
"splits/<int:event_id>/attachments/<uuid:attachment_id>/download/",
|
||||
views.attachment_download,
|
||||
name="split_attachment_download",
|
||||
),
|
||||
path(
|
||||
"splits/<int:event_id>/attachments/<uuid:attachment_id>/delete/",
|
||||
views.attachment_delete,
|
||||
name="split_attachment_delete",
|
||||
),
|
||||
# WYGIWYH Transaction Sync
|
||||
path(
|
||||
"splits/<int:event_id>/sync/expense/<int:expense_id>/",
|
||||
views.sync_expense,
|
||||
name="split_sync_expense",
|
||||
),
|
||||
path(
|
||||
"splits/<int:event_id>/sync/payment/<int:payment_id>/",
|
||||
views.sync_payment,
|
||||
name="split_sync_payment",
|
||||
),
|
||||
path(
|
||||
"splits/<int:event_id>/sync/settlement/",
|
||||
views.sync_settlement,
|
||||
name="split_sync_settlement",
|
||||
),
|
||||
path(
|
||||
"splits/<int:event_id>/sync/unlink/<int:link_id>/",
|
||||
views.sync_unlink,
|
||||
name="split_sync_unlink",
|
||||
),
|
||||
# External Participant Portal (Shared UUID Link)
|
||||
path(
|
||||
"splits/share/<uuid:share_token>/",
|
||||
views.external_auth,
|
||||
name="split_external_auth",
|
||||
),
|
||||
path(
|
||||
"splits/share/<uuid:share_token>/logout/",
|
||||
views.external_logout,
|
||||
name="split_external_logout",
|
||||
),
|
||||
path(
|
||||
"splits/share/<uuid:share_token>/event/",
|
||||
views.external_event_detail,
|
||||
name="split_external_event_detail",
|
||||
),
|
||||
path(
|
||||
"splits/share/<uuid:share_token>/event/content/",
|
||||
views.external_event_content,
|
||||
name="split_external_event_content",
|
||||
),
|
||||
path(
|
||||
"splits/share/<uuid:share_token>/event/report/",
|
||||
views.external_event_report,
|
||||
name="split_external_event_report",
|
||||
),
|
||||
path(
|
||||
"splits/share/<uuid:share_token>/toasts/",
|
||||
views.external_toasts,
|
||||
name="split_external_toasts",
|
||||
),
|
||||
path(
|
||||
"splits/share/<uuid:share_token>/expenses/add/",
|
||||
views.external_expense_add,
|
||||
name="split_external_expense_add",
|
||||
),
|
||||
path(
|
||||
"splits/share/<uuid:share_token>/expenses/<int:expense_id>/edit/",
|
||||
views.external_expense_edit,
|
||||
name="split_external_expense_edit",
|
||||
),
|
||||
path(
|
||||
"splits/share/<uuid:share_token>/expenses/<int:expense_id>/delete/",
|
||||
views.external_expense_delete,
|
||||
name="split_external_expense_delete",
|
||||
),
|
||||
path(
|
||||
"splits/share/<uuid:share_token>/payments/add/",
|
||||
views.external_payment_add,
|
||||
name="split_external_payment_add",
|
||||
),
|
||||
path(
|
||||
"splits/share/<uuid:share_token>/payments/<int:payment_id>/edit/",
|
||||
views.external_payment_edit,
|
||||
name="split_external_payment_edit",
|
||||
),
|
||||
path(
|
||||
"splits/share/<uuid:share_token>/payments/<int:payment_id>/delete/",
|
||||
views.external_payment_delete,
|
||||
name="split_external_payment_delete",
|
||||
),
|
||||
path(
|
||||
"splits/share/<uuid:share_token>/attachments/<uuid:attachment_id>/download/",
|
||||
views.external_attachment_download,
|
||||
name="split_external_attachment_download",
|
||||
),
|
||||
path(
|
||||
"splits/share/<uuid:share_token>/attachments/<uuid:attachment_id>/delete/",
|
||||
views.external_attachment_delete,
|
||||
name="split_external_attachment_delete",
|
||||
),
|
||||
]
|
||||
File diff suppressed because it is too large.
Load diff
@@ -126,6 +126,12 @@
|
||||
active="dca_strategy_index||dca_strategy_detail_index"
|
||||
icon="fa-solid fa-magnifying-glass-chart">
|
||||
</c-components.sidebar-menu-item>
|
||||
<c-components.sidebar-menu-item
|
||||
title="{% translate 'Split Expenses' %}"
|
||||
url='split_event_index'
|
||||
active="split_event_index||split_event_detail"
|
||||
icon="fa-solid fa-people-arrows">
|
||||
</c-components.sidebar-menu-item>
|
||||
<c-components.sidebar-menu-item
|
||||
title="{% translate 'Unit Price Calculator' %}"
|
||||
url='unit_price_calculator'
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
{% load i18n %}
|
||||
{% load split_urls %}
|
||||
{% if item and item.attachments.all %}
|
||||
<div class="flex flex-wrap gap-2 mb-3">
|
||||
{% for att in item.attachments.all %}
|
||||
<span class="badge badge-outline gap-1">
|
||||
<a href="{% split_portal_url urls 'attachment_download_name' attachment_id=att.id %}"
|
||||
target="_blank" rel="noopener" class="no-underline hover:underline">
|
||||
<i class="fa-solid fa-paperclip fa-fw"></i>{{ att.original_name }}
|
||||
</a>
|
||||
<button type="button"
|
||||
class="text-error cursor-pointer"
|
||||
aria-label="{% translate 'Delete' %}"
|
||||
hx-delete="{% split_portal_url urls 'attachment_delete_name' attachment_id=att.id %}"
|
||||
hx-trigger="confirmed"
|
||||
hx-swap="none"
|
||||
data-title="{% translate 'Are you sure?' %}"
|
||||
data-text="{% translate "You won't be able to revert this!" %}"
|
||||
data-confirm-text="{% translate 'Yes, delete it!' %}"
|
||||
_="install prompt_swal
|
||||
on htmx:afterRequest[detail.successful] remove closest .badge">
|
||||
<i class="fa-solid fa-xmark fa-fw"></i>
|
||||
</button>
|
||||
</span>
|
||||
{% endfor %}
|
||||
</div>
|
||||
{% endif %}
|
||||
@@ -0,0 +1 @@
|
||||
{% load i18n %}{% if item.attachments.all %}<i class="fa-solid fa-paperclip text-xs text-base-content/40 ms-1.5" aria-label="{% translate 'Has attachments' %}"></i>{% endif %}{% if item.user_tx_links %}<i class="fa-solid fa-link text-xs text-base-content/40 ms-1.5" aria-label="{% translate 'Linked to your transactions' %}"></i>{% endif %}
|
||||
@@ -0,0 +1,114 @@
|
||||
{% load i18n %}
|
||||
{% load split_urls %}
|
||||
<li>
|
||||
<details name="split-activity" class="group">
|
||||
<summary class="list-none [&::-webkit-details-marker]:hidden flex items-center gap-3 px-2 py-2.5 rounded-box cursor-pointer
|
||||
hover:bg-base-content/5 transition-colors duration-150
|
||||
focus-visible:outline-2 focus-visible:outline-primary">
|
||||
<div class="w-10 shrink-0 text-center leading-tight {% if item.is_payment %}text-base-content/50{% endif %}">
|
||||
<div class="text-xs uppercase text-base-content/50">{{ item.date|date:"M" }}</div>
|
||||
<div class="text-lg font-semibold tabular-nums">{{ item.date|date:"j" }}</div>
|
||||
</div>
|
||||
|
||||
<div class="min-w-0 flex-1">
|
||||
{% if item.is_payment %}
|
||||
<div class="line-clamp-2 wrap-anywhere">
|
||||
<i class="fa-solid fa-hand-holding-dollar text-success me-1"></i>
|
||||
{% 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' %}
|
||||
</div>
|
||||
{% if item.notes %}<div class="text-xs text-base-content/50 truncate">{{ item.notes }}</div>{% endif %}
|
||||
{% else %}
|
||||
<div class="truncate font-medium">{{ item.description }}{% include 'splits/fragments/event/activity_flags.html' %}</div>
|
||||
<div class="text-xs text-base-content/50 truncate tabular-nums">
|
||||
{% if item.paid_by_id == me_id %}{% translate 'You paid' %}{% else %}{% blocktranslate with name=item.paid_by.name %}{{ name }} paid{% endblocktranslate %}{% endif %}
|
||||
<c-amount.display :amount="item.amount" :prefix="event.currency.prefix" :suffix="event.currency.suffix" :decimal_places="event.currency.decimal_places" divless></c-amount.display>
|
||||
</div>
|
||||
{% endif %}
|
||||
</div>
|
||||
|
||||
<div class="shrink-0 text-end text-sm tabular-nums">
|
||||
{% if item.is_payment %}
|
||||
<c-amount.display :amount="item.amount" :prefix="event.currency.prefix" :suffix="event.currency.suffix" :decimal_places="event.currency.decimal_places" divless></c-amount.display>
|
||||
{% elif item.my_delta is None %}
|
||||
<div class="text-xs text-base-content/40">{% translate 'not involved' %}</div>
|
||||
{% elif item.my_delta > 0 %}
|
||||
<div class="text-xs text-base-content/50">{% translate 'you lent' %}</div>
|
||||
<c-amount.display :amount="item.my_delta_abs" :prefix="event.currency.prefix" :suffix="event.currency.suffix" :decimal_places="event.currency.decimal_places" color="green" divless></c-amount.display>
|
||||
{% elif item.my_delta < 0 %}
|
||||
<div class="text-xs text-base-content/50">{% translate 'you borrowed' %}</div>
|
||||
<c-amount.display :amount="item.my_delta_abs" :prefix="event.currency.prefix" :suffix="event.currency.suffix" :decimal_places="event.currency.decimal_places" color="red" divless></c-amount.display>
|
||||
{% else %}
|
||||
<div class="text-xs text-base-content/40">{% translate 'settled' %}</div>
|
||||
{% endif %}
|
||||
</div>
|
||||
|
||||
<div class="w-4 shrink-0 text-xs text-base-content/40">
|
||||
<i class="fa-solid fa-chevron-down transition-[rotate] duration-200 ease-[cubic-bezier(0.23,1,0.32,1)] group-open:rotate-180"></i>
|
||||
</div>
|
||||
</summary>
|
||||
|
||||
<div class="ms-15 me-2 mb-3 flex flex-col gap-3 text-sm
|
||||
transition-[opacity,translate] duration-200 ease-[cubic-bezier(0.23,1,0.32,1)]
|
||||
starting:opacity-0 motion-safe:starting:-translate-y-1">
|
||||
{% if not item.is_payment %}
|
||||
<dl class="flex flex-col divide-y divide-base-content/10 tabular-nums">
|
||||
{% for s in item.shares.all %}
|
||||
<div class="flex justify-between gap-4 py-1.5">
|
||||
<dt class="text-base-content/60 min-w-0 truncate">{% if s.participant_id == me_id %}{% translate 'You' %}{% else %}{{ s.participant.name }}{% endif %}</dt>
|
||||
<dd class="whitespace-nowrap"><c-amount.display :amount="s.amount" :prefix="event.currency.prefix" :suffix="event.currency.suffix" :decimal_places="event.currency.decimal_places" divless></c-amount.display></dd>
|
||||
</div>
|
||||
{% endfor %}
|
||||
</dl>
|
||||
{% if item.split_type != 'EQUAL' %}
|
||||
<div class="text-xs text-base-content/50 -mt-2">{% blocktranslate with mode=item.get_split_type_display %}Split by {{ mode }}{% endblocktranslate %}</div>
|
||||
{% endif %}
|
||||
{% endif %}
|
||||
|
||||
{% if item.notes %}<p class="text-base-content/70 whitespace-pre-line text-pretty">{{ item.notes }}</p>{% endif %}
|
||||
|
||||
{% if item.attachments.all or item.user_tx_links %}
|
||||
<div class="flex flex-wrap gap-1">
|
||||
{% for att in item.attachments.all %}
|
||||
<a href="{% split_portal_url urls 'attachment_download_name' attachment_id=att.id %}"
|
||||
target="_blank" rel="noopener" class="badge badge-sm badge-outline no-underline">
|
||||
<i class="fa-solid fa-paperclip"></i>{{ att.original_name }}
|
||||
</a>
|
||||
{% endfor %}
|
||||
{% include 'splits/fragments/tx_links.html' with links=item.user_tx_links %}
|
||||
</div>
|
||||
{% endif %}
|
||||
|
||||
{% if item.can_sync or item.can_edit %}
|
||||
<div class="flex flex-wrap gap-1 -ms-3">
|
||||
{% if item.can_sync %}
|
||||
<button type="button" class="btn btn-ghost btn-sm"
|
||||
hx-get="{% if item.is_payment %}{% url 'split_sync_payment' event_id=event.id payment_id=item.id %}{% else %}{% url 'split_sync_expense' event_id=event.id expense_id=item.id %}{% endif %}"
|
||||
hx-target="#generic-offcanvas">
|
||||
<i class="fa-solid fa-wallet"></i>{% translate 'Add to my transactions' %}
|
||||
</button>
|
||||
{% endif %}
|
||||
{% if item.can_edit %}
|
||||
<button type="button" class="btn btn-ghost btn-sm"
|
||||
hx-get="{% if item.is_payment %}{% split_portal_url urls 'payment_edit_name' payment_id=item.id %}{% else %}{% split_portal_url urls 'expense_edit_name' expense_id=item.id %}{% endif %}"
|
||||
hx-target="#generic-offcanvas">
|
||||
<i class="fa-solid fa-pencil"></i>{% translate 'Edit' %}
|
||||
</button>
|
||||
<button type="button" class="btn btn-ghost btn-sm text-error"
|
||||
hx-delete="{% if item.is_payment %}{% split_portal_url urls 'payment_delete_name' payment_id=item.id %}{% else %}{% split_portal_url urls 'expense_delete_name' expense_id=item.id %}{% endif %}"
|
||||
hx-trigger="confirmed"
|
||||
data-bypass-on-ctrl="true"
|
||||
data-title="{% translate 'Are you sure?' %}"
|
||||
data-text="{% translate "You won't be able to revert this!" %}"
|
||||
data-confirm-text="{% translate 'Yes, delete it!' %}"
|
||||
_="install prompt_swal">
|
||||
<i class="fa-solid fa-trash"></i>{% translate 'Delete' %}
|
||||
</button>
|
||||
{% endif %}
|
||||
</div>
|
||||
{% endif %}
|
||||
</div>
|
||||
</details>
|
||||
</li>
|
||||
@@ -0,0 +1,11 @@
|
||||
{% extends 'extends/offcanvas.html' %}
|
||||
{% load i18n %}
|
||||
{% load crispy_forms_tags %}
|
||||
|
||||
{% block title %}{% translate 'Add event' %}{% endblock %}
|
||||
|
||||
{% block body %}
|
||||
<form hx-post="{% url 'split_event_add' %}" hx-target="#generic-offcanvas" novalidate>
|
||||
{% crispy form %}
|
||||
</form>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,188 @@
|
||||
{% load i18n %}
|
||||
{% load l10n %}
|
||||
{% with c=event.currency %}
|
||||
<c-components.fab>
|
||||
<c-components.fab_menu_button
|
||||
color="error" hx_target="#generic-offcanvas" hx_trigger="click"
|
||||
url="{{ urls.expense_add }}"
|
||||
icon="fa-solid fa-receipt"
|
||||
title="{% translate 'Expense' %}"></c-components.fab_menu_button>
|
||||
<c-components.fab_menu_button
|
||||
color="success" hx_target="#generic-offcanvas" hx_trigger="click"
|
||||
url="{{ urls.payment_add }}"
|
||||
icon="fa-solid fa-hand-holding-dollar"
|
||||
title="{% translate 'Payment' %}"></c-components.fab_menu_button>
|
||||
</c-components.fab>
|
||||
|
||||
<div class="container pb-20">
|
||||
<div class="flex items-center gap-2 mb-1">
|
||||
{% if not actor.is_external_portal %}
|
||||
<a href="{% url 'split_event_index' %}" hx-boost="true"
|
||||
class="btn btn-ghost btn-sm btn-square text-base-content/50 hover:text-base-content"
|
||||
aria-label="{% translate 'Split Expenses' %}"><i class="fa-solid fa-arrow-left"></i></a>
|
||||
{% endif %}
|
||||
<h1 class="text-2xl font-bold truncate text-balance">{{ event.name }}</h1>
|
||||
{% if event.is_archived %}<span class="badge badge-warning badge-sm">{% translate 'Archived' %}</span>{% endif %}
|
||||
{% if actor.is_creator %}
|
||||
<button class="btn btn-ghost btn-sm btn-square text-base-content/40 hover:text-base-content"
|
||||
data-tippy-content="{% translate 'People' %}" aria-label="{% translate 'People' %}"
|
||||
hx-get="{% url 'split_participants_manage' event_id=event.id %}" hx-target="#generic-offcanvas">
|
||||
<i class="fa-solid fa-user-group"></i>
|
||||
</button>
|
||||
<button class="btn btn-ghost btn-sm btn-square text-base-content/40 hover:text-base-content"
|
||||
data-tippy-content="{% translate 'Edit event' %}" aria-label="{% translate 'Edit event' %}"
|
||||
hx-get="{% url 'split_event_edit' event_id=event.id %}" hx-target="#generic-offcanvas">
|
||||
<i class="fa-solid fa-pencil"></i>
|
||||
</button>
|
||||
{% elif actor.is_wygiwyh_user %}
|
||||
<button class="btn btn-ghost btn-sm btn-square text-base-content/40 hover:text-error"
|
||||
data-tippy-content="{% translate 'Leave event' %}" aria-label="{% translate 'Leave event' %}"
|
||||
hx-post="{% url 'split_event_leave' event_id=event.id %}"
|
||||
hx-trigger="confirmed"
|
||||
data-title="{% translate 'Leave this event?' %}"
|
||||
data-text="{% translate 'It disappears from your list. Expenses and payments you were part of stay, so the others still see correct balances.' %}"
|
||||
data-confirm-text="{% translate 'Leave' %}"
|
||||
_="install prompt_swal">
|
||||
<i class="fa-solid fa-right-from-bracket"></i>
|
||||
</button>
|
||||
{% endif %}
|
||||
{% include 'splits/fragments/event/share_menu.html' %}
|
||||
</div>
|
||||
<div class="text-sm text-base-content/50 mb-6 {% if not actor.is_external_portal %}ps-10{% endif %}">
|
||||
{% blocktranslate count counter=active_participants_count %}{{ counter }} person{% plural %}{{ counter }} people{% endblocktranslate %}
|
||||
{% if event.description %}<div class="text-pretty whitespace-pre-line mt-1">{{ event.description }}</div>{% endif %}
|
||||
</div>
|
||||
|
||||
<div class="hidden" data-export="header">
|
||||
<div class="text-2xl font-bold text-balance">{{ event.name }}</div>
|
||||
<div class="text-sm text-base-content/60 tabular-nums">
|
||||
{% blocktranslate count counter=active_participants_count %}{{ counter }} person{% plural %}{{ counter }} people{% endblocktranslate %}
|
||||
· {% translate 'Group total' %} <c-amount.display :amount="total_spent" :prefix="c.prefix" :suffix="c.suffix" :decimal_places="c.decimal_places" divless></c-amount.display>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{# The one number people open this page for #}
|
||||
{% if my_balance %}
|
||||
<div class="card bg-base-100 card-border shadow mb-4">
|
||||
<div class="card-body p-5 flex-row flex-wrap items-end justify-between gap-4">
|
||||
<div>
|
||||
{% if not my_balance.net_balance %}
|
||||
<div class="text-2xl font-bold"><i class="fa-solid fa-circle-check text-success me-2"></i>{% if transfers %}{% translate 'You are settled up' %}{% else %}{% translate 'Everyone is settled up' %}{% endif %}</div>
|
||||
{% else %}
|
||||
<div class="text-sm text-base-content/60">
|
||||
{% if my_balance.net_balance > 0 %}{% translate 'You are owed' %}{% else %}{% translate 'You owe' %}{% endif %}
|
||||
</div>
|
||||
<div class="text-3xl sm:text-4xl font-bold tabular-nums tracking-tight whitespace-nowrap">
|
||||
{# Show the magnitude; the sentence above carries the direction #}
|
||||
<c-amount.display :amount="my_balance_abs" :prefix="c.prefix" :suffix="c.suffix"
|
||||
:decimal_places="c.decimal_places" color="{% if my_balance.net_balance > 0 %}green{% elif my_balance.net_balance < 0 %}red{% endif %}" divless></c-amount.display>
|
||||
</div>
|
||||
{% endif %}
|
||||
</div>
|
||||
<div class="text-sm sm:text-end tabular-nums">
|
||||
<div class="text-base-content/60">{% translate 'Group total' %}</div>
|
||||
<c-amount.display :amount="total_spent" :prefix="c.prefix" :suffix="c.suffix" :decimal_places="c.decimal_places" divless></c-amount.display>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{% endif %}
|
||||
|
||||
<div class="grid grid-cols-1 lg:grid-cols-3 gap-4">
|
||||
<div class="flex flex-col gap-4">
|
||||
{% if transfers %}
|
||||
<div class="card bg-base-100 card-border shadow" data-export="settle">
|
||||
<div class="px-5 pt-4 pb-1 font-semibold">{% translate 'Settle up' %}</div>
|
||||
<ul class="px-5 pb-3 flex flex-col divide-y divide-base-content/10 text-sm">
|
||||
{% for item in transfers %}{% with t=item.transfer %}
|
||||
<li class="py-3 flex flex-col gap-2">
|
||||
<div class="flex items-baseline justify-between gap-3">
|
||||
<span class="min-w-0">
|
||||
<span class="font-medium" data-export-name="{{ t.from_participant.name }}">{% if t.from_participant.id == me_id %}{% translate 'You' %}{% else %}{{ t.from_participant.name }}{% endif %}</span>
|
||||
<i class="fa-solid fa-arrow-right text-xs text-base-content/40 mx-1"></i>
|
||||
<span class="font-medium" data-export-name="{{ t.to_participant.name }}">{% if t.to_participant.id == me_id %}{% translate 'You' %}{% else %}{{ t.to_participant.name }}{% endif %}</span>
|
||||
</span>
|
||||
<span class="tabular-nums whitespace-nowrap font-semibold">
|
||||
<c-amount.display :amount="t.amount" :prefix="c.prefix" :suffix="c.suffix" :decimal_places="c.decimal_places" divless></c-amount.display>
|
||||
</span>
|
||||
</div>
|
||||
{% if item.tx_links %}
|
||||
<div class="flex flex-wrap gap-1" data-export-hide>{% include 'splits/fragments/tx_links.html' with links=item.tx_links %}</div>
|
||||
{% endif %}
|
||||
{% if item.can_record or item.user_direction %}
|
||||
<div class="flex gap-2" data-export-hide>
|
||||
{% if item.can_record %}
|
||||
<button type="button" class="btn btn-sm btn-soft btn-success flex-1"
|
||||
hx-get="{{ urls.payment_add }}?from={{ t.from_participant.id }}&to={{ t.to_participant.id }}&amount={{ t.amount|unlocalize }}"
|
||||
hx-target="#generic-offcanvas">
|
||||
<i class="fa-solid fa-check"></i>{% translate 'Record as paid' %}
|
||||
</button>
|
||||
{% endif %}
|
||||
{% if item.user_direction %}
|
||||
<button type="button" class="btn btn-sm btn-ghost btn-square"
|
||||
data-tippy-content="{% if item.user_direction == 'out' %}{% translate 'Add as planned expense in my transactions' %}{% else %}{% translate 'Add as expected income in my transactions' %}{% endif %}"
|
||||
aria-label="{% translate 'Add to my transactions' %}"
|
||||
hx-get="{% url 'split_sync_settlement' event_id=event.id %}?direction={{ item.user_direction }}&counterparty={{ item.counterparty.id }}&amount={{ t.amount|unlocalize }}"
|
||||
hx-target="#generic-offcanvas">
|
||||
<i class="fa-solid fa-wallet"></i>
|
||||
</button>
|
||||
{% endif %}
|
||||
</div>
|
||||
{% endif %}
|
||||
</li>
|
||||
{% endwith %}{% endfor %}
|
||||
</ul>
|
||||
</div>
|
||||
{% endif %}
|
||||
|
||||
<div class="card bg-base-100 card-border shadow" data-export="balances">
|
||||
<div class="px-5 pt-4 pb-1 font-semibold">{% translate 'Balances' %}</div>
|
||||
<ul class="px-5 pb-3 flex flex-col divide-y divide-base-content/10 text-sm">
|
||||
{% for row in balance_rows %}{% with b=row.balance %}
|
||||
<li class="py-2.5 {% if not b.participant.is_active %}opacity-50{% endif %}">
|
||||
<div class="flex items-baseline justify-between gap-3">
|
||||
<span class="min-w-0 truncate">
|
||||
{{ b.participant.name }}
|
||||
{% if b.participant.id == me_id %}<span class="badge badge-xs badge-primary align-middle" data-export-hide>{% translate 'you' %}</span>{% endif %}
|
||||
{% if not b.participant.is_active %}<span class="badge badge-xs badge-ghost align-middle">{% translate 'inactive' %}</span>{% endif %}
|
||||
</span>
|
||||
<span class="tabular-nums whitespace-nowrap">
|
||||
<c-amount.display :amount="b.net_balance" :prefix="c.prefix" :suffix="c.suffix" :decimal_places="c.decimal_places" color="auto" divless></c-amount.display>
|
||||
</span>
|
||||
</div>
|
||||
{# Diverging bar: right of center is owed money, left owes #}
|
||||
<div class="relative h-1 mt-1.5 rounded-full bg-base-content/10" aria-hidden="true">
|
||||
<div class="absolute inset-y-0 left-1/2 w-px bg-base-content/20"></div>
|
||||
{% if row.bar %}
|
||||
<div class="absolute inset-y-0 rounded-full {% if b.net_balance > 0 %}left-1/2 bg-success{% else %}right-1/2 bg-error{% endif %}"
|
||||
style="width: {{ row.bar }}%"></div>
|
||||
{% endif %}
|
||||
</div>
|
||||
<div class="text-xs text-base-content/50 tabular-nums mt-1">
|
||||
{% translate 'paid' %} <c-amount.display :amount="b.total_paid" :prefix="c.prefix" :suffix="c.suffix" :decimal_places="c.decimal_places" divless></c-amount.display>
|
||||
· {% translate 'share' %} <c-amount.display :amount="b.total_owed" :prefix="c.prefix" :suffix="c.suffix" :decimal_places="c.decimal_places" divless></c-amount.display>
|
||||
</div>
|
||||
</li>
|
||||
{% endwith %}{% endfor %}
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="lg:col-span-2">
|
||||
<div class="card bg-base-100 card-border shadow">
|
||||
<div class="px-5 pt-4 pb-1 font-semibold">{% translate 'Activity' %}</div>
|
||||
{% if activity %}
|
||||
<ul class="px-3 pb-2 flex flex-col">
|
||||
{% for item in activity %}
|
||||
{% include 'splits/fragments/event/activity_item.html' %}
|
||||
{% endfor %}
|
||||
</ul>
|
||||
{% else %}
|
||||
<c-msg.empty icon="fa-solid fa-receipt"
|
||||
title="{% translate 'Nothing here yet' %}"
|
||||
subtitle="{% translate 'Add the first expense with the + button' %}"></c-msg.empty>
|
||||
{% endif %}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{% endwith %}
|
||||
@@ -0,0 +1,23 @@
|
||||
{% extends 'extends/offcanvas.html' %}
|
||||
{% load i18n %}
|
||||
{% load crispy_forms_tags %}
|
||||
|
||||
{% block title %}{% translate 'Edit event' %}{% endblock %}
|
||||
|
||||
{% block body %}
|
||||
<form hx-post="{% url 'split_event_edit' event_id=event.id %}" hx-target="#generic-offcanvas" novalidate>
|
||||
{% crispy form %}
|
||||
</form>
|
||||
|
||||
<div class="divider"></div>
|
||||
<button type="button"
|
||||
class="btn btn-error btn-outline w-full"
|
||||
hx-delete="{% url 'split_event_delete' event_id=event.id %}"
|
||||
hx-trigger="confirmed"
|
||||
data-title="{% translate 'Delete this event?' %}"
|
||||
data-text="{% translate 'All its expenses, payments and attachments are deleted. Transactions you linked in your accounts are kept.' %}"
|
||||
data-confirm-text="{% translate 'Yes, delete it!' %}"
|
||||
_="install prompt_swal">
|
||||
<i class="fa-solid fa-trash fa-fw"></i>{% translate 'Delete event' %}
|
||||
</button>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,58 @@
|
||||
{% load i18n %}
|
||||
<script>
|
||||
// Renders tagged sections ([data-export]) into one phone-width PNG, then shares (touch devices) or downloads it
|
||||
async function splitExportImage(button) {
|
||||
if (button.disabled) return;
|
||||
button.disabled = true;
|
||||
document.activeElement?.blur(); // closes the daisyUI dropdown
|
||||
|
||||
const card = document.createElement('div');
|
||||
card.className = 'bg-base-200 text-base-content font-mono p-6 flex flex-col gap-4';
|
||||
// Off-screen but laid out, so it renders at a fixed phone-friendly width
|
||||
card.style.cssText = 'position: fixed; left: -10000px; top: 0; width: 480px;';
|
||||
|
||||
for (const name of ['header', ...button.dataset.sections.split(',')]) {
|
||||
const source = document.querySelector(`[data-export="${name}"]`);
|
||||
if (!source) continue;
|
||||
const clone = source.cloneNode(true);
|
||||
clone.classList.remove('hidden', 'shadow');
|
||||
clone.querySelectorAll('[data-export-hide]').forEach((el) => el.remove());
|
||||
clone.querySelectorAll('[data-export-name]').forEach((el) => (el.textContent = el.dataset.exportName));
|
||||
// Font Awesome 7's `content: "…" / ""` alt syntax renders a stray "/" in the capture
|
||||
clone.querySelectorAll('.fa-arrow-right').forEach((el) => el.replaceWith(' → '));
|
||||
card.append(clone);
|
||||
}
|
||||
const footer = document.createElement('div');
|
||||
footer.className = 'text-xs text-base-content/40 text-end';
|
||||
footer.textContent = 'WYGIWYH';
|
||||
card.append(footer);
|
||||
document.body.append(card);
|
||||
|
||||
try {
|
||||
const blob = await window.domToBlob(card, {
|
||||
scale: 2,
|
||||
backgroundColor: getComputedStyle(card).backgroundColor,
|
||||
});
|
||||
const file = new File([blob], button.dataset.filename, {type: 'image/png'});
|
||||
if (matchMedia('(pointer: coarse)').matches && navigator.canShare?.({files: [file]})) {
|
||||
try {
|
||||
await navigator.share({files: [file]});
|
||||
return;
|
||||
} catch (e) {
|
||||
if (e.name === 'AbortError') return;
|
||||
}
|
||||
}
|
||||
const link = document.createElement('a');
|
||||
link.href = URL.createObjectURL(file);
|
||||
link.download = file.name;
|
||||
link.click();
|
||||
setTimeout(() => URL.revokeObjectURL(link.href), 1000);
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
Swal.fire({icon: 'error', text: "{% translate "Couldn't create the image." %}"});
|
||||
} finally {
|
||||
card.remove();
|
||||
button.disabled = false;
|
||||
}
|
||||
}
|
||||
</script>
|
||||
@@ -0,0 +1,71 @@
|
||||
{% load i18n %}
|
||||
<c-ui.fab-single-action
|
||||
url="{% url 'split_event_add' %}"
|
||||
hx_target="#generic-offcanvas">
|
||||
</c-ui.fab-single-action>
|
||||
<div class="container">
|
||||
<div class="flex flex-wrap justify-between items-center gap-3 mb-3">
|
||||
<div class="text-3xl font-bold font-mono">{% translate 'Split Expenses' %}</div>
|
||||
<label class="label cursor-pointer text-sm">
|
||||
<input type="checkbox" class="toggle toggle-sm"
|
||||
{% if show_archived %}checked{% endif %}
|
||||
hx-get="{% url 'split_event_list' %}{% if not show_archived %}?archived=1{% endif %}"
|
||||
hx-target="closest .show-loading"
|
||||
hx-trigger="change">
|
||||
{% translate 'Show archived' %}
|
||||
</label>
|
||||
</div>
|
||||
|
||||
{% if not event_cards %}
|
||||
<c-msg.empty
|
||||
icon="fa-solid fa-people-arrows"
|
||||
title="{% translate 'No events yet' %}"
|
||||
subtitle="{% translate 'Create one for a trip, a shared flat or a dinner' %}"></c-msg.empty>
|
||||
{% else %}
|
||||
<div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-3">
|
||||
{% for card in event_cards %}
|
||||
<a href="{% url 'split_event_detail' event_id=card.event.id %}" hx-boost="true"
|
||||
class="card bg-base-100 card-border shadow no-underline hover:shadow-lg transition-shadow">
|
||||
<div class="card-body">
|
||||
<div class="flex justify-between items-start gap-2">
|
||||
<div class="card-title text-xl min-w-0"><span class="truncate">{{ card.event.name }}</span></div>
|
||||
<div class="flex gap-1 shrink-0">
|
||||
{% if card.event.is_archived %}<span class="badge badge-warning">{% translate 'Archived' %}</span>{% endif %}
|
||||
<span class="badge badge-secondary rounded-full">{{ card.event.currency.code }}</span>
|
||||
</div>
|
||||
</div>
|
||||
{% if card.event.description %}
|
||||
<div class="text-base-content/60 line-clamp-2">{{ card.event.description }}</div>
|
||||
{% endif %}
|
||||
<div class="grid grid-cols-2 gap-2 mt-2">
|
||||
<div>
|
||||
<div class="text-sm text-base-content/60">{% translate 'Total spent' %}</div>
|
||||
<c-amount.display
|
||||
:amount="card.total_spent"
|
||||
:prefix="card.event.currency.prefix"
|
||||
:suffix="card.event.currency.suffix"
|
||||
:decimal_places="card.event.currency.decimal_places"></c-amount.display>
|
||||
</div>
|
||||
{% if card.my_balance %}
|
||||
<div class="text-right">
|
||||
<div class="text-sm text-base-content/60">{% translate 'Your balance' %}</div>
|
||||
<c-amount.display
|
||||
:amount="card.my_balance.net_balance"
|
||||
:prefix="card.event.currency.prefix"
|
||||
:suffix="card.event.currency.suffix"
|
||||
:decimal_places="card.event.currency.decimal_places"
|
||||
color="auto"></c-amount.display>
|
||||
</div>
|
||||
{% endif %}
|
||||
</div>
|
||||
<div class="text-sm text-base-content/60 mt-2">
|
||||
<i class="fa-solid fa-users fa-fw"></i>
|
||||
{% blocktranslate count counter=card.participant_count %}{{ counter }} person{% plural %}{{ counter }} people{% endblocktranslate %}
|
||||
{% if card.is_creator %}· {% translate 'Organizer' %}{% endif %}
|
||||
</div>
|
||||
</div>
|
||||
</a>
|
||||
{% endfor %}
|
||||
</div>
|
||||
{% endif %}
|
||||
</div>
|
||||
@@ -0,0 +1,34 @@
|
||||
{% load i18n %}
|
||||
<div class="dropdown dropdown-end ms-auto shrink-0">
|
||||
<div tabindex="0" role="button" class="btn btn-ghost btn-sm">
|
||||
<i class="fa-solid fa-arrow-up-from-bracket"></i><span class="hidden sm:inline">{% translate 'Share' %}</span>
|
||||
</div>
|
||||
<ul tabindex="-1" class="dropdown-content menu bg-base-100 rounded-box z-10 w-60 p-2 shadow-lg mt-1">
|
||||
<li>
|
||||
<a href="{{ urls.report }}" target="_blank" rel="noopener" class="no-underline">
|
||||
<i class="fa-solid fa-file-pdf fa-fw"></i>{% translate 'Full report (PDF)' %}
|
||||
</a>
|
||||
</li>
|
||||
<li class="menu-title">{% translate 'Image' %}</li>
|
||||
<li>
|
||||
<button type="button" onclick="splitExportImage(this)"
|
||||
data-sections="{% if transfers %}settle,{% endif %}balances" data-filename="{{ event.name|slugify }}-summary.png">
|
||||
<i class="fa-solid fa-image fa-fw"></i>{% translate 'Summary' %}
|
||||
</button>
|
||||
</li>
|
||||
{% if transfers %}
|
||||
<li>
|
||||
<button type="button" onclick="splitExportImage(this)"
|
||||
data-sections="settle" data-filename="{{ event.name|slugify }}-settle-up.png">
|
||||
<i class="fa-solid fa-arrow-right-arrow-left fa-fw"></i>{% translate 'Settle up' %}
|
||||
</button>
|
||||
</li>
|
||||
{% endif %}
|
||||
<li>
|
||||
<button type="button" onclick="splitExportImage(this)"
|
||||
data-sections="balances" data-filename="{{ event.name|slugify }}-balances.png">
|
||||
<i class="fa-solid fa-scale-balanced fa-fw"></i>{% translate 'Balances' %}
|
||||
</button>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
@@ -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 %}
|
||||
<form hx-post="{{ post_url }}"
|
||||
hx-target="#generic-offcanvas"
|
||||
hx-encoding="multipart/form-data"
|
||||
novalidate>
|
||||
{% if form.non_field_errors %}
|
||||
<div class="alert alert-error mb-3">{{ form.non_field_errors }}</div>
|
||||
{% endif %}
|
||||
|
||||
{{ form.description|as_crispy_field }}
|
||||
<div class="grid grid-cols-1 sm:grid-cols-2 gap-x-3">
|
||||
{{ form.amount|as_crispy_field }}
|
||||
{{ form.date|as_crispy_field }}
|
||||
{{ form.paid_by|as_crispy_field }}
|
||||
{{ form.split_type|as_crispy_field }}
|
||||
</div>
|
||||
|
||||
<fieldset class="fieldset my-3">
|
||||
<legend class="fieldset-legend">{% translate 'Split between' %}</legend>
|
||||
<div class="flex flex-col gap-2">
|
||||
{% for row in participant_rows %}
|
||||
<div class="flex items-center justify-between gap-2">
|
||||
<label class="label cursor-pointer flex-1 text-base-content">
|
||||
<input type="checkbox"
|
||||
name="share_participants"
|
||||
value="{{ row.participant.id }}"
|
||||
class="checkbox checkbox-sm"
|
||||
{% if row.selected %}checked{% endif %} />
|
||||
{{ row.participant.name }}
|
||||
</label>
|
||||
<input type="number"
|
||||
step="any"
|
||||
min="0"
|
||||
inputmode="decimal"
|
||||
name="share_value_{{ row.participant.id }}"
|
||||
value="{{ row.value }}"
|
||||
aria-label="{{ row.participant.name }}"
|
||||
class="input input-sm w-32 split-value-input" />
|
||||
</div>
|
||||
{% endfor %}
|
||||
</div>
|
||||
<p class="label" id="split-mode-hint"></p>
|
||||
</fieldset>
|
||||
|
||||
{{ form.notes|as_crispy_field }}
|
||||
{{ form.attachments|as_crispy_field }}
|
||||
{% include 'splits/fragments/attachments_existing.html' with item=expense %}
|
||||
|
||||
<button type="submit" class="btn btn-primary w-full mt-3">
|
||||
{% if expense %}{% translate 'Update' %}{% else %}{% translate 'Add' %}{% endif %}
|
||||
</button>
|
||||
</form>
|
||||
|
||||
<script>
|
||||
(function () {
|
||||
const modeSelect = document.getElementById('id_split_type');
|
||||
const hint = document.getElementById('split-mode-hint');
|
||||
const hints = {
|
||||
EQUAL: "{% translate 'Divided equally between the people checked' %}",
|
||||
EXACT: "{% translate 'Amounts must add up to the total' %}",
|
||||
PERCENTAGE: "{% translate 'Percentages must add up to 100' %}",
|
||||
SHARES: "{% translate 'Weights, e.g. 2 pays twice as much as 1' %}",
|
||||
};
|
||||
const placeholders = {EXACT: "{{ event.currency.code }}", PERCENTAGE: "%", SHARES: "×"};
|
||||
|
||||
function update() {
|
||||
const mode = modeSelect.value;
|
||||
hint.textContent = hints[mode] || '';
|
||||
document.querySelectorAll('.split-value-input').forEach((inp) => {
|
||||
inp.classList.toggle('hidden', mode === 'EQUAL');
|
||||
inp.placeholder = placeholders[mode] || '';
|
||||
});
|
||||
}
|
||||
|
||||
modeSelect.addEventListener('change', update);
|
||||
update();
|
||||
})();
|
||||
</script>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,141 @@
|
||||
{% extends 'extends/offcanvas.html' %}
|
||||
{% load i18n %}
|
||||
|
||||
{% block title %}{% translate 'People' %}{% endblock %}
|
||||
|
||||
{% block body %}
|
||||
<fieldset class="fieldset">
|
||||
<legend class="fieldset-legend">{% translate 'Share link' %}</legend>
|
||||
{% if event.allow_external_access %}
|
||||
<div class="join w-full">
|
||||
<input type="text" id="split-share-url-input" class="input join-item w-full" value="{{ share_url }}" readonly
|
||||
aria-label="{% translate 'Share link' %}" />
|
||||
{# navigator.clipboard needs HTTPS; self-hosted instances often run on plain HTTP #}
|
||||
<button type="button" class="btn btn-primary join-item"
|
||||
onclick="const i = document.getElementById('split-share-url-input'), b = this;
|
||||
const done = () => { b.innerText = '{% translate "Copied!" %}'; setTimeout(() => b.innerText = '{% translate "Copy" %}', 1500); };
|
||||
if (navigator.clipboard && window.isSecureContext) navigator.clipboard.writeText(i.value).then(done);
|
||||
else { i.select(); document.execCommand('copy'); done(); }">{% translate 'Copy' %}</button>
|
||||
</div>
|
||||
<p class="label whitespace-normal">
|
||||
{% translate 'People without an account open this link, pick their name and set a password the first time.' %}
|
||||
</p>
|
||||
<div>
|
||||
<button type="button" class="btn btn-ghost btn-sm text-warning"
|
||||
hx-post="{% url 'split_event_regenerate_link' event_id=event.id %}"
|
||||
hx-target="#generic-offcanvas"
|
||||
hx-trigger="confirmed"
|
||||
data-title="{% translate 'Regenerate share link?' %}"
|
||||
data-text="{% translate 'The current link stops working and everyone signed in through it is signed out.' %}"
|
||||
data-confirm-text="{% translate 'Regenerate' %}"
|
||||
_="install prompt_swal">
|
||||
<i class="fa-solid fa-rotate fa-fw"></i>{% translate 'Regenerate link' %}
|
||||
</button>
|
||||
</div>
|
||||
{% else %}
|
||||
<p class="text-sm text-base-content/70">
|
||||
{% translate 'Link sharing is off. Turn on "Allow external access" in the event settings to share it.' %}
|
||||
</p>
|
||||
{% endif %}
|
||||
</fieldset>
|
||||
|
||||
<fieldset class="fieldset">
|
||||
<legend class="fieldset-legend">{% translate 'Add person without an account' %}</legend>
|
||||
<form hx-post="{% url 'split_participant_add_external' event_id=event.id %}" hx-target="#generic-offcanvas"
|
||||
class="join w-full">
|
||||
<input type="text" name="name" value="{{ external_form.name.value|default:'' }}"
|
||||
placeholder="{% translate 'Name' %}" aria-label="{% translate 'Name' %}"
|
||||
class="input join-item w-full {% if external_form.name.errors %}input-error{% endif %}" required />
|
||||
<button type="submit" class="btn btn-primary join-item">{% translate 'Add' %}</button>
|
||||
</form>
|
||||
{% if external_form.name.errors %}<p class="label text-error">{{ external_form.name.errors.0 }}</p>{% endif %}
|
||||
</fieldset>
|
||||
|
||||
{% if wygiwyh_form.fields.user.queryset.exists %}
|
||||
<fieldset class="fieldset">
|
||||
<legend class="fieldset-legend">{% translate 'Add user' %}</legend>
|
||||
<form hx-post="{% url 'split_participant_add_wygiwyh' event_id=event.id %}" hx-target="#generic-offcanvas"
|
||||
class="flex gap-2 items-start">
|
||||
<div class="flex-1 min-w-0">{{ wygiwyh_form.user }}</div>
|
||||
<button type="submit" class="btn btn-primary">{% translate 'Add' %}</button>
|
||||
</form>
|
||||
{% if wygiwyh_form.user.errors %}<p class="label text-error">{{ wygiwyh_form.user.errors.0 }}</p>{% endif %}
|
||||
</fieldset>
|
||||
{% endif %}
|
||||
|
||||
<fieldset class="fieldset">
|
||||
<legend class="fieldset-legend">{% translate 'Participants' %}</legend>
|
||||
<ul class="list bg-base-200 rounded-box">
|
||||
{% for p in participants %}
|
||||
<li class="list-row items-center {% if not p.is_active %}opacity-60{% endif %}">
|
||||
<div class="list-col-grow min-w-0">
|
||||
<div class="truncate">{{ p.display_name }}</div>
|
||||
<div class="flex flex-wrap gap-1 mt-1">
|
||||
{% if p.is_creator %}<span class="badge badge-xs badge-primary">{% translate 'Organizer' %}</span>{% endif %}
|
||||
{% if p.is_external %}
|
||||
{% if p.is_claimed %}
|
||||
<span class="badge badge-xs badge-ghost">{% translate 'Password set' %}</span>
|
||||
{% else %}
|
||||
<span class="badge badge-xs badge-ghost">{% translate 'Never signed in' %}</span>
|
||||
{% endif %}
|
||||
{% endif %}
|
||||
{% if not p.is_active %}<span class="badge badge-xs badge-warning">{% translate 'Inactive' %}</span>{% endif %}
|
||||
</div>
|
||||
</div>
|
||||
<div class="join">
|
||||
{% if p.is_external and p.is_claimed %}
|
||||
<button type="button" class="btn btn-sm btn-secondary join-item"
|
||||
data-tippy-content="{% translate 'Reset password' %}"
|
||||
aria-label="{% translate 'Reset password' %}"
|
||||
hx-post="{% url 'split_participant_reset_password' event_id=event.id participant_id=p.id %}"
|
||||
hx-target="#generic-offcanvas"
|
||||
hx-trigger="confirmed"
|
||||
data-title="{% translate 'Reset password?' %}"
|
||||
data-text="{% translate 'They will choose a new one the next time they sign in.' %}"
|
||||
data-confirm-text="{% translate 'Reset' %}"
|
||||
_="install prompt_swal">
|
||||
<i class="fa-solid fa-key fa-fw"></i>
|
||||
</button>
|
||||
{% endif %}
|
||||
{% if not p.is_creator %}
|
||||
{% if p.is_active %}
|
||||
<button type="button" class="btn btn-sm btn-secondary join-item"
|
||||
data-tippy-content="{% translate 'Deactivate' %}"
|
||||
aria-label="{% translate 'Deactivate' %}"
|
||||
hx-post="{% url 'split_participant_toggle_active' event_id=event.id participant_id=p.id %}"
|
||||
hx-target="#generic-offcanvas">
|
||||
<i class="fa-solid fa-user-slash fa-fw"></i>
|
||||
</button>
|
||||
{% else %}
|
||||
<button type="button" class="btn btn-sm btn-secondary join-item"
|
||||
data-tippy-content="{% translate 'Reactivate' %}"
|
||||
aria-label="{% translate 'Reactivate' %}"
|
||||
hx-post="{% url 'split_participant_toggle_active' event_id=event.id participant_id=p.id %}"
|
||||
hx-target="#generic-offcanvas">
|
||||
<i class="fa-solid fa-user-check fa-fw"></i>
|
||||
</button>
|
||||
{% endif %}
|
||||
{% if p.deletable %}
|
||||
<button type="button" class="btn btn-sm btn-error join-item"
|
||||
data-tippy-content="{% translate 'Remove' %}"
|
||||
aria-label="{% translate 'Remove' %}"
|
||||
hx-delete="{% url 'split_participant_delete' event_id=event.id participant_id=p.id %}"
|
||||
hx-target="#generic-offcanvas"
|
||||
hx-trigger="confirmed"
|
||||
data-title="{% translate 'Are you sure?' %}"
|
||||
data-text="{% translate "You won't be able to revert this!" %}"
|
||||
data-confirm-text="{% translate 'Yes, delete it!' %}"
|
||||
_="install prompt_swal">
|
||||
<i class="fa-solid fa-trash fa-fw"></i>
|
||||
</button>
|
||||
{% endif %}
|
||||
{% endif %}
|
||||
</div>
|
||||
</li>
|
||||
{% endfor %}
|
||||
</ul>
|
||||
<p class="label whitespace-normal">
|
||||
{% translate "People with expenses or payments can't be removed, only deactivated." %}
|
||||
</p>
|
||||
</fieldset>
|
||||
{% endblock %}
|
||||
@@ -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 %}
|
||||
<form hx-post="{{ post_url }}"
|
||||
hx-target="#generic-offcanvas"
|
||||
hx-encoding="multipart/form-data"
|
||||
novalidate>
|
||||
{% if form.non_field_errors %}
|
||||
<div class="alert alert-error mb-3">{{ form.non_field_errors }}</div>
|
||||
{% endif %}
|
||||
|
||||
<div class="grid grid-cols-1 sm:grid-cols-2 gap-x-3">
|
||||
{{ form.from_participant|as_crispy_field }}
|
||||
{{ form.to_participant|as_crispy_field }}
|
||||
{{ form.amount|as_crispy_field }}
|
||||
{{ form.date|as_crispy_field }}
|
||||
</div>
|
||||
{{ form.notes|as_crispy_field }}
|
||||
{{ form.attachments|as_crispy_field }}
|
||||
{% include 'splits/fragments/attachments_existing.html' with item=payment %}
|
||||
|
||||
<button type="submit" class="btn btn-primary w-full mt-3">
|
||||
{% if payment %}{% translate 'Update' %}{% else %}{% translate 'Record' %}{% endif %}
|
||||
</button>
|
||||
</form>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,66 @@
|
||||
{% extends 'extends/offcanvas.html' %}
|
||||
{% load i18n %}
|
||||
{% load crispy_forms_filters %}
|
||||
|
||||
{% block title %}{{ title }}{% endblock %}
|
||||
|
||||
{% block body %}
|
||||
<form hx-post="{{ post_url }}"
|
||||
hx-target="#generic-offcanvas"
|
||||
novalidate
|
||||
id="split-sync-form">
|
||||
{% if form.non_field_errors %}
|
||||
<div class="alert alert-error mb-3">{{ form.non_field_errors }}</div>
|
||||
{% endif %}
|
||||
|
||||
<div class="join w-full mb-3">
|
||||
<input type="radio" name="mode" value="create" aria-label="{% translate 'Create new' %}"
|
||||
class="join-item btn btn-sm flex-1 sync-mode-radio"
|
||||
{% if form.mode.value != 'link' %}checked{% endif %} />
|
||||
<input type="radio" name="mode" value="link" aria-label="{% translate 'Link existing' %}"
|
||||
class="join-item btn btn-sm flex-1 sync-mode-radio"
|
||||
{% if form.mode.value == 'link' %}checked{% endif %} />
|
||||
</div>
|
||||
|
||||
<div id="sync-create-fields">
|
||||
<p class="text-sm text-base-content/70 mb-2">
|
||||
{% 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 %}
|
||||
</p>
|
||||
{{ form.account|as_crispy_field }}
|
||||
<div class="grid grid-cols-1 sm:grid-cols-2 gap-x-3">
|
||||
{{ form.amount|as_crispy_field }}
|
||||
{{ form.date|as_crispy_field }}
|
||||
</div>
|
||||
{{ 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 }}
|
||||
</div>
|
||||
|
||||
<div id="sync-link-fields" class="hidden">
|
||||
{{ form.existing_transaction|as_crispy_field }}
|
||||
</div>
|
||||
|
||||
<button type="submit" class="btn btn-primary w-full mt-3">{% translate 'Save' %}</button>
|
||||
</form>
|
||||
|
||||
<script>
|
||||
(function () {
|
||||
const form = document.getElementById('split-sync-form');
|
||||
function update() {
|
||||
const linking = form.querySelector('.sync-mode-radio:checked').value === 'link';
|
||||
document.getElementById('sync-create-fields').classList.toggle('hidden', linking);
|
||||
document.getElementById('sync-link-fields').classList.toggle('hidden', !linking);
|
||||
}
|
||||
form.querySelectorAll('.sync-mode-radio').forEach((r) => r.addEventListener('change', update));
|
||||
update();
|
||||
})();
|
||||
</script>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,16 @@
|
||||
{% load i18n %}
|
||||
{% for link in links %}
|
||||
<span class="badge badge-sm {% if link.transaction.is_paid %}badge-success{% else %}badge-info{% endif %} gap-1"
|
||||
data-tippy-content="{% if link.transaction.is_paid %}{% translate 'Linked transaction' %}{% else %}{% translate 'Linked transaction, not paid yet' %}{% endif %}">
|
||||
<i class="fa-solid fa-link fa-fw"></i>{{ link.transaction.account.name }}
|
||||
<button type="button" class="cursor-pointer" aria-label="{% translate 'Unlink' %}"
|
||||
hx-delete="{% url 'split_sync_unlink' event_id=event.id link_id=link.id %}"
|
||||
hx-trigger="confirmed"
|
||||
data-title="{% translate 'Unlink this transaction?' %}"
|
||||
data-text="{% translate 'The transaction itself is kept.' %}"
|
||||
data-confirm-text="{% translate 'Unlink' %}"
|
||||
_="install prompt_swal">
|
||||
<i class="fa-solid fa-xmark fa-fw"></i>
|
||||
</button>
|
||||
</span>
|
||||
{% endfor %}
|
||||
@@ -0,0 +1,9 @@
|
||||
{% extends "layouts/base.html" %}
|
||||
{% load i18n %}
|
||||
|
||||
{% block title %}{{ event.name }} :: {% translate 'Split Expenses' %}{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<div hx-get="{{ urls.event_content }}" hx-trigger="load, updated from:window" class="show-loading"></div>
|
||||
{% include 'splits/fragments/event/export_script.html' %}
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,8 @@
|
||||
{% extends "layouts/base.html" %}
|
||||
{% load i18n %}
|
||||
|
||||
{% block title %}{% translate 'Split Expenses' %}{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<div hx-get="{% url 'split_event_list' %}" hx-trigger="load, updated from:window" class="show-loading"></div>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,149 @@
|
||||
{% load i18n %}
|
||||
{% load title %}
|
||||
{% with c=event.currency %}
|
||||
<!doctype html>
|
||||
<html lang="en" data-theme="wygiwyh_light" class="bg-base-100">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>{% filter site_title %}{{ event.name }} :: {% translate 'Report' %}{% endfilter %}</title>
|
||||
{% include 'includes/head/favicons.html' %}
|
||||
{% include 'includes/styles.html' %}
|
||||
<style>
|
||||
@page { size: A4; margin: 14mm; }
|
||||
tr, li { break-inside: avoid; }
|
||||
h2 { break-after: avoid; }
|
||||
</style>
|
||||
</head>
|
||||
<body class="font-mono bg-base-100 text-base-content">
|
||||
<div class="max-w-3xl mx-auto p-6 print:p-0 flex flex-col gap-8">
|
||||
<div class="flex justify-end gap-2 print:hidden">
|
||||
<button type="button" class="btn btn-primary btn-sm" onclick="window.print()">
|
||||
<i class="fa-solid fa-file-pdf"></i>{% translate 'Save as PDF' %}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<header>
|
||||
<h1 class="text-3xl font-bold text-balance">{{ event.name }}</h1>
|
||||
{% if event.description %}<p class="text-base-content/70 whitespace-pre-line text-pretty mt-1">{{ event.description }}</p>{% endif %}
|
||||
<p class="text-sm text-base-content/60 mt-2 tabular-nums">
|
||||
{% blocktranslate count counter=active_participants_count %}{{ counter }} person{% plural %}{{ counter }} people{% endblocktranslate %}
|
||||
· {% translate 'Group total' %} <c-amount.display :amount="total_spent" :prefix="c.prefix" :suffix="c.suffix" :decimal_places="c.decimal_places" divless></c-amount.display>
|
||||
· {% now "SHORT_DATE_FORMAT" %}
|
||||
</p>
|
||||
</header>
|
||||
|
||||
<section>
|
||||
<h2 class="text-lg font-semibold mb-2">{% translate 'Settle up' %}</h2>
|
||||
{% if transfers %}
|
||||
<table class="table table-sm tabular-nums">
|
||||
<tbody>
|
||||
{% for item in transfers %}{% with t=item.transfer %}
|
||||
<tr>
|
||||
<td>{{ t.from_participant.name }} <i class="fa-solid fa-arrow-right text-xs text-base-content/40 mx-1"></i> {{ t.to_participant.name }}</td>
|
||||
<td class="text-end whitespace-nowrap font-semibold"><c-amount.display :amount="t.amount" :prefix="c.prefix" :suffix="c.suffix" :decimal_places="c.decimal_places" divless></c-amount.display></td>
|
||||
</tr>
|
||||
{% endwith %}{% endfor %}
|
||||
</tbody>
|
||||
</table>
|
||||
{% else %}
|
||||
<p class="text-base-content/70">{% translate 'Everyone is settled up.' %}</p>
|
||||
{% endif %}
|
||||
</section>
|
||||
|
||||
<section>
|
||||
<h2 class="text-lg font-semibold mb-2">{% translate 'Balances' %}</h2>
|
||||
<table class="table table-sm tabular-nums">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>{% translate 'Person' %}</th>
|
||||
<th class="text-end">{% translate 'Paid' %}</th>
|
||||
<th class="text-end">{% translate 'Share' %}</th>
|
||||
<th class="text-end">{% translate 'Sent' %}</th>
|
||||
<th class="text-end">{% translate 'Received' %}</th>
|
||||
<th class="text-end">{% translate 'Balance' %}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{% for row in balance_rows %}{% with b=row.balance %}
|
||||
<tr>
|
||||
<td>{{ b.participant.name }}{% if not b.participant.is_active %} <span class="text-base-content/50">({% translate 'inactive' %})</span>{% endif %}</td>
|
||||
<td class="text-end whitespace-nowrap"><c-amount.display :amount="b.total_paid" :prefix="c.prefix" :suffix="c.suffix" :decimal_places="c.decimal_places" divless></c-amount.display></td>
|
||||
<td class="text-end whitespace-nowrap"><c-amount.display :amount="b.total_owed" :prefix="c.prefix" :suffix="c.suffix" :decimal_places="c.decimal_places" divless></c-amount.display></td>
|
||||
<td class="text-end whitespace-nowrap"><c-amount.display :amount="b.payments_sent" :prefix="c.prefix" :suffix="c.suffix" :decimal_places="c.decimal_places" divless></c-amount.display></td>
|
||||
<td class="text-end whitespace-nowrap"><c-amount.display :amount="b.payments_received" :prefix="c.prefix" :suffix="c.suffix" :decimal_places="c.decimal_places" divless></c-amount.display></td>
|
||||
<td class="text-end whitespace-nowrap font-semibold"><c-amount.display :amount="b.net_balance" :prefix="c.prefix" :suffix="c.suffix" :decimal_places="c.decimal_places" color="auto" divless></c-amount.display></td>
|
||||
</tr>
|
||||
{% endwith %}{% endfor %}
|
||||
</tbody>
|
||||
</table>
|
||||
</section>
|
||||
|
||||
<section>
|
||||
<h2 class="text-lg font-semibold mb-2">{% translate 'Expenses' %}</h2>
|
||||
<table class="table table-sm tabular-nums">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>{% translate 'Date' %}</th>
|
||||
<th>{% translate 'Expense' %}</th>
|
||||
<th class="text-end">{% translate 'Amount' %}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{% for item in activity %}{% if not item.is_payment %}
|
||||
<tr>
|
||||
<td class="whitespace-nowrap align-top">{{ item.date|date:"SHORT_DATE_FORMAT" }}</td>
|
||||
<td>
|
||||
<div class="font-medium">{{ item.description }}</div>
|
||||
<div class="text-xs text-base-content/60">
|
||||
{% blocktranslate with name=item.paid_by.name %}Paid by {{ name }}{% endblocktranslate %}
|
||||
{% if item.split_type != 'EQUAL' %}· {{ item.get_split_type_display }}{% endif %}
|
||||
</div>
|
||||
<div class="text-xs text-base-content/60">
|
||||
{% for s in item.shares.all %}{{ s.participant.name }} <c-amount.display :amount="s.amount" :prefix="c.prefix" :suffix="c.suffix" :decimal_places="c.decimal_places" divless></c-amount.display>{% if not forloop.last %} · {% endif %}{% endfor %}
|
||||
</div>
|
||||
{% if item.notes %}<div class="text-xs text-base-content/60 italic whitespace-pre-line">{{ item.notes }}</div>{% endif %}
|
||||
</td>
|
||||
<td class="text-end whitespace-nowrap align-top"><c-amount.display :amount="item.amount" :prefix="c.prefix" :suffix="c.suffix" :decimal_places="c.decimal_places" divless></c-amount.display></td>
|
||||
</tr>
|
||||
{% endif %}{% endfor %}
|
||||
{% if not expense_count %}<tr><td colspan="3" class="text-base-content/60">{% translate 'No expenses.' %}</td></tr>{% endif %}
|
||||
</tbody>
|
||||
</table>
|
||||
</section>
|
||||
|
||||
<section>
|
||||
<h2 class="text-lg font-semibold mb-2">{% translate 'Payments' %}</h2>
|
||||
<table class="table table-sm tabular-nums">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>{% translate 'Date' %}</th>
|
||||
<th>{% translate 'Payment' %}</th>
|
||||
<th class="text-end">{% translate 'Amount' %}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{% for item in activity %}{% if item.is_payment %}
|
||||
<tr>
|
||||
<td class="whitespace-nowrap align-top">{{ item.date|date:"SHORT_DATE_FORMAT" }}</td>
|
||||
<td>
|
||||
{{ item.from_participant.name }} <i class="fa-solid fa-arrow-right text-xs text-base-content/40 mx-1"></i> {{ item.to_participant.name }}
|
||||
{% if item.notes %}<div class="text-xs text-base-content/60 italic whitespace-pre-line">{{ item.notes }}</div>{% endif %}
|
||||
</td>
|
||||
<td class="text-end whitespace-nowrap align-top"><c-amount.display :amount="item.amount" :prefix="c.prefix" :suffix="c.suffix" :decimal_places="c.decimal_places" divless></c-amount.display></td>
|
||||
</tr>
|
||||
{% endif %}{% endfor %}
|
||||
{% if not payment_count %}<tr><td colspan="3" class="text-base-content/60">{% translate 'No payments.' %}</td></tr>{% endif %}
|
||||
</tbody>
|
||||
</table>
|
||||
</section>
|
||||
</div>
|
||||
|
||||
{% include 'includes/scripts.html' %}
|
||||
<script>
|
||||
// Opened from "Full report (PDF)": go straight to the print dialog once amounts and fonts are in
|
||||
window.addEventListener('load', () => setTimeout(() => window.print(), 300));
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
{% endwith %}
|
||||
@@ -0,0 +1,66 @@
|
||||
{% extends "layouts/base_auth.html" %}
|
||||
{% load i18n %}
|
||||
{% load crispy_forms_filters %}
|
||||
|
||||
{% block title %}{{ event.name }}{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<div class="min-h-screen flex items-center justify-center p-4">
|
||||
<div class="w-full max-w-md">
|
||||
<div class="card bg-base-100 shadow-2xl">
|
||||
<div class="card-body">
|
||||
<h1 class="text-2xl card-title text-balance">{{ event.name }}</h1>
|
||||
{% if event.description %}
|
||||
<p class="text-sm text-base-content/60 text-pretty whitespace-pre-line">{{ event.description }}</p>
|
||||
{% endif %}
|
||||
|
||||
{% if not external_participants %}
|
||||
<p class="mt-2 text-base-content/70">
|
||||
{% translate 'Nobody without an account has been added yet. Ask the organizer to add your name.' %}
|
||||
</p>
|
||||
{% else %}
|
||||
<form method="post" class="mt-2" id="external-auth-form" novalidate>
|
||||
{% csrf_token %}
|
||||
{% if form.non_field_errors %}<div class="alert alert-error mb-3">{{ form.non_field_errors }}</div>{% endif %}
|
||||
{{ form.participant|as_crispy_field }}
|
||||
<p id="first-time-hint" class="text-sm text-base-content/70 my-2 hidden">
|
||||
{% translate 'First time here: pick a password so only you can sign in as this person.' %}
|
||||
</p>
|
||||
<div id="first-time-fields" class="hidden">
|
||||
{{ form.username|as_crispy_field }}
|
||||
</div>
|
||||
{{ form.password|as_crispy_field }}
|
||||
<div id="confirm-field" class="hidden">
|
||||
{{ form.password_confirm|as_crispy_field }}
|
||||
</div>
|
||||
<button type="submit" class="btn btn-primary w-full mt-4" id="auth-submit">{% translate 'Continue' %}</button>
|
||||
</form>
|
||||
{{ claimed_ids|json_script:"split-claimed-ids" }}
|
||||
<script>
|
||||
(function () {
|
||||
const claimed = new Set(JSON.parse(document.getElementById('split-claimed-ids').textContent).map(String));
|
||||
const select = document.getElementById('id_participant');
|
||||
const submit = document.getElementById('auth-submit');
|
||||
function update() {
|
||||
const firstTime = !!select.value && !claimed.has(select.value);
|
||||
['first-time-hint', 'first-time-fields', 'confirm-field'].forEach(
|
||||
(id) => document.getElementById(id).classList.toggle('hidden', !firstTime)
|
||||
);
|
||||
submit.textContent = firstTime ? "{% translate 'Set password and join' %}"
|
||||
: select.value ? "{% translate 'Sign in' %}" : "{% translate 'Continue' %}";
|
||||
}
|
||||
select.addEventListener('change', update);
|
||||
update();
|
||||
// base_auth loads scripts after the content, so set up Tom Select once they're in
|
||||
window.addEventListener('load', () => {
|
||||
select.classList.remove('select');
|
||||
if (!select.tomselect) new TomSelect(select);
|
||||
});
|
||||
})();
|
||||
</script>
|
||||
{% endif %}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,64 @@
|
||||
{% load pwa %}
|
||||
{% load i18n %}
|
||||
{% load title %}
|
||||
<!DOCTYPE html>
|
||||
<html lang="en"
|
||||
data-theme="{% if request.session.theme == 'wygiwyh_light' %}wygiwyh_light{% else %}wygiwyh_dark{% endif %}">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<title>
|
||||
{% filter site_title %}
|
||||
{% block title %}{% translate 'Split Expenses' %}{% endblock title %}
|
||||
{% endfilter %}
|
||||
</title>
|
||||
{% include 'includes/head/favicons.html' %}
|
||||
{% progressive_web_app_meta %}
|
||||
{% block extra_styles %}{% endblock %}
|
||||
{% include 'includes/scripts.html' %}
|
||||
{% block extra_js_head %}{% endblock %}
|
||||
</head>
|
||||
<body class="font-mono">
|
||||
<div _="install htmx_error_handler" hx-headers='{"X-CSRFToken": "{{ csrf_token }}"}'>
|
||||
{% if actor %}
|
||||
<header class="navbar border-b border-base-content/10 px-4">
|
||||
<div class="flex-1 flex items-center gap-3 min-w-0">
|
||||
<div class="logo"></div>
|
||||
<div class="truncate">
|
||||
<span class="font-bold text-lg">{{ event.name }}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="flex-none flex items-center gap-3">
|
||||
<span class="text-sm text-base-content/70 hidden sm:inline">
|
||||
<i class="fa-solid fa-user mr-1"></i>{{ actor.participant.display_name }}
|
||||
</span>
|
||||
<form method="post" action="{% url 'split_external_logout' share_token=event.share_token %}">
|
||||
{% csrf_token %}
|
||||
<button type="submit" class="btn btn-ghost btn-sm">
|
||||
<i class="fa-solid fa-right-from-bracket"></i>
|
||||
<span class="hidden sm:inline">{% translate 'Sign out' %}</span>
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
</header>
|
||||
{% endif %}
|
||||
|
||||
<main class="max-w-6xl mx-auto my-6 px-3">
|
||||
<div id="content">
|
||||
{% block content %}{% endblock content %}
|
||||
</div>
|
||||
{% include "includes/offcanvas.html" %}
|
||||
{% if actor %}
|
||||
<div id="toasts">
|
||||
<div class="toast toast-top toast-end toast-container z-1050"
|
||||
hx-trigger="load, updated from:window, toasts from:window"
|
||||
hx-get="{% url 'split_external_toasts' share_token=event.share_token %}"
|
||||
hx-swap="beforeend">
|
||||
</div>
|
||||
</div>
|
||||
{% endif %}
|
||||
</main>
|
||||
</div>
|
||||
{% block extra_js_body %}{% endblock extra_js_body %}
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,17 @@
|
||||
{% extends "layouts/base_auth.html" %}
|
||||
{% load i18n %}
|
||||
|
||||
{% block title %}{{ event.name }}{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<div class="min-h-screen flex items-center justify-center p-4">
|
||||
<div class="card bg-base-100 shadow-2xl w-full max-w-md">
|
||||
<div class="card-body">
|
||||
<h1 class="text-2xl card-title text-balance">{{ event.name }}</h1>
|
||||
<p class="text-base-content/70">
|
||||
<i class="fa-solid fa-lock me-1"></i>{% translate 'The organizer turned off link access for this event.' %}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,9 @@
|
||||
{% extends "splits/pages/external_base.html" %}
|
||||
{% load i18n %}
|
||||
|
||||
{% block title %}{{ event.name }} :: {% translate 'Split Expenses' %}{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<div hx-get="{{ urls.event_content }}" hx-trigger="load, updated from:window" class="show-loading"></div>
|
||||
{% include 'splits/fragments/event/export_script.html' %}
|
||||
{% endblock %}
|
||||
Generated
+7
@@ -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",
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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;
|
||||
@@ -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';
|
||||
Reference in new issue
Block a user