Open-source personal finance manager. Self-hosted, privacy-first.
feat: filter transactions by amount or range (#212) (#213)
Tássio Noronha95e250c229c0
diff --git a/backend/app/api/transactions.py b/backend/app/api/transactions.pyindex 1d1a7d3a..23430424 100644--- a/backend/app/api/transactions.py+++ b/backend/app/api/transactions.py@@ -77,6 +77,8 @@ async def list_transactions(include_opening_balance: bool = Query(False),exclude_transfers: bool = Query(False),tags: Optional[List[str]] = Query(None),+ min_amount: Optional[float] = Query(None, ge=0, description="Filter to transactions with absolute amount >= this value (primary currency)."),+ max_amount: Optional[float] = Query(None, ge=0, description="Filter to transactions with absolute amount <= this value (primary currency)."),sort_by: Optional[str] = Query(None, description="Column to sort by (date|amount|description|payee|category|account|type|status). Default: date desc."),sort_dir: str = Query("desc", regex="^(asc|desc)$"),session: AsyncSession = Depends(get_async_session),@@ -97,6 +99,8 @@ async def list_transactions(unbilled_only=unbilled_only,sort_by=sort_by,sort_dir=sort_dir,+ min_amount=min_amount,+ max_amount=max_amount,include_summary=True,)primary_currency = user.primary_currencydiff --git a/backend/tests/test_transactions_api.py b/backend/tests/test_transactions_api.pyindex ffd212aa..bd3ea0a9 100644--- a/backend/tests/test_transactions_api.py+++ b/backend/tests/test_transactions_api.py@@ -137,6 +137,82 @@ async def test_list_transactions_filter_by_category_ids_no_match(assert data["items"] == []+async def test_list_transactions_filter_by_exact_amount(+ client: AsyncClient, auth_headers, test_transactions: list[Transaction],+):+ """Setting min_amount==max_amount matches only that exact amount (issue #212)."""+ response = await client.get(+ "/api/transactions?min_amount=45&max_amount=45", headers=auth_headers+ )+ assert response.status_code == 200+ data = response.json()+ assert data["total"] == 1+ assert data["items"][0]["description"] == "IFOOD RESTAURANTE"+++async def test_list_transactions_filter_by_min_amount(+ client: AsyncClient, auth_headers, test_transactions: list[Transaction],+):+ """min_amount alone is an open-ended lower bound."""+ response = await client.get(+ "/api/transactions?min_amount=40", headers=auth_headers+ )+ assert response.status_code == 200+ data = response.json()+ descriptions = {item["description"] for item in data["items"]}+ # 45.00 IFOOD, 150.00 PIX, 8000.00 SALARIO — UBER 25.50 and NETFLIX 39.90 dropped+ assert descriptions == {"IFOOD RESTAURANTE", "PIX RECEBIDO", "SALARIO FEV"}+ assert data["total"] == 3+++async def test_list_transactions_filter_by_max_amount(+ client: AsyncClient, auth_headers, test_transactions: list[Transaction],+):+ """max_amount alone is an open-ended upper bound."""+ response = await client.get(+ "/api/transactions?max_amount=50", headers=auth_headers+ )+ assert response.status_code == 200+ data = response.json()+ descriptions = {item["description"] for item in data["items"]}+ # 25.50 UBER, 39.90 NETFLIX, 45.00 IFOOD — PIX 150 and SALARIO 8000 dropped+ assert descriptions == {"UBER TRIP", "NETFLIX", "IFOOD RESTAURANTE"}+ assert data["total"] == 3+++async def test_list_transactions_filter_by_amount_range(+ client: AsyncClient, auth_headers, test_transactions: list[Transaction],+):+ """Combining min_amount + max_amount filters to a closed range."""+ response = await client.get(+ "/api/transactions?min_amount=40&max_amount=60", headers=auth_headers+ )+ assert response.status_code == 200+ data = response.json()+ assert data["total"] == 1+ assert data["items"][0]["description"] == "IFOOD RESTAURANTE"+++async def test_list_transactions_amount_filter_combines_with_type(+ client: AsyncClient, auth_headers, test_transactions: list[Transaction],+):+ """Amount filters compose with other filters (here: type=debit)."""+ response = await client.get(+ "/api/transactions?max_amount=50&type=debit", headers=auth_headers+ )+ assert response.status_code == 200+ data = response.json()+ descriptions = {item["description"] for item in data["items"]}+ # Among <=50: UBER (debit), NETFLIX (debit), IFOOD (debit). PIX 150 excluded by amount.+ assert descriptions == {"UBER TRIP", "NETFLIX", "IFOOD RESTAURANTE"}+ assert data["total"] == 3++@pytest.mark.asyncioasync def test_list_transactions_filter_by_account_ids_multi(client: AsyncClient,diff --git a/frontend/src/components/transactions-filter-bar.tsx b/frontend/src/components/transactions-filter-bar.tsxindex 79509d6f..ca8cb0ee 100644--- a/frontend/src/components/transactions-filter-bar.tsx+++ b/frontend/src/components/transactions-filter-bar.tsx@@ -7,6 +7,7 @@ import {Calendar as CalendarIcon,Check,ChevronRight,+ Coins,ListFilter,Search,Store,@@ -60,6 +61,9 @@ interface TransactionsFilterBarProps {filterFrom: stringfilterTo: stringonDateRangeChange: (from: string, to: string) => void+ filterMinAmount: string+ filterMaxAmount: string+ onAmountRangeChange: (min: string, max: string) => voidonClearAll: () => voidaccounts: Account[]categories: Category[]@@ -95,6 +99,9 @@ export function TransactionsFilterBar({filterFrom,filterTo,onDateRangeChange,+ filterMinAmount,+ filterMaxAmount,+ onAmountRangeChange,onClearAll,accounts,categories,@@ -113,6 +120,9 @@ export function TransactionsFilterBar({const [dateCustomOpen, setDateCustomOpen] = useState(false)const [draftFrom, setDraftFrom] = useState<string>(filterFrom)const [draftTo, setDraftTo] = useState<string>(filterTo)+ const [amountSubOpen, setAmountSubOpen] = useState(false)+ const [draftMinAmount, setDraftMinAmount] = useState<string>(filterMinAmount)+ const [draftMaxAmount, setDraftMaxAmount] = useState<string>(filterMaxAmount)const searchRef = useRef<HTMLInputElement>(null)// When a CheckRow is clicked inside a submenu, Radix tries to close the submenu@@ -138,6 +148,7 @@ export function TransactionsFilterBar({if (!open) {setAccountSubOpen(false)setCategorySubOpen(false)+ setAmountSubOpen(false)keepAccountSubOpenRef.current = falsekeepCategorySubOpenRef.current = false}@@ -174,6 +185,8 @@ export function TransactionsFilterBar({!!filterType ||!!filterFrom ||!!filterTo ||+ !!filterMinAmount ||+ !!filterMaxAmount ||searchInput.trim().length > 0const typeLabel =@@ -195,6 +208,49 @@ export function TransactionsFilterBar({return `≤ ${fmt(filterTo)}`}, [filterFrom, filterTo, locale])+ const amountLabel = useMemo(() => {+ if (!filterMinAmount && !filterMaxAmount) return null+ const fmt = (raw: string) => {+ const n = Number(raw)+ if (!Number.isFinite(n)) return raw+ return n.toLocaleString(locale, {+ minimumFractionDigits: 2,+ maximumFractionDigits: 2,+ })+ }+ if (filterMinAmount && filterMaxAmount) {+ if (filterMinAmount === filterMaxAmount) return `= ${fmt(filterMinAmount)}`+ return `${fmt(filterMinAmount)} — ${fmt(filterMaxAmount)}`+ }+ if (filterMinAmount) return `≥ ${fmt(filterMinAmount)}`+ return `≤ ${fmt(filterMaxAmount)}`+ }, [filterMinAmount, filterMaxAmount, locale])++ const applyAmountRange = () => {+ const normalize = (raw: string) => raw.trim().replace(',', '.')+ const min = normalize(draftMinAmount)+ const max = normalize(draftMaxAmount)+ const minOk = min === '' || (Number.isFinite(Number(min)) && Number(min) >= 0)+ const maxOk = max === '' || (Number.isFinite(Number(max)) && Number(max) >= 0)+ if (!minOk || !maxOk) return+ // Swap if user inverted the range so the filter still makes sense.+ if (min && max && Number(min) > Number(max)) {+ onAmountRangeChange(max, min)+ } else {+ onAmountRangeChange(min, max)+ }+ setAmountSubOpen(false)+ setMenuOpen(false)+ }++ const handleAmountSubOpenChange = (open: boolean) => {+ if (open) {+ setDraftMinAmount(filterMinAmount)+ setDraftMaxAmount(filterMaxAmount)+ }+ setAmountSubOpen(open)+ }+const datePresets = useMemo(() => {const today = new Date()return [@@ -652,6 +708,101 @@ export function TransactionsFilterBar({</DropdownMenuSubContent></DropdownMenuPortal></DropdownMenuSub>++ {/* Amount range submenu — exact match by setting min=max */}+ <DropdownMenuSub+ open={amountSubOpen}+ onOpenChange={handleAmountSubOpenChange}+ >+ <DropdownMenuSubTrigger className="gap-2 text-[13px]">+ <Coins size={14} className="text-muted-foreground" />+ <span className="flex-1">+ {t('transactions.filtersBar.amount')}+ </span>+ {amountLabel && (+ <span className="max-w-[90px] truncate text-[11px] text-muted-foreground">+ {amountLabel}+ </span>+ )}+ </DropdownMenuSubTrigger>+ <DropdownMenuPortal>+ <DropdownMenuSubContent+ sideOffset={8}+ className="w-[260px] p-2"+ >+ <div className="flex items-center gap-2">+ <div className="flex-1">+ <label className="block px-1 pb-1 text-[10.5px] font-semibold uppercase tracking-[0.08em] text-muted-foreground/80">+ {t('transactions.filtersBar.amountMinLabel')}+ </label>+ <input+ type="number"+ inputMode="decimal"+ min={0}+ step="0.01"+ placeholder="0.00"+ value={draftMinAmount}+ onChange={(e) => setDraftMinAmount(e.target.value)}+ onKeyDown={(e) => {+ if (e.key === 'Enter') {+ e.preventDefault()+ applyAmountRange()+ }+ }}+ className="h-8 w-full rounded-md border border-border bg-background px-2 text-[13px] outline-none focus:border-primary/60 focus:ring-[2px] focus:ring-primary/15"+ />+ </div>+ <div className="flex-1">+ <label className="block px-1 pb-1 text-[10.5px] font-semibold uppercase tracking-[0.08em] text-muted-foreground/80">+ {t('transactions.filtersBar.amountMaxLabel')}+ </label>+ <input+ type="number"+ inputMode="decimal"+ min={0}+ step="0.01"+ placeholder="0.00"+ value={draftMaxAmount}+ onChange={(e) => setDraftMaxAmount(e.target.value)}+ onKeyDown={(e) => {+ if (e.key === 'Enter') {+ e.preventDefault()+ applyAmountRange()+ }+ }}+ className="h-8 w-full rounded-md border border-border bg-background px-2 text-[13px] outline-none focus:border-primary/60 focus:ring-[2px] focus:ring-primary/15"+ />+ </div>+ </div>+ <p className="mt-2 text-[10.5px] leading-snug text-muted-foreground/80">+ {t('transactions.filtersBar.amountHint')}+ </p>+ <div className="mt-2 flex items-center justify-between gap-2">+ <button+ type="button"+ onClick={() => {+ setDraftMinAmount('')+ setDraftMaxAmount('')+ onAmountRangeChange('', '')+ setAmountSubOpen(false)+ setMenuOpen(false)+ }}+ className="text-[12px] font-medium text-muted-foreground transition-colors hover:text-foreground"+ >+ {t('transactions.filtersBar.reset')}+ </button>+ <Button+ type="button"+ size="sm"+ disabled={!draftMinAmount && !draftMaxAmount}+ onClick={applyAmountRange}+ >+ {t('transactions.filtersBar.apply')}+ </Button>+ </div>+ </DropdownMenuSubContent>+ </DropdownMenuPortal>+ </DropdownMenuSub></DropdownMenuGroup>{hasAnyFilter && (@@ -680,7 +831,8 @@ export function TransactionsFilterBar({filterUncategorized ||!!selectedPayee ||!!typeLabel ||- !!dateLabel) && (+ !!dateLabel ||+ !!amountLabel) && (<div className="flex flex-wrap items-center gap-1 border-t border-border/60 px-2 py-1.5">{filterAccountIds.map((id) => {const account = accountById.get(id)@@ -747,6 +899,14 @@ export function TransactionsFilterBar({onRemove={() => onDateRangeChange('', '')}/>)}+ {amountLabel && (+ <FilterChip+ icon={<Coins size={12} />}+ label={t('transactions.filtersBar.amount')}+ value={amountLabel}+ onRemove={() => onAmountRangeChange('', '')}+ />+ )}</div>)}</div>diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.tsindex aff0df52..bc31a0d0 100644--- a/frontend/src/lib/api.ts+++ b/frontend/src/lib/api.ts@@ -273,6 +273,8 @@ export const transactions = {include_opening_balance?: booleanexclude_transfers?: booleantags?: string[]+ min_amount?: number+ max_amount?: numbersort_by?: stringsort_dir?: 'asc' | 'desc'}): Promise<PaginatedTransactions> => {diff --git a/frontend/src/locales/en.json b/frontend/src/locales/en.jsonindex 4d0f094d..ebb55a28 100644--- a/frontend/src/locales/en.json+++ b/frontend/src/locales/en.json@@ -315,6 +315,10 @@"filters": "Filters","filterBy": "Filter by","date": "Date",+ "amount": "Amount",+ "amountMinLabel": "Min",+ "amountMaxLabel": "Max",+ "amountHint": "Leave one empty for an open-ended range. Set both to the same value to match exactly.","customRange": "Custom range…","pickRange": "Pick a start and end date","noOptions": "Nothing here yet",diff --git a/frontend/src/locales/pt-BR.json b/frontend/src/locales/pt-BR.jsonindex 33837f86..ce1041ca 100644--- a/frontend/src/locales/pt-BR.json+++ b/frontend/src/locales/pt-BR.json@@ -315,6 +315,10 @@"filters": "Filtros","filterBy": "Filtrar por","date": "Data",+ "amount": "Valor",+ "amountMinLabel": "Mín",+ "amountMaxLabel": "Máx",+ "amountHint": "Deixe um vazio para um intervalo aberto. Use o mesmo valor nos dois para buscar exato.","customRange": "Período personalizado…","pickRange": "Escolha uma data inicial e final","noOptions": "Nada por aqui ainda",diff --git a/frontend/src/pages/transactions.tsx b/frontend/src/pages/transactions.tsxindex 9849b9dd..f40eb721 100644--- a/frontend/src/pages/transactions.tsx+++ b/frontend/src/pages/transactions.tsx@@ -87,6 +87,8 @@ export default function TransactionsPage() {const [filterPayee, setFilterPayee] = useState<string>(searchParams.get('payee_id') ?? '')const [filterGroupId, setFilterGroupId] = useState<string>(searchParams.get('group_id') ?? '')const [filterType, setFilterType] = useState<string>(searchParams.get('type') ?? '')+ const [filterMinAmount, setFilterMinAmount] = useState<string>(searchParams.get('min_amount') ?? '')+ const [filterMaxAmount, setFilterMaxAmount] = useState<string>(searchParams.get('max_amount') ?? '')const [tagFilters, setTagFilters] = useState<string[]>([])// When the page is opened with a `group_id`, fetch its name so the@@ -153,6 +155,8 @@ export default function TransactionsPage() {setFilterAccountIds(accounts ? accounts.split(',') : []);setFilterFrom(searchParams.get('from') ?? '');setFilterTo(searchParams.get('to') ?? '');+ setFilterMinAmount(searchParams.get('min_amount') ?? '');+ setFilterMaxAmount(searchParams.get('max_amount') ?? '');setPage(1)}, [searchParams])@@ -171,6 +175,8 @@ export default function TransactionsPage() {['account_id', filterAccountIds.join(',')],['from', filterFrom],['to', filterTo],+ ['min_amount', filterMinAmount],+ ['max_amount', filterMaxAmount],].filter(([, v]) => v.length),);@@ -190,6 +196,8 @@ export default function TransactionsPage() {filterAccountIds,filterFrom,filterTo,+ filterMinAmount,+ filterMaxAmount,]);useEffect(() => {@@ -205,7 +213,7 @@ export default function TransactionsPage() {useEffect(() => {setSelectedIds(new Set())setBulkCategory('')- }, [page, filterAccountIds, filterCategoryIds, filterUncategorized, filterPayee, filterType, filterFrom, filterTo, searchQuery])+ }, [page, filterAccountIds, filterCategoryIds, filterUncategorized, filterPayee, filterType, filterFrom, filterTo, filterMinAmount, filterMaxAmount, searchQuery])// Reset bulk category when selection changes so the same category can be re-applieduseEffect(() => {@@ -234,7 +242,7 @@ export default function TransactionsPage() {}, [highlightId, searchQuery, filterPayee, filterCategoryIds, page])const { data, isLoading } = useQuery({- queryKey: ['transactions', page, filterAccountIds, filterCategoryIds, filterUncategorized, filterPayee, filterGroupId, filterType, filterFrom, filterTo, searchQuery, tagFilters, grid.sortBy, grid.sortDir],+ queryKey: ['transactions', page, filterAccountIds, filterCategoryIds, filterUncategorized, filterPayee, filterGroupId, filterType, filterFrom, filterTo, filterMinAmount, filterMaxAmount, searchQuery, tagFilters, grid.sortBy, grid.sortDir],queryFn: () =>transactions.list({page,@@ -247,6 +255,8 @@ export default function TransactionsPage() {uncategorized: filterUncategorized ? true : undefined,from: filterFrom || undefined,to: filterTo || undefined,+ min_amount: filterMinAmount ? Number(filterMinAmount) : undefined,+ max_amount: filterMaxAmount ? Number(filterMaxAmount) : undefined,q: searchQuery || undefined,tags: tagFilters.length > 0 ? tagFilters : undefined,...grid.apiSort,@@ -267,6 +277,8 @@ export default function TransactionsPage() {uncategorized: filterUncategorized || undefined,from: filterFrom || undefined,to: filterTo || undefined,+ min_amount: filterMinAmount || undefined,+ max_amount: filterMaxAmount || undefined,tags: tagFilters.length ? tagFilters : undefined,sort_by: grid.sortBy,sort_dir: grid.sortDir,@@ -1040,6 +1052,9 @@ export default function TransactionsPage() {filterFrom={filterFrom}filterTo={filterTo}onDateRangeChange={(from, to) => { setFilterFrom(from); setFilterTo(to); setPage(1) }}+ filterMinAmount={filterMinAmount}+ filterMaxAmount={filterMaxAmount}+ onAmountRangeChange={(min, max) => { setFilterMinAmount(min); setFilterMaxAmount(max); setPage(1) }}onClearAll={() => {setFilterFrom('')setFilterTo('')@@ -1049,6 +1064,8 @@ export default function TransactionsPage() {setFilterPayee('')setFilterGroupId('')setFilterType('')+ setFilterMinAmount('')+ setFilterMaxAmount('')setSearchInput('')setSearchQuery('')clearTagFilters()