diff --git a/app/apps/calendar_view/views.py b/app/apps/calendar_view/views.py index 852e06a2..c6c23cc4 100644 --- a/app/apps/calendar_view/views.py +++ b/app/apps/calendar_view/views.py @@ -7,6 +7,7 @@ from django.views.decorators.http import require_http_methods from apps.calendar_view.utils.calendar import get_transactions_by_day from apps.transactions.models import Transaction +from apps.transactions.utils.changed_rows import changed_rows @login_required @@ -73,6 +74,9 @@ def calendar_transactions_list(request, day: int, month: int, year: int): "id", ) + if "only" in request.GET: + return changed_rows(request, transactions, grouped=False) + return render( request, "calendar_view/fragments/list_transactions.html", diff --git a/app/apps/monthly_overview/views.py b/app/apps/monthly_overview/views.py index 94922936..045da56f 100644 --- a/app/apps/monthly_overview/views.py +++ b/app/apps/monthly_overview/views.py @@ -20,6 +20,7 @@ from apps.transactions.utils.calculations import ( calculate_percentage_distribution, calculate_account_totals, ) +from apps.transactions.utils.changed_rows import LIST_PREFETCH, changed_rows from apps.transactions.utils.default_ordering import default_order @@ -83,23 +84,7 @@ def transactions_list(request, month: int, year: int): transactions_filtered = f.qs.filter( reference_date__year=year, reference_date__month=month, - ).collapse_transfers().prefetch_related( - "account", - "account__group", - "category", - "tags", - "account__exchange_currency", - "account__currency", - "installment_plan", - "entities", - "dca_expense_entries", - "sub_transactions", - "dca_income_entries", - "linked_transaction__account__currency", - "linked_transaction__account__group", - "linked_transaction__category", - "linked_transaction__tags", - ) + ).collapse_transfers() # Late transactions: date < today and is_paid = False (only shown for default ordering) late_transactions = None @@ -116,6 +101,13 @@ def transactions_list(request, month: int, year: int): transactions_filtered = default_order(transactions_filtered, order=order) + if "only" in request.GET: + return changed_rows(request, transactions_filtered, late=late_transactions) + + if late_transactions is not None: + late_transactions = late_transactions.prefetch_related(*LIST_PREFETCH) + transactions_filtered = transactions_filtered.prefetch_related(*LIST_PREFETCH) + return render( request, "monthly_overview/fragments/list.html", diff --git a/app/apps/transactions/tests/test_changed_rows.py b/app/apps/transactions/tests/test_changed_rows.py new file mode 100644 index 00000000..32e4c964 --- /dev/null +++ b/app/apps/transactions/tests/test_changed_rows.py @@ -0,0 +1,133 @@ +import json +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 apps.accounts.models import Account, AccountGroup +from apps.currencies.models import Currency +from apps.transactions.models import Transaction + + +@override_settings( + STORAGES={ + "default": {"BACKEND": "django.core.files.storage.FileSystemStorage"}, + "staticfiles": { + "BACKEND": "django.contrib.staticfiles.storage.StaticFilesStorage" + }, + }, + WHITENOISE_AUTOREFRESH=True, +) +class ChangedRowsTests(TestCase): + """The lists' ?only= mode, used to move saved rows in place.""" + + def setUp(self): + user = get_user_model().objects.create_user( + email="test@test.com", password="testpass123" + ) + self.client.login(username="test@test.com", password="testpass123") + currency = Currency.objects.create(code="USD", name="US Dollar") + self.account = Account.objects.create( + name="Account", + group=AccountGroup.objects.create(name="Group"), + currency=currency, + ) + self.rows = [ + Transaction.objects.create( + account=self.account, + type=Transaction.Type.EXPENSE, + is_paid=True, + date=date(2025, 12, 10), + reference_date=date(2025, 12, 1), + amount=Decimal("10"), + description=f"row {i}", + owner=user, + ) + for i in range(3) + ] + + def _only(self, *ids): + return self.client.get( + reverse("monthly_transactions_list", kwargs={"month": 12, "year": 2025}), + {"order": "older", "only": [str(i) for i in ids]}, + HTTP_HX_REQUEST="true", + ) + + def test_row_comes_with_the_row_after_it(self): + first, middle, last = self.rows + response = self._only(middle.pk) + self.assertContains(response, f'data-next-id="{last.pk}"') + self.assertContains(response, f'data-transaction-id="{middle.pk}"') + self.assertNotContains(response, f'data-transaction-id="{first.pk}"') + + def test_last_row_has_nothing_after_it(self): + response = self._only(self.rows[-1].pk) + self.assertContains(response, 'data-next-id="" data-next-group=""') + + def test_row_that_left_the_month_is_not_returned(self): + moved = self.rows[1] + moved.reference_date = date(2026, 1, 1) + moved.save() + response = self._only(moved.pk) + self.assertNotContains(response, "`` request: renders just those rows the list + still shows, each with the row (and, for a list split by date, the divider) + that comes after it. The client moves them into place and drops the rows + that aren't listed any more. + See transaction_mover in templates/includes/scripts/hyperscript/transactions.html + + ``rows`` and ``late`` are the list's own ordered querysets, so where a row + goes is always decided by the same ordering the full list uses.""" + wanted = {int(pk) for pk in request.GET.getlist("only") if pk.isdigit()} + combined = Transaction.transfers_combined() + fields = ("id", "date", "type", "linked_transaction_id") + + listed = rows.values_list(*fields) + if paginate_by: + listed = Paginator(listed, paginate_by).get_page(page).object_list + + # [slug, label, rows] in display order, grouped like the list templates + groups = [] + if late is not None: + late_rows = list(late.values_list(*fields)) + if late_rows: + groups.append(["late-transactions", None, late_rows]) + for row in listed: + slug, label = "", "" + if grouped: + label = naturaldate(row[1]) + slug = slugify(label) + if groups and groups[-1][0] == slug: + groups[-1][2].append(row) + else: + groups.append([slug, label, [row]]) + + def row_id(pk, _date, type_, linked_id): + # A combined transfer is shown, and identified, by its "from" side + if combined and linked_id and type_ == Transaction.Type.INCOME: + return linked_id + return pk + + changed = [] + for i, (slug, label, group_rows) in enumerate(groups): + for j, row in enumerate(group_rows): + if row[0] in wanted: + after = group_rows[j + 1] if j + 1 < len(group_rows) else None + changed.append( + { + "pk": row[0], + "slug": slug, + "label": label, + "late": label is None, + "next_id": row_id(*after) if after else "", + "next_group": groups[i + 1][0] if i + 1 < len(groups) else "", + } + ) + + found = Transaction.objects.prefetch_related(*LIST_PREFETCH).in_bulk( + [c["pk"] for c in changed] + ) + for c in changed: + c["transactions"] = [found[c["pk"]]] + + return render( + request, + "transactions/fragments/changed_rows.html", + {"changed": changed}, + ) diff --git a/app/apps/transactions/views/installment_plans.py b/app/apps/transactions/views/installment_plans.py index c89b9cd5..fb803974 100644 --- a/app/apps/transactions/views/installment_plans.py +++ b/app/apps/transactions/views/installment_plans.py @@ -9,6 +9,7 @@ from django.views.decorators.http import require_http_methods from apps.common.decorators.htmx import only_htmx from apps.transactions.forms import InstallmentPlanForm from apps.transactions.models import InstallmentPlan +from apps.transactions.utils.changed_rows import changed_rows @login_required @@ -69,6 +70,9 @@ def installment_plan_transactions(request, installment_plan_id): installment_plan = get_object_or_404(InstallmentPlan.objects, id=installment_plan_id) transactions = installment_plan.transactions.prefetch_related("sub_transactions").order_by("reference_date", "id") + if "only" in request.GET: + return changed_rows(request, transactions, grouped=False) + return render( request, "installment_plans/fragments/list_transactions.html", diff --git a/app/apps/transactions/views/recurring_transactions.py b/app/apps/transactions/views/recurring_transactions.py index e41386e7..93827b62 100644 --- a/app/apps/transactions/views/recurring_transactions.py +++ b/app/apps/transactions/views/recurring_transactions.py @@ -12,6 +12,7 @@ from apps.common.decorators.htmx import only_htmx from apps.transactions.forms import RecurringTransactionForm from apps.transactions.models import RecurringTransaction from apps.transactions.tasks import generate_recurring_transactions +from apps.transactions.utils.changed_rows import changed_rows @login_required @@ -94,6 +95,9 @@ def recurring_transaction_transactions(request, recurring_transaction_id): "reference_date", "id" ) + if "only" in request.GET: + return changed_rows(request, transactions, grouped=False) + return render( request, "recurring_transactions/fragments/list_transactions.html", diff --git a/app/apps/transactions/views/transactions.py b/app/apps/transactions/views/transactions.py index 8c6dfa04..222ca310 100644 --- a/app/apps/transactions/views/transactions.py +++ b/app/apps/transactions/views/transactions.py @@ -19,6 +19,7 @@ from apps.transactions.utils.calculations import ( calculate_currency_totals, calculate_percentage_distribution, ) +from apps.transactions.utils.changed_rows import LIST_PREFETCH, changed_rows from apps.transactions.utils.default_ordering import default_order from apps.transactions.utils.select_search import ( search_transactions, @@ -42,6 +43,21 @@ def _get_accessible_transaction_or_404(transaction_id): return get_object_or_404(Transaction.objects, id=transaction_id) +def _transactions_changed(*transactions, hide_offcanvas=True): + """HX-Trigger for saved transactions. Lists with transaction_mover move just + these rows instead of re-rendering, other pages fall back to a full "updated". + See templates/includes/scripts/hyperscript/transactions.html""" + ids = set() + for transaction in transactions: + ids.add(str(transaction.pk)) + if transaction.linked_transaction_id: + ids.add(str(transaction.linked_transaction_id)) + trigger = {"transactions_changed": {"ids": sorted(ids)}, "toasts": None} + if hide_offcanvas: + trigger["hide_offcanvas"] = None + return json.dumps(trigger) + + def _get_accessible_attachment_or_404(attachment_id): attachment = get_object_or_404( TransactionAttachment.objects.select_related("transaction"), @@ -159,7 +175,7 @@ def transaction_add(request): if "submit" in request.POST: return HttpResponse( status=204, - headers={"HX-Trigger": "updated, hide_offcanvas"}, + headers={"HX-Trigger": _transactions_changed(saved_instance)}, ) elif "submit_and_another" in request.POST: form = TransactionForm( @@ -229,7 +245,9 @@ def transaction_add(request): {"form": form}, ) if update: - response["HX-Trigger"] = "updated" + response["HX-Trigger"] = _transactions_changed( + saved_instance, hide_offcanvas=False + ) return response @@ -367,12 +385,12 @@ def transaction_edit(request, transaction_id, **kwargs): if request.method == "POST": form = TransactionForm(request.POST, instance=transaction) if form.is_valid(): - form.save() + saved_instance = form.save() messages.success(request, _("Transaction updated successfully")) return HttpResponse( status=204, - headers={"HX-Trigger": "updated, hide_offcanvas"}, + headers={"HX-Trigger": _transactions_changed(saved_instance)}, ) else: form = TransactionForm(instance=transaction) @@ -548,11 +566,11 @@ def transactions_transfer(request): if request.method == "POST": form = TransferForm(request.POST) if form.is_valid(): - form.save() + saved = form.save() messages.success(request, _("Transfer added successfully")) return HttpResponse( status=204, - headers={"HX-Trigger": "updated, hide_offcanvas"}, + headers={"HX-Trigger": _transactions_changed(*saved)}, ) else: form = TransferForm( @@ -578,11 +596,11 @@ def transaction_transfer_edit(request, transaction_id): if request.method == "POST": form = TransferForm(request.POST, instance=transaction) if form.is_valid(): - form.save() + saved = form.save() messages.success(request, _("Transfer updated successfully")) return HttpResponse( status=204, - headers={"HX-Trigger": "updated, hide_offcanvas"}, + headers={"HX-Trigger": _transactions_changed(*saved)}, ) else: form = TransferForm(instance=transaction) @@ -825,25 +843,7 @@ def transaction_all_list(request): today = timezone.localdate(timezone.now()) - transactions = Transaction.objects.prefetch_related( - "account", - "account__group", - "category", - "tags", - "account__exchange_currency", - "account__currency", - "installment_plan", - "entities", - "dca_expense_entries", - "sub_transactions", - "dca_income_entries", - "linked_transaction__account__currency", - "linked_transaction__account__group", - "linked_transaction__category", - "linked_transaction__tags", - ).all() - - f = TransactionsFilter(request.GET, queryset=transactions) + f = TransactionsFilter(request.GET, queryset=Transaction.objects.all()) # Late transactions: date < today and is_paid = False (only shown for default ordering on first page) late_transactions = None @@ -864,6 +864,19 @@ def transaction_all_list(request): main_transactions = default_order(main_transactions, order=order) + if "only" in request.GET: + return changed_rows( + request, + main_transactions, + late=late_transactions, + paginate_by=100, + page=page_number, + ) + + if late_transactions is not None: + late_transactions = late_transactions.prefetch_related(*LIST_PREFETCH) + main_transactions = main_transactions.prefetch_related(*LIST_PREFETCH) + paginator = Paginator(main_transactions, 100) page_obj = paginator.get_page(page_number) @@ -895,7 +908,7 @@ def transaction_all_summary(request): "dca_income_entries", ).all() - f = TransactionsFilter(request.GET, queryset=transactions) + f = TransactionsFilter(request.GET, queryset=Transaction.objects.all()) currency_data = calculate_currency_totals(f.qs.all(), ignore_empty=True) currency_percentages = calculate_percentage_distribution(currency_data) @@ -929,7 +942,7 @@ def transaction_all_account_summary(request): "dca_income_entries", ).all() - f = TransactionsFilter(request.GET, queryset=transactions) + f = TransactionsFilter(request.GET, queryset=Transaction.objects.all()) account_data = calculate_account_totals(transactions_queryset=f.qs.all()) account_percentages = calculate_percentage_distribution(account_data) @@ -959,7 +972,7 @@ def transaction_all_currency_summary(request): "dca_income_entries", ).all() - f = TransactionsFilter(request.GET, queryset=transactions) + f = TransactionsFilter(request.GET, queryset=Transaction.objects.all()) currency_data = calculate_currency_totals( f.qs.exclude(account__in=request.user.untracked_accounts.all()), diff --git a/app/templates/calendar_view/fragments/list_transactions.html b/app/templates/calendar_view/fragments/list_transactions.html index 81c57e4f..fcf54d2e 100644 --- a/app/templates/calendar_view/fragments/list_transactions.html +++ b/app/templates/calendar_view/fragments/list_transactions.html @@ -5,7 +5,8 @@ {% block title %}{% translate 'Transactions on' %} {{ date|date:"SHORT_DATE_FORMAT" }}{% endblock %} {% block body %} -
+
{% for transaction in transactions %} {% empty %} diff --git a/app/templates/includes/scripts/hyperscript/transactions.html b/app/templates/includes/scripts/hyperscript/transactions.html index 41659bbc..0d5db97b 100644 --- a/app/templates/includes/scripts/hyperscript/transactions.html +++ b/app/templates/includes/scripts/hyperscript/transactions.html @@ -57,6 +57,144 @@ trigger updated on window end end + + -- Saved transactions only get moved in place by a list with + -- transaction_mover, everywhere else the page reloads like before + on transactions_changed from window + if no <[data-moves-transactions]/> then trigger updated on window end + end + + -- Puts added or edited transactions in place without reloading the list. + -- + -- The add and edit endpoints answer with `transactions_changed` and the ids + -- they saved. The list asks its own endpoint (hx-get, with its hx-include + -- values) for just those rows with ?only=. The server answers with each row + -- it still shows plus the row that comes after it (and for a list split by + -- date, the row's divider and the divider after that), so where a row goes is + -- always decided by the server's ordering. Rows it doesn't answer with have + -- left the list (filter, month) and go away. + -- See apps/transactions/utils/changed_rows.py + -- + -- With data-moves-transactions="page" the list is one page of many: a row + -- that joins or leaves it shifts every page after it, so that reloads instead. + behavior transaction_mover + on transactions_changed from window + set ids to event.detail.ids + if me.matches('#transactions-list') + set list to me + else + set list to the first <#transactions-list/> in me + end + if no ids or no list then exit end + if no <.transaction/> in list + -- the empty state is server-rendered + trigger updated on window + exit + end + + make a URLSearchParams called params + if my @hx-include + repeat for source in document.querySelectorAll(my @hx-include) + if source.matches('form') + make a FormData from source called fields + repeat for pair in Array.from(fields.entries()) + call params.append(pair[0], pair[1]) + end + else if source.name + call params.set(source.name, source.value) + end + end + end + repeat for id in ids + call params.append('only', id) + end + call fetch(`${my @hx-get}?${params}`, {headers: {'HX-Request': 'true'}}) + set res to it + if not res.ok + trigger updated on window + exit + end + call res.text() + set markup to it + + make a