diff --git a/app/apps/api/serializers/transactions.py b/app/apps/api/serializers/transactions.py index 05d51c08..8628ffde 100644 --- a/app/apps/api/serializers/transactions.py +++ b/app/apps/api/serializers/transactions.py @@ -1,5 +1,6 @@ from decimal import Decimal +from django.db import transaction as db_transaction from django.utils.translation import gettext_lazy as _ from drf_spectacular import openapi from drf_spectacular.types import OpenApiTypes @@ -22,10 +23,85 @@ from apps.transactions.models import ( InstallmentPlan, TransactionEntity, RecurringTransaction, + SubTransaction, ) from apps.common.middleware.thread_local import get_current_user +class SubTransactionSerializer(serializers.ModelSerializer): + class Meta: + model = SubTransaction + fields = ["id", "name", "amount"] + read_only_fields = ["id"] + + +class SubTransactionsMixin: + """`sub_transactions`, when sent, replaces the parts; a non-empty list sets + the amount to their sum. Declare the field on the serializer itself.""" + + sub_amount_field = "amount" + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self.fields[self.sub_amount_field].required = False + + def is_transfer(self, data): + return False + + def validate(self, data): + field = self.sub_amount_field + subs = data.get("sub_transactions") + has_parts = self.instance is not None and self.instance.sub_transactions.exists() + if self.is_transfer(data): + if subs: + raise serializers.ValidationError( + {"sub_transactions": _("Transfers can't have sub-transactions.")} + ) + if has_parts: + data["sub_transactions"] = [] + elif subs: + data[field] = sum(sub["amount"] for sub in subs) + elif subs is None and field in data and has_parts: + raise serializers.ValidationError( + { + field: _( + "The amount is the sum of the sub-transactions; " + "send sub_transactions instead." + ) + } + ) + if not self.partial and data.get(field) is None: + raise serializers.ValidationError({field: _("This field is required.")}) + return super().validate(data) + + @staticmethod + def set_sub_transactions(instance, subs): + if subs is None: + return + instance.sub_transactions.all().delete() + for sub in subs: + instance.sub_transactions.create(**sub) + + def create(self, validated_data): + subs = validated_data.pop("sub_transactions", None) + with db_transaction.atomic(): + instance = super().create(validated_data) + self.set_sub_transactions(instance, subs) + self.after_save(instance, created=True) + return instance + + def update(self, instance, validated_data): + subs = validated_data.pop("sub_transactions", None) + with db_transaction.atomic(): + instance = super().update(instance, validated_data) + self.set_sub_transactions(instance, subs) + self.after_save(instance, created=False) + return instance + + def after_save(self, instance, created): + """Runs once the parts are saved, e.g. to generate transactions from them.""" + + class TransactionCategorySerializer(serializers.ModelSerializer): permission_classes = [IsAuthenticated] @@ -62,7 +138,9 @@ class TransactionEntitySerializer(serializers.ModelSerializer): ] -class InstallmentPlanSerializer(serializers.ModelSerializer): +class InstallmentPlanSerializer(SubTransactionsMixin, serializers.ModelSerializer): + sub_amount_field = "installment_amount" + sub_transactions = SubTransactionSerializer(many=True, required=False) category: str | int = TransactionCategoryField(required=False) tags: str | int = TransactionTagField(required=False) entities: str | int = TransactionEntityField(required=False) @@ -84,6 +162,7 @@ class InstallmentPlanSerializer(serializers.ModelSerializer): "end_date", "recurrence", "installment_amount", + "sub_transactions", "category", "tags", "entities", @@ -91,18 +170,15 @@ class InstallmentPlanSerializer(serializers.ModelSerializer): ] read_only_fields = ["installment_total_number", "end_date"] - def create(self, validated_data): - instance = super().create(validated_data) - instance.create_transactions() - return instance - - def update(self, instance, validated_data): - instance = super().update(instance, validated_data) - instance.update_transactions() - return instance + def after_save(self, instance, created): + if created: + instance.create_transactions() + else: + instance.update_transactions() -class RecurringTransactionSerializer(serializers.ModelSerializer): +class RecurringTransactionSerializer(SubTransactionsMixin, serializers.ModelSerializer): + sub_transactions = SubTransactionSerializer(many=True, required=False) category: str | int = TransactionCategoryField(required=False) tags: str | int = TransactionTagField(required=False) entities: str | int = TransactionEntityField(required=False) @@ -115,6 +191,7 @@ class RecurringTransactionSerializer(serializers.ModelSerializer): "account", "type", "amount", + "sub_transactions", "to_account", "to_amount", "description", @@ -142,19 +219,20 @@ class RecurringTransactionSerializer(serializers.ModelSerializer): ) return super().validate(attrs) - def create(self, validated_data): - instance = super().create(validated_data) - instance.create_upcoming_transactions() - return instance + def is_transfer(self, data): + type_ = data.get("type", getattr(self.instance, "type", None)) + return type_ == RecurringTransaction.Type.TRANSFER - def update(self, instance, validated_data): - instance = super().update(instance, validated_data) - instance.update_unpaid_transactions() - instance.generate_upcoming_transactions() - return instance + def after_save(self, instance, created): + if created: + instance.create_upcoming_transactions() + else: + instance.update_unpaid_transactions() + instance.generate_upcoming_transactions() -class TransactionSerializer(serializers.ModelSerializer): +class TransactionSerializer(SubTransactionsMixin, serializers.ModelSerializer): + sub_transactions = SubTransactionSerializer(many=True, required=False) category: str | int = TransactionCategoryField(required=False) tags: str | int = TransactionTagField(required=False) entities: str | int = TransactionEntityField(required=False) @@ -194,6 +272,9 @@ class TransactionSerializer(serializers.ModelSerializer): self.fields["account_id"].queryset = Account.objects.all() + def is_transfer(self, data): + return bool(self.instance and self.instance.linked_transaction_id) + def validate(self, data): if not self.partial: if "date" in data and "reference_date" not in data: @@ -204,12 +285,12 @@ class TransactionSerializer(serializers.ModelSerializer): raise serializers.ValidationError( _("Either 'date' or 'reference_date' must be provided.") ) - return data + return super().validate(data) def create(self, validated_data): tags = validated_data.pop("tags", []) entities = validated_data.pop("entities", []) - transaction = Transaction.objects.create(**validated_data) + transaction = super().create(validated_data) transaction.tags.set(tags) transaction.entities.set(entities) return transaction @@ -217,9 +298,7 @@ class TransactionSerializer(serializers.ModelSerializer): def update(self, instance, validated_data): tags = validated_data.pop("tags", None) entities = validated_data.pop("entities", None) - for attr, value in validated_data.items(): - setattr(instance, attr, value) - instance.save() + instance = super().update(instance, validated_data) if tags is not None: instance.tags.set(tags) diff --git a/app/apps/api/views/transactions.py b/app/apps/api/views/transactions.py index fdc00030..50e11517 100644 --- a/app/apps/api/views/transactions.py +++ b/app/apps/api/views/transactions.py @@ -52,7 +52,7 @@ class TransactionViewSet(viewsets.ModelViewSet): ordering = ["-id"] def get_queryset(self): - return Transaction.objects.all() + return Transaction.objects.prefetch_related("sub_transactions") def perform_create(self, serializer): instance = serializer.save() @@ -145,7 +145,7 @@ class InstallmentPlanViewSet(viewsets.ModelViewSet): ordering = ["-id"] def get_queryset(self): - return InstallmentPlan.objects.all() + return InstallmentPlan.objects.prefetch_related("sub_transactions") class RecurringTransactionViewSet(viewsets.ModelViewSet): @@ -175,4 +175,4 @@ class RecurringTransactionViewSet(viewsets.ModelViewSet): ordering = ["-id"] def get_queryset(self): - return RecurringTransaction.objects.all() + return RecurringTransaction.objects.prefetch_related("sub_transactions") 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/common/management/commands/load_demo_data.py b/app/apps/common/management/commands/load_demo_data.py index 8455e0c1..b17b86c1 100644 --- a/app/apps/common/management/commands/load_demo_data.py +++ b/app/apps/common/management/commands/load_demo_data.py @@ -118,6 +118,12 @@ class Command(BaseCommand): out.save() return out, inc + def split(self, owner, *parts): + """Breaks `owner` into named parts; call before it generates transactions.""" + for name, amount in parts: + owner.sub_transactions.create(name=name, amount=Decimal(amount)) + return owner + def rate(self, series, months): return series[months + HISTORY_MONTHS] @@ -278,6 +284,7 @@ class Command(BaseCommand): notes="12 interest-free installments on the credit card.", ) laptop.entities.set([self.ents["BuyMore"]]) + self.split(laptop, ("Laptop", "99.90"), ("Extended warranty", "8.35")) laptop.create_transactions() dental = InstallmentPlan.objects.create( account=checking, type=EX, description="Dental treatment", @@ -289,7 +296,8 @@ class Command(BaseCommand): # Recurring transactions def recurring(account, amount, description, category, start, entity=None, - recurrence=RecurringTransaction.RecurrenceType.MONTH, paused=False): + recurrence=RecurringTransaction.RecurrenceType.MONTH, paused=False, + parts=()): r = RecurringTransaction.objects.create( account=account, type=EX, amount=amount, description=description, category=self.cats[category], start_date=start, recurrence_type=recurrence, @@ -297,6 +305,7 @@ class Command(BaseCommand): ) if entity: r.entities.set([self.ents[entity]]) + self.split(r, *parts) if not paused: r.create_upcoming_transactions() return r @@ -304,7 +313,8 @@ class Command(BaseCommand): recurring(card, Decimal("15.99"), "StreamFlix", "Subscriptions", self.day(-HISTORY_MONTHS, 3), "StreamFlix") recurring(checking, Decimal("59.99"), "Internet", "Utilities", - self.day(-HISTORY_MONTHS, 15), "FiberNet") + self.day(-HISTORY_MONTHS, 15), "FiberNet", + parts=[("Internet plan", "49.99"), ("Router rental", "10.00")]) recurring(checking, Decimal("39.90"), "Gym membership", "Health", self.day(-HISTORY_MONTHS, 2), "Iron Gym") recurring(card, Decimal("14.99"), "Domain renewal", "Subscriptions", @@ -458,8 +468,9 @@ class Command(BaseCommand): self.transfer(stock_acc, checking, Decimal("3"), self.day(-2, 21), "Sell AAPL", to_amount=q(3 * self.rate(aapl_usd, -2)), mute=False, category="Investments") - self.tx(retirement, EX, Decimal("45.00"), self.day(-6, 30), "Annual management fee", - "Fees") + fee = self.tx(retirement, EX, Decimal("45.00"), self.day(-6, 30), + "Annual management fee", "Fees") + self.split(fee, ("Management fee", "40.00"), ("Custody fee", "5.00")) for m, spent in ((-9, 1500), (-3, 800)): self.transfer(checking, gold_acc, Decimal(spent), self.day(m, 12), "Buy gold", to_amount=q(Decimal(spent) / self.rate(gold_usd, m)), mute=False, @@ -489,6 +500,11 @@ class Command(BaseCommand): notes="Very old transactions are no problem.") self.transfer(old_bank, checking, Decimal("1200.00"), self.day(-HISTORY_MONTHS, 3), "Closing old bank account", category="Transfers") + # One receipt, split into what was bought + shop = self.tx(card, EX, Decimal("87.35"), self.day(-1, 24), "Big grocery shop", + "Groceries", ["essentials", "home"], ["Fresh Market"]) + self.split(shop, ("Produce", "24.80"), ("Meat & fish", "38.15"), + ("Household supplies", "16.40"), ("Snacks", "8.00")) # Balance reconciliation: the wallet had less cash than recorded self.tx(cash, EX, Decimal("12.40"), self.day(-2, 28), "Balance reconciliation") @@ -511,6 +527,7 @@ class Command(BaseCommand): description="Lunch", category=self.cats["Dining"], ) lunch.tags.set([self.tags["work"]]) + self.split(lunch, ("Meal", "11.90"), ("Tip", "2.00")) # Rules run on transactions you create or edit ride = TransactionRule.objects.create( diff --git a/app/apps/common/tests/test_demo_data.py b/app/apps/common/tests/test_demo_data.py index 54eeb246..7a54625e 100644 --- a/app/apps/common/tests/test_demo_data.py +++ b/app/apps/common/tests/test_demo_data.py @@ -10,7 +10,12 @@ from apps.accounts.models import Account from apps.common.middleware.thread_local import delete_current_user, write_current_user from apps.dca.models import DCAStrategy from apps.investments.services import get_holding_performance -from apps.transactions.models import Transaction +from apps.transactions.models import ( + InstallmentPlan, + QuickTransaction, + RecurringTransaction, + Transaction, +) @override_settings( @@ -73,6 +78,21 @@ class LoadDemoDataTests(TestCase): self.assertNotEqual(apple.realized, 0) # partial sale self.assertTrue(perfs["Retirement Fund"].results) # gains and losses + def test_sub_transactions_add_up(self): + self.load(date(2031, 7, 14)) + owners = [ + *Transaction.all_objects.filter(sub_transactions__isnull=False).distinct(), + *RecurringTransaction.all_objects.filter(sub_transactions__isnull=False).distinct(), + *QuickTransaction.objects.filter(sub_transactions__isnull=False).distinct(), + ] + plans = InstallmentPlan.all_objects.filter(sub_transactions__isnull=False).distinct() + self.assertTrue(plans) + self.assertGreater(len(owners), len(plans)) + for owner in [*owners, *plans]: + with self.subTest(owner=str(owner)): + amount = getattr(owner, "installment_amount", None) or owner.amount + self.assertEqual(sum(s.amount for s in owner.sub_transactions.all()), amount) + def test_running_twice_is_a_no_op(self): self.load(date(2031, 7, 14)) count = Transaction.all_objects.count() diff --git a/app/apps/export_app/forms.py b/app/apps/export_app/forms.py index caa436c8..7d50ffb1 100644 --- a/app/apps/export_app/forms.py +++ b/app/apps/export_app/forms.py @@ -61,6 +61,12 @@ class ExportForm(forms.Form): label=_("Installment Plans"), initial=True, ) + quick_transactions = forms.BooleanField( + required=False, + widget=forms.CheckboxInput(), + label=_("Quick Transactions"), + initial=True, + ) exchange_rates = forms.BooleanField( required=False, widget=forms.CheckboxInput(), @@ -116,6 +122,7 @@ class ExportForm(forms.Form): "tags", "installment_plans", "recurring_transactions", + "quick_transactions", "exchange_rates_services", "exchange_rates", "bank_sync", @@ -142,10 +149,12 @@ class RestoreForm(forms.Form): transactions_tags = forms.FileField(required=False, label=_("Tags")) transactions_entities = forms.FileField(required=False, label=_("Entities")) transactions = forms.FileField(required=False, label=_("Transactions")) + sub_transactions = forms.FileField(required=False, label=_("Sub-transactions")) installment_plans = forms.FileField(required=False, label=_("Installment Plans")) recurring_transactions = forms.FileField( required=False, label=_("Recurring Transactions") ) + quick_transactions = forms.FileField(required=False, label=_("Quick Transactions")) automatic_exchange_rates = forms.FileField( required=False, label=_("Automatic Exchange Rates") ) @@ -180,11 +189,13 @@ class RestoreForm(forms.Form): "accounts", "currencies", "transactions", + "sub_transactions", "transactions_categories", "transactions_entities", "transactions_tags", "installment_plans", "recurring_transactions", + "quick_transactions", "automatic_exchange_rates", "exchange_rates", "bank_sync_services", diff --git a/app/apps/export_app/resources/transactions.py b/app/apps/export_app/resources/transactions.py index dbcb0f14..1abde7ca 100644 --- a/app/apps/export_app/resources/transactions.py +++ b/app/apps/export_app/resources/transactions.py @@ -1,4 +1,9 @@ +from functools import reduce +from operator import or_ + +from django.db.models import Q from import_export import fields, resources +from import_export.widgets import ForeignKeyWidget from apps.accounts.models import Account from apps.export_app.widgets.foreign_key import ( @@ -14,6 +19,8 @@ from apps.transactions.models import ( TransactionEntity, RecurringTransaction, InstallmentPlan, + QuickTransaction, + SubTransaction, ) from apps.export_app.widgets.numbers import UniversalDecimalWidget @@ -166,3 +173,106 @@ class InstallmentPlanResource(resources.ModelResource): def dehydrate_account_owner(self, obj): """Export the account's owner ID for proper import matching.""" return obj.account.owner_id if obj.account else None + + +class AnyOwnerForeignKeyWidget(ForeignKeyWidget): + """Finds the parent among every user's rows, soft-deleted ones included.""" + + def get_queryset(self, value, row, *args, **kwargs): + return self.model._base_manager.all() + + +class QuickTransactionResource(resources.ModelResource): + account = fields.Field( + attribute="account", + column_name="account", + widget=AllObjectsForeignKeyWidget(Account, "name"), + ) + to_account = fields.Field( + attribute="to_account", + column_name="to_account", + widget=AllObjectsForeignKeyWidget(Account, "name"), + ) + category = fields.Field( + attribute="category", + column_name="category", + widget=AutoCreateForeignKeyWidget(TransactionCategory, "name"), + ) + tags = fields.Field( + attribute="tags", + column_name="tags", + widget=AutoCreateManyToManyWidget(TransactionTag, field="name"), + ) + entities = fields.Field( + attribute="entities", + column_name="entities", + widget=AutoCreateManyToManyWidget(TransactionEntity, field="name"), + ) + internal_id = EmptyStringToNoneField( + column_name="internal_id", attribute="internal_id" + ) + amount = fields.Field( + attribute="amount", + column_name="amount", + widget=UniversalDecimalWidget(), + ) + to_amount = fields.Field( + attribute="to_amount", + column_name="to_amount", + widget=UniversalDecimalWidget(), + ) + + class Meta: + model = QuickTransaction + + def get_queryset(self): + return QuickTransaction.all_objects.all() + + +SUB_TRANSACTION_BACKUP_PARENTS = ( + "transaction", + "installment_plan", + "recurring_transaction", + "quick_transaction", +) + + +class SubTransactionResource(resources.ModelResource): + transaction = fields.Field( + attribute="transaction", + column_name="transaction", + widget=AnyOwnerForeignKeyWidget(Transaction), + ) + installment_plan = fields.Field( + attribute="installment_plan", + column_name="installment_plan", + widget=AnyOwnerForeignKeyWidget(InstallmentPlan), + ) + recurring_transaction = fields.Field( + attribute="recurring_transaction", + column_name="recurring_transaction", + widget=AnyOwnerForeignKeyWidget(RecurringTransaction), + ) + quick_transaction = fields.Field( + attribute="quick_transaction", + column_name="quick_transaction", + widget=AnyOwnerForeignKeyWidget(QuickTransaction), + ) + amount = fields.Field( + attribute="amount", + column_name="amount", + widget=UniversalDecimalWidget(), + ) + + def __init__(self, parents=SUB_TRANSACTION_BACKUP_PARENTS, **kwargs): + """`parents`: the kinds of parent being exported, whose parts go along.""" + super().__init__(**kwargs) + self.parents = parents + + class Meta: + model = SubTransaction + + def get_queryset(self): + return SubTransaction.objects.filter( + reduce(or_, (Q(**{f"{p}__isnull": False}) for p in self.parents), Q(pk__in=[])) + ) diff --git a/app/apps/export_app/tests.py b/app/apps/export_app/tests.py index e70c0357..e929864c 100644 --- a/app/apps/export_app/tests.py +++ b/app/apps/export_app/tests.py @@ -1,4 +1,5 @@ import io +from datetime import date import zipfile from decimal import Decimal @@ -9,9 +10,21 @@ from apps.accounts.models import Account, InvestmentClass from apps.common.middleware.thread_local import delete_current_user, write_current_user from apps.currencies.models import Currency from apps.export_app.resources.accounts import AccountResource, InvestmentClassResource -from apps.export_app.resources.transactions import TransactionEntityResource +from apps.export_app.resources.transactions import ( + InstallmentPlanResource, + QuickTransactionResource, + SubTransactionResource, + TransactionEntityResource, + TransactionResource, +) from apps.export_app.views import process_imports -from apps.transactions.models import TransactionEntity +from apps.transactions.models import ( + InstallmentPlan, + QuickTransaction, + SubTransaction, + Transaction, + TransactionEntity, +) class InvestmentRestoreTests(TestCase): @@ -51,3 +64,58 @@ class InvestmentRestoreTests(TestCase): self.assertEqual(account.investment_class.name, "Stocks") self.assertEqual(account.investment_class.target, Decimal("60")) self.assertEqual([e.name for e in account.income_entities.all()], ["Broker"]) + + +class SubTransactionBackupTests(TestCase): + def setUp(self): + self.user = get_user_model().objects.create_user(email="s@test.com", password="pw") + write_current_user(self.user) + self.addCleanup(delete_current_user) + account = Account.objects.create( + name="A", currency=Currency.objects.create(code="USD", name="USD", decimal_places=2) + ) + self.transaction = Transaction.objects.create( + account=account, type="EX", date=date(2030, 1, 10), amount=5 + ) + self.plan = InstallmentPlan.objects.create( + account=account, type="EX", description="Laptop", number_of_installments=2, + start_date=date(2030, 1, 10), installment_amount=100, + ) + SubTransaction.objects.create(transaction=self.transaction, name="Fee", amount="1.25") + SubTransaction.objects.create(transaction=self.transaction, name="Item", amount="3.75") + SubTransaction.objects.create(installment_plan=self.plan, name="Principal", amount=100) + lunch = QuickTransaction.objects.create( + name="Lunch", account=account, type="EX", amount=Decimal("13.90") + ) + SubTransaction.objects.create(quick_transaction=lunch, name="Meal", amount="11.90") + SubTransaction.objects.create(quick_transaction=lunch, name="Tip", amount=2) + + def _parts(self): + return sorted( + SubTransaction.objects.values_list( + "name", "transaction", "installment_plan", "quick_transaction__name", "amount" + ) + ) + + def test_round_trip_puts_parts_back_on_their_parents(self): + before = self._parts() + backup = io.BytesIO() + with zipfile.ZipFile(backup, "w") as z: + for resource, name in ( + (TransactionResource(), "transactions"), + (InstallmentPlanResource(), "installment_plans"), + (QuickTransactionResource(), "quick_transactions"), + (SubTransactionResource(), "sub_transactions"), + ): + z.writestr(f"{name}.csv", resource.export().csv) + + SubTransaction.objects.all().delete() + QuickTransaction.all_objects.all().delete() + backup.seek(0) + process_imports(None, {"zip_file": backup}) + + self.assertEqual(self._parts(), before) + + def test_exports_only_the_parts_of_exported_parents(self): + dataset = SubTransactionResource(parents=["installment_plan"]).export() + self.assertEqual([row["name"] for row in dataset.dict], ["Principal"]) diff --git a/app/apps/export_app/views.py b/app/apps/export_app/views.py index c413d3e4..3a521ddc 100644 --- a/app/apps/export_app/views.py +++ b/app/apps/export_app/views.py @@ -46,6 +46,8 @@ from apps.export_app.resources.transactions import ( TransactionCategoyResource, InstallmentPlanResource, RecurringTransactionResource, + QuickTransactionResource, + SubTransactionResource, ) from apps.export_app.resources.users import UserResource from apps.common.decorators.demo import disabled_on_demo @@ -84,6 +86,9 @@ def export_form(request): export_recurring_transactions = form.cleaned_data.get( "recurring_transactions", False ) + export_quick_transactions = form.cleaned_data.get( + "quick_transactions", False + ) export_exchange_rates_services = form.cleaned_data.get( "exchange_rates_services", False @@ -123,6 +128,27 @@ def export_form(request): exports.append( (RecurringTransactionResource().export(), "recurring_transactions") ) + if export_quick_transactions: + exports.append( + (QuickTransactionResource().export(), "quick_transactions") + ) + sub_transaction_parents = [ + parent + for parent, exported in ( + ("transaction", export_transactions), + ("installment_plan", export_installment_plans), + ("recurring_transaction", export_recurring_transactions), + ("quick_transaction", export_quick_transactions), + ) + if exported + ] + if sub_transaction_parents: + exports.append( + ( + SubTransactionResource(parents=sub_transaction_parents).export(), + "sub_transactions", + ) + ) if export_exchange_rates_services: exports.append( (ExchangeRateServiceResource().export(), "automatic_exchange_rates") @@ -250,7 +276,9 @@ def process_imports(request, cleaned_data): ("exchange_rates", ExchangeRateResource), ("installment_plans", InstallmentPlanResource), ("recurring_transactions", RecurringTransactionResource), + ("quick_transactions", QuickTransactionResource), ("transactions", TransactionResource), + ("sub_transactions", SubTransactionResource), ("bank_sync_services", BankSyncServiceResource), ("bank_sync_accounts", BankSyncAccountResource), ("dca_strategies", DCAStrategyResource), 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/rules/forms.py b/app/apps/rules/forms.py index b5b39357..d001efbf 100644 --- a/app/apps/rules/forms.py +++ b/app/apps/rules/forms.py @@ -190,6 +190,7 @@ class UpdateOrCreateTransactionRuleActionForm(forms.ModelForm): "set_date": _("Date"), "set_reference_date": _("Reference Date"), "set_amount": _("Amount"), + "set_sub_transactions": _("Sub-transactions"), "set_description": _("Description"), "set_tags": _("Tags"), "set_entities": _("Entities"), @@ -367,6 +368,7 @@ class UpdateOrCreateTransactionRuleActionForm(forms.ModelForm): Field("set_reference_date", rows=1), Field("set_description", rows=1), Field("set_amount", rows=1), + Field("set_sub_transactions", rows=1), Field("set_category", rows=1), Field("set_tags", rows=1), Field("set_notes", rows=1), diff --git a/app/apps/rules/migrations/0019_sub_transactions.py b/app/apps/rules/migrations/0019_sub_transactions.py new file mode 100644 index 00000000..4106d3f7 --- /dev/null +++ b/app/apps/rules/migrations/0019_sub_transactions.py @@ -0,0 +1,23 @@ +# Generated by Django 5.2.17 on 2026-11-14 03:08 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('rules', '0018_transactionrule_order'), + ] + + operations = [ + migrations.AddField( + model_name='updateorcreatetransactionruleaction', + name='set_sub_transactions', + field=models.TextField(blank=True, verbose_name='Sub-transactions'), + ), + migrations.AlterField( + model_name='transactionruleaction', + name='field', + field=models.CharField(choices=[('account', 'Account'), ('type', 'Type'), ('is_paid', 'Paid'), ('date', 'Date'), ('reference_date', 'Reference Date'), ('mute', 'Mute'), ('amount', 'Amount'), ('sub_transactions', 'Sub-transactions'), ('description', 'Description'), ('notes', 'Notes'), ('category', 'Category'), ('tags', 'Tags'), ('entities', 'Entities'), ('internal_nome', 'Internal Note'), ('internal_id', 'Internal ID')], max_length=50, verbose_name='Field'), + ), + ] diff --git a/app/apps/rules/models.py b/app/apps/rules/models.py index 653c87c7..85259278 100644 --- a/app/apps/rules/models.py +++ b/app/apps/rules/models.py @@ -39,6 +39,7 @@ class TransactionRuleAction(models.Model): reference_date = "reference_date", _("Reference Date") mute = "mute", _("Mute") amount = "amount", _("Amount") + sub_transactions = "sub_transactions", _("Sub-transactions") description = "description", _("Description") notes = "notes", _("Notes") category = "category", _("Category") @@ -315,6 +316,10 @@ class UpdateOrCreateTransactionRuleAction(models.Model): verbose_name=_("Tags"), blank=True, ) + set_sub_transactions = models.TextField( + verbose_name=_("Sub-transactions"), + blank=True, + ) set_mute = models.TextField( verbose_name=_("Mute"), blank=True, diff --git a/app/apps/rules/tasks.py b/app/apps/rules/tasks.py index 427be97d..ba4573c1 100644 --- a/app/apps/rules/tasks.py +++ b/app/apps/rules/tasks.py @@ -17,12 +17,14 @@ from procrastinate.contrib.django import app from simpleeval import EvalWithCompoundTypes from apps.accounts.models import Account +from apps.common.functions.decimals import truncate_decimal from apps.common.middleware.thread_local import write_current_user, delete_current_user from apps.rules.models import ( TransactionRule, TransactionRuleAction, ) from apps.transactions.models import ( + SubTransaction, Transaction, TransactionCategory, TransactionTag, @@ -32,6 +34,39 @@ from apps.rules.utils import transactions logger = logging.getLogger(__name__) +SUB_TRANSACTIONS_SHAPE = ( + "Sub-transactions must be a list like [{'name': 'Fee', 'amount': 1.5}, ...]" +) + + +def build_sub_transactions(transaction: Transaction, value) -> list[SubTransaction]: + """Validated sub-transactions for `transaction` from a rule expression's result.""" + if not isinstance(value, (list, tuple)): + raise ValueError(SUB_TRANSACTIONS_SHAPE) + places = transaction.account.currency.decimal_places + subs = [] + for item in value: + if not isinstance(item, dict) or item.get("amount") is None: + raise ValueError(SUB_TRANSACTIONS_SHAPE) + sub = SubTransaction( + transaction=transaction, + name=str(item.get("name") or "").strip(), + amount=truncate_decimal( + value=Decimal(str(item["amount"])), decimal_places=places + ), + ) + # the transaction may not be saved yet, so its link isn't checked here + sub.full_clean(exclude=["transaction"], validate_constraints=False) + subs.append(sub) + return subs + + +def _snapshot(transaction: Transaction) -> Transaction: + """A copy to show in dry-run results, as the transaction is right now.""" + copy = transaction.deepcopy() + copy.copy_sub_transactions_from(transaction) + return copy + class DryRunResults: def __init__(self, dry_run: bool): @@ -49,7 +84,7 @@ class DryRunResults: if not self.dry_run: return if isinstance(instance, Transaction): - instance = instance.deepcopy() + instance = _snapshot(instance) elif isinstance(instance, dict): instance = deepcopy(instance) @@ -65,7 +100,7 @@ class DryRunResults: if not self.dry_run: return if isinstance(instance, Transaction): - instance = instance.deepcopy() + instance = _snapshot(instance) elif isinstance(instance, dict): instance = deepcopy(instance) @@ -95,7 +130,7 @@ class DryRunResults: return if isinstance(end_instance, Transaction): - end_instance = end_instance.deepcopy() + end_instance = _snapshot(end_instance) elif isinstance(end_instance, dict): end_instance = deepcopy(end_instance) @@ -201,6 +236,14 @@ def check_for_transaction_rules( f"{prefix}entities_ids": ( [x.id for x in transaction.entities.all()] if transaction.id else [] ), + f"{prefix}sub_transactions": ( + [ + {"name": s.name, "amount": s.amount} + for s in transaction.sub_transactions.all() + ] + if transaction.id + else [] + ), f"{prefix}is_expense": transaction.type == Transaction.Type.EXPENSE, f"{prefix}is_income": transaction.type == Transaction.Type.INCOME, f"{prefix}is_paid": transaction.is_paid, @@ -250,6 +293,10 @@ def check_for_transaction_rules( f"{prefix}entities_ids": [ x[0] for x in transaction.get("entities", []) ], + f"{prefix}sub_transactions": [ + {"name": s["name"], "amount": Decimal(s["amount"])} + for s in transaction.get("sub_transactions", []) + ], f"{prefix}is_expense": transaction.get("type") == Transaction.Type.EXPENSE, f"{prefix}is_income": transaction.get("type") @@ -274,6 +321,22 @@ def check_for_transaction_rules( f"{prefix}installment_total": transaction.get("installment_total"), } + def _evaluate_sub_transactions(transaction, value): + """The parts an expression's `value` gives `transaction`, with its amount set + to their sum, or None for a transfer, which can't have any.""" + if transaction.linked_transaction_id: + _log("Skipped: transfers can't have sub-transactions") + return None + subs = build_sub_transactions(transaction, value) + if subs: + transaction.amount = sum(s.amount for s in subs) + _log(f"Sub-transactions will be set as: {[(s.name, s.amount) for s in subs]}") + return subs + + def _save_sub_transactions(transaction, subs): + transaction.sub_transactions.all().delete() + SubTransaction.objects.bulk_create(subs) + def _process_update_or_create_transaction_action(processed_action): """Helper to process a single linked transaction action""" @@ -295,7 +358,7 @@ def check_for_transaction_rules( existing = True if dry_run: - starting_instance = transaction.deepcopy() + starting_instance = _snapshot(transaction) _log("Found at least one matching transaction, using latest:") _log("{}".format(pformat(model_to_dict(transaction)))) @@ -348,7 +411,15 @@ def check_for_transaction_rules( processed_action.set_reference_date ) - if processed_action.set_amount: + subs = None + if processed_action.set_sub_transactions: + subs = _evaluate_sub_transactions( + transaction, simple.eval(processed_action.set_sub_transactions) + ) + + # A transaction with parts gets its amount from them + has_parts = bool(subs) if subs is not None else transaction.has_sub_transactions + if processed_action.set_amount and not has_parts: transaction.amount = simple.eval(processed_action.set_amount) if processed_action.set_description: @@ -383,6 +454,8 @@ def check_for_transaction_rules( ) ) transaction.save() + if subs is not None: + _save_sub_transactions(transaction, subs) # Handle M2M fields after save tags = [] @@ -441,7 +514,10 @@ def check_for_transaction_rules( dry_run_results.header("edit_transaction", action=processed_action) field = processed_action.field - original_value = getattr(transaction, field) + if field == TransactionRuleAction.Field.sub_transactions: + original_value = list(transaction.sub_transactions.values("name", "amount")) + else: + original_value = getattr(transaction, field) new_value = simple.eval(processed_action.value) tags = [] @@ -518,6 +594,18 @@ def check_for_transaction_rules( transaction.entities.add(entity) entities.append(entity) + elif field == TransactionRuleAction.Field.sub_transactions: + subs = _evaluate_sub_transactions(transaction, new_value) + if subs is not None: + _save_sub_transactions(transaction, subs) + new_value = ", ".join(f"{s.name}: {s.amount}" for s in subs) or "[]" + + elif ( + field == TransactionRuleAction.Field.amount + and transaction.has_sub_transactions + ): + _log("Skipped: the amount is the sum of the transaction's sub-transactions") + else: setattr( transaction, diff --git a/app/apps/rules/tests/test_tasks.py b/app/apps/rules/tests/test_tasks.py index 9520318a..b03f26cc 100644 --- a/app/apps/rules/tests/test_tasks.py +++ b/app/apps/rules/tests/test_tasks.py @@ -6,10 +6,15 @@ from django.contrib.auth import get_user_model from django.test import TransactionTestCase from apps.accounts.models import Account +from apps.common.middleware.thread_local import write_current_user from apps.currencies.models import Currency -from apps.rules.models import TransactionRule, UpdateOrCreateTransactionRuleAction +from apps.rules.models import ( + TransactionRule, + TransactionRuleAction, + UpdateOrCreateTransactionRuleAction, +) from apps.rules.tasks import check_for_transaction_rules -from apps.transactions.models import Transaction +from apps.transactions.models import SubTransaction, Transaction def run_check_for_transaction_rules_without_worker_wrapper(**kwargs): @@ -122,3 +127,104 @@ class CheckForTransactionRulesTests(TransactionTestCase): generated_transaction = Transaction.objects.get(description="Muted copy") self.assertTrue(generated_transaction.mute) self.assertFalse(generated_transaction.is_paid) + + @patch("apps.rules.signals.check_for_transaction_rules.defer") + def test_edit_amount_skips_transactions_with_sub_transactions(self, mock_defer): + rule = TransactionRule.objects.create( + active=True, on_update=True, name="Set amount", trigger="True", owner=self.user + ) + TransactionRuleAction.objects.create(rule=rule, field="amount", value="99") + TransactionRuleAction.objects.create(rule=rule, field="description", value="'Ruled'") + amounts = {} + for parts in ([], [Decimal("4"), Decimal("6")]): + transaction = Transaction.objects.create( + account=self.account, type=Transaction.Type.EXPENSE, amount=sum(parts) or 1, + date=date(2026, 5, 4), owner=self.user, + ) + for amount in parts: + SubTransaction.objects.create(transaction=transaction, name="Part", amount=amount) + run_check_for_transaction_rules_without_worker_wrapper( + instance_id=transaction.id, user_id=self.user.id, signal="transaction_updated" + ) + transaction.refresh_from_db() + self.assertEqual(transaction.description, "Ruled") + amounts[len(parts)] = transaction.amount + self.assertEqual(amounts, {0: Decimal("99"), 2: Decimal("10")}) + + +class SubTransactionRuleTests(TransactionTestCase): + def setUp(self): + self.user = get_user_model().objects.create_user(email="subs@example.com", password="x") + currency = Currency.objects.create(code="USD", name="US Dollar", decimal_places=2) + self.account = Account.objects.create(name="Main", currency=currency, owner=self.user) + self.rule = TransactionRule.objects.create( + active=True, on_update=True, name="Parts", trigger="True", owner=self.user + ) + + def _transaction(self, *parts, amount=None): + transaction = Transaction.objects.create( + account=self.account, type=Transaction.Type.EXPENSE, date=date(2026, 5, 4), + amount=amount if amount is not None else sum(a for _, a in parts), owner=self.user, + ) + for name, part in parts: + SubTransaction.objects.create(transaction=transaction, name=name, amount=part) + return transaction + + def _run(self, transaction): + with patch("apps.rules.signals.check_for_transaction_rules.defer"): + run_check_for_transaction_rules_without_worker_wrapper( + instance_id=transaction.id, user_id=self.user.id, signal="transaction_updated" + ) + transaction.refresh_from_db() + return transaction.amount, list(transaction.sub_transactions.values_list("name", "amount")) + + def _edit(self, expression): + TransactionRuleAction.objects.create(rule=self.rule, field="sub_transactions", value=expression) + + def test_edit_action_adds_changes_and_deletes_parts(self): + self._edit( + '[{"name": s["name"], "amount": s["amount"] * 2} for s in sub_transactions' + ' if s["name"] != "Tip"] + [{"name": "Fee", "amount": decimal("0.50")}]' + ) + result = self._run(self._transaction(("Meal", Decimal("10")), ("Tip", Decimal("2")))) + self.assertEqual(result, (Decimal("20.50"), [("Meal", Decimal("20")), ("Fee", Decimal("0.5"))])) + + def test_edit_action_splits_a_plain_transaction_and_clearing_keeps_amount(self): + self._edit('[{"name": "Principal", "amount": amount - 5}, {"name": "Fee", "amount": 5}]') + self.assertEqual( + self._run(self._transaction(amount=Decimal("100"))), + (Decimal("100"), [("Principal", Decimal("95")), ("Fee", Decimal("5"))]), + ) + self.rule.transaction_actions.update(value="[]") + self.assertEqual(self._run(self._transaction(("A", Decimal("3")))), (Decimal("3"), [])) + + def test_invalid_parts_leave_the_transaction_alone(self): + transaction = self._transaction(("A", Decimal("3"))) + for expression in ('"Fee"', '[{"name": "Fee"}]', '[{"name": "", "amount": 1}]', + '[{"name": "Refund", "amount": -1}]'): + with self.subTest(expression=expression): + self.rule.transaction_actions.all().delete() + self._edit(expression) + self.assertEqual(self._run(transaction), (Decimal("3"), [("A", Decimal("3"))])) + + def test_transfers_are_skipped(self): + out, inc = self._transaction(amount=Decimal("5")), self._transaction(amount=Decimal("5")) + write_current_user(self.user) + with patch("apps.rules.signals.check_for_transaction_rules.defer"): + Transaction.objects.filter(pk=out.pk).update(linked_transaction=inc) + self._edit('[{"name": "Fee", "amount": 1}]') + self.assertEqual(self._run(out), (Decimal("5"), [])) + + def test_update_or_create_creates_a_transaction_from_its_parts(self): + UpdateOrCreateTransactionRuleAction.objects.create( + rule=self.rule, set_account="account_id", set_type="'EX'", set_date="date", + set_description="'Copy'", set_amount="999", + set_sub_transactions="sub_transactions + [{'name': 'Fee', 'amount': 1}]", + ) + self._run(self._transaction(("A", Decimal("3")))) + copy = Transaction.objects.get(description="Copy") + self.assertEqual(copy.amount, Decimal("4")) + self.assertEqual( + list(copy.sub_transactions.values_list("name", "amount")), + [("A", Decimal("3")), ("Fee", Decimal("1"))], + ) diff --git a/app/apps/rules/utils/transactions.py b/app/apps/rules/utils/transactions.py index 9dd7cba2..85361ebe 100644 --- a/app/apps/rules/utils/transactions.py +++ b/app/apps/rules/utils/transactions.py @@ -86,6 +86,10 @@ def serialize_transaction(sender: Transaction, deleted: bool): "notes": sender.notes, "tags": list(sender.tags.values_list("id", "name")), "entities": list(sender.entities.values_list("id", "name")), + "sub_transactions": [ + {"name": name, "amount": str(amount)} + for name, amount in sender.sub_transactions.values_list("name", "amount") + ], "deleted": deleted, "internal_note": sender.internal_note, "internal_id": sender.internal_id, 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..7d2104b7 --- /dev/null +++ b/app/apps/transactions/tests/test_sub_transactions.py @@ -0,0 +1,321 @@ +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) + + +class SubTransactionApiTests(TestCase): + def setUp(self): + user = get_user_model().objects.create_user( + email="api@test.com", password="pw", is_superuser=True + ) + self.api = APIClient() + self.api.force_authenticate(user=user) + currency = Currency.objects.create(code="EUR", name="EUR", decimal_places=2) + self.account = Account.objects.create(name="A", currency=currency, owner=user) + + def test_create_read_and_update_sub_transactions(self): + response = self.api.post( + "/api/transactions/", + {"account_id": self.account.id, "type": "EX", "date": "2030-01-10", "description": "Shop", + "sub_transactions": [{"name": "A", "amount": "1.50"}, {"name": "B", "amount": "2"}]}, + format="json", + ) + self.assertEqual(response.status_code, 201, response.data) + self.assertEqual(Decimal(response.data["amount"]), Decimal("3.50")) + self.assertEqual([s["name"] for s in response.data["sub_transactions"]], ["A", "B"]) + url = f"/api/transactions/{response.data['id']}/" + + # The amount can't drift from the parts + response = self.api.patch(url, {"amount": "9"}, format="json") + self.assertEqual(response.status_code, 400) + + response = self.api.patch(url, {"sub_transactions": [{"name": "C", "amount": "4"}]}, format="json") + self.assertEqual(response.status_code, 200, response.data) + self.assertEqual(Decimal(response.data["amount"]), Decimal("4")) + self.assertEqual(self.api.get(url).data["sub_transactions"][0]["name"], "C") + + def test_amount_required_without_sub_transactions(self): + response = self.api.post( + "/api/transactions/", + {"account_id": self.account.id, "type": "EX", "date": "2030-01-10"}, + format="json", + ) + self.assertEqual(response.status_code, 400) + self.assertIn("amount", response.data) + + def _parts(self, owner): + return [(s.name, s.amount) for s in owner.sub_transactions.all()] + + def test_installment_plan_parts_reach_every_installment(self): + response = self.api.post( + "/api/installment-plans/", + {"account": self.account.id, "type": "EX", "description": "Laptop", + "number_of_installments": 3, "start_date": "2030-01-10", "recurrence": "monthly", + "sub_transactions": [{"name": "Principal", "amount": "90"}, {"name": "Interest", "amount": "10"}]}, + format="json", + ) + self.assertEqual(response.status_code, 201, response.data) + self.assertEqual(Decimal(response.data["installment_amount"]), Decimal("100")) + plan = InstallmentPlan.all_objects.get() + installments = plan.transactions.all() + self.assertEqual(len(installments), 3) + for transaction in installments: + self.assertEqual(transaction.amount, Decimal("100")) + self.assertEqual(len(self._parts(transaction)), 2) + + url = f"/api/installment-plans/{plan.id}/" + self.assertEqual(self.api.patch(url, {"installment_amount": "5"}, format="json").status_code, 400) + response = self.api.patch(url, {"sub_transactions": [{"name": "Principal", "amount": "80"}]}, format="json") + self.assertEqual(response.status_code, 200, response.data) + for transaction in plan.transactions.all(): + self.assertEqual(self._parts(transaction), [("Principal", Decimal("80"))]) + self.assertEqual(transaction.amount, Decimal("80")) + + def test_recurring_parts_follow_its_transactions_and_transfers_drop_them(self): + response = self.api.post( + "/api/recurring-transactions/", + {"account": self.account.id, "type": "EX", "description": "Internet", + "start_date": timezone.localdate().isoformat(), "recurrence_type": "month", "recurrence_interval": 1, + "sub_transactions": [{"name": "Plan", "amount": "50"}, {"name": "Router", "amount": "10"}]}, + format="json", + ) + self.assertEqual(response.status_code, 201, response.data) + self.assertEqual(Decimal(response.data["amount"]), Decimal("60")) + self.assertEqual([s["name"] for s in response.data["sub_transactions"]], ["Plan", "Router"]) + recurring = RecurringTransaction.all_objects.get() + generated = Transaction.all_objects.filter(recurring_transaction=recurring) + self.assertTrue(generated) + for transaction in generated: + self.assertEqual(transaction.amount, Decimal("60")) + self.assertEqual(len(self._parts(transaction)), 2) + + other = Account.objects.create(name="B", currency=self.account.currency, owner=self.account.owner) + url = f"/api/recurring-transactions/{recurring.id}/" + self.assertEqual( + self.api.patch(url, {"type": "TR", "to_account": other.id, + "sub_transactions": [{"name": "X", "amount": "1"}]}, format="json").status_code, + 400, + ) + response = self.api.patch(url, {"type": "TR", "to_account": other.id}, format="json") + self.assertEqual(response.status_code, 200, response.data) + self.assertEqual(response.data["sub_transactions"], []) 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 %}