From 42544242d94e266904dcac6bfd958a762ce56835 Mon Sep 17 00:00:00 2001 From: Rick Falkvinge Date: Thu, 9 Apr 2026 11:00:05 +0200 Subject: [PATCH] Add Inspect Ledgers page and API endpoints MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Backend: - GET /api/organizations/{orgId}/inspect/accounts-tree: flat account list grouped by type for the account selector - GET /api/organizations/{orgId}/inspect/ledger: rich ledger entries with transaction comment, sequence ID, debit/credit split, running balance, foreign currency, dependency info — joins rows with parent transactions Frontend: - InspectLedgersPage: searchable Autocomplete account selector grouped by account type, year/month dropdowns, transaction grid with Tx#, date+time, description (with tooltip), debit, credit, running balance, foreign currency chips, period totals row, prior balance display - Fixed column widths via tableLayout: fixed + colgroup Also cleans up unused imports in AccountTreeGrid and removes stale AnimatedRow function. Made-with: Cursor --- frontend/src/App.tsx | 3 +- frontend/src/components/AccountTreeGrid.tsx | 44 +--- frontend/src/pages/InspectLedgersPage.tsx | 214 ++++++++++++++++++ .../Endpoints/InspectLedgerEndpoints.cs | 90 ++++++++ src/UsingCash.Api/Program.cs | 1 + 5 files changed, 309 insertions(+), 43 deletions(-) create mode 100644 frontend/src/pages/InspectLedgersPage.tsx create mode 100644 src/UsingCash.Api/Endpoints/InspectLedgerEndpoints.cs diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index 7f8dddb3..57af5781 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -9,6 +9,7 @@ import ProfitLossPage from './pages/ProfitLossPage' import ChartOfAccountsPage from './pages/ChartOfAccountsPage' import CryptoTreasuryPage from './pages/CryptoTreasuryPage' import ExpenseClaimsPage from './pages/ExpenseClaimsPage' +import InspectLedgersPage from './pages/InspectLedgersPage' import PlaceholderPage from './pages/PlaceholderPage' function RequireAuth({ children }: { children: React.ReactNode }) { @@ -25,7 +26,7 @@ export default function App() { }> } /> } /> - } /> + } /> } /> } /> } /> diff --git a/frontend/src/components/AccountTreeGrid.tsx b/frontend/src/components/AccountTreeGrid.tsx index 908aacf2..03982238 100644 --- a/frontend/src/components/AccountTreeGrid.tsx +++ b/frontend/src/components/AccountTreeGrid.tsx @@ -1,9 +1,9 @@ -import { useState, useMemo, useCallback, useRef, useEffect } from 'react' +import { useState, useMemo, useCallback } from 'react' import { Table, TableBody, TableCell, TableContainer, TableHead, TableRow, Paper, IconButton, Box, Typography, } from '@mui/material' -import { ExpandMore, ChevronRight, Folder, FolderOpen, Description } from '@mui/icons-material' +import { ChevronRight, Folder, FolderOpen, Description } from '@mui/icons-material' export interface TreeNode { id: number @@ -83,46 +83,6 @@ function formatValue(cents: number, reverseSign: boolean): string { return val < 0 ? `−${formatted}` : formatted } -function AnimatedRow({ visible, children }: { visible: boolean; children: React.ReactNode }) { - const rowRef = useRef(null) - const [height, setHeight] = useState(undefined) - const [mounted, setMounted] = useState(visible) - - useEffect(() => { - if (visible) { - setMounted(true) - requestAnimationFrame(() => { - if (rowRef.current) setHeight(rowRef.current.scrollHeight) - }) - } else { - setHeight(0) - const timer = setTimeout(() => setMounted(false), 300) - return () => clearTimeout(timer) - } - }, [visible]) - - useEffect(() => { - if (mounted && visible && rowRef.current) { - setHeight(rowRef.current.scrollHeight) - } - }, [mounted, visible]) - - if (!mounted) return null - - return ( - - {children} - - ) -} export default function AccountTreeGrid({ nodes, columnHeaders, title, onDownloadCsv, reverseSign = false, diff --git a/frontend/src/pages/InspectLedgersPage.tsx b/frontend/src/pages/InspectLedgersPage.tsx new file mode 100644 index 00000000..9209de38 --- /dev/null +++ b/frontend/src/pages/InspectLedgersPage.tsx @@ -0,0 +1,214 @@ +import { useState, useEffect } from 'react' +import { + Box, Typography, Paper, Table, TableBody, TableCell, TableContainer, + TableHead, TableRow, Select, MenuItem, FormControl, InputLabel, + Skeleton, Chip, Tooltip, TextField, Autocomplete, +} from '@mui/material' +import { useOrg } from '../contexts/OrgContext' +import { api } from '../api/client' +import { formatCents } from '../utils/money' + +interface AccountOption { + id: number; name: string; parentId: number; accountType: string; open: boolean +} + +interface LedgerEntry { + rowId: number; transactionId: number; sequenceId: number + dateTime: string; description: string; accountName: string + debitCents: number; creditCents: number; balanceCents: number + foreignCurrencyCode: string; foreignCurrencyAmountCents: number + dependencyType: number | null; dependencyForeignId: number | null +} + +interface LedgerResponse { + accountId: number; year: number; month: number + from: string; to: string; priorBalanceCents: number + entries: LedgerEntry[]; entryCount: number +} + +const MONTHS = [ + { value: 0, label: 'Full Year' }, + { value: 1, label: 'January' }, { value: 2, label: 'February' }, + { value: 3, label: 'March' }, { value: 4, label: 'April' }, + { value: 5, label: 'May' }, { value: 6, label: 'June' }, + { value: 7, label: 'July' }, { value: 8, label: 'August' }, + { value: 9, label: 'September' }, { value: 10, label: 'October' }, + { value: 11, label: 'November' }, { value: 12, label: 'December' }, +] + +const currentYear = new Date().getFullYear() +const YEARS = Array.from({ length: 15 }, (_, i) => currentYear - i) + +export default function InspectLedgersPage() { + const { activeOrg } = useOrg() + const [accounts, setAccounts] = useState([]) + const [selectedAccount, setSelectedAccount] = useState(null) + const [year, setYear] = useState(currentYear) + const [month, setMonth] = useState(0) + const [data, setData] = useState(null) + const [loading, setLoading] = useState(false) + + useEffect(() => { + if (!activeOrg) return + api.get(`/organizations/${activeOrg.organizationId}/inspect/accounts-tree`) + .then(setAccounts) + .catch(() => {}) + }, [activeOrg]) + + useEffect(() => { + if (!activeOrg || !selectedAccount) return + setLoading(true) + api.get( + `/organizations/${activeOrg.organizationId}/inspect/ledger?accountId=${selectedAccount.id}&year=${year}&month=${month}` + ) + .then(setData) + .catch(() => setData(null)) + .finally(() => setLoading(false)) + }, [activeOrg, selectedAccount, year, month]) + + if (!activeOrg) return null + + return ( + + Inspect Ledgers + + + a.accountType} + getOptionLabel={a => a.name} + value={selectedAccount} + onChange={(_, v) => setSelectedAccount(v)} + sx={{ minWidth: 350, flex: 1 }} + renderInput={params => } + renderOption={(props, option) => ( +
  • + + {option.name} + {!option.open && } + +
  • + )} + /> + + + Year + + + + + Month + + +
    + + {!selectedAccount ? ( + + Select an account to inspect its ledger entries. + + ) : loading ? ( + + ) : data && data.entries.length > 0 ? ( + <> + + + {data.entryCount} entries, {data.from} to {data.to} + + + Prior balance: {formatCents(data.priorBalanceCents)} + + + + + + + + + + + + + + + + Tx# + Date + Description + Debit + Credit + Balance + + + + {data.entries.map(entry => ( + + + {entry.sequenceId || entry.transactionId} + + + {new Date(entry.dateTime).toLocaleDateString('sv-SE')} + + {new Date(entry.dateTime).toLocaleTimeString('sv-SE', { hour: '2-digit', minute: '2-digit' })} + + + + + {entry.description} + + {entry.foreignCurrencyCode && ( + + )} + + 0 ? 'text.primary' : 'text.disabled', + }}> + {entry.debitCents > 0 ? formatCents(entry.debitCents) : ''} + + 0 ? 'error.main' : 'text.disabled', + }}> + {entry.creditCents > 0 ? formatCents(entry.creditCents) : ''} + + + {formatCents(entry.balanceCents)} + + + ))} + + + + Period totals + + + {formatCents(data.entries.reduce((s, e) => s + e.debitCents, 0))} + + + {formatCents(data.entries.reduce((s, e) => s + e.creditCents, 0))} + + + {formatCents(data.entries[data.entries.length - 1]?.balanceCents ?? 0)} + + + +
    +
    + + ) : data ? ( + + No entries for this period. + + ) : null} +
    + ) +} diff --git a/src/UsingCash.Api/Endpoints/InspectLedgerEndpoints.cs b/src/UsingCash.Api/Endpoints/InspectLedgerEndpoints.cs new file mode 100644 index 00000000..7e249348 --- /dev/null +++ b/src/UsingCash.Api/Endpoints/InspectLedgerEndpoints.cs @@ -0,0 +1,90 @@ +using UsingCash.Database.Repositories; + +namespace UsingCash.Api.Endpoints; + +public static class InspectLedgerEndpoints +{ + public static RouteGroupBuilder MapInspectLedgerEndpoints(this IEndpointRouteBuilder app) + { + var group = app.MapGroup("/api/organizations/{orgId:int}/inspect"); + + group.MapGet("/ledger", async (int orgId, int accountId, int? year, int? month, + FinancialRepository repo) => + { + var yr = year ?? DateTime.UtcNow.Year; + var mo = month ?? 0; + + DateTime from, to; + if (mo > 0 && mo <= 12) + { + from = new DateTime(yr, mo, 1); + to = mo == 12 ? new DateTime(yr + 1, 1, 1) : new DateTime(yr, mo + 1, 1); + } + else + { + from = new DateTime(yr, 1, 1); + to = new DateTime(yr + 1, 1, 1); + } + + var rows = await repo.GetRowsForAccountInRange(accountId, from, to); + long priorBalance = await repo.GetAccountBalanceCents(accountId, from); + + var entries = new List(); + long runningBalance = priorBalance; + + foreach (var row in rows) + { + runningBalance += row.AmountCents; + + var tx = await repo.GetTransaction(row.FinancialTransactionId); + var dep = await repo.GetTransactionDependency(row.FinancialTransactionId); + + var account = await repo.GetAccount(row.FinancialAccountId); + + entries.Add(new + { + rowId = row.FinancialTransactionRowId, + transactionId = row.FinancialTransactionId, + sequenceId = tx?.OrganizationSequenceId ?? 0, + dateTime = tx?.DateTime, + description = tx?.Comment ?? "", + accountName = account?.Name ?? "", + debitCents = row.AmountCents > 0 ? row.AmountCents : 0, + creditCents = row.AmountCents < 0 ? -row.AmountCents : 0, + balanceCents = runningBalance, + foreignCurrencyCode = row.ForeignCurrencyCode, + foreignCurrencyAmountCents = row.ForeignCurrencyAmountCents, + dependencyType = dep?.TypeId, + dependencyForeignId = dep?.ForeignId, + }); + } + + return Results.Ok(new + { + accountId, + year = yr, + month = mo, + from = from.ToString("yyyy-MM-dd"), + to = to.ToString("yyyy-MM-dd"), + priorBalanceCents = priorBalance, + entries, + entryCount = entries.Count, + }); + }); + + group.MapGet("/accounts-tree", async (int orgId, FinancialRepository repo) => + { + var accounts = await repo.GetAccountsForOrganization(orgId); + return Results.Ok(accounts.Select(a => new + { + id = a.FinancialAccountId, + name = a.Name, + parentId = a.ParentFinancialAccountId, + accountType = a.AccountType.ToString(), + open = a.Open, + }).OrderBy(a => a.accountType).ThenBy(a => a.name)); + }); + + return group; + } +} diff --git a/src/UsingCash.Api/Program.cs b/src/UsingCash.Api/Program.cs index ab5d9a96..3dd3209c 100644 --- a/src/UsingCash.Api/Program.cs +++ b/src/UsingCash.Api/Program.cs @@ -25,6 +25,7 @@ app.MapOrganizationEndpoints(); app.MapUserEndpoints(); app.MapEndOfMonthEndpoints(); app.MapTreeReportEndpoints(); +app.MapInspectLedgerEndpoints(); app.MapDevEndpoints(); app.UseDefaultFiles();