diff --git a/app/apps/common/widgets/tom_select.py b/app/apps/common/widgets/tom_select.py index 5c9b0548..0f22d106 100644 --- a/app/apps/common/widgets/tom_select.py +++ b/app/apps/common/widgets/tom_select.py @@ -1,3 +1,5 @@ +import json + from django.forms import SelectMultiple, widgets from django.urls import reverse from django.utils.translation import gettext_lazy as _ @@ -142,6 +144,7 @@ class TransactionSelect(TomSelect): def build_attrs(self, base_attrs, extra_attrs=None): attrs = super().build_attrs(base_attrs, extra_attrs) + attrs["data-render"] = "transaction" if self.load_income and self.load_expense: attrs["data-load"] = reverse("transactions_search") @@ -155,3 +158,13 @@ class TransactionSelect(TomSelect): ) return attrs + + def create_option(self, name, value, *args, **kwargs): + option = super().create_option(name, value, *args, **kwargs) + instance = getattr(value, "instance", None) + if instance is not None: + from apps.transactions.utils.select_search import transaction_option + + # tom-select reads this to render the selected transaction like the search results + option["attrs"]["data-data"] = json.dumps(transaction_option(instance)) + return option diff --git a/app/apps/transactions/tests/test_transaction_search.py b/app/apps/transactions/tests/test_transaction_search.py new file mode 100644 index 00000000..6b02e95b --- /dev/null +++ b/app/apps/transactions/tests/test_transaction_search.py @@ -0,0 +1,74 @@ +from datetime import timedelta +from decimal import Decimal + +from django.contrib.auth import get_user_model +from django.test import TestCase +from django.urls import reverse +from django.utils import timezone + +from apps.accounts.models import Account +from apps.currencies.models import Currency +from apps.transactions.models import ( + Transaction, + TransactionCategory, + TransactionEntity, + TransactionTag, +) + + +class TransactionSearchTests(TestCase): + def setUp(self): + self.user = get_user_model().objects.create_user( + email="search@test.com", password="pass" + ) + self.client.login(username="search@test.com", password="pass") + self.user.settings.date_format = "d/m/Y" + self.user.settings.number_format = "DC" + self.user.settings.save() + + currency = Currency.objects.create(code="BRL", name="Real", decimal_places=2) + self.account = Account.objects.create(name="Wallet", currency=currency) + self.today = timezone.localdate(timezone.now()) + + def make(self, days, description="", amount="10", **kwargs): + return Transaction.objects.create( + account=self.account, + type=Transaction.Type.EXPENSE, + date=self.today + timedelta(days=days), + reference_date=(self.today + timedelta(days=days)).replace(day=1), + amount=Decimal(amount), + description=description, + **kwargs, + ) + + def search(self, q=""): + response = self.client.get(reverse("transactions_search"), {"q": q}) + self.assertEqual(response.status_code, 200) + return [row["description"] for row in response.json()] + + def test_order_matches_monthly_view(self): + for days, name in [(-30, "old"), (-2, "recent"), (-1, "yesterday"), + (10, "far"), (2, "soon"), (1, "tomorrow"), (0, "today")]: + self.make(days, name) + self.assertEqual( + self.search(), + ["today", "tomorrow", "yesterday", "soon", "far", "recent", "old"], + ) + + def test_search_fields(self): + t = self.make(-5, "Groceries", amount="1234.56") + t.category = TransactionCategory.objects.create(name="Food") + t.save() + t.tags.add(TransactionTag.objects.create(name="home"), + TransactionTag.objects.create(name="weekly")) + t.entities.add(TransactionEntity.objects.create(name="Market")) + self.make(-6, "Other", amount="5") + + day = (self.today - timedelta(days=5)) + for q in ["food", "market", "1.234,56", "1234", + day.strftime("%d/%m/%Y"), day.strftime("%d/%m"), + "home weekly", "groceries food"]: + self.assertEqual(self.search(q), ["Groceries"], q) + + self.assertEqual(self.search("wallet"), ["Groceries", "Other"]) + self.assertEqual(self.search("groceries nomatch"), []) diff --git a/app/apps/transactions/utils/select_search.py b/app/apps/transactions/utils/select_search.py new file mode 100644 index 00000000..161383a5 --- /dev/null +++ b/app/apps/transactions/utils/select_search.py @@ -0,0 +1,95 @@ +import datetime +import re +from decimal import Decimal, InvalidOperation + +from apps.common.functions.format import get_format +from apps.common.utils.django import django_to_python_datetime +from apps.transactions.templatetags.currency_display import currency_display +from django.db.models import Q +from django.template.defaultfilters import date as date_filter + + +def transaction_option(t): + """Data used by the transaction picker (tom-select) to render a mini transaction.""" + currency = t.account.currency + return { + "value": str(t.id), + "text": str(t), + "description": t.description, + "date": date_filter(t.date, "SHORT_DATE_FORMAT"), + "type": t.type, + "is_paid": t.is_paid, + "amount": currency_display( + t.amount, + currency.prefix, + currency.suffix, + currency.decimal_places, + string=True, + ), + "account": ( + f"{t.account.group.name} • {t.account.name}" + if t.account.group + else t.account.name + ), + "category": t.category.name if t.category else "", + "tags": [tag.name for tag in t.tags.all()], + "entities": [entity.name for entity in t.entities.all()], + } + + +def _parse_date(term): + """Match a term against the user's date format; without a year it matches any year.""" + fmt = django_to_python_datetime(get_format("SHORT_DATE_FORMAT")) + try: + return Q(date=datetime.datetime.strptime(term, fmt).date()) + except ValueError: + pass + # Drop the year and its adjacent separator, e.g. "%d/%m/%Y" -> "%d/%m" + no_year = re.sub(r"[^%\w]?%[Yy][^%\w]?", "", fmt, count=1).strip() + if no_year == fmt or not no_year: + return None + try: + # 2000 is a leap year, so 29/02 parses + parsed = datetime.datetime.strptime(f"{term} 2000", f"{no_year} %Y") + except ValueError: + return None + return Q(date__day=parsed.day, date__month=parsed.month) + + +def _parse_amount(term): + if not re.fullmatch(r"[\d.,\s]*\d[\d.,\s]*", term): + return None + thousand = get_format("THOUSAND_SEPARATOR") + decimal = get_format("DECIMAL_SEPARATOR") + normalized = term.replace(thousand, "").replace(decimal, ".") + try: + value = Decimal(normalized) + except InvalidOperation: + return None + if decimal not in term: + # Whole number: "12" finds 12.00 to 12.99 + return Q(amount__gte=value, amount__lt=value + 1) + return Q(amount=value) + + +def search_transactions(queryset, search_term): + """Every word must match some field (description, category, entity, date, amount...).""" + matches = queryset.model.objects.all() + for term in search_term.split(): + term_q = ( + Q(description__icontains=term) + | Q(notes__icontains=term) + | Q(internal_note__icontains=term) + | Q(tags__name__icontains=term) + | Q(entities__name__icontains=term) + | Q(category__name__icontains=term) + | Q(account__name__icontains=term) + | Q(account__group__name__icontains=term) + ) + for extra in (_parse_date(term), _parse_amount(term)): + if extra is not None: + term_q |= extra + # One filter() per word so different words can match different tags/entities + matches = matches.filter(term_q) + # id__in avoids duplicate rows from the tag/entity joins + return queryset.filter(id__in=matches.values("id")) diff --git a/app/apps/transactions/views/transactions.py b/app/apps/transactions/views/transactions.py index a18c17bf..fa2f0207 100644 --- a/app/apps/transactions/views/transactions.py +++ b/app/apps/transactions/views/transactions.py @@ -20,11 +20,15 @@ from apps.transactions.utils.calculations import ( calculate_percentage_distribution, ) from apps.transactions.utils.default_ordering import default_order +from apps.transactions.utils.select_search import ( + search_transactions, + transaction_option, +) from dateutil.relativedelta import relativedelta from django.contrib import messages from django.contrib.auth.decorators import login_required from django.core.paginator import Paginator -from django.db.models import Case, IntegerField, Q, Value, When +from django.db.models import Case, F, IntegerField, Q, Value, When from django.http import FileResponse, Http404, HttpResponse, JsonResponse, QueryDict from django.shortcuts import get_object_or_404, render from django.utils import timezone @@ -971,51 +975,41 @@ def transactions_trash_can_list(request): @login_required @require_http_methods(["GET"]) def get_recent_transactions(request, filter_type=None): - """Return the 100 most recent non-deleted transactions with optional search.""" - # Get search term from query params + """Return up to 100 non-deleted transactions, ordered like the monthly view, with optional search.""" search_term = request.GET.get("q", "").strip() today = timezone.localdate(timezone.now()) yesterday = today - timezone.timedelta(days=1) tomorrow = today + timezone.timedelta(days=1) - # Base queryset with selected fields + queryset = Transaction.objects.filter(deleted=False) + + if filter_type == "expenses": + queryset = queryset.filter(type=Transaction.Type.EXPENSE) + elif filter_type == "income": + queryset = queryset.filter(type=Transaction.Type.INCOME) + + if search_term: + queryset = search_transactions(queryset, search_term) + + # Today, tomorrow, yesterday, then upcoming (soonest first), then past (newest first) queryset = ( - Transaction.objects.filter(deleted=False) - .annotate( + queryset.annotate( date_order=Case( When(date=today, then=Value(0)), When(date=tomorrow, then=Value(1)), When(date=yesterday, then=Value(2)), When(date__gt=tomorrow, then=Value(3)), - When(date__lt=yesterday, then=Value(4)), - default=Value(5), + default=Value(4), output_field=IntegerField(), - ) + ), + upcoming_date=Case(When(date__gt=tomorrow, then=F("date"))), ) - .select_related("account", "category") - .order_by("date_order", "date", "id") + .select_related("account__currency", "account__group", "category") + .prefetch_related("tags", "entities") + .order_by( + "date_order", F("upcoming_date").asc(nulls_last=True), "-date", "-id" + )[:100] ) - if filter_type: - if filter_type == "expenses": - queryset = queryset.filter(type=Transaction.Type.EXPENSE) - elif filter_type == "income": - queryset = queryset.filter(type=Transaction.Type.INCOME) - - # Apply search if provided - if search_term: - queryset = queryset.filter( - Q(description__icontains=search_term) - | Q(notes__icontains=search_term) - | Q(internal_note__icontains=search_term) - | Q(tags__name__icontains=search_term) - | Q(category__name__icontains=search_term) - ) - - # Prepare data for JSON response - data = [] - for t in queryset: - data.append({"text": str(t), "value": str(t.id)}) - - return JsonResponse(data, safe=False) + return JsonResponse([transaction_option(t) for t in queryset], safe=False) diff --git a/frontend/src/js/select.js b/frontend/src/js/select.js index f40494ab..dc573918 100644 --- a/frontend/src/js/select.js +++ b/frontend/src/js/select.js @@ -3,6 +3,31 @@ import * as Popper from "@popperjs/core"; import '../styles/_tom-select.scss' +// Mini version of cotton/transaction/item.html, used by TransactionSelect +function renderTransaction(data, escape, compact) { + if (!data.date) { + return `