from django.core.paginator import Paginator from django.shortcuts import render from django.utils.text import slugify from apps.common.templatetags.natural import naturaldate from apps.transactions.models import Transaction # What a transaction row (cotton/transaction/item.html) reads LIST_PREFETCH = ( "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", ) def changed_rows( request, rows, late=None, grouped=True, paginate_by=None, page=None ): """Answers a list's ``?only=`` 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}, )