mirror of
https://github.com/eitchtee/WYGIWYH.git
synced 2026-11-29 11:52:56 +01:00
Merge pull request #648 from eitchtee/feat/transaction-picker
feat(transactions): better transaction picker for DCA and rules
This commit is contained in:
6 files changed
+342
-33
No files matched your search
@@ -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
|
||||
@@ -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"), [])
|
||||
@@ -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"))
|
||||
@@ -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)
|
||||
@@ -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 `<div>${escape(data.text)}</div>`;
|
||||
}
|
||||
const kind = data.type === 'EX' ? 'expense' : 'income';
|
||||
const meta = [
|
||||
data.category && `<span><i class="fa-solid fa-icons fa-fw"></i>${escape(data.category)}</span>`,
|
||||
data.tags && data.tags.length && `<span><i class="fa-solid fa-hashtag fa-fw"></i>${escape(data.tags.join(', '))}</span>`,
|
||||
data.entities && data.entities.length && `<span><i class="fa-solid fa-user-group fa-fw"></i>${escape(data.entities.join(', '))}</span>`,
|
||||
].filter(Boolean).join('');
|
||||
return `<div class="ts-tx ts-tx-${kind}${compact ? ' ts-tx-compact' : ''}">
|
||||
<i class="ts-tx-paid fa-regular ${data.is_paid ? 'fa-circle-check' : 'fa-circle'}"></i>
|
||||
<div class="ts-tx-main">
|
||||
<div class="ts-tx-date"><i class="fa-solid fa-calendar fa-fw"></i>${escape(data.date)}</div>
|
||||
<div class="ts-tx-desc">${escape(data.description || '')}</div>
|
||||
${meta && !compact ? `<div class="ts-tx-meta">${meta}</div>` : ''}
|
||||
</div>
|
||||
<div class="ts-tx-side">
|
||||
<div class="ts-tx-amount text-${kind}">${escape(data.amount)}</div>
|
||||
<div class="ts-tx-account">${escape(data.account)}</div>
|
||||
</div>
|
||||
</div>`;
|
||||
}
|
||||
|
||||
window.TomSelect = function createDynamicTomSelect(element) {
|
||||
const schedulePopperUpdate = function (instance) {
|
||||
// Wait for TomSelect DOM updates before recalculating dropdown position.
|
||||
@@ -98,12 +123,25 @@ window.TomSelect = function createDynamicTomSelect(element) {
|
||||
};
|
||||
}
|
||||
|
||||
if (element.dataset.render === 'transaction') {
|
||||
config.dataAttr = 'data'; // dataset key of the data-data attribute
|
||||
config.render.option = (data, escape) => renderTransaction(data, escape, false);
|
||||
config.render.item = (data, escape) => renderTransaction(data, escape, true);
|
||||
}
|
||||
|
||||
if (element.dataset.load) {
|
||||
// The server searches and orders; don't let tom-select re-filter or re-sort the results
|
||||
config.score = () => () => 1;
|
||||
config.sortField = [{field: '$order'}];
|
||||
config.preload = 'focus';
|
||||
config.shouldLoad = () => true;
|
||||
config.load = function (query, callback) {
|
||||
let url = element.dataset.load + '?q=' + encodeURIComponent(query);
|
||||
fetch(url)
|
||||
.then(response => response.json())
|
||||
.then(json => {
|
||||
// Drop results from the previous query, keeping the selected item
|
||||
this.clearOptions();
|
||||
callback(json);
|
||||
}).catch(() => {
|
||||
callback();
|
||||
|
||||
@@ -399,3 +399,98 @@
|
||||
.tomselect-checkbox {
|
||||
margin-right: 0.5rem;
|
||||
}
|
||||
|
||||
/* Mini transaction (TransactionSelect) */
|
||||
.ts-tx {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.75rem;
|
||||
width: 100%;
|
||||
min-width: 0;
|
||||
padding: 0.375rem 0.5rem;
|
||||
border-left: 4px solid var(--color-success);
|
||||
border-radius: var(--radius-field, 0.25rem);
|
||||
background-color: var(--color-base-100);
|
||||
font-family: var(--font-mono, ui-monospace, monospace);
|
||||
font-size: 0.8125rem;
|
||||
line-height: 1.25rem;
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
.ts-tx-expense {
|
||||
border-left-color: var(--color-error);
|
||||
}
|
||||
|
||||
.ts-tx-paid {
|
||||
color: color-mix(in oklab, var(--color-base-content) 50%, transparent);
|
||||
font-size: 1.125rem;
|
||||
}
|
||||
|
||||
.ts-tx-main,
|
||||
.ts-tx-side {
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.ts-tx-main {
|
||||
flex: 1 1 auto;
|
||||
}
|
||||
|
||||
.ts-tx-side {
|
||||
flex: 0 1 auto;
|
||||
max-width: 45%;
|
||||
text-align: right;
|
||||
}
|
||||
|
||||
.ts-tx-date,
|
||||
.ts-tx-meta,
|
||||
.ts-tx-account {
|
||||
color: color-mix(in oklab, var(--color-base-content) 70%, transparent);
|
||||
font-size: 0.75rem;
|
||||
}
|
||||
|
||||
.ts-tx i.fa-fw {
|
||||
margin-right: 0.25rem;
|
||||
font-size: 0.625rem;
|
||||
}
|
||||
|
||||
.ts-tx-desc {
|
||||
color: var(--color-base-content);
|
||||
font-size: 0.875rem;
|
||||
}
|
||||
|
||||
.ts-tx-meta {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
column-gap: 0.75rem;
|
||||
}
|
||||
|
||||
.ts-tx-amount {
|
||||
font-weight: 500;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.ts-tx-desc,
|
||||
.ts-tx-account {
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
/* Selected value inside the control: no card chrome, leave room for the clear button and arrow */
|
||||
.ts-control .ts-tx-compact {
|
||||
padding: 0 1.5rem 0 0.5rem;
|
||||
background: transparent;
|
||||
}
|
||||
|
||||
.ts-dropdown .option:has(.ts-tx) {
|
||||
padding: 0.25rem 0.375rem;
|
||||
}
|
||||
|
||||
.ts-dropdown .active .ts-tx {
|
||||
background-color: transparent;
|
||||
}
|
||||
|
||||
.ts-control > .item:has(.ts-tx) {
|
||||
flex: 1 1 auto;
|
||||
min-width: 0;
|
||||
}
|
||||
Reference in new issue
Block a user