fix: compound inflation, budget planner CSV import, simplify budget manager
- Fix compound inflation: use Math.pow(1 + rate/100, yearsGap) instead of flat rate so multi-year gaps (e.g., 2026→2029) compound annually - Budget Planner: add CSV import flow + Download Template button; show proper empty state when no base budget exists with Create/Import options - Budget Manager: remove CSV import, Download Template, and Save buttons; redirect users to Budget Planner when no budget exists for selected year - Fix getAvailableYears to return null latestBudgetYear when no budgets exist and include current year in year selector for fresh tenants Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
@@ -1,4 +1,4 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { useState, useEffect, useRef } from 'react';
|
||||
import {
|
||||
Title, Table, Group, Button, Stack, Text, NumberInput,
|
||||
Select, Loader, Center, Badge, Card, Alert, Modal,
|
||||
@@ -7,6 +7,7 @@ import { notifications } from '@mantine/notifications';
|
||||
import {
|
||||
IconDeviceFloppy, IconInfoCircle, IconPencil, IconX,
|
||||
IconCheck, IconArrowBack, IconTrash, IconRefresh,
|
||||
IconUpload, IconDownload,
|
||||
} from '@tabler/icons-react';
|
||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
|
||||
import api from '../../services/api';
|
||||
@@ -41,6 +42,43 @@ function hydrateLine(row: any): PlanLine {
|
||||
return line as PlanLine;
|
||||
}
|
||||
|
||||
function parseCurrencyValue(val: string): number {
|
||||
if (!val) return 0;
|
||||
let s = val.trim();
|
||||
if (!s || s === '-' || s === '$-' || s === '$ -') return 0;
|
||||
const isNegative = s.includes('(') && s.includes(')');
|
||||
s = s.replace(/[$,\s()]/g, '');
|
||||
if (!s || s === '-') return 0;
|
||||
const num = parseFloat(s);
|
||||
if (isNaN(num)) return 0;
|
||||
return isNegative ? -num : num;
|
||||
}
|
||||
|
||||
function parseCSV(text: string): Record<string, string>[] {
|
||||
const lines = text.trim().split('\n');
|
||||
if (lines.length < 2) return [];
|
||||
const headers = lines[0].split(',').map((h) => h.trim().toLowerCase());
|
||||
const rows: Record<string, string>[] = [];
|
||||
for (let i = 1; i < lines.length; i++) {
|
||||
const line = lines[i].trim();
|
||||
if (!line) continue;
|
||||
const values: string[] = [];
|
||||
let current = '';
|
||||
let inQuotes = false;
|
||||
for (let j = 0; j < line.length; j++) {
|
||||
const ch = line[j];
|
||||
if (ch === '"') { inQuotes = !inQuotes; }
|
||||
else if (ch === ',' && !inQuotes) { values.push(current.trim()); current = ''; }
|
||||
else { current += ch; }
|
||||
}
|
||||
values.push(current.trim());
|
||||
const row: Record<string, string> = {};
|
||||
headers.forEach((h, idx) => { row[h] = values[idx] || ''; });
|
||||
rows.push(row);
|
||||
}
|
||||
return rows;
|
||||
}
|
||||
|
||||
const statusColors: Record<string, string> = {
|
||||
planning: 'blue',
|
||||
approved: 'yellow',
|
||||
@@ -61,6 +99,7 @@ export function BudgetPlanningPage() {
|
||||
const [isEditing, setIsEditing] = useState(false);
|
||||
const [inflationInput, setInflationInput] = useState<number>(2.5);
|
||||
const [confirmModal, setConfirmModal] = useState<{ action: string; title: string; message: string } | null>(null);
|
||||
const fileInputRef = useRef<HTMLInputElement>(null);
|
||||
|
||||
// Available years
|
||||
const { data: availableYears } = useQuery<any>({
|
||||
@@ -99,11 +138,19 @@ export function BudgetPlanningPage() {
|
||||
}
|
||||
}, [plan]);
|
||||
|
||||
const hasBaseBudget = !!availableYears?.latestBudgetYear;
|
||||
|
||||
const yearOptions = (availableYears?.years || []).map((y: any) => ({
|
||||
value: String(y.year),
|
||||
label: `${y.year}${y.hasPlan ? ` (${y.status})` : ''}`,
|
||||
}));
|
||||
|
||||
// If no base budget at all, also offer the current year as an option
|
||||
const currentYear = new Date().getFullYear();
|
||||
const allYearOptions = !hasBaseBudget && !yearOptions.find((y: any) => y.value === String(currentYear))
|
||||
? [{ value: String(currentYear), label: String(currentYear) }, ...yearOptions]
|
||||
: yearOptions;
|
||||
|
||||
// Mutations
|
||||
const createMutation = useMutation({
|
||||
mutationFn: async () => {
|
||||
@@ -150,6 +197,45 @@ export function BudgetPlanningPage() {
|
||||
},
|
||||
});
|
||||
|
||||
const importMutation = useMutation({
|
||||
mutationFn: async (lines: Record<string, string>[]) => {
|
||||
const parsed = lines.map((row) => ({
|
||||
account_number: row.account_number || row.accountnumber || '',
|
||||
account_name: row.account_name || row.accountname || '',
|
||||
jan: parseCurrencyValue(row.jan),
|
||||
feb: parseCurrencyValue(row.feb),
|
||||
mar: parseCurrencyValue(row.mar),
|
||||
apr: parseCurrencyValue(row.apr),
|
||||
may: parseCurrencyValue(row.may),
|
||||
jun: parseCurrencyValue(row.jun),
|
||||
jul: parseCurrencyValue(row.jul),
|
||||
aug: parseCurrencyValue(row.aug),
|
||||
sep: parseCurrencyValue(row.sep),
|
||||
oct: parseCurrencyValue(row.oct),
|
||||
nov: parseCurrencyValue(row.nov),
|
||||
dec_amt: parseCurrencyValue(row.dec_amt || row.dec || ''),
|
||||
}));
|
||||
const { data } = await api.post(`/board-planning/budget-plans/${selectedYear}/import`, parsed);
|
||||
return data;
|
||||
},
|
||||
onSuccess: (data) => {
|
||||
queryClient.invalidateQueries({ queryKey: ['budget-plan', selectedYear] });
|
||||
queryClient.invalidateQueries({ queryKey: ['budget-plan-available-years'] });
|
||||
queryClient.invalidateQueries({ queryKey: ['accounts'] });
|
||||
let msg = `Imported ${data.imported} budget line(s)`;
|
||||
if (data.created?.length) msg += `. Created ${data.created.length} new account(s)`;
|
||||
if (data.errors?.length) msg += `. ${data.errors.length} error(s): ${data.errors.join('; ')}`;
|
||||
notifications.show({
|
||||
message: msg,
|
||||
color: data.errors?.length ? 'yellow' : 'green',
|
||||
autoClose: 10000,
|
||||
});
|
||||
},
|
||||
onError: (err: any) => {
|
||||
notifications.show({ message: err.response?.data?.message || 'Import failed', color: 'red' });
|
||||
},
|
||||
});
|
||||
|
||||
const inflationMutation = useMutation({
|
||||
mutationFn: () => api.put(`/board-planning/budget-plans/${selectedYear}/inflation`, {
|
||||
inflationRate: inflationInput,
|
||||
@@ -197,6 +283,45 @@ export function BudgetPlanningPage() {
|
||||
queryClient.invalidateQueries({ queryKey: ['budget-plan', selectedYear] });
|
||||
};
|
||||
|
||||
const handleDownloadTemplate = async () => {
|
||||
try {
|
||||
const yr = selectedYear || currentYear;
|
||||
const response = await api.get(`/board-planning/budget-plans/${yr}/template`, {
|
||||
responseType: 'blob',
|
||||
});
|
||||
const blob = new Blob([response.data], { type: 'text/csv' });
|
||||
const url = window.URL.createObjectURL(blob);
|
||||
const a = document.createElement('a');
|
||||
a.href = url;
|
||||
a.download = `budget_template_${yr}.csv`;
|
||||
document.body.appendChild(a);
|
||||
a.click();
|
||||
document.body.removeChild(a);
|
||||
window.URL.revokeObjectURL(url);
|
||||
} catch (err: any) {
|
||||
notifications.show({ message: 'Failed to download template', color: 'red' });
|
||||
}
|
||||
};
|
||||
|
||||
const handleImportCSV = () => {
|
||||
fileInputRef.current?.click();
|
||||
};
|
||||
|
||||
const handleFileChange = (event: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const file = event.target.files?.[0];
|
||||
if (!file) return;
|
||||
const reader = new FileReader();
|
||||
reader.onload = (e) => {
|
||||
const text = e.target?.result as string;
|
||||
if (!text) { notifications.show({ message: 'Could not read file', color: 'red' }); return; }
|
||||
const rows = parseCSV(text);
|
||||
if (rows.length === 0) { notifications.show({ message: 'No data rows found in CSV', color: 'red' }); return; }
|
||||
importMutation.mutate(rows);
|
||||
};
|
||||
reader.readAsText(file);
|
||||
event.target.value = '';
|
||||
};
|
||||
|
||||
const hasPlan = !!plan?.id;
|
||||
const status = plan?.status || 'planning';
|
||||
const cellsEditable = !isReadOnly && isEditing && status !== 'ratified';
|
||||
@@ -223,22 +348,72 @@ export function BudgetPlanningPage() {
|
||||
</Group>
|
||||
<Group>
|
||||
<Select
|
||||
data={yearOptions}
|
||||
data={allYearOptions}
|
||||
value={selectedYear}
|
||||
onChange={setSelectedYear}
|
||||
w={180}
|
||||
placeholder="Select year"
|
||||
/>
|
||||
<Button
|
||||
variant="outline"
|
||||
leftSection={<IconDownload size={16} />}
|
||||
onClick={handleDownloadTemplate}
|
||||
size="sm"
|
||||
>
|
||||
Download Template
|
||||
</Button>
|
||||
</Group>
|
||||
</Group>
|
||||
|
||||
{/* Hidden file input for CSV import */}
|
||||
<input
|
||||
type="file"
|
||||
ref={fileInputRef}
|
||||
style={{ display: 'none' }}
|
||||
accept=".csv,.txt"
|
||||
onChange={handleFileChange}
|
||||
/>
|
||||
|
||||
{isLoading && <Center h={300}><Loader /></Center>}
|
||||
|
||||
{/* Empty state - no plan for selected year */}
|
||||
{!isLoading && !hasPlan && selectedYear && (
|
||||
{/* Empty state - no base budget exists at all */}
|
||||
{!isLoading && !hasPlan && selectedYear && !hasBaseBudget && (
|
||||
<Alert icon={<IconInfoCircle size={16} />} color="orange" variant="light">
|
||||
<Stack gap="sm">
|
||||
<Text fw={600}>No budget data found in the system</Text>
|
||||
<Text size="sm">
|
||||
To get started with budget planning, you need to load an initial budget.
|
||||
You can either create a new budget from scratch or import an existing budget from a CSV file.
|
||||
</Text>
|
||||
<Text size="sm" c="dimmed">
|
||||
Use <Text span fw={600}>Download Template</Text> above to get a CSV with your chart of accounts pre-populated,
|
||||
fill in the monthly amounts, then import it below.
|
||||
</Text>
|
||||
<Group>
|
||||
<Button
|
||||
leftSection={<IconUpload size={16} />}
|
||||
onClick={handleImportCSV}
|
||||
loading={importMutation.isPending}
|
||||
>
|
||||
Import Budget from CSV
|
||||
</Button>
|
||||
<Button
|
||||
variant="light"
|
||||
onClick={() => createMutation.mutate()}
|
||||
loading={createMutation.isPending}
|
||||
>
|
||||
Create Empty Budget Plan
|
||||
</Button>
|
||||
</Group>
|
||||
</Stack>
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
{/* Empty state - base budget exists but no plan for this year */}
|
||||
{!isLoading && !hasPlan && selectedYear && hasBaseBudget && (
|
||||
<Alert icon={<IconInfoCircle size={16} />} color="blue" variant="light">
|
||||
<Stack gap="sm">
|
||||
<Text>No budget plan exists for {selectedYear}. Create one based on the current active budget with an inflation adjustment.</Text>
|
||||
<Text>No budget plan exists for {selectedYear}. Create one based on the {availableYears?.latestBudgetYear} budget with an inflation adjustment, or import a CSV directly.</Text>
|
||||
<Group>
|
||||
<NumberInput
|
||||
label="Inflation Rate (%)"
|
||||
@@ -258,9 +433,19 @@ export function BudgetPlanningPage() {
|
||||
>
|
||||
Create Budget Plan for {selectedYear}
|
||||
</Button>
|
||||
<Text mt={24} c="dimmed">or</Text>
|
||||
<Button
|
||||
mt={24}
|
||||
variant="outline"
|
||||
leftSection={<IconUpload size={16} />}
|
||||
onClick={handleImportCSV}
|
||||
loading={importMutation.isPending}
|
||||
>
|
||||
Import from CSV
|
||||
</Button>
|
||||
</Group>
|
||||
<Text size="xs" c="dimmed">
|
||||
Base year: {availableYears?.latestBudgetYear || 'N/A'}. Each monthly amount will be inflated by the specified percentage.
|
||||
Base year: {availableYears?.latestBudgetYear}. Each monthly amount will be compounded annually by the specified inflation rate.
|
||||
</Text>
|
||||
</Stack>
|
||||
</Alert>
|
||||
@@ -292,7 +477,7 @@ export function BudgetPlanningPage() {
|
||||
setConfirmModal({
|
||||
action: 'inflation',
|
||||
title: 'Apply Inflation Rate',
|
||||
message: `This will recalculate all non-manually-adjusted lines using ${inflationInput}% inflation from the base year (${plan.base_year}). Manually adjusted lines will be preserved.`,
|
||||
message: `This will recalculate all non-manually-adjusted lines using ${inflationInput}% inflation compounded annually from the base year (${plan.base_year}). Manually adjusted lines will be preserved.`,
|
||||
});
|
||||
}}
|
||||
disabled={status === 'ratified' || isReadOnly}
|
||||
@@ -305,6 +490,19 @@ export function BudgetPlanningPage() {
|
||||
<Group>
|
||||
{!isReadOnly && (
|
||||
<>
|
||||
{/* Import CSV into existing plan */}
|
||||
{status !== 'ratified' && (
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
leftSection={<IconUpload size={16} />}
|
||||
onClick={handleImportCSV}
|
||||
loading={importMutation.isPending}
|
||||
>
|
||||
Import CSV
|
||||
</Button>
|
||||
)}
|
||||
|
||||
{/* Status actions */}
|
||||
{status === 'planning' && (
|
||||
<>
|
||||
|
||||
Reference in New Issue
Block a user