feat(berths): ship Waiting List + Maintenance Log tabs

Both berth-detail surfaces were stubbed/hidden behind a comment in
berth-tabs.tsx. Their backing schema already existed; this wires the UI
and fills the service gaps.

Maintenance Log (was ~60% built: schema/migration/add+get service/route):
- new edit + delete: updateMaintenanceLog / deleteMaintenanceLog service
  (port-scoped tenant guard), PATCH/DELETE at maintenance/[logId], plus
  updateMaintenanceLogSchema. add schema now accepts null for cost /
  responsibleParty so the shared add+edit dialog sends one body shape.
- BerthMaintenanceTab: list (newest first) + add/edit dialog + delete
  confirm, realtime invalidation. New berth:maintenanceUpdated/Removed
  socket events.

Waiting List (un-hide the orphaned manager + next-in-line notify):
- getWaitingList now left-joins the client so the queue renders names,
  not raw ids.
- WaitingListManager rewritten: ClientPicker instead of free-text id,
  client names, manage_waiting_list gating on add/reorder/remove, and a
  "Next in line" marker on position 1.
- notifyWaitlistNextInLine: when a berth transitions to available,
  surface the #1 client to staff who hold berths.manage_waiting_list
  (mirrors the interest-based notifyNextInLine; dedupeKey-suppressed).
  Hooked into updateBerthStatus on any -> available transition.

Tests: maintenance add/get/update/delete + cross-port guard; waitlist
notify recipient-resolution / payload / empty + no-permission no-ops.
Verified end-to-end in the browser (create/render/delete for both).

Also adds scripts/dev-reset-admin-pw.ts (reset a synthetic user's
password via the better-auth hasher after a dev reseed).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-06-01 21:55:04 +02:00
parent d98aa5cc8a
commit 8be7a6e29d
11 changed files with 1046 additions and 103 deletions

View File

@@ -0,0 +1,28 @@
import 'dotenv/config';
import { and, eq } from 'drizzle-orm';
import { auth } from '@/lib/auth';
import { db } from '@/lib/db';
import { user, account } from '@/lib/db/schema/users';
async function main() {
const email = process.argv[2] ?? 'admin@portnimara.test';
const pw = process.argv[3] ?? 'SuperAdmin12345!';
const [u] = await db.select().from(user).where(eq(user.email, email)).limit(1);
if (!u) throw new Error(`user not found: ${email}`);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const ctx = await (auth as any).$context;
const hash = await ctx.password.hash(pw);
const res = await db
.update(account)
.set({ password: hash })
.where(and(eq(account.userId, u.id), eq(account.providerId, 'credential')))
.returning({ id: account.id });
console.log(`updated ${res.length} credential row(s) for ${email}`);
process.exit(0);
}
main().catch((e) => {
console.error(e);
process.exit(1);
});

View File

@@ -0,0 +1,42 @@
import { NextResponse } from 'next/server';
import { withAuth, withPermission } from '@/lib/api/helpers';
import { parseBody } from '@/lib/api/route-helpers';
import { updateMaintenanceLogSchema } from '@/lib/validators/berths';
import { updateMaintenanceLog, deleteMaintenanceLog } from '@/lib/services/berths.service';
import { errorResponse } from '@/lib/errors';
// PATCH /api/v1/berths/[id]/maintenance/[logId]
export const PATCH = withAuth(
withPermission('berths', 'edit', async (req, ctx, params) => {
try {
const body = await parseBody(req, updateMaintenanceLogSchema);
const log = await updateMaintenanceLog(params.id!, params.logId!, ctx.portId, body, {
userId: ctx.userId,
portId: ctx.portId,
ipAddress: ctx.ipAddress,
userAgent: ctx.userAgent,
});
return NextResponse.json({ data: log });
} catch (error) {
return errorResponse(error);
}
}),
);
// DELETE /api/v1/berths/[id]/maintenance/[logId]
export const DELETE = withAuth(
withPermission('berths', 'edit', async (_req, ctx, params) => {
try {
await deleteMaintenanceLog(params.id!, params.logId!, ctx.portId, {
userId: ctx.userId,
portId: ctx.portId,
ipAddress: ctx.ipAddress,
userAgent: ctx.userAgent,
});
return new NextResponse(null, { status: 204 });
} catch (error) {
return errorResponse(error);
}
}),
);

View File

@@ -0,0 +1,370 @@
'use client';
import { useState } from 'react';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { Loader2, Pencil, Plus, Trash2, Wrench } from 'lucide-react';
import { toast } from 'sonner';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { DatePicker } from '@/components/ui/date-picker';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/components/ui/select';
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog';
import { PermissionGate } from '@/components/shared/permission-gate';
import { EmptyState } from '@/components/shared/empty-state';
import { useConfirmation } from '@/hooks/use-confirmation';
import { useRealtimeInvalidation } from '@/hooks/use-realtime-invalidation';
import { apiFetch } from '@/lib/api/client';
import { toastError } from '@/lib/api/toast-error';
import { formatCurrency } from '@/lib/utils/currency';
import { cn } from '@/lib/utils';
type MaintenanceCategory = 'routine' | 'repair' | 'inspection' | 'upgrade';
interface MaintenanceLog {
id: string;
berthId: string;
category: MaintenanceCategory;
description: string;
cost: string | null;
costCurrency: string | null;
responsibleParty: string | null;
/** 'YYYY-MM-DD' calendar date (postgres `date` column). */
performedDate: string;
photoFileIds: string[] | null;
createdAt: string;
updatedAt: string;
}
const CATEGORIES: MaintenanceCategory[] = ['routine', 'repair', 'inspection', 'upgrade'];
const CATEGORY_LABELS: Record<MaintenanceCategory, string> = {
routine: 'Routine',
repair: 'Repair',
inspection: 'Inspection',
upgrade: 'Upgrade',
};
const CATEGORY_TONES: Record<MaintenanceCategory, string> = {
routine: 'bg-slate-100 text-slate-700',
repair: 'bg-rose-100 text-rose-700',
inspection: 'bg-blue-100 text-blue-700',
upgrade: 'bg-emerald-100 text-emerald-700',
};
/** Render a 'YYYY-MM-DD' calendar date without a timezone shift — treat it
* as a wall-clock date, not an instant (else dates west of UTC render a day
* early). */
function formatDate(iso: string): string {
const [y, m, d] = iso.split('-').map(Number);
if (!y || !m || !d) return iso;
return new Date(y, m - 1, d).toLocaleDateString();
}
export function BerthMaintenanceTab({ berthId }: { berthId: string }) {
const qc = useQueryClient();
const { confirm, dialog: confirmDialog } = useConfirmation();
const [dialogOpen, setDialogOpen] = useState(false);
const [editing, setEditing] = useState<MaintenanceLog | null>(null);
const { data, isLoading } = useQuery<{ data: MaintenanceLog[] }>({
queryKey: ['berths', berthId, 'maintenance'],
queryFn: () => apiFetch(`/api/v1/berths/${berthId}/maintenance`),
});
useRealtimeInvalidation({
'berth:maintenanceAdded': [['berths', berthId, 'maintenance']],
'berth:maintenanceUpdated': [['berths', berthId, 'maintenance']],
'berth:maintenanceRemoved': [['berths', berthId, 'maintenance']],
});
const logs = data?.data ?? [];
const deleteMutation = useMutation({
mutationFn: (logId: string) =>
apiFetch(`/api/v1/berths/${berthId}/maintenance/${logId}`, { method: 'DELETE' }),
onSuccess: () => {
qc.invalidateQueries({ queryKey: ['berths', berthId, 'maintenance'] });
toast.success('Maintenance entry deleted.');
},
onError: (err) => toastError(err),
});
async function handleDelete(log: MaintenanceLog) {
const ok = await confirm({
title: 'Delete maintenance entry',
description: `Delete the ${CATEGORY_LABELS[log.category].toLowerCase()} entry from ${formatDate(
log.performedDate,
)}? This cannot be undone.`,
confirmLabel: 'Delete',
});
if (!ok) return;
deleteMutation.mutate(log.id);
}
return (
<div className="space-y-5">
<div className="flex items-center justify-between">
<h3 className="text-lg font-semibold">Maintenance log</h3>
<PermissionGate resource="berths" action="edit">
<Button
size="sm"
onClick={() => {
setEditing(null);
setDialogOpen(true);
}}
>
<Plus className="me-1.5 h-4 w-4" aria-hidden />
Add entry
</Button>
</PermissionGate>
</div>
{isLoading ? (
<p className="text-sm text-muted-foreground">Loading</p>
) : logs.length === 0 ? (
<EmptyState
icon={Wrench}
title="No maintenance recorded"
description="Log routine upkeep, repairs, inspections, and upgrades for this berth."
/>
) : (
<ul className="space-y-2">
{logs.map((log) => (
<li key={log.id} className="rounded-lg border bg-background p-4">
<div className="flex items-start justify-between gap-3">
<div className="min-w-0 flex-1 space-y-1">
<div className="flex flex-wrap items-center gap-2">
<Badge
variant="outline"
className={cn(
'border-transparent text-xs font-semibold',
CATEGORY_TONES[log.category],
)}
>
{CATEGORY_LABELS[log.category]}
</Badge>
<span className="text-sm font-medium">{formatDate(log.performedDate)}</span>
{log.cost ? (
<span className="text-xs text-muted-foreground">
{formatCurrency(log.cost, log.costCurrency)}
</span>
) : null}
</div>
<p className="whitespace-pre-wrap break-words text-sm text-foreground">
{log.description}
</p>
{log.responsibleParty ? (
<p className="text-xs text-muted-foreground">By {log.responsibleParty}</p>
) : null}
</div>
<PermissionGate resource="berths" action="edit">
<div className="flex shrink-0 items-center gap-1">
<Button
variant="ghost"
size="icon"
className="size-8"
onClick={() => {
setEditing(log);
setDialogOpen(true);
}}
aria-label="Edit entry"
>
<Pencil className="size-4" aria-hidden />
</Button>
<Button
variant="ghost"
size="icon"
className="size-8 text-destructive hover:text-destructive"
onClick={() => handleDelete(log)}
aria-label="Delete entry"
disabled={deleteMutation.isPending}
>
<Trash2 className="size-4" aria-hidden />
</Button>
</div>
</PermissionGate>
</div>
</li>
))}
</ul>
)}
{/* Keyed conditional mount: a fresh form state is seeded from `editing`
each time the dialog opens (add => key 'new', edit => key <id>). */}
{dialogOpen && (
<MaintenanceEntryDialog
key={editing?.id ?? 'new'}
berthId={berthId}
editing={editing}
onClose={() => setDialogOpen(false)}
/>
)}
{confirmDialog}
</div>
);
}
function MaintenanceEntryDialog({
berthId,
editing,
onClose,
}: {
berthId: string;
editing: MaintenanceLog | null;
onClose: () => void;
}) {
const qc = useQueryClient();
const isEdit = editing !== null;
const [category, setCategory] = useState<MaintenanceCategory>(editing?.category ?? 'routine');
const [performedDate, setPerformedDate] = useState(
editing?.performedDate ?? new Date().toISOString().slice(0, 10),
);
const [description, setDescription] = useState(editing?.description ?? '');
const [cost, setCost] = useState(editing?.cost ?? '');
const [costCurrency, setCostCurrency] = useState(editing?.costCurrency ?? 'USD');
const [responsibleParty, setResponsibleParty] = useState(editing?.responsibleParty ?? '');
const mutation = useMutation({
mutationFn: async () => {
const body = {
category,
performedDate,
description: description.trim(),
// Empty cost clears the column (null), not 0.
cost: cost.trim() === '' ? null : Number(cost),
costCurrency: costCurrency.trim() || 'USD',
responsibleParty: responsibleParty.trim() === '' ? null : responsibleParty.trim(),
};
if (isEdit) {
return apiFetch(`/api/v1/berths/${berthId}/maintenance/${editing.id}`, {
method: 'PATCH',
body,
});
}
return apiFetch(`/api/v1/berths/${berthId}/maintenance`, { method: 'POST', body });
},
onSuccess: () => {
qc.invalidateQueries({ queryKey: ['berths', berthId, 'maintenance'] });
toast.success(isEdit ? 'Maintenance entry updated.' : 'Maintenance entry added.');
onClose();
},
onError: (err) => toastError(err),
});
const canSave = description.trim().length > 0 && performedDate.length > 0;
return (
<Dialog open onOpenChange={(next) => !next && onClose()}>
<DialogContent className="sm:max-w-lg">
<DialogHeader>
<DialogTitle>{isEdit ? 'Edit maintenance entry' : 'Add maintenance entry'}</DialogTitle>
<DialogDescription>
Record upkeep performed on this berth: category, date, what was done, and optional cost.
</DialogDescription>
</DialogHeader>
<div className="space-y-3 py-1">
<div className="grid grid-cols-2 gap-3">
<div>
<Label>Category</Label>
<Select value={category} onValueChange={(v) => setCategory(v as MaintenanceCategory)}>
<SelectTrigger className="mt-1">
<SelectValue />
</SelectTrigger>
<SelectContent>
{CATEGORIES.map((c) => (
<SelectItem key={c} value={c}>
{CATEGORY_LABELS[c]}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
<div>
<Label>Date performed</Label>
<div className="mt-1">
<DatePicker value={performedDate} onChange={setPerformedDate} toDate={new Date()} />
</div>
</div>
</div>
<div>
<Label>Description *</Label>
<Textarea
value={description}
onChange={(e) => setDescription(e.target.value)}
rows={3}
className="mt-1"
placeholder="What was done"
/>
</div>
<div className="grid grid-cols-3 gap-3">
<div className="col-span-2">
<Label>Cost (optional)</Label>
<Input
type="number"
inputMode="decimal"
min="0"
step="0.01"
value={cost}
onChange={(e) => setCost(e.target.value)}
className="mt-1"
placeholder="0.00"
/>
</div>
<div>
<Label>Currency</Label>
<Input
value={costCurrency}
onChange={(e) => setCostCurrency(e.target.value.toUpperCase())}
maxLength={3}
className="mt-1"
/>
</div>
</div>
<div>
<Label>Responsible party (optional)</Label>
<Input
value={responsibleParty}
onChange={(e) => setResponsibleParty(e.target.value)}
className="mt-1"
placeholder="Contractor / staff name"
/>
</div>
</div>
<DialogFooter>
<Button variant="outline" onClick={onClose} disabled={mutation.isPending}>
Cancel
</Button>
<Button onClick={() => mutation.mutate()} disabled={!canSave || mutation.isPending}>
{mutation.isPending ? (
<Loader2 className="me-1.5 h-3.5 w-3.5 animate-spin" aria-hidden />
) : null}
{isEdit ? 'Save changes' : 'Add entry'}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
);
}

View File

@@ -28,6 +28,8 @@ import { BerthInterestsTab } from './berth-interests-tab';
import { BerthInterestPulse } from './berth-interest-pulse';
import { BerthDocumentsTab } from './berth-documents-tab';
import { BerthDealDocumentsTab } from './berth-deal-documents-tab';
import { BerthMaintenanceTab } from './berth-maintenance-tab';
import { WaitingListManager } from './waiting-list-manager';
import type { BerthDetailData as BerthData } from './berth-detail-header';
@@ -462,9 +464,16 @@ function buildBerthDetailRemainder(berth: BerthData): DetailTab[] {
label: 'Interest Documents',
content: <BerthDealDocumentsTab berthId={berth.id} />,
},
// Waiting List + Maintenance Log tabs were stubs ("coming soon")
// visible to every operator. Hidden here until the
// berth_waiting_list / berth_maintenance_log feature surfaces ship.
{
id: 'waiting-list',
label: 'Waiting List',
content: <WaitingListManager berthId={berth.id} />,
},
{
id: 'maintenance',
label: 'Maintenance',
content: <BerthMaintenanceTab berthId={berth.id} />,
},
{
id: 'activity',
label: 'Activity',

View File

@@ -12,7 +12,8 @@ import {
} 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 { GripVertical, Plus, Loader2, Trash2, Users } from 'lucide-react';
import { toast } from 'sonner';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
@@ -24,11 +25,17 @@ import {
SelectTrigger,
SelectValue,
} from '@/components/ui/select';
import { EmptyState } from '@/components/shared/empty-state';
import { ClientPicker } from '@/components/shared/client-picker';
import { usePermissions } from '@/hooks/use-permissions';
import { useRealtimeInvalidation } from '@/hooks/use-realtime-invalidation';
import { apiFetch } from '@/lib/api/client';
import { toastError } from '@/lib/api/toast-error';
interface WaitingListEntry {
id: string;
clientId: string;
clientName: string | null;
position: number;
priority: string;
notifyPref: string;
@@ -40,15 +47,31 @@ interface WaitingListManagerProps {
berthId: string;
}
/** Shape the PUT (full-replace) endpoint accepts per entry. */
function toPutEntry(e: WaitingListEntry, position: number) {
return {
clientId: e.clientId,
position,
priority: e.priority as 'normal' | 'high',
notifyPref: e.notifyPref as 'email' | 'in_app' | 'both',
notes: e.notes ?? undefined,
};
}
function SortableEntry({
entry,
isNext,
canManage,
onRemove,
}: {
entry: WaitingListEntry;
isNext: boolean;
canManage: boolean;
onRemove: (id: string) => void;
}) {
const { attributes, listeners, setNodeRef, transform, transition, isDragging } = useSortable({
id: entry.id,
disabled: !canManage,
});
const style = {
@@ -61,45 +84,59 @@ function SortableEntry({
<div
ref={setNodeRef}
style={style}
className="flex items-center gap-3 border rounded-md p-3 bg-card"
className="flex items-center gap-3 rounded-md border bg-card p-3"
>
<button
{...attributes}
{...listeners}
className="cursor-grab active:cursor-grabbing text-muted-foreground"
>
<GripVertical className="h-4 w-4" aria-hidden />
</button>
{canManage ? (
<button
{...attributes}
{...listeners}
className="cursor-grab text-muted-foreground active:cursor-grabbing"
aria-label="Drag to reorder"
>
<GripVertical className="h-4 w-4" aria-hidden />
</button>
) : null}
<span className="text-sm font-mono w-6 text-center text-muted-foreground">
<span className="w-6 text-center font-mono text-sm 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 className="min-w-0 flex-1">
<p className="truncate text-sm font-medium">
{entry.clientName ?? `Client ${entry.clientId.slice(0, 8)}`}
</p>
{entry.notes && <p className="truncate text-xs text-muted-foreground">{entry.notes}</p>}
</div>
<Badge variant={entry.priority === 'high' ? 'destructive' : 'secondary'}>
{entry.priority}
</Badge>
{isNext ? (
<Badge variant="outline" className="border-transparent bg-emerald-100 text-emerald-700">
Next in line
</Badge>
) : null}
<button
onClick={() => onRemove(entry.id)}
className="text-muted-foreground hover:text-destructive transition-colors"
>
<Trash2 className="h-4 w-4" aria-hidden />
</button>
{entry.priority === 'high' ? <Badge variant="destructive">High</Badge> : null}
{canManage ? (
<button
onClick={() => onRemove(entry.id)}
className="text-muted-foreground transition-colors hover:text-destructive"
aria-label="Remove from waiting list"
>
<Trash2 className="h-4 w-4" aria-hidden />
</button>
) : null}
</div>
);
}
export function WaitingListManager({ berthId }: WaitingListManagerProps) {
const queryClient = useQueryClient();
const { can } = usePermissions();
const canManage = can('berths', 'manage_waiting_list');
const sensors = useSensors(useSensor(PointerSensor));
const [showAddForm, setShowAddForm] = useState(false);
const [newClientId, setNewClientId] = useState('');
const [newClientId, setNewClientId] = useState<string | null>(null);
const [newPriority, setNewPriority] = useState<'normal' | 'high'>('normal');
const [newNotes, setNewNotes] = useState('');
@@ -108,98 +145,96 @@ export function WaitingListManager({ berthId }: WaitingListManagerProps) {
queryFn: () => apiFetch(`/api/v1/berths/${berthId}/waiting-list`),
});
useRealtimeInvalidation({
'berth:waitingListChanged': [['berth-waiting-list', berthId]],
});
const entries = data?.data ?? [];
function resetForm() {
setShowAddForm(false);
setNewClientId(null);
setNewPriority('normal');
setNewNotes('');
}
const reorderMutation = useMutation({
mutationFn: (body: { entryId: string; newPosition: number }) =>
apiFetch(`/api/v1/berths/${berthId}/waiting-list`, {
method: 'PATCH',
body,
}),
apiFetch(`/api/v1/berths/${berthId}/waiting-list`, { method: 'PATCH', body }),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['berth-waiting-list', berthId] });
},
onError: (err) => toastError(err),
});
const addMutation = useMutation({
mutationFn: (entries: WaitingListEntry[]) =>
const replaceMutation = useMutation({
mutationFn: (entries: ReturnType<typeof toPutEntry>[]) =>
apiFetch(`/api/v1/berths/${berthId}/waiting-list`, {
method: 'PUT',
body: { entries },
}),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['berth-waiting-list', berthId] });
setShowAddForm(false);
setNewClientId('');
setNewNotes('');
resetForm();
},
onError: (err) => toastError(err),
});
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);
const overEntry = entries.find((e) => e.id === over.id);
if (!overEntry) return;
reorderMutation.mutate({
entryId: active.id as string,
newPosition: overEntry.position,
});
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,
]);
if (!newClientId) return;
if (entries.some((e) => e.clientId === newClientId)) {
toast.error('That client is already on this waiting list.');
return;
}
const next = [
...entries.map((e, i) => toPutEntry(e, i + 1)),
{
clientId: newClientId,
position: entries.length + 1,
priority: newPriority,
notifyPref: 'email' as const,
notes: newNotes.trim() || undefined,
},
];
replaceMutation.mutate(next);
}
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" />;
const remaining = entries.filter((e) => e.id !== entryId).map((e, i) => toPutEntry(e, i + 1));
replaceMutation.mutate(remaining);
}
return (
<div className="space-y-3">
<div className="space-y-4">
<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" aria-hidden />
Add
</Button>
<div>
<h3 className="text-lg font-semibold">Waiting list</h3>
<p className="text-xs text-muted-foreground">
When this berth becomes available, the person at the top is flagged to the team.
</p>
</div>
{canManage ? (
<Button size="sm" variant="outline" onClick={() => setShowAddForm((v) => !v)}>
<Plus className="me-1.5 h-4 w-4" aria-hidden />
Add
</Button>
) : null}
</div>
{showAddForm && (
<div className="border rounded-md p-3 space-y-3 bg-muted/30">
<Input
placeholder="Client ID"
{showAddForm && canManage && (
<div className="space-y-3 rounded-md border bg-muted/30 p-3">
<ClientPicker
value={newClientId}
onChange={(e) => setNewClientId(e.target.value)}
onChange={setNewClientId}
placeholder="Select a client to add…"
/>
<Select value={newPriority} onValueChange={(v) => setNewPriority(v as 'normal' | 'high')}>
<SelectTrigger>
@@ -216,29 +251,43 @@ export function WaitingListManager({ berthId }: WaitingListManagerProps) {
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" aria-hidden />
<Button
size="sm"
onClick={handleAdd}
disabled={!newClientId || replaceMutation.isPending}
>
{replaceMutation.isPending && (
<Loader2 className="me-1.5 h-4 w-4 animate-spin" aria-hidden />
)}
Add to List
Add to list
</Button>
<Button size="sm" variant="ghost" onClick={() => setShowAddForm(false)}>
<Button size="sm" variant="ghost" onClick={resetForm}>
Cancel
</Button>
</div>
</div>
)}
{entries.length === 0 ? (
<p className="text-sm text-muted-foreground text-center py-6">
No entries on waiting list.
</p>
{isLoading ? (
<div className="h-24 animate-pulse rounded bg-muted" />
) : entries.length === 0 ? (
<EmptyState
icon={Users}
title="No one waiting"
description="Add clients who want this berth so the team can follow up when it frees up."
/>
) : (
<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} />
{entries.map((entry, i) => (
<SortableEntry
key={entry.id}
entry={entry}
isNext={i === 0}
canManage={canManage}
onRemove={handleRemove}
/>
))}
</div>
</SortableContext>

View File

@@ -23,6 +23,7 @@ import type {
BulkUpdateBerthPricesInput,
ListBerthsQuery,
AddMaintenanceLogInput,
UpdateMaintenanceLogInput,
UpdateWaitingListInput,
} from '@/lib/validators/berths';
@@ -615,6 +616,22 @@ export async function updateBerthStatus(
await setPrimaryBerth(data.interestId, id);
}
// Next-in-line: when a berth frees up (any status -> available), surface
// the #1 client on its waiting list to the staff who manage the queue.
// Fire-and-forget via dynamic import (keeps the notifications stack out of
// this module's static graph); dedupeKey collapses rapid re-fires.
if (existing.status !== 'available' && data.status === 'available') {
void import('@/lib/services/next-in-line-notify.service')
.then(({ notifyWaitlistNextInLine }) =>
notifyWaitlistNextInLine({
portId,
berthId: id,
mooringNumber: existing.mooringNumber,
}),
)
.catch(() => {});
}
return updated!;
}
@@ -860,9 +877,9 @@ export async function addMaintenanceLog(
portId,
category: data.category,
description: data.description,
cost: data.cost !== undefined ? String(data.cost) : undefined,
cost: data.cost == null ? undefined : String(data.cost),
costCurrency: data.costCurrency,
responsibleParty: data.responsibleParty,
responsibleParty: data.responsibleParty ?? undefined,
performedDate: data.performedDate,
photoFileIds: data.photoFileIds,
createdBy: meta.userId,
@@ -902,7 +919,102 @@ export async function getMaintenanceLogs(id: string, portId: string) {
.select()
.from(berthMaintenanceLog)
.where(and(eq(berthMaintenanceLog.berthId, id), eq(berthMaintenanceLog.portId, portId)))
.orderBy(berthMaintenanceLog.performedDate);
.orderBy(desc(berthMaintenanceLog.performedDate));
}
// ─── Update Maintenance Log ───────────────────────────────────────────────────
export async function updateMaintenanceLog(
berthId: string,
logId: string,
portId: string,
data: UpdateMaintenanceLogInput,
meta: AuditMeta,
) {
// Tenant guard: the entry must belong to a berth in this port. port_id is
// on the row itself, so a single (id, berth_id, port_id) match is the
// defense-in-depth scope — no foreign-tenant row can be reached.
const existing = await db.query.berthMaintenanceLog.findFirst({
where: and(
eq(berthMaintenanceLog.id, logId),
eq(berthMaintenanceLog.berthId, berthId),
eq(berthMaintenanceLog.portId, portId),
),
});
if (!existing) throw new NotFoundError('Maintenance log entry');
const patch: Partial<typeof berthMaintenanceLog.$inferInsert> = { updatedAt: new Date() };
if (data.category !== undefined) patch.category = data.category;
if (data.description !== undefined) patch.description = data.description;
if (data.cost !== undefined) patch.cost = data.cost === null ? null : String(data.cost);
if (data.costCurrency !== undefined) patch.costCurrency = data.costCurrency;
if (data.responsibleParty !== undefined) patch.responsibleParty = data.responsibleParty;
if (data.performedDate !== undefined) patch.performedDate = data.performedDate;
if (data.photoFileIds !== undefined) patch.photoFileIds = data.photoFileIds;
const rows = await db
.update(berthMaintenanceLog)
.set(patch)
.where(
and(
eq(berthMaintenanceLog.id, logId),
eq(berthMaintenanceLog.berthId, berthId),
eq(berthMaintenanceLog.portId, portId),
),
)
.returning();
const log = rows[0]!;
void createAuditLog({
userId: meta.userId,
portId,
action: 'update',
entityType: 'berth_maintenance_log',
entityId: log.id,
metadata: { berthId, category: log.category },
ipAddress: meta.ipAddress,
userAgent: meta.userAgent,
});
emitToRoom(`port:${portId}`, 'berth:maintenanceUpdated', { berthId, logEntry: log });
return log;
}
// ─── Delete Maintenance Log ───────────────────────────────────────────────────
export async function deleteMaintenanceLog(
berthId: string,
logId: string,
portId: string,
meta: AuditMeta,
) {
const rows = await db
.delete(berthMaintenanceLog)
.where(
and(
eq(berthMaintenanceLog.id, logId),
eq(berthMaintenanceLog.berthId, berthId),
eq(berthMaintenanceLog.portId, portId),
),
)
.returning({ id: berthMaintenanceLog.id });
if (rows.length === 0) throw new NotFoundError('Maintenance log entry');
void createAuditLog({
userId: meta.userId,
portId,
action: 'delete',
entityType: 'berth_maintenance_log',
entityId: logId,
metadata: { berthId },
ipAddress: meta.ipAddress,
userAgent: meta.userAgent,
});
emitToRoom(`port:${portId}`, 'berth:maintenanceRemoved', { berthId, logId });
return { id: logId };
}
// ─── Get Waiting List ─────────────────────────────────────────────────────────
@@ -913,9 +1025,23 @@ export async function getWaitingList(id: string, portId: string) {
});
if (!existing) throw new NotFoundError('Berth');
// Left-join the client so the UI can render names (the queue stores only
// clientId). A left join keeps a row even if the client was hard-deleted.
return db
.select()
.select({
id: berthWaitingList.id,
berthId: berthWaitingList.berthId,
clientId: berthWaitingList.clientId,
clientName: clients.fullName,
yachtId: berthWaitingList.yachtId,
position: berthWaitingList.position,
priority: berthWaitingList.priority,
notifyPref: berthWaitingList.notifyPref,
notes: berthWaitingList.notes,
createdAt: berthWaitingList.createdAt,
})
.from(berthWaitingList)
.leftJoin(clients, eq(clients.id, berthWaitingList.clientId))
.where(eq(berthWaitingList.berthId, id))
.orderBy(berthWaitingList.position);
}

View File

@@ -10,10 +10,12 @@
* (the canonical "this person handles the pipeline" permission).
*/
import { eq } from 'drizzle-orm';
import { asc, eq } from 'drizzle-orm';
import { db } from '@/lib/db';
import { userPortRoles, roles, type RolePermissions } from '@/lib/db/schema/users';
import { berthWaitingList } from '@/lib/db/schema/berths';
import { clients } from '@/lib/db/schema/clients';
import { logger } from '@/lib/logger';
import { createNotification } from '@/lib/services/notifications.service';
import { STAGE_LABELS, type PipelineStage } from '@/lib/constants';
@@ -88,3 +90,68 @@ export async function notifyNextInLine(input: BerthReleaseNotificationInput): Pr
});
}
}
/**
* Waiting-list next-in-line. When a berth transitions to `available`, surface
* the #1 client on that berth's waiting list to the staff who manage the
* queue so they can reach out / open a deal. Informational only — no
* automatic linking or stage changes.
*
* Recipients = port users whose role grants `berths.manage_waiting_list`.
* No-ops when the waiting list is empty or no one holds the permission.
*/
export async function notifyWaitlistNextInLine(input: {
portId: string;
berthId: string;
mooringNumber: string;
}): Promise<void> {
// #1 on the queue (lowest position). Left-join the client for the name.
const [next] = await db
.select({
clientName: clients.fullName,
priority: berthWaitingList.priority,
})
.from(berthWaitingList)
.leftJoin(clients, eq(clients.id, berthWaitingList.clientId))
.where(eq(berthWaitingList.berthId, input.berthId))
.orderBy(asc(berthWaitingList.position))
.limit(1);
if (!next) return; // empty waiting list - nothing to surface
const recipientRows = await db
.select({ userId: userPortRoles.userId, permissions: roles.permissions })
.from(userPortRoles)
.innerJoin(roles, eq(userPortRoles.roleId, roles.id))
.where(eq(userPortRoles.portId, input.portId));
const recipientIds = new Set<string>();
for (const r of recipientRows) {
const perms = r.permissions as RolePermissions | null;
if (perms?.berths?.manage_waiting_list) recipientIds.add(r.userId);
}
if (recipientIds.size === 0) {
logger.debug(
{ portId: input.portId, berthId: input.berthId },
'No waiting-list managers to notify of berth availability',
);
return;
}
const clientLabel = next.clientName ?? '(unknown client)';
const priorityNote = next.priority === 'high' ? ' (high priority)' : '';
for (const userId of recipientIds) {
void createNotification({
portId: input.portId,
userId,
type: 'berth_waiting_list_update',
title: `Berth ${input.mooringNumber} is now available`,
description: `${clientLabel} is next in line${priorityNote}. Open the berth to action the waiting list.`,
link: `/berths/${input.berthId}`,
entityType: 'berth',
entityId: input.berthId,
dedupeKey: `berth-waitlist-available:${input.berthId}`,
});
}
}

View File

@@ -15,6 +15,8 @@ export interface ServerToClientEvents {
entry: unknown;
}) => void;
'berth:maintenanceAdded': (payload: { berthId: string; logEntry: unknown }) => void;
'berth:maintenanceUpdated': (payload: { berthId: string; logEntry: unknown }) => void;
'berth:maintenanceRemoved': (payload: { berthId: string; logId: string }) => void;
// Client events
'client:created': (payload: { clientId: string; clientName: string; source: string }) => void;

View File

@@ -158,15 +158,35 @@ export type BulkUpdateBerthPricesInput = z.infer<typeof bulkUpdateBerthPricesSch
export const addMaintenanceLogSchema = z.object({
category: z.enum(['routine', 'repair', 'inspection', 'upgrade']),
description: z.string().min(1),
cost: z.coerce.number().optional(),
// `null` accepted (and treated as "no value") so the shared add/edit dialog
// can send a single body shape — an empty optional field maps to null.
cost: z.coerce.number().nullable().optional(),
costCurrency: z.string().optional(),
responsibleParty: z.string().optional(),
responsibleParty: z.string().nullable().optional(),
performedDate: z.string().min(1, 'Performed date is required'),
photoFileIds: z.array(z.string()).optional(),
});
export type AddMaintenanceLogInput = z.infer<typeof addMaintenanceLogSchema>;
// ─── Update Maintenance Log ───────────────────────────────────────────────────
// Partial of the add schema — every field optional so the edit dialog can
// PATCH just the touched columns. `cost` and `responsibleParty` accept `null`
// so the rep can clear a previously-recorded value (an empty edit field maps
// to null in the UI, not to 0 / '').
export const updateMaintenanceLogSchema = z.object({
category: z.enum(['routine', 'repair', 'inspection', 'upgrade']).optional(),
description: z.string().min(1).optional(),
cost: z.coerce.number().nullable().optional(),
costCurrency: z.string().optional(),
responsibleParty: z.string().nullable().optional(),
performedDate: z.string().min(1).optional(),
photoFileIds: z.array(z.string()).optional(),
});
export type UpdateMaintenanceLogInput = z.infer<typeof updateMaintenanceLogSchema>;
// ─── Update Waiting List ──────────────────────────────────────────────────────
export const updateWaitingListSchema = z.object({

View File

@@ -0,0 +1,118 @@
/**
* Integration test: berth maintenance-log service (add / get / update / delete).
*
* The schema + add/get already existed; this covers the new update + delete
* paths and the tenant guard (an entry can only be reached through its own
* berth + port). Runs against the real test DB.
*/
import { beforeAll, describe, expect, it } from 'vitest';
import { db } from '@/lib/db';
import { berthMaintenanceLog } from '@/lib/db/schema/berths';
import { eq } from 'drizzle-orm';
let svc: typeof import('@/lib/services/berths.service');
let makePort: typeof import('../helpers/factories').makePort;
let makeBerth: typeof import('../helpers/factories').makeBerth;
let makeAuditMeta: typeof import('../helpers/factories').makeAuditMeta;
beforeAll(async () => {
svc = await import('@/lib/services/berths.service');
const f = await import('../helpers/factories');
makePort = f.makePort;
makeBerth = f.makeBerth;
makeAuditMeta = f.makeAuditMeta;
});
describe('berth maintenance log', () => {
async function setup() {
const port = await makePort();
const berth = await makeBerth({ portId: port.id });
const meta = makeAuditMeta({ portId: port.id });
return { port, berth, meta };
}
it('adds, lists (newest first), updates, and deletes an entry', async () => {
const { port, berth, meta } = await setup();
const created = await svc.addMaintenanceLog(
berth.id,
port.id,
{
category: 'repair',
description: 'Replaced cleat bolt',
cost: 120.5,
costCurrency: 'EUR',
responsibleParty: 'Dockside Ltd',
performedDate: '2026-05-10',
},
meta,
);
expect(created.category).toBe('repair');
expect(created.cost).toBe('120.5');
// A second, more recent entry to assert ordering.
await svc.addMaintenanceLog(
berth.id,
port.id,
{ category: 'inspection', description: 'Annual check', performedDate: '2026-05-20' },
meta,
);
const list = await svc.getMaintenanceLogs(berth.id, port.id);
expect(list).toHaveLength(2);
// Newest performedDate first.
expect(list[0]!.performedDate).toBe('2026-05-20');
expect(list[1]!.performedDate).toBe('2026-05-10');
const updated = await svc.updateMaintenanceLog(
berth.id,
created.id,
port.id,
{ description: 'Replaced cleat bolt + washer', cost: null },
meta,
);
expect(updated.description).toBe('Replaced cleat bolt + washer');
// cost cleared to null
expect(updated.cost).toBeNull();
await svc.deleteMaintenanceLog(berth.id, created.id, port.id, meta);
const afterDelete = await db
.select()
.from(berthMaintenanceLog)
.where(eq(berthMaintenanceLog.id, created.id));
expect(afterDelete).toHaveLength(0);
const remaining = await svc.getMaintenanceLogs(berth.id, port.id);
expect(remaining).toHaveLength(1);
expect(remaining[0]!.category).toBe('inspection');
});
it('refuses to update or delete an entry through a different port (tenant guard)', async () => {
const { port, berth, meta } = await setup();
const otherPort = await makePort();
const entry = await svc.addMaintenanceLog(
berth.id,
port.id,
{ category: 'routine', description: 'Pressure wash', performedDate: '2026-05-15' },
meta,
);
await expect(
svc.updateMaintenanceLog(berth.id, entry.id, otherPort.id, { description: 'hijack' }, meta),
).rejects.toThrow();
await expect(
svc.deleteMaintenanceLog(berth.id, entry.id, otherPort.id, meta),
).rejects.toThrow();
// Untouched.
const [row] = await db
.select()
.from(berthMaintenanceLog)
.where(eq(berthMaintenanceLog.id, entry.id));
expect(row!.description).toBe('Pressure wash');
});
});

View File

@@ -0,0 +1,112 @@
/**
* Integration test: waiting-list next-in-line notification.
*
* `notifyWaitlistNextInLine` surfaces the #1 client on a berth's waiting list
* to staff who hold `berths.manage_waiting_list` when the berth frees up.
* `createNotification` is mocked so we assert the fan-out decision (who, what
* payload) without exercising the full notification insert / preferences /
* queue path (covered by notification-lifecycle.test.ts).
*/
import { beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
vi.mock('@/lib/services/notifications.service', () => ({
createNotification: vi.fn(async () => null),
}));
import { db } from '@/lib/db';
import { user, roles, userPortRoles, type RolePermissions } from '@/lib/db/schema/users';
import { berthWaitingList } from '@/lib/db/schema/berths';
import { createNotification } from '@/lib/services/notifications.service';
let notifyWaitlistNextInLine: typeof import('@/lib/services/next-in-line-notify.service').notifyWaitlistNextInLine;
let makePort: typeof import('../helpers/factories').makePort;
let makeBerth: typeof import('../helpers/factories').makeBerth;
let makeClient: typeof import('../helpers/factories').makeClient;
beforeAll(async () => {
notifyWaitlistNextInLine = (await import('@/lib/services/next-in-line-notify.service'))
.notifyWaitlistNextInLine;
const f = await import('../helpers/factories');
makePort = f.makePort;
makeBerth = f.makeBerth;
makeClient = f.makeClient;
});
beforeEach(() => {
vi.mocked(createNotification).mockClear();
});
async function seedManager(portId: string, perms: RolePermissions): Promise<string> {
const suffix = crypto.randomUUID().slice(0, 8);
const [u] = await db
.insert(user)
.values({
id: crypto.randomUUID(),
name: `WL User ${suffix}`,
email: `wl-${suffix}@test.local`,
emailVerified: true,
})
.returning();
const [role] = await db
.insert(roles)
.values({ name: `WL Role ${suffix}`, permissions: perms })
.returning();
await db.insert(userPortRoles).values({ userId: u!.id, portId, roleId: role!.id });
return u!.id;
}
describe('notifyWaitlistNextInLine', () => {
it('notifies managers about the #1 client when a berth frees up', async () => {
const port = await makePort();
const berth = await makeBerth({ portId: port.id, overrides: { mooringNumber: 'WL1' } });
const first = await makeClient({ portId: port.id, overrides: { fullName: 'Ada First' } });
const second = await makeClient({ portId: port.id, overrides: { fullName: 'Bob Second' } });
await db.insert(berthWaitingList).values([
{ berthId: berth.id, clientId: first.id, position: 1, priority: 'high' },
{ berthId: berth.id, clientId: second.id, position: 2, priority: 'normal' },
]);
await seedManager(port.id, { berths: { manage_waiting_list: true } } as RolePermissions);
await notifyWaitlistNextInLine({
portId: port.id,
berthId: berth.id,
mooringNumber: 'WL1',
});
expect(createNotification).toHaveBeenCalledTimes(1);
const payload = vi.mocked(createNotification).mock.calls[0]![0];
expect(payload.type).toBe('berth_waiting_list_update');
expect(payload.title).toContain('WL1');
// #1 by position (Ada), with the high-priority note.
expect(payload.description).toContain('Ada First');
expect(payload.description).toContain('high priority');
expect(payload.dedupeKey).toBe(`berth-waitlist-available:${berth.id}`);
expect(payload.entityId).toBe(berth.id);
});
it('does not notify users who lack manage_waiting_list', async () => {
const port = await makePort();
const berth = await makeBerth({ portId: port.id, overrides: { mooringNumber: 'WL2' } });
const c = await makeClient({ portId: port.id, overrides: { fullName: 'Carol Only' } });
await db.insert(berthWaitingList).values({ berthId: berth.id, clientId: c.id, position: 1 });
await seedManager(port.id, { berths: { manage_waiting_list: false } } as RolePermissions);
await notifyWaitlistNextInLine({ portId: port.id, berthId: berth.id, mooringNumber: 'WL2' });
expect(createNotification).not.toHaveBeenCalled();
});
it('no-ops when the waiting list is empty', async () => {
const port = await makePort();
const berth = await makeBerth({ portId: port.id, overrides: { mooringNumber: 'WL3' } });
await seedManager(port.id, { berths: { manage_waiting_list: true } } as RolePermissions);
await notifyWaitlistNextInLine({ portId: port.id, berthId: berth.id, mooringNumber: 'WL3' });
expect(createNotification).not.toHaveBeenCalled();
});
});