From ae245fb1d1d8101b9e1553f732db2b8c2742ee83 Mon Sep 17 00:00:00 2001 From: Herculino Trotta Date: Sat, 14 Nov 2026 02:13:21 -0300 Subject: [PATCH] feat(transactions): add sub-transactions Splits a transaction into named parts whose amounts add up to its amount, e.g. the items of a big purchase or the fees inside an investment contribution. Parts can be set on transactions, installment plans, recurring and quick transactions, and are copied to the transactions they generate. Transfers can't have parts. Transactions show their parts under a tab on the card and in the investment detail. The content filter matches part names, and bulk edits leave the amount of split transactions alone. --- app/apps/calendar_view/views.py | 2 +- app/apps/insights/views.py | 3 +- app/apps/investments/views.py | 1 + app/apps/monthly_overview/views.py | 1 + app/apps/transactions/filters.py | 6 +- app/apps/transactions/forms.py | 99 +++++++- .../migrations/0053_sub_transaction.py | 34 +++ app/apps/transactions/models.py | 109 ++++++++- .../tests/test_sub_transactions.py | 223 ++++++++++++++++++ app/apps/transactions/views/actions.py | 1 + app/apps/transactions/views/conversions.py | 7 + .../transactions/views/installment_plans.py | 2 +- .../transactions/views/quick_transactions.py | 1 + .../views/recurring_transactions.py | 2 +- app/apps/transactions/views/transactions.py | 4 + app/templates/cotton/transaction/item.html | 33 ++- .../investments/fragments/detail.html | 10 +- .../widgets/sub_transaction_row.html | 14 ++ .../widgets/sub_transactions.html | 58 +++++ 19 files changed, 595 insertions(+), 15 deletions(-) create mode 100644 app/apps/transactions/migrations/0053_sub_transaction.py create mode 100644 app/apps/transactions/tests/test_sub_transactions.py create mode 100644 app/templates/transactions/widgets/sub_transaction_row.html create mode 100644 app/templates/transactions/widgets/sub_transactions.html diff --git a/app/apps/calendar_view/views.py b/app/apps/calendar_view/views.py index bf03bb44..852e06a2 100644 --- a/app/apps/calendar_view/views.py +++ b/app/apps/calendar_view/views.py @@ -66,7 +66,7 @@ def calendar_list(request, month: int, year: int): @require_http_methods(["GET"]) def calendar_transactions_list(request, day: int, month: int, year: int): date = datetime.date(year=year, month=month, day=day) - transactions = Transaction.objects.filter(date=date).collapse_transfers().order_by( + transactions = Transaction.objects.filter(date=date).collapse_transfers().prefetch_related("sub_transactions").order_by( "date", "-type", "-is_paid", diff --git a/app/apps/insights/views.py b/app/apps/insights/views.py index f0a806e5..ff4e2857 100644 --- a/app/apps/insights/views.py +++ b/app/apps/insights/views.py @@ -308,6 +308,7 @@ def latest_transactions(request): transactions = ( Transaction.objects.filter(created_at__gte=limit) .collapse_transfers() + .prefetch_related("sub_transactions") .order_by("-id")[:30] ) @@ -325,7 +326,7 @@ def late_transactions(request): now = timezone.localdate(timezone.now()) transactions = Transaction.objects.filter( is_paid=False, date__lt=now - ).collapse_transfers() + ).collapse_transfers().prefetch_related("sub_transactions") return render( request, diff --git a/app/apps/investments/views.py b/app/apps/investments/views.py index ddc18c45..417f0658 100644 --- a/app/apps/investments/views.py +++ b/app/apps/investments/views.py @@ -215,6 +215,7 @@ def investment_detail(request, account_id): "account__currency__exchange_currency", "account__exchange_currency", ) + .prefetch_related("sub_transactions") .order_by("-date", "-id")[:50] ) income = [] diff --git a/app/apps/monthly_overview/views.py b/app/apps/monthly_overview/views.py index f0f85a20..01876021 100644 --- a/app/apps/monthly_overview/views.py +++ b/app/apps/monthly_overview/views.py @@ -93,6 +93,7 @@ def transactions_list(request, month: int, year: int): "installment_plan", "entities", "dca_expense_entries", + "sub_transactions", "dca_income_entries", "linked_transaction__account__currency", "linked_transaction__account__group", diff --git a/app/apps/transactions/filters.py b/app/apps/transactions/filters.py index 2a940a48..784598ca 100644 --- a/app/apps/transactions/filters.py +++ b/app/apps/transactions/filters.py @@ -6,6 +6,7 @@ from apps.common.widgets.decimal import ArbitraryDecimalDisplayNumberInput from apps.common.widgets.tom_select import TomSelectMultiple from apps.currencies.models import Currency from apps.transactions.models import ( + SubTransaction, Transaction, TransactionCategory, TransactionEntity, @@ -31,7 +32,10 @@ MUTE_STATUS_CHOICES = ( def content_filter(queryset, name, value): queryset = queryset.filter( - Q(description__icontains=value) | Q(notes__icontains=value) + Q(description__icontains=value) + | Q(notes__icontains=value) + # a subquery, so a transaction with several matching parts isn't listed twice + | Q(pk__in=SubTransaction.objects.filter(name__icontains=value).values("transaction")) ) return queryset diff --git a/app/apps/transactions/forms.py b/app/apps/transactions/forms.py index 743dea1c..24ebe568 100644 --- a/app/apps/transactions/forms.py +++ b/app/apps/transactions/forms.py @@ -17,6 +17,7 @@ from apps.transactions.models import ( TransactionAttachment, QuickTransaction, RecurringTransaction, + SubTransaction, Transaction, TransactionCategory, TransactionEntity, @@ -54,7 +55,89 @@ class MultipleFileField(forms.FileField): return [] -class TransactionForm(forms.ModelForm): +class SubTransactionForm(forms.ModelForm): + class Meta: + model = SubTransaction + fields = ["name", "amount"] + widgets = { + "name": forms.TextInput( + attrs={"class": "input join-item flex-1", "placeholder": _("Name")} + ), + } + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + # Built per request so the mask uses the user's number format + self.fields["amount"].widget = ArbitraryDecimalDisplayNumberInput( + attrs={ + "class": "input join-item w-2/5", + "inputmode": "decimal", + "placeholder": _("Amount"), + } + ) + + +class SubTransactionsFormMixin: + """Adds sub-transactions to a transaction or template form; while there are any, + the amount field is their sum. Transfers don't take them. + + Rendered by transactions/widgets/sub_transactions.html, placed after the amount. + """ + + sub_amount_field = "amount" + + def __init__(self, *args, sub_transactions_initial=None, **kwargs): + super().__init__(*args, **kwargs) + data = self.data if self.is_bound else None + if data is not None and "sub-TOTAL_FORMS" not in data: + # Posts without the formset (e.g. shortcuts to /add/) leave sub-transactions alone + data = {"sub-TOTAL_FORMS": "0", "sub-INITIAL_FORMS": "0"} + initial = sub_transactions_initial or [] + self.sub_transactions = forms.inlineformset_factory( + type(self.instance), + SubTransaction, + form=SubTransactionForm, + extra=len(initial), + can_delete=True, + )(data, instance=self.instance, prefix="sub", initial=initial) + # With sub-transactions the amount is their sum, see clean() + self.fields[self.sub_amount_field].required = False + + def _takes_sub_transactions(self): + return self.cleaned_data.get("type") != "TR" + + def clean(self): + cleaned_data = super().clean() + field = self.sub_amount_field + if self._takes_sub_transactions() and self.sub_transactions.is_valid(): + amounts = [ + f.cleaned_data["amount"] + for f in self.sub_transactions.forms + if f.cleaned_data and not f.cleaned_data.get("DELETE") + ] + if amounts: + cleaned_data[field] = sum(amounts) + if cleaned_data.get(field) is None and field not in self.errors: + self.add_error(field, self.fields[field].error_messages["required"]) + return cleaned_data + + def is_valid(self): + return super().is_valid() and ( + not self._takes_sub_transactions() or self.sub_transactions.is_valid() + ) + + def save(self, *args, **kwargs): + with db_transaction.atomic(): + instance = super().save(*args, **kwargs) + if self._takes_sub_transactions(): + self.sub_transactions.instance = instance + self.sub_transactions.save() + else: + instance.sub_transactions.all().delete() + return instance + + +class TransactionForm(SubTransactionsFormMixin, forms.ModelForm): category = DynamicModelChoiceField( create_field="name", model=TransactionCategory, @@ -164,6 +247,7 @@ class TransactionForm(forms.ModelForm): ), "description", Field("amount", inputmode="decimal"), + HTML('{% include "transactions/widgets/sub_transactions.html" %}'), Row( Column("category"), Column("tags"), @@ -187,6 +271,7 @@ class TransactionForm(forms.ModelForm): ), "description", Field("amount", inputmode="decimal"), + HTML('{% include "transactions/widgets/sub_transactions.html" %}'), Accordion( AccordionGroup( _("More"), @@ -322,7 +407,7 @@ def _type_aware(form, *layout): ) -class QuickTransactionForm(forms.ModelForm): +class QuickTransactionForm(SubTransactionsFormMixin, forms.ModelForm): category = DynamicModelChoiceField( create_field="name", model=TransactionCategory, @@ -432,6 +517,7 @@ class QuickTransactionForm(forms.ModelForm): ), "description", Field("amount", inputmode="decimal"), + HTML('{% include "transactions/widgets/sub_transactions.html" %}'), _transfer_fields(self), Row( Column("category"), @@ -833,7 +919,9 @@ class TransferForm(forms.Form): return from_transaction, to_transaction -class InstallmentPlanForm(forms.ModelForm): +class InstallmentPlanForm(SubTransactionsFormMixin, forms.ModelForm): + sub_amount_field = "installment_amount" + account = forms.ModelChoiceField( queryset=Account.objects.filter(is_archived=False), label=_("Account"), @@ -956,6 +1044,7 @@ class InstallmentPlanForm(forms.ModelForm): Column("recurrence", css_class="col-span-12 md:col-span-4"), ), "installment_amount", + HTML('{% include "transactions/widgets/sub_transactions.html" %}'), Row( Column("category"), Column("tags"), @@ -989,6 +1078,7 @@ class InstallmentPlanForm(forms.ModelForm): # Take the amount set on the form, even if already paid source_transaction.amount = instance.installment_amount source_transaction.save() + source_transaction.copy_sub_transactions_from(instance) instance.update_transactions() elif is_new: instance.create_transactions() @@ -1085,7 +1175,7 @@ class TransactionCategoryForm(forms.ModelForm): ) -class RecurringTransactionForm(forms.ModelForm): +class RecurringTransactionForm(SubTransactionsFormMixin, forms.ModelForm): account = forms.ModelChoiceField( queryset=Account.objects.filter(is_archived=False), label=_("Account"), @@ -1209,6 +1299,7 @@ class RecurringTransactionForm(forms.ModelForm): "description", Switch("add_description_to_transaction"), "amount", + HTML('{% include "transactions/widgets/sub_transactions.html" %}'), _transfer_fields(self), Row( Column("category"), diff --git a/app/apps/transactions/migrations/0053_sub_transaction.py b/app/apps/transactions/migrations/0053_sub_transaction.py new file mode 100644 index 00000000..85f003fa --- /dev/null +++ b/app/apps/transactions/migrations/0053_sub_transaction.py @@ -0,0 +1,34 @@ +# Generated by Django 5.2.17 on 2026-11-13 22:22 + +import apps.transactions.validators +import django.db.models.deletion +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('transactions', '0052_transfer_templates'), + ] + + operations = [ + migrations.CreateModel( + name='SubTransaction', + fields=[ + ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('name', models.CharField(max_length=255, verbose_name='Name')), + ('amount', models.DecimalField(decimal_places=30, max_digits=42, validators=[apps.transactions.validators.validate_non_negative, apps.transactions.validators.validate_decimal_places], verbose_name='Amount')), + ('installment_plan', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='sub_transactions', to='transactions.installmentplan')), + ('quick_transaction', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='sub_transactions', to='transactions.quicktransaction')), + ('recurring_transaction', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='sub_transactions', to='transactions.recurringtransaction')), + ('transaction', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='sub_transactions', to='transactions.transaction', verbose_name='Transaction')), + ], + options={ + 'verbose_name': 'Sub-transaction', + 'verbose_name_plural': 'Sub-transactions', + 'db_table': 'sub_transactions', + 'ordering': ['id'], + 'constraints': [models.CheckConstraint(condition=models.Q(models.Q(('installment_plan__isnull', True), ('quick_transaction__isnull', True), ('recurring_transaction__isnull', True), ('transaction__isnull', False)), models.Q(('installment_plan__isnull', True), ('quick_transaction__isnull', True), ('recurring_transaction__isnull', False), ('transaction__isnull', True)), models.Q(('installment_plan__isnull', False), ('quick_transaction__isnull', True), ('recurring_transaction__isnull', True), ('transaction__isnull', True)), models.Q(('installment_plan__isnull', True), ('quick_transaction__isnull', False), ('recurring_transaction__isnull', True), ('transaction__isnull', True)), _connector='OR'), name='sub_transaction_has_one_parent')], + }, + ), + ] diff --git a/app/apps/transactions/models.py b/app/apps/transactions/models.py index e928b062..da76eaf9 100644 --- a/app/apps/transactions/models.py +++ b/app/apps/transactions/models.py @@ -1,6 +1,8 @@ import calendar import decimal +import functools import logging +import operator import uuid from copy import deepcopy from pathlib import Path @@ -444,9 +446,10 @@ class Transaction(OwnedObject): if isinstance(self.amount, (str, int, float)): self.amount = decimal.Decimal(str(self.amount)) - self.amount = truncate_decimal( - value=self.amount, decimal_places=account.currency.decimal_places - ) + if self.amount is not None: # missing amount is reported by field validation + self.amount = truncate_decimal( + value=self.amount, decimal_places=account.currency.decimal_places + ) # Normalize reference_date if self.reference_date: @@ -572,6 +575,24 @@ class Transaction(OwnedObject): def hard_delete(self, *args, **kwargs): super().delete(*args, **kwargs) + @property + def has_sub_transactions(self): + return bool(self.pk) and self.sub_transactions.exists() + + @property + def saved_sub_transactions(self): + """Sub-transactions, or none for an unsaved preview (which can't query them).""" + return self.sub_transactions.all() if self.pk else [] + + def copy_sub_transactions_from(self, source): + """Makes this transaction's sub-transactions copies of ``source``'s (a + transaction or a template that generates them).""" + self.sub_transactions.all().delete() + SubTransaction.objects.bulk_create( + SubTransaction(transaction=self, name=sub.name, amount=sub.amount) + for sub in source.sub_transactions.all() + ) + def exchanged_amount(self): return self._exchanged_to( self.account.exchange_currency or self.account.currency.exchange_currency @@ -658,6 +679,81 @@ class Transaction(OwnedObject): return new_obj +SUB_TRANSACTION_PARENTS = ( + "transaction", + "recurring_transaction", + "installment_plan", + "quick_transaction", +) + + +class SubTransaction(models.Model): + """A named part of a transaction, or of a template that generates them; when + present, the parts add up to its amount. Exactly one parent is set. + + Soft deletion follows the parent: sub-transactions are only reached through it. + """ + + transaction = models.ForeignKey( + Transaction, + on_delete=models.CASCADE, + null=True, + blank=True, + related_name="sub_transactions", + verbose_name=_("Transaction"), + ) + recurring_transaction = models.ForeignKey( + "RecurringTransaction", + on_delete=models.CASCADE, + null=True, + blank=True, + related_name="sub_transactions", + ) + installment_plan = models.ForeignKey( + "InstallmentPlan", + on_delete=models.CASCADE, + null=True, + blank=True, + related_name="sub_transactions", + ) + quick_transaction = models.ForeignKey( + "QuickTransaction", + on_delete=models.CASCADE, + null=True, + blank=True, + related_name="sub_transactions", + ) + name = models.CharField(max_length=255, verbose_name=_("Name")) + amount = models.DecimalField( + max_digits=42, + decimal_places=30, + verbose_name=_("Amount"), + validators=[validate_non_negative, validate_decimal_places], + ) + + class Meta: + verbose_name = _("Sub-transaction") + verbose_name_plural = _("Sub-transactions") + db_table = "sub_transactions" + ordering = ["id"] + constraints = [ + models.CheckConstraint( + # One of: only "transaction" set, only "recurring_transaction" set, ... + condition=functools.reduce( + operator.or_, + ( + Q(**{f"{p}__isnull": p != parent for p in SUB_TRANSACTION_PARENTS}) + for parent in SUB_TRANSACTION_PARENTS + ), + ), + name="sub_transaction_has_one_parent", + ) + ] + + def __str__(self): + return self.name + + class TransactionAttachment(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) transaction = models.ForeignKey( @@ -855,6 +951,7 @@ class InstallmentPlan(models.Model): ) new_transaction.tags.set(self.tags.all()) new_transaction.entities.set(self.entities.all()) + new_transaction.copy_sub_transactions_from(self) @transaction.atomic def update_transactions(self): @@ -896,6 +993,7 @@ class InstallmentPlan(models.Model): not existing_transaction.is_paid ): # Don't update value for paid transactions existing_transaction.amount = self.installment_amount + existing_transaction.copy_sub_transactions_from(self) existing_transaction.save() @@ -922,6 +1020,7 @@ class InstallmentPlan(models.Model): ) new_transaction.tags.set(self.tags.all()) new_transaction.entities.set(self.entities.all()) + new_transaction.copy_sub_transactions_from(self) # Remove any extra transactions that are no longer part of the plan self.transactions.filter( @@ -1127,6 +1226,7 @@ class RecurringTransaction(TransferTemplate): # different one, and the scoped default manager would hide private rows. created_transaction.tags.set(self.tags(manager="all_objects").all()) created_transaction.entities.set(self.entities(manager="all_objects").all()) + created_transaction.copy_sub_transactions_from(self) self.complete_transfer(created_transaction) def adopt_transaction(self, existing_transaction, date, reference_date): @@ -1169,6 +1269,7 @@ class RecurringTransaction(TransferTemplate): existing_transaction.save() existing_transaction.tags.set(self.tags(manager="all_objects").all()) existing_transaction.entities.set(self.entities(manager="all_objects").all()) + existing_transaction.copy_sub_transactions_from(self) def get_recurrence_delta(self): if self.recurrence_type == self.RecurrenceType.DAY: @@ -1286,6 +1387,8 @@ class RecurringTransaction(TransferTemplate): self.entities(manager="all_objects").all() ) + existing_transaction.copy_sub_transactions_from(self) + # Save updated transaction existing_transaction.save() diff --git a/app/apps/transactions/tests/test_sub_transactions.py b/app/apps/transactions/tests/test_sub_transactions.py new file mode 100644 index 00000000..12eda71c --- /dev/null +++ b/app/apps/transactions/tests/test_sub_transactions.py @@ -0,0 +1,223 @@ +from decimal import Decimal + +from django.contrib.auth import get_user_model +from django.test import TestCase, override_settings +from django.urls import reverse +from django.utils import timezone +from rest_framework.test import APIClient + +from apps.accounts.models import Account, AccountGroup +from apps.currencies.models import Currency +from apps.transactions.models import ( + InstallmentPlan, + QuickTransaction, + RecurringTransaction, + SubTransaction, + Transaction, +) +from apps.transactions.filters import content_filter, exclude_matching +from apps.transactions.views.actions import clone_transaction + + +def _subs(*rows, initial=0): + data = {"sub-TOTAL_FORMS": str(len(rows)), "sub-INITIAL_FORMS": str(initial)} + for i, row in enumerate(rows): + data.update({f"sub-{i}-{k}": v for k, v in row.items()}) + return data + + +@override_settings( + STORAGES={ + "default": {"BACKEND": "django.core.files.storage.FileSystemStorage"}, + "staticfiles": {"BACKEND": "django.contrib.staticfiles.storage.StaticFilesStorage"}, + }, + WHITENOISE_AUTOREFRESH=True, +) +class SubTransactionTests(TestCase): + def setUp(self): + user = get_user_model().objects.create_user(email="u@test.com", password="pw") + self.client.login(username="u@test.com", password="pw") + currency = Currency.objects.create(code="USD", name="USD", decimal_places=2) + self.account = Account.objects.create( + name="A", group=AccountGroup.objects.create(name="G"), currency=currency + ) + self.base = { + "account": self.account.id, + "type": "EX", + "is_paid": True, + "date": timezone.localdate().isoformat(), + "description": "Groceries", + } + + def _add(self, data): + return self.client.post( + reverse("transaction_add"), {**data, "submit": ""}, headers={"HX-Request": "true"} + ) + + def test_amount_is_sum_of_sub_transactions(self): + response = self._add( + {**self.base, "amount": "999", **_subs( + {"name": "Milk", "amount": "2.50"}, {"name": "Bread", "amount": "4"} + )} + ) + self.assertEqual(response.status_code, 204) + transaction = Transaction.objects.get() + self.assertEqual(transaction.amount, Decimal("6.50")) + self.assertEqual( + list(transaction.sub_transactions.values_list("name", flat=True)), + ["Milk", "Bread"], + ) + + def test_amount_required_without_sub_transactions(self): + response = self._add({**self.base, **_subs()}) + self.assertEqual(response.status_code, 200) + self.assertIn("amount", response.context["form"].errors) + self.assertFalse(Transaction.objects.exists()) + + def test_sub_transaction_needs_name(self): + response = self._add({**self.base, **_subs({"name": "", "amount": "3"})}) + self.assertEqual(response.status_code, 200) + self.assertFalse(Transaction.objects.exists()) + + def test_edit_removing_sub_transactions_restores_typed_amount(self): + transaction = Transaction.objects.create( + account=self.account, type="EX", date=timezone.localdate(), amount=5 + ) + sub = SubTransaction.objects.create(transaction=transaction, name="Fee", amount=5) + response = self.client.post( + reverse("transaction_edit", kwargs={"transaction_id": transaction.id}), + {**self.base, "amount": "12", **_subs( + {"id": sub.id, "name": "Fee", "amount": "5", "DELETE": "on"}, initial=1 + )}, + headers={"HX-Request": "true"}, + ) + self.assertEqual(response.status_code, 204) + transaction.refresh_from_db() + self.assertEqual(transaction.amount, Decimal("12")) + self.assertFalse(transaction.sub_transactions.exists()) + + @override_settings(ENABLE_SOFT_DELETE=True) + def test_soft_delete_hides_and_hard_delete_removes_sub_transactions(self): + transaction = Transaction.objects.create( + account=self.account, type="EX", date=timezone.localdate(), amount=5 + ) + SubTransaction.objects.create(transaction=transaction, name="Fee", amount=5) + url = reverse("transaction_delete", kwargs={"transaction_id": transaction.id}) + self.client.delete(url, headers={"HX-Request": "true"}) + # soft: sub-transactions stay with (and are hidden by) the deleted parent + self.assertTrue(Transaction.deleted_objects.filter(pk=transaction.pk).exists()) + self.assertEqual(SubTransaction.objects.count(), 1) + self.client.delete(url, headers={"HX-Request": "true"}) + self.assertFalse(SubTransaction.objects.exists()) + + def test_clone_copies_sub_transactions(self): + transaction = Transaction.objects.create( + account=self.account, type="EX", date=timezone.localdate(), amount=5 + ) + SubTransaction.objects.create(transaction=transaction, name="Fee", amount=5) + clone = clone_transaction(transaction) + self.assertEqual(list(clone.sub_transactions.values_list("name", "amount")), [("Fee", Decimal("5"))]) + + def test_content_filter_matches_sub_transaction_names(self): + shop = Transaction.objects.create( + account=self.account, type="EX", date=timezone.localdate(), amount=5, description="Shop" + ) + SubTransaction.objects.create(transaction=shop, name="Milk", amount=2) + SubTransaction.objects.create(transaction=shop, name="Oat milk", amount=3) + other = Transaction.objects.create( + account=self.account, type="EX", date=timezone.localdate(), amount=1, description="Bus" + ) + everything = Transaction.all_objects.all() + self.assertEqual(list(content_filter(everything, "description", "milk")), [shop]) + self.assertEqual(list(exclude_matching(content_filter)(everything, "x", "milk")), [other]) + + def test_bulk_edit_leaves_amount_of_split_transactions(self): + split = Transaction.objects.create( + account=self.account, type="EX", date=timezone.localdate(), amount=5 + ) + SubTransaction.objects.create(transaction=split, name="Fee", amount=5) + plain = Transaction.objects.create( + account=self.account, type="EX", date=timezone.localdate(), amount=1 + ) + response = self.client.post( + reverse("transactions_bulk_edit"), + {"transactions": [split.id, plain.id], "amount": "50", "description": "Edited"}, + headers={"HX-Request": "true"}, + ) + self.assertEqual(response.status_code, 204) + split.refresh_from_db() + plain.refresh_from_db() + self.assertEqual((split.amount, split.description), (Decimal("5"), "Edited")) + self.assertEqual(plain.amount, Decimal("50")) + + def _post(self, url_name, data): + return self.client.post(reverse(url_name), data, headers={"HX-Request": "true"}) + + def _parts(self, transaction): + return list(transaction.sub_transactions.values_list("name", "amount")) + + def test_quick_transaction_parts_are_copied_to_created_transaction(self): + self._post( + "quick_transaction_add", + {**self.base, "name": "Lunch", **_subs({"name": "Meal", "amount": "20"}, {"name": "Tip", "amount": "2"})}, + ) + quick = QuickTransaction.objects.get() + self.assertEqual(quick.amount, Decimal("22")) + self.client.get( + reverse("quick_transaction_add_as_transaction", kwargs={"quick_transaction_id": quick.id}), + headers={"HX-Request": "true"}, + ) + transaction = Transaction.objects.get() + self.assertEqual(transaction.amount, Decimal("22")) + self.assertEqual(self._parts(transaction), [("Meal", Decimal("20")), ("Tip", Decimal("2"))]) + + def test_quick_transfer_drops_parts(self): + other = Account.objects.create(name="B", group=self.account.group, currency=self.account.currency) + response = self._post( + "quick_transaction_add", + {**self.base, "type": "TR", "to_account": other.id, "amount": "5", "name": "Move", + **_subs({"name": "Hidden", "amount": "9"})}, + ) + self.assertEqual(response.status_code, 204) + quick = QuickTransaction.objects.get() + self.assertEqual(quick.amount, Decimal("5")) + self.assertFalse(quick.sub_transactions.exists()) + + def test_recurring_parts_follow_generated_and_unpaid_transactions(self): + self._post( + "recurring_transaction_add", + {**self.base, "start_date": timezone.localdate().isoformat(), "recurrence_type": "month", + "recurrence_interval": 1, "keep_at_most": 2, **_subs({"name": "Plan", "amount": "10"})}, + ) + recurring = RecurringTransaction.all_objects.get() + self.assertEqual(recurring.amount, Decimal("10")) + generated = recurring.transactions.all() + self.assertTrue(generated) + for transaction in generated: + self.assertEqual(self._parts(transaction), [("Plan", Decimal("10"))]) + + sub = recurring.sub_transactions.get() + self.client.post( + reverse("recurring_transaction_edit", kwargs={"recurring_transaction_id": recurring.id}), + {**self.base, "start_date": timezone.localdate().isoformat(), "recurrence_type": "month", + "recurrence_interval": 1, "keep_at_most": 2, + **_subs({"id": sub.id, "name": "Plan", "amount": "10"}, {"name": "Tax", "amount": "1"}, initial=1)}, + headers={"HX-Request": "true"}, + ) + for transaction in recurring.transactions.all(): + self.assertEqual(transaction.amount, Decimal("11")) + self.assertEqual(len(self._parts(transaction)), 2) + + def test_installment_parts_are_copied_to_each_installment(self): + self._post( + "installment_plan_add", + {**self.base, "number_of_installments": 2, "installment_start": 1, + "start_date": timezone.localdate().isoformat(), "recurrence": "monthly", + **_subs({"name": "Principal", "amount": "90"}, {"name": "Interest", "amount": "10"})}, + ) + plan = InstallmentPlan.all_objects.get() + self.assertEqual(plan.installment_amount, Decimal("100")) + self.assertEqual(plan.transactions.count(), 2) + for transaction in plan.transactions.all(): + self.assertEqual(transaction.amount, Decimal("100")) + self.assertEqual(len(self._parts(transaction)), 2) diff --git a/app/apps/transactions/views/actions.py b/app/apps/transactions/views/actions.py index fdaf3a0f..287e9ca8 100644 --- a/app/apps/transactions/views/actions.py +++ b/app/apps/transactions/views/actions.py @@ -32,6 +32,7 @@ def _copy(transaction): new_transaction.tags.add(*transaction.tags.all()) new_transaction.entities.add(*transaction.entities.all()) + new_transaction.copy_sub_transactions_from(transaction) return new_transaction diff --git a/app/apps/transactions/views/conversions.py b/app/apps/transactions/views/conversions.py index 8d57d5f4..6a6b5911 100644 --- a/app/apps/transactions/views/conversions.py +++ b/app/apps/transactions/views/conversions.py @@ -37,6 +37,10 @@ def _initial_from_transaction(transaction: Transaction): return initial +def _sub_transactions_initial(transaction: Transaction): + return list(transaction.sub_transactions.values("name", "amount")) + + def _get_unlinked_transaction(transaction_id): # Transactions already generated by a plan or recurrence can't be converted again return get_object_or_404( @@ -78,6 +82,7 @@ def transaction_convert_to_quick_transaction(request, transaction_id): ) else: form = QuickTransactionForm( + sub_transactions_initial=_sub_transactions_initial(transaction), initial={ **_initial_from_transaction(transaction), "is_paid": transaction.is_paid, @@ -114,6 +119,7 @@ def transaction_convert_to_recurring_transaction(request, transaction_id): ) else: form = RecurringTransactionForm( + sub_transactions_initial=_sub_transactions_initial(transaction), initial={ **_initial_from_transaction(transaction), "amount": transaction.amount, @@ -154,6 +160,7 @@ def transaction_convert_to_installment_plan(request, transaction_id): ) else: form = InstallmentPlanForm( + sub_transactions_initial=_sub_transactions_initial(transaction), initial={ **_initial_from_transaction(transaction), "installment_amount": transaction.amount, diff --git a/app/apps/transactions/views/installment_plans.py b/app/apps/transactions/views/installment_plans.py index f2927591..5f1fd192 100644 --- a/app/apps/transactions/views/installment_plans.py +++ b/app/apps/transactions/views/installment_plans.py @@ -67,7 +67,7 @@ def finished_installment_plans_list(request): @require_http_methods(["GET"]) def installment_plan_transactions(request, installment_plan_id): installment_plan = get_object_or_404(InstallmentPlan, id=installment_plan_id) - transactions = installment_plan.transactions.all().order_by("reference_date", "id") + transactions = installment_plan.transactions.prefetch_related("sub_transactions").order_by("reference_date", "id") return render( request, diff --git a/app/apps/transactions/views/quick_transactions.py b/app/apps/transactions/views/quick_transactions.py index 0c60e438..59af0192 100644 --- a/app/apps/transactions/views/quick_transactions.py +++ b/app/apps/transactions/views/quick_transactions.py @@ -155,6 +155,7 @@ def quick_transaction_add_as_transaction(request, quick_transaction_id): new_transaction.save() new_transaction.tags.set(quick_transaction.tags.all()) new_transaction.entities.set(quick_transaction.entities.all()) + new_transaction.copy_sub_transactions_from(quick_transaction) to_transaction = quick_transaction.complete_transfer(new_transaction) transaction_created.send(sender=new_transaction) diff --git a/app/apps/transactions/views/recurring_transactions.py b/app/apps/transactions/views/recurring_transactions.py index d12cfd9a..bca4fb18 100644 --- a/app/apps/transactions/views/recurring_transactions.py +++ b/app/apps/transactions/views/recurring_transactions.py @@ -90,7 +90,7 @@ def recurring_transaction_transactions(request, recurring_transaction_id): recurring_transaction = get_object_or_404( RecurringTransaction, id=recurring_transaction_id ) - transactions = recurring_transaction.transactions.collapse_transfers().order_by( + transactions = recurring_transaction.transactions.collapse_transfers().prefetch_related("sub_transactions").order_by( "reference_date", "id" ) diff --git a/app/apps/transactions/views/transactions.py b/app/apps/transactions/views/transactions.py index 9ca4e68d..29040c27 100644 --- a/app/apps/transactions/views/transactions.py +++ b/app/apps/transactions/views/transactions.py @@ -409,6 +409,8 @@ def transactions_bulk_edit(request): transaction.tags.set(value) elif field_name == "entities": transaction.entities.set(value) + elif field_name == "amount" and transaction.has_sub_transactions: + continue # its amount is the sum of its parts else: setattr(transaction, field_name, value) @@ -802,6 +804,7 @@ def transaction_all_list(request): "installment_plan", "entities", "dca_expense_entries", + "sub_transactions", "dca_income_entries", "linked_transaction__account__currency", "linked_transaction__account__group", @@ -971,6 +974,7 @@ def transactions_trash_can_list(request): "installment_plan", "entities", "dca_expense_entries", + "sub_transactions", "dca_income_entries", "linked_transaction__account__currency", "linked_transaction__account__group", diff --git a/app/templates/cotton/transaction/item.html b/app/templates/cotton/transaction/item.html index 5275b51d..8c5d6490 100644 --- a/app/templates/cotton/transaction/item.html +++ b/app/templates/cotton/transaction/item.html @@ -2,10 +2,12 @@ {% load i18n %} {# With "Combine transfers" on, a transfer is shown once: its "from" side with the "to" side alongside #} {% with transaction=transaction.display_transaction transfer_to=transaction.transfer_to is_transfer=transaction.shown_as_transfer %} +{% with subs=transaction.saved_sub_transactions %}
-
+ class="transaction {% if is_transfer %}transfer{% elif transaction.type == "EX" %}expense{% else %}income{% endif %} group/transaction" + {% if subs %}x-data="{ subsOpen: false }"{% endif %}> +
{% if not disable_selection or not dummy %}
+ {% if subs %} + {# Breakdown, opened from the tab hanging under the card; amounts line up with the total #} +
+
    + {% for sub in subs %} +
  • + {{ sub.name }} + +
  • + {% endfor %} +
+
+ + {% endif %}
{% endwith %} +{% endwith %} diff --git a/app/templates/investments/fragments/detail.html b/app/templates/investments/fragments/detail.html index 2f31ad2d..e5342855 100644 --- a/app/templates/investments/fragments/detail.html +++ b/app/templates/investments/fragments/detail.html @@ -283,8 +283,16 @@ {% endif %} {% endif %} + {# Breakdown, e.g. fees and taxes inside a contribution #} + {% with subs=tx.sub_transactions.all %}{% if subs %} + + {% endif %}{% endwith %} - + {# What the other side paid beats a rate conversion, so it's shown first #} {% if p and p.account.currency != a %} diff --git a/app/templates/transactions/widgets/sub_transaction_row.html b/app/templates/transactions/widgets/sub_transaction_row.html new file mode 100644 index 00000000..014fc4ba --- /dev/null +++ b/app/templates/transactions/widgets/sub_transaction_row.html @@ -0,0 +1,14 @@ +{% load i18n %} +
+ {{ sub.id }} + +
+ {{ sub.name }} + {{ sub.amount }} + +
+ {% for error in sub.non_field_errors %}
{{ error }}
{% endfor %} + {% for error in sub.name.errors %}
{{ error }}
{% endfor %} + {% for error in sub.amount.errors %}
{{ error }}
{% endfor %} +
diff --git a/app/templates/transactions/widgets/sub_transactions.html b/app/templates/transactions/widgets/sub_transactions.html new file mode 100644 index 00000000..92f22928 --- /dev/null +++ b/app/templates/transactions/widgets/sub_transactions.html @@ -0,0 +1,58 @@ +{% load i18n formats %} +{% with formset=form.sub_transactions %} +{# The amount is the sum of these rows, so it's hidden while there are any. #} +{# Transfers don't take them; `type` comes from the form's _type_aware scope when it has one. #} +
+ {{ formset.management_form }} + {% for error in formset.non_form_errors %}
{{ error }}
{% endfor %} + + {% translate 'Sub-transactions' %} + +
+ {% for sub in formset %} + {% include "transactions/widgets/sub_transaction_row.html" with sub=sub %} + {% endfor %} +
+ + + +
+ + {% translate 'Total' %}: +
+
+{% endwith %}