Fix bugs: monthly actuals month filter, unit assessments, project funding logic, UI cleanup

- Fix monthly actuals showing same data for all months (SQL JOIN excluded
  month filter from SUM — added je.id IS NOT NULL guard)
- Fix units displaying $0 assessment by reading from assessment group
  instead of stale unit field; add special assessment column
- Replace proportional project funding with priority-based sequential
  allocation — near-term items get fully funded first; add is_funding_locked
  flag so users can manually lock a project's fund balance
- Remove post-creation opening balance UI (keep only initial balance on
  account creation); remove redundant Fund filter dropdown from Accounts

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
2026-02-25 14:05:07 -05:00
parent 45a267d787
commit e0c956859b
7 changed files with 148 additions and 353 deletions

View File

@@ -37,7 +37,6 @@ import {
IconStarFilled,
IconAdjustments,
IconInfoCircle,
IconCurrencyDollar,
} from '@tabler/icons-react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import api from '../../services/api';
@@ -125,7 +124,6 @@ export function AccountsPage() {
const [adjustingAccount, setAdjustingAccount] = useState<Account | null>(null);
const [search, setSearch] = useState('');
const [filterType, setFilterType] = useState<string | null>(null);
const [filterFund, setFilterFund] = useState<string | null>(null);
const [showArchived, setShowArchived] = useState(false);
const queryClient = useQueryClient();
@@ -283,63 +281,6 @@ export function AccountsPage() {
},
});
// ── Opening balance state + mutations ──
const [obOpened, { open: openOB, close: closeOB }] = useDisclosure(false);
const [bulkOBOpened, { open: openBulkOB, close: closeBulkOB }] = useDisclosure(false);
const [obAccount, setOBAccount] = useState<Account | null>(null);
const [bulkOBDate, setBulkOBDate] = useState<Date | null>(new Date());
const [bulkOBEntries, setBulkOBEntries] = useState<Record<string, number>>({});
const obForm = useForm({
initialValues: {
targetBalance: 0,
asOfDate: new Date() as Date | null,
memo: '',
},
validate: {
targetBalance: (v) => (v !== undefined && v !== null ? null : 'Required'),
asOfDate: (v) => (v ? null : 'Required'),
},
});
const openingBalanceMutation = useMutation({
mutationFn: (values: { accountId: string; targetBalance: number; asOfDate: string; memo: string }) =>
api.post(`/accounts/${values.accountId}/opening-balance`, {
targetBalance: values.targetBalance,
asOfDate: values.asOfDate,
memo: values.memo,
}),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['accounts'] });
queryClient.invalidateQueries({ queryKey: ['trial-balance'] });
notifications.show({ message: 'Opening balance set successfully', color: 'green' });
closeOB();
setOBAccount(null);
obForm.reset();
},
onError: (err: any) => {
notifications.show({ message: err.response?.data?.message || 'Error setting opening balance', color: 'red' });
},
});
const bulkOBMutation = useMutation({
mutationFn: (dto: { asOfDate: string; entries: { accountId: string; targetBalance: number }[] }) =>
api.post('/accounts/bulk-opening-balances', dto),
onSuccess: (res: any) => {
queryClient.invalidateQueries({ queryKey: ['accounts'] });
queryClient.invalidateQueries({ queryKey: ['trial-balance'] });
const d = res.data;
let msg = `Opening balances: ${d.processed} updated, ${d.skipped} unchanged`;
if (d.errors?.length) msg += `. ${d.errors.length} error(s)`;
notifications.show({ message: msg, color: d.errors?.length ? 'yellow' : 'green', autoClose: 10000 });
closeBulkOB();
setBulkOBEntries({});
},
onError: (err: any) => {
notifications.show({ message: err.response?.data?.message || 'Error setting opening balances', color: 'red' });
},
});
// ── Investment edit form ──
const invForm = useForm({
initialValues: {
@@ -449,51 +390,6 @@ export function AccountsPage() {
});
};
// ── Opening balance handlers ──
const handleSetOpeningBalance = (account: Account) => {
setOBAccount(account);
const tbEntry = trialBalance.find((tb) => tb.id === account.id);
obForm.setValues({
targetBalance: parseFloat(tbEntry?.balance || account.balance || '0'),
asOfDate: new Date(),
memo: '',
});
openOB();
};
const handleOBSubmit = (values: { targetBalance: number; asOfDate: Date | null; memo: string }) => {
if (!obAccount || !values.asOfDate) return;
openingBalanceMutation.mutate({
accountId: obAccount.id,
targetBalance: values.targetBalance,
asOfDate: values.asOfDate.toISOString().split('T')[0],
memo: values.memo,
});
};
const handleOpenBulkOB = () => {
const entries: Record<string, number> = {};
for (const a of accounts.filter((acc) => ['asset', 'liability'].includes(acc.account_type) && acc.is_active && !acc.is_system)) {
const tb = trialBalance.find((t) => t.id === a.id);
entries[a.id] = parseFloat(tb?.balance || a.balance || '0');
}
setBulkOBEntries(entries);
setBulkOBDate(new Date());
openBulkOB();
};
const handleBulkOBSubmit = () => {
if (!bulkOBDate) return;
const entries = Object.entries(bulkOBEntries).map(([accountId, targetBalance]) => ({
accountId,
targetBalance,
}));
bulkOBMutation.mutate({
asOfDate: bulkOBDate.toISOString().split('T')[0],
entries,
});
};
// ── Filtering ──
// Only show asset and liability accounts — these represent real cash positions.
// Income, expense, and equity accounts are internal bookkeeping managed via
@@ -504,7 +400,6 @@ export function AccountsPage() {
if (!VISIBLE_ACCOUNT_TYPES.includes(a.account_type)) return false;
if (search && !a.name.toLowerCase().includes(search.toLowerCase()) && !String(a.account_number).includes(search)) return false;
if (filterType && a.account_type !== filterType) return false;
if (filterFund && a.fund_type !== filterFund) return false;
return true;
});
@@ -548,12 +443,6 @@ export function AccountsPage() {
return sum + (bal * (rate / 100) / 12);
}, 0);
// ── Opening balance modal: current balance ──
const obCurrentBalance = obAccount
? parseFloat(trialBalance.find((tb) => tb.id === obAccount.id)?.balance || obAccount.balance || '0')
: 0;
const obAdjustmentAmount = (obForm.values.targetBalance || 0) - obCurrentBalance;
// ── Adjust modal: current balance from trial balance ──
const adjustCurrentBalance = adjustingAccount
? parseFloat(
@@ -583,9 +472,6 @@ export function AccountsPage() {
onChange={(e) => setShowArchived(e.currentTarget.checked)}
size="sm"
/>
<Button variant="light" leftSection={<IconCurrencyDollar size={16} />} onClick={handleOpenBulkOB}>
Set Opening Balances
</Button>
<Button leftSection={<IconPlus size={16} />} onClick={handleNew}>
Add Account
</Button>
@@ -640,14 +526,6 @@ export function AccountsPage() {
onChange={setFilterType}
w={150}
/>
<Select
placeholder="Fund"
clearable
data={['operating', 'reserve']}
value={filterFund}
onChange={setFilterFund}
w={150}
/>
</Group>
<Tabs defaultValue="all">
@@ -674,7 +552,7 @@ export function AccountsPage() {
onArchive={archiveMutation.mutate}
onSetPrimary={(id) => setPrimaryMutation.mutate(id)}
onAdjustBalance={handleAdjustBalance}
onSetOpeningBalance={handleSetOpeningBalance}
/>
{investments.filter(i => i.is_active).length > 0 && (
<>
@@ -692,7 +570,7 @@ export function AccountsPage() {
onArchive={archiveMutation.mutate}
onSetPrimary={(id) => setPrimaryMutation.mutate(id)}
onAdjustBalance={handleAdjustBalance}
onSetOpeningBalance={handleSetOpeningBalance}
/>
{operatingInvestments.length > 0 && (
<>
@@ -710,7 +588,7 @@ export function AccountsPage() {
onArchive={archiveMutation.mutate}
onSetPrimary={(id) => setPrimaryMutation.mutate(id)}
onAdjustBalance={handleAdjustBalance}
onSetOpeningBalance={handleSetOpeningBalance}
/>
{reserveInvestments.length > 0 && (
<>
@@ -728,7 +606,7 @@ export function AccountsPage() {
onArchive={archiveMutation.mutate}
onSetPrimary={(id) => setPrimaryMutation.mutate(id)}
onAdjustBalance={handleAdjustBalance}
onSetOpeningBalance={handleSetOpeningBalance}
isArchivedView
/>
</Tabs.Panel>
@@ -946,126 +824,6 @@ export function AccountsPage() {
)}
</Modal>
{/* Opening Balance Modal */}
<Modal opened={obOpened} onClose={closeOB} title="Set Opening Balance" size="md" closeOnClickOutside={false}>
{obAccount && (
<form onSubmit={obForm.onSubmit(handleOBSubmit)}>
<Stack>
<Text size="sm" c="dimmed">
Account: <strong>{obAccount.account_number} - {obAccount.name}</strong>
</Text>
<TextInput
label="Current Balance"
value={fmt(obCurrentBalance)}
readOnly
variant="filled"
/>
<NumberInput
label="Target Opening Balance"
description="The balance this account should have as of the selected date"
required
prefix="$"
decimalScale={2}
thousandSeparator=","
allowNegative
{...obForm.getInputProps('targetBalance')}
/>
<DateInput
label="As-of Date"
description="The date the balance should be effective"
required
clearable
{...obForm.getInputProps('asOfDate')}
/>
<TextInput
label="Memo"
placeholder="Optional memo"
{...obForm.getInputProps('memo')}
/>
<Alert icon={<IconInfoCircle size={16} />} color={obAdjustmentAmount >= 0 ? 'blue' : 'orange'} variant="light">
<Text size="sm">
Adjustment: <strong>{fmt(obAdjustmentAmount)}</strong>
{obAdjustmentAmount > 0 && ' (increase)'}
{obAdjustmentAmount < 0 && ' (decrease)'}
{obAdjustmentAmount === 0 && ' (no change)'}
</Text>
</Alert>
<Button type="submit" loading={openingBalanceMutation.isPending}>
Set Opening Balance
</Button>
</Stack>
</form>
)}
</Modal>
{/* Bulk Opening Balance Modal */}
<Modal opened={bulkOBOpened} onClose={closeBulkOB} title="Set Opening Balances" size="xl" closeOnClickOutside={false}>
<Stack>
<DateInput
label="As-of Date"
description="All opening balances will be effective as of this date"
required
value={bulkOBDate}
onChange={setBulkOBDate}
/>
<Table striped highlightOnHover>
<Table.Thead>
<Table.Tr>
<Table.Th>Acct #</Table.Th>
<Table.Th>Name</Table.Th>
<Table.Th>Type</Table.Th>
<Table.Th>Fund</Table.Th>
<Table.Th ta="right">Current Balance</Table.Th>
<Table.Th ta="right">Target Balance</Table.Th>
</Table.Tr>
</Table.Thead>
<Table.Tbody>
{accounts
.filter((a) => ['asset', 'liability'].includes(a.account_type) && a.is_active && !a.is_system)
.map((a) => {
const currentBal = parseFloat(trialBalance.find((t) => t.id === a.id)?.balance || a.balance || '0');
return (
<Table.Tr key={a.id}>
<Table.Td>{a.account_number}</Table.Td>
<Table.Td>{a.name}</Table.Td>
<Table.Td>
<Badge color={accountTypeColors[a.account_type]} variant="light" size="sm">{a.account_type}</Badge>
</Table.Td>
<Table.Td>
<Badge color={a.fund_type === 'reserve' ? 'violet' : 'gray'} variant="light" size="sm">{a.fund_type}</Badge>
</Table.Td>
<Table.Td ta="right" ff="monospace">{fmt(currentBal)}</Table.Td>
<Table.Td>
<NumberInput
size="xs"
prefix="$"
decimalScale={2}
thousandSeparator=","
allowNegative
value={bulkOBEntries[a.id] ?? currentBal}
onChange={(v) => setBulkOBEntries((prev) => ({ ...prev, [a.id]: Number(v) || 0 }))}
styles={{ input: { textAlign: 'right', fontFamily: 'monospace' } }}
/>
</Table.Td>
</Table.Tr>
);
})}
</Table.Tbody>
</Table>
<Button onClick={handleBulkOBSubmit} loading={bulkOBMutation.isPending}>
Apply Opening Balances
</Button>
</Stack>
</Modal>
{/* Investment Edit Modal */}
<Modal opened={invEditOpened} onClose={closeInvEdit} title="Edit Investment Account" size="md" closeOnClickOutside={false}>
{editingInvestment && (
@@ -1150,7 +908,6 @@ function AccountTable({
onArchive,
onSetPrimary,
onAdjustBalance,
onSetOpeningBalance,
isArchivedView = false,
}: {
accounts: Account[];
@@ -1158,7 +915,6 @@ function AccountTable({
onArchive: (a: Account) => void;
onSetPrimary: (id: string) => void;
onAdjustBalance: (a: Account) => void;
onSetOpeningBalance: (a: Account) => void;
isArchivedView?: boolean;
}) {
const hasRates = accounts.some((a) => a.interest_rate && parseFloat(a.interest_rate) > 0);
@@ -1259,13 +1015,6 @@ function AccountTable({
</ActionIcon>
</Tooltip>
)}
{!a.is_system && (
<Tooltip label="Set Opening Balance">
<ActionIcon variant="subtle" color="teal" onClick={() => onSetOpeningBalance(a)}>
<IconCurrencyDollar size={16} />
</ActionIcon>
</Tooltip>
)}
{!a.is_system && (
<Tooltip label="Adjust Balance">
<ActionIcon variant="subtle" color="blue" onClick={() => onAdjustBalance(a)}>

View File

@@ -2,13 +2,13 @@ import { useState, useRef } from 'react';
import {
Title, Table, Group, Button, Stack, Text, Modal, TextInput,
NumberInput, Select, Textarea, Badge, ActionIcon, Loader, Center,
Card, SimpleGrid, Progress,
Card, SimpleGrid, Progress, Switch, Tooltip,
} from '@mantine/core';
import { DateInput } from '@mantine/dates';
import { useForm } from '@mantine/form';
import { useDisclosure } from '@mantine/hooks';
import { notifications } from '@mantine/notifications';
import { IconPlus, IconEdit, IconUpload, IconDownload } from '@tabler/icons-react';
import { IconPlus, IconEdit, IconUpload, IconDownload, IconLock, IconLockOpen } from '@tabler/icons-react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import api from '../../services/api';
import { parseCSV, downloadBlob } from '../../utils/csv';
@@ -41,6 +41,7 @@ interface Project {
account_id: string;
notes: string;
is_active: boolean;
is_funding_locked: boolean;
}
const FUTURE_YEAR = 9999;
@@ -151,6 +152,7 @@ export function ProjectsPage() {
target_year: currentYear,
target_month: 6,
notes: '',
is_funding_locked: false,
},
validate: {
name: (v) => (v.length > 0 ? null : 'Required'),
@@ -258,6 +260,7 @@ export function ProjectsPage() {
target_year: p.target_year || currentYear,
target_month: p.target_month || 6,
notes: p.notes || '',
is_funding_locked: p.is_funding_locked || false,
});
open();
};
@@ -300,9 +303,16 @@ export function ProjectsPage() {
const pct = cost > 0 ? (funded / cost) * 100 : 0;
const color = pct >= 70 ? 'green' : pct >= 40 ? 'yellow' : 'red';
return (
<Text span c={color} ff="monospace">
{pct.toFixed(0)}%
</Text>
<Group gap={4} justify="flex-end">
{project.is_funding_locked && (
<Tooltip label="Funding manually locked">
<IconLock size={14} style={{ color: 'var(--mantine-color-blue-5)' }} />
</Tooltip>
)}
<Text span c={color} ff="monospace">
{pct.toFixed(0)}%
</Text>
</Group>
);
};
@@ -540,12 +550,18 @@ export function ProjectsPage() {
{/* Row 5: Conditional reserve fields */}
{form.values.fund_source === 'reserve' && (
<>
<Switch
label="Lock Funding"
description="When locked, the fund balance and percentage you set here will be used as-is instead of being auto-calculated from the reserve balance"
{...form.getInputProps('is_funding_locked', { type: 'checkbox' })}
/>
<Group grow>
<NumberInput
label="Current Fund Balance"
prefix="$"
decimalScale={2}
min={0}
disabled={!form.values.is_funding_locked}
{...form.getInputProps('current_fund_balance')}
/>
<NumberInput
@@ -561,6 +577,7 @@ export function ProjectsPage() {
decimalScale={1}
min={0}
max={100}
disabled={!form.values.is_funding_locked}
{...form.getInputProps('funded_percentage')}
/>
</Group>

View File

@@ -23,6 +23,7 @@ interface Unit {
assessment_group_id?: string;
assessment_group_name?: string;
group_regular_assessment?: string;
group_special_assessment?: string;
group_frequency?: string;
}
@@ -193,6 +194,7 @@ export function UnitsPage() {
<Table.Th>Email</Table.Th>
<Table.Th>Group</Table.Th>
<Table.Th ta="right">Assessment</Table.Th>
<Table.Th ta="right">Special Assessment</Table.Th>
<Table.Th>Status</Table.Th>
<Table.Th></Table.Th>
</Table.Tr>
@@ -211,7 +213,15 @@ export function UnitsPage() {
<Text size="xs" c="dimmed">-</Text>
)}
</Table.Td>
<Table.Td ta="right" ff="monospace">${parseFloat(u.monthly_assessment || '0').toFixed(2)}</Table.Td>
<Table.Td ta="right" ff="monospace">
${parseFloat(u.group_regular_assessment || u.monthly_assessment || '0').toFixed(2)}
</Table.Td>
<Table.Td ta="right" ff="monospace">
{parseFloat(u.group_special_assessment || '0') > 0
? `$${parseFloat(u.group_special_assessment || '0').toFixed(2)}`
: <Text size="sm" c="dimmed">-</Text>
}
</Table.Td>
<Table.Td><Badge color={u.status === 'active' ? 'green' : 'gray'} size="sm">{u.status}</Badge></Table.Td>
<Table.Td>
<Group gap={4}>
@@ -227,7 +237,7 @@ export function UnitsPage() {
</Table.Td>
</Table.Tr>
))}
{filtered.length === 0 && <Table.Tr><Table.Td colSpan={8}><Text ta="center" c="dimmed" py="lg">No units yet</Text></Table.Td></Table.Tr>}
{filtered.length === 0 && <Table.Tr><Table.Td colSpan={9}><Text ta="center" c="dimmed" py="lg">No units yet</Text></Table.Td></Table.Tr>}
</Table.Tbody>
</Table>