Add smart MoneyInput, DateInput, and expense claim submission form
MoneyInput component: - Accepts flexible monetary input: 1234.50, 1234,50, 1.234,50, 1,234.50 - Heuristic: if both dot and comma present, last one is decimal separator - If single separator followed by exactly 3 digits, it's thousands - Shows "→ formatted" confirmation below the field while typing - Returns value in cents (Int64) to parent - Right-aligned monospace display with currency code adornment - On blur, replaces raw input with formatted value DateInput component: - Wrapper around native date picker - Always stores/communicates ISO 8601 (YYYY-MM-DD) ExpenseClaimFormPage: - Description, date, budget account selector, total amount, VAT amount (when org VatEnabled), receipt upload, submit button - Finds system accounts (Expense Claims debt, VAT inbound) automatically - Shows net amount (excl. VAT) when VAT is entered - Uploads attached document after claim creation - Redirects to expense claims list on success - "File Expense Claim" button added to expense claims list page Made-with: Cursor
This commit is contained in:
@@ -10,6 +10,7 @@ import ChartOfAccountsPage from './pages/ChartOfAccountsPage'
|
||||
import CryptoTreasuryPage from './pages/CryptoTreasuryPage'
|
||||
import ExpenseClaimsPage from './pages/ExpenseClaimsPage'
|
||||
import InspectLedgersPage from './pages/InspectLedgersPage'
|
||||
import ExpenseClaimFormPage from './pages/ExpenseClaimFormPage'
|
||||
import PlaceholderPage from './pages/PlaceholderPage'
|
||||
|
||||
function RequireAuth({ children }: { children: React.ReactNode }) {
|
||||
@@ -31,6 +32,7 @@ export default function App() {
|
||||
<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/expense-claims/new" element={<ExpenseClaimFormPage />} />
|
||||
<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" />} />
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
import { TextField } from '@mui/material'
|
||||
|
||||
interface DateInputProps {
|
||||
label: string
|
||||
value: string
|
||||
onChange: (isoDate: string) => void
|
||||
required?: boolean
|
||||
error?: boolean
|
||||
helperText?: string
|
||||
size?: 'small' | 'medium'
|
||||
fullWidth?: boolean
|
||||
}
|
||||
|
||||
/**
|
||||
* Date input using the native date picker.
|
||||
* Always stores and communicates in ISO 8601 (YYYY-MM-DD).
|
||||
* The browser renders in the user's locale format.
|
||||
*/
|
||||
export default function DateInput({
|
||||
label, value, onChange, required, error, helperText,
|
||||
size = 'small', fullWidth = true,
|
||||
}: DateInputProps) {
|
||||
return (
|
||||
<TextField
|
||||
type="date"
|
||||
label={label}
|
||||
value={value}
|
||||
onChange={e => onChange(e.target.value)}
|
||||
size={size}
|
||||
fullWidth={fullWidth}
|
||||
required={required}
|
||||
error={error}
|
||||
helperText={helperText}
|
||||
InputLabelProps={{ shrink: true }}
|
||||
/>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,198 @@
|
||||
import { useState, useCallback, useEffect } from 'react'
|
||||
import { TextField, Typography, Box, InputAdornment } from '@mui/material'
|
||||
|
||||
interface MoneyInputProps {
|
||||
label: string
|
||||
value: number | null
|
||||
onChange: (cents: number | null) => void
|
||||
currencyCode?: string
|
||||
required?: boolean
|
||||
error?: boolean
|
||||
helperText?: string
|
||||
size?: 'small' | 'medium'
|
||||
fullWidth?: boolean
|
||||
autoFocus?: boolean
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse a flexible monetary input string into cents.
|
||||
*
|
||||
* Handles:
|
||||
* "1234.50" → 123450 (dot as decimal)
|
||||
* "1234,50" → 123450 (comma as decimal)
|
||||
* "1,234.50" → 123450 (comma as thousands, dot as decimal)
|
||||
* "1.234,50" → 123450 (dot as thousands, comma as decimal)
|
||||
* "1234" → 123400 (no decimals)
|
||||
* "1234.5" → 123450 (one decimal digit)
|
||||
*
|
||||
* Heuristic: if the string has both dot and comma, the LAST one is the
|
||||
* decimal separator. If only one separator exists and it's followed by
|
||||
* exactly 3 digits, it's a thousands separator (e.g., "1.234" = 1234,
|
||||
* not 1.234). Otherwise it's a decimal separator.
|
||||
*/
|
||||
function parseMoney(input: string): number | null {
|
||||
const trimmed = input.trim().replace(/\s/g, '')
|
||||
if (!trimmed || trimmed === '-') return null
|
||||
|
||||
const isNegative = trimmed.startsWith('-')
|
||||
const abs = isNegative ? trimmed.slice(1) : trimmed
|
||||
|
||||
// Remove currency symbols and letters
|
||||
const cleaned = abs.replace(/[^0-9.,]/g, '')
|
||||
if (!cleaned) return null
|
||||
|
||||
const lastDot = cleaned.lastIndexOf('.')
|
||||
const lastComma = cleaned.lastIndexOf(',')
|
||||
|
||||
let wholePart: string
|
||||
let decimalPart: string
|
||||
|
||||
if (lastDot >= 0 && lastComma >= 0) {
|
||||
// Both present: last one is the decimal separator
|
||||
if (lastDot > lastComma) {
|
||||
// "1,234.50" — dot is decimal
|
||||
wholePart = cleaned.substring(0, lastDot).replace(/[.,]/g, '')
|
||||
decimalPart = cleaned.substring(lastDot + 1)
|
||||
} else {
|
||||
// "1.234,50" — comma is decimal
|
||||
wholePart = cleaned.substring(0, lastComma).replace(/[.,]/g, '')
|
||||
decimalPart = cleaned.substring(lastComma + 1)
|
||||
}
|
||||
} else if (lastDot >= 0) {
|
||||
const afterDot = cleaned.substring(lastDot + 1)
|
||||
if (afterDot.length === 3 && cleaned.indexOf('.') === lastDot) {
|
||||
// "1.234" — dot is thousands separator (exactly 3 digits after, single dot)
|
||||
wholePart = cleaned.replace(/\./g, '')
|
||||
decimalPart = ''
|
||||
} else {
|
||||
// "1234.50" or "1234.5" — dot is decimal
|
||||
wholePart = cleaned.substring(0, lastDot).replace(/\./g, '')
|
||||
decimalPart = afterDot
|
||||
}
|
||||
} else if (lastComma >= 0) {
|
||||
const afterComma = cleaned.substring(lastComma + 1)
|
||||
if (afterComma.length === 3 && cleaned.indexOf(',') === lastComma) {
|
||||
// "1,234" — comma is thousands separator
|
||||
wholePart = cleaned.replace(/,/g, '')
|
||||
decimalPart = ''
|
||||
} else {
|
||||
// "1234,50" or "1234,5" — comma is decimal
|
||||
wholePart = cleaned.substring(0, lastComma).replace(/,/g, '')
|
||||
decimalPart = afterComma
|
||||
}
|
||||
} else {
|
||||
// No separator: "1234"
|
||||
wholePart = cleaned
|
||||
decimalPart = ''
|
||||
}
|
||||
|
||||
// Normalize decimal to exactly 2 digits
|
||||
if (decimalPart.length === 0) decimalPart = '00'
|
||||
else if (decimalPart.length === 1) decimalPart = decimalPart + '0'
|
||||
else if (decimalPart.length > 2) decimalPart = decimalPart.substring(0, 2)
|
||||
|
||||
const cents = parseInt(wholePart + decimalPart, 10)
|
||||
if (isNaN(cents)) return null
|
||||
|
||||
return isNegative ? -cents : cents
|
||||
}
|
||||
|
||||
function formatForDisplay(cents: number): string {
|
||||
const value = cents / 100
|
||||
return value.toLocaleString(undefined, {
|
||||
minimumFractionDigits: 2,
|
||||
maximumFractionDigits: 2,
|
||||
})
|
||||
}
|
||||
|
||||
export default function MoneyInput({
|
||||
label, value, onChange, currencyCode, required, error, helperText,
|
||||
size = 'small', fullWidth = true, autoFocus,
|
||||
}: MoneyInputProps) {
|
||||
const [rawInput, setRawInput] = useState('')
|
||||
const [displayValue, setDisplayValue] = useState('')
|
||||
const [isFocused, setIsFocused] = useState(false)
|
||||
|
||||
// Sync external value → display (when not focused)
|
||||
useEffect(() => {
|
||||
if (!isFocused && value !== null) {
|
||||
setDisplayValue(formatForDisplay(value))
|
||||
setRawInput(formatForDisplay(value))
|
||||
} else if (!isFocused && value === null) {
|
||||
setDisplayValue('')
|
||||
setRawInput('')
|
||||
}
|
||||
}, [value, isFocused])
|
||||
|
||||
const handleChange = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const input = e.target.value
|
||||
setRawInput(input)
|
||||
|
||||
const cents = parseMoney(input)
|
||||
onChange(cents)
|
||||
|
||||
if (cents !== null) {
|
||||
setDisplayValue(formatForDisplay(cents))
|
||||
} else {
|
||||
setDisplayValue('')
|
||||
}
|
||||
}, [onChange])
|
||||
|
||||
const handleFocus = useCallback(() => {
|
||||
setIsFocused(true)
|
||||
}, [])
|
||||
|
||||
const handleBlur = useCallback(() => {
|
||||
setIsFocused(false)
|
||||
// On blur, replace raw input with formatted value
|
||||
if (value !== null) {
|
||||
setRawInput(formatForDisplay(value))
|
||||
}
|
||||
}, [value])
|
||||
|
||||
const showConfirmation = isFocused && rawInput.length > 0 && displayValue && rawInput !== displayValue
|
||||
|
||||
return (
|
||||
<Box sx={{ position: 'relative' }}>
|
||||
<TextField
|
||||
label={label}
|
||||
value={isFocused ? rawInput : displayValue}
|
||||
onChange={handleChange}
|
||||
onFocus={handleFocus}
|
||||
onBlur={handleBlur}
|
||||
size={size}
|
||||
fullWidth={fullWidth}
|
||||
required={required}
|
||||
error={error}
|
||||
helperText={helperText}
|
||||
autoFocus={autoFocus}
|
||||
inputProps={{ inputMode: 'decimal', style: { textAlign: 'right', fontFamily: '"Roboto Mono", monospace' } }}
|
||||
InputProps={{
|
||||
endAdornment: currencyCode ? (
|
||||
<InputAdornment position="end">
|
||||
<Typography variant="caption" color="text.secondary">{currencyCode}</Typography>
|
||||
</InputAdornment>
|
||||
) : undefined,
|
||||
}}
|
||||
/>
|
||||
{showConfirmation && (
|
||||
<Typography
|
||||
variant="caption"
|
||||
sx={{
|
||||
position: 'absolute',
|
||||
right: currencyCode ? 40 : 8,
|
||||
bottom: -16,
|
||||
color: 'success.main',
|
||||
fontFamily: '"Roboto Mono", monospace',
|
||||
fontSize: 11,
|
||||
fontWeight: 600,
|
||||
}}
|
||||
>
|
||||
→ {displayValue}
|
||||
</Typography>
|
||||
)}
|
||||
</Box>
|
||||
)
|
||||
}
|
||||
|
||||
export { parseMoney }
|
||||
@@ -0,0 +1,205 @@
|
||||
import { useState, useEffect } from 'react'
|
||||
import { useNavigate } from 'react-router-dom'
|
||||
import {
|
||||
Box, Typography, Paper, Button, Autocomplete, TextField,
|
||||
Alert, Snackbar, Divider,
|
||||
} from '@mui/material'
|
||||
import { Send, AttachFile } from '@mui/icons-material'
|
||||
import { useOrg } from '../contexts/OrgContext'
|
||||
import { api, type Account } from '../api/client'
|
||||
import MoneyInput from '../components/MoneyInput'
|
||||
import DateInput from '../components/DateInput'
|
||||
|
||||
export default function ExpenseClaimFormPage() {
|
||||
const { activeOrg } = useOrg()
|
||||
const navigate = useNavigate()
|
||||
|
||||
const [accounts, setAccounts] = useState<Account[]>([])
|
||||
const [description, setDescription] = useState('')
|
||||
const [expenseDate, setExpenseDate] = useState(new Date().toISOString().slice(0, 10))
|
||||
const [amountCents, setAmountCents] = useState<number | null>(null)
|
||||
const [vatCents, setVatCents] = useState<number | null>(null)
|
||||
const [selectedAccount, setSelectedAccount] = useState<Account | null>(null)
|
||||
const [file, setFile] = useState<File | null>(null)
|
||||
const [submitting, setSubmitting] = useState(false)
|
||||
const [error, setError] = useState('')
|
||||
const [success, setSuccess] = useState(false)
|
||||
|
||||
useEffect(() => {
|
||||
if (!activeOrg) return
|
||||
api.accounts(activeOrg.organizationId).list()
|
||||
.then(accts => setAccounts(accts.filter(a => a.expensable && a.open)))
|
||||
.catch(() => {})
|
||||
}, [activeOrg])
|
||||
|
||||
if (!activeOrg) return null
|
||||
|
||||
const isValid = description.trim().length > 0
|
||||
&& amountCents !== null && amountCents > 0
|
||||
&& selectedAccount !== null
|
||||
&& expenseDate.length > 0
|
||||
|
||||
const handleSubmit = async () => {
|
||||
if (!isValid || !selectedAccount || !activeOrg) return
|
||||
setSubmitting(true)
|
||||
setError('')
|
||||
|
||||
try {
|
||||
// Find the system accounts needed for the ledger transaction
|
||||
const allAccounts = await api.accounts(activeOrg.organizationId).list()
|
||||
const debtsExpenseClaims = allAccounts.find(a => a.name.includes('Debt_ExpenseClaims') || a.name.includes('Expense Claims'))
|
||||
const vatAccount = allAccounts.find(a => a.name.includes('VatInboundUnreported') || a.name.includes('Inbound VAT to report'))
|
||||
|
||||
if (!debtsExpenseClaims) {
|
||||
setError('System account "Expense Claims" (debt) not found. Check chart of accounts.')
|
||||
setSubmitting(false)
|
||||
return
|
||||
}
|
||||
|
||||
const result = await api.post<{ expenseClaimId: number; financialTransactionId: number }>(
|
||||
`/organizations/${activeOrg.organizationId}/expense-claims`,
|
||||
{
|
||||
expenseDate,
|
||||
description: description.trim(),
|
||||
budgetId: selectedAccount.financialAccountId,
|
||||
amountCents: amountCents,
|
||||
vatCents: vatCents ?? 0,
|
||||
debtsExpenseClaimsAccountId: debtsExpenseClaims.financialAccountId,
|
||||
assetsVatInboundUnreportedAccountId: vatAccount?.financialAccountId ?? 0,
|
||||
}
|
||||
)
|
||||
|
||||
// Upload document if attached
|
||||
if (file && result.expenseClaimId) {
|
||||
const formData = new FormData()
|
||||
formData.append('file', file)
|
||||
formData.append('documentType', 'ExpenseReceipt')
|
||||
formData.append('foreignId', result.expenseClaimId.toString())
|
||||
formData.append('description', description.trim())
|
||||
await api.upload(`/organizations/${activeOrg.organizationId}/documents`, formData)
|
||||
}
|
||||
|
||||
setSuccess(true)
|
||||
setTimeout(() => navigate('/financial/expense-claims'), 1500)
|
||||
} catch (err: unknown) {
|
||||
setError(err instanceof Error ? err.message : 'Submission failed')
|
||||
} finally {
|
||||
setSubmitting(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Box sx={{ maxWidth: 700 }}>
|
||||
<Typography variant="h5" sx={{ fontWeight: 600, mb: 3 }}>File Expense Claim</Typography>
|
||||
|
||||
<Paper sx={{ p: 3 }} elevation={2}>
|
||||
<Box sx={{ display: 'flex', flexDirection: 'column', gap: 2.5 }}>
|
||||
|
||||
<TextField
|
||||
label="Description"
|
||||
value={description}
|
||||
onChange={e => setDescription(e.target.value)}
|
||||
required
|
||||
fullWidth
|
||||
size="small"
|
||||
placeholder="What was this expense for?"
|
||||
autoFocus
|
||||
/>
|
||||
|
||||
<Box sx={{ display: 'flex', gap: 2 }}>
|
||||
<DateInput
|
||||
label="Expense Date"
|
||||
value={expenseDate}
|
||||
onChange={setExpenseDate}
|
||||
required
|
||||
fullWidth={false}
|
||||
/>
|
||||
|
||||
<Autocomplete
|
||||
options={accounts}
|
||||
getOptionLabel={a => a.name}
|
||||
value={selectedAccount}
|
||||
onChange={(_, v) => setSelectedAccount(v)}
|
||||
sx={{ flex: 1 }}
|
||||
renderInput={params => (
|
||||
<TextField {...params} label="Budget Account" size="small" required />
|
||||
)}
|
||||
/>
|
||||
</Box>
|
||||
|
||||
<Box sx={{ display: 'flex', gap: 2 }}>
|
||||
<Box sx={{ flex: 1 }}>
|
||||
<MoneyInput
|
||||
label="Total Amount"
|
||||
value={amountCents}
|
||||
onChange={setAmountCents}
|
||||
currencyCode={activeOrg.currencyCode}
|
||||
required
|
||||
/>
|
||||
</Box>
|
||||
|
||||
{activeOrg.vatEnabled && (
|
||||
<Box sx={{ flex: 1 }}>
|
||||
<MoneyInput
|
||||
label="VAT Amount"
|
||||
value={vatCents}
|
||||
onChange={setVatCents}
|
||||
currencyCode={activeOrg.currencyCode}
|
||||
/>
|
||||
</Box>
|
||||
)}
|
||||
</Box>
|
||||
|
||||
{activeOrg.vatEnabled && amountCents !== null && amountCents > 0 && (
|
||||
<Typography variant="body2" color="text.secondary" sx={{ mt: -1, ml: 0.5 }}>
|
||||
Net amount (excl. VAT): {((amountCents - (vatCents ?? 0)) / 100).toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })} {activeOrg.currencyCode}
|
||||
</Typography>
|
||||
)}
|
||||
|
||||
<Divider />
|
||||
|
||||
<Box>
|
||||
<Button
|
||||
variant="outlined"
|
||||
component="label"
|
||||
startIcon={<AttachFile />}
|
||||
sx={{ textTransform: 'none' }}
|
||||
>
|
||||
{file ? file.name : 'Attach Receipt (PDF, image)'}
|
||||
<input
|
||||
type="file"
|
||||
hidden
|
||||
accept=".pdf,.jpg,.jpeg,.png,.gif,.webp"
|
||||
onChange={e => setFile(e.target.files?.[0] ?? null)}
|
||||
/>
|
||||
</Button>
|
||||
{file && (
|
||||
<Typography variant="caption" color="text.secondary" sx={{ ml: 1 }}>
|
||||
{(file.size / 1024).toFixed(0)} KB
|
||||
</Typography>
|
||||
)}
|
||||
</Box>
|
||||
|
||||
{error && <Alert severity="error">{error}</Alert>}
|
||||
|
||||
<Button
|
||||
variant="contained"
|
||||
onClick={handleSubmit}
|
||||
disabled={!isValid || submitting}
|
||||
startIcon={<Send />}
|
||||
sx={{ alignSelf: 'flex-end', px: 4 }}
|
||||
>
|
||||
{submitting ? 'Submitting...' : 'Submit Expense Claim'}
|
||||
</Button>
|
||||
|
||||
</Box>
|
||||
</Paper>
|
||||
|
||||
<Snackbar
|
||||
open={success}
|
||||
autoHideDuration={3000}
|
||||
message="Expense claim submitted successfully!"
|
||||
/>
|
||||
</Box>
|
||||
)
|
||||
}
|
||||
@@ -1,11 +1,14 @@
|
||||
import { useState, useEffect } from 'react'
|
||||
import { Box, Typography, Paper, Table, TableBody, TableCell, TableContainer, TableHead, TableRow, Chip, Skeleton } from '@mui/material'
|
||||
import { useNavigate } from 'react-router-dom'
|
||||
import { Box, Typography, Paper, Table, TableBody, TableCell, TableContainer, TableHead, TableRow, Chip, Skeleton, Button } from '@mui/material'
|
||||
import { Add } from '@mui/icons-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 navigate = useNavigate()
|
||||
const [claims, setClaims] = useState<ExpenseClaim[]>([])
|
||||
const [loading, setLoading] = useState(true)
|
||||
|
||||
@@ -22,7 +25,12 @@ export default function ExpenseClaimsPage() {
|
||||
|
||||
return (
|
||||
<Box>
|
||||
<Typography variant="h5" sx={{ fontWeight: 600, mb: 3 }}>Expense Claims</Typography>
|
||||
<Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 3 }}>
|
||||
<Typography variant="h5" sx={{ fontWeight: 600 }}>Expense Claims</Typography>
|
||||
<Button variant="contained" startIcon={<Add />} onClick={() => navigate('/financial/expense-claims/new')}>
|
||||
File Expense Claim
|
||||
</Button>
|
||||
</Box>
|
||||
|
||||
{loading ? <Skeleton height={300} /> : (
|
||||
<TableContainer component={Paper} elevation={2}>
|
||||
|
||||
Reference in New Issue
Block a user