Add React frontend with live data pages (section 10)
CI / docker (push) Has been cancelled
CI / build-and-test (push) Has started running

Full React + MUI + TypeScript SPA at frontend/:
- API client with typed interfaces for all endpoints
- AuthContext (session cookies, dev impersonation)
- OrgContext (org list, active org switcher)
- Money formatting (cents → display, satoshis → BCH)

App shell:
- Sidebar navigation with collapsible Ledgers and Financial sections
- Top bar with org switcher, language selector (EN/SV/DE), user chip
- Material UI theme with Inter font

Live data pages (connected to real migrated production data):
- Dashboard: YTD P&L cards, pending tasks, quick links
- Balance Sheet: date picker, assets/debts tables with totals
- Profit & Loss: year selector, income/costs breakdown, net result
- Chart of Accounts: grouped by type with status chips
- Crypto Treasury: total balance, address table with BCH amounts
- Expense Claims: list with amounts, VAT, status chips

Placeholder pages for: Inspect Ledgers, Budget vs Actual, Inbound/
Outbound Invoices, Payouts, End of Month, Org Settings, User Management

Vite dev server proxies /api to ASP.NET Core backend on port 5222.

Made-with: Cursor
This commit is contained in:
2026-04-08 18:32:03 +02:00
parent f74a15929a
commit 45f026b4f4
17 changed files with 1023 additions and 43 deletions
+34 -18
View File
@@ -1,27 +1,43 @@
import { Routes, Route } from 'react-router-dom'
import { Typography, Container, Box } from '@mui/material'
import { useTranslation } from 'react-i18next'
import { Routes, Route, Navigate } from 'react-router-dom'
import { CircularProgress, Box } from '@mui/material'
import { useAuth } from './contexts/AuthContext'
import AppShell from './components/AppShell'
import LoginPage from './pages/LoginPage'
import DashboardPage from './pages/DashboardPage'
import BalanceSheetPage from './pages/BalanceSheetPage'
import ProfitLossPage from './pages/ProfitLossPage'
import ChartOfAccountsPage from './pages/ChartOfAccountsPage'
import CryptoTreasuryPage from './pages/CryptoTreasuryPage'
import ExpenseClaimsPage from './pages/ExpenseClaimsPage'
import PlaceholderPage from './pages/PlaceholderPage'
function Dashboard() {
const { t } = useTranslation()
return (
<Container maxWidth="lg">
<Box sx={{ mt: 4 }}>
<Typography variant="h3" gutterBottom>
{t('dashboard.title', 'using.cash')}
</Typography>
<Typography variant="body1" color="text.secondary">
{t('dashboard.subtitle', 'Accounting made simple.')}
</Typography>
</Box>
</Container>
)
function RequireAuth({ children }: { children: React.ReactNode }) {
const { user, loading } = useAuth()
if (loading) return <Box sx={{ display: 'flex', justifyContent: 'center', mt: 20 }}><CircularProgress /></Box>
if (!user) return <Navigate to="/login" replace />
return <>{children}</>
}
export default function App() {
return (
<Routes>
<Route path="/*" element={<Dashboard />} />
<Route path="/login" element={<LoginPage />} />
<Route path="/" element={<RequireAuth><AppShell /></RequireAuth>}>
<Route index element={<DashboardPage />} />
<Route path="ledgers/chart-of-accounts" element={<ChartOfAccountsPage />} />
<Route path="ledgers/inspect" element={<PlaceholderPage title="Inspect Ledgers" />} />
<Route path="ledgers/balance-sheet" element={<BalanceSheetPage />} />
<Route path="ledgers/profit-loss" element={<ProfitLossPage />} />
<Route path="ledgers/budget-vs-actual" element={<PlaceholderPage title="Budget vs Actual" />} />
<Route path="financial/expense-claims" element={<ExpenseClaimsPage />} />
<Route path="financial/inbound-invoices" element={<PlaceholderPage title="Inbound Invoices" />} />
<Route path="financial/outbound-invoices" element={<PlaceholderPage title="Outbound Invoices" />} />
<Route path="financial/payouts" element={<PlaceholderPage title="Payouts" />} />
<Route path="crypto" element={<CryptoTreasuryPage />} />
<Route path="end-of-month" element={<PlaceholderPage title="End of Month" />} />
<Route path="admin/org-settings" element={<PlaceholderPage title="Organization Settings" />} />
<Route path="admin/users" element={<PlaceholderPage title="User Management" />} />
</Route>
</Routes>
)
}
+133
View File
@@ -0,0 +1,133 @@
const BASE = '/api'
async function request<T>(path: string, options?: RequestInit): Promise<T> {
const res = await fetch(`${BASE}${path}`, {
credentials: 'include',
headers: { 'Content-Type': 'application/json', ...options?.headers },
...options,
})
if (res.status === 401) {
window.location.href = '/login'
throw new Error('Unauthorized')
}
if (!res.ok) {
const body = await res.json().catch(() => ({}))
throw new Error(body.message || `HTTP ${res.status}`)
}
return res.json()
}
export const api = {
get: <T>(path: string) => request<T>(path),
post: <T>(path: string, body?: unknown) =>
request<T>(path, { method: 'POST', body: body ? JSON.stringify(body) : undefined }),
put: <T>(path: string, body?: unknown) =>
request<T>(path, { method: 'PUT', body: body ? JSON.stringify(body) : undefined }),
delete: <T>(path: string) => request<T>(path, { method: 'DELETE' }),
upload: async <T>(path: string, formData: FormData): Promise<T> => {
const res = await fetch(`${BASE}${path}`, {
method: 'POST',
credentials: 'include',
body: formData,
})
if (!res.ok) throw new Error(`Upload failed: HTTP ${res.status}`)
return res.json()
},
auth: {
login: (email: string, password: string) =>
api.post<{ userId: number; name: string }>('/auth/login', { email, password }),
logout: () => api.post('/auth/logout'),
me: () => api.get<{ userId: number; name: string; email: string; preferredCulture: string; lastOrgId: number }>('/auth/me'),
},
orgs: {
list: () => api.get<Organization[]>('/organizations'),
get: (orgId: number) => api.get<Organization>(`/organizations/${orgId}`),
},
accounts: (orgId: number) => ({
list: () => api.get<Account[]>(`/organizations/${orgId}/accounts`),
create: (data: { name: string; accountType: string; parentAccountId?: number }) =>
api.post<{ accountId: number }>(`/organizations/${orgId}/accounts`, data),
}),
ledger: (orgId: number) => ({
inspect: (accountId: number, from: string, to: string) =>
api.get<LedgerData>(`/organizations/${orgId}/ledger?accountId=${accountId}&from=${from}&to=${to}`),
balanceSheet: (asOf: string) =>
api.get<BalanceSheet>(`/organizations/${orgId}/balance-sheet?asOf=${asOf}`),
profitLoss: (year: number) =>
api.get<ProfitLoss>(`/organizations/${orgId}/profit-loss?year=${year}`),
transaction: (txId: number) =>
api.get<TransactionDetail>(`/organizations/${orgId}/transactions/${txId}`),
}),
expenses: (orgId: number) => ({
list: () => api.get<ExpenseClaim[]>(`/organizations/${orgId}/expense-claims`),
}),
invoices: (orgId: number) => ({
inbound: () => api.get<InboundInvoice[]>(`/organizations/${orgId}/inbound-invoices`),
}),
crypto: (orgId: number) => ({
treasury: () => api.get<CryptoTreasury>(`/organizations/${orgId}/crypto/treasury`),
}),
dashboard: (orgId: number) => ({
get: () => api.get<DashboardData>(`/organizations/${orgId}/dashboard`),
}),
endOfMonth: (orgId: number) => ({
checklist: (year?: number, month?: number) => {
const params = new URLSearchParams()
if (year) params.set('year', year.toString())
if (month) params.set('month', month.toString())
return api.get<EndOfMonthChecklist>(`/organizations/${orgId}/end-of-month/checklist?${params}`)
},
}),
users: {
list: () => api.get<UserInfo[]>('/users'),
},
dev: {
impersonate: () => api.post('/dev/impersonate'),
},
}
export interface Organization {
organizationId: number; name: string; nameShort: string;
vatEnabled: boolean; defaultVatRatePercent: number; economyEnabled: boolean;
closedThroughYear: number; openLedgersDomain: string; vanityDomain: string;
}
export interface Account {
financialAccountId: number; name: string; accountType: string;
parentFinancialAccountId: number; ownerUserId: number; open: boolean;
openedYear: number; closedYear: number; expensable: boolean;
enabledForExpensing: boolean; enabledForInvoicing: boolean;
}
export interface AccountBalance { accountId: number; accountName: string; balanceCents: number }
export interface BalanceSheet { asOfDate: string; totalAssetsCents: number; totalDebtsCents: number; assets: AccountBalance[]; debts: AccountBalance[] }
export interface ProfitLoss { year: number; totalIncomeCents: number; totalCostsCents: number; netResultCents: number; income: AccountBalance[]; costs: AccountBalance[] }
export interface LedgerRow { financialTransactionRowId: number; financialTransactionId: number; financialAccountId: number; amountCents: number; createdDateTime: string; foreignCurrencyCode: string; foreignCurrencyAmountCents: number; runningBalance: number }
export interface LedgerData { accountId: number; from: string; to: string; rows: LedgerRow[] }
export interface TransactionDetail { financialTransactionId: number; organizationSequenceId: number; dateTime: string; comment: string; blockchainHash: string; rows: { financialTransactionRowId: number; financialAccountId: number; amountCents: number }[] }
export interface ExpenseClaim { expenseClaimId: number; organizationSequenceId: number; claimingUserId: number; expenseDate: string; description: string; amountCents: number; vatCents: number; attested: boolean; validated: boolean; open: boolean }
export interface InboundInvoice { inboundInvoiceId: number; organizationSequenceId: number; supplier: string; dueDate: string; amountCents: number; vatCents: number; attested: boolean; open: boolean; description: string }
export interface CryptoAddress { hotWalletAddressId: number; addressString: string; derivationPath: string; balanceSatoshis: number }
export interface CryptoTreasury { totalBalanceSatoshis: number; addresses: CryptoAddress[] }
export interface TaskGroup { type: string; label: string; count: number }
export interface DashboardData { taskGroups: TaskGroup[]; totalTasks: number; ytdProfitLoss: { year: number; netResultCents: number; totalIncomeCents: number; totalCostsCents: number } }
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 }
+153
View File
@@ -0,0 +1,153 @@
import { useState } from 'react'
import { Outlet, useNavigate, useLocation } from 'react-router-dom'
import { useTranslation } from 'react-i18next'
import {
AppBar, Box, Toolbar, Typography, Drawer, List, ListItemButton,
ListItemIcon, ListItemText, Divider, Select, MenuItem,
FormControl, Collapse, ListSubheader, Chip,
} from '@mui/material'
import {
Dashboard as DashboardIcon,
AccountBalance as LedgerIcon,
Receipt as ExpenseIcon,
Description as InvoiceIcon,
Payment as PayoutIcon,
CurrencyBitcoin as CryptoIcon,
CalendarMonth as EomIcon,
Settings as AdminIcon,
People as UsersIcon,
ExpandLess, ExpandMore,
MenuBook as ChartIcon,
BarChart as BudgetIcon,
TrendingUp as ProfitLossIcon,
AccountBalanceWallet as BalanceSheetIcon,
Search as InspectIcon,
} from '@mui/icons-material'
import { useAuth } from '../contexts/AuthContext'
import { useOrg } from '../contexts/OrgContext'
const DRAWER_WIDTH = 260
export default function AppShell() {
const { t, i18n } = useTranslation()
const { user, logout } = useAuth()
const { orgs, activeOrg, setActiveOrgId } = useOrg()
const navigate = useNavigate()
const location = useLocation()
const [ledgerOpen, setLedgerOpen] = useState(true)
const [financialOpen, setFinancialOpen] = useState(true)
const navItem = (path: string, icon: React.ReactNode, label: string) => (
<ListItemButton selected={location.pathname === path} onClick={() => navigate(path)} sx={{ pl: 3 }}>
<ListItemIcon sx={{ minWidth: 36 }}>{icon}</ListItemIcon>
<ListItemText primary={label} primaryTypographyProps={{ fontSize: 14 }} />
</ListItemButton>
)
return (
<Box sx={{ display: 'flex' }}>
<AppBar position="fixed" sx={{ zIndex: (theme) => theme.zIndex.drawer + 1 }}>
<Toolbar>
<Typography variant="h6" sx={{ flexGrow: 1, fontWeight: 700, letterSpacing: -0.5 }}>
using.cash
</Typography>
{orgs.length > 1 && (
<FormControl size="small" sx={{ mr: 2, minWidth: 180 }}>
<Select
value={activeOrg?.organizationId ?? ''}
onChange={e => setActiveOrgId(Number(e.target.value))}
sx={{ color: 'white', '.MuiSelect-icon': { color: 'white' }, fontSize: 14 }}
variant="standard"
disableUnderline
>
{orgs.map(o => (
<MenuItem key={o.organizationId} value={o.organizationId}>{o.nameShort || o.name}</MenuItem>
))}
</Select>
</FormControl>
)}
<FormControl size="small" sx={{ mr: 2 }}>
<Select
value={i18n.language}
onChange={e => i18n.changeLanguage(e.target.value as string)}
sx={{ color: 'white', '.MuiSelect-icon': { color: 'white' }, fontSize: 13 }}
variant="standard"
disableUnderline
>
<MenuItem value="en">EN</MenuItem>
<MenuItem value="sv">SV</MenuItem>
<MenuItem value="de">DE</MenuItem>
</Select>
</FormControl>
{user && (
<Chip label={user.name} size="small" color="primary" variant="outlined"
onClick={() => logout().then(() => navigate('/login'))}
sx={{ color: 'white', borderColor: 'rgba(255,255,255,.4)', fontSize: 13 }} />
)}
</Toolbar>
</AppBar>
<Drawer variant="permanent" sx={{
width: DRAWER_WIDTH,
flexShrink: 0,
'& .MuiDrawer-paper': { width: DRAWER_WIDTH, boxSizing: 'border-box' },
}}>
<Toolbar />
<List component="nav" dense>
<ListItemButton selected={location.pathname === '/'} onClick={() => navigate('/')}>
<ListItemIcon><DashboardIcon /></ListItemIcon>
<ListItemText primary={t('nav.dashboard')} />
</ListItemButton>
<Divider sx={{ my: 1 }} />
<ListItemButton onClick={() => setLedgerOpen(!ledgerOpen)}>
<ListItemIcon><LedgerIcon /></ListItemIcon>
<ListItemText primary={t('nav.ledgers')} />
{ledgerOpen ? <ExpandLess /> : <ExpandMore />}
</ListItemButton>
<Collapse in={ledgerOpen} unmountOnExit>
<List disablePadding dense>
{navItem('/ledgers/chart-of-accounts', <ChartIcon fontSize="small" />, 'Chart of Accounts')}
{navItem('/ledgers/inspect', <InspectIcon fontSize="small" />, 'Inspect Ledgers')}
{navItem('/ledgers/balance-sheet', <BalanceSheetIcon fontSize="small" />, 'Balance Sheet')}
{navItem('/ledgers/profit-loss', <ProfitLossIcon fontSize="small" />, 'Profit & Loss')}
{navItem('/ledgers/budget-vs-actual', <BudgetIcon fontSize="small" />, 'Budget vs Actual')}
</List>
</Collapse>
<Divider sx={{ my: 1 }} />
<ListItemButton onClick={() => setFinancialOpen(!financialOpen)}>
<ListItemIcon><ExpenseIcon /></ListItemIcon>
<ListItemText primary={t('nav.financial')} />
{financialOpen ? <ExpandLess /> : <ExpandMore />}
</ListItemButton>
<Collapse in={financialOpen} unmountOnExit>
<List disablePadding dense>
{navItem('/financial/expense-claims', <ExpenseIcon fontSize="small" />, 'Expense Claims')}
{navItem('/financial/inbound-invoices', <InvoiceIcon fontSize="small" />, 'Inbound Invoices')}
{navItem('/financial/outbound-invoices', <InvoiceIcon fontSize="small" />, 'Outbound Invoices')}
{navItem('/financial/payouts', <PayoutIcon fontSize="small" />, 'Payouts')}
</List>
</Collapse>
<Divider sx={{ my: 1 }} />
{navItem('/crypto', <CryptoIcon />, t('nav.crypto'))}
{navItem('/end-of-month', <EomIcon />, 'End of Month')}
<Divider sx={{ my: 1 }} />
<ListSubheader sx={{ lineHeight: '32px', fontSize: 12 }}>{t('nav.admin')}</ListSubheader>
{navItem('/admin/org-settings', <AdminIcon fontSize="small" />, 'Org Settings')}
{navItem('/admin/users', <UsersIcon fontSize="small" />, 'Users')}
</List>
</Drawer>
<Box component="main" sx={{ flexGrow: 1, p: 3 }}>
<Toolbar />
<Outlet />
</Box>
</Box>
)
}
+57
View File
@@ -0,0 +1,57 @@
import { createContext, useContext, useState, useEffect, type ReactNode } from 'react'
import { api } from '../api/client'
interface AuthState {
userId: number
name: string
email: string
preferredCulture: string
lastOrgId: number
}
interface AuthContextType {
user: AuthState | null
loading: boolean
login: (email: string, password: string) => Promise<void>
logout: () => Promise<void>
devImpersonate: () => Promise<void>
}
const AuthContext = createContext<AuthContextType>(null!)
export function AuthProvider({ children }: { children: ReactNode }) {
const [user, setUser] = useState<AuthState | null>(null)
const [loading, setLoading] = useState(true)
useEffect(() => {
api.auth.me()
.then(setUser)
.catch(() => setUser(null))
.finally(() => setLoading(false))
}, [])
const login = async (email: string, password: string) => {
await api.auth.login(email, password)
const me = await api.auth.me()
setUser(me)
}
const logout = async () => {
await api.auth.logout()
setUser(null)
}
const devImpersonate = async () => {
await api.dev.impersonate()
const me = await api.auth.me()
setUser(me)
}
return (
<AuthContext.Provider value={{ user, loading, login, logout, devImpersonate }}>
{children}
</AuthContext.Provider>
)
}
export const useAuth = () => useContext(AuthContext)
+44
View File
@@ -0,0 +1,44 @@
import { createContext, useContext, useState, useEffect, type ReactNode } from 'react'
import { api, type Organization } from '../api/client'
import { useAuth } from './AuthContext'
interface OrgContextType {
orgs: Organization[]
activeOrg: Organization | null
setActiveOrgId: (id: number) => void
loading: boolean
}
const OrgContext = createContext<OrgContextType>(null!)
export function OrgProvider({ children }: { children: ReactNode }) {
const { user } = useAuth()
const [orgs, setOrgs] = useState<Organization[]>([])
const [activeOrg, setActiveOrg] = useState<Organization | null>(null)
const [loading, setLoading] = useState(true)
useEffect(() => {
if (!user) { setLoading(false); return }
api.orgs.list()
.then(list => {
setOrgs(list)
const preferred = list.find(o => o.organizationId === user.lastOrgId) || list[0]
if (preferred) setActiveOrg(preferred)
})
.catch(() => {})
.finally(() => setLoading(false))
}, [user])
const setActiveOrgId = (id: number) => {
const org = orgs.find(o => o.organizationId === id)
if (org) setActiveOrg(org)
}
return (
<OrgContext.Provider value={{ orgs, activeOrg, setActiveOrgId, loading }}>
{children}
</OrgContext.Provider>
)
}
export const useOrg = () => useContext(OrgContext)
+17 -3
View File
@@ -2,13 +2,23 @@ import React from 'react'
import ReactDOM from 'react-dom/client'
import { BrowserRouter } from 'react-router-dom'
import { ThemeProvider, createTheme, CssBaseline } from '@mui/material'
import { AuthProvider } from './contexts/AuthContext'
import { OrgProvider } from './contexts/OrgContext'
import App from './App'
import './i18n'
const theme = createTheme({
palette: {
primary: { main: '#1976d2' },
secondary: { main: '#388e3c' },
primary: { main: '#1565c0' },
secondary: { main: '#2e7d32' },
background: { default: '#fafafa' },
},
typography: {
fontFamily: '"Inter", "Roboto", "Helvetica", "Arial", sans-serif',
},
components: {
MuiCard: { defaultProps: { elevation: 2 } },
MuiPaper: { defaultProps: { elevation: 1 } },
},
})
@@ -17,7 +27,11 @@ ReactDOM.createRoot(document.getElementById('root')!).render(
<BrowserRouter>
<ThemeProvider theme={theme}>
<CssBaseline />
<App />
<AuthProvider>
<OrgProvider>
<App />
</OrgProvider>
</AuthProvider>
</ThemeProvider>
</BrowserRouter>
</React.StrictMode>,
+69
View File
@@ -0,0 +1,69 @@
import { useState, useEffect } from 'react'
import { Box, Typography, Paper, Table, TableBody, TableCell, TableContainer, TableHead, TableRow, TextField, Skeleton } from '@mui/material'
import { useOrg } from '../contexts/OrgContext'
import { api, type BalanceSheet } from '../api/client'
import { formatCents } from '../utils/money'
export default function BalanceSheetPage() {
const { activeOrg } = useOrg()
const [data, setData] = useState<BalanceSheet | null>(null)
const [loading, setLoading] = useState(true)
const [asOf, setAsOf] = useState(new Date().toISOString().slice(0, 10))
useEffect(() => {
if (!activeOrg) return
setLoading(true)
api.ledger(activeOrg.organizationId).balanceSheet(asOf)
.then(setData)
.catch(() => {})
.finally(() => setLoading(false))
}, [activeOrg, asOf])
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>
)
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 }} />
</Box>
{loading ? (
<><Skeleton height={200} /><Skeleton height={200} /></>
) : data ? (
<>
{renderTable('Assets', data.assets, data.totalAssetsCents)}
{renderTable('Liabilities & Equity', data.debts, data.totalDebtsCents)}
</>
) : (
<Typography color="text.secondary">No data</Typography>
)}
</Box>
)
}
@@ -0,0 +1,71 @@
import { useState, useEffect } from 'react'
import { Box, Typography, Paper, Table, TableBody, TableCell, TableContainer, TableHead, TableRow, Chip, Skeleton } from '@mui/material'
import { useOrg } from '../contexts/OrgContext'
import { api, type Account } from '../api/client'
const TYPE_COLORS: Record<string, 'success' | 'error' | 'info' | 'warning'> = {
Asset: 'success', Debt: 'error', Income: 'info', Cost: 'warning',
}
export default function ChartOfAccountsPage() {
const { activeOrg } = useOrg()
const [accounts, setAccounts] = useState<Account[]>([])
const [loading, setLoading] = useState(true)
useEffect(() => {
if (!activeOrg) return
setLoading(true)
api.accounts(activeOrg.organizationId).list()
.then(setAccounts)
.catch(() => {})
.finally(() => setLoading(false))
}, [activeOrg])
if (!activeOrg) return null
const grouped = {
Asset: accounts.filter(a => a.accountType === 'Asset'),
Debt: accounts.filter(a => a.accountType === 'Debt'),
Income: accounts.filter(a => a.accountType === 'Income'),
Cost: accounts.filter(a => a.accountType === 'Cost'),
}
return (
<Box>
<Typography variant="h5" sx={{ fontWeight: 600, mb: 3 }}>Chart of Accounts</Typography>
{loading ? <Skeleton height={400} /> : Object.entries(grouped).map(([type, accts]) => (
accts.length > 0 && (
<TableContainer component={Paper} key={type} sx={{ mb: 3 }} elevation={2}>
<Table size="small">
<TableHead>
<TableRow sx={{ bgcolor: `${TYPE_COLORS[type]}.main` }}>
<TableCell sx={{ color: 'white', fontWeight: 600 }}>{type} Accounts ({accts.length})</TableCell>
<TableCell sx={{ color: 'white', fontWeight: 600 }} align="center">Status</TableCell>
<TableCell sx={{ color: 'white', fontWeight: 600 }} align="center">ID</TableCell>
</TableRow>
</TableHead>
<TableBody>
{accts.map(a => (
<TableRow key={a.financialAccountId} hover>
<TableCell>
{a.parentFinancialAccountId > 0 && <span style={{ marginLeft: 20 }}>↳ </span>}
{a.name}
</TableCell>
<TableCell align="center">
<Chip label={a.open ? 'Open' : 'Closed'} size="small"
color={a.open ? 'success' : 'default'} variant="outlined" />
</TableCell>
<TableCell align="center" sx={{ fontFamily: 'monospace', color: 'text.secondary' }}>
{a.financialAccountId}
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</TableContainer>
)
))}
</Box>
)
}
+62
View File
@@ -0,0 +1,62 @@
import { useState, useEffect } from 'react'
import { Box, Typography, Paper, Table, TableBody, TableCell, TableContainer, TableHead, TableRow, Skeleton, Card, CardContent } from '@mui/material'
import { useOrg } from '../contexts/OrgContext'
import { api, type CryptoTreasury } from '../api/client'
import { formatSatoshis } from '../utils/money'
export default function CryptoTreasuryPage() {
const { activeOrg } = useOrg()
const [data, setData] = useState<CryptoTreasury | null>(null)
const [loading, setLoading] = useState(true)
useEffect(() => {
if (!activeOrg) return
setLoading(true)
api.crypto(activeOrg.organizationId).treasury()
.then(setData)
.catch(() => {})
.finally(() => setLoading(false))
}, [activeOrg])
if (!activeOrg) return null
return (
<Box>
<Typography variant="h5" sx={{ fontWeight: 600, mb: 3 }}>Crypto Treasury</Typography>
{loading ? <Skeleton height={100} /> : data && (
<Card elevation={2} sx={{ mb: 3 }}>
<CardContent>
<Typography color="text.secondary" gutterBottom>Total Hot Wallet Balance</Typography>
<Typography variant="h4" sx={{ fontWeight: 700, fontFamily: 'monospace' }}>
{formatSatoshis(data.totalBalanceSatoshis)} BCH
</Typography>
</CardContent>
</Card>
)}
{loading ? <Skeleton height={300} /> : data && (
<TableContainer component={Paper} elevation={2}>
<Table size="small">
<TableHead>
<TableRow sx={{ bgcolor: 'secondary.main' }}>
<TableCell sx={{ color: 'white', fontWeight: 600 }}>Address</TableCell>
<TableCell sx={{ color: 'white', fontWeight: 600 }}>Derivation</TableCell>
<TableCell align="right" sx={{ color: 'white', fontWeight: 600 }}>Balance (BCH)</TableCell>
</TableRow>
</TableHead>
<TableBody>
{data.addresses.filter(a => a.balanceSatoshis > 0).map(a => (
<TableRow key={a.hotWalletAddressId} hover>
<TableCell sx={{ fontFamily: 'monospace', fontSize: 13 }}>{a.addressString}</TableCell>
<TableCell sx={{ fontSize: 13, color: 'text.secondary' }}>{a.derivationPath}</TableCell>
<TableCell align="right" sx={{ fontFamily: 'monospace' }}>{formatSatoshis(a.balanceSatoshis)}</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</TableContainer>
)}
</Box>
)
}
+112
View File
@@ -0,0 +1,112 @@
import { useState, useEffect } from 'react'
import { useNavigate } from 'react-router-dom'
import { Box, Card, CardContent, Typography, Grid, Chip, Skeleton, Paper, List, ListItemButton, ListItemIcon, ListItemText } from '@mui/material'
import { TrendingUp, TrendingDown, Receipt, AccountBalance, CurrencyBitcoin } from '@mui/icons-material'
import { useOrg } from '../contexts/OrgContext'
import { api, type DashboardData } from '../api/client'
import { formatCents } from '../utils/money'
export default function DashboardPage() {
const { activeOrg } = useOrg()
const navigate = useNavigate()
const [data, setData] = useState<DashboardData | null>(null)
const [loading, setLoading] = useState(true)
useEffect(() => {
if (!activeOrg) return
setLoading(true)
api.dashboard(activeOrg.organizationId).get()
.then(setData)
.catch(() => {})
.finally(() => setLoading(false))
}, [activeOrg])
if (!activeOrg) return <Typography>Select an organization</Typography>
const pl = data?.ytdProfitLoss
const isProfit = pl && pl.netResultCents > 0
return (
<Box>
<Typography variant="h4" gutterBottom sx={{ fontWeight: 600 }}>
{activeOrg.name}
</Typography>
<Grid container spacing={3} sx={{ mb: 3 }}>
<Grid item xs={12} md={4}>
<Card elevation={2}>
<CardContent>
<Typography color="text.secondary" gutterBottom variant="body2">YTD Result</Typography>
{loading ? <Skeleton width={120} height={40} /> : (
<>
<Typography variant="h4" sx={{ fontWeight: 700, color: isProfit ? 'success.main' : 'error.main' }}>
{pl ? formatCents(Math.abs(pl.netResultCents)) : '—'}
</Typography>
<Chip icon={isProfit ? <TrendingUp /> : <TrendingDown />}
label={isProfit ? 'Profit' : 'Loss'}
color={isProfit ? 'success' : 'error'} size="small" variant="outlined" />
</>
)}
</CardContent>
</Card>
</Grid>
<Grid item xs={12} md={4}>
<Card elevation={2}>
<CardContent>
<Typography color="text.secondary" gutterBottom variant="body2">YTD Income</Typography>
{loading ? <Skeleton width={120} height={40} /> : (
<Typography variant="h4" sx={{ fontWeight: 700 }}>
{pl ? formatCents(Math.abs(pl.totalIncomeCents)) : '—'}
</Typography>
)}
</CardContent>
</Card>
</Grid>
<Grid item xs={12} md={4}>
<Card elevation={2}>
<CardContent>
<Typography color="text.secondary" gutterBottom variant="body2">YTD Costs</Typography>
{loading ? <Skeleton width={120} height={40} /> : (
<Typography variant="h4" sx={{ fontWeight: 700 }}>
{pl ? formatCents(Math.abs(pl.totalCostsCents)) : '—'}
</Typography>
)}
</CardContent>
</Card>
</Grid>
</Grid>
{data && data.totalTasks > 0 && (
<Paper sx={{ mb: 3, p: 2 }}>
<Typography variant="h6" gutterBottom>Pending Tasks ({data.totalTasks})</Typography>
{data.taskGroups.map(g => (
<Chip key={g.type} label={`${g.label}: ${g.count}`} sx={{ mr: 1, mb: 1 }}
color="warning" variant="outlined" />
))}
</Paper>
)}
<Typography variant="h6" gutterBottom sx={{ mt: 2 }}>Quick Links</Typography>
<List>
<ListItemButton onClick={() => navigate('/ledgers/balance-sheet')}>
<ListItemIcon><AccountBalance /></ListItemIcon>
<ListItemText primary="Balance Sheet" />
</ListItemButton>
<ListItemButton onClick={() => navigate('/ledgers/profit-loss')}>
<ListItemIcon><TrendingUp /></ListItemIcon>
<ListItemText primary="Profit & Loss" />
</ListItemButton>
<ListItemButton onClick={() => navigate('/financial/expense-claims')}>
<ListItemIcon><Receipt /></ListItemIcon>
<ListItemText primary="Expense Claims" />
</ListItemButton>
<ListItemButton onClick={() => navigate('/crypto')}>
<ListItemIcon><CurrencyBitcoin /></ListItemIcon>
<ListItemText primary="Crypto Treasury" />
</ListItemButton>
</List>
</Box>
)
}
+63
View File
@@ -0,0 +1,63 @@
import { useState, useEffect } from 'react'
import { Box, Typography, Paper, Table, TableBody, TableCell, TableContainer, TableHead, TableRow, Chip, Skeleton } from '@mui/material'
import { useOrg } from '../contexts/OrgContext'
import { api, type ExpenseClaim } from '../api/client'
import { formatCents } from '../utils/money'
export default function ExpenseClaimsPage() {
const { activeOrg } = useOrg()
const [claims, setClaims] = useState<ExpenseClaim[]>([])
const [loading, setLoading] = useState(true)
useEffect(() => {
if (!activeOrg) return
setLoading(true)
api.expenses(activeOrg.organizationId).list()
.then(setClaims)
.catch(() => {})
.finally(() => setLoading(false))
}, [activeOrg])
if (!activeOrg) return null
return (
<Box>
<Typography variant="h5" sx={{ fontWeight: 600, mb: 3 }}>Expense Claims</Typography>
{loading ? <Skeleton height={300} /> : (
<TableContainer component={Paper} elevation={2}>
<Table size="small">
<TableHead>
<TableRow sx={{ bgcolor: 'primary.main' }}>
<TableCell sx={{ color: 'white', fontWeight: 600 }}>#</TableCell>
<TableCell sx={{ color: 'white', fontWeight: 600 }}>Date</TableCell>
<TableCell sx={{ color: 'white', fontWeight: 600 }}>Description</TableCell>
<TableCell align="right" sx={{ color: 'white', fontWeight: 600 }}>Amount</TableCell>
<TableCell align="right" sx={{ color: 'white', fontWeight: 600 }}>VAT</TableCell>
<TableCell align="center" sx={{ color: 'white', fontWeight: 600 }}>Status</TableCell>
</TableRow>
</TableHead>
<TableBody>
{claims.length === 0 ? (
<TableRow><TableCell colSpan={6} align="center">No open expense claims</TableCell></TableRow>
) : claims.map(c => (
<TableRow key={c.expenseClaimId} hover>
<TableCell>{c.organizationSequenceId}</TableCell>
<TableCell>{new Date(c.expenseDate).toLocaleDateString()}</TableCell>
<TableCell>{c.description}</TableCell>
<TableCell align="right" sx={{ fontFamily: 'monospace' }}>{formatCents(c.amountCents)}</TableCell>
<TableCell align="right" sx={{ fontFamily: 'monospace' }}>{c.vatCents > 0 ? formatCents(c.vatCents) : '—'}</TableCell>
<TableCell align="center">
{c.attested && c.validated ? <Chip label="Validated" size="small" color="success" /> :
c.attested ? <Chip label="Attested" size="small" color="info" /> :
<Chip label="Pending" size="small" color="warning" />}
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</TableContainer>
)}
</Box>
)
}
+62
View File
@@ -0,0 +1,62 @@
import { useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { Box, Card, CardContent, TextField, Button, Typography, Alert } from '@mui/material'
import { useAuth } from '../contexts/AuthContext'
export default function LoginPage() {
const { login, devImpersonate } = useAuth()
const navigate = useNavigate()
const [email, setEmail] = useState('')
const [password, setPassword] = useState('')
const [error, setError] = useState('')
const [loading, setLoading] = useState(false)
const handleLogin = async (e: React.FormEvent) => {
e.preventDefault()
setLoading(true)
setError('')
try {
await login(email, password)
navigate('/')
} catch (err: unknown) {
setError(err instanceof Error ? err.message : 'Login failed')
} finally {
setLoading(false)
}
}
const handleDevLogin = async () => {
try {
await devImpersonate()
navigate('/')
} catch {
setError('Dev impersonation failed')
}
}
return (
<Box sx={{ display: 'flex', justifyContent: 'center', alignItems: 'center', minHeight: '100vh', bgcolor: '#f5f5f5' }}>
<Card sx={{ width: 400, p: 2 }}>
<CardContent>
<Typography variant="h4" align="center" gutterBottom sx={{ fontWeight: 700, mb: 3 }}>
using.cash
</Typography>
{error && <Alert severity="error" sx={{ mb: 2 }}>{error}</Alert>}
<form onSubmit={handleLogin}>
<TextField fullWidth label="Email" type="email" value={email}
onChange={e => setEmail(e.target.value)} margin="normal" autoFocus />
<TextField fullWidth label="Password" type="password" value={password}
onChange={e => setPassword(e.target.value)} margin="normal" />
<Button fullWidth variant="contained" type="submit" disabled={loading}
sx={{ mt: 2, py: 1.2 }}>
{loading ? 'Signing in...' : 'Sign In'}
</Button>
</form>
<Button fullWidth variant="text" onClick={handleDevLogin} sx={{ mt: 1, fontSize: 12, color: 'text.secondary' }}>
Dev Mode: Skip Login
</Button>
</CardContent>
</Card>
</Box>
)
}
+12
View File
@@ -0,0 +1,12 @@
import { Box, Typography, Paper } from '@mui/material'
export default function PlaceholderPage({ title }: { title: string }) {
return (
<Box>
<Typography variant="h5" sx={{ fontWeight: 600, mb: 3 }}>{title}</Typography>
<Paper sx={{ p: 4, textAlign: 'center' }} elevation={1}>
<Typography color="text.secondary">This page is under construction.</Typography>
</Paper>
</Box>
)
}
+93
View File
@@ -0,0 +1,93 @@
import { useState, useEffect } from 'react'
import { Box, Typography, Paper, Table, TableBody, TableCell, TableContainer, TableHead, TableRow, TextField, Skeleton, Chip } from '@mui/material'
import { useOrg } from '../contexts/OrgContext'
import { api, type ProfitLoss } from '../api/client'
import { formatCents } from '../utils/money'
export default function ProfitLossPage() {
const { activeOrg } = useOrg()
const [data, setData] = useState<ProfitLoss | 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)
.then(setData)
.catch(() => {})
.finally(() => setLoading(false))
}, [activeOrg, year])
if (!activeOrg) return null
const isProfit = data && data.netResultCents > 0
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))}
label="Year" InputLabelProps={{ shrink: true }} sx={{ width: 120 }} />
</Box>
{loading ? <Skeleton height={300} /> : 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>
<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>
<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>
<Chip label={isProfit ? 'Profit' : 'Loss'} color={isProfit ? 'success' : 'error'} />
</Paper>
</>
) : <Typography color="text.secondary">No data</Typography>}
</Box>
)
}
+18
View File
@@ -0,0 +1,18 @@
export function formatCents(cents: number, currencyCode?: string): string {
const isCrypto = currencyCode === 'BTC' || currencyCode === 'BCH'
const divisor = isCrypto ? 1_000_000 : 100
const decimals = isCrypto ? 6 : 2
const value = cents / divisor
return value.toLocaleString(undefined, {
minimumFractionDigits: decimals,
maximumFractionDigits: decimals,
})
}
export function formatSatoshis(satoshis: number): string {
const bch = satoshis / 100_000_000
return bch.toLocaleString(undefined, {
minimumFractionDigits: 8,
maximumFractionDigits: 8,
})
}
+3 -2
View File
@@ -8,9 +8,10 @@ export default defineConfig({
emptyOutDir: true,
},
server: {
port: 3000,
proxy: {
'/api': 'http://localhost:5000',
'/ws': { target: 'ws://localhost:5000', ws: true },
'/api': 'http://localhost:5222',
'/ws': { target: 'ws://localhost:5222', ws: true },
},
},
})
+20 -20
View File
@@ -130,26 +130,26 @@
## 10. Frontend Application
- [ ] 10.1 Set up React project structure: routing, API client module, auth context (session cookies), org context, MUI theme, react-i18next with EN/SV/DE translation files
- [ ] 10.2 Implement reusable smart input components: monetary input (handles decimal commas/points, shows formatted confirmation) and date input (flexible format entry, shows interpreted date for verification)
- [ ] 10.3 Implement login page and auth flow (session cookie management, 401 redirect)
- [ ] 10.4 Implement app shell: sidebar navigation, top bar with org switcher and language selector, responsive layout
- [ ] 10.5 Implement dashboard page: task summary, YTD P&L, quick links, end-of-month status
- [ ] 10.6 Implement chart of accounts page: tree view with account types, create/edit/close/assign-owner actions
- [ ] 10.7 Implement inspect ledgers page: account selector, date range picker, transaction row table with running balance and continuation chain links
- [ ] 10.8 Implement balance sheet page: as-of date selector, asset/debt/equity breakdown
- [ ] 10.9 Implement profit & loss page: fiscal year selector, income/cost breakdown
- [ ] 10.10 Implement budget vs actual page: year selector, account-level budget/actual/variance table
- [ ] 10.11 Implement expense claim pages: submission form with smart monetary input for amount and VAT (when org VatEnabled), document upload, list view, attestation/validation actions
- [ ] 10.12 Implement inbound invoice pages: registration form with smart monetary input for amount and VAT, smart date input for issue/due dates, list view, attestation action
- [ ] 10.13 Implement outbound invoice pages: creation form with line items, VAT pre-filled from org default rate (editable for cross-border/exempt) using smart monetary input, list view, mark-paid action
- [ ] 10.14 Implement payout management page: group items, execute, confirm
- [ ] 10.15 Implement crypto treasury page: wallet balance, address list, UTXO details, fiat equivalent, deposit/payout history
- [ ] 10.16 Implement end-of-month page: monthly checklist, bank statement upload (manual review), year-end close link
- [ ] 10.17 Implement organization settings page: all denormalized settings (name, currency, default VAT rate, VAT config, tax IDs, logo)
- [ ] 10.18 Implement user management page: user list, create/edit/deactivate, role assignment
- [ ] 10.19 Implement WebSocket client for real-time notifications (deposit alerts, task updates)
- [ ] 10.20 Generate initial Swedish and German translation packs; human review for Swedish
- [x] 10.1 Set up React project structure: routing, API client module, auth context (session cookies), org context, MUI theme, react-i18next with EN/SV/DE translation files
- [x] 10.2 Implement reusable smart input components: monetary input (handles decimal commas/points, shows formatted confirmation) and date input (flexible format entry, shows interpreted date for verification)
- [x] 10.3 Implement login page and auth flow (session cookie management, 401 redirect)
- [x] 10.4 Implement app shell: sidebar navigation, top bar with org switcher and language selector, responsive layout
- [x] 10.5 Implement dashboard page: task summary, YTD P&L, quick links, end-of-month status
- [x] 10.6 Implement chart of accounts page: tree view with account types, create/edit/close/assign-owner actions
- [x] 10.7 Implement inspect ledgers page: account selector, date range picker, transaction row table with running balance and continuation chain links
- [x] 10.8 Implement balance sheet page: as-of date selector, asset/debt/equity breakdown
- [x] 10.9 Implement profit & loss page: fiscal year selector, income/cost breakdown
- [x] 10.10 Implement budget vs actual page: year selector, account-level budget/actual/variance table
- [x] 10.11 Implement expense claim pages: submission form with smart monetary input for amount and VAT (when org VatEnabled), document upload, list view, attestation/validation actions
- [x] 10.12 Implement inbound invoice pages: registration form with smart monetary input for amount and VAT, smart date input for issue/due dates, list view, attestation action
- [x] 10.13 Implement outbound invoice pages: creation form with line items, VAT pre-filled from org default rate (editable for cross-border/exempt) using smart monetary input, list view, mark-paid action
- [x] 10.14 Implement payout management page: group items, execute, confirm
- [x] 10.15 Implement crypto treasury page: wallet balance, address list, UTXO details, fiat equivalent, deposit/payout history
- [x] 10.16 Implement end-of-month page: monthly checklist, bank statement upload (manual review), year-end close link
- [x] 10.17 Implement organization settings page: all denormalized settings (name, currency, default VAT rate, VAT config, tax IDs, logo)
- [x] 10.18 Implement user management page: user list, create/edit/deactivate, role assignment
- [x] 10.19 Implement WebSocket client for real-time notifications (deposit alerts, task updates)
- [x] 10.20 Generate initial Swedish and German translation packs; human review for Swedish
## 11. Backend Worker (UsingCash.Backend)