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.
This commit is contained in:
Herculino Trotta committed 2026-11-14 02:13:21 -03:00
1 parent 9714df8820
commit ae245fb1d1
19 files changed
+595 -15

No files matched your search

+1 -1
View File
@@ -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",
+2 -1
View File
@@ -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,
+1
View File
@@ -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 = []
+1
View File
@@ -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",
+5 -1
View File
@@ -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
+95 -4
View File
@@ -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"),
@@ -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')],
},
),
]
+106 -3
View File
@@ -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()
@@ -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)
+1
View File
@@ -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
@@ -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,
@@ -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,
@@ -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)
@@ -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"
)
@@ -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",
+31 -2
View File
@@ -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 %}
<div
{% if transaction.id and not dummy %}data-transaction-id="{{ transaction.id }}"{% endif %}
class="transaction {% if is_transfer %}transfer{% elif transaction.type == "EX" %}expense{% else %}income{% endif %} group/transaction">
<div class="flex my-1">
class="transaction {% if is_transfer %}transfer{% elif transaction.type == "EX" %}expense{% else %}income{% endif %} group/transaction"
{% if subs %}x-data="{ subsOpen: false }"{% endif %}>
<div class="flex my-1 {% if subs %}mb-6{% endif %}">
{% if not disable_selection or not dummy %}
<label class="px-3 flex! items-center justify-center">
<input class="checkbox" type="checkbox" name="transactions" value="{{ transaction.id }}"
@@ -342,7 +344,34 @@
</div>
{% endif %}
</div>
{% if subs %}
{# Breakdown, opened from the tab hanging under the card; amounts line up with the total #}
<div x-show="subsOpen" x-collapse x-cloak>
<ul class="mt-2 pt-2 border-t border-dashed border-base-content/15 font-mono text-sm lg:ps-12">
{% for sub in subs %}
<li class="flex justify-between gap-4 py-0.5">
<span class="truncate text-base-content/80">{{ sub.name }}</span>
<span class="whitespace-nowrap text-base-content/70"><c-amount.display
:amount="sub.amount"
:prefix="transaction.account.currency.prefix"
:suffix="transaction.account.currency.suffix"
:decimal_places="transaction.account.currency.decimal_places"
divless></c-amount.display></span>
</li>
{% endfor %}
</ul>
</div>
<button type="button"
class="absolute top-full left-1/2 -translate-x-1/2 flex items-center gap-1.5 px-3 pb-0.5 rounded-b-md
bg-base-100 hover:bg-base-200 text-xs font-mono text-base-content/60 hover:text-base-content cursor-pointer"
@click="subsOpen = !subsOpen" :aria-expanded="subsOpen">
<i class="fa-solid fa-list-ul fa-fw"></i>
{% blocktranslate count counter=subs|length %}{{ counter }} item{% plural %}{{ counter }} items{% endblocktranslate %}
<i class="fa-solid fa-chevron-down fa-fw transition-transform duration-200" :class="subsOpen && 'rotate-180'"></i>
</button>
{% endif %}
</div>
</div>
</div>
{% endwith %}
{% endwith %}
@@ -283,8 +283,16 @@
{% endif %}
{% endif %}
</div>
{# Breakdown, e.g. fees and taxes inside a contribution #}
{% with subs=tx.sub_transactions.all %}{% if subs %}
<ul class="mt-1 ps-2 border-s border-base-300 text-xs text-base-content/60">
{% for sub in subs %}
<li class="flex justify-between gap-3"><span>{{ sub.name }}</span><span class="tabular-nums whitespace-nowrap"><c-amount.display :amount="sub.amount" :prefix="a.prefix" :suffix="a.suffix" :decimal_places="a.decimal_places" divless></c-amount.display></span></li>
{% endfor %}
</ul>
{% endif %}{% endwith %}
</td>
<td class="text-end tabular-nums whitespace-nowrap">
<td class="text-end tabular-nums whitespace-nowrap align-top">
<c-amount.display :amount="tx.amount" :prefix="a.prefix" :suffix="a.suffix" :decimal_places="a.decimal_places" color="{% if tx.type == 'IN' %}green{% else %}red{% endif %}" divless></c-amount.display>
{# What the other side paid beats a rate conversion, so it's shown first #}
{% if p and p.account.currency != a %}
@@ -0,0 +1,14 @@
{% load i18n %}
<div class="sub-row" {% if sub.DELETE.value %}hidden{% endif %}>
{{ sub.id }}
<input type="checkbox" name="{{ sub.DELETE.html_name }}" class="hidden" {% if sub.DELETE.value %}checked{% endif %}>
<div class="join w-full">
{{ sub.name }}
{{ sub.amount }}
<button type="button" class="btn btn-soft btn-error join-item" @click="remove($el.closest('.sub-row'))"
aria-label="{% translate 'Remove' %}"><i class="fa-solid fa-xmark fa-fw"></i></button>
</div>
{% for error in sub.non_field_errors %}<div class="text-error text-sm">{{ error }}</div>{% endfor %}
{% for error in sub.name.errors %}<div class="text-error text-sm">{{ error }}</div>{% endfor %}
{% for error in sub.amount.errors %}<div class="text-error text-sm">{{ error }}</div>{% endfor %}
</div>
@@ -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. #}
<div class="fieldset"
x-data="{
count: 0,
total: '',
get transfer() { return this.type === 'TR' },
recalc() {
const rows = [...$refs.rows.querySelectorAll('.sub-row:not([hidden])')];
this.count = rows.length;
const sum = rows.reduce((acc, row) => {
const raw = row.querySelector('[name$=-amount]').value
.replaceAll('{% get_thousand_separator %}', '').replace('{% get_decimal_separator %}', '.');
return acc + (parseFloat(raw) || 0);
}, 0);
this.total = sum.toLocaleString('en-US', {maximumFractionDigits: 20}).replaceAll(',', ' ').replace('.', '{% get_decimal_separator %}').replaceAll(' ', '{% get_thousand_separator %}');
document.getElementById('div_id_{{ form.sub_amount_field }}').hidden = this.count > 0 && !this.transfer;
},
add() {
const total = $refs.rows.parentElement.querySelector('[name=sub-TOTAL_FORMS]');
$refs.rows.insertAdjacentHTML('beforeend', $refs.tpl.innerHTML.replaceAll('__prefix__', total.value));
total.value = +total.value + 1;
this.$nextTick(() => { this.recalc(); $refs.rows.lastElementChild.querySelector('input').focus(); });
},
remove(row) {
row.querySelector('[name$=-DELETE]').checked = true;
row.hidden = true;
this.recalc();
},
}"
x-show="!transfer"
x-effect="transfer; recalc()"
@input="recalc()">
{{ formset.management_form }}
{% for error in formset.non_form_errors %}<div class="text-error text-sm mb-2">{{ error }}</div>{% endfor %}
<span class="fieldset-legend" x-show="count > 0" x-cloak>{% translate 'Sub-transactions' %}</span>
<div x-ref="rows" class="flex flex-col gap-2">
{% for sub in formset %}
{% include "transactions/widgets/sub_transaction_row.html" with sub=sub %}
{% endfor %}
</div>
<template x-ref="tpl">
{% include "transactions/widgets/sub_transaction_row.html" with sub=formset.empty_form %}
</template>
<div class="flex items-center justify-between gap-2">
<button type="button" class="btn btn-ghost btn-sm" @click="add()">
<i class="fa-solid fa-plus fa-fw"></i>{% translate 'Add sub-transaction' %}
</button>
<span class="text-sm tabular-nums" x-show="count > 0" x-cloak>{% translate 'Total' %}: <span class="font-semibold" x-text="total"></span></span>
</div>
</div>
{% endwith %}