import { useState, useMemo } from 'react'; import { Title, Table, Group, Button, Stack, Text, NumberInput, Select, Loader, Center, Card, SimpleGrid, Badge, Alert, } from '@mantine/core'; import { notifications } from '@mantine/notifications'; import { IconDeviceFloppy, IconInfoCircle, IconCalendarMonth, } from '@tabler/icons-react'; import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'; import api from '../../services/api'; import { useIsReadOnly } from '../../stores/authStore'; import { AttachmentPanel } from '../../components/attachments/AttachmentPanel'; interface ActualLine { account_id: string; account_number: string; account_name: string; account_type: string; fund_type: string; budget_amount: number; actual_amount: number; } interface ActualsGrid { year: number; month: number; month_label: string; existing_journal_entry_id: string | null; lines: ActualLine[]; } const monthOptions = [ { value: '1', label: 'January' }, { value: '2', label: 'February' }, { value: '3', label: 'March' }, { value: '4', label: 'April' }, { value: '5', label: 'May' }, { value: '6', label: 'June' }, { value: '7', label: 'July' }, { value: '8', label: 'August' }, { value: '9', label: 'September' }, { value: '10', label: 'October' }, { value: '11', label: 'November' }, { value: '12', label: 'December' }, ]; function getDefaultMonth(): { year: string; month: string } { const now = new Date(); // Default to previous completed month const prev = new Date(now.getFullYear(), now.getMonth() - 1, 1); return { year: String(prev.getFullYear()), month: String(prev.getMonth() + 1), }; } const fmt = (v: number) => (v || 0).toLocaleString('en-US', { style: 'currency', currency: 'USD', minimumFractionDigits: 0 }); export function MonthlyActualsPage() { const defaults = getDefaultMonth(); const [year, setYear] = useState(defaults.year); const [month, setMonth] = useState(defaults.month); const [editedAmounts, setEditedAmounts] = useState>({}); const [savedJEId, setSavedJEId] = useState(null); const queryClient = useQueryClient(); const isReadOnly = useIsReadOnly(); const yearOptions = Array.from({ length: 5 }, (_, i) => { const y = new Date().getFullYear() - 2 + i; return { value: String(y), label: String(y) }; }); const { data: grid, isLoading } = useQuery({ queryKey: ['monthly-actuals', year, month], queryFn: async () => { const { data } = await api.get(`/monthly-actuals/${year}/${month}`); setEditedAmounts({}); setSavedJEId(data.existing_journal_entry_id || null); return data; }, }); const saveMutation = useMutation({ mutationFn: async () => { const lines = (grid?.lines || []) .map((line) => ({ accountId: line.account_id, amount: editedAmounts[line.account_id] !== undefined ? editedAmounts[line.account_id] : line.actual_amount, })) .filter((l) => l.amount !== 0); const { data } = await api.post(`/monthly-actuals/${year}/${month}`, { lines }); return data; }, onSuccess: (data) => { queryClient.invalidateQueries({ queryKey: ['monthly-actuals'] }); queryClient.invalidateQueries({ queryKey: ['journal-entries'] }); queryClient.invalidateQueries({ queryKey: ['accounts'] }); queryClient.invalidateQueries({ queryKey: ['budget-vs-actual'] }); setSavedJEId(data.journal_entry_id); notifications.show({ message: data.message || 'Actuals saved and reconciled', color: 'green', autoClose: 5000, }); }, onError: (err: any) => { notifications.show({ message: err.response?.data?.message || 'Failed to save actuals', color: 'red', }); }, }); const getAmount = (line: ActualLine): number => { return editedAmounts[line.account_id] !== undefined ? editedAmounts[line.account_id] : line.actual_amount; }; const updateAmount = (accountId: string, value: number) => { setEditedAmounts((prev) => ({ ...prev, [accountId]: value })); }; const lines = grid?.lines || []; const incomeLines = lines.filter((l) => l.account_type === 'income'); const expenseLines = lines.filter((l) => l.account_type === 'expense'); const totals = useMemo(() => { const incomeBudget = incomeLines.reduce((s, l) => s + l.budget_amount, 0); const incomeActual = incomeLines.reduce((s, l) => s + getAmount(l), 0); const expenseBudget = expenseLines.reduce((s, l) => s + l.budget_amount, 0); const expenseActual = expenseLines.reduce((s, l) => s + getAmount(l), 0); return { incomeBudget, incomeActual, expenseBudget, expenseActual }; }, [lines, editedAmounts]); const hasChanges = Object.keys(editedAmounts).length > 0; const monthLabel = monthOptions.find((m) => m.value === month)?.label || ''; if (isLoading) return
; const renderSection = ( title: string, sectionLines: ActualLine[], bgColor: string, budgetTotal: number, actualTotal: number, ) => { if (sectionLines.length === 0) return null; const variance = actualTotal - budgetTotal; const isExpense = title === 'Expenses'; return [ {title} {fmt(budgetTotal)} 0 ? 'red' : 'green') : (variance > 0 ? 'green' : 'red'))} > {variance > 0 ? '+' : ''}{fmt(variance)} , ...sectionLines.map((line) => { const amount = getAmount(line); const lineVariance = amount - line.budget_amount; return ( {line.account_number} {line.account_name} {line.fund_type === 'reserve' && R} {fmt(line.budget_amount)} updateAmount(line.account_id, Number(v) || 0)} size="xs" hideControls decimalScale={2} allowNegative disabled={isReadOnly} styles={{ input: { textAlign: 'right', fontFamily: 'monospace' } }} /> 0 ? 'red' : 'green') : (lineVariance > 0 ? 'green' : 'red'))} > {lineVariance > 0 ? '+' : ''}{fmt(lineVariance)} ); }), ]; }; return ( Monthly Actuals v && setMonth(v)} w={150} /> {!isReadOnly && ( )} Income Budget {fmt(totals.incomeBudget)} Actual: {fmt(totals.incomeActual)} Expense Budget {fmt(totals.expenseBudget)} Actual: {fmt(totals.expenseActual)} Net Budget = 0 ? 'green' : 'red'}> {fmt(totals.incomeBudget - totals.expenseBudget)} Net Actual = 0 ? 'green' : 'red'}> {fmt(totals.incomeActual - totals.expenseActual)} {lines.length === 0 && ( } color="blue" variant="light"> No income or expense accounts found for {monthLabel} {year}. Import a budget first to create accounts. )} {savedJEId && ( } color="green" variant="light"> Actuals for {monthLabel} {year} have been reconciled. Journal entry created and auto-posted. Reconciled )}
Acct # Account Name Budget Actual Variance {renderSection('Income', incomeLines, '#e6f9e6', totals.incomeBudget, totals.incomeActual)} {renderSection('Expenses', expenseLines, '#fde8e8', totals.expenseBudget, totals.expenseActual)}
{/* Attachment panel - show when we have a saved journal entry for this month */} {savedJEId && ( Attachments (Receipts & Invoices) )}
); }