mirror of
https://github.com/eitchtee/WYGIWYH.git
synced 2026-11-22 00:21:50 +01:00
feat(api): expose split expenses in the REST API and MCP
Add /api/splits/ endpoints for events, participants, expenses and payments, plus an event summary (balances and settle-up) and leave action. They share the web UI's access rules and share calculation. MCP reaches them through search_api/call_api, and its instructions now point to them.
This commit is contained in:
1 parent
77bf2d7bdb
commit
fe2e366a74
7 files changed
+772
-3
No files matched your search
+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()
|
||||
Reference in new issue
Block a user