- Unify reserve_components + capital_projects into single projects model with full CRUD backend and new Projects page frontend - Rewrite Capital Planning to read from unified projects/planning endpoint; add empty state directing users to Projects page when no planning items exist - Add default designation to assessment groups with auto-set on first creation; units now require an assessment group (pre-populated with default) - Add primary account designation (one per fund type) and balance adjustment via journal entries against equity offset accounts (3000/3100) - Add computed investment fields (interest earned, maturity value, days remaining) with PostgreSQL date arithmetic fix for DATE - DATE integer result - Restructure sidebar: investments in Accounts tab, Year-End under Reports, Planning section with Projects and Capital Planning - Fix new tenant creation seeding unwanted default chart of accounts — new tenants now start with a blank slate Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
255 lines
10 KiB
TypeScript
255 lines
10 KiB
TypeScript
import { useState } from 'react';
|
|
import {
|
|
Title, Table, Group, Button, Stack, TextInput, Modal,
|
|
NumberInput, Select, Badge, ActionIcon, Text, Loader, Center, Tooltip, Alert,
|
|
} from '@mantine/core';
|
|
import { useForm } from '@mantine/form';
|
|
import { useDisclosure } from '@mantine/hooks';
|
|
import { notifications } from '@mantine/notifications';
|
|
import { IconPlus, IconEdit, IconSearch, IconTrash, IconInfoCircle } from '@tabler/icons-react';
|
|
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
|
|
import api from '../../services/api';
|
|
|
|
interface Unit {
|
|
id: string;
|
|
unit_number: string;
|
|
address_line1: string;
|
|
owner_name: string;
|
|
owner_email: string;
|
|
monthly_assessment: string;
|
|
status: string;
|
|
balance_due?: string;
|
|
assessment_group_id?: string;
|
|
assessment_group_name?: string;
|
|
group_regular_assessment?: string;
|
|
group_frequency?: string;
|
|
}
|
|
|
|
interface AssessmentGroup {
|
|
id: string;
|
|
name: string;
|
|
regular_assessment: string;
|
|
frequency: string;
|
|
is_default: boolean;
|
|
}
|
|
|
|
export function UnitsPage() {
|
|
const [opened, { open, close }] = useDisclosure(false);
|
|
const [editing, setEditing] = useState<Unit | null>(null);
|
|
const [search, setSearch] = useState('');
|
|
const [deleteConfirm, setDeleteConfirm] = useState<Unit | null>(null);
|
|
const queryClient = useQueryClient();
|
|
|
|
const { data: units = [], isLoading } = useQuery<Unit[]>({
|
|
queryKey: ['units'],
|
|
queryFn: async () => { const { data } = await api.get('/units'); return data; },
|
|
});
|
|
|
|
const { data: assessmentGroups = [] } = useQuery<AssessmentGroup[]>({
|
|
queryKey: ['assessment-groups'],
|
|
queryFn: async () => { const { data } = await api.get('/assessment-groups'); return data; },
|
|
});
|
|
|
|
const defaultGroup = assessmentGroups.find(g => g.is_default);
|
|
const hasGroups = assessmentGroups.length > 0;
|
|
|
|
const form = useForm({
|
|
initialValues: {
|
|
unit_number: '', address_line1: '', city: '', state: '', zip_code: '',
|
|
owner_name: '', owner_email: '', owner_phone: '', monthly_assessment: 0,
|
|
assessment_group_id: '' as string | null,
|
|
},
|
|
validate: {
|
|
unit_number: (v) => (v.length > 0 ? null : 'Required'),
|
|
assessment_group_id: (v) => (v && v.length > 0 ? null : 'Assessment group is required'),
|
|
},
|
|
});
|
|
|
|
const saveMutation = useMutation({
|
|
mutationFn: (values: any) => {
|
|
const payload = { ...values, assessment_group_id: values.assessment_group_id || null };
|
|
return editing ? api.put(`/units/${editing.id}`, payload) : api.post('/units', payload);
|
|
},
|
|
onSuccess: () => {
|
|
queryClient.invalidateQueries({ queryKey: ['units'] });
|
|
notifications.show({ message: editing ? 'Unit updated' : 'Unit created', color: 'green' });
|
|
close(); setEditing(null); form.reset();
|
|
},
|
|
onError: (err: any) => { notifications.show({ message: err.response?.data?.message || 'Error', color: 'red' }); },
|
|
});
|
|
|
|
const deleteMutation = useMutation({
|
|
mutationFn: (id: string) => api.delete(`/units/${id}`),
|
|
onSuccess: () => {
|
|
queryClient.invalidateQueries({ queryKey: ['units'] });
|
|
notifications.show({ message: 'Unit deleted', color: 'green' });
|
|
setDeleteConfirm(null);
|
|
},
|
|
onError: (err: any) => {
|
|
notifications.show({ message: err.response?.data?.message || 'Cannot delete unit', color: 'red' });
|
|
setDeleteConfirm(null);
|
|
},
|
|
});
|
|
|
|
const handleEdit = (u: Unit) => {
|
|
setEditing(u);
|
|
form.setValues({
|
|
unit_number: u.unit_number, address_line1: u.address_line1 || '',
|
|
city: '', state: '', zip_code: '', owner_name: u.owner_name || '',
|
|
owner_email: u.owner_email || '', owner_phone: '', monthly_assessment: parseFloat(u.monthly_assessment || '0'),
|
|
assessment_group_id: u.assessment_group_id || '',
|
|
});
|
|
open();
|
|
};
|
|
|
|
const handleNew = () => {
|
|
setEditing(null);
|
|
form.reset();
|
|
// Pre-populate with default group
|
|
if (defaultGroup) {
|
|
form.setFieldValue('assessment_group_id', defaultGroup.id);
|
|
form.setFieldValue('monthly_assessment', parseFloat(defaultGroup.regular_assessment || '0'));
|
|
}
|
|
open();
|
|
};
|
|
|
|
const handleGroupChange = (groupId: string | null) => {
|
|
form.setFieldValue('assessment_group_id', groupId);
|
|
if (groupId) {
|
|
const group = assessmentGroups.find(g => g.id === groupId);
|
|
if (group) {
|
|
form.setFieldValue('monthly_assessment', parseFloat(group.regular_assessment || '0'));
|
|
}
|
|
}
|
|
};
|
|
|
|
const filtered = units.filter((u) =>
|
|
!search || u.unit_number.toLowerCase().includes(search.toLowerCase()) ||
|
|
(u.owner_name || '').toLowerCase().includes(search.toLowerCase())
|
|
);
|
|
|
|
if (isLoading) return <Center h={300}><Loader /></Center>;
|
|
|
|
return (
|
|
<Stack>
|
|
<Group justify="space-between">
|
|
<Title order={2}>Units / Homeowners</Title>
|
|
{hasGroups ? (
|
|
<Button leftSection={<IconPlus size={16} />} onClick={handleNew}>Add Unit</Button>
|
|
) : (
|
|
<Tooltip label="Create an assessment group first">
|
|
<Button leftSection={<IconPlus size={16} />} disabled>Add Unit</Button>
|
|
</Tooltip>
|
|
)}
|
|
</Group>
|
|
|
|
{!hasGroups && (
|
|
<Alert icon={<IconInfoCircle size={16} />} color="yellow" variant="light">
|
|
You must create at least one assessment group before adding units. Go to Assessment Groups to create one.
|
|
</Alert>
|
|
)}
|
|
|
|
<TextInput placeholder="Search units..." leftSection={<IconSearch size={16} />} value={search} onChange={(e) => setSearch(e.currentTarget.value)} />
|
|
<Table striped highlightOnHover>
|
|
<Table.Thead>
|
|
<Table.Tr>
|
|
<Table.Th>Unit #</Table.Th>
|
|
<Table.Th>Address</Table.Th>
|
|
<Table.Th>Owner</Table.Th>
|
|
<Table.Th>Email</Table.Th>
|
|
<Table.Th>Group</Table.Th>
|
|
<Table.Th ta="right">Assessment</Table.Th>
|
|
<Table.Th>Status</Table.Th>
|
|
<Table.Th></Table.Th>
|
|
</Table.Tr>
|
|
</Table.Thead>
|
|
<Table.Tbody>
|
|
{filtered.map((u) => (
|
|
<Table.Tr key={u.id}>
|
|
<Table.Td fw={500}>{u.unit_number}</Table.Td>
|
|
<Table.Td>{u.address_line1}</Table.Td>
|
|
<Table.Td>{u.owner_name}</Table.Td>
|
|
<Table.Td>{u.owner_email}</Table.Td>
|
|
<Table.Td>
|
|
{u.assessment_group_name ? (
|
|
<Badge variant="light" size="sm">{u.assessment_group_name}</Badge>
|
|
) : (
|
|
<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><Badge color={u.status === 'active' ? 'green' : 'gray'} size="sm">{u.status}</Badge></Table.Td>
|
|
<Table.Td>
|
|
<Group gap={4}>
|
|
<ActionIcon variant="subtle" onClick={() => handleEdit(u)}>
|
|
<IconEdit size={16} />
|
|
</ActionIcon>
|
|
<Tooltip label="Delete unit">
|
|
<ActionIcon variant="subtle" color="red" onClick={() => setDeleteConfirm(u)}>
|
|
<IconTrash size={16} />
|
|
</ActionIcon>
|
|
</Tooltip>
|
|
</Group>
|
|
</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>}
|
|
</Table.Tbody>
|
|
</Table>
|
|
|
|
{/* Create/Edit Modal */}
|
|
<Modal opened={opened} onClose={close} title={editing ? 'Edit Unit' : 'New Unit'} size="md">
|
|
<form onSubmit={form.onSubmit((v) => saveMutation.mutate(v))}>
|
|
<Stack>
|
|
<TextInput label="Unit Number" required {...form.getInputProps('unit_number')} />
|
|
<TextInput label="Address" {...form.getInputProps('address_line1')} />
|
|
<Group grow>
|
|
<TextInput label="City" {...form.getInputProps('city')} />
|
|
<TextInput label="State" {...form.getInputProps('state')} />
|
|
<TextInput label="ZIP" {...form.getInputProps('zip_code')} />
|
|
</Group>
|
|
<TextInput label="Owner Name" {...form.getInputProps('owner_name')} />
|
|
<TextInput label="Owner Email" {...form.getInputProps('owner_email')} />
|
|
<TextInput label="Owner Phone" {...form.getInputProps('owner_phone')} />
|
|
<Select
|
|
label="Assessment Group"
|
|
description="Required — all units must belong to an assessment group"
|
|
required
|
|
data={assessmentGroups.map(g => ({
|
|
value: g.id,
|
|
label: `${g.name}${g.is_default ? ' (Default)' : ''} — $${parseFloat(g.regular_assessment || '0').toFixed(2)}/${g.frequency || 'mo'}`,
|
|
}))}
|
|
value={form.values.assessment_group_id}
|
|
onChange={handleGroupChange}
|
|
error={form.errors.assessment_group_id}
|
|
/>
|
|
<NumberInput label="Monthly Assessment" prefix="$" decimalScale={2} min={0} {...form.getInputProps('monthly_assessment')} />
|
|
<Button type="submit" loading={saveMutation.isPending}>{editing ? 'Update' : 'Create'}</Button>
|
|
</Stack>
|
|
</form>
|
|
</Modal>
|
|
|
|
{/* Delete Confirmation Modal */}
|
|
<Modal opened={!!deleteConfirm} onClose={() => setDeleteConfirm(null)} title="Delete Unit" size="sm">
|
|
<Stack>
|
|
<Text>
|
|
Are you sure you want to delete unit <strong>{deleteConfirm?.unit_number}</strong>
|
|
{deleteConfirm?.owner_name ? ` (${deleteConfirm.owner_name})` : ''}?
|
|
</Text>
|
|
<Text size="sm" c="dimmed">This action cannot be undone.</Text>
|
|
<Group justify="flex-end">
|
|
<Button variant="default" onClick={() => setDeleteConfirm(null)}>Cancel</Button>
|
|
<Button
|
|
color="red"
|
|
loading={deleteMutation.isPending}
|
|
onClick={() => deleteConfirm && deleteMutation.mutate(deleteConfirm.id)}
|
|
>
|
|
Delete
|
|
</Button>
|
|
</Group>
|
|
</Stack>
|
|
</Modal>
|
|
</Stack>
|
|
);
|
|
}
|