From 14cfc14aafde8b39aba8fe2228cc086d1894a97b Mon Sep 17 00:00:00 2001 From: Rick Falkvinge Date: Thu, 9 Apr 2026 15:00:20 +0200 Subject: [PATCH] Add Search tab with cross-account transaction search Backend: GET /api/organizations/{orgId}/search/transactions - Text search on transaction description (case-insensitive) - Tx# / sequence ID lookup - Amount range (min/max in cents, matches absolute row amounts) - Date range (from/to) - Optional account filter - Returns transactions with nested rows, same format as General Journal - Results ordered by date descending, capped at 500 Frontend: SearchTab component - Search bar with description field (autofocus, Enter to search), Tx# field, amount min/max, date from/to pickers, Search button - Results displayed in General Journal format: transaction headers with account rows, clickable for transaction detail dialog - "N transactions found" with query echo - Empty state before first search, "No transactions found" after - Same visual style as General Journal (badges, colSpan, monospace) Search tab now enabled in the Inspect Ledgers tab bar. Made-with: Cursor --- frontend/src/pages/InspectLedgersPage.tsx | 7 +- frontend/src/pages/inspect/SearchTab.tsx | 279 ++++++++++++++++++ .../Endpoints/SearchEndpoints.cs | 145 +++++++++ src/UsingCash.Api/Program.cs | 1 + 4 files changed, 428 insertions(+), 4 deletions(-) create mode 100644 frontend/src/pages/inspect/SearchTab.tsx create mode 100644 src/UsingCash.Api/Endpoints/SearchEndpoints.cs diff --git a/frontend/src/pages/InspectLedgersPage.tsx b/frontend/src/pages/InspectLedgersPage.tsx index 1325b6dc..3850f705 100644 --- a/frontend/src/pages/InspectLedgersPage.tsx +++ b/frontend/src/pages/InspectLedgersPage.tsx @@ -2,6 +2,7 @@ import { useState } from 'react' import { Box, Typography, Tabs, Tab } from '@mui/material' import AccountLedgerTab from './inspect/AccountLedgerTab' import GeneralJournalTab from './inspect/GeneralJournalTab' +import SearchTab from './inspect/SearchTab' function TabPanel({ children, value, index }: { children: React.ReactNode; value: number; index: number }) { return ( @@ -21,7 +22,7 @@ export default function InspectLedgersPage() { setTab(v)} sx={{ borderBottom: 1, borderColor: 'divider' }}> - + @@ -31,9 +32,7 @@ export default function InspectLedgersPage() { - - Transaction search — coming soon. - + ) diff --git a/frontend/src/pages/inspect/SearchTab.tsx b/frontend/src/pages/inspect/SearchTab.tsx new file mode 100644 index 00000000..4adc04e1 --- /dev/null +++ b/frontend/src/pages/inspect/SearchTab.tsx @@ -0,0 +1,279 @@ +import { useState, useEffect } from 'react' +import { + Box, Typography, Table, TableBody, TableCell, TableContainer, + TableHead, TableRow, Paper, TextField, Button, Chip, Tooltip, + Skeleton, InputAdornment, +} from '@mui/material' +import { Search as SearchIcon, AttachFile } from '@mui/icons-material' +import { useOrg } from '../../contexts/OrgContext' +import { api } from '../../api/client' +import { formatCents } from '../../utils/money' +import TransactionDetailDialog from '../../components/TransactionDetailDialog' + +interface SearchRow { + rowId: number; accountId: number; accountName: string; accountType: string + debitCents: number; creditCents: number + foreignCurrencyCode: string; foreignCurrencyAmountCents: number +} + +interface SearchTransaction { + transactionId: number; sequenceId: number; dateTime: string + description: string; blockchainHash: string; hasDocumentation: boolean + rows: SearchRow[] +} + +interface SearchResponse { + query: string; resultCount: number; transactions: SearchTransaction[] +} + +export default function SearchTab() { + const { activeOrg } = useOrg() + const [query, setQuery] = useState('') + const [txId, setTxId] = useState('') + const [amountMin, setAmountMin] = useState('') + const [amountMax, setAmountMax] = useState('') + const [dateFrom, setDateFrom] = useState('') + const [dateTo, setDateTo] = useState('') + const [data, setData] = useState(null) + const [loading, setLoading] = useState(false) + const [hasSearched, setHasSearched] = useState(false) + const [selectedTxId, setSelectedTxId] = useState(null) + const [accountNames, setAccountNames] = useState>({}) + + useEffect(() => { + if (!activeOrg) return + api.get<{ id: number; name: string }[]>(`/organizations/${activeOrg.organizationId}/inspect/accounts-tree`) + .then(accounts => { + const map: Record = {} + for (const a of accounts) map[a.id] = a.name + setAccountNames(map) + }) + .catch(() => {}) + }, [activeOrg]) + + const doSearch = () => { + if (!activeOrg) return + setLoading(true) + setHasSearched(true) + + const params = new URLSearchParams() + if (query.trim()) params.set('q', query.trim()) + if (txId.trim()) params.set('txId', txId.trim()) + if (amountMin.trim()) { + const cents = Math.round(parseFloat(amountMin) * 100) + if (!isNaN(cents)) params.set('amountMin', cents.toString()) + } + if (amountMax.trim()) { + const cents = Math.round(parseFloat(amountMax) * 100) + if (!isNaN(cents)) params.set('amountMax', cents.toString()) + } + if (dateFrom) params.set('dateFrom', dateFrom) + if (dateTo) params.set('dateTo', dateTo) + + api.get(`/organizations/${activeOrg.organizationId}/search/transactions?${params}`) + .then(setData) + .catch(() => setData(null)) + .finally(() => setLoading(false)) + } + + const handleKeyDown = (e: React.KeyboardEvent) => { + if (e.key === 'Enter') doSearch() + } + + if (!activeOrg) return null + + return ( + + + + setQuery(e.target.value)} + onKeyDown={handleKeyDown} + sx={{ flex: 2, minWidth: 200 }} + InputProps={{ + startAdornment: , + }} + placeholder="Search transaction descriptions..." + autoFocus + /> + setTxId(e.target.value)} + onKeyDown={handleKeyDown} + sx={{ width: 90 }} + /> + setAmountMin(e.target.value)} + onKeyDown={handleKeyDown} + sx={{ width: 120 }} + placeholder="0.00" + /> + setAmountMax(e.target.value)} + onKeyDown={handleKeyDown} + sx={{ width: 120 }} + placeholder="0.00" + /> + setDateFrom(e.target.value)} + InputLabelProps={{ shrink: true }} + sx={{ width: 150 }} + /> + setDateTo(e.target.value)} + InputLabelProps={{ shrink: true }} + sx={{ width: 150 }} + /> + + + + + {loading ? ( + + ) : data && data.transactions.length > 0 ? ( + <> + + {data.resultCount} transaction{data.resultCount !== 1 ? 's' : ''} found + {data.query && <> matching "{data.query}"} + + + + + + + + + + + + + + Tx# + Date + Description / Account + Debit + Credit + + + + {data.transactions.map(tx => [ + setSelectedTxId(tx.transactionId)} + > + + {tx.sequenceId || tx.transactionId} + + + {new Date(tx.dateTime).toLocaleDateString('sv-SE')} + + {new Date(tx.dateTime).toLocaleTimeString('sv-SE', { hour: '2-digit', minute: '2-digit' })} + + + + {tx.description} + {tx.hasDocumentation && ( + + )} + + + + , + + ...tx.rows.map(row => ( + + + + + + + + {row.accountName} + + + + + 0 ? 'text.primary' : 'text.disabled', + }}> + {row.debitCents > 0 ? formatCents(row.debitCents) : ''} + + 0 ? 'error.main' : 'text.disabled', + }}> + {row.creditCents > 0 ? formatCents(row.creditCents) : ''} + + + )), + ])} + +
+
+ + ) : hasSearched && data ? ( + + No transactions found. + + ) : !hasSearched ? ( + + + Enter search criteria above and press Search or Enter. + + + ) : null} + + {activeOrg && ( + setSelectedTxId(null)} + transactionId={selectedTxId} + orgId={activeOrg.organizationId} + accountNames={accountNames} + currencyCode={activeOrg.currencyCode} + /> + )} +
+ ) +} diff --git a/src/UsingCash.Api/Endpoints/SearchEndpoints.cs b/src/UsingCash.Api/Endpoints/SearchEndpoints.cs new file mode 100644 index 00000000..77b9e172 --- /dev/null +++ b/src/UsingCash.Api/Endpoints/SearchEndpoints.cs @@ -0,0 +1,145 @@ +using UsingCash.Api.Support; +using UsingCash.Database.Repositories; + +namespace UsingCash.Api.Endpoints; + +public static class SearchEndpoints +{ + public static RouteGroupBuilder MapSearchEndpoints(this IEndpointRouteBuilder app) + { + var group = app.MapGroup("/api/organizations/{orgId:int}/search"); + + group.MapGet("/transactions", async (int orgId, string? q, int? txId, + long? amountMin, long? amountMax, string? dateFrom, string? dateTo, + int? accountId, int? limit, FinancialRepository repo) => + { + var maxResults = Math.Min(limit ?? 100, 500); + var allAccounts = await repo.GetAccountsForOrganization(orgId); + var accountMap = allAccounts.ToDictionary(a => a.FinancialAccountId, a => AccountNameResolver.Resolve(a.Name)); + + string AccountPath(int acctId) + { + if (!accountMap.TryGetValue(acctId, out var name)) return $"#{acctId}"; + var acct = allAccounts.FirstOrDefault(a => a.FinancialAccountId == acctId); + if (acct != null && acct.ParentFinancialAccountId != 0 && accountMap.TryGetValue(acct.ParentFinancialAccountId, out var parentName)) + return $"{parentName} » {name}"; + return name; + } + + // Build date range + DateTime from = DateTime.MinValue, to = DateTime.MaxValue; + if (!string.IsNullOrEmpty(dateFrom) && DateTime.TryParse(dateFrom, out var df)) from = df; + if (!string.IsNullOrEmpty(dateTo) && DateTime.TryParse(dateTo, out var dt)) to = dt.AddDays(1); + + // Determine which accounts to search + var searchAccountIds = accountId.HasValue + ? new List { accountId.Value } + : allAccounts.Select(a => a.FinancialAccountId).ToList(); + + // Collect matching rows + var matchingTxIds = new HashSet(); + var allRows = new List<(Basic.Types.BasicFinancialTransactionRow Row, int AccountId)>(); + + foreach (var acctId in searchAccountIds) + { + var rows = await repo.GetRowsForAccountInRange(acctId, from, to); + foreach (var row in rows) + { + allRows.Add((row, acctId)); + } + } + + // Deduplicate rows by rowId (same row can appear if account is in multiple search paths) + var seenRowIds = new HashSet(); + var uniqueRows = new List<(Basic.Types.BasicFinancialTransactionRow Row, int AccountId)>(); + foreach (var (row, acctId) in allRows) + { + if (seenRowIds.Add(row.FinancialTransactionRowId)) + uniqueRows.Add((row, acctId)); + } + + // Load transactions + var txCache = new Dictionary(); + foreach (var (row, _) in uniqueRows) + { + if (!txCache.ContainsKey(row.FinancialTransactionId)) + { + var tx = await repo.GetTransaction(row.FinancialTransactionId); + if (tx != null && tx.OrganizationId == orgId) + txCache[tx.FinancialTransactionId] = tx; + } + } + + // Filter by search criteria + var matchedTxs = txCache.Values.AsEnumerable(); + + if (!string.IsNullOrWhiteSpace(q)) + { + var terms = q.ToLowerInvariant(); + matchedTxs = matchedTxs.Where(tx => + tx.Comment.Contains(terms, StringComparison.OrdinalIgnoreCase)); + } + + if (txId.HasValue) + { + matchedTxs = matchedTxs.Where(tx => + tx.OrganizationSequenceId == txId.Value || tx.FinancialTransactionId == txId.Value); + } + + if (amountMin.HasValue || amountMax.HasValue) + { + var txIdsWithMatchingAmounts = new HashSet(); + foreach (var (row, _) in uniqueRows) + { + var absAmount = Math.Abs(row.AmountCents); + if (amountMin.HasValue && absAmount < amountMin.Value) continue; + if (amountMax.HasValue && absAmount > amountMax.Value) continue; + txIdsWithMatchingAmounts.Add(row.FinancialTransactionId); + } + matchedTxs = matchedTxs.Where(tx => txIdsWithMatchingAmounts.Contains(tx.FinancialTransactionId)); + } + + // Build results + var results = matchedTxs + .OrderByDescending(tx => tx.DateTime) + .ThenByDescending(tx => tx.FinancialTransactionId) + .Take(maxResults) + .Select(tx => + { + var txRows = uniqueRows + .Where(r => r.Row.FinancialTransactionId == tx.FinancialTransactionId) + .Select(r => new + { + rowId = r.Row.FinancialTransactionRowId, + accountId = r.AccountId, + accountName = AccountPath(r.AccountId), + accountType = allAccounts.FirstOrDefault(a => a.FinancialAccountId == r.AccountId)?.AccountType.ToString() ?? "", + debitCents = r.Row.AmountCents > 0 ? r.Row.AmountCents : 0, + creditCents = r.Row.AmountCents < 0 ? -r.Row.AmountCents : 0, + foreignCurrencyCode = r.Row.ForeignCurrencyCode, + foreignCurrencyAmountCents = r.Row.ForeignCurrencyAmountCents, + }).ToList(); + + return new + { + transactionId = tx.FinancialTransactionId, + sequenceId = tx.OrganizationSequenceId, + dateTime = tx.DateTime, + description = tx.Comment, + blockchainHash = tx.BlockchainHash, + hasDocumentation = tx.HasDocumentation, + rows = txRows, + }; + }).ToList(); + + return Results.Ok(new + { + query = q, + resultCount = results.Count, + transactions = results, + }); + }); + + return group; + } +} diff --git a/src/UsingCash.Api/Program.cs b/src/UsingCash.Api/Program.cs index 3dd3209c..c656c7f2 100644 --- a/src/UsingCash.Api/Program.cs +++ b/src/UsingCash.Api/Program.cs @@ -26,6 +26,7 @@ app.MapUserEndpoints(); app.MapEndOfMonthEndpoints(); app.MapTreeReportEndpoints(); app.MapInspectLedgerEndpoints(); +app.MapSearchEndpoints(); app.MapDevEndpoints(); app.UseDefaultFiles();