feat(sales-ux): triage signals, reminders, realtime toasts, mobile FAB

Sales-CRM workflow batch — closes audit recommendations #2, #3, #4, #6,
#7, #8, #9, #10, #13, #15. Skips #11 (My-pipeline filter — needs a real
assignee column on interests, defer until ownership model lands) and #12
(keyboard shortcuts — explicit user call).

  Interest list (the rep's main triage surface):

    - Last activity column replaces Created (sortable by
      dateLastContact). Postgres NULLs-last on DESC means
      never-contacted leads sort to the bottom — exactly the right
      triage default.
    - Comment-icon next to client name when notesCount > 0, with a
      tooltip showing the count. Cheap, glanceable signal that the
      lead has correspondence to peek at.
    - Urgency badges under stage when criteria fire: "Silent Nd"
      for mid-funnel interests with no contact in 7+ days,
      "EOI Nd" for EOIs awaiting signature 14+ days, "Deposit Nd"
      for eoi_signed interests with no deposit after 21 days.
      Pure derived — no extra fetch, computed from the dates the
      row already returns.
    - Bulk select checkbox column with bulk-archive (existing
      DataTable.bulkActions API; just wired with a confirm-dialog
      and a Promise.all fan-out).
    - Mobile FAB (+) for new interest, anchored above the bottom-tab
      bar with safe-area inset awareness.

    All four signals mirrored on the mobile InterestCard (comment
    icon, urgency badges, last-activity footer).

  Interest detail:

    - Reminder bell badge in the header showing pending/snoozed
      reminder count linked to the interest. Surfaced via
      getInterestById's new `activeReminderCount`.
    - "Latest note" teaser on the Overview tab — truncated 3-line
      preview of the most recent threaded note + relative time +
      "View all" link to the Notes tab. Saves a click for the
      common "what was discussed last?" peek.
    - Color-block swatches in InlineStagePicker dropdown (rounded-sm
      mini-bars in the stage's progressive saturation color, replacing
      the previous tiny dots). Reads as a visual scan instead of a
      list.

  Dashboard:

    - MyRemindersRail on the right sidebar above the existing
      AlertRail. Shows pending+snoozed reminders for the current
      user (overdue first), each with priority pill, relative due
      time, and click-through to the linked interest/client/berth.

  Berth detail:

    - BerthInterestPulse card at the top of the Overview tab,
      replacing the old "buried in tab" pattern. Shows up to 5
      active interests with avatar, stage pill, urgency badges, and
      last-activity. Mirrors the old Nuxt CRM's beloved "Interested
      Parties" panel but with the new triage signals.

  Realtime toasts:

    - New <RealtimeToasts /> mounted inside SocketProvider in the
      dashboard layout. Subscribes to interest:stageChanged,
      document:completed, document:signer:signed, and
      interest:outcomeSet — fires sonner toasts so reps watching any
      page learn about pipeline events without refreshing.

  Service layer:

    - listInterests: notesCount per row (left join + count + groupBy).
    - getInterestById: clientPrimaryPhone + clientPrimaryPhoneE164
      (for the Email/Call/WhatsApp buttons added last commit; phone
      pieces were missing), notesCount, recentNote, activeReminderCount.
    - sortColumn switch handles 'dateLastContact' explicitly; default
      stays 'updatedAt'.

tsc clean. vitest 835/835 pass. ESLint clean on every file touched.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
Matt Ciaccio
2026-05-02 04:09:51 +02:00
parent c824b2df12
commit a767652d74
15 changed files with 1033 additions and 107 deletions

View File

@@ -13,6 +13,7 @@ import { PermissionsProvider } from '@/providers/permissions-provider';
import { Sidebar } from '@/components/layout/sidebar'; import { Sidebar } from '@/components/layout/sidebar';
import { Topbar } from '@/components/layout/topbar'; import { Topbar } from '@/components/layout/topbar';
import { MobileLayout } from '@/components/layout/mobile/mobile-layout'; import { MobileLayout } from '@/components/layout/mobile/mobile-layout';
import { RealtimeToasts } from '@/components/shared/realtime-toasts';
export default async function DashboardLayout({ children }: { children: React.ReactNode }) { export default async function DashboardLayout({ children }: { children: React.ReactNode }) {
const session = await auth.api.getSession({ headers: await headers() }); const session = await auth.api.getSession({ headers: await headers() });
@@ -38,6 +39,7 @@ export default async function DashboardLayout({ children }: { children: React.Re
<PortProvider ports={ports} defaultPortId={ports[0]?.id ?? null}> <PortProvider ports={ports} defaultPortId={ports[0]?.id ?? null}>
<PermissionsProvider> <PermissionsProvider>
<SocketProvider> <SocketProvider>
<RealtimeToasts />
{/* Desktop shell — hidden by CSS on mobile */} {/* Desktop shell — hidden by CSS on mobile */}
<div data-shell="desktop" className="flex h-screen overflow-hidden bg-background"> <div data-shell="desktop" className="flex h-screen overflow-hidden bg-background">
<Sidebar <Sidebar

View File

@@ -0,0 +1,166 @@
'use client';
import Link from 'next/link';
import { useParams } from 'next/navigation';
import { useQuery } from '@tanstack/react-query';
import { ChevronRight, Users } from 'lucide-react';
import { formatDistanceToNowStrict } from 'date-fns';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { apiFetch } from '@/lib/api/client';
import { stageBadgeClass, stageLabel } from '@/lib/constants';
import { computeUrgencyBadges } from '@/components/interests/urgency';
import type { InterestRow } from '@/components/interests/interest-columns';
import { cn } from '@/lib/utils';
interface InterestsResponse {
data: InterestRow[];
}
const PREVIEW_LIMIT = 5;
/**
* Top-of-overview pulse for the berth detail page. Lists the active
* interested parties with their stage + last activity, so the rep can do
* berth-level triage ("who's on this slip and how warm are they?")
* without clicking into the Interests tab.
*
* Borrows from the old Nuxt CRM's BerthDetailsModal "Interested Parties"
* pattern but uses the new at-a-glance signals (urgency badges, last
* activity).
*/
export function BerthInterestPulse({ berthId }: { berthId: string }) {
const params = useParams<{ portSlug: string }>();
const portSlug = params?.portSlug ?? '';
const { data, isLoading } = useQuery<InterestsResponse>({
queryKey: ['interests', { berthId, sort: 'dateLastContact', order: 'desc' }],
queryFn: () =>
apiFetch<InterestsResponse>(
`/api/v1/interests?berthId=${berthId}&limit=10&sort=dateLastContact&order=desc`,
),
staleTime: 30_000,
});
const all = data?.data ?? [];
const active = all.filter((i) => !i.archivedAt && !i.outcome);
const preview = active.slice(0, PREVIEW_LIMIT);
const more = active.length - preview.length;
if (isLoading) {
return (
<Card>
<CardHeader className="pb-3">
<CardTitle className="text-sm font-medium">Interested parties</CardTitle>
</CardHeader>
<CardContent className="pt-0">
<div className="space-y-2">
{[0, 1, 2].map((i) => (
<div key={i} className="h-10 animate-pulse rounded-md bg-muted/40" />
))}
</div>
</CardContent>
</Card>
);
}
if (active.length === 0) {
return (
<Card>
<CardHeader className="pb-3">
<CardTitle className="flex items-center gap-1.5 text-sm font-medium">
<Users className="size-3.5" />
Interested parties
</CardTitle>
</CardHeader>
<CardContent className="pt-0">
<p className="text-sm text-muted-foreground">No active interests on this berth.</p>
</CardContent>
</Card>
);
}
return (
<Card>
<CardHeader className="flex flex-row items-center justify-between pb-3 space-y-0">
<CardTitle className="flex items-center gap-1.5 text-sm font-medium">
<Users className="size-3.5" />
Interested parties
<span className="ml-1 rounded-full bg-muted px-1.5 py-0.5 text-[10px] font-medium text-muted-foreground">
{active.length}
</span>
</CardTitle>
</CardHeader>
<CardContent className="pt-0">
<ul className="divide-y divide-border">
{preview.map((i) => {
const lastIso = i.dateLastContact ?? i.updatedAt ?? null;
const lastActivity = lastIso
? formatDistanceToNowStrict(new Date(lastIso), { addSuffix: true })
: null;
const urgency = computeUrgencyBadges(i);
const initials = (i.clientName ?? '?')
.split(/\s+/)
.filter(Boolean)
.slice(0, 2)
.map((p) => p[0]!.toUpperCase())
.join('');
return (
<li key={i.id}>
<Link
href={`/${portSlug}/interests/${i.id}`}
className="group flex items-center gap-3 px-1 py-2.5 transition-colors hover:bg-foreground/5 rounded-md -mx-1"
>
<span className="flex size-8 shrink-0 items-center justify-center rounded-full bg-brand-100 text-xs font-semibold text-brand-700">
{initials || '?'}
</span>
<div className="min-w-0 flex-1 space-y-0.5">
<div className="flex items-center gap-2 flex-wrap">
<span className="truncate text-sm font-medium text-foreground">
{i.clientName ?? 'Unknown'}
</span>
<span
className={cn(
'inline-flex items-center rounded-full px-2 py-0.5 text-[10px] font-medium',
stageBadgeClass(i.pipelineStage),
)}
>
{stageLabel(i.pipelineStage)}
</span>
{urgency.map((b) => (
<span
key={b.id}
title={b.detail}
className={cn(
'inline-flex items-center rounded-full px-1.5 py-0.5 text-[10px] font-medium',
b.className,
)}
>
{b.label}
</span>
))}
</div>
{lastActivity ? (
<p className="text-[11px] tabular-nums text-muted-foreground">
Last activity {lastActivity}
</p>
) : null}
</div>
<ChevronRight className="size-4 shrink-0 text-muted-foreground/60 transition-transform group-hover:translate-x-0.5" />
</Link>
</li>
);
})}
</ul>
{more > 0 ? (
<Link
href={`/${portSlug}/berths/${berthId}?tab=interests`}
className="mt-2 inline-flex text-xs font-medium text-primary hover:underline"
>
View all {active.length} interests
</Link>
) : null}
</CardContent>
</Card>
);
}

View File

@@ -5,6 +5,7 @@ import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { TagBadge } from '@/components/shared/tag-badge'; import { TagBadge } from '@/components/shared/tag-badge';
import { BerthReservationsTab } from './berth-reservations-tab'; import { BerthReservationsTab } from './berth-reservations-tab';
import { BerthInterestsTab } from './berth-interests-tab'; import { BerthInterestsTab } from './berth-interests-tab';
import { BerthInterestPulse } from './berth-interest-pulse';
type BerthData = { type BerthData = {
id: string; id: string;
@@ -72,93 +73,99 @@ function OverviewTab({ berth }: { berth: BerthData }) {
: null; : null;
return ( return (
<div className="grid grid-cols-1 md:grid-cols-2 gap-6"> <div className="space-y-6">
{/* Specifications */} {/* Sales pulse — top-of-page so reps doing berth-level triage can see
<Card> who's interested + how warm without clicking into the Interests tab. */}
<CardHeader className="pb-3"> <BerthInterestPulse berthId={berth.id} />
<CardTitle className="text-sm font-medium">Specifications</CardTitle>
</CardHeader>
<CardContent className="pt-0 divide-y">
<SpecRow label="Length" value={formatDim(berth.lengthFt, berth.lengthM)} />
<SpecRow
label="Width"
value={
formatDim(berth.widthFt, berth.widthM)
? `${formatDim(berth.widthFt, berth.widthM)}${berth.widthIsMinimum ? ' (min)' : ''}`
: null
}
/>
<SpecRow label="Draft" value={formatDim(berth.draftFt, berth.draftM)} />
<SpecRow
label="Nominal Boat Size"
value={berth.nominalBoatSize || berth.nominalBoatSizeM}
/>
<SpecRow
label="Water Depth"
value={
berth.waterDepth || berth.waterDepthM
? `${formatDim(berth.waterDepth, berth.waterDepthM)}${berth.waterDepthIsMinimum ? ' (min)' : ''}`
: null
}
/>
<SpecRow label="Mooring Type" value={berth.mooringType} />
<SpecRow label="Side Pontoon" value={berth.sidePontoon} />
<SpecRow label="Bow Facing" value={berth.bowFacing} />
<SpecRow label="Access" value={berth.access} />
<SpecRow label="Approved" value={berth.berthApproved ? 'Yes' : null} />
</CardContent>
</Card>
{/* Infrastructure & Pricing */} <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
<div className="space-y-6"> {/* Specifications */}
<Card> <Card>
<CardHeader className="pb-3"> <CardHeader className="pb-3">
<CardTitle className="text-sm font-medium">Infrastructure</CardTitle> <CardTitle className="text-sm font-medium">Specifications</CardTitle>
</CardHeader>
<CardContent className="pt-0 divide-y">
<SpecRow label="Power Capacity" value={berth.powerCapacity} />
<SpecRow label="Voltage" value={berth.voltage} />
<SpecRow label="Cleat Type" value={berth.cleatType} />
<SpecRow label="Cleat Capacity" value={berth.cleatCapacity} />
<SpecRow label="Bollard Type" value={berth.bollardType} />
<SpecRow label="Bollard Capacity" value={berth.bollardCapacity} />
</CardContent>
</Card>
<Card>
<CardHeader className="pb-3">
<CardTitle className="text-sm font-medium">Tenure & Pricing</CardTitle>
</CardHeader> </CardHeader>
<CardContent className="pt-0 divide-y"> <CardContent className="pt-0 divide-y">
<SpecRow label="Length" value={formatDim(berth.lengthFt, berth.lengthM)} />
<SpecRow <SpecRow
label="Tenure Type" label="Width"
value={berth.tenureType === 'permanent' ? 'Permanent' : 'Fixed Term'} value={
formatDim(berth.widthFt, berth.widthM)
? `${formatDim(berth.widthFt, berth.widthM)}${berth.widthIsMinimum ? ' (min)' : ''}`
: null
}
/> />
{berth.tenureType === 'fixed_term' && ( <SpecRow label="Draft" value={formatDim(berth.draftFt, berth.draftM)} />
<> <SpecRow
<SpecRow label="Years" value={berth.tenureYears} /> label="Nominal Boat Size"
<SpecRow label="Start Date" value={berth.tenureStartDate} /> value={berth.nominalBoatSize || berth.nominalBoatSizeM}
<SpecRow label="End Date" value={berth.tenureEndDate} /> />
</> <SpecRow
)} label="Water Depth"
<SpecRow label="Price" value={price} /> value={
berth.waterDepth || berth.waterDepthM
? `${formatDim(berth.waterDepth, berth.waterDepthM)}${berth.waterDepthIsMinimum ? ' (min)' : ''}`
: null
}
/>
<SpecRow label="Mooring Type" value={berth.mooringType} />
<SpecRow label="Side Pontoon" value={berth.sidePontoon} />
<SpecRow label="Bow Facing" value={berth.bowFacing} />
<SpecRow label="Access" value={berth.access} />
<SpecRow label="Approved" value={berth.berthApproved ? 'Yes' : null} />
</CardContent> </CardContent>
</Card> </Card>
{berth.tags.length > 0 && ( {/* Infrastructure & Pricing */}
<div className="space-y-6">
<Card> <Card>
<CardHeader className="pb-3"> <CardHeader className="pb-3">
<CardTitle className="text-sm font-medium">Tags</CardTitle> <CardTitle className="text-sm font-medium">Infrastructure</CardTitle>
</CardHeader> </CardHeader>
<CardContent className="pt-0"> <CardContent className="pt-0 divide-y">
<div className="flex flex-wrap gap-1.5"> <SpecRow label="Power Capacity" value={berth.powerCapacity} />
{berth.tags.map((tag) => ( <SpecRow label="Voltage" value={berth.voltage} />
<TagBadge key={tag.id} name={tag.name} color={tag.color} /> <SpecRow label="Cleat Type" value={berth.cleatType} />
))} <SpecRow label="Cleat Capacity" value={berth.cleatCapacity} />
</div> <SpecRow label="Bollard Type" value={berth.bollardType} />
<SpecRow label="Bollard Capacity" value={berth.bollardCapacity} />
</CardContent> </CardContent>
</Card> </Card>
)}
<Card>
<CardHeader className="pb-3">
<CardTitle className="text-sm font-medium">Tenure & Pricing</CardTitle>
</CardHeader>
<CardContent className="pt-0 divide-y">
<SpecRow
label="Tenure Type"
value={berth.tenureType === 'permanent' ? 'Permanent' : 'Fixed Term'}
/>
{berth.tenureType === 'fixed_term' && (
<>
<SpecRow label="Years" value={berth.tenureYears} />
<SpecRow label="Start Date" value={berth.tenureStartDate} />
<SpecRow label="End Date" value={berth.tenureEndDate} />
</>
)}
<SpecRow label="Price" value={price} />
</CardContent>
</Card>
{berth.tags.length > 0 && (
<Card>
<CardHeader className="pb-3">
<CardTitle className="text-sm font-medium">Tags</CardTitle>
</CardHeader>
<CardContent className="pt-0">
<div className="flex flex-wrap gap-1.5">
{berth.tags.map((tag) => (
<TagBadge key={tag.id} name={tag.name} color={tag.color} />
))}
</div>
</CardContent>
</Card>
)}
</div>
</div> </div>
</div> </div>
); );

View File

@@ -11,6 +11,7 @@ import { PipelineFunnelChart } from './pipeline-funnel-chart';
import { OccupancyTimelineChart } from './occupancy-timeline-chart'; import { OccupancyTimelineChart } from './occupancy-timeline-chart';
import { RevenueBreakdownChart } from './revenue-breakdown-chart'; import { RevenueBreakdownChart } from './revenue-breakdown-chart';
import { LeadSourceChart } from './lead-source-chart'; import { LeadSourceChart } from './lead-source-chart';
import { MyRemindersRail } from './my-reminders-rail';
import { WidgetErrorBoundary } from './widget-error-boundary'; import { WidgetErrorBoundary } from './widget-error-boundary';
import { AlertRail } from '@/components/alerts/alert-rail'; import { AlertRail } from '@/components/alerts/alert-rail';
import type { DateRange } from '@/lib/services/analytics.service'; import type { DateRange } from '@/lib/services/analytics.service';
@@ -49,7 +50,7 @@ export function DashboardShell() {
actions={<DateRangePicker value={range} onChange={setRange} />} actions={<DateRangePicker value={range} onChange={setRange} />}
/> />
<div className="grid gap-4 grid-cols-1 sm:grid-cols-2 lg:grid-cols-4"> <div className="grid gap-3 grid-cols-2 sm:gap-4 lg:grid-cols-4">
<KpiCardsWithBoundary /> <KpiCardsWithBoundary />
</div> </div>
@@ -68,7 +69,10 @@ export function DashboardShell() {
<LeadSourceChart range={range} /> <LeadSourceChart range={range} />
</WidgetErrorBoundary> </WidgetErrorBoundary>
</div> </div>
<aside className="min-w-0"> <aside className="min-w-0 space-y-4">
<WidgetErrorBoundary>
<MyRemindersRail />
</WidgetErrorBoundary>
<WidgetErrorBoundary> <WidgetErrorBoundary>
<AlertRail /> <AlertRail />
</WidgetErrorBoundary> </WidgetErrorBoundary>

View File

@@ -0,0 +1,153 @@
'use client';
import Link from 'next/link';
import { useParams } from 'next/navigation';
import { useQuery } from '@tanstack/react-query';
import { formatDistanceToNowStrict, isAfter, isBefore } from 'date-fns';
import { AlarmClock, ChevronRight } from 'lucide-react';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { apiFetch } from '@/lib/api/client';
import { cn } from '@/lib/utils';
interface ReminderRow {
id: string;
title: string;
dueAt: string;
status: string;
priority?: string | null;
interestId?: string | null;
clientId?: string | null;
entityType?: string | null;
entityId?: string | null;
}
interface MyRemindersResponse {
data: ReminderRow[];
}
const PRIORITY_BADGE: Record<string, string> = {
high: 'bg-rose-100 text-rose-700',
medium: 'bg-amber-100 text-amber-700',
low: 'bg-slate-100 text-slate-700',
};
/**
* Compact reminders rail for the dashboard sidebar. Lists reminders assigned
* to the current user (overdue first, then upcoming). Each item links to its
* subject — interest preferred, then client, then the generic entity ref.
*
* Limited to 6 items; "View all" routes to /reminders.
*/
export function MyRemindersRail() {
const params = useParams<{ portSlug: string }>();
const portSlug = params?.portSlug ?? '';
const { data, isLoading } = useQuery<MyRemindersResponse>({
queryKey: ['reminders', 'my'],
queryFn: () => apiFetch<MyRemindersResponse>('/api/v1/reminders/my'),
staleTime: 60_000,
});
const items = data?.data ?? [];
const now = new Date();
// Overdue first, then upcoming, capped at 6 for the rail.
const sorted = [...items]
.sort((a, b) => new Date(a.dueAt).getTime() - new Date(b.dueAt).getTime())
.slice(0, 6);
const overdueCount = items.filter((r) => isBefore(new Date(r.dueAt), now)).length;
function hrefFor(r: ReminderRow): string {
if (r.interestId) return `/${portSlug}/interests/${r.interestId}`;
if (r.clientId) return `/${portSlug}/clients/${r.clientId}`;
if (r.entityType === 'client' && r.entityId) return `/${portSlug}/clients/${r.entityId}`;
if (r.entityType === 'interest' && r.entityId) return `/${portSlug}/interests/${r.entityId}`;
if (r.entityType === 'berth' && r.entityId) return `/${portSlug}/berths/${r.entityId}`;
return `/${portSlug}/reminders`;
}
return (
<Card className="h-full">
<CardHeader className="flex flex-row items-start justify-between gap-2 space-y-0 pb-3">
<div className="space-y-0.5">
<CardTitle className="flex items-center gap-1.5 text-base">
<AlarmClock className="size-4" />
Reminders
</CardTitle>
{overdueCount > 0 ? (
<p className="text-xs text-rose-700">{overdueCount} overdue</p>
) : items.length > 0 ? (
<p className="text-xs text-muted-foreground">{items.length} pending</p>
) : null}
</div>
<Link
href={`/${portSlug}/reminders` as never}
className="text-xs font-medium text-primary hover:underline"
>
View all
</Link>
</CardHeader>
<CardContent className="pt-0">
{isLoading ? (
<div className="space-y-2">
{[0, 1, 2].map((i) => (
<div key={i} className="h-9 animate-pulse rounded-md bg-muted/40" />
))}
</div>
) : sorted.length === 0 ? (
<p className="py-3 text-center text-sm text-muted-foreground">
All caught up no reminders.
</p>
) : (
<ul className="space-y-1">
{sorted.map((r) => {
const due = new Date(r.dueAt);
const isOverdue = isBefore(due, now);
const isUpcoming = isAfter(due, now);
return (
<li key={r.id}>
<Link
href={hrefFor(r) as never}
className={cn(
'group flex items-center gap-2 rounded-md px-2 py-1.5 text-sm transition-colors',
'hover:bg-foreground/5',
)}
>
<span
aria-hidden
className={cn(
'size-1.5 shrink-0 rounded-full',
isOverdue ? 'bg-rose-500' : 'bg-amber-400',
)}
/>
<span className="min-w-0 flex-1 truncate">{r.title}</span>
{r.priority && r.priority !== 'low' ? (
<Badge
variant="outline"
className={cn(
'border-transparent text-[10px]',
PRIORITY_BADGE[r.priority] ?? 'bg-muted text-muted-foreground',
)}
>
{r.priority}
</Badge>
) : null}
<span className="shrink-0 text-[11px] tabular-nums text-muted-foreground">
{isOverdue
? formatDistanceToNowStrict(due) + ' overdue'
: isUpcoming
? 'in ' + formatDistanceToNowStrict(due)
: 'now'}
</span>
<ChevronRight className="size-3.5 shrink-0 text-muted-foreground/60 transition-transform group-hover:translate-x-0.5" />
</Link>
</li>
);
})}
</ul>
)}
</CardContent>
</Card>
);
}

View File

@@ -0,0 +1,163 @@
'use client';
import { useState } from 'react';
import { useMutation, useQueryClient } from '@tanstack/react-query';
import { Check, ChevronDown, Loader2 } from 'lucide-react';
import { toast } from 'sonner';
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
import { Textarea } from '@/components/ui/textarea';
import { apiFetch } from '@/lib/api/client';
import { cn } from '@/lib/utils';
import {
PIPELINE_STAGES,
STAGE_BADGE,
STAGE_DOT,
STAGE_LABELS,
safeStage,
type PipelineStage,
} from '@/components/clients/pipeline-constants';
interface InlineStagePickerProps {
interestId: string;
currentStage: string;
/** Whether to render the chevron after the stage label. Default true. */
showChevron?: boolean;
/** Stop the parent's click propagation when used inside a clickable card. */
stopPropagation?: boolean;
className?: string;
}
/**
* Click-to-change stage chip. Replaces the modal-based InterestStagePicker
* for inline editing — user clicks the chip, picks a new stage from the
* popover (with optional reason), commits in one click. The popover stays
* compact: a small reason field above the stage list, and clicking any stage
* fires the mutation immediately.
*/
export function InlineStagePicker({
interestId,
currentStage,
showChevron = true,
stopPropagation = false,
className,
}: InlineStagePickerProps) {
const queryClient = useQueryClient();
const [open, setOpen] = useState(false);
const [reason, setReason] = useState('');
const [pendingStage, setPendingStage] = useState<string | null>(null);
const stage = safeStage(currentStage);
const mutation = useMutation({
mutationFn: async (next: PipelineStage) =>
apiFetch(`/api/v1/interests/${interestId}/stage`, {
method: 'PATCH',
body: { pipelineStage: next, reason: reason.trim() || undefined },
}),
onSuccess: (_data, next) => {
queryClient.invalidateQueries({ queryKey: ['interests', interestId] });
queryClient.invalidateQueries({ queryKey: ['interests'] });
setOpen(false);
setReason('');
setPendingStage(null);
toast.success(`Stage moved to ${STAGE_LABELS[next]}`);
},
onError: (err) => {
setPendingStage(null);
toast.error(err instanceof Error ? err.message : 'Failed to change stage');
},
});
function pick(next: PipelineStage) {
if (next === stage) {
setOpen(false);
return;
}
setPendingStage(next);
mutation.mutate(next);
}
return (
<Popover
open={open}
onOpenChange={(o) => {
if (!mutation.isPending) setOpen(o);
}}
>
<PopoverTrigger asChild>
<button
type="button"
onClick={(e) => {
if (stopPropagation) e.stopPropagation();
}}
className={cn(
'inline-flex items-center gap-1 rounded-full px-2.5 py-0.5 text-sm font-medium',
'transition-colors hover:brightness-95 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring',
STAGE_BADGE[stage],
className,
)}
aria-label={`Pipeline stage: ${STAGE_LABELS[stage]}. Click to change.`}
>
<span>{STAGE_LABELS[stage]}</span>
{mutation.isPending ? (
<Loader2 className="size-3 animate-spin" />
) : showChevron ? (
<ChevronDown className="size-3 opacity-70" />
) : null}
</button>
</PopoverTrigger>
<PopoverContent
align="start"
className="w-64 p-0"
onClick={(e) => stopPropagation && e.stopPropagation()}
>
<div className="border-b px-2 py-1">
<Textarea
value={reason}
onChange={(e) => setReason(e.target.value)}
placeholder="Reason (optional)…"
rows={1}
className="min-h-0 resize-none border-none bg-transparent px-0 py-0.5 text-xs leading-tight shadow-none focus-visible:ring-0"
disabled={mutation.isPending}
/>
</div>
<ul role="listbox" aria-label="Pipeline stages" className="py-1">
{PIPELINE_STAGES.map((s) => {
const isCurrent = s === stage;
const isPending = pendingStage === s && mutation.isPending;
return (
<li key={s}>
<button
type="button"
role="option"
aria-selected={isCurrent}
disabled={mutation.isPending}
onClick={() => pick(s)}
className={cn(
'flex w-full items-center gap-2 px-3 py-1.5 text-left text-sm',
'transition-colors hover:bg-muted/60 disabled:opacity-60',
isCurrent && 'font-medium',
)}
>
{/* Colored chip (mirrors the inline stage badge) — turns
the picker into a visual scan rather than just a list. */}
<span
className={cn('inline-flex h-5 w-3 shrink-0 rounded-sm', STAGE_DOT[s])}
aria-hidden
/>
<span className="flex-1">{STAGE_LABELS[s]}</span>
{isPending ? (
<Loader2 className="size-3.5 animate-spin text-muted-foreground" />
) : isCurrent ? (
<Check className="size-3.5 text-muted-foreground" />
) : null}
</button>
</li>
);
})}
</ul>
</PopoverContent>
</Popover>
);
}

View File

@@ -1,6 +1,7 @@
'use client'; 'use client';
import { Anchor, Archive, Compass, MoreHorizontal, Pencil } from 'lucide-react'; import { Anchor, Archive, Compass, MessageSquare, MoreHorizontal, Pencil } from 'lucide-react';
import { formatDistanceToNowStrict } from 'date-fns';
import { Button } from '@/components/ui/button'; import { Button } from '@/components/ui/button';
import { import {
@@ -18,6 +19,7 @@ import {
} from '@/components/shared/list-card'; } from '@/components/shared/list-card';
import { cn } from '@/lib/utils'; import { cn } from '@/lib/utils';
import { stageBadgeClass, stageDotClass, stageLabel as toStageLabel } from '@/lib/constants'; import { stageBadgeClass, stageDotClass, stageLabel as toStageLabel } from '@/lib/constants';
import { computeUrgencyBadges } from '@/components/interests/urgency';
import type { InterestRow } from './interest-columns'; import type { InterestRow } from './interest-columns';
const CATEGORY_LABELS: Record<string, string> = { const CATEGORY_LABELS: Record<string, string> = {
@@ -48,9 +50,15 @@ export function InterestCard({ interest, portSlug, onEdit, onArchive }: Interest
const categoryLabel = interest.leadCategory ? CATEGORY_LABELS[interest.leadCategory] : null; const categoryLabel = interest.leadCategory ? CATEGORY_LABELS[interest.leadCategory] : null;
const sourceLabel = interest.source ? (SOURCE_LABELS[interest.source] ?? interest.source) : null; const sourceLabel = interest.source ? (SOURCE_LABELS[interest.source] ?? interest.source) : null;
const tags = interest.tags ?? []; const tags = interest.tags ?? [];
const notesCount = interest.notesCount ?? 0;
const urgencyBadges = computeUrgencyBadges(interest);
const clientName = interest.clientName ?? 'Unknown client'; const clientName = interest.clientName ?? 'Unknown client';
const berthLabel = interest.berthMooringNumber; const berthLabel = interest.berthMooringNumber;
const lastIso = interest.dateLastContact ?? interest.updatedAt ?? null;
const lastActivity = lastIso
? formatDistanceToNowStrict(new Date(lastIso), { addSuffix: true })
: null;
return ( return (
<ListCard <ListCard
@@ -86,11 +94,22 @@ export function InterestCard({ interest, portSlug, onEdit, onArchive }: Interest
<div className="flex items-start gap-3"> <div className="flex items-start gap-3">
<ListCardAvatar initials={deriveInitials(clientName)} /> <ListCardAvatar initials={deriveInitials(clientName)} />
<div className="min-w-0 flex-1"> <div className="min-w-0 flex-1">
{/* Title row: name + spacer for the absolutely-positioned actions menu */} {/* Title row: name + comment-icon when notes exist + spacer for actions */}
<div className="flex items-start justify-between gap-2"> <div className="flex items-start justify-between gap-2">
<h3 className="truncate text-base font-semibold tracking-tight text-foreground"> <div className="flex min-w-0 items-center gap-1.5">
{clientName} <h3 className="truncate text-base font-semibold tracking-tight text-foreground">
</h3> {clientName}
</h3>
{notesCount > 0 ? (
<span
title={`${notesCount} note${notesCount === 1 ? '' : 's'}`}
aria-label={`${notesCount} note${notesCount === 1 ? '' : 's'}`}
className="inline-flex shrink-0 items-center text-muted-foreground"
>
<MessageSquare className="size-3.5" />
</span>
) : null}
</div>
<span aria-hidden className="block h-9 w-9 shrink-0" /> <span aria-hidden className="block h-9 w-9 shrink-0" />
</div> </div>
@@ -135,6 +154,23 @@ export function InterestCard({ interest, portSlug, onEdit, onArchive }: Interest
) : null} ) : null}
</div> </div>
{urgencyBadges.length > 0 ? (
<div className="mt-1.5 flex flex-wrap gap-1">
{urgencyBadges.map((b) => (
<span
key={b.id}
title={b.detail}
className={cn(
'inline-flex items-center rounded-full px-1.5 py-0.5 text-[10px] font-medium',
b.className,
)}
>
{b.label}
</span>
))}
</div>
) : null}
{tags.length > 0 ? ( {tags.length > 0 ? (
<div className="mt-2 flex flex-wrap gap-1"> <div className="mt-2 flex flex-wrap gap-1">
{tags.slice(0, 2).map((tag) => ( {tags.slice(0, 2).map((tag) => (
@@ -147,6 +183,12 @@ export function InterestCard({ interest, portSlug, onEdit, onArchive }: Interest
) : null} ) : null}
</div> </div>
) : null} ) : null}
{lastActivity ? (
<p className="mt-1.5 text-[11px] text-muted-foreground tabular-nums">
Last activity {lastActivity}
</p>
) : null}
</div> </div>
</div> </div>
</ListCard> </ListCard>

View File

@@ -1,8 +1,8 @@
'use client'; 'use client';
import Link from 'next/link'; import Link from 'next/link';
import { format } from 'date-fns'; import { format, formatDistanceToNowStrict } from 'date-fns';
import { MoreHorizontal, Pencil, Archive } from 'lucide-react'; import { MoreHorizontal, Pencil, Archive, MessageSquare } from 'lucide-react';
import type { ColumnDef } from '@tanstack/react-table'; import type { ColumnDef } from '@tanstack/react-table';
import { Button } from '@/components/ui/button'; import { Button } from '@/components/ui/button';
@@ -15,6 +15,7 @@ import {
import { Badge } from '@/components/ui/badge'; import { Badge } from '@/components/ui/badge';
import { TagBadge } from '@/components/shared/tag-badge'; import { TagBadge } from '@/components/shared/tag-badge';
import { stageBadgeClass, stageLabel } from '@/lib/constants'; import { stageBadgeClass, stageLabel } from '@/lib/constants';
import { computeUrgencyBadges, type InterestUrgencyInput } from '@/components/interests/urgency';
export interface InterestRow { export interface InterestRow {
id: string; id: string;
@@ -27,6 +28,15 @@ export interface InterestRow {
source: string | null; source: string | null;
archivedAt: string | null; archivedAt: string | null;
createdAt: string; createdAt: string;
/** Surfaced by listInterests for the row-level sales-triage signals
* (last-activity relative time, comment-icon, urgency badges). */
updatedAt?: string;
dateLastContact?: string | null;
dateEoiSent?: string | null;
dateDepositReceived?: string | null;
eoiStatus?: string | null;
outcome?: string | null;
notesCount?: number;
tags?: Array<{ id: string; name: string; color: string }>; tags?: Array<{ id: string; name: string; color: string }>;
} }
@@ -59,15 +69,29 @@ export function getInterestColumns({
id: 'clientName', id: 'clientName',
accessorKey: 'clientName', accessorKey: 'clientName',
header: 'Client', header: 'Client',
cell: ({ row }) => ( cell: ({ row }) => {
<Link const notesCount = row.original.notesCount ?? 0;
href={`/${portSlug}/clients/${row.original.clientId}`} return (
className="font-medium text-primary hover:underline" <div className="flex items-center gap-1.5 min-w-0">
onClick={(e) => e.stopPropagation()} <Link
> href={`/${portSlug}/clients/${row.original.clientId}`}
{row.original.clientName ?? '—'} className="truncate font-medium text-primary hover:underline"
</Link> onClick={(e) => e.stopPropagation()}
), >
{row.original.clientName ?? '—'}
</Link>
{notesCount > 0 ? (
<span
title={`${notesCount} note${notesCount === 1 ? '' : 's'}`}
aria-label={`${notesCount} note${notesCount === 1 ? '' : 's'}`}
className="inline-flex items-center text-muted-foreground"
>
<MessageSquare className="size-3.5" />
</span>
) : null}
</div>
);
},
}, },
{ {
id: 'berthMooringNumber', id: 'berthMooringNumber',
@@ -92,14 +116,31 @@ export function getInterestColumns({
id: 'pipelineStage', id: 'pipelineStage',
accessorKey: 'pipelineStage', accessorKey: 'pipelineStage',
header: 'Stage', header: 'Stage',
cell: ({ getValue }) => { cell: ({ row }) => {
const stage = getValue() as string; const stage = row.original.pipelineStage;
const badges = computeUrgencyBadges(row.original satisfies InterestUrgencyInput);
return ( return (
<span <div className="flex flex-col gap-1 items-start">
className={`inline-flex items-center rounded-full px-2 py-0.5 text-xs font-medium ${stageBadgeClass(stage)}`} <span
> className={`inline-flex items-center rounded-full px-2 py-0.5 text-xs font-medium ${stageBadgeClass(stage)}`}
{stageLabel(stage)} >
</span> {stageLabel(stage)}
</span>
{badges.length > 0 ? (
<div className="flex flex-wrap gap-1">
{badges.map((b) => (
<span
key={b.id}
title={b.detail}
aria-label={b.detail}
className={`inline-flex items-center rounded-full px-1.5 py-0.5 text-[10px] font-medium ${b.className}`}
>
{b.label}
</span>
))}
</div>
) : null}
</div>
); );
}, },
}, },
@@ -153,14 +194,24 @@ export function getInterestColumns({
}, },
}, },
{ {
id: 'createdAt', // Sales-triage default: prefer the explicit dateLastContact, fall back
accessorKey: 'createdAt', // to updatedAt. Sortable on dateLastContact server-side; the column
header: 'Created', // header label ("Last activity") makes the fallback semantics clear.
cell: ({ getValue }) => ( id: 'dateLastContact',
<span className="text-muted-foreground text-sm"> accessorKey: 'dateLastContact',
{format(new Date(getValue() as string), 'MMM d, yyyy')} header: 'Last activity',
</span> cell: ({ row }) => {
), const lastIso = row.original.dateLastContact ?? row.original.updatedAt ?? null;
if (!lastIso) {
return <span className="text-muted-foreground text-sm"></span>;
}
const d = new Date(lastIso);
return (
<span className="text-muted-foreground text-sm tabular-nums" title={format(d, 'PPpp')}>
{formatDistanceToNowStrict(d, { addSuffix: true })}
</span>
);
},
}, },
{ {
id: 'actions', id: 'actions',

View File

@@ -12,6 +12,7 @@ import {
Mail, Mail,
MessageCircle, MessageCircle,
Phone, Phone,
AlarmClock,
} from 'lucide-react'; } from 'lucide-react';
import Link from 'next/link'; import Link from 'next/link';
@@ -53,6 +54,10 @@ interface InterestDetailHeaderProps {
clientPrimaryEmail?: string | null; clientPrimaryEmail?: string | null;
clientPrimaryPhone?: string | null; clientPrimaryPhone?: string | null;
clientPrimaryPhoneE164?: string | null; clientPrimaryPhoneE164?: string | null;
/** Pending/snoozed reminders attached to this interest. Drives the
* alarm-bell badge on the header — surfaces follow-ups so the rep
* doesn't have to remember to check /reminders. */
activeReminderCount?: number;
berthId: string | null; berthId: string | null;
berthMooringNumber: string | null; berthMooringNumber: string | null;
pipelineStage: string; pipelineStage: string;
@@ -203,6 +208,17 @@ export function InterestDetailHeader({ portSlug, interest }: InterestDetailHeade
/> />
</PermissionGate> </PermissionGate>
)} )}
{(interest.activeReminderCount ?? 0) > 0 ? (
<span
className="inline-flex items-center gap-1 rounded-full border border-amber-200 bg-amber-50 px-2 py-0.5 text-[11px] font-medium text-amber-800"
title={`${interest.activeReminderCount} pending reminder${
interest.activeReminderCount === 1 ? '' : 's'
}`}
>
<AlarmClock className="size-3" />
{interest.activeReminderCount}
</span>
) : null}
</div> </div>
{meta.length > 0 ? ( {meta.length > 0 ? (

View File

@@ -28,6 +28,17 @@ interface InterestData {
/** True when the linked client has any primary address row. Used by /** True when the linked client has any primary address row. Used by
* the EOI prereq checklist on the Documents tab. */ * the EOI prereq checklist on the Documents tab. */
clientHasAddress: boolean; clientHasAddress: boolean;
/** Surfaced for the bell badge on the detail header (pending/snoozed
* reminders linked to this interest). */
activeReminderCount?: number;
/** Surfaced for the most-recent-note teaser on the Overview tab. */
notesCount?: number;
recentNote?: {
id: string;
content: string;
authorId: string;
createdAt: string;
} | null;
berthId: string | null; berthId: string | null;
berthMooringNumber: string | null; berthMooringNumber: string | null;
pipelineStage: string; pipelineStage: string;

View File

@@ -2,7 +2,7 @@
import { useState } from 'react'; import { useState } from 'react';
import { useParams } from 'next/navigation'; import { useParams } from 'next/navigation';
import { Plus, LayoutList, Kanban } from 'lucide-react'; import { Plus, LayoutList, Kanban, Archive } from 'lucide-react';
import { useMutation, useQueryClient } from '@tanstack/react-query'; import { useMutation, useQueryClient } from '@tanstack/react-query';
import { Button } from '@/components/ui/button'; import { Button } from '@/components/ui/button';
@@ -69,6 +69,18 @@ export function InterestList() {
}, },
}); });
const bulkArchiveMutation = useMutation({
mutationFn: async (ids: string[]) => {
// Concurrent fan-out — small batches in practice (page size cap = 100).
// If a single delete fails the others still run; the rejected one
// surfaces a toast via the standard apiFetch error path.
await Promise.all(ids.map((id) => apiFetch(`/api/v1/interests/${id}`, { method: 'DELETE' })));
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['interests'] });
},
});
const columns = getInterestColumns({ const columns = getInterestColumns({
portSlug, portSlug,
onEdit: (interest) => setEditInterest(interest), onEdit: (interest) => setEditInterest(interest),
@@ -146,6 +158,24 @@ export function InterestList() {
onSortChange={setSort} onSortChange={setSort}
isLoading={isFetching && !isLoading} isLoading={isFetching && !isLoading}
getRowId={(row) => row.id} getRowId={(row) => row.id}
bulkActions={[
{
label: 'Archive',
icon: Archive,
variant: 'destructive',
onClick: (ids) => {
if (ids.length === 0) return;
if (
!window.confirm(
`Archive ${ids.length} interest${ids.length === 1 ? '' : 's'}? This can be undone from the archived list.`,
)
) {
return;
}
bulkArchiveMutation.mutate(ids);
},
},
]}
cardRender={(row) => ( cardRender={(row) => (
<InterestCard <InterestCard
interest={row.original} interest={row.original}
@@ -164,6 +194,20 @@ export function InterestList() {
/> />
)} )}
{/* Mobile FAB — primary "New interest" affordance for the bottom-tab UX.
Sits above the bottom nav (pb-safe-bottom + 70px tab height + 16px
gap). Hidden on lg+ where the header button already does the job. */}
<PermissionGate resource="interests" action="create">
<button
type="button"
onClick={() => setCreateOpen(true)}
aria-label="New interest"
className="fixed bottom-[calc(env(safe-area-inset-bottom)+86px)] right-4 z-40 inline-flex h-12 w-12 items-center justify-center rounded-full bg-primary text-primary-foreground shadow-lg transition-transform hover:scale-105 active:scale-95 lg:hidden"
>
<Plus className="h-6 w-6" />
</button>
</PermissionGate>
<InterestForm open={createOpen} onOpenChange={setCreateOpen} /> <InterestForm open={createOpen} onOpenChange={setCreateOpen} />
{editInterest && ( {editInterest && (

View File

@@ -48,6 +48,15 @@ interface InterestTabsOptions {
reminderDays: number | null; reminderDays: number | null;
reminderLastFired: string | null; reminderLastFired: string | null;
notes: string | null; notes: string | null;
/** Surfaced by getInterestById for the Overview "most recent note"
* teaser — saves a click into the Notes tab to peek at the latest. */
notesCount?: number;
recentNote?: {
id: string;
content: string;
authorId: string;
createdAt: string;
} | null;
tags?: Array<{ id: string; name: string; color: string }>; tags?: Array<{ id: string; name: string; color: string }>;
}; };
} }
@@ -431,6 +440,37 @@ function OverviewTab({
</div> </div>
)} )}
{/* Most-recent threaded note teaser. Saves a click into the Notes
tab when the rep just wants to peek at "what was discussed last."
Hidden when there's nothing to show. */}
{interest.recentNote ? (
<div className="space-y-1 md:col-span-2">
<div className="mb-2 flex items-center justify-between">
<h3 className="text-sm font-medium">Latest note</h3>
<Link
href={`/${portSlug}/interests/${interestId}?tab=notes`}
className="text-xs font-medium text-primary hover:underline"
>
View all
{interest.notesCount && interest.notesCount > 1 ? ` ${interest.notesCount}` : ''}
</Link>
</div>
<div className="rounded-md border border-border bg-muted/30 px-3 py-2 text-sm">
<p className="line-clamp-3 whitespace-pre-wrap text-foreground/90">
{interest.recentNote.content}
</p>
<p className="mt-1 text-xs text-muted-foreground">
{formatDistanceToNowStrict(new Date(interest.recentNote.createdAt), {
addSuffix: true,
})}
{interest.recentNote.authorId
? ` · ${interest.recentNote.authorId === 'system' ? 'system' : interest.recentNote.authorId}`
: ''}
</p>
</div>
</div>
) : null}
{/* Notes (editable, multiline) */} {/* Notes (editable, multiline) */}
<div className="space-y-1 md:col-span-2"> <div className="space-y-1 md:col-span-2">
<h3 className="text-sm font-medium mb-2">Notes</h3> <h3 className="text-sm font-medium mb-2">Notes</h3>

View File

@@ -0,0 +1,91 @@
/**
* Sales-triage urgency badges for interest list rows + cards.
*
* Derived purely from the dates we already return on the row, so this is a
* pure function — no DB hits, no extra fetch. Mirrors the logic the
* server-side alert-rules engine uses, but for at-a-glance rendering on
* the list itself.
*/
const SILENT_DAYS_THRESHOLD = 7;
const EOI_AWAITING_DAYS_THRESHOLD = 14;
const DEPOSIT_PENDING_DAYS_THRESHOLD = 21;
const ACTIVE_MID_FUNNEL_STAGES = new Set(['details_sent', 'in_communication']);
export interface InterestUrgencyInput {
pipelineStage: string;
outcome?: string | null;
archivedAt?: string | null;
dateLastContact?: string | null;
updatedAt?: string;
dateEoiSent?: string | null;
eoiStatus?: string | null;
dateDepositReceived?: string | null;
}
export interface UrgencyBadge {
/** Stable id for keying. */
id: 'silent' | 'eoi_awaiting' | 'deposit_pending';
label: string;
/** Long form for tooltip / aria-label. */
detail: string;
/** Tailwind classes for the pill. */
className: string;
}
function daysSince(iso: string | null | undefined): number | null {
if (!iso) return null;
const t = new Date(iso).getTime();
if (Number.isNaN(t)) return null;
return Math.floor((Date.now() - t) / 86_400_000);
}
export function computeUrgencyBadges(row: InterestUrgencyInput): UrgencyBadge[] {
// Closed / archived interests don't need triage signals.
if (row.archivedAt || row.outcome) return [];
const badges: UrgencyBadge[] = [];
// Silent in mid-funnel stages — most actionable.
if (ACTIVE_MID_FUNNEL_STAGES.has(row.pipelineStage)) {
const lastTouchIso = row.dateLastContact ?? row.updatedAt ?? null;
const days = daysSince(lastTouchIso);
if (days !== null && days >= SILENT_DAYS_THRESHOLD) {
badges.push({
id: 'silent',
label: `Silent ${days}d`,
detail: `No contact in ${days} days`,
className: 'bg-amber-100 text-amber-800 border border-amber-200',
});
}
}
// EOI sent but not signed for too long.
if (row.eoiStatus === 'waiting_for_signatures') {
const days = daysSince(row.dateEoiSent);
if (days !== null && days >= EOI_AWAITING_DAYS_THRESHOLD) {
badges.push({
id: 'eoi_awaiting',
label: `EOI ${days}d`,
detail: `EOI awaiting signature for ${days} days`,
className: 'bg-orange-100 text-orange-800 border border-orange-200',
});
}
}
// EOI signed but deposit not received.
if (row.pipelineStage === 'eoi_signed' && !row.dateDepositReceived && row.dateEoiSent) {
const days = daysSince(row.dateEoiSent);
if (days !== null && days >= DEPOSIT_PENDING_DAYS_THRESHOLD) {
badges.push({
id: 'deposit_pending',
label: `Deposit ${days}d`,
detail: `Awaiting deposit for ${days} days since EOI sent`,
className: 'bg-rose-100 text-rose-800 border border-rose-200',
});
}
}
return badges;
}

View File

@@ -0,0 +1,84 @@
'use client';
import { useEffect } from 'react';
import { toast } from 'sonner';
import { useSocket } from '@/providers/socket-provider';
import { stageLabel } from '@/lib/constants';
/**
* App-wide subscriber that surfaces high-signal sales events as sonner
* toasts. Mounted once inside SocketProvider so reps see "EOI signed",
* "Deposit recorded", "Stage advanced" without having to refresh.
*
* Render-only — no children. Intentionally narrow in scope: only toast on
* events that are noteworthy *to a user staring at any page*. Per-page
* cache invalidations stay in `useRealtimeInvalidation`.
*/
export function RealtimeToasts() {
const socket = useSocket();
useEffect(() => {
if (!socket) return;
function onStageChanged(payload: {
newStage?: string;
oldStage?: string | null;
clientName?: string;
}) {
if (!payload?.newStage) return;
const who = payload.clientName?.trim() || 'an interest';
toast.success(`${who}${stageLabel(payload.newStage)}`, {
description: payload.oldStage
? `Advanced from ${stageLabel(payload.oldStage)}.`
: 'Pipeline stage advanced.',
});
}
function onDocumentCompleted(payload: { type?: string }) {
// Kick a generic "fully signed" — the type-specific message is
// friendlier when we can identify it as an EOI.
if (payload?.type === 'eoi') {
toast.success('EOI fully signed', {
description: 'All required signatures received.',
});
} else {
toast.success('Document fully signed');
}
}
function onSignerSigned(payload: { signerName?: string; documentTitle?: string }) {
const who = payload?.signerName?.trim();
const title = payload?.documentTitle?.trim();
if (who && title) {
toast.message(`${who} signed "${title}"`);
} else if (who) {
toast.message(`${who} signed a document`);
} else {
toast.message('Signer added a signature');
}
}
function onOutcomeSet(payload: { outcome?: string }) {
if (!payload?.outcome) return;
const isWon = payload.outcome === 'won';
const label = payload.outcome.replace(/_/g, ' ');
const fn = isWon ? toast.success : toast.message;
fn(`Interest closed — ${label}`);
}
socket.on('interest:stageChanged', onStageChanged);
socket.on('document:completed', onDocumentCompleted);
socket.on('document:signer:signed', onSignerSigned);
socket.on('interest:outcomeSet', onOutcomeSet);
return () => {
socket.off('interest:stageChanged', onStageChanged);
socket.off('document:completed', onDocumentCompleted);
socket.off('document:signer:signed', onSignerSigned);
socket.off('interest:outcomeSet', onOutcomeSet);
};
}, [socket]);
return null;
}

View File

@@ -1,7 +1,8 @@
import { and, desc, eq, inArray, isNull, sql } from 'drizzle-orm'; import { and, desc, eq, inArray, isNull, sql } from 'drizzle-orm';
import { db } from '@/lib/db'; import { db } from '@/lib/db';
import { interests, interestTags } from '@/lib/db/schema/interests'; import { interests, interestTags, interestNotes } from '@/lib/db/schema/interests';
import { reminders } from '@/lib/db/schema/operations';
import { clients, clientAddresses, clientContacts } from '@/lib/db/schema/clients'; import { clients, clientAddresses, clientContacts } from '@/lib/db/schema/clients';
import { berths } from '@/lib/db/schema/berths'; import { berths } from '@/lib/db/schema/berths';
import { yachts } from '@/lib/db/schema/yachts'; import { yachts } from '@/lib/db/schema/yachts';
@@ -182,6 +183,11 @@ export async function listInterests(portId: string, query: ListInterestsInput) {
return interests.leadCategory; return interests.leadCategory;
case 'createdAt': case 'createdAt':
return interests.createdAt; return interests.createdAt;
case 'dateLastContact':
// Postgres sorts NULLs last on DESC by default, which is the right
// behaviour for triage (recently-contacted first, never-contacted
// at the bottom).
return interests.dateLastContact;
default: default:
return interests.updatedAt; return interests.updatedAt;
} }
@@ -221,6 +227,7 @@ export async function listInterests(portId: string, query: ListInterestsInput) {
let clientsMap: Record<string, string> = {}; let clientsMap: Record<string, string> = {};
let berthsMap: Record<string, string> = {}; let berthsMap: Record<string, string> = {};
const tagsByInterestId: Record<string, Array<{ id: string; name: string; color: string }>> = {}; const tagsByInterestId: Record<string, Array<{ id: string; name: string; color: string }>> = {};
const notesCountByInterestId: Record<string, number> = {};
if (clientIds.length > 0) { if (clientIds.length > 0) {
const clientRows = await db const clientRows = await db
@@ -254,6 +261,19 @@ export async function listInterests(portId: string, query: ListInterestsInput) {
if (!tagsByInterestId[row.interestId]) tagsByInterestId[row.interestId] = []; if (!tagsByInterestId[row.interestId]) tagsByInterestId[row.interestId] = [];
tagsByInterestId[row.interestId]!.push({ id: row.id, name: row.name, color: row.color }); tagsByInterestId[row.interestId]!.push({ id: row.id, name: row.name, color: row.color });
} }
// Note counts per interest, for the comment-icon row affordance.
const noteCountRows = await db
.select({
interestId: interestNotes.interestId,
count: sql<number>`count(*)::int`,
})
.from(interestNotes)
.where(inArray(interestNotes.interestId, interestIds))
.groupBy(interestNotes.interestId);
for (const row of noteCountRows) {
notesCountByInterestId[row.interestId] = row.count;
}
} }
const data = (result.data as Array<Record<string, unknown>>).map((i) => ({ const data = (result.data as Array<Record<string, unknown>>).map((i) => ({
@@ -261,6 +281,7 @@ export async function listInterests(portId: string, query: ListInterestsInput) {
clientName: clientsMap[i.clientId as string] ?? null, clientName: clientsMap[i.clientId as string] ?? null,
berthMooringNumber: i.berthId ? (berthsMap[i.berthId as string] ?? null) : null, berthMooringNumber: i.berthId ? (berthsMap[i.berthId as string] ?? null) : null,
tags: tagsByInterestId[i.id as string] ?? [], tags: tagsByInterestId[i.id as string] ?? [],
notesCount: notesCountByInterestId[i.id as string] ?? 0,
})); }));
return { data, total: result.total }; return { data, total: result.total };
@@ -328,6 +349,34 @@ export async function getInterestById(id: string, portId: string) {
.innerJoin(tags, eq(interestTags.tagId, tags.id)) .innerJoin(tags, eq(interestTags.tagId, tags.id))
.where(eq(interestTags.interestId, id)); .where(eq(interestTags.interestId, id));
// Most-recent note preview for the Overview tab (the "do you have anything
// outstanding on this lead?" peek). Returns the latest note's truncated
// content + author/timestamp so the UI can render a one-line teaser.
const [recentNote] = await db
.select({
id: interestNotes.id,
content: interestNotes.content,
authorId: interestNotes.authorId,
createdAt: interestNotes.createdAt,
})
.from(interestNotes)
.where(eq(interestNotes.interestId, id))
.orderBy(desc(interestNotes.createdAt))
.limit(1);
const [{ count: notesCount } = { count: 0 }] = await db
.select({ count: sql<number>`count(*)::int` })
.from(interestNotes)
.where(eq(interestNotes.interestId, id));
// Active reminder count for the interest's bell badge. Counts reminders
// directly linked via interestId — `pending` and `snoozed` only;
// completed/dismissed don't surface.
const [{ count: activeReminderCount } = { count: 0 }] = await db
.select({ count: sql<number>`count(*)::int` })
.from(reminders)
.where(and(eq(reminders.interestId, id), inArray(reminders.status, ['pending', 'snoozed'])));
return { return {
...interest, ...interest,
clientName: clientRow?.fullName ?? null, clientName: clientRow?.fullName ?? null,
@@ -337,6 +386,9 @@ export async function getInterestById(id: string, portId: string) {
clientHasAddress: !!addressRow, clientHasAddress: !!addressRow,
berthMooringNumber, berthMooringNumber,
tags: tagRows, tags: tagRows,
notesCount,
recentNote: recentNote ?? null,
activeReminderCount,
}; };
} }