Files
pn-new-crm/src/components/berths/waiting-list-manager.tsx
Matt Ciaccio e8d61c91c4
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
feat(platform): residential module + admin UI + reliability fixes
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>
2026-04-27 21:54:32 +02:00

248 lines
7.2 KiB
TypeScript

'use client';
import { useState } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import {
DndContext,
closestCenter,
type DragEndEvent,
PointerSensor,
useSensor,
useSensors,
} from '@dnd-kit/core';
import { SortableContext, verticalListSortingStrategy, useSortable } from '@dnd-kit/sortable';
import { CSS } from '@dnd-kit/utilities';
import { GripVertical, Plus, Loader2, Trash2 } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Badge } from '@/components/ui/badge';
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/components/ui/select';
import { apiFetch } from '@/lib/api/client';
interface WaitingListEntry {
id: string;
clientId: string;
position: number;
priority: string;
notifyPref: string;
notes: string | null;
createdAt: string;
}
interface WaitingListManagerProps {
berthId: string;
}
function SortableEntry({
entry,
onRemove,
}: {
entry: WaitingListEntry;
onRemove: (id: string) => void;
}) {
const { attributes, listeners, setNodeRef, transform, transition, isDragging } = useSortable({
id: entry.id,
});
const style = {
transform: CSS.Transform.toString(transform),
transition,
opacity: isDragging ? 0.5 : 1,
};
return (
<div
ref={setNodeRef}
style={style}
className="flex items-center gap-3 border rounded-md p-3 bg-card"
>
<button
{...attributes}
{...listeners}
className="cursor-grab active:cursor-grabbing text-muted-foreground"
>
<GripVertical className="h-4 w-4" />
</button>
<span className="text-sm font-mono w-6 text-center text-muted-foreground">
{entry.position}
</span>
<div className="flex-1 min-w-0">
<p className="text-sm truncate">{entry.clientId}</p>
{entry.notes && <p className="text-xs text-muted-foreground truncate">{entry.notes}</p>}
</div>
<Badge variant={entry.priority === 'high' ? 'destructive' : 'secondary'}>
{entry.priority}
</Badge>
<button
onClick={() => onRemove(entry.id)}
className="text-muted-foreground hover:text-destructive transition-colors"
>
<Trash2 className="h-4 w-4" />
</button>
</div>
);
}
export function WaitingListManager({ berthId }: WaitingListManagerProps) {
const queryClient = useQueryClient();
const sensors = useSensors(useSensor(PointerSensor));
const [showAddForm, setShowAddForm] = useState(false);
const [newClientId, setNewClientId] = useState('');
const [newPriority, setNewPriority] = useState<'normal' | 'high'>('normal');
const [newNotes, setNewNotes] = useState('');
const { data, isLoading } = useQuery<{ data: WaitingListEntry[] }>({
queryKey: ['berth-waiting-list', berthId],
queryFn: () => apiFetch(`/api/v1/berths/${berthId}/waiting-list`),
});
const reorderMutation = useMutation({
mutationFn: (body: { entryId: string; newPosition: number }) =>
apiFetch(`/api/v1/berths/${berthId}/waiting-list`, {
method: 'PATCH',
body,
}),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['berth-waiting-list', berthId] });
},
});
const addMutation = useMutation({
mutationFn: (entries: WaitingListEntry[]) =>
apiFetch(`/api/v1/berths/${berthId}/waiting-list`, {
method: 'PUT',
body: { entries },
}),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['berth-waiting-list', berthId] });
setShowAddForm(false);
setNewClientId('');
setNewNotes('');
},
});
const entries = data?.data ?? [];
function handleDragEnd(event: DragEndEvent) {
const { active, over } = event;
if (!over || active.id === over.id) return;
const overId = over.id as string;
const overEntry = entries.find((e) => e.id === overId);
if (!overEntry) return;
reorderMutation.mutate({
entryId: active.id as string,
newPosition: overEntry.position,
});
}
function handleAdd() {
if (!newClientId.trim()) return;
const newEntry = {
clientId: newClientId.trim(),
position: entries.length + 1,
priority: newPriority,
notifyPref: 'email' as const,
notes: newNotes || undefined,
};
addMutation.mutate([
...entries.map((e) => ({
...e,
notifyPref: e.notifyPref as 'email' | 'in_app' | 'both',
priority: e.priority as 'normal' | 'high',
})),
newEntry as WaitingListEntry,
]);
}
function handleRemove(entryId: string) {
const remaining = entries
.filter((e) => e.id !== entryId)
.map((e, i) => ({
...e,
position: i + 1,
notifyPref: e.notifyPref as 'email' | 'in_app' | 'both',
priority: e.priority as 'normal' | 'high',
}));
addMutation.mutate(remaining);
}
if (isLoading) {
return <div className="h-24 bg-muted animate-pulse rounded" />;
}
return (
<div className="space-y-3">
<div className="flex items-center justify-between">
<span className="text-sm font-medium">Waiting List ({entries.length})</span>
<Button size="sm" variant="outline" onClick={() => setShowAddForm((v) => !v)}>
<Plus className="mr-1.5 h-4 w-4" />
Add
</Button>
</div>
{showAddForm && (
<div className="border rounded-md p-3 space-y-3 bg-muted/30">
<Input
placeholder="Client ID"
value={newClientId}
onChange={(e) => setNewClientId(e.target.value)}
/>
<Select value={newPriority} onValueChange={(v) => setNewPriority(v as 'normal' | 'high')}>
<SelectTrigger>
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="normal">Normal priority</SelectItem>
<SelectItem value="high">High priority</SelectItem>
</SelectContent>
</Select>
<Input
placeholder="Notes (optional)"
value={newNotes}
onChange={(e) => setNewNotes(e.target.value)}
/>
<div className="flex gap-2">
<Button size="sm" onClick={handleAdd} disabled={addMutation.isPending}>
{addMutation.isPending && <Loader2 className="mr-1.5 h-4 w-4 animate-spin" />}
Add to List
</Button>
<Button size="sm" variant="ghost" onClick={() => setShowAddForm(false)}>
Cancel
</Button>
</div>
</div>
)}
{entries.length === 0 ? (
<p className="text-sm text-muted-foreground text-center py-6">
No entries on waiting list.
</p>
) : (
<DndContext sensors={sensors} collisionDetection={closestCenter} onDragEnd={handleDragEnd}>
<SortableContext items={entries.map((e) => e.id)} strategy={verticalListSortingStrategy}>
<div className="space-y-2">
{entries.map((entry) => (
<SortableEntry key={entry.id} entry={entry} onRemove={handleRemove} />
))}
</div>
</SortableContext>
</DndContext>
)}
</div>
);
}