diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index 57af5781..8f823e6e 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -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() { } /> } /> } /> + } /> } /> } /> } /> diff --git a/frontend/src/components/DateInput.tsx b/frontend/src/components/DateInput.tsx new file mode 100644 index 00000000..848d267a --- /dev/null +++ b/frontend/src/components/DateInput.tsx @@ -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 ( + onChange(e.target.value)} + size={size} + fullWidth={fullWidth} + required={required} + error={error} + helperText={helperText} + InputLabelProps={{ shrink: true }} + /> + ) +} diff --git a/frontend/src/components/MoneyInput.tsx b/frontend/src/components/MoneyInput.tsx new file mode 100644 index 00000000..ec990853 --- /dev/null +++ b/frontend/src/components/MoneyInput.tsx @@ -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) => { + 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 ( + + + {currencyCode} + + ) : undefined, + }} + /> + {showConfirmation && ( + + → {displayValue} + + )} + + ) +} + +export { parseMoney } diff --git a/frontend/src/pages/ExpenseClaimFormPage.tsx b/frontend/src/pages/ExpenseClaimFormPage.tsx new file mode 100644 index 00000000..a955739b --- /dev/null +++ b/frontend/src/pages/ExpenseClaimFormPage.tsx @@ -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([]) + const [description, setDescription] = useState('') + const [expenseDate, setExpenseDate] = useState(new Date().toISOString().slice(0, 10)) + const [amountCents, setAmountCents] = useState(null) + const [vatCents, setVatCents] = useState(null) + const [selectedAccount, setSelectedAccount] = useState(null) + const [file, setFile] = useState(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 ( + + File Expense Claim + + + + + setDescription(e.target.value)} + required + fullWidth + size="small" + placeholder="What was this expense for?" + autoFocus + /> + + + + + a.name} + value={selectedAccount} + onChange={(_, v) => setSelectedAccount(v)} + sx={{ flex: 1 }} + renderInput={params => ( + + )} + /> + + + + + + + + {activeOrg.vatEnabled && ( + + + + )} + + + {activeOrg.vatEnabled && amountCents !== null && amountCents > 0 && ( + + Net amount (excl. VAT): {((amountCents - (vatCents ?? 0)) / 100).toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })} {activeOrg.currencyCode} + + )} + + + + + + {file && ( + + {(file.size / 1024).toFixed(0)} KB + + )} + + + {error && {error}} + + + + + + + + + ) +} diff --git a/frontend/src/pages/ExpenseClaimsPage.tsx b/frontend/src/pages/ExpenseClaimsPage.tsx index 88039e6d..360c1859 100644 --- a/frontend/src/pages/ExpenseClaimsPage.tsx +++ b/frontend/src/pages/ExpenseClaimsPage.tsx @@ -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([]) const [loading, setLoading] = useState(true) @@ -22,7 +25,12 @@ export default function ExpenseClaimsPage() { return ( - Expense Claims + + Expense Claims + + {loading ? : (