Add AccountTreeGrid component and tree report endpoints
New reusable AccountTreeGrid component:
- Hierarchical tree with expand/collapse per node
- Σ prefix on aggregated parent values when collapsed
- Parent nodes show sum of all descendants when collapsed
- Own-value shown when expanded (for nodes with direct amounts)
- Column totals invariant: same regardless of expand/collapse state
- Folder/document icons matching v5 visual language
- CSS transitions on hover and state changes
- CSV download support per section
New backend endpoints:
- GET /api/organizations/{orgId}/reports/balance-sheet-tree?year=N
Returns accounts with quarterly columns: Start, Q1, Q2, Q3, Q4, Current
- GET /api/organizations/{orgId}/reports/profit-loss-tree?year=N
Returns accounts with: Last Year, Q1, Q2, Q3, Q4, YTD
Rebuilt pages using tree grid:
- Balance Sheet: Assets and Liabilities sections with quarterly breakdown
- Profit & Loss: Revenue and Expenses sections with quarterly breakdown,
net result chip, CSV download
Modeled after v5 Open Ledgers treegrid functionality.
Made-with: Cursor
This commit is contained in:
@@ -61,6 +61,10 @@ export const api = {
|
||||
api.get<ProfitLoss>(`/organizations/${orgId}/profit-loss?year=${year}`),
|
||||
transaction: (txId: number) =>
|
||||
api.get<TransactionDetail>(`/organizations/${orgId}/transactions/${txId}`),
|
||||
balanceSheetTree: (year: number) =>
|
||||
api.get<TreeReport>(`/organizations/${orgId}/reports/balance-sheet-tree?year=${year}`),
|
||||
profitLossTree: (year: number) =>
|
||||
api.get<TreeReport>(`/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[] }
|
||||
|
||||
@@ -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<number, TreeNode>()
|
||||
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<number>,
|
||||
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<Set<number>>(() => {
|
||||
const topLevel = new Set<number>()
|
||||
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 (
|
||||
<Box>
|
||||
{title && (
|
||||
<Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 1 }}>
|
||||
<Typography variant="h6" sx={{ fontWeight: 600 }}>{title}</Typography>
|
||||
{onDownloadCsv && (
|
||||
<Typography
|
||||
variant="body2"
|
||||
sx={{ cursor: 'pointer', color: 'primary.main', textDecoration: 'underline' }}
|
||||
onClick={onDownloadCsv}
|
||||
>
|
||||
Download CSV
|
||||
</Typography>
|
||||
)}
|
||||
</Box>
|
||||
)}
|
||||
|
||||
<TableContainer component={Paper} elevation={2}>
|
||||
<Table size="small" sx={{ '& td, & th': { py: 0.5, fontSize: 13 } }}>
|
||||
<TableHead>
|
||||
<TableRow sx={{ bgcolor: 'primary.main' }}>
|
||||
<TableCell sx={{ color: 'white', fontWeight: 600, minWidth: 280 }}>Account</TableCell>
|
||||
{columnHeaders.map((h, i) => (
|
||||
<TableCell key={i} align="right" sx={{ color: 'white', fontWeight: 600, minWidth: 100 }}>
|
||||
{h}
|
||||
</TableCell>
|
||||
))}
|
||||
</TableRow>
|
||||
</TableHead>
|
||||
<TableBody>
|
||||
{visibleRows.map(row => {
|
||||
const isExpanded = expanded.has(row.node.id)
|
||||
const isParent = !row.isLeaf
|
||||
const showAggregate = isParent && !isExpanded
|
||||
|
||||
return (
|
||||
<TableRow
|
||||
key={row.node.id}
|
||||
hover
|
||||
sx={{
|
||||
bgcolor: isParent && row.depth === 0 ? 'rgba(25, 118, 210, 0.04)' : undefined,
|
||||
'&:hover': { bgcolor: 'action.hover' },
|
||||
transition: 'background-color 0.2s',
|
||||
}}
|
||||
>
|
||||
<TableCell sx={{ pl: 1 + row.depth * 2.5 }}>
|
||||
<Box sx={{ display: 'flex', alignItems: 'center', gap: 0.5 }}>
|
||||
{isParent ? (
|
||||
<IconButton size="small" onClick={() => toggleExpand(row.node.id)} sx={{ p: 0.25 }}>
|
||||
{isExpanded ? <ExpandMore fontSize="small" /> : <ChevronRight fontSize="small" />}
|
||||
</IconButton>
|
||||
) : (
|
||||
<Box sx={{ width: 24 }} />
|
||||
)}
|
||||
{isParent ? (
|
||||
isExpanded ? <FolderOpen fontSize="small" sx={{ color: 'warning.main', mr: 0.5 }} />
|
||||
: <Folder fontSize="small" sx={{ color: 'warning.main', mr: 0.5 }} />
|
||||
) : (
|
||||
<Description fontSize="small" sx={{ color: 'action.disabled', mr: 0.5 }} />
|
||||
)}
|
||||
<Typography variant="body2" sx={{
|
||||
fontWeight: isParent ? 600 : 400,
|
||||
fontSize: 13,
|
||||
}}>
|
||||
{row.node.name}
|
||||
</Typography>
|
||||
</Box>
|
||||
</TableCell>
|
||||
|
||||
{row.aggregatedValues.map((val, i) => (
|
||||
<TableCell
|
||||
key={i}
|
||||
align="right"
|
||||
sx={{
|
||||
fontFamily: 'monospace',
|
||||
fontSize: 13,
|
||||
fontWeight: isParent ? 600 : 400,
|
||||
color: val < 0 ? 'error.main' : val === 0 ? 'text.disabled' : 'text.primary',
|
||||
opacity: showAggregate ? 1 : 1,
|
||||
transition: 'opacity 0.3s ease',
|
||||
}}
|
||||
>
|
||||
<Box sx={{
|
||||
display: 'inline-flex',
|
||||
alignItems: 'center',
|
||||
gap: 0.25,
|
||||
transition: 'opacity 0.3s ease-in-out',
|
||||
}}>
|
||||
{showAggregate && val !== 0 && (
|
||||
<Typography component="span" sx={{ fontSize: 11, color: 'text.secondary', fontWeight: 400 }}>
|
||||
Σ
|
||||
</Typography>
|
||||
)}
|
||||
{isParent && isExpanded && row.hasOwnValue ? (
|
||||
formatValue(row.node.ownValues[i] || 0, reverseSign)
|
||||
) : (
|
||||
formatValue(val, reverseSign)
|
||||
)}
|
||||
</Box>
|
||||
</TableCell>
|
||||
))}
|
||||
</TableRow>
|
||||
)
|
||||
})}
|
||||
|
||||
{/* Totals row */}
|
||||
<TableRow sx={{ bgcolor: 'grey.100', borderTop: 2, borderColor: 'divider' }}>
|
||||
<TableCell sx={{ fontWeight: 700, fontSize: 13 }}>Total</TableCell>
|
||||
{totals.map((val, i) => (
|
||||
<TableCell key={i} align="right" sx={{
|
||||
fontWeight: 700, fontFamily: 'monospace', fontSize: 13,
|
||||
color: val < 0 ? 'error.main' : 'text.primary',
|
||||
}}>
|
||||
{formatValue(val, reverseSign)}
|
||||
</TableCell>
|
||||
))}
|
||||
</TableRow>
|
||||
</TableBody>
|
||||
</Table>
|
||||
</TableContainer>
|
||||
</Box>
|
||||
)
|
||||
}
|
||||
@@ -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<BalanceSheet | null>(null)
|
||||
const [data, setData] = useState<TreeReport | null>(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) => (
|
||||
<TableContainer component={Paper} sx={{ mb: 3 }} elevation={2}>
|
||||
<Table size="small">
|
||||
<TableHead>
|
||||
<TableRow sx={{ bgcolor: 'primary.main' }}>
|
||||
<TableCell sx={{ color: 'white', fontWeight: 600 }}>{title}</TableCell>
|
||||
<TableCell align="right" sx={{ color: 'white', fontWeight: 600 }}>Balance</TableCell>
|
||||
</TableRow>
|
||||
</TableHead>
|
||||
<TableBody>
|
||||
{items.map(item => (
|
||||
<TableRow key={item.accountId} hover>
|
||||
<TableCell>{item.accountName}</TableCell>
|
||||
<TableCell align="right" sx={{ fontFamily: 'monospace' }}>{formatCents(item.balanceCents)}</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
<TableRow sx={{ bgcolor: 'grey.100' }}>
|
||||
<TableCell sx={{ fontWeight: 700 }}>Total</TableCell>
|
||||
<TableCell align="right" sx={{ fontWeight: 700, fontFamily: 'monospace' }}>{formatCents(totalCents)}</TableCell>
|
||||
</TableRow>
|
||||
</TableBody>
|
||||
</Table>
|
||||
</TableContainer>
|
||||
)
|
||||
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 (
|
||||
<Box>
|
||||
<Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 3 }}>
|
||||
<Typography variant="h5" sx={{ fontWeight: 600 }}>Balance Sheet</Typography>
|
||||
<TextField type="date" size="small" value={asOf} onChange={e => setAsOf(e.target.value)}
|
||||
label="As of" InputLabelProps={{ shrink: true }} />
|
||||
<Typography variant="h5" sx={{ fontWeight: 600 }}>
|
||||
Balance Sheet for {activeOrg.name}, {year}
|
||||
</Typography>
|
||||
<TextField type="number" size="small" value={year}
|
||||
onChange={e => setYear(Number(e.target.value))}
|
||||
label="Year" InputLabelProps={{ shrink: true }} sx={{ width: 120 }} />
|
||||
</Box>
|
||||
|
||||
{loading ? (
|
||||
<><Skeleton height={200} /><Skeleton height={200} /></>
|
||||
<><Skeleton height={300} /><Skeleton height={300} /></>
|
||||
) : data ? (
|
||||
<>
|
||||
{renderTable('Assets', data.assets, data.totalAssetsCents)}
|
||||
{renderTable('Liabilities & Equity', data.debts, data.totalDebtsCents)}
|
||||
<AccountTreeGrid
|
||||
title="Assets"
|
||||
nodes={assetNodes}
|
||||
columnHeaders={data.columnHeaders}
|
||||
onDownloadCsv={() => handleDownloadCsv('assets')}
|
||||
/>
|
||||
|
||||
<Divider sx={{ my: 3 }} />
|
||||
|
||||
<AccountTreeGrid
|
||||
title="Liabilities & Equity"
|
||||
nodes={liabilityNodes}
|
||||
columnHeaders={data.columnHeaders}
|
||||
onDownloadCsv={() => handleDownloadCsv('liabilities')}
|
||||
/>
|
||||
</>
|
||||
) : (
|
||||
<Typography color="text.secondary">No data</Typography>
|
||||
<Typography color="text.secondary">No data available</Typography>
|
||||
)}
|
||||
</Box>
|
||||
)
|
||||
|
||||
@@ -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<ProfitLoss | null>(null)
|
||||
const [data, setData] = useState<TreeReport | null>(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 (
|
||||
<Box>
|
||||
<Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 3 }}>
|
||||
<Typography variant="h5" sx={{ fontWeight: 600 }}>Profit & Loss</Typography>
|
||||
<TextField type="number" size="small" value={year} onChange={e => setYear(Number(e.target.value))}
|
||||
<Typography variant="h5" sx={{ fontWeight: 600 }}>
|
||||
P&L for {activeOrg.name}, {year}
|
||||
</Typography>
|
||||
<TextField type="number" size="small" value={year}
|
||||
onChange={e => setYear(Number(e.target.value))}
|
||||
label="Year" InputLabelProps={{ shrink: true }} sx={{ width: 120 }} />
|
||||
</Box>
|
||||
|
||||
{loading ? <Skeleton height={300} /> : data ? (
|
||||
{loading ? (
|
||||
<Skeleton height={500} />
|
||||
) : data ? (
|
||||
<>
|
||||
<TableContainer component={Paper} elevation={2} sx={{ mb: 3 }}>
|
||||
<Table size="small">
|
||||
<TableHead>
|
||||
<TableRow sx={{ bgcolor: 'success.main' }}>
|
||||
<TableCell sx={{ color: 'white', fontWeight: 600 }}>Income</TableCell>
|
||||
<TableCell align="right" sx={{ color: 'white', fontWeight: 600 }}>Amount</TableCell>
|
||||
</TableRow>
|
||||
</TableHead>
|
||||
<TableBody>
|
||||
{data.income.map(item => (
|
||||
<TableRow key={item.accountId} hover>
|
||||
<TableCell>{item.accountName}</TableCell>
|
||||
<TableCell align="right" sx={{ fontFamily: 'monospace' }}>{formatCents(Math.abs(item.balanceCents))}</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
<TableRow sx={{ bgcolor: 'grey.100' }}>
|
||||
<TableCell sx={{ fontWeight: 700 }}>Total Income</TableCell>
|
||||
<TableCell align="right" sx={{ fontWeight: 700, fontFamily: 'monospace' }}>{formatCents(Math.abs(data.totalIncomeCents))}</TableCell>
|
||||
</TableRow>
|
||||
</TableBody>
|
||||
</Table>
|
||||
</TableContainer>
|
||||
<AccountTreeGrid
|
||||
title="Revenue"
|
||||
nodes={revenueNodes}
|
||||
columnHeaders={data.columnHeaders}
|
||||
reverseSign
|
||||
/>
|
||||
|
||||
<TableContainer component={Paper} elevation={2} sx={{ mb: 3 }}>
|
||||
<Table size="small">
|
||||
<TableHead>
|
||||
<TableRow sx={{ bgcolor: 'error.main' }}>
|
||||
<TableCell sx={{ color: 'white', fontWeight: 600 }}>Costs</TableCell>
|
||||
<TableCell align="right" sx={{ color: 'white', fontWeight: 600 }}>Amount</TableCell>
|
||||
</TableRow>
|
||||
</TableHead>
|
||||
<TableBody>
|
||||
{data.costs.map(item => (
|
||||
<TableRow key={item.accountId} hover>
|
||||
<TableCell>{item.accountName}</TableCell>
|
||||
<TableCell align="right" sx={{ fontFamily: 'monospace' }}>{formatCents(Math.abs(item.balanceCents))}</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
<TableRow sx={{ bgcolor: 'grey.100' }}>
|
||||
<TableCell sx={{ fontWeight: 700 }}>Total Costs</TableCell>
|
||||
<TableCell align="right" sx={{ fontWeight: 700, fontFamily: 'monospace' }}>{formatCents(Math.abs(data.totalCostsCents))}</TableCell>
|
||||
</TableRow>
|
||||
</TableBody>
|
||||
</Table>
|
||||
</TableContainer>
|
||||
<Divider sx={{ my: 3 }} />
|
||||
|
||||
<AccountTreeGrid
|
||||
title="Expenses"
|
||||
nodes={expenseNodes}
|
||||
columnHeaders={data.columnHeaders}
|
||||
/>
|
||||
|
||||
<Divider sx={{ my: 3 }} />
|
||||
|
||||
<Paper sx={{ p: 2, display: 'flex', alignItems: 'center', gap: 2 }} elevation={2}>
|
||||
<Typography variant="h6">Net Result:</Typography>
|
||||
<Typography variant="h5" sx={{ fontWeight: 700, color: isProfit ? 'success.main' : 'error.main' }}>
|
||||
{formatCents(Math.abs(data.netResultCents))}
|
||||
<Typography variant="h6">Net Result (YTD):</Typography>
|
||||
<Typography variant="h5" sx={{
|
||||
fontWeight: 700,
|
||||
fontFamily: 'monospace',
|
||||
color: isProfit ? 'success.main' : 'error.main',
|
||||
}}>
|
||||
{(Math.abs(netResult) / 100).toLocaleString(undefined, { minimumFractionDigits: 0 })}
|
||||
</Typography>
|
||||
<Chip label={isProfit ? 'Profit' : 'Loss'} color={isProfit ? 'success' : 'error'} />
|
||||
<Box sx={{ flex: 1 }} />
|
||||
<Typography
|
||||
variant="body2"
|
||||
sx={{ cursor: 'pointer', color: 'primary.main', textDecoration: 'underline' }}
|
||||
onClick={handleDownloadCsv}
|
||||
>
|
||||
Download CSV
|
||||
</Typography>
|
||||
</Paper>
|
||||
</>
|
||||
) : <Typography color="text.secondary">No data</Typography>}
|
||||
) : (
|
||||
<Typography color="text.secondary">No data available</Typography>
|
||||
)}
|
||||
</Box>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -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<object>();
|
||||
foreach (var acct in balanceAccounts)
|
||||
{
|
||||
var values = new List<long>();
|
||||
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<object>();
|
||||
foreach (var acct in plAccounts)
|
||||
{
|
||||
var values = new List<long>();
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -24,6 +24,7 @@ app.MapDashboardEndpoints();
|
||||
app.MapOrganizationEndpoints();
|
||||
app.MapUserEndpoints();
|
||||
app.MapEndOfMonthEndpoints();
|
||||
app.MapTreeReportEndpoints();
|
||||
app.MapDevEndpoints();
|
||||
|
||||
app.UseDefaultFiles();
|
||||
|
||||
Reference in New Issue
Block a user