feat(platform): residential module + admin UI + reliability fixes
All checks were successful
Build & Push Docker Images / lint (pull_request) Successful in 1m2s
Build & Push Docker Images / build-and-push (pull_request) Has been skipped

Residential platform
- New schema: residentialClients, residentialInterests (separate from
  marina/yacht clients) with migration 0010
- Service layer with CRUD + audit + sockets + per-port portal toggle
- v1 + public API routes (/api/v1/residential/*, /api/public/residential-inquiries)
- List + detail pages with inline editing for clients and interests
- Per-user residentialAccess toggle on userPortRoles (migration 0011)
- Permission keys: residential_clients, residential_interests
- Sidebar nav + role form integration
- Smoke spec covering page loads, UI create flow, public endpoint

Admin & shared UI
- Admin → Forms (form templates CRUD) with validators + service
- Notification preferences page (in-app + email per type)
- Email composition + accounts list + threads view
- Branded auth shell shared across CRM + portal auth surfaces
- Inline editing extended to yacht/company/interest detail pages
- InlineTagEditor + per-entity tags endpoints (yachts, companies)
- Notes service polymorphic across clients/interests/yachts/companies
- Client list columns: yachtCount + companyCount badges
- Reservation file-download via presigned URL (replaces stale <a href>)

Route handler refactor
- Extracted yachts/companies/berths reservation handlers to sibling
  handlers.ts files (Next.js 15 route.ts only allows specific exports)

Reliability fixes
- apiFetch double-stringify bug fixed across 13 components
  (apiFetch already JSON.stringifies its body; passing a stringified
  body produced double-encoded JSON which failed zod validation)
- SocketProvider gated behind useSyncExternalStore-based mount check
  to avoid useSession() SSR crashes under React 19 + Next 15
- apiFetch falls back to URL-pathname → port-id resolution when the
  Zustand store hasn't hydrated yet (fresh contexts, e2e tests)
- CRM invite flow (schema, service, route, email, dev script)
- Dashboard route → [portSlug]/dashboard/page.tsx + redirect
- Document the dev-server restart-after-migration gotcha in CLAUDE.md

Tests
- 5-case residential smoke spec
- Integration test updates for new service signatures

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
Matt Ciaccio
2026-04-27 21:54:32 +02:00
parent fac8021156
commit e8d61c91c4
121 changed files with 34105 additions and 1016 deletions

View File

@@ -0,0 +1,243 @@
'use client';
import { useEffect, useState } from 'react';
import { useMutation } from '@tanstack/react-query';
import { Plus, Trash2 } from 'lucide-react';
import { toast } from 'sonner';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Switch } from '@/components/ui/switch';
import { Textarea } from '@/components/ui/textarea';
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/components/ui/select';
import { Sheet, SheetContent, SheetFooter, SheetHeader, SheetTitle } from '@/components/ui/sheet';
import { apiFetch } from '@/lib/api/client';
import type { FormField } from '@/lib/validators/form-templates';
interface FormTemplate {
id: string;
name: string;
description: string | null;
fields: FormField[];
isActive: boolean;
}
interface Props {
open: boolean;
onOpenChange: (open: boolean) => void;
template: FormTemplate | null;
onSaved: () => void;
}
const DEFAULT_FIELD: FormField = {
key: '',
label: '',
type: 'text',
required: false,
};
const FIELD_TYPES: Array<{ value: FormField['type']; label: string }> = [
{ value: 'text', label: 'Text' },
{ value: 'textarea', label: 'Long text' },
{ value: 'email', label: 'Email' },
{ value: 'phone', label: 'Phone' },
{ value: 'number', label: 'Number' },
{ value: 'select', label: 'Select' },
{ value: 'checkbox', label: 'Checkbox' },
];
export function FormTemplateForm({ open, onOpenChange, template, onSaved }: Props) {
const [name, setName] = useState('');
const [description, setDescription] = useState('');
const [isActive, setIsActive] = useState(true);
const [fields, setFields] = useState<FormField[]>([{ ...DEFAULT_FIELD }]);
useEffect(() => {
if (template) {
setName(template.name);
setDescription(template.description ?? '');
setIsActive(template.isActive);
setFields(template.fields.length > 0 ? template.fields : [{ ...DEFAULT_FIELD }]);
} else {
setName('');
setDescription('');
setIsActive(true);
setFields([{ ...DEFAULT_FIELD }]);
}
}, [template, open]);
const saveMutation = useMutation({
mutationFn: () => {
const payload = {
name,
description: description || undefined,
fields,
isActive,
};
if (template) {
return apiFetch(`/api/v1/admin/form-templates/${template.id}`, {
method: 'PATCH',
body: payload,
});
}
return apiFetch('/api/v1/admin/form-templates', {
method: 'POST',
body: payload,
});
},
onSuccess: () => {
toast.success(template ? 'Template saved' : 'Template created');
onSaved();
onOpenChange(false);
},
onError: (err) => toast.error(err instanceof Error ? err.message : 'Save failed'),
});
function updateField(idx: number, patch: Partial<FormField>) {
setFields((prev) => prev.map((f, i) => (i === idx ? { ...f, ...patch } : f)));
}
function addField() {
setFields((prev) => [...prev, { ...DEFAULT_FIELD }]);
}
function removeField(idx: number) {
setFields((prev) => (prev.length === 1 ? prev : prev.filter((_, i) => i !== idx)));
}
return (
<Sheet open={open} onOpenChange={onOpenChange}>
<SheetContent className="overflow-y-auto sm:max-w-2xl">
<SheetHeader>
<SheetTitle>{template ? 'Edit form template' : 'New form template'}</SheetTitle>
</SheetHeader>
<div className="space-y-4 py-4">
<div className="space-y-1">
<Label>Name</Label>
<Input value={name} onChange={(e) => setName(e.target.value)} />
</div>
<div className="space-y-1">
<Label>Description</Label>
<Textarea
rows={2}
value={description}
onChange={(e) => setDescription(e.target.value)}
/>
</div>
<div className="flex items-center gap-2">
<Switch checked={isActive} onCheckedChange={setIsActive} />
<Label>Active</Label>
</div>
<div className="border-t pt-3 space-y-3">
<div className="flex items-center justify-between">
<Label className="text-sm font-medium">Fields</Label>
<Button variant="outline" size="sm" onClick={addField}>
<Plus className="h-3.5 w-3.5 mr-1" />
Add field
</Button>
</div>
{fields.map((f, i) => (
<div key={i} className="rounded-md border p-3 space-y-2">
<div className="flex items-center justify-between">
<span className="text-xs text-muted-foreground">Field {i + 1}</span>
{fields.length > 1 && (
<Button
variant="ghost"
size="icon"
className="text-destructive h-7 w-7"
onClick={() => removeField(i)}
>
<Trash2 className="h-3.5 w-3.5" />
</Button>
)}
</div>
<div className="grid grid-cols-2 gap-2">
<div className="space-y-1">
<Label className="text-xs">Key (no spaces)</Label>
<Input
value={f.key}
onChange={(e) => updateField(i, { key: e.target.value })}
placeholder="email"
/>
</div>
<div className="space-y-1">
<Label className="text-xs">Label</Label>
<Input
value={f.label}
onChange={(e) => updateField(i, { label: e.target.value })}
placeholder="Email address"
/>
</div>
<div className="space-y-1">
<Label className="text-xs">Type</Label>
<Select
value={f.type}
onValueChange={(v) => updateField(i, { type: v as FormField['type'] })}
>
<SelectTrigger>
<SelectValue />
</SelectTrigger>
<SelectContent>
{FIELD_TYPES.map((ft) => (
<SelectItem key={ft.value} value={ft.value}>
{ft.label}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
<div className="space-y-1 flex items-end gap-2 pb-1">
<Switch
checked={!!f.required}
onCheckedChange={(v) => updateField(i, { required: v })}
/>
<Label className="text-xs">Required</Label>
</div>
</div>
{f.type === 'select' && (
<div className="space-y-1">
<Label className="text-xs">Options (comma-separated)</Label>
<Input
value={(f.options ?? []).join(', ')}
onChange={(e) =>
updateField(i, {
options: e.target.value
.split(',')
.map((s) => s.trim())
.filter(Boolean),
})
}
/>
</div>
)}
</div>
))}
</div>
</div>
<SheetFooter>
<Button variant="ghost" onClick={() => onOpenChange(false)}>
Cancel
</Button>
<Button
onClick={() => saveMutation.mutate()}
disabled={
saveMutation.isPending ||
!name.trim() ||
fields.some((f) => !f.key.trim() || !f.label.trim())
}
>
{saveMutation.isPending ? 'Saving…' : 'Save template'}
</Button>
</SheetFooter>
</SheetContent>
</Sheet>
);
}

View File

@@ -0,0 +1,123 @@
'use client';
import { useState } from 'react';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { format } from 'date-fns';
import { Pencil, Plus, Trash2 } from 'lucide-react';
import { toast } from 'sonner';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { ConfirmationDialog } from '@/components/shared/confirmation-dialog';
import { PageHeader } from '@/components/shared/page-header';
import { apiFetch } from '@/lib/api/client';
import type { FormField } from '@/lib/validators/form-templates';
import { FormTemplateForm } from './form-template-form';
export interface FormTemplate {
id: string;
name: string;
description: string | null;
fields: FormField[];
isActive: boolean;
updatedAt: string;
}
export function FormTemplateList() {
const qc = useQueryClient();
const [formOpen, setFormOpen] = useState(false);
const [editing, setEditing] = useState<FormTemplate | null>(null);
const { data: templates = [], isLoading } = useQuery<FormTemplate[]>({
queryKey: ['admin', 'form-templates'],
queryFn: () =>
apiFetch<{ data: FormTemplate[] }>('/api/v1/admin/form-templates').then((r) => r.data),
});
const deleteMutation = useMutation({
mutationFn: (id: string) =>
apiFetch(`/api/v1/admin/form-templates/${id}`, { method: 'DELETE' }),
onSuccess: () => {
toast.success('Template deleted');
qc.invalidateQueries({ queryKey: ['admin', 'form-templates'] });
},
onError: (err) => toast.error(err instanceof Error ? err.message : 'Delete failed'),
});
return (
<div>
<PageHeader
title="Form Templates"
description="Public intake forms for clients (residential inquiries, EOI supplements, etc.)"
actions={
<Button
onClick={() => {
setEditing(null);
setFormOpen(true);
}}
>
<Plus className="h-4 w-4 mr-1.5" />
New template
</Button>
}
/>
{isLoading ? (
<p className="text-sm text-muted-foreground">Loading</p>
) : templates.length === 0 ? (
<div className="rounded-lg border border-dashed p-8 text-center text-muted-foreground">
<p className="text-sm">No form templates yet.</p>
</div>
) : (
<div className="rounded-lg border divide-y">
{templates.map((t) => (
<div key={t.id} className="flex items-center gap-3 p-3">
<div className="flex-1 min-w-0">
<div className="flex items-center gap-2">
<span className="text-sm font-medium">{t.name}</span>
{!t.isActive && (
<Badge variant="outline" className="text-xs">
Inactive
</Badge>
)}
</div>
<div className="text-xs text-muted-foreground">
{t.fields.length} field{t.fields.length === 1 ? '' : 's'} · updated{' '}
{format(new Date(t.updatedAt), 'MMM d, yyyy')}
</div>
</div>
<Button
variant="ghost"
size="icon"
onClick={() => {
setEditing(t);
setFormOpen(true);
}}
>
<Pencil className="h-4 w-4" />
</Button>
<ConfirmationDialog
trigger={
<Button variant="ghost" size="icon" className="text-destructive">
<Trash2 className="h-4 w-4" />
</Button>
}
title="Delete form template"
description={`Delete "${t.name}"? Existing submissions will be preserved.`}
confirmLabel="Delete"
onConfirm={() => deleteMutation.mutate(t.id)}
/>
</div>
))}
</div>
)}
<FormTemplateForm
open={formOpen}
onOpenChange={setFormOpen}
template={editing}
onSaved={() => qc.invalidateQueries({ queryKey: ['admin', 'form-templates'] })}
/>
</div>
);
}

View File

@@ -77,6 +77,14 @@ const DEFAULT_PERMISSIONS: Record<string, Record<string, boolean>> = {
manage_tags: false,
system_backup: false,
},
residential_clients: { view: false, create: false, edit: false, delete: false },
residential_interests: {
view: false,
create: false,
edit: false,
delete: false,
change_stage: false,
},
};
const GROUP_LABELS: Record<string, string> = {

View File

@@ -30,6 +30,14 @@ const KNOWN_SETTINGS: Array<{
type: 'boolean' | 'number' | 'json' | 'string';
defaultValue: unknown;
}> = [
{
key: 'client_portal_enabled',
label: 'Client Portal',
description:
'Allow clients of this port to sign in and manage their account through the client portal.',
type: 'boolean',
defaultValue: true,
},
{
key: 'ai_interest_scoring',
label: 'AI Interest Scoring',
@@ -89,6 +97,14 @@ const KNOWN_SETTINGS: Array<{
type: 'json',
defaultValue: [],
},
{
key: 'residential_notification_recipients',
label: 'Residential Notification Recipients',
description:
'Email addresses (JSON array) that receive sales alerts for new residential inquiries. Falls back to Inquiry Contact Email when empty.',
type: 'json',
defaultValue: [],
},
];
export function SettingsManager() {

View File

@@ -30,6 +30,7 @@ interface UserFormProps {
phone: string | null;
isActive: boolean;
role: { id: string; name: string };
residentialAccess?: boolean;
} | null;
onSuccess: () => void;
}
@@ -43,6 +44,7 @@ export function UserForm({ open, onOpenChange, user, onSuccess }: UserFormProps)
const [phone, setPhone] = useState('');
const [roleId, setRoleId] = useState('');
const [isActive, setIsActive] = useState(true);
const [residentialAccess, setResidentialAccess] = useState(false);
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
@@ -63,6 +65,7 @@ export function UserForm({ open, onOpenChange, user, onSuccess }: UserFormProps)
setPhone(user.phone ?? '');
setRoleId(user.role.id);
setIsActive(user.isActive);
setResidentialAccess(user.residentialAccess ?? false);
setPassword('');
} else {
setName('');
@@ -71,6 +74,7 @@ export function UserForm({ open, onOpenChange, user, onSuccess }: UserFormProps)
setPhone('');
setRoleId('');
setIsActive(true);
setResidentialAccess(false);
setPassword('');
}
setError(null);
@@ -91,6 +95,7 @@ export function UserForm({ open, onOpenChange, user, onSuccess }: UserFormProps)
phone: phone || null,
roleId,
isActive,
residentialAccess,
},
});
} else {
@@ -103,6 +108,7 @@ export function UserForm({ open, onOpenChange, user, onSuccess }: UserFormProps)
displayName,
phone: phone || undefined,
roleId,
residentialAccess,
},
});
}
@@ -190,6 +196,21 @@ export function UserForm({ open, onOpenChange, user, onSuccess }: UserFormProps)
</Select>
</div>
<div className="flex items-center justify-between rounded-lg border p-3">
<div>
<Label htmlFor="user-residential">Residential access</Label>
<p className="text-xs text-muted-foreground">
Grant this user access to residential clients and interests in addition to their
primary role.
</p>
</div>
<Switch
id="user-residential"
checked={residentialAccess}
onCheckedChange={setResidentialAccess}
/>
</div>
{isEdit && (
<div className="flex items-center justify-between rounded-lg border p-3">
<div>