fix(transactions): drop unpaid recurring occurrences past a shorter end date

Editing a recurring transaction to end earlier kept its unpaid occurrences
after the new end date, counting them in projected balances, and left
last_generated_date past it. Remove them (both sides of a generated transfer;
a partner linked from elsewhere is unlinked and kept) and move the bookmark
back to the last remaining occurrence. Paid occurrences stay.

Also pin ENABLE_SOFT_DELETE=False on the test that asserts hard deletes, so a
.env that turns soft delete on no longer fails it.
This commit is contained in:
Herculino Trotta committed 2026-11-15 16:36:29 -03:00
1 parent eb51e240ac
commit f5414223ab
2 files changed
+76 -1

No files matched your search

+35 -1
View File
@@ -1366,8 +1366,11 @@ class RecurringTransaction(TransferTemplate):
and take the account, type, amount, description, category, notes, tags and
entities of the recurrence; a transfer's "to" side takes the "to" account and
amount. Turning the recurrence into a transfer adds the missing "to" sides,
and turning it into an income or expense removes them.
and turning it into an income or expense removes them. Unpaid ones after a
new end date are removed.
"""
self._remove_occurrences_after_end()
unpaid_transactions = list(
self.transactions.filter(is_paid=False).select_related(
"linked_transaction"
@@ -1430,6 +1433,37 @@ class RecurringTransaction(TransferTemplate):
if not existing_transaction.linked_transaction_id:
self.complete_transfer(existing_transaction)
def _remove_occurrences_after_end(self):
"""Removes unpaid occurrences an earlier end date no longer reaches, and
moves the generation bookmark back so a later extension fills the gap."""
if not self.end_date:
return
removed = set()
stale = self.transactions.filter(
is_paid=False, date__gt=self.end_date
).select_related("linked_transaction")
for existing_transaction in stale:
if existing_transaction.pk in removed:
continue
partner = existing_transaction.linked_transaction
own_partner = bool(partner and partner.recurring_transaction_id == self.pk)
if partner and not own_partner:
# A link made elsewhere (e.g. a DCA entry): keep the partner
Transaction.all_objects.filter(pk=partner.pk).update(
linked_transaction=None
)
existing_transaction.delete(_with_partner=own_partner)
removed.update({existing_transaction.pk, partner.pk if own_partner else None})
if self.last_generated_date and self.last_generated_date > self.end_date:
last = self.transactions.order_by("-date").first()
self.last_generated_date = last.date if last else None
self.last_generated_reference_date = last.reference_date if last else None
self.save(
update_fields=["last_generated_date", "last_generated_reference_date"]
)
def _is_to_side(self, existing_transaction):
"""Whether a transaction is the "to" side of a transfer this generated."""
return bool(
@@ -1,6 +1,7 @@
from datetime import date
from decimal import Decimal
from dateutil.relativedelta import relativedelta
from django.contrib.auth import get_user_model
from django.test import TestCase, override_settings
from django.urls import reverse
@@ -383,10 +384,50 @@ class TransferTemplateTests(TransferTestBase):
paid_from.refresh_from_db()
self.assertEqual(paid_from.linked_transaction, paid_to)
@override_settings(ENABLE_SOFT_DELETE=False) # .env may turn it on
def test_recurring_update_out_of_transfer_removes_to_sides(self):
self._assert_update_out_of_transfer_removes_to_sides()
self.assertFalse(Transaction.deleted_objects.exists())
def _shorten(self, recurring, months):
"""Ends ``recurring`` after its first ``months`` + 1 occurrences."""
recurring.end_date = recurring.start_date + relativedelta(months=months)
recurring.save()
recurring.update_unpaid_transactions()
recurring.refresh_from_db()
def test_shorter_end_date_removes_later_unpaid_occurrences(self):
recurring = self._recurring(type=RecurringTransaction.Type.EXPENSE, keep_at_most=4)
recurring.create_upcoming_transactions()
last = recurring.transactions.latest("date")
last.is_paid = True # already happened: stays
last.save()
self.assertEqual(recurring.transactions.count(), 5)
self._shorten(recurring, 1)
end = recurring.end_date
self.assertEqual(
list(recurring.transactions.order_by("date").values_list("date", "is_paid")),
[(recurring.start_date, False), (end, False), (last.date, True)],
)
self.assertEqual(recurring.last_generated_date, last.date)
last.delete()
self._shorten(recurring, 1)
self.assertEqual(recurring.last_generated_date, end)
self.assertEqual(recurring.last_generated_reference_date, end.replace(day=1))
def test_shorter_end_date_removes_both_sides_of_later_transfers(self):
recurring = self._recurring(keep_at_most=3)
recurring.create_upcoming_transactions()
self.assertEqual(recurring.transactions.count(), 8)
self._shorten(recurring, 1)
self.assertEqual(recurring.transactions.count(), 4)
self.assertFalse(recurring.transactions.filter(date__gt=recurring.end_date).exists())
@override_settings(ENABLE_SOFT_DELETE=True)
def test_recurring_update_out_of_transfer_soft_deletes_to_sides(self):
self._assert_update_out_of_transfer_removes_to_sides()