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
This commit is contained in:
@@ -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() {
|
||||
<Tabs value={tab} onChange={(_, v) => setTab(v)} sx={{ borderBottom: 1, borderColor: 'divider' }}>
|
||||
<Tab label="Account Ledger" />
|
||||
<Tab label="General Journal" />
|
||||
<Tab label="Search" disabled />
|
||||
<Tab label="Search" />
|
||||
</Tabs>
|
||||
|
||||
<TabPanel value={tab} index={0}>
|
||||
@@ -31,9 +32,7 @@ export default function InspectLedgersPage() {
|
||||
<GeneralJournalTab />
|
||||
</TabPanel>
|
||||
<TabPanel value={tab} index={2}>
|
||||
<Typography color="text.secondary" sx={{ p: 4, textAlign: 'center' }}>
|
||||
Transaction search — coming soon.
|
||||
</Typography>
|
||||
<SearchTab />
|
||||
</TabPanel>
|
||||
</Box>
|
||||
)
|
||||
|
||||
@@ -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<SearchResponse | null>(null)
|
||||
const [loading, setLoading] = useState(false)
|
||||
const [hasSearched, setHasSearched] = useState(false)
|
||||
const [selectedTxId, setSelectedTxId] = useState<number | null>(null)
|
||||
const [accountNames, setAccountNames] = useState<Record<number, string>>({})
|
||||
|
||||
useEffect(() => {
|
||||
if (!activeOrg) return
|
||||
api.get<{ id: number; name: string }[]>(`/organizations/${activeOrg.organizationId}/inspect/accounts-tree`)
|
||||
.then(accounts => {
|
||||
const map: Record<number, string> = {}
|
||||
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<SearchResponse>(`/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 (
|
||||
<Box>
|
||||
<Paper sx={{ p: 2, mb: 3 }} elevation={2}>
|
||||
<Box sx={{ display: 'flex', gap: 2, flexWrap: 'wrap', alignItems: 'flex-end' }}>
|
||||
<TextField
|
||||
label="Description"
|
||||
size="small"
|
||||
value={query}
|
||||
onChange={e => setQuery(e.target.value)}
|
||||
onKeyDown={handleKeyDown}
|
||||
sx={{ flex: 2, minWidth: 200 }}
|
||||
InputProps={{
|
||||
startAdornment: <InputAdornment position="start"><SearchIcon sx={{ fontSize: 18, color: 'text.disabled' }} /></InputAdornment>,
|
||||
}}
|
||||
placeholder="Search transaction descriptions..."
|
||||
autoFocus
|
||||
/>
|
||||
<TextField
|
||||
label="Tx#"
|
||||
size="small"
|
||||
value={txId}
|
||||
onChange={e => setTxId(e.target.value)}
|
||||
onKeyDown={handleKeyDown}
|
||||
sx={{ width: 90 }}
|
||||
/>
|
||||
<TextField
|
||||
label="Amount min"
|
||||
size="small"
|
||||
value={amountMin}
|
||||
onChange={e => setAmountMin(e.target.value)}
|
||||
onKeyDown={handleKeyDown}
|
||||
sx={{ width: 120 }}
|
||||
placeholder="0.00"
|
||||
/>
|
||||
<TextField
|
||||
label="Amount max"
|
||||
size="small"
|
||||
value={amountMax}
|
||||
onChange={e => setAmountMax(e.target.value)}
|
||||
onKeyDown={handleKeyDown}
|
||||
sx={{ width: 120 }}
|
||||
placeholder="0.00"
|
||||
/>
|
||||
<TextField
|
||||
label="From"
|
||||
type="date"
|
||||
size="small"
|
||||
value={dateFrom}
|
||||
onChange={e => setDateFrom(e.target.value)}
|
||||
InputLabelProps={{ shrink: true }}
|
||||
sx={{ width: 150 }}
|
||||
/>
|
||||
<TextField
|
||||
label="To"
|
||||
type="date"
|
||||
size="small"
|
||||
value={dateTo}
|
||||
onChange={e => setDateTo(e.target.value)}
|
||||
InputLabelProps={{ shrink: true }}
|
||||
sx={{ width: 150 }}
|
||||
/>
|
||||
<Button variant="contained" onClick={doSearch} sx={{ height: 40 }}>
|
||||
Search
|
||||
</Button>
|
||||
</Box>
|
||||
</Paper>
|
||||
|
||||
{loading ? (
|
||||
<Skeleton height={400} />
|
||||
) : data && data.transactions.length > 0 ? (
|
||||
<>
|
||||
<Typography variant="body2" color="text.secondary" sx={{ mb: 1 }}>
|
||||
{data.resultCount} transaction{data.resultCount !== 1 ? 's' : ''} found
|
||||
{data.query && <> matching "<strong>{data.query}</strong>"</>}
|
||||
</Typography>
|
||||
|
||||
<TableContainer component={Paper} elevation={2}>
|
||||
<Table size="small" sx={{ tableLayout: 'fixed', '& td, & th': { py: 0.4, fontSize: 13 } }}>
|
||||
<colgroup>
|
||||
<col style={{ width: 55 }} />
|
||||
<col style={{ width: 125 }} />
|
||||
<col />
|
||||
<col style={{ width: 125 }} />
|
||||
<col style={{ width: 125 }} />
|
||||
</colgroup>
|
||||
<TableHead>
|
||||
<TableRow sx={{ bgcolor: 'primary.main' }}>
|
||||
<TableCell sx={{ color: 'white', fontWeight: 600 }}>Tx#</TableCell>
|
||||
<TableCell sx={{ color: 'white', fontWeight: 600 }}>Date</TableCell>
|
||||
<TableCell sx={{ color: 'white', fontWeight: 600 }}>Description / Account</TableCell>
|
||||
<TableCell align="right" sx={{ color: 'white', fontWeight: 600 }}>Debit</TableCell>
|
||||
<TableCell align="right" sx={{ color: 'white', fontWeight: 600 }}>Credit</TableCell>
|
||||
</TableRow>
|
||||
</TableHead>
|
||||
<TableBody>
|
||||
{data.transactions.map(tx => [
|
||||
<TableRow
|
||||
key={`tx-${tx.transactionId}`}
|
||||
sx={{
|
||||
bgcolor: 'rgba(25, 118, 210, 0.04)',
|
||||
borderTop: '1px solid',
|
||||
borderColor: 'divider',
|
||||
cursor: 'pointer',
|
||||
'&:hover': { bgcolor: 'rgba(25, 118, 210, 0.08)' },
|
||||
}}
|
||||
onClick={() => setSelectedTxId(tx.transactionId)}
|
||||
>
|
||||
<TableCell sx={{ fontWeight: 700, fontFamily: 'monospace', fontSize: 12 }}>
|
||||
{tx.sequenceId || tx.transactionId}
|
||||
</TableCell>
|
||||
<TableCell sx={{ fontWeight: 600, fontSize: 12, whiteSpace: 'nowrap' }}>
|
||||
{new Date(tx.dateTime).toLocaleDateString('sv-SE')}
|
||||
<Typography component="span" sx={{ ml: 0.5, fontSize: 11, color: 'text.disabled' }}>
|
||||
{new Date(tx.dateTime).toLocaleTimeString('sv-SE', { hour: '2-digit', minute: '2-digit' })}
|
||||
</Typography>
|
||||
</TableCell>
|
||||
<TableCell sx={{ fontWeight: 600 }}>
|
||||
{tx.description}
|
||||
{tx.hasDocumentation && (
|
||||
<AttachFile sx={{ fontSize: 14, ml: 0.5, color: 'text.secondary', verticalAlign: 'middle' }} />
|
||||
)}
|
||||
</TableCell>
|
||||
<TableCell />
|
||||
<TableCell />
|
||||
</TableRow>,
|
||||
|
||||
...tx.rows.map(row => (
|
||||
<TableRow key={`row-${row.rowId}`} hover>
|
||||
<TableCell />
|
||||
<TableCell colSpan={2} sx={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
|
||||
<Box sx={{ display: 'inline-flex', alignItems: 'center', gap: 0.75 }}>
|
||||
<Chip
|
||||
label={row.accountType}
|
||||
size="small"
|
||||
variant="outlined"
|
||||
sx={{ fontSize: 10, height: 18, minWidth: 48, flexShrink: 0 }}
|
||||
color={
|
||||
row.accountType === 'Asset' ? 'success' :
|
||||
row.accountType === 'Debt' ? 'error' :
|
||||
row.accountType === 'Income' ? 'info' : 'warning'
|
||||
}
|
||||
/>
|
||||
<Tooltip title={row.accountName} placement="top-start">
|
||||
<Typography component="span" variant="body2" sx={{ fontSize: 13, color: 'text.secondary' }}>
|
||||
{row.accountName}
|
||||
</Typography>
|
||||
</Tooltip>
|
||||
</Box>
|
||||
</TableCell>
|
||||
<TableCell align="right" sx={{
|
||||
fontFamily: '"Roboto Mono", monospace',
|
||||
whiteSpace: 'nowrap',
|
||||
color: row.debitCents > 0 ? 'text.primary' : 'text.disabled',
|
||||
}}>
|
||||
{row.debitCents > 0 ? formatCents(row.debitCents) : ''}
|
||||
</TableCell>
|
||||
<TableCell align="right" sx={{
|
||||
fontFamily: '"Roboto Mono", monospace',
|
||||
whiteSpace: 'nowrap',
|
||||
color: row.creditCents > 0 ? 'error.main' : 'text.disabled',
|
||||
}}>
|
||||
{row.creditCents > 0 ? formatCents(row.creditCents) : ''}
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
)),
|
||||
])}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</TableContainer>
|
||||
</>
|
||||
) : hasSearched && data ? (
|
||||
<Paper sx={{ p: 4, textAlign: 'center' }} elevation={1}>
|
||||
<Typography color="text.secondary">No transactions found.</Typography>
|
||||
</Paper>
|
||||
) : !hasSearched ? (
|
||||
<Paper sx={{ p: 4, textAlign: 'center' }} elevation={1}>
|
||||
<Typography color="text.secondary">
|
||||
Enter search criteria above and press Search or Enter.
|
||||
</Typography>
|
||||
</Paper>
|
||||
) : null}
|
||||
|
||||
{activeOrg && (
|
||||
<TransactionDetailDialog
|
||||
open={selectedTxId !== null}
|
||||
onClose={() => setSelectedTxId(null)}
|
||||
transactionId={selectedTxId}
|
||||
orgId={activeOrg.organizationId}
|
||||
accountNames={accountNames}
|
||||
currencyCode={activeOrg.currencyCode}
|
||||
/>
|
||||
)}
|
||||
</Box>
|
||||
)
|
||||
}
|
||||
@@ -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<int> { accountId.Value }
|
||||
: allAccounts.Select(a => a.FinancialAccountId).ToList();
|
||||
|
||||
// Collect matching rows
|
||||
var matchingTxIds = new HashSet<int>();
|
||||
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<int>();
|
||||
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<int, Basic.Types.BasicFinancialTransaction>();
|
||||
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<int>();
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -26,6 +26,7 @@ app.MapUserEndpoints();
|
||||
app.MapEndOfMonthEndpoints();
|
||||
app.MapTreeReportEndpoints();
|
||||
app.MapInspectLedgerEndpoints();
|
||||
app.MapSearchEndpoints();
|
||||
app.MapDevEndpoints();
|
||||
|
||||
app.UseDefaultFiles();
|
||||
|
||||
Reference in New Issue
Block a user