diff --git a/frontend/src/api/client.ts b/frontend/src/api/client.ts index b04d01b4..4dbbc3ae 100644 --- a/frontend/src/api/client.ts +++ b/frontend/src/api/client.ts @@ -61,6 +61,10 @@ export const api = { api.get(`/organizations/${orgId}/profit-loss?year=${year}`), transaction: (txId: number) => api.get(`/organizations/${orgId}/transactions/${txId}`), + balanceSheetTree: (year: number) => + api.get(`/organizations/${orgId}/reports/balance-sheet-tree?year=${year}`), + profitLossTree: (year: number) => + api.get(`/organizations/${orgId}/reports/profit-loss-tree?year=${year}`), }), expenses: (orgId: number) => ({ @@ -130,3 +134,6 @@ export interface DashboardData { taskGroups: TaskGroup[]; totalTasks: number; yt export interface EndOfMonthChecklist { year: number; month: number; checklist: { booksBalanced: boolean; unbalancedCount: number }; canCloseYear: boolean; closedThroughYear: number } export interface UserInfo { userId: number; name: string; email: string; active: boolean; preferredCulture: string } + +export interface TreeReportNode { id: number; name: string; parentId: number; accountType: string; ownValues: number[] } +export interface TreeReport { year: number; columnHeaders: string[]; nodes: TreeReportNode[] } diff --git a/frontend/src/components/AccountTreeGrid.tsx b/frontend/src/components/AccountTreeGrid.tsx new file mode 100644 index 00000000..3ce6b68c --- /dev/null +++ b/frontend/src/components/AccountTreeGrid.tsx @@ -0,0 +1,268 @@ +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' + +export interface TreeNode { + id: number + name: string + parentId: number + ownValues: number[] + children?: TreeNode[] +} + +export interface AccountTreeGridProps { + nodes: TreeNode[] + columnHeaders: string[] + title?: string + currencyCode?: string + onDownloadCsv?: () => void + /** Show sign-reversed display for result accounts (Income/Cost) */ + reverseSign?: boolean +} + +interface FlatRow { + node: TreeNode + depth: number + isLeaf: boolean + hasOwnValue: boolean + aggregatedValues: number[] +} + +function buildTree(nodes: TreeNode[]): TreeNode[] { + const byId = new Map() + const roots: TreeNode[] = [] + + for (const n of nodes) { + byId.set(n.id, { ...n, children: [] }) + } + + for (const n of nodes) { + const node = byId.get(n.id)! + if (n.parentId === 0 || !byId.has(n.parentId)) { + roots.push(node) + } else { + byId.get(n.parentId)!.children!.push(node) + } + } + + return roots +} + +function computeAggregates(node: TreeNode, colCount: number): number[] { + const sums = new Array(colCount).fill(0) + for (let i = 0; i < colCount; i++) { + sums[i] = node.ownValues[i] || 0 + } + if (node.children) { + for (const child of node.children) { + const childSums = computeAggregates(child, colCount) + for (let i = 0; i < colCount; i++) { + sums[i] += childSums[i] + } + } + } + return sums +} + +function flattenVisible( + nodes: TreeNode[], + expanded: Set, + colCount: number, + depth: number = 0 +): FlatRow[] { + const rows: FlatRow[] = [] + + for (const node of nodes) { + const isLeaf = !node.children || node.children.length === 0 + const hasOwnValue = (node.ownValues || []).some(v => v !== 0) + const aggregatedValues = isLeaf ? node.ownValues : computeAggregates(node, colCount) + + rows.push({ node, depth, isLeaf, hasOwnValue, aggregatedValues }) + + if (!isLeaf && expanded.has(node.id)) { + rows.push(...flattenVisible(node.children!, expanded, colCount, depth + 1)) + } + } + + return rows +} + +function formatValue(cents: number, reverseSign: boolean): string { + const val = reverseSign ? -cents : cents + const abs = Math.abs(val) + const formatted = (abs / 100).toLocaleString(undefined, { + minimumFractionDigits: 0, + maximumFractionDigits: 0, + }) + return val < 0 ? `−${formatted}` : val === 0 ? '0' : formatted +} + +export default function AccountTreeGrid({ + nodes, + columnHeaders, + title, + onDownloadCsv, + reverseSign = false, +}: AccountTreeGridProps) { + const [expanded, setExpanded] = useState>(() => { + const topLevel = new Set() + for (const n of nodes) { + if (n.children && n.children.length > 0 && n.parentId === 0) { + topLevel.add(n.id) + } + } + return topLevel + }) + + const tree = useMemo(() => buildTree(nodes), [nodes]) + const colCount = columnHeaders.length + + const visibleRows = useMemo( + () => flattenVisible(tree, expanded, colCount), + [tree, expanded, colCount] + ) + + const toggleExpand = useCallback((id: number) => { + setExpanded(prev => { + const next = new Set(prev) + if (next.has(id)) next.delete(id) + else next.add(id) + return next + }) + }, []) + + const totals = useMemo(() => { + const sums = new Array(colCount).fill(0) + for (const node of tree) { + const agg = computeAggregates(node, colCount) + for (let i = 0; i < colCount; i++) sums[i] += agg[i] + } + return sums + }, [tree, colCount]) + + return ( + + {title && ( + + {title} + {onDownloadCsv && ( + + Download CSV + + )} + + )} + + + + + + Account + {columnHeaders.map((h, i) => ( + + {h} + + ))} + + + + {visibleRows.map(row => { + const isExpanded = expanded.has(row.node.id) + const isParent = !row.isLeaf + const showAggregate = isParent && !isExpanded + + return ( + + + + {isParent ? ( + toggleExpand(row.node.id)} sx={{ p: 0.25 }}> + {isExpanded ? : } + + ) : ( + + )} + {isParent ? ( + isExpanded ? + : + ) : ( + + )} + + {row.node.name} + + + + + {row.aggregatedValues.map((val, i) => ( + + + {showAggregate && val !== 0 && ( + + Σ + + )} + {isParent && isExpanded && row.hasOwnValue ? ( + formatValue(row.node.ownValues[i] || 0, reverseSign) + ) : ( + formatValue(val, reverseSign) + )} + + + ))} + + ) + })} + + {/* Totals row */} + + Total + {totals.map((val, i) => ( + + {formatValue(val, reverseSign)} + + ))} + + +
+
+
+ ) +} diff --git a/frontend/src/pages/BalanceSheetPage.tsx b/frontend/src/pages/BalanceSheetPage.tsx index 8a37dcfa..305d7699 100644 --- a/frontend/src/pages/BalanceSheetPage.tsx +++ b/frontend/src/pages/BalanceSheetPage.tsx @@ -1,68 +1,91 @@ -import { useState, useEffect } from 'react' -import { Box, Typography, Paper, Table, TableBody, TableCell, TableContainer, TableHead, TableRow, TextField, Skeleton } from '@mui/material' +import { useState, useEffect, useMemo } from 'react' +import { Box, Typography, TextField, Skeleton, Divider } from '@mui/material' import { useOrg } from '../contexts/OrgContext' -import { api, type BalanceSheet } from '../api/client' -import { formatCents } from '../utils/money' +import { api, type TreeReport } from '../api/client' +import AccountTreeGrid, { type TreeNode } from '../components/AccountTreeGrid' export default function BalanceSheetPage() { const { activeOrg } = useOrg() - const [data, setData] = useState(null) + const [data, setData] = useState(null) const [loading, setLoading] = useState(true) - const [asOf, setAsOf] = useState(new Date().toISOString().slice(0, 10)) + const [year, setYear] = useState(new Date().getFullYear()) useEffect(() => { if (!activeOrg) return setLoading(true) - api.ledger(activeOrg.organizationId).balanceSheet(asOf) + api.ledger(activeOrg.organizationId).balanceSheetTree(year) .then(setData) .catch(() => {}) .finally(() => setLoading(false)) - }, [activeOrg, asOf]) + }, [activeOrg, year]) + + const { assetNodes, liabilityNodes } = useMemo(() => { + if (!data) return { assetNodes: [], liabilityNodes: [] } + + const assets: TreeNode[] = [] + const liabilities: TreeNode[] = [] + + for (const n of data.nodes) { + const node: TreeNode = { id: n.id, name: n.name, parentId: n.parentId, ownValues: n.ownValues } + if (n.accountType === 'Asset') assets.push(node) + else liabilities.push(node) + } + + return { assetNodes: assets, liabilityNodes: liabilities } + }, [data]) if (!activeOrg) return null - const renderTable = (title: string, items: { accountId: number; accountName: string; balanceCents: number }[], totalCents: number) => ( - - - - - {title} - Balance - - - - {items.map(item => ( - - {item.accountName} - {formatCents(item.balanceCents)} - - ))} - - Total - {formatCents(totalCents)} - - -
-
- ) + const handleDownloadCsv = (section: string) => { + if (!data) return + const date = new Date().toISOString().slice(0, 10).replace(/-/g, '') + const filename = `BalanceSheet${year}-${date}-${section}.csv` + + const nodes = section === 'assets' ? assetNodes : liabilityNodes + const headers = ['Account', ...data.columnHeaders] + const rows = nodes.map(n => [n.name, ...n.ownValues.map(v => (v / 100).toFixed(2))]) + + const csv = [headers.join(','), ...rows.map(r => r.join(','))].join('\n') + const blob = new Blob([csv], { type: 'text/csv' }) + const url = URL.createObjectURL(blob) + const a = document.createElement('a') + a.href = url; a.download = filename; a.click() + URL.revokeObjectURL(url) + } return ( - Balance Sheet - setAsOf(e.target.value)} - label="As of" InputLabelProps={{ shrink: true }} /> + + Balance Sheet for {activeOrg.name}, {year} + + setYear(Number(e.target.value))} + label="Year" InputLabelProps={{ shrink: true }} sx={{ width: 120 }} /> {loading ? ( - <> + <> ) : data ? ( <> - {renderTable('Assets', data.assets, data.totalAssetsCents)} - {renderTable('Liabilities & Equity', data.debts, data.totalDebtsCents)} + handleDownloadCsv('assets')} + /> + + + + handleDownloadCsv('liabilities')} + /> ) : ( - No data + No data available )} ) diff --git a/frontend/src/pages/ProfitLossPage.tsx b/frontend/src/pages/ProfitLossPage.tsx index 43556497..aa57c432 100644 --- a/frontend/src/pages/ProfitLossPage.tsx +++ b/frontend/src/pages/ProfitLossPage.tsx @@ -1,93 +1,126 @@ -import { useState, useEffect } from 'react' -import { Box, Typography, Paper, Table, TableBody, TableCell, TableContainer, TableHead, TableRow, TextField, Skeleton, Chip } from '@mui/material' +import { useState, useEffect, useMemo } from 'react' +import { Box, Typography, TextField, Skeleton, Divider, Paper, Chip } from '@mui/material' import { useOrg } from '../contexts/OrgContext' -import { api, type ProfitLoss } from '../api/client' -import { formatCents } from '../utils/money' +import { api, type TreeReport } from '../api/client' +import AccountTreeGrid, { type TreeNode } from '../components/AccountTreeGrid' export default function ProfitLossPage() { const { activeOrg } = useOrg() - const [data, setData] = useState(null) + const [data, setData] = useState(null) const [loading, setLoading] = useState(true) const [year, setYear] = useState(new Date().getFullYear()) useEffect(() => { if (!activeOrg) return setLoading(true) - api.ledger(activeOrg.organizationId).profitLoss(year) + api.ledger(activeOrg.organizationId).profitLossTree(year) .then(setData) .catch(() => {}) .finally(() => setLoading(false)) }, [activeOrg, year]) + const { revenueNodes, expenseNodes, resultTotals } = useMemo(() => { + if (!data) return { revenueNodes: [], expenseNodes: [], resultTotals: [] } + + const revenue: TreeNode[] = [] + const expenses: TreeNode[] = [] + + for (const n of data.nodes) { + const node: TreeNode = { id: n.id, name: n.name, parentId: n.parentId, ownValues: n.ownValues } + if (n.accountType === 'Income') revenue.push(node) + else expenses.push(node) + } + + const colCount = data.columnHeaders.length + const results = new Array(colCount).fill(0) + for (const n of data.nodes) { + for (let i = 0; i < colCount; i++) { + results[i] += n.ownValues[i] || 0 + } + } + + return { revenueNodes: revenue, expenseNodes: expenses, resultTotals: results } + }, [data]) + if (!activeOrg) return null - const isProfit = data && data.netResultCents > 0 + const ytdIdx = data ? data.columnHeaders.length - 1 : 0 + const netResult = resultTotals[ytdIdx] || 0 + const isProfit = -netResult > 0 + + const handleDownloadCsv = () => { + if (!data) return + const date = new Date().toISOString().slice(0, 10).replace(/-/g, '') + const filename = `ProfitLoss${year}-${date}.csv` + + const headers = ['Account', 'Type', ...data.columnHeaders] + const rows = data.nodes.map(n => + [n.name, n.accountType, ...n.ownValues.map(v => (v / 100).toFixed(2))] + ) + + const csv = [headers.join(','), ...rows.map(r => r.join(','))].join('\n') + const blob = new Blob([csv], { type: 'text/csv' }) + const url = URL.createObjectURL(blob) + const a = document.createElement('a') + a.href = url; a.download = filename; a.click() + URL.revokeObjectURL(url) + } return ( - Profit & Loss - setYear(Number(e.target.value))} + + P&L for {activeOrg.name}, {year} + + setYear(Number(e.target.value))} label="Year" InputLabelProps={{ shrink: true }} sx={{ width: 120 }} /> - {loading ? : data ? ( + {loading ? ( + + ) : data ? ( <> - - - - - Income - Amount - - - - {data.income.map(item => ( - - {item.accountName} - {formatCents(Math.abs(item.balanceCents))} - - ))} - - Total Income - {formatCents(Math.abs(data.totalIncomeCents))} - - -
-
+ - - - - - Costs - Amount - - - - {data.costs.map(item => ( - - {item.accountName} - {formatCents(Math.abs(item.balanceCents))} - - ))} - - Total Costs - {formatCents(Math.abs(data.totalCostsCents))} - - -
-
+ + + + + - Net Result: - - {formatCents(Math.abs(data.netResultCents))} + Net Result (YTD): + + {(Math.abs(netResult) / 100).toLocaleString(undefined, { minimumFractionDigits: 0 })} + + + Download CSV + - ) : No data} + ) : ( + No data available + )}
) } diff --git a/src/UsingCash.Api/Endpoints/TreeReportEndpoints.cs b/src/UsingCash.Api/Endpoints/TreeReportEndpoints.cs new file mode 100644 index 00000000..42a9f883 --- /dev/null +++ b/src/UsingCash.Api/Endpoints/TreeReportEndpoints.cs @@ -0,0 +1,122 @@ +using UsingCash.Common.Enums; +using UsingCash.Database.Repositories; + +namespace UsingCash.Api.Endpoints; + +public static class TreeReportEndpoints +{ + public static RouteGroupBuilder MapTreeReportEndpoints(this IEndpointRouteBuilder app) + { + var group = app.MapGroup("/api/organizations/{orgId:int}/reports"); + + group.MapGet("/balance-sheet-tree", async (int orgId, int? year, FinancialRepository repo) => + { + var yr = year ?? DateTime.UtcNow.Year; + var accounts = await repo.GetAccountsForOrganization(orgId); + var balanceAccounts = accounts.Where(a => + a.AccountType is FinancialAccountType.Asset or FinancialAccountType.Debt).ToList(); + + var periods = new[] + { + ("Start", new DateTime(yr, 1, 1)), + ("Q1", new DateTime(yr, 4, 1)), + ("Q2", new DateTime(yr, 7, 1)), + ("Q3", new DateTime(yr, 10, 1)), + ("Q4", new DateTime(yr + 1, 1, 1)), + ("Current", DateTime.UtcNow), + }; + + var nodes = new List(); + foreach (var acct in balanceAccounts) + { + var values = new List(); + for (int i = 0; i < periods.Length; i++) + { + if (i == 0) + { + var bal = await repo.GetAccountBalanceCents(acct.Identity, periods[0].Item2); + values.Add(bal); + } + else + { + var from = periods[i - 1].Item2; + var to = periods[i].Item2; + var rows = await repo.GetRowsForAccountInRange(acct.Identity, from, to); + values.Add(rows.Sum(r => r.AmountCents)); + } + } + + nodes.Add(new + { + id = acct.Identity, + name = acct.Name, + parentId = acct.ParentFinancialAccountId, + accountType = acct.AccountType.ToString(), + ownValues = values, + }); + } + + return Results.Ok(new + { + year = yr, + columnHeaders = periods.Select(p => p.Item1).ToArray(), + nodes, + }); + }); + + group.MapGet("/profit-loss-tree", async (int orgId, int? year, FinancialRepository repo) => + { + var yr = year ?? DateTime.UtcNow.Year; + var accounts = await repo.GetAccountsForOrganization(orgId); + var plAccounts = accounts.Where(a => + a.AccountType is FinancialAccountType.Income or FinancialAccountType.Cost).ToList(); + + var lastYearStart = new DateTime(yr - 1, 1, 1); + var lastYearEnd = new DateTime(yr, 1, 1); + var q1Start = new DateTime(yr, 1, 1); + var q2Start = new DateTime(yr, 4, 1); + var q3Start = new DateTime(yr, 7, 1); + var q4Start = new DateTime(yr, 10, 1); + var yearEnd = new DateTime(yr + 1, 1, 1); + + var periodRanges = new (string Name, DateTime From, DateTime To)[] + { + ("Last Year", lastYearStart, lastYearEnd), + ("Q1", q1Start, q2Start), + ("Q2", q2Start, q3Start), + ("Q3", q3Start, q4Start), + ("Q4", q4Start, yearEnd), + ("YTD", q1Start, DateTime.UtcNow > yearEnd ? yearEnd : DateTime.UtcNow), + }; + + var nodes = new List(); + foreach (var acct in plAccounts) + { + var values = new List(); + foreach (var (_, from, to) in periodRanges) + { + var rows = await repo.GetRowsForAccountInRange(acct.Identity, from, to); + values.Add(rows.Sum(r => r.AmountCents)); + } + + nodes.Add(new + { + id = acct.Identity, + name = acct.Name, + parentId = acct.ParentFinancialAccountId, + accountType = acct.AccountType.ToString(), + ownValues = values, + }); + } + + return Results.Ok(new + { + year = yr, + columnHeaders = periodRanges.Select(p => p.Name).ToArray(), + nodes, + }); + }); + + return group; + } +} diff --git a/src/UsingCash.Api/Program.cs b/src/UsingCash.Api/Program.cs index 8861cffb..ab5d9a96 100644 --- a/src/UsingCash.Api/Program.cs +++ b/src/UsingCash.Api/Program.cs @@ -24,6 +24,7 @@ app.MapDashboardEndpoints(); app.MapOrganizationEndpoints(); app.MapUserEndpoints(); app.MapEndOfMonthEndpoints(); +app.MapTreeReportEndpoints(); app.MapDevEndpoints(); app.UseDefaultFiles();