diff --git a/frontend/src/pages/InspectLedgersPage.tsx b/frontend/src/pages/InspectLedgersPage.tsx index a66e9778..1325b6dc 100644 --- a/frontend/src/pages/InspectLedgersPage.tsx +++ b/frontend/src/pages/InspectLedgersPage.tsx @@ -1,330 +1,40 @@ -import { useState, useEffect, useMemo } from 'react' -import { - Box, Typography, Paper, Table, TableBody, TableCell, TableContainer, - TableHead, TableRow, Select, MenuItem, FormControl, InputLabel, - Skeleton, Chip, Tooltip, TextField, Autocomplete, FormControlLabel, Checkbox, -} 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; accountId: number; accountName: string - debitCents: number; creditCents: number; balanceCents: number - foreignCurrencyCode: string; foreignCurrencyAmountCents: number - dependencyType: number | null; dependencyForeignId: number | null -} - -interface LedgerResponse { - accountId: number; accountName: string; isGroup: boolean; groupAccountCount: 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 [selectedAccountId, setSelectedAccountId] = useState(null) - const [year, setYear] = useState(currentYear) - const [month, setMonth] = useState(0) - const [data, setData] = useState(null) - const [loading, setLoading] = useState(false) - const [ownOnly, setOwnOnly] = useState(false) - - useEffect(() => { - if (!activeOrg) return - api.get(`/organizations/${activeOrg.organizationId}/inspect/accounts-tree`) - .then(setAccounts) - .catch(() => {}) - }, [activeOrg]) - - const isGroupAccount = useMemo(() => { - if (!selectedAccountId) return false - return accounts.some(a => a.parentId === selectedAccountId) - }, [selectedAccountId, accounts]) - - useEffect(() => { - if (!activeOrg || !selectedAccountId) return - setLoading(true) - const ownParam = ownOnly ? '&ownOnly=true' : '' - api.get( - `/organizations/${activeOrg.organizationId}/inspect/ledger?accountId=${selectedAccountId}&year=${year}&month=${month}${ownParam}` - ) - .then(setData) - .catch(() => setData(null)) - .finally(() => setLoading(false)) - }, [activeOrg, selectedAccountId, year, month, ownOnly]) - - interface AccountWithDepth extends AccountOption { - depth: number - hasChildren: boolean - } - - const accountsWithDepth = useMemo(() => { - const byId = new Map() - const childrenOf = new Map() - - for (const a of accounts) { - byId.set(a.id, a) - if (!childrenOf.has(a.parentId)) childrenOf.set(a.parentId, []) - childrenOf.get(a.parentId)!.push(a) - } - - const result: AccountWithDepth[] = [] - - function walk(parentId: number, depth: number, accountType: string) { - const children = (childrenOf.get(parentId) || []) - .filter(a => a.accountType === accountType) - .sort((a, b) => a.name.localeCompare(b.name)) - for (const child of children) { - const hasChildren = (childrenOf.get(child.id) || []).length > 0 - result.push({ ...child, depth, hasChildren }) - walk(child.id, depth + 1, accountType) - } - } - - for (const type of ['Asset', 'Debt', 'Income', 'Cost']) { - walk(0, 0, type) - } - - return result - }, [accounts]) - - if (!activeOrg) return null +import { useState } from 'react' +import { Box, Typography, Tabs, Tab } from '@mui/material' +import AccountLedgerTab from './inspect/AccountLedgerTab' +import GeneralJournalTab from './inspect/GeneralJournalTab' +function TabPanel({ children, value, index }: { children: React.ReactNode; value: number; index: number }) { return ( - - Inspect Ledgers + + ) +} - - a.accountType} - getOptionLabel={a => a.name} - value={accountsWithDepth.find(a => a.id === selectedAccountId) ?? null} - onChange={(_, v) => { setSelectedAccountId(v?.id ?? null); setOwnOnly(false) }} - isOptionEqualToValue={(opt, val) => opt.id === val.id} - sx={{ minWidth: 350, flex: 1 }} - renderInput={params => } - renderOption={(props, option) => ( -
  • - - - {option.name} - - {!option.open && } - -
  • - )} - /> +export default function InspectLedgersPage() { + const [tab, setTab] = useState(0) - - Year - - - - - Month - - -
    - - {!selectedAccountId ? ( - - Select an account to inspect its ledger entries. - - ) : ( - <> - {isGroupAccount && ( - - setOwnOnly(e.target.checked)} />} - label={ - Show only this account's own transactions (exclude sub-accounts) - } - /> - - )} - - {loading ? ( - - ) : data && data.entries.length > 0 ? ( - <> - - - {data.entryCount} entries, {data.from} to {data.to} - {data.isGroup && !ownOnly && ( - - ({data.groupAccountCount} accounts) - - )} - - - Amounts in {activeOrg.currencyCode || 'presentation currency'} - - - - - {(() => { - const showAccountCol = isGroupAccount && !ownOnly - return ( - - - - - {showAccountCol && } - - - - - - - - Tx# - Date - {showAccountCol && Account} - Description - Debit - Credit - Balance - - - - {/* Prior balance row */} - - - - {showAccountCol && } - - Prior balance - - - - - {formatCents(data.priorBalanceCents)} - - - - {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' })} - - - {showAccountCol && ( - - - {entry.accountName} - - - )} - - - {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 row โ€” debit and credit sums only */} - - - - {showAccountCol && } - Period totals - - {formatCents(data.entries.reduce((s, e) => s + e.debitCents, 0))} - - - {formatCents(data.entries.reduce((s, e) => s + e.creditCents, 0))} - - - - - {/* Closing balance row */} - - - - {showAccountCol && } - - Closing balance - - - - - {formatCents(data.entries[data.entries.length - 1]?.balanceCents ?? data.priorBalanceCents)} - - - -
    - ) - })()} -
    - - ) : data ? ( - - No entries for this period. - - ) : null} - - )} + return ( + + Inspect Ledgers + + setTab(v)} sx={{ borderBottom: 1, borderColor: 'divider' }}> + + + + + + + + + + + + + + Transaction search โ€” coming soon. + + ) } diff --git a/frontend/src/pages/inspect/AccountLedgerTab.tsx b/frontend/src/pages/inspect/AccountLedgerTab.tsx new file mode 100644 index 00000000..16f882d6 --- /dev/null +++ b/frontend/src/pages/inspect/AccountLedgerTab.tsx @@ -0,0 +1,328 @@ +import { useState, useEffect, useMemo } from 'react' +import { + Box, Typography, Paper, Table, TableBody, TableCell, TableContainer, + TableHead, TableRow, Select, MenuItem, FormControl, InputLabel, + Skeleton, Chip, Tooltip, TextField, Autocomplete, FormControlLabel, Checkbox, +} 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; accountId: number; accountName: string + debitCents: number; creditCents: number; balanceCents: number + foreignCurrencyCode: string; foreignCurrencyAmountCents: number + dependencyType: number | null; dependencyForeignId: number | null +} + +interface LedgerResponse { + accountId: number; accountName: string; isGroup: boolean; groupAccountCount: 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 AccountLedgerTab() { + const { activeOrg } = useOrg() + const [accounts, setAccounts] = useState([]) + const [selectedAccountId, setSelectedAccountId] = useState(null) + const [year, setYear] = useState(currentYear) + const [month, setMonth] = useState(0) + const [data, setData] = useState(null) + const [loading, setLoading] = useState(false) + const [ownOnly, setOwnOnly] = useState(false) + + useEffect(() => { + if (!activeOrg) return + api.get(`/organizations/${activeOrg.organizationId}/inspect/accounts-tree`) + .then(setAccounts) + .catch(() => {}) + }, [activeOrg]) + + const isGroupAccount = useMemo(() => { + if (!selectedAccountId) return false + return accounts.some(a => a.parentId === selectedAccountId) + }, [selectedAccountId, accounts]) + + useEffect(() => { + if (!activeOrg || !selectedAccountId) return + setLoading(true) + const ownParam = ownOnly ? '&ownOnly=true' : '' + api.get( + `/organizations/${activeOrg.organizationId}/inspect/ledger?accountId=${selectedAccountId}&year=${year}&month=${month}${ownParam}` + ) + .then(setData) + .catch(() => setData(null)) + .finally(() => setLoading(false)) + }, [activeOrg, selectedAccountId, year, month, ownOnly]) + + interface AccountWithDepth extends AccountOption { + depth: number + hasChildren: boolean + } + + const accountsWithDepth = useMemo(() => { + const byId = new Map() + const childrenOf = new Map() + + for (const a of accounts) { + byId.set(a.id, a) + if (!childrenOf.has(a.parentId)) childrenOf.set(a.parentId, []) + childrenOf.get(a.parentId)!.push(a) + } + + const result: AccountWithDepth[] = [] + + function walk(parentId: number, depth: number, accountType: string) { + const children = (childrenOf.get(parentId) || []) + .filter(a => a.accountType === accountType) + .sort((a, b) => a.name.localeCompare(b.name)) + for (const child of children) { + const hasChildren = (childrenOf.get(child.id) || []).length > 0 + result.push({ ...child, depth, hasChildren }) + walk(child.id, depth + 1, accountType) + } + } + + for (const type of ['Asset', 'Debt', 'Income', 'Cost']) { + walk(0, 0, type) + } + + return result + }, [accounts]) + + if (!activeOrg) return null + + return ( + + + a.accountType} + getOptionLabel={a => a.name} + value={accountsWithDepth.find(a => a.id === selectedAccountId) ?? null} + onChange={(_, v) => { setSelectedAccountId(v?.id ?? null); setOwnOnly(false) }} + isOptionEqualToValue={(opt, val) => opt.id === val.id} + sx={{ minWidth: 350, flex: 1 }} + renderInput={params => } + renderOption={(props, option) => ( +
  • + + + {option.name} + + {!option.open && } + +
  • + )} + /> + + + Year + + + + + Month + + +
    + + {!selectedAccountId ? ( + + Select an account to inspect its ledger entries. + + ) : ( + <> + {isGroupAccount && ( + + setOwnOnly(e.target.checked)} />} + label={ + Show only this account's own transactions (exclude sub-accounts) + } + /> + + )} + + {loading ? ( + + ) : data && data.entries.length > 0 ? ( + <> + + + {data.entryCount} entries, {data.from} to {data.to} + {data.isGroup && !ownOnly && ( + + ({data.groupAccountCount} accounts) + + )} + + + Amounts in {activeOrg.currencyCode || 'presentation currency'} + + + + + {(() => { + const showAccountCol = isGroupAccount && !ownOnly + return ( + + + + + {showAccountCol && } + + + + + + + + Tx# + Date + {showAccountCol && Account} + Description + Debit + Credit + Balance + + + + {/* Prior balance row */} + + + + {showAccountCol && } + + Prior balance + + + + + {formatCents(data.priorBalanceCents)} + + + + {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' })} + + + {showAccountCol && ( + + + {entry.accountName} + + + )} + + + {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 row โ€” debit and credit sums only */} + + + + {showAccountCol && } + Period totals + + {formatCents(data.entries.reduce((s, e) => s + e.debitCents, 0))} + + + {formatCents(data.entries.reduce((s, e) => s + e.creditCents, 0))} + + + + + {/* Closing balance row */} + + + + {showAccountCol && } + + Closing balance + + + + + {formatCents(data.entries[data.entries.length - 1]?.balanceCents ?? data.priorBalanceCents)} + + + +
    + ) + })()} +
    + + ) : data ? ( + + No entries for this period. + + ) : null} + + )} +
    + ) +} diff --git a/frontend/src/pages/inspect/GeneralJournalTab.tsx b/frontend/src/pages/inspect/GeneralJournalTab.tsx new file mode 100644 index 00000000..5ee05ba9 --- /dev/null +++ b/frontend/src/pages/inspect/GeneralJournalTab.tsx @@ -0,0 +1,243 @@ +import { useState, useEffect } from 'react' +import { + Box, Typography, Table, TableBody, TableCell, TableContainer, + TableHead, TableRow, Paper, Select, MenuItem, FormControl, + InputLabel, Skeleton, Chip, Tooltip, +} from '@mui/material' +import { ChevronRight, AttachFile } from '@mui/icons-material' +import { useOrg } from '../../contexts/OrgContext' +import { api } from '../../api/client' +import { formatCents } from '../../utils/money' + +interface JournalRow { + rowId: number; accountId: number; accountName: string; accountType: string + debitCents: number; creditCents: number + foreignCurrencyCode: string; foreignCurrencyAmountCents: number +} + +interface JournalTransaction { + transactionId: number; sequenceId: number; dateTime: string + description: string; blockchainHash: string; hasDocumentation: boolean + rows: JournalRow[] +} + +interface JournalResponse { + year: number; month: number; from: string; to: string + transactionCount: number; transactions: JournalTransaction[] +} + +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) + +const TYPE_ABBREV: Record = { + Asset: 'Asset', Debt: 'Debt', Income: 'Income', Cost: 'Cost', +} + +export default function GeneralJournalTab() { + const { activeOrg } = useOrg() + const [year, setYear] = useState(currentYear) + const [month, setMonth] = useState(new Date().getMonth() + 1) + const [data, setData] = useState(null) + const [loading, setLoading] = useState(false) + const [collapsedTxs, setCollapsedTxs] = useState>(new Set()) + + useEffect(() => { + if (!activeOrg) return + setLoading(true) + api.get( + `/organizations/${activeOrg.organizationId}/inspect/general-journal?year=${year}&month=${month}` + ) + .then(setData) + .catch(() => setData(null)) + .finally(() => setLoading(false)) + }, [activeOrg, year, month]) + + const toggleTx = (txId: number) => { + setCollapsedTxs(prev => { + const next = new Set(prev) + if (next.has(txId)) next.delete(txId) + else next.add(txId) + return next + }) + } + + if (!activeOrg) return null + + return ( + + + + Year + + + + Month + + + {data && ( + + {data.transactionCount} transactions, {data.from} to {data.to} + + )} + + + Amounts in {activeOrg.currencyCode || 'presentation currency'} + + + + {loading ? ( + + ) : data && data.transactions.length > 0 ? ( + + + + + + + + + + + + + + Tx# + Date + Description / Account + Debit + Credit + + + + {data.transactions.map(tx => { + const isCollapsed = collapsedTxs.has(tx.transactionId) + + return [ + // Transaction header row + toggleTx(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 && ( + + )} + + + + , + + // Transaction row entries (collapsible) + ...tx.rows.map(row => ( + *': { + maxHeight: isCollapsed ? 0 : 30, + overflow: 'hidden', + opacity: isCollapsed ? 0 : 1, + transition: 'max-height 0.3s ease, opacity 0.25s ease', + }, + }} + > + + + + + + + + + {row.accountName} + + + {row.foreignCurrencyCode && ( + + )} + + 0 ? 'text.primary' : 'text.disabled', + }}> + {row.debitCents > 0 ? formatCents(row.debitCents) : ''} + + 0 ? 'error.main' : 'text.disabled', + }}> + {row.creditCents > 0 ? formatCents(row.creditCents) : ''} + + + )), + ] + })} + +
    +
    + ) : data ? ( + + No transactions for this period. + + ) : null} +
    + ) +} diff --git a/src/UsingCash.Api/Endpoints/InspectLedgerEndpoints.cs b/src/UsingCash.Api/Endpoints/InspectLedgerEndpoints.cs index ab624e8e..e60e4980 100644 --- a/src/UsingCash.Api/Endpoints/InspectLedgerEndpoints.cs +++ b/src/UsingCash.Api/Endpoints/InspectLedgerEndpoints.cs @@ -122,6 +122,95 @@ public static class InspectLedgerEndpoints }).OrderBy(a => a.accountType).ThenBy(a => a.name)); }); + group.MapGet("/general-journal", async (int orgId, 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 allAccounts = await repo.GetAccountsForOrganization(orgId); + var accountMap = allAccounts.ToDictionary(a => a.FinancialAccountId); + + string AccountPath(int acctId) + { + if (!accountMap.TryGetValue(acctId, out var acct)) return $"#{acctId}"; + if (acct.ParentFinancialAccountId != 0 && accountMap.TryGetValue(acct.ParentFinancialAccountId, out var parent)) + return $"{parent.Name} ยป {acct.Name}"; + return acct.Name; + } + + // Get ALL rows for ALL accounts in this org for the period, sorted by transaction + var allRows = new List<(UsingCash.Basic.Types.BasicFinancialTransactionRow Row, int AccountId)>(); + foreach (var acct in allAccounts) + { + var rows = await repo.GetRowsForAccountInRange(acct.FinancialAccountId, from, to); + allRows.AddRange(rows.Select(r => (r, acct.FinancialAccountId))); + } + + // Group by transaction, ordered by transaction datetime + var txCache = new Dictionary(); + foreach (var (row, _) in allRows) + { + if (!txCache.ContainsKey(row.FinancialTransactionId)) + { + var tx = await repo.GetTransaction(row.FinancialTransactionId); + if (tx != null) txCache[tx.FinancialTransactionId] = tx; + } + } + + var grouped = allRows + .GroupBy(r => r.Row.FinancialTransactionId) + .Where(g => txCache.ContainsKey(g.Key)) + .OrderBy(g => txCache[g.Key].DateTime) + .ThenBy(g => g.Key) + .Select(g => + { + var tx = txCache[g.Key]; + return new + { + transactionId = tx.FinancialTransactionId, + sequenceId = tx.OrganizationSequenceId, + dateTime = tx.DateTime, + description = tx.Comment, + blockchainHash = tx.BlockchainHash, + hasDocumentation = tx.HasDocumentation, + rows = g.Select(r => new + { + rowId = r.Row.FinancialTransactionRowId, + accountId = r.AccountId, + accountName = AccountPath(r.AccountId), + accountType = accountMap.TryGetValue(r.AccountId, out var a) ? a.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(), + }; + }).ToList(); + + return Results.Ok(new + { + year = yr, + month = mo, + from = from.ToString("yyyy-MM-dd"), + to = to.ToString("yyyy-MM-dd"), + transactionCount = grouped.Count, + transactions = grouped, + }); + }); + return group; } }