From 3716b9b0e3f79582456ca67f741eda005079a8ec Mon Sep 17 00:00:00 2001 From: Herculino Trotta Date: Mon, 2 Nov 2026 01:14:46 -0300 Subject: [PATCH] feat(transactions): link transfer sides and show them as a single item Transfers are still two transactions, now linked to each other: - shown as one item in lists, with each side's amount, account, category and tags ("Combine transfers" user setting, on by default) - date, reference date, paid and mute stay in sync between sides - edit opens the transfer form; delete, restore, duplicate and bulk actions act on both sides - transfers made by the transfer form now trigger rules for each side Recurring and quick transactions gain a Transfer type, with a "To account" and optional "To amount", generating linked transfers. A transfer can be converted into either. Existing transfers are left as they are, since there is no reliable way to pair them. --- app/apps/api/serializers/transactions.py | 13 + app/apps/calendar_view/views.py | 2 +- .../management/commands/load_demo_data.py | 4 + app/apps/insights/views.py | 12 +- app/apps/monthly_overview/views.py | 6 +- app/apps/transactions/forms.py | 248 +++++++---- .../0051_transaction_linked_transaction.py | 19 + .../migrations/0052_transfer_templates.py | 46 ++ app/apps/transactions/models.py | 197 ++++++++- app/apps/transactions/tests/test_transfers.py | 405 ++++++++++++++++++ app/apps/transactions/urls.py | 5 + app/apps/transactions/views/actions.py | 62 ++- app/apps/transactions/views/conversions.py | 19 +- .../transactions/views/quick_transactions.py | 14 +- .../views/recurring_transactions.py | 2 +- app/apps/transactions/views/transactions.py | 74 +++- app/apps/users/forms.py | 4 +- .../0029_usersettings_combine_transfers.py | 18 + app/apps/users/models.py | 5 + app/templates/cotton/transaction/item.html | 108 ++++- .../fragments/create_menu.html | 2 +- .../quick_transactions/fragments/list.html | 7 +- .../fragments/table.html | 7 +- .../transactions/fragments/transfer.html | 4 +- .../income_expense_toggle_buttons.html | 2 +- 25 files changed, 1105 insertions(+), 180 deletions(-) create mode 100644 app/apps/transactions/migrations/0051_transaction_linked_transaction.py create mode 100644 app/apps/transactions/migrations/0052_transfer_templates.py create mode 100644 app/apps/transactions/tests/test_transfers.py create mode 100644 app/apps/users/migrations/0029_usersettings_combine_transfers.py diff --git a/app/apps/api/serializers/transactions.py b/app/apps/api/serializers/transactions.py index dcb77bc0..05d51c08 100644 --- a/app/apps/api/serializers/transactions.py +++ b/app/apps/api/serializers/transactions.py @@ -115,6 +115,8 @@ class RecurringTransactionSerializer(serializers.ModelSerializer): "account", "type", "amount", + "to_account", + "to_amount", "description", "category", "tags", @@ -130,6 +132,16 @@ class RecurringTransactionSerializer(serializers.ModelSerializer): ] read_only_fields = ["last_generated_date", "last_generated_reference_date"] + def validate(self, attrs): + # Same rule as TransferTemplate.clean(), which DRF doesn't run + type_ = attrs.get("type", getattr(self.instance, "type", None)) + to_account = attrs.get("to_account", getattr(self.instance, "to_account", None)) + if type_ == RecurringTransaction.Type.TRANSFER and not to_account: + raise serializers.ValidationError( + {"to_account": _("This field is required.")} + ) + return super().validate(attrs) + def create(self, validated_data): instance = super().create(validated_data) instance.create_upcoming_transactions() @@ -170,6 +182,7 @@ class TransactionSerializer(serializers.ModelSerializer): "id", "installment_plan", "recurring_transaction", + "linked_transaction", "installment_id", "owner", "deleted_at", diff --git a/app/apps/calendar_view/views.py b/app/apps/calendar_view/views.py index 80bcf8eb..bf03bb44 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).order_by( + transactions = Transaction.objects.filter(date=date).collapse_transfers().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 d0e45644..09ec4d3d 100644 --- a/app/apps/common/management/commands/load_demo_data.py +++ b/app/apps/common/management/commands/load_demo_data.py @@ -110,6 +110,10 @@ class Command(BaseCommand): """Same shape as TransferForm.save(): an expense and an income.""" out = self.tx(source, EX, amount, when, description, category, mute=mute) inc = self.tx(target, IN, to_amount or amount, when, description, category, mute=mute) + inc.linked_transaction = out + inc.save() + out.linked_transaction = inc + out.save() return out, inc def rate(self, series, months): diff --git a/app/apps/insights/views.py b/app/apps/insights/views.py index ab3cfd5c..f0a806e5 100644 --- a/app/apps/insights/views.py +++ b/app/apps/insights/views.py @@ -305,9 +305,11 @@ def overview_results(request): @require_http_methods(["GET"]) def latest_transactions(request): limit = timezone.now() - relativedelta(days=3) - transactions = Transaction.objects.filter(created_at__gte=limit).order_by("-id")[ - :30 - ] + transactions = ( + Transaction.objects.filter(created_at__gte=limit) + .collapse_transfers() + .order_by("-id")[:30] + ) return render( request, @@ -321,7 +323,9 @@ def latest_transactions(request): @require_http_methods(["GET"]) def late_transactions(request): now = timezone.localdate(timezone.now()) - transactions = Transaction.objects.filter(is_paid=False, date__lt=now) + transactions = Transaction.objects.filter( + is_paid=False, date__lt=now + ).collapse_transfers() return render( request, diff --git a/app/apps/monthly_overview/views.py b/app/apps/monthly_overview/views.py index 4d7f49c2..f0f85a20 100644 --- a/app/apps/monthly_overview/views.py +++ b/app/apps/monthly_overview/views.py @@ -83,7 +83,7 @@ def transactions_list(request, month: int, year: int): transactions_filtered = f.qs.filter( reference_date__year=year, reference_date__month=month, - ).prefetch_related( + ).collapse_transfers().prefetch_related( "account", "account__group", "category", @@ -94,6 +94,10 @@ def transactions_list(request, month: int, year: int): "entities", "dca_expense_entries", "dca_income_entries", + "linked_transaction__account__currency", + "linked_transaction__account__group", + "linked_transaction__category", + "linked_transaction__tags", ) # Late transactions: date < today and is_paid = False (only shown for default ordering) diff --git a/app/apps/transactions/forms.py b/app/apps/transactions/forms.py index 0855075c..174ec0e8 100644 --- a/app/apps/transactions/forms.py +++ b/app/apps/transactions/forms.py @@ -33,6 +33,7 @@ from crispy_forms.layout import ( Row, ) from django import forms +from django.db import transaction as db_transaction from django.db.models import Q from django.utils.translation import gettext_lazy as _ @@ -299,6 +300,28 @@ class TransactionAttachmentForm(forms.Form): return created +def _transfer_fields(form): + """To account/To amount for recurring and quick transfers, shown only for the Transfer type.""" + form.fields["to_account"].queryset = Account.objects.filter( + Q(is_archived=False) | Q(pk=form.instance.to_account_id) + ) + form.fields["to_amount"].widget = ArbitraryDecimalDisplayNumberInput() + return Div( + Row(Column("to_account"), Column("to_amount")), + x_show="type === 'TR'", + x_cloak="", + ) + + +def _type_aware(form, *layout): + """Wraps a layout so it knows the selected type (used by _transfer_fields).""" + return Div( + *layout, + x_data="{ type: '%s' }" % (form["type"].value() or ""), + **{"x-on:change": "if ($event.target.name === 'type') type = $event.target.value"}, + ) + + class QuickTransactionForm(forms.ModelForm): category = DynamicModelChoiceField( create_field="name", @@ -327,6 +350,12 @@ class QuickTransactionForm(forms.ModelForm): label=_("Account"), widget=TomSelect(clear_button=False, group_by="group"), ) + to_account = forms.ModelChoiceField( + queryset=Account.objects.filter(is_archived=False), + label=_("To account"), + widget=TomSelect(clear_button=False, group_by="group"), + required=False, + ) class Meta: model = QuickTransaction @@ -336,6 +365,8 @@ class QuickTransactionForm(forms.ModelForm): "type", "is_paid", "amount", + "to_account", + "to_amount", "description", "notes", "category", @@ -386,25 +417,29 @@ class QuickTransactionForm(forms.ModelForm): self.helper.form_tag = False self.helper.form_method = "post" self.helper.layout = Layout( - Field( - "type", - template="transactions/widgets/income_expense_toggle_buttons.html", - ), - Field("is_paid", template="transactions/widgets/paid_toggle_button.html"), - "name", - HTML('
'), - Row( - Column("account"), - Column("entities"), - ), - "description", - Field("amount", inputmode="decimal"), - Row( - Column("category"), - Column("tags"), - ), - "notes", - Switch("mute"), + _type_aware( + self, + Field( + "type", + template="transactions/widgets/income_expense_toggle_buttons.html", + ), + Field("is_paid", template="transactions/widgets/paid_toggle_button.html"), + "name", + HTML('
'), + Row( + Column("account"), + Column("entities"), + ), + "description", + Field("amount", inputmode="decimal"), + _transfer_fields(self), + Row( + Column("category"), + Column("tags"), + ), + "notes", + Switch("mute"), + ) ) if self.instance and self.instance.pk: @@ -623,7 +658,26 @@ class TransferForm(forms.Form): help_text=_("Muted transactions won't be displayed on monthly summaries"), ) - def __init__(self, *args, **kwargs): + def __init__(self, *args, instance=None, **kwargs): + # instance: either side of an existing transfer, to edit it + self.instance = instance + if instance: + from_t, to_t = instance.transfer_from, instance.transfer_to + kwargs["initial"] = { + "from_account": from_t.account, + "to_account": to_t.account, + "from_amount": from_t.amount, + "to_amount": to_t.amount, + "from_category": from_t.category, + "to_category": to_t.category, + "from_tags": list(from_t.tags.all()), + "to_tags": list(to_t.tags.all()), + "date": from_t.date, + "reference_date": from_t.reference_date, + "description": from_t.description, + "notes": from_t.notes, + "mute": from_t.mute, + } super().__init__(*args, **kwargs) self.helper = FormHelper() @@ -659,7 +713,11 @@ class TransferForm(forms.Form): css_class="bg-base-100 rounded-box p-4 border-base-content/60 border", ), FormActions( - NoClassSubmit("submit", _("Transfer"), css_class="btn btn-primary"), + NoClassSubmit( + "submit", + _("Update") if instance else _("Transfer"), + css_class="btn btn-primary", + ), ), ) @@ -696,48 +754,50 @@ class TransferForm(forms.Form): return cleaned_data def save(self): - mute = self.cleaned_data["mute"] + data = self.cleaned_data - from_account = self.cleaned_data["from_account"] - to_account = self.cleaned_data["to_account"] - from_amount = self.cleaned_data["from_amount"] - to_amount = self.cleaned_data["to_amount"] or from_amount - date = self.cleaned_data["date"] - reference_date = self.cleaned_data["reference_date"] - description = self.cleaned_data["description"] - from_category = self.cleaned_data.get("from_category") - to_category = self.cleaned_data.get("to_category") - notes = self.cleaned_data.get("notes") + if self.instance: + from_transaction = self.instance.transfer_from + to_transaction = self.instance.transfer_to + # Snapshots for update rules, taken before anything changes + old_data = [ + deepcopy(Transaction.objects.get(pk=t.pk)) + for t in (from_transaction, to_transaction) + ] + else: + from_transaction = Transaction(type=Transaction.Type.EXPENSE, is_paid=True) + to_transaction = Transaction(type=Transaction.Type.INCOME, is_paid=True) - # Create "From" transaction - from_transaction = Transaction.objects.create( - account=from_account, - type=Transaction.Type.EXPENSE, - is_paid=True, - date=date, - reference_date=reference_date, - amount=from_amount, - description=description, - category=from_category, - notes=notes, - mute=mute, - ) - from_transaction.tags.set(self.cleaned_data.get("from_tags", [])) + for transaction, side in ((from_transaction, "from"), (to_transaction, "to")): + transaction.account = data[f"{side}_account"] + transaction.category = data.get(f"{side}_category") + transaction.date = data["date"] + transaction.reference_date = data["reference_date"] + transaction.description = data["description"] + transaction.notes = data.get("notes") + transaction.mute = data["mute"] + from_transaction.amount = data["from_amount"] + to_transaction.amount = data["to_amount"] or data["from_amount"] - # Create "To" transaction - to_transaction = Transaction.objects.create( - account=to_account, - type=Transaction.Type.INCOME, - is_paid=True, - date=date, - reference_date=reference_date, - amount=to_amount, - description=description, - category=to_category, - notes=notes, - mute=mute, - ) - to_transaction.tags.set(self.cleaned_data.get("to_tags", [])) + # Both sides get the shared fields here, so no partner sync (and its rule + # signal) on save; the signals below cover each side once. + with db_transaction.atomic(): + from_transaction.save(sync_partner=False) + to_transaction.linked_transaction = from_transaction + to_transaction.save(sync_partner=False) + if not from_transaction.linked_transaction_id: + from_transaction.linked_transaction = to_transaction + from_transaction.save(sync_partner=False) + + from_transaction.tags.set(data.get("from_tags", [])) + to_transaction.tags.set(data.get("to_tags", [])) + + # Rules run for each side, like any other transaction + for i, transaction in enumerate((from_transaction, to_transaction)): + if self.instance: + transaction_updated.send(sender=transaction, old_data=old_data[i]) + else: + transaction_created.send(sender=transaction) return from_transaction, to_transaction @@ -1023,7 +1083,13 @@ class RecurringTransactionForm(forms.ModelForm): label=_("Entities"), queryset=TransactionEntity.objects.filter(active=True), ) - type = forms.ChoiceField(choices=Transaction.Type.choices) + type = forms.ChoiceField(choices=RecurringTransaction.Type.choices) + to_account = forms.ModelChoiceField( + queryset=Account.objects.filter(is_archived=False), + label=_("To account"), + widget=TomSelect(clear_button=False, group_by="group"), + required=False, + ) class Meta: model = RecurringTransaction @@ -1031,6 +1097,8 @@ class RecurringTransactionForm(forms.ModelForm): "account", "type", "amount", + "to_account", + "to_amount", "description", "add_description_to_transaction", "category", @@ -1097,33 +1165,37 @@ class RecurringTransactionForm(forms.ModelForm): self.helper.form_tag = False self.helper.layout = Layout( - Field( - "type", - template="transactions/widgets/income_expense_toggle_buttons.html", - ), - Row( - Column("account"), - Column("entities"), - ), - "description", - Switch("add_description_to_transaction"), - "amount", - Row( - Column("category"), - Column("tags"), - ), - "notes", - Switch("add_notes_to_transaction"), - Row( - Column("start_date"), - Column("reference_date"), - ), - Row( - Column("recurrence_interval", css_class="col-span-12 md:col-span-4"), - Column("recurrence_type", css_class="col-span-12 md:col-span-4"), - Column("end_date", css_class="col-span-12 md:col-span-4"), - ), - AppendedText("keep_at_most", _("future transactions")), + _type_aware( + self, + Field( + "type", + template="transactions/widgets/income_expense_toggle_buttons.html", + ), + Row( + Column("account"), + Column("entities"), + ), + "description", + Switch("add_description_to_transaction"), + "amount", + _transfer_fields(self), + Row( + Column("category"), + Column("tags"), + ), + "notes", + Switch("add_notes_to_transaction"), + Row( + Column("start_date"), + Column("reference_date"), + ), + Row( + Column("recurrence_interval", css_class="col-span-12 md:col-span-4"), + Column("recurrence_type", css_class="col-span-12 md:col-span-4"), + Column("end_date", css_class="col-span-12 md:col-span-4"), + ), + AppendedText("keep_at_most", _("future transactions")), + ) ) self.fields["amount"].widget = ArbitraryDecimalDisplayNumberInput() diff --git a/app/apps/transactions/migrations/0051_transaction_linked_transaction.py b/app/apps/transactions/migrations/0051_transaction_linked_transaction.py new file mode 100644 index 00000000..3fb22fa9 --- /dev/null +++ b/app/apps/transactions/migrations/0051_transaction_linked_transaction.py @@ -0,0 +1,19 @@ +# Generated by Django 5.2.17 on 2026-11-01 04:40 + +import django.db.models.deletion +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('transactions', '0050_filterpreset'), + ] + + operations = [ + migrations.AddField( + model_name='transaction', + name='linked_transaction', + field=models.OneToOneField(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='+', to='transactions.transaction', verbose_name='Linked Transaction'), + ), + ] diff --git a/app/apps/transactions/migrations/0052_transfer_templates.py b/app/apps/transactions/migrations/0052_transfer_templates.py new file mode 100644 index 00000000..a7876ae8 --- /dev/null +++ b/app/apps/transactions/migrations/0052_transfer_templates.py @@ -0,0 +1,46 @@ +# Generated by Django 5.2.17 on 2026-11-02 03:31 + +import apps.transactions.validators +import django.db.models.deletion +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('accounts', '0016_account_untracked_by'), + ('transactions', '0051_transaction_linked_transaction'), + ] + + operations = [ + migrations.AddField( + model_name='quicktransaction', + name='to_account', + field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='+', to='accounts.account', verbose_name='To account'), + ), + migrations.AddField( + model_name='quicktransaction', + name='to_amount', + field=models.DecimalField(blank=True, decimal_places=30, help_text='Leave empty to use the same amount', max_digits=42, null=True, validators=[apps.transactions.validators.validate_non_negative, apps.transactions.validators.validate_decimal_places], verbose_name='To amount'), + ), + migrations.AddField( + model_name='recurringtransaction', + name='to_account', + field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='+', to='accounts.account', verbose_name='To account'), + ), + migrations.AddField( + model_name='recurringtransaction', + name='to_amount', + field=models.DecimalField(blank=True, decimal_places=30, help_text='Leave empty to use the same amount', max_digits=42, null=True, validators=[apps.transactions.validators.validate_non_negative, apps.transactions.validators.validate_decimal_places], verbose_name='To amount'), + ), + migrations.AlterField( + model_name='quicktransaction', + name='type', + field=models.CharField(choices=[('IN', 'Income'), ('TR', 'Transfer'), ('EX', 'Expense')], default='EX', max_length=2, verbose_name='Type'), + ), + migrations.AlterField( + model_name='recurringtransaction', + name='type', + field=models.CharField(choices=[('IN', 'Income'), ('TR', 'Transfer'), ('EX', 'Expense')], default='EX', max_length=2, verbose_name='Type'), + ), + ] diff --git a/app/apps/transactions/models.py b/app/apps/transactions/models.py index be54a1f7..03255867 100644 --- a/app/apps/transactions/models.py +++ b/app/apps/transactions/models.py @@ -19,6 +19,7 @@ from apps.transactions.storage import PrivateMediaStorage from apps.transactions.validators import validate_decimal_places, validate_non_negative from dateutil.relativedelta import relativedelta from django.conf import settings +from django.core.exceptions import ObjectDoesNotExist, ValidationError from django.core.validators import MinValueValidator from django.db import models, transaction from django.db.models import Q @@ -145,6 +146,16 @@ class SoftDeleteQuerySet(models.QuerySet): def hard_delete(self): return super().delete() + def collapse_transfers(self): + # A transfer is listed once: drop its income side when the expense side is also listed + if not Transaction.transfers_combined(): + return self + return self.exclude( + type=Transaction.Type.INCOME, + linked_transaction__type=Transaction.Type.EXPENSE, + linked_transaction__in=self.values("pk"), + ) + class SoftDeleteManager(models.Manager): def get_queryset(self): @@ -376,6 +387,14 @@ class Transaction(OwnedObject): related_name="transactions", verbose_name=_("Recurring Transaction"), ) + linked_transaction = models.OneToOneField( + "self", + on_delete=models.SET_NULL, + null=True, + blank=True, + related_name="+", + verbose_name=_("Linked Transaction"), + ) internal_note = models.TextField(blank=True, verbose_name=_("Internal Note")) internal_id = models.TextField( blank=True, null=True, unique=True, verbose_name=_("Internal ID") @@ -434,7 +453,7 @@ class Transaction(OwnedObject): elif not self.reference_date and self.date: self.reference_date = self.date.replace(day=1) - def save(self, *args, **kwargs): + def save(self, *args, sync_partner=True, **kwargs): # This is here so Django validation doesn't trigger an error before clean() is ran if not self.reference_date and self.date: self.reference_date = self.date.replace(day=1) @@ -444,7 +463,73 @@ class Transaction(OwnedObject): self.full_clean() super().save(*args, **kwargs) - def delete(self, *args, **kwargs): + # Both sides of a transfer share date, reference date, paid and mute state. + # all_objects: never reach a side the current user can no longer see. + if sync_partner and self.linked_transaction_id: + Transaction.all_objects.filter( + pk=self.linked_transaction_id + ).exclude( + date=self.date, + reference_date=self.reference_date, + is_paid=self.is_paid, + mute=self.mute, + ).update( + date=self.date, + reference_date=self.reference_date, + is_paid=self.is_paid, + mute=self.mute, + ) + + @staticmethod + def transfers_combined(): + """The current user's "Combine transfers" setting (on when unknown).""" + try: + return get_current_user().settings.combine_transfers + except (AttributeError, ObjectDoesNotExist): + return True + + @property + def shown_as_transfer(self): + return bool(self.linked_transaction_id) and self.transfers_combined() + + @property + def display_transaction(self): + """The side a listing renders: the "from" side for a combined transfer.""" + return self.transfer_from if self.shown_as_transfer else self + + def add_transfer_side(self, account, amount): + """Creates the "to" side of a transfer for this saved "from" (expense) transaction.""" + to_transaction = self.deepcopy() + to_transaction.account = account + to_transaction.type = Transaction.Type.INCOME + to_transaction.amount = amount + to_transaction.linked_transaction = self + to_transaction.save() + self.linked_transaction = to_transaction + self.save() + return to_transaction + + @property + def transfer_from(self): + if self.linked_transaction_id and self.type == self.Type.INCOME: + return self.linked_transaction + return self + + @property + def transfer_to(self): + if self.linked_transaction_id and self.type == self.Type.EXPENSE: + return self.linked_transaction + return self + + def delete(self, *args, _with_partner=True, **kwargs): + # Transfers are deleted as a pair + if _with_partner and self.linked_transaction_id: + partner = Transaction.all_objects.filter( + pk=self.linked_transaction_id + ).first() + if partner: + partner.delete(_with_partner=False) + if settings.ENABLE_SOFT_DELETE: if not self.deleted: self.deleted = True @@ -531,7 +616,7 @@ class Transaction(OwnedObject): continue # Reset any unique fields to None to avoid constraint violations - if field.unique and field.name == "internal_id": + if field.unique and field.name in ("internal_id", "linked_transaction"): setattr(new_obj, field.name, None) continue @@ -828,7 +913,63 @@ class InstallmentPlan(models.Model): super().delete(*args, **kwargs) -class RecurringTransaction(models.Model): +class TransferTemplate(models.Model): + """Lets a recurring or quick transaction of type Transfer generate linked transfers.""" + + to_account = models.ForeignKey( + "accounts.Account", + on_delete=models.CASCADE, + null=True, + blank=True, + related_name="+", + verbose_name=_("To account"), + ) + to_amount = models.DecimalField( + max_digits=42, + decimal_places=30, + null=True, + blank=True, + verbose_name=_("To amount"), + help_text=_("Leave empty to use the same amount"), + validators=[validate_non_negative, validate_decimal_places], + ) + + class Meta: + abstract = True + + @property + def is_transfer(self): + return self.type == self.Type.TRANSFER + + @property + def transaction_type(self): + """Type of the generated transaction: a transfer starts with its expense side.""" + return Transaction.Type.EXPENSE if self.is_transfer else self.type + + def clean(self): + super().clean() + if self.is_transfer: + if not self.to_account_id: + raise ValidationError({"to_account": _("This field is required.")}) + if self.to_account_id == self.account_id: + raise ValidationError( + {"to_account": _("From and To accounts must be different.")} + ) + + def complete_transfer(self, transaction): + """Adds the "to" side when this generates transfers.""" + if self.is_transfer and self.to_account_id: + return transaction.add_transfer_side( + self.to_account, self.to_amount or self.amount + ) + + +class RecurringTransaction(TransferTemplate): + class Type(models.TextChoices): + INCOME = "IN", _("Income") + TRANSFER = "TR", _("Transfer") + EXPENSE = "EX", _("Expense") + class RecurrenceType(models.TextChoices): DAY = "day", _("day(s)") WEEK = "week", _("week(s)") @@ -841,8 +982,8 @@ class RecurringTransaction(models.Model): ) type = models.CharField( max_length=2, - choices=Transaction.Type, - default=Transaction.Type.EXPENSE, + choices=Type, + default=Type.EXPENSE, verbose_name=_("Type"), ) amount = models.DecimalField( @@ -947,7 +1088,7 @@ class RecurringTransaction(models.Model): def create_transaction(self, date, reference_date): created_transaction = Transaction.all_objects.create( account=self.account, - type=self.type, + type=self.transaction_type, date=date, reference_date=reference_date.replace(day=1), amount=self.amount, @@ -964,10 +1105,35 @@ class RecurringTransaction(models.Model): # 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()) + self.complete_transfer(created_transaction) def adopt_transaction(self, existing_transaction, date, reference_date): - existing_transaction.account = self.account - existing_transaction.type = self.type + self._apply_to( + existing_transaction, + self.account, + self.transaction_type, + self.amount, + date, + reference_date, + ) + if not self.is_transfer: + return + if existing_transaction.linked_transaction_id: + # Converting a transfer: its "to" side joins the recurrence too + self._apply_to( + existing_transaction.linked_transaction, + self.to_account, + Transaction.Type.INCOME, + self.to_amount or self.amount, + date, + reference_date, + ) + else: + self.complete_transfer(existing_transaction) + + def _apply_to(self, existing_transaction, account, type, amount, date, reference_date): + existing_transaction.account = account + existing_transaction.type = type existing_transaction.date = date existing_transaction.reference_date = reference_date.replace(day=1) existing_transaction.description = ( @@ -976,7 +1142,7 @@ class RecurringTransaction(models.Model): existing_transaction.category = self.category existing_transaction.notes = self.notes if self.add_notes_to_transaction else "" existing_transaction.recurring_transaction = self - existing_transaction.amount = self.amount + existing_transaction.amount = amount existing_transaction.save() existing_transaction.tags.set(self.tags(manager="all_objects").all()) @@ -1063,7 +1229,13 @@ class RecurringTransaction(models.Model): for existing_transaction in unpaid_transactions: # Update fields based on RecurringTransaction - existing_transaction.amount = self.amount + is_to_side = ( + existing_transaction.linked_transaction_id + and existing_transaction.type == Transaction.Type.INCOME + ) + existing_transaction.amount = ( + self.to_amount or self.amount if is_to_side else self.amount + ) existing_transaction.description = ( self.description if self.add_description_to_transaction else "" ) @@ -1089,9 +1261,10 @@ class RecurringTransaction(models.Model): self.transactions.filter(is_paid=False, date__gt=today).delete() -class QuickTransaction(OwnedObject): +class QuickTransaction(TransferTemplate, OwnedObject): class Type(models.TextChoices): INCOME = "IN", _("Income") + TRANSFER = "TR", _("Transfer") EXPENSE = "EX", _("Expense") name = models.CharField( diff --git a/app/apps/transactions/tests/test_transfers.py b/app/apps/transactions/tests/test_transfers.py new file mode 100644 index 00000000..32ed8d55 --- /dev/null +++ b/app/apps/transactions/tests/test_transfers.py @@ -0,0 +1,405 @@ +from datetime import date +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 apps.accounts.models import Account, AccountGroup +from apps.common.middleware.thread_local import delete_current_user, write_current_user +from apps.currencies.models import Currency +from apps.transactions.forms import RecurringTransactionForm, TransferForm +from apps.transactions.models import ( + QuickTransaction, + RecurringTransaction, + Transaction, + TransactionCategory, + TransactionTag, +) +from apps.rules.signals import transaction_created, transaction_updated +from apps.transactions.views.actions import clone_transaction + + +@override_settings( + STORAGES={ + "default": {"BACKEND": "django.core.files.storage.FileSystemStorage"}, + "staticfiles": { + "BACKEND": "django.contrib.staticfiles.storage.StaticFilesStorage" + }, + }, + WHITENOISE_AUTOREFRESH=True, +) +class TransferTestBase(TestCase): + def setUp(self): + self.user = get_user_model().objects.create_user( + email="transfer@test.com", password="testpass123" + ) + self.client.login(username="transfer@test.com", password="testpass123") + write_current_user(self.user) + self.addCleanup(delete_current_user) + currency = Currency.objects.create(code="USD", name="US Dollar", decimal_places=2) + group = AccountGroup.objects.create(name="Group") + self.checking = Account.objects.create(name="Checking", group=group, currency=currency) + self.savings = Account.objects.create(name="Savings", group=group, currency=currency) + + def _transfer(self, **overrides): + data = { + "from_account": self.checking.id, + "to_account": self.savings.id, + "from_amount": "100", + "to_amount": "98", + "date": "2026-03-10", + "reference_date": "2026-03-01", + "description": "Move money", + "mute": True, + **overrides, + } + form = TransferForm(data) + self.assertTrue(form.is_valid(), form.errors) + return form.save() + + +class TransferTests(TransferTestBase): + def test_creates_linked_pair_with_own_amounts(self): + from_t, to_t = self._transfer() + from_t.refresh_from_db() + to_t.refresh_from_db() + + self.assertEqual(from_t.linked_transaction, to_t) + self.assertEqual(to_t.linked_transaction, from_t) + self.assertEqual(from_t.type, Transaction.Type.EXPENSE) + self.assertEqual(to_t.type, Transaction.Type.INCOME) + self.assertEqual(from_t.amount, Decimal("100")) + self.assertEqual(to_t.amount, Decimal("98")) + + def test_listing_collapses_pair_unless_one_side_is_filtered_out(self): + from_t, to_t = self._transfer() + Transaction.objects.create( + account=self.checking, type="IN", date=date(2026, 3, 1), amount=5 + ) + + listed = Transaction.objects.all().collapse_transfers() + self.assertEqual(listed.count(), 2) + self.assertNotIn(to_t, listed) + + only_savings = Transaction.objects.filter(account=self.savings) + self.assertEqual(list(only_savings.collapse_transfers()), [to_t]) + + def test_shared_fields_stay_in_sync(self): + from_t, to_t = self._transfer() + + to_t.date = date(2026, 4, 2) + to_t.reference_date = date(2026, 4, 1) + to_t.is_paid = False + to_t.save() + + from_t.refresh_from_db() + self.assertEqual(from_t.date, date(2026, 4, 2)) + self.assertEqual(from_t.reference_date, date(2026, 4, 1)) + self.assertFalse(from_t.is_paid) + + def test_edit_updates_both_sides(self): + from_t, to_t = self._transfer() + + form = TransferForm( + { + "from_account": self.checking.id, + "to_account": self.savings.id, + "from_amount": "50", + "to_amount": "49", + "date": "2026-03-15", + "description": "Edited", + }, + instance=to_t, + ) + self.assertTrue(form.is_valid(), form.errors) + form.save() + + self.assertEqual(Transaction.objects.count(), 2) + from_t.refresh_from_db() + to_t.refresh_from_db() + self.assertEqual((from_t.amount, to_t.amount), (Decimal("50"), Decimal("49"))) + self.assertEqual(from_t.date, to_t.date) + self.assertEqual(to_t.description, "Edited") + + @override_settings(ENABLE_SOFT_DELETE=True) + def test_delete_and_restore_both_sides(self): + from_t, to_t = self._transfer() + + from_t.delete() + self.assertEqual(Transaction.objects.count(), 0) + + response = self.client.get( + reverse("transaction_undelete", kwargs={"transaction_id": to_t.id}), + HTTP_HX_REQUEST="true", + ) + self.assertEqual(response.status_code, 204) + self.assertEqual(Transaction.objects.count(), 2) + + @override_settings(ENABLE_SOFT_DELETE=False) + def test_hard_delete_both_sides(self): + from_t, _ = self._transfer() + from_t.delete() + self.assertEqual(Transaction.userless_all_objects.count(), 0) + + def test_clone_creates_new_linked_pair(self): + from_t, to_t = self._transfer() + + new_from = clone_transaction(from_t) + new_to = new_from.linked_transaction + + self.assertEqual(Transaction.objects.count(), 4) + self.assertEqual(new_to.linked_transaction, new_from) + self.assertEqual(new_to.amount, to_t.amount) + + def test_edit_view_routes_transfer_to_transfer_form(self): + _, to_t = self._transfer() + + response = self.client.get( + reverse("transaction_edit", kwargs={"transaction_id": to_t.id}), + HTTP_HX_REQUEST="true", + ) + self.assertEqual(response.status_code, 200) + self.assertIsInstance(response.context["form"], TransferForm) + + def test_monthly_list_renders_transfer_once(self): + from_t, to_t = self._transfer() + + response = self.client.get( + reverse("monthly_transactions_list", kwargs={"month": 3, "year": 2026}), + HTTP_HX_REQUEST="true", + ) + content = response.content.decode() + self.assertIn(f'data-transaction-id="{from_t.id}"', content) + self.assertNotIn(f'data-transaction-id="{to_t.id}"', content) + self.assertIn("Savings", content) + + def test_combine_transfers_off_lists_both_sides(self): + self.user.settings.combine_transfers = False + self.user.settings.save() + from_t, to_t = self._transfer() + + self.assertEqual(Transaction.objects.all().collapse_transfers().count(), 2) + response = self.client.get( + reverse("monthly_transactions_list", kwargs={"month": 3, "year": 2026}), + HTTP_HX_REQUEST="true", + ) + content = response.content.decode() + self.assertIn(f'data-transaction-id="{from_t.id}"', content) + self.assertIn(f'data-transaction-id="{to_t.id}"', content) + self.assertEqual(content.count("fa-right-left"), 2) # marker on each side + + def test_item_shows_both_sides_category_and_tags(self): + out_cat = TransactionCategory.objects.create(name="OutCat") + in_cat = TransactionCategory.objects.create(name="InCat") + out_tag = TransactionTag.objects.create(name="OutTag") + in_tag = TransactionTag.objects.create(name="InTag") + self._transfer( + from_category=str(out_cat.id), + to_category=str(in_cat.id), + from_tags=[out_tag.name], + to_tags=[in_tag.name], + ) + + response = self.client.get( + reverse("monthly_transactions_list", kwargs={"month": 3, "year": 2026}), + HTTP_HX_REQUEST="true", + ) + content = response.content.decode() + for name in ("OutCat", "InCat", "OutTag", "InTag"): + self.assertIn(name, content) + + +class TransferTemplateTests(TransferTestBase): + """Recurring and quick transactions of type Transfer.""" + + def _recurring(self, **overrides): + return RecurringTransaction.objects.create( + account=self.checking, + type=RecurringTransaction.Type.TRANSFER, + to_account=self.savings, + amount=Decimal("100"), + to_amount=Decimal("95"), + description="Savings", + start_date=timezone.localdate(), + recurrence_type=RecurringTransaction.RecurrenceType.MONTH, + recurrence_interval=1, + keep_at_most=2, + **overrides, + ) + + def test_recurring_transfer_generates_linked_pairs(self): + recurring = self._recurring() + recurring.create_upcoming_transactions() + + sides = recurring.transactions.all() + expenses = sides.filter(type=Transaction.Type.EXPENSE) + self.assertEqual(sides.count(), expenses.count() * 2) + for from_t in expenses: + to_t = from_t.linked_transaction + self.assertEqual(to_t.linked_transaction, from_t) + self.assertEqual(to_t.account, self.savings) + self.assertEqual(to_t.amount, Decimal("95")) + self.assertEqual(to_t.recurring_transaction, recurring) + self.assertEqual(to_t.date, from_t.date) + + def test_recurring_update_keeps_side_amounts(self): + recurring = self._recurring() + recurring.create_upcoming_transactions() + + recurring.amount, recurring.to_amount = Decimal("10"), Decimal("9") + recurring.save() + recurring.update_unpaid_transactions() + + amounts = set(recurring.transactions.values_list("type", "amount")) + self.assertEqual( + amounts, + {(Transaction.Type.EXPENSE, Decimal("10")), (Transaction.Type.INCOME, Decimal("9"))}, + ) + + def test_transfer_type_requires_other_account(self): + form = RecurringTransactionForm( + { + "type": "TR", + "account": self.checking.id, + "amount": "10", + "description": "x", + "start_date": "2026-03-01", + "recurrence_type": "month", + "recurrence_interval": "1", + "keep_at_most": "2", + } + ) + self.assertFalse(form.is_valid()) + self.assertIn("to_account", form.errors) + + def test_quick_transfer_creates_linked_pair(self): + quick = QuickTransaction.objects.create( + name="To savings", + account=self.checking, + type=QuickTransaction.Type.TRANSFER, + to_account=self.savings, + amount=Decimal("20"), + ) + + response = self.client.get( + reverse( + "quick_transaction_add_as_transaction", + kwargs={"quick_transaction_id": quick.id}, + ), + HTTP_HX_REQUEST="true", + ) + + self.assertEqual(response.status_code, 204) + from_t = Transaction.objects.get(type=Transaction.Type.EXPENSE) + self.assertEqual(from_t.account, self.checking) + self.assertEqual(from_t.linked_transaction.account, self.savings) + self.assertEqual(from_t.linked_transaction.amount, Decimal("20")) + + def test_convert_transfer_to_recurring_adopts_both_sides(self): + from_t, to_t = self._transfer() + + response = self.client.post( + reverse( + "transaction_convert_to_recurring_transaction", + kwargs={"transaction_id": to_t.id}, + ), + { + "type": "TR", + "account": self.checking.id, + "to_account": self.savings.id, + "amount": "100", + "to_amount": "98", + "description": "Move money", + "add_description_to_transaction": "on", + "start_date": "2026-03-10", + "recurrence_type": "month", + "recurrence_interval": "1", + "keep_at_most": "1", + }, + HTTP_HX_REQUEST="true", + ) + + self.assertEqual(response.status_code, 204) + from_t.refresh_from_db() + to_t.refresh_from_db() + self.assertIsNotNone(from_t.recurring_transaction) + self.assertEqual(to_t.recurring_transaction, from_t.recurring_transaction) + self.assertEqual(from_t.linked_transaction, to_t) + + +class TransferRuleSignalTests(TransferTestBase): + def _capture(self, signal): + senders = [] + + def receiver(sender, **kwargs): + senders.append((sender.pk, kwargs.get("old_data"))) + + signal.connect(receiver, weak=False) + self.addCleanup(signal.disconnect, receiver) + return senders + + def test_create_and_edit_trigger_rules_for_both_sides(self): + created = self._capture(transaction_created) + from_t, to_t = self._transfer() + self.assertEqual({pk for pk, _ in created}, {from_t.pk, to_t.pk}) + + updated = self._capture(transaction_updated) + form = TransferForm( + { + "from_account": self.checking.id, + "to_account": self.savings.id, + "from_amount": "7", + "date": "2026-04-10", # date change used to fire "updated" twice for the "to" side + }, + instance=from_t, + ) + self.assertTrue(form.is_valid(), form.errors) + form.save() + + self.assertEqual(sorted(pk for pk, _ in updated), sorted([from_t.pk, to_t.pk])) + old_amounts = {old.amount for _, old in updated} + self.assertEqual(old_amounts, {Decimal("100"), Decimal("98")}) + + +class TransferReviewFixTests(TransferTestBase): + def test_pair_of_two_incomes_stays_listed(self): + from_t, to_t = self._transfer() + Transaction.objects.filter(pk=from_t.pk).update(type=Transaction.Type.INCOME) + + listed = Transaction.objects.all().collapse_transfers() + self.assertEqual(listed.count(), 2) + + @override_settings(ENABLE_SOFT_DELETE=False) + def test_bulk_delete_removes_both_sides(self): + from_t, _ = self._transfer() + + response = self.client.get( + reverse("transactions_bulk_delete") + f"?transactions={from_t.id}", + HTTP_HX_REQUEST="true", + ) + + self.assertEqual(response.status_code, 204) + self.assertEqual(Transaction.userless_all_objects.count(), 0) + + @override_settings(ENABLE_SOFT_DELETE=False) + def test_delete_leaves_a_side_the_user_cannot_see(self): + other = get_user_model().objects.create_user( + email="other@test.com", password="testpass123" + ) + hidden = Account.objects.create( + name="Hidden", + currency=self.checking.currency, + owner=other, + visibility="private", + ) + from_t = Transaction.objects.create( + account=self.checking, type="EX", date=date(2026, 3, 1), amount=5 + ) + partner = from_t.add_transfer_side(hidden, Decimal("5")) + + from_t.delete() + + partner.refresh_from_db() + self.assertIsNone(partner.linked_transaction) diff --git a/app/apps/transactions/urls.py b/app/apps/transactions/urls.py index 00291fa9..fa54b3a6 100644 --- a/app/apps/transactions/urls.py +++ b/app/apps/transactions/urls.py @@ -171,6 +171,11 @@ urlpatterns = [ views.transactions_transfer, name="transactions_transfer", ), + path( + "transactions//transfer/edit/", + views.transaction_transfer_edit, + name="transaction_transfer_edit", + ), path("tags/", views.tags_index, name="tags_index"), path("tags/list/", views.tags_list, name="tags_list"), path("tags/table/active/", views.tags_table_active, name="tags_table_active"), diff --git a/app/apps/transactions/views/actions.py b/app/apps/transactions/views/actions.py index 6ad3bd73..eec3af02 100644 --- a/app/apps/transactions/views/actions.py +++ b/app/apps/transactions/views/actions.py @@ -3,6 +3,7 @@ from copy import deepcopy from django.contrib import messages from django.contrib.auth.decorators import login_required +from django.db.models import Q from django.http import HttpResponse from django.utils.translation import gettext_lazy as _, ngettext_lazy @@ -11,11 +12,43 @@ from apps.transactions.models import Transaction from apps.rules.signals import transaction_updated +def _selected(manager, request): + """Selected transactions plus the other side of any selected transfer.""" + ids = request.GET.getlist("transactions", []) + return manager.filter(Q(id__in=ids) | Q(linked_transaction_id__in=ids)) + + +def _copy(transaction): + new_transaction = deepcopy(transaction) + new_transaction.pk = None + new_transaction.installment_plan = None + new_transaction.installment_id = None + new_transaction.recurring_transaction = None + new_transaction.internal_id = None + new_transaction.linked_transaction = None + new_transaction.save() + + new_transaction.tags.add(*transaction.tags.all()) + new_transaction.entities.add(*transaction.entities.all()) + return new_transaction + + +def clone_transaction(transaction): + """Duplicates a transaction, or both sides of a transfer.""" + new_transaction = _copy(transaction) + if transaction.linked_transaction_id: + new_partner = _copy(transaction.linked_transaction) + new_partner.linked_transaction = new_transaction + new_partner.save() + new_transaction.linked_transaction = new_partner + new_transaction.save() + return new_transaction + + @only_htmx @login_required def bulk_pay_transactions(request): - selected_transactions = request.GET.getlist("transactions", []) - transactions = Transaction.objects.filter(id__in=selected_transactions) + transactions = _selected(Transaction.objects, request) count = transactions.count() transactions.update(is_paid=True) @@ -38,8 +71,7 @@ def bulk_pay_transactions(request): @only_htmx @login_required def bulk_unpay_transactions(request): - selected_transactions = request.GET.getlist("transactions", []) - transactions = Transaction.objects.filter(id__in=selected_transactions) + transactions = _selected(Transaction.objects, request) count = transactions.count() transactions.update(is_paid=False) @@ -62,8 +94,7 @@ def bulk_unpay_transactions(request): @only_htmx @login_required def bulk_delete_transactions(request): - selected_transactions = request.GET.getlist("transactions", []) - transactions = Transaction.objects.filter(id__in=selected_transactions) + transactions = _selected(Transaction.objects, request) deleted_ids = [str(pk) for pk in transactions.values_list("id", flat=True)] count = len(deleted_ids) transactions.delete() @@ -98,8 +129,7 @@ def bulk_delete_transactions(request): @only_htmx @login_required def bulk_undelete_transactions(request): - selected_transactions = request.GET.getlist("transactions", []) - transactions = Transaction.deleted_objects.filter(id__in=selected_transactions) + transactions = _selected(Transaction.deleted_objects, request) count = transactions.count() transactions.update(deleted=False, deleted_at=None, emit_signal=False) @@ -126,17 +156,13 @@ def bulk_clone_transactions(request): transactions = Transaction.objects.filter(id__in=selected_transactions) count = transactions.count() + cloned_ids = set() for transaction in transactions: - new_transaction = deepcopy(transaction) - new_transaction.pk = None - new_transaction.installment_plan = None - new_transaction.installment_id = None - new_transaction.recurring_transaction = None - new_transaction.internal_id = None - new_transaction.save() - - new_transaction.tags.add(*transaction.tags.all()) - new_transaction.entities.add(*transaction.entities.all()) + # Both sides of a transfer selected: clone the pair once + if transaction.linked_transaction_id in cloned_ids: + continue + clone_transaction(transaction) + cloned_ids.add(transaction.id) messages.success( request, diff --git a/app/apps/transactions/views/conversions.py b/app/apps/transactions/views/conversions.py index 759d435c..89a37249 100644 --- a/app/apps/transactions/views/conversions.py +++ b/app/apps/transactions/views/conversions.py @@ -1,7 +1,7 @@ from django.contrib import messages from django.contrib.auth.decorators import login_required from django.db import transaction as db_transaction -from django.http import HttpResponse +from django.http import Http404, HttpResponse from django.shortcuts import render, get_object_or_404 from django.urls import reverse from django.utils.translation import gettext_lazy as _ @@ -17,7 +17,7 @@ from apps.transactions.models import Transaction def _initial_from_transaction(transaction: Transaction): - return { + initial = { "account": transaction.account_id, "type": transaction.type, "description": transaction.description, @@ -26,6 +26,14 @@ def _initial_from_transaction(transaction: Transaction): "tags": list(transaction.tags.values_list("name", flat=True)), "entities": list(transaction.entities.values_list("name", flat=True)), } + if transaction.linked_transaction_id: + to_transaction = transaction.transfer_to + initial.update( + type="TR", + to_account=to_transaction.account_id, + to_amount=to_transaction.amount, + ) + return initial def _get_unlinked_transaction(transaction_id): @@ -54,7 +62,8 @@ def _render_convert_form(request, form, title, transaction_id, url_name): @login_required @require_http_methods(["GET", "POST"]) def transaction_convert_to_quick_transaction(request, transaction_id): - transaction = get_object_or_404(Transaction, id=transaction_id) + # A transfer converts from its "from" side + transaction = get_object_or_404(Transaction, id=transaction_id).transfer_from if request.method == "POST": form = QuickTransactionForm(request.POST) @@ -89,7 +98,7 @@ def transaction_convert_to_quick_transaction(request, transaction_id): @login_required @require_http_methods(["GET", "POST"]) def transaction_convert_to_recurring_transaction(request, transaction_id): - transaction = _get_unlinked_transaction(transaction_id) + transaction = _get_unlinked_transaction(transaction_id).transfer_from if request.method == "POST": form = RecurringTransactionForm(request.POST) @@ -128,6 +137,8 @@ def transaction_convert_to_recurring_transaction(request, transaction_id): @require_http_methods(["GET", "POST"]) def transaction_convert_to_installment_plan(request, transaction_id): transaction = _get_unlinked_transaction(transaction_id) + if transaction.linked_transaction_id: + raise Http404() # Installment plans don't support transfers if request.method == "POST": form = InstallmentPlanForm(request.POST) diff --git a/app/apps/transactions/views/quick_transactions.py b/app/apps/transactions/views/quick_transactions.py index b8c9acb7..0c60e438 100644 --- a/app/apps/transactions/views/quick_transactions.py +++ b/app/apps/transactions/views/quick_transactions.py @@ -1,5 +1,6 @@ from django.contrib import messages from django.contrib.auth.decorators import login_required +from django.db import transaction as db_transaction from django.forms import model_to_dict from django.http import HttpResponse from django.shortcuts import render, get_object_or_404 @@ -138,20 +139,27 @@ def quick_transaction_add_as_transaction(request, quick_transaction_id): "tags", "entities", "internal_id", + "to_account", + "to_amount", ], ) new_transaction = Transaction(**quick_transaction_data) + new_transaction.type = quick_transaction.transaction_type new_transaction.account = quick_transaction.account new_transaction.category = quick_transaction.category new_transaction.date = today new_transaction.reference_date = today.replace(day=1) - new_transaction.save() - new_transaction.tags.set(quick_transaction.tags.all()) - new_transaction.entities.set(quick_transaction.entities.all()) + with db_transaction.atomic(): + new_transaction.save() + new_transaction.tags.set(quick_transaction.tags.all()) + new_transaction.entities.set(quick_transaction.entities.all()) + to_transaction = quick_transaction.complete_transfer(new_transaction) transaction_created.send(sender=new_transaction) + if to_transaction: + transaction_created.send(sender=to_transaction) messages.success(request, _("Transaction added successfully")) diff --git a/app/apps/transactions/views/recurring_transactions.py b/app/apps/transactions/views/recurring_transactions.py index f3a43388..d12cfd9a 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.all().order_by( + transactions = recurring_transaction.transactions.collapse_transfers().order_by( "reference_date", "id" ) diff --git a/app/apps/transactions/views/transactions.py b/app/apps/transactions/views/transactions.py index 8e542051..a18c17bf 100644 --- a/app/apps/transactions/views/transactions.py +++ b/app/apps/transactions/views/transactions.py @@ -13,6 +13,7 @@ from apps.transactions.forms import ( TransferForm, ) from apps.transactions.models import FilterPreset, Transaction, TransactionAttachment +from apps.transactions.views.actions import clone_transaction from apps.transactions.utils.calculations import ( calculate_account_totals, calculate_currency_totals, @@ -344,6 +345,9 @@ def transaction_simple_add(request): def transaction_edit(request, transaction_id, **kwargs): transaction = get_object_or_404(Transaction, id=transaction_id) + if transaction.linked_transaction_id: + return transaction_transfer_edit(request, transaction_id) + if request.method == "POST": form = TransactionForm(request.POST, instance=transaction) if form.is_valid(): @@ -424,16 +428,7 @@ def transactions_bulk_edit(request): @require_http_methods(["GET", "POST"]) def transaction_clone(request, transaction_id, **kwargs): transaction = get_object_or_404(Transaction, id=transaction_id) - new_transaction = deepcopy(transaction) - new_transaction.pk = None - new_transaction.installment_plan = None - new_transaction.installment_id = None - new_transaction.recurring_transaction = None - new_transaction.internal_id = None - new_transaction.save() - - new_transaction.tags.add(*transaction.tags.all()) - new_transaction.entities.add(*transaction.entities.all()) + clone_transaction(transaction) messages.success(request, _("Transaction duplicated successfully")) @@ -474,6 +469,9 @@ def transaction_clone(request, transaction_id, **kwargs): @require_http_methods(["DELETE"]) def transaction_delete(request, transaction_id, **kwargs): transaction = get_object_or_404(Transaction.all_objects, id=transaction_id) + deleted_ids = [str(transaction_id)] + if transaction.linked_transaction_id: + deleted_ids.append(str(transaction.linked_transaction_id)) transaction.delete() @@ -487,7 +485,7 @@ def transaction_delete(request, transaction_id, **kwargs): headers={ "HX-Trigger": json.dumps( { - "transactions_deleted": {"ids": [str(transaction_id)]}, + "transactions_deleted": {"ids": deleted_ids}, "selective_update": None, "toasts": None, } @@ -500,11 +498,12 @@ def transaction_delete(request, transaction_id, **kwargs): @login_required @require_http_methods(["GET"]) def transaction_undelete(request, transaction_id, **kwargs): - transaction = get_object_or_404(Transaction.deleted_objects, id=transaction_id) + get_object_or_404(Transaction.deleted_objects, id=transaction_id) - transaction.deleted = False - transaction.deleted_at = None - transaction.save() + # Restores the other side of a transfer too + Transaction.deleted_objects.filter( + Q(id=transaction_id) | Q(linked_transaction_id=transaction_id) + ).update(deleted=False, deleted_at=None, emit_signal=False) messages.success(request, _("Transaction restored successfully")) @@ -548,6 +547,33 @@ def transactions_transfer(request): return render(request, "transactions/fragments/transfer.html", {"form": form}) +@only_htmx +@login_required +@require_http_methods(["GET", "POST"]) +def transaction_transfer_edit(request, transaction_id): + transaction = get_object_or_404( + Transaction, id=transaction_id, linked_transaction__isnull=False + ) + + if request.method == "POST": + form = TransferForm(request.POST, instance=transaction) + if form.is_valid(): + form.save() + messages.success(request, _("Transfer updated successfully")) + return HttpResponse( + status=204, + headers={"HX-Trigger": "updated, hide_offcanvas"}, + ) + else: + form = TransferForm(instance=transaction) + + return render( + request, + "transactions/fragments/transfer.html", + {"form": form, "transaction": transaction}, + ) + + @only_htmx @login_required @require_http_methods(["GET"]) @@ -760,6 +786,10 @@ def transaction_all_list(request): "entities", "dca_expense_entries", "dca_income_entries", + "linked_transaction__account__currency", + "linked_transaction__account__group", + "linked_transaction__category", + "linked_transaction__tags", ).all() f = TransactionsFilter(request.GET, queryset=transactions) @@ -767,18 +797,19 @@ def transaction_all_list(request): # Late transactions: date < today and is_paid = False (only shown for default ordering on first page) late_transactions = None page_number = request.GET.get("page", 1) + filtered = f.qs.collapse_transfers() if order == "default" and str(page_number) == "1": - late_transactions = f.qs.filter( + late_transactions = filtered.filter( date__lt=today, is_paid=False, ).order_by("date", "id") # Exclude late transactions from the main paginated list - main_transactions = f.qs.exclude( + main_transactions = filtered.exclude( date__lt=today, is_paid=False, ) else: - main_transactions = f.qs + main_transactions = filtered main_transactions = default_order(main_transactions, order=order) @@ -922,10 +953,13 @@ def transactions_trash_can_list(request): "account__currency", "installment_plan", "entities", - "entities", "dca_expense_entries", "dca_income_entries", - ).all() + "linked_transaction__account__currency", + "linked_transaction__account__group", + "linked_transaction__category", + "linked_transaction__tags", + ).collapse_transfers() return render( request, diff --git a/app/apps/users/forms.py b/app/apps/users/forms.py index cb8b4c1d..46639a74 100644 --- a/app/apps/users/forms.py +++ b/app/apps/users/forms.py @@ -2,7 +2,7 @@ from datetime import timedelta from apps.common.middleware.thread_local import get_current_user from apps.users.models import APIToken -from apps.common.widgets.crispy.daisyui import Range +from apps.common.widgets.crispy.daisyui import Range, Switch from apps.common.widgets.crispy.submit import NoClassSubmit from apps.common.widgets.range import RangeInput from apps.common.widgets.tom_select import TomSelect @@ -157,6 +157,7 @@ class UserSettingsForm(forms.ModelForm): "datetime_format", "number_format", "default_account", + "combine_transfers", "volume", ] widgets = { @@ -183,6 +184,7 @@ class UserSettingsForm(forms.ModelForm): HTML('
'), "start_page", "default_account", + Switch("combine_transfers"), HTML('
'), Range("volume"), FormActions( diff --git a/app/apps/users/migrations/0029_usersettings_combine_transfers.py b/app/apps/users/migrations/0029_usersettings_combine_transfers.py new file mode 100644 index 00000000..7b2b6647 --- /dev/null +++ b/app/apps/users/migrations/0029_usersettings_combine_transfers.py @@ -0,0 +1,18 @@ +# Generated by Django 5.2.17 on 2026-11-01 22:52 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('users', '0028_alter_usersettings_volume'), + ] + + operations = [ + migrations.AddField( + model_name='usersettings', + name='combine_transfers', + field=models.BooleanField(default=True, help_text='Show both sides of a transfer as a single item', verbose_name='Combine transfers'), + ), + ] diff --git a/app/apps/users/models.py b/app/apps/users/models.py index 7b21216e..62594cc1 100644 --- a/app/apps/users/models.py +++ b/app/apps/users/models.py @@ -479,6 +479,11 @@ class UserSettings(models.Model): ) hide_amounts = models.BooleanField(default=False) mute_sounds = models.BooleanField(default=False) + combine_transfers = models.BooleanField( + default=True, + verbose_name=_("Combine transfers"), + help_text=_("Show both sides of a transfer as a single item"), + ) volume = models.PositiveIntegerField( default=10, validators=[MinValueValidator(0), MaxValueValidator(10)], diff --git a/app/templates/cotton/transaction/item.html b/app/templates/cotton/transaction/item.html index 1ae35b81..6e4ec65d 100644 --- a/app/templates/cotton/transaction/item.html +++ b/app/templates/cotton/transaction/item.html @@ -1,8 +1,10 @@ {% load markdown %} {% 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 %}
+ class="transaction {% if is_transfer %}transfer{% elif transaction.type == "EX" %}expense{% else %}income{% endif %} group/transaction">
{% if not disable_selection or not dummy %}