9 Commits

Author SHA1 Message Date
Matt Ciaccio
80fc5932be chore: ignore tooling caches, scratch screenshots, sister website project
Three categories added to .gitignore:

  Tool caches / runtime state:
    .claude/                — Claude Code session state + lock files
                              (scheduled_tasks.lock untracked here)
    .serena/                — Serena MCP project cache
    ruvector.db             — RuVector AgentDB binary

  Scratch screenshots:
    /*.jpg                  — debug captures dropped at repo root
    /.audit-screenshots/    — UX audit run output (regenerable)

  Sister project:
    /website/               — separate Nuxt marketing site, kept on disk
                              for reference but not tracked in this repo

The single tracked file in .claude/ (scheduled_tasks.lock) is removed
from the index here; future dev sessions won't bring it back.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-03 16:17:13 +02:00
Matt Ciaccio
b26b87b2fa chore(dev): react-grab viewport sync helper for in-page debug toolbar
Mounts a dev-only client component that syncs the react-grab debug
toolbar's pinned edge / collapsed state across viewport changes (so
the toolbar doesn't drift off-screen when resizing or rotating).

Render is gated by NODE_ENV === 'development' in src/app/layout.tsx;
production builds tree-shake the import out via process.env replacement.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-03 16:15:47 +02:00
Matt Ciaccio
88f76b6b04 feat(mobile): rework bottom nav (Dashboard/Berths/Clients/Documents/More)
Old order  : Dashboard / Clients / Yachts  / Berths    / More
New order  : Dashboard / Berths  / Clients / Documents / More

Reasoning (also captured as in-file comments above each tab list):
  - Yachts is asset-record traffic — rarely browsed standalone, almost
    always reached from inside an interest or client. Pulled out of the
    bottom row, kept available in the More sheet.
  - Documents (signature tracking / EOI queue) earns a slot at the
    bottom because reps chase signers as a daily activity.
  - Interests is intentionally NOT in the bottom row: having both
    Clients and Interests as peer tabs created a Clients-vs-Interests
    confusion for sales reps. The new per-client Interests tab + the
    bottom-sheet drawer (see ClientInterestsTab) cover the day-to-day
    deal review without needing a dedicated bottom-nav peer.
  - Clients moves to the center: it's the primary mental anchor for
    "find this person", with everything else (yachts, companies,
    interests) reached as a tab on the client detail page.

More-sheet reorder mirrors the new priority: Interests / Yachts /
Companies first (most-likely overflow targets), then financial
(Invoices, Expenses), then Email / Alerts / Reports / Reminders /
Settings / Admin. Documents removed from the More sheet (now in
the bottom row).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-03 16:15:37 +02:00
Matt Ciaccio
a32f41b91d fix(dashboard): scope h-full to xl + tighter mobile sizing on KPIs
The Alerts rail and Reminders rail were using h-full unconditionally, which
worked at xl: where the dashboard grid pairs them with a sibling chart
column, but produced weirdly stretched empty cards in the single-column
mobile stack (no fixed-height context to fill).

  alert-rail / my-reminders-rail: h-full -> xl:h-full

KPI tiles + skeleton rendered the same desktop padding (p-5) and font sizes
on phone, leaving the value cramped against a wide white frame. Tighter
mobile defaults that scale up at sm:

  KPITile      p-3 sm:p-5, label text-[10px] sm:text-xs,
               value mt-1 text-lg sm:mt-2 sm:text-2xl, value truncates
  KpiTileSkeleton: matching p-3 sm:p-5 + smaller skeleton bars on mobile

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-03 16:15:20 +02:00
Matt Ciaccio
cf1c8b66db feat(client): phone-edit row dilation + mobile contacts layout
InlinePhoneField now lays the country picker + number on top, with Save +
Cancel buttons on a second line — the previous single-line cluster was
cramped at every viewport size and broke entirely below ~480px.

A new onEditingChange callback notifies the parent when the field enters
edit mode, so contact rows can react. ContactsEditor uses it to "dilate"
the row visually: lift out of the muted baseline with a soft primary
ring + slightly brighter surface + bumped padding. Single visual signal
replaces the need for any "now editing" label, and the dilation also
hides the noisy chip cluster (label / star / trash) that would otherwise
fight the editor for space.

Mobile improvements applied at the same time:
  - Each row stacks value editor on top, action cluster below at <sm
  - Action cluster ("Add tag" + Make-primary star + trash) uses
    justify-end on the new row so it doesn't collide with the picker
  - Trash icon stays opacity-0/group-hover on desktop but is always
    visible on touch (no hover state on touch) — sm:opacity-0 +
    sm:group-hover:opacity-100 instead of the prior unconditional fade
  - NewContactForm wraps onto multiple lines below sm (basis-full on
    the value field) so the channel picker, value, label, and buttons
    each get usable width

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-03 16:15:07 +02:00
Matt Ciaccio
596476280d feat(ui): inline-edit dropdowns auto-open + auto-exit on dismiss
When a user clicks an inline-edit affordance for country / timezone /
subdivision, the field flipped to its combobox trigger but the popover
didn't open — they had to click again. And if they dismissed the popover
without picking, the field stayed in edit mode showing a "Select country…"
trigger they couldn't get out of.

Combobox primitives (country / timezone / subdivision) now accept:
  - defaultOpen — open on first render
  - onOpenChange — fired on every open/close transition

InlineCountryField / InlineTimezoneField / and the country + subdivision
fields inside addresses-editor pass defaultOpen=true and use onOpenChange
to auto-exit edit mode when the popover closes without a selection. A
pickedRef gate prevents the close-handler from racing the commit() exit
when the user does pick a value.

Bonus: addresses-editor now renders a flag emoji next to the country name
in the read-only state (regional-indicator pair from the ISO code).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-03 16:14:51 +02:00
Matt Ciaccio
e9359fc431 feat(client): interests tab + pipeline summary panel + list-row counts
Promotes interests from a stub tab to a first-class surface on the client
detail page, and surfaces pipeline activity in two more places:

UI:
  - New ClientInterestsTab (475 lines) — table of every active interest
    for the client with stage-stepper visualization, lead category, source,
    last-activity timestamp, and a drawer-on-tap row preview.
  - New OverviewTab pipeline-summary panel above the existing 2-column
    layout, rendering ClientPipelineSummary (already on this branch) in
    its panel variant. Reps see the live pipeline at a glance without
    leaving Overview.
  - Removes "Preferred Language" inline field from the Overview tab and
    the create form — unused, and the field added noise without driving
    any downstream behavior.
  - Tab order: Overview / Interests / Yachts / Companies / ... (Interests
    moves up from the back of the list, where it was a stub anyway).

Data:
  - listClients now returns interestCount + latestInterest{stage, mooring}
    per row, joined from interests + berths in two parallel queries.
    ClientRow type updated to surface them; Client list views can now
    render "3 interests · last on D-02 (EOI Signed)" without a per-row
    fetch.
  - Contact rows in client detail now expose valueE164 + valueCountry to
    the UI (already returned by the API; just wasn't typed through the
    detail-page contract).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-03 16:14:37 +02:00
Matt Ciaccio
4767caec01 feat(client): redesign detail header with action chips + condensed meta
Replaces the inline "Source · email · phone" text strip with three primary
action chips and a smaller meta line:

  Mail / Call / WhatsApp action buttons surface the most-used outbound
  contacts on a single tap. WhatsApp deep-link strips the leading + from
  the canonical E.164 number (or falls back to digit-only of the value).

  Meta line now reads "Country · Added MMM d, yyyy" using nationalityIso
  resolved through getCountryName(); date-fns formats createdAt.

  Portal Invite + GDPR Export buttons remain available but only render
  on sm+; on mobile they're reachable through the More sheet.

  Archive / Restore is now a small icon button in the top-right corner
  rather than a labeled button competing with the primary action chips.
  Destructive intent stays out of the main action flow; hover swaps to
  destructive color for archive (and stays neutral for restore).

The previous source/preferred-contact-method/preferred-language/timezone
fields no longer render in the header — they live on the Overview tab via
the inline editor pattern (see client-tabs.tsx).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-03 16:14:19 +02:00
Matt Ciaccio
49d92234dd fix(test): align stage names with consolidated pipeline enum
Followup to 886119c (refactor(sales): consolidate pipeline stages) — the
runtime enum was renamed but a few test fixtures and PDF report templates
still referenced the legacy names, leaving them broken at the type level
(36 tsc errors before this fix).

Renames in this commit:
  visited        -> in_communication (alerts test) / removed (PDF reports)
  signed_eoi_nda -> eoi_signed
  contract       -> contract_signed (interests test) / contract_sent (factory)

Affected files: pipeline-report, revenue-report, makeCreateInterestInput
factory, alerts-engine, pipeline-transitions, interest-scoring.

Verification: tsc clean, 858/858 vitest passing.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-03 16:14:04 +02:00
31 changed files with 1128 additions and 293 deletions

View File

@@ -1 +0,0 @@
{"sessionId":"fd05cbd7-d695-4a70-9223-4b25f3369829","pid":88534,"acquiredAt":1776866083076}

10
.gitignore vendored
View File

@@ -28,9 +28,19 @@ docker-compose.override.yml
# Ad-hoc screenshots / scratch artifacts at repo root
/*.png
/*.jpg
# Legacy Nuxt portal — kept on disk for reference, not tracked here
/client-portal/
# Sister marketing site — separate Nuxt project, not part of CRM tracking
/website/
# Mobile audit screenshots — generated locally, regenerable
/.audit/
/.audit-screenshots/
# Tool caches / runtime state
/.claude/
/.serena/
/ruvector.db

View File

@@ -4,6 +4,7 @@ import { headers } from 'next/headers';
import { Inter, JetBrains_Mono } from 'next/font/google';
import { Toaster } from 'sonner';
import { classifyFormFactor } from '@/lib/form-factor';
import { ReactGrabViewportSync } from '@/components/dev/react-grab-viewport-sync';
import './globals.css';
const inter = Inter({
@@ -66,6 +67,7 @@ export default async function RootLayout({ children }: { children: React.ReactNo
>
{children}
<Toaster richColors position="top-right" />
{process.env.NODE_ENV === 'development' && <ReactGrabViewportSync />}
</body>
</html>
);

View File

@@ -22,7 +22,11 @@ export function AlertRail() {
<section
data-testid="alert-rail"
aria-label="Active alerts"
className="flex h-full flex-col gap-3"
// `h-full` is intentional only at xl: where the parent dashboard grid
// gives this rail a sibling column whose height it should match. On
// mobile (single-column stack) there's no fixed-height context, so
// forcing 100% height makes the section overflow / look stretched.
className="flex flex-col gap-3 xl:h-full"
>
<div className="flex items-baseline justify-between">
<h2 className="text-sm font-semibold tracking-tight">Alerts</h2>

View File

@@ -25,6 +25,8 @@ export interface ClientRow {
createdAt: string;
yachtCount?: number;
companyCount?: number;
interestCount?: number;
latestInterest?: { stage: string; mooringNumber: string | null } | null;
contacts?: Array<{ channel: string; value: string; isPrimary: boolean }>;
tags?: Array<{ id: string; name: string; color: string }>;
}

View File

@@ -2,7 +2,8 @@
import { useState } from 'react';
import { useMutation, useQueryClient } from '@tanstack/react-query';
import { Archive, RotateCcw, Mail, Phone } from 'lucide-react';
import { Archive, Mail, MessageCircle, Phone, RotateCcw } from 'lucide-react';
import { format } from 'date-fns';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
@@ -12,31 +13,28 @@ import { DetailHeaderStrip } from '@/components/shared/detail-header-strip';
import { PortalInviteButton } from '@/components/clients/portal-invite-button';
import { GdprExportButton } from '@/components/clients/gdpr-export-button';
import { apiFetch } from '@/lib/api/client';
import { cn } from '@/lib/utils';
import { getCountryName } from '@/lib/i18n/countries';
interface ClientDetailHeaderProps {
client: {
id: string;
fullName: string;
nationality?: string | null;
preferredContactMethod?: string | null;
preferredLanguage?: string | null;
timezone?: string | null;
source?: string | null;
sourceDetails?: string | null;
nationalityIso?: string | null;
archivedAt?: string | null;
contacts?: Array<{ channel: string; value: string; isPrimary: boolean; label?: string | null }>;
createdAt?: string;
contacts?: Array<{
channel: string;
value: string;
valueE164?: string | null;
isPrimary: boolean;
label?: string | null;
}>;
tags?: Array<{ id: string; name: string; color: string }>;
clientPortalEnabled?: boolean;
};
}
const SOURCE_LABELS: Record<string, string> = {
website: 'Website',
manual: 'Manual',
referral: 'Referral',
broker: 'Broker',
};
export function ClientDetailHeader({ client }: ClientDetailHeaderProps) {
const queryClient = useQueryClient();
const [archiveOpen, setArchiveOpen] = useState(false);
@@ -62,19 +60,34 @@ export function ClientDetailHeader({ client }: ClientDetailHeaderProps) {
});
const primaryEmail =
client.contacts?.find((c) => c.channel === 'email' && c.isPrimary) ??
client.contacts?.find((c) => c.channel === 'email');
const primaryPhone =
client.contacts?.find((c) => c.channel === 'email' && c.isPrimary)?.value ??
client.contacts?.find((c) => c.channel === 'email')?.value;
const primaryPhoneContact =
client.contacts?.find((c) => c.channel === 'phone' && c.isPrimary) ??
client.contacts?.find((c) => c.channel === 'phone');
const primaryPhone = primaryPhoneContact?.value;
// wa.me requires the E.164 number without the leading "+". Strip from the
// canonical E.164 form when available; otherwise strip non-digits from the
// display value as a best-effort fallback.
const whatsappNumber = primaryPhoneContact?.valueE164
? primaryPhoneContact.valueE164.replace(/^\+/, '')
: primaryPhoneContact?.value
? primaryPhoneContact.value.replace(/[^\d]/g, '')
: null;
const country = client.nationalityIso ? getCountryName(client.nationalityIso, 'en') : null;
const addedLabel = client.createdAt
? `Added ${format(new Date(client.createdAt), 'MMM d, yyyy')}`
: null;
const meta = [country, addedLabel].filter(Boolean) as string[];
return (
<>
<DetailHeaderStrip>
<div className="flex items-start gap-3 flex-wrap">
<div className="flex-1 min-w-0">
<div className="flex items-start gap-3">
<div className="min-w-0 flex-1 space-y-2">
<div className="flex items-center gap-2 flex-wrap">
<h1 className="hidden sm:block text-2xl font-bold text-foreground truncate">
<h1 className="truncate text-lg font-bold text-foreground sm:text-2xl">
{client.fullName}
</h1>
{isArchived && (
@@ -84,31 +97,71 @@ export function ClientDetailHeader({ client }: ClientDetailHeaderProps) {
)}
</div>
<div className="flex items-center gap-4 mt-2 flex-wrap text-sm text-muted-foreground">
{client.source && (
<span>
Source:{' '}
<span className="text-foreground">
{SOURCE_LABELS[client.source] ?? client.source}
</span>
</span>
)}
{primaryEmail && (
<span className="flex items-center gap-1">
<Mail className="h-3.5 w-3.5" />
{primaryEmail.value}
</span>
)}
{primaryPhone && (
<span className="flex items-center gap-1">
<Phone className="h-3.5 w-3.5" />
{primaryPhone.value}
</span>
)}
{meta.length > 0 ? (
<p className="text-xs text-muted-foreground sm:text-sm">{meta.join(' · ')}</p>
) : null}
<div className="flex flex-wrap items-center gap-1.5 pt-1">
{primaryEmail ? (
<Button
asChild
variant="outline"
size="sm"
className="h-8 gap-1.5 px-2.5 [&_svg]:size-3.5"
>
<a href={`mailto:${primaryEmail}`} aria-label={`Email ${primaryEmail}`}>
<Mail />
Email
</a>
</Button>
) : null}
{primaryPhone ? (
<Button
asChild
variant="outline"
size="sm"
className="h-8 gap-1.5 px-2.5 [&_svg]:size-3.5"
>
<a href={`tel:${primaryPhone}`} aria-label={`Call ${primaryPhone}`}>
<Phone />
Call
</a>
</Button>
) : null}
{whatsappNumber ? (
<Button
asChild
variant="outline"
size="sm"
className="h-8 gap-1.5 px-2.5 [&_svg]:size-3.5"
>
<a
href={`https://wa.me/${whatsappNumber}`}
target="_blank"
rel="noopener noreferrer"
aria-label={`Message ${primaryPhone} on WhatsApp`}
>
<MessageCircle />
WhatsApp
</a>
</Button>
) : null}
{!isArchived && client.clientPortalEnabled !== false ? (
<div className="hidden sm:inline-flex">
<PortalInviteButton
clientId={client.id}
clientName={client.fullName}
defaultEmail={primaryEmail}
/>
</div>
) : null}
<div className="hidden sm:inline-flex">
<GdprExportButton clientId={client.id} />
</div>
</div>
{client.tags && client.tags.length > 0 && (
<div className="flex flex-wrap gap-1 mt-2">
<div className="flex flex-wrap gap-1">
{client.tags.map((tag) => (
<TagBadge key={tag.id} name={tag.name} color={tag.color} />
))}
@@ -116,34 +169,21 @@ export function ClientDetailHeader({ client }: ClientDetailHeaderProps) {
)}
</div>
{/* Actions */}
<div className="flex flex-wrap items-center gap-2">
{!isArchived && client.clientPortalEnabled !== false && (
<PortalInviteButton
clientId={client.id}
clientName={client.fullName}
defaultEmail={primaryEmail?.value}
/>
{/* Top-right: archive/restore as a small icon button — destructive
action sits out of the primary action flow. */}
<button
type="button"
onClick={() => setArchiveOpen(true)}
aria-label={isArchived ? 'Restore client' : 'Archive client'}
title={isArchived ? 'Restore client' : 'Archive client'}
className={cn(
'shrink-0 rounded-md p-1.5 text-muted-foreground/70 transition-colors',
'hover:bg-foreground/5 hover:text-foreground',
isArchived ? 'hover:text-foreground' : 'hover:text-destructive',
)}
<GdprExportButton clientId={client.id} />
<Button
variant={isArchived ? 'outline' : 'outline'}
size="sm"
onClick={() => setArchiveOpen(true)}
>
{isArchived ? (
<>
<RotateCcw className="mr-1.5 h-3.5 w-3.5" />
Restore
</>
) : (
<>
<Archive className="mr-1.5 h-3.5 w-3.5" />
Archive
</>
)}
</Button>
</div>
>
{isArchived ? <RotateCcw className="size-4" /> : <Archive className="size-4" />}
</button>
</div>
</DetailHeaderStrip>

View File

@@ -29,6 +29,8 @@ interface ClientData {
id: string;
channel: string;
value: string;
valueE164: string | null;
valueCountry: string | null;
label: string | null;
isPrimary: boolean;
notes: string | null;

View File

@@ -339,10 +339,6 @@ export function ClientForm({ open, onOpenChange, client }: ClientFormProps) {
</SelectContent>
</Select>
</div>
<div className="space-y-1">
<Label>Preferred Language</Label>
<Input {...register('preferredLanguage')} placeholder="English" />
</div>
<div className="space-y-1">
<Label>Timezone</Label>
<TimezoneCombobox

View File

@@ -0,0 +1,460 @@
'use client';
import { useState } from 'react';
import Link from 'next/link';
import { useParams } from 'next/navigation';
import type { Route } from 'next';
import { useQuery } from '@tanstack/react-query';
import { format, formatDistanceToNowStrict } from 'date-fns';
import { ArrowRight, CheckCircle2, ChevronRight, Circle, Plus } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { EmptyState } from '@/components/shared/empty-state';
import { Skeleton } from '@/components/ui/skeleton';
import { Drawer, DrawerContent, DrawerHeader, DrawerTitle } from '@/components/shared/drawer';
import { apiFetch } from '@/lib/api/client';
import { PIPELINE_STAGES, type PipelineStage } from '@/lib/constants';
import { cn } from '@/lib/utils';
import { STAGE_BADGE, STAGE_LABELS, safeStage } from '@/components/clients/pipeline-constants';
import {
StageStepper,
useClientInterests,
type ClientInterestRow,
} from '@/components/clients/client-pipeline-summary';
import { InterestForm } from '@/components/interests/interest-form';
const LEAD_CATEGORY_LABELS: Record<string, string> = {
general_interest: 'General interest',
specific_qualified: 'Specific qualified',
hot_lead: 'Hot lead',
};
function InterestRowItem({
interest,
onOpen,
}: {
interest: ClientInterestRow;
onOpen: (i: ClientInterestRow) => void;
}) {
const stage = safeStage(interest.pipelineStage);
const berthLabel = interest.berthMooringNumber
? `Berth ${interest.berthMooringNumber}`
: 'General interest';
const yachtLabel = interest.yachtName ?? null;
return (
// Tap opens a bottom-sheet preview drawer rather than navigating to the
// full interest page. The drawer covers ~80% of mobile interactions
// ("what stage is this at, when did we last touch it"). For deeper
// edits the drawer has an "Open full page" CTA.
<button
type="button"
onClick={() => onOpen(interest)}
className={cn(
'group block w-full rounded-xl border border-border bg-card p-4 text-left shadow-sm transition-all',
'hover:border-border/70 hover:shadow-md',
)}
>
<div className="flex items-start justify-between gap-3">
<div className="min-w-0 flex-1">
<div className="flex items-center gap-2 flex-wrap">
<h3 className="truncate text-base font-semibold tracking-tight text-foreground">
{berthLabel}
</h3>
<span
className={cn(
'shrink-0 rounded-full px-2 py-0.5 text-[11px] font-medium',
STAGE_BADGE[stage],
)}
>
{STAGE_LABELS[stage]}
</span>
</div>
{yachtLabel ? (
<p className="mt-0.5 truncate text-xs text-muted-foreground">{yachtLabel}</p>
) : null}
</div>
<ChevronRight className="size-4 shrink-0 text-muted-foreground transition-transform group-hover:translate-x-0.5" />
</div>
<div className="mt-3">
<StageStepper current={stage} />
</div>
</button>
);
}
function lastActivityFor(interest: ClientInterestRow): string | null {
const candidates = [interest.dateLastContact, interest.updatedAt]
.filter((v): v is string => Boolean(v))
.map((v) => new Date(v).getTime())
.filter((t) => !Number.isNaN(t));
if (candidates.length === 0) return null;
return `${formatDistanceToNowStrict(new Date(Math.max(...candidates)))} ago`;
}
/** Full interest record returned by `/api/v1/interests/[id]`. Only the fields
* the drawer actually reads are typed here; the API returns more. */
interface InterestDetail {
id: string;
pipelineStage: string;
leadCategory: string | null;
source: string | null;
notes: string | null;
dateLastContact: string | null;
dateEoiSent: string | null;
dateEoiSigned: string | null;
dateDepositReceived: string | null;
dateContractSent: string | null;
dateContractSigned: string | null;
}
function useInterestDetail(id: string | null) {
return useQuery<{ data: InterestDetail }>({
queryKey: ['interest-detail-drawer', id],
queryFn: () => apiFetch<{ data: InterestDetail }>(`/api/v1/interests/${id}`),
enabled: id !== null,
// Detail rarely changes during a single drawer-open session; stale-time
// keeps re-opens snappy without preventing background refetch.
staleTime: 30_000,
});
}
/** Format a date-only or ISO timestamp as e.g. "Apr 8, 2026". Returns null for
* empty input so callers can render an "empty" state. */
function formatDate(value: string | null | undefined): string | null {
if (!value) return null;
const d = new Date(value);
if (Number.isNaN(d.getTime())) return null;
return format(d, 'MMM d, yyyy');
}
/** A single milestone row inside the drawer's milestone summary. Filled
* circle when the step is done, hollow when pending. Trailing meta line
* shows the date stamp or a "pending" hint. */
function MilestoneRow({
label,
done,
date,
hint = 'pending',
}: {
label: string;
done: boolean;
date: string | null;
hint?: string;
}) {
return (
<li className="flex items-center gap-2 py-1">
{done ? (
<CheckCircle2 className="size-4 shrink-0 text-emerald-600" aria-hidden />
) : (
<Circle className="size-4 shrink-0 text-muted-foreground/40" aria-hidden />
)}
<span className={cn('flex-1 text-sm', done ? 'text-foreground' : 'text-muted-foreground')}>
{label}
</span>
<span className="text-xs text-muted-foreground tabular-nums">{date ?? hint}</span>
</li>
);
}
/**
* Bottom-sheet preview of a single interest. Designed for the mobile
* "tap an interest → see what's happening without leaving the client
* page" flow. Shows the pipeline progress, a compact milestone summary
* (EOI / Deposit / Contract), lead context, last contact, and a notes
* teaser. Tap-out / drag-down dismisses; the full edit page is one tap
* away via "Open full page →".
*/
function InterestPreviewDrawer({
interest,
portSlug,
onClose,
}: {
interest: ClientInterestRow | null;
portSlug: string;
onClose: () => void;
}) {
// Pin the most recently selected interest so the drawer stays populated
// during the close-animation tail (Vaul keeps the content mounted ~250ms
// after `open=false`). Conditional setState is safe here — the guard
// ensures it only fires when the prop actually changes to a new row.
const [pinned, setPinned] = useState<ClientInterestRow | null>(interest);
if (interest && interest !== pinned) setPinned(interest);
const showing = pinned;
const detail = useInterestDetail(showing?.id ?? null);
const fullDetail = detail.data?.data ?? null;
const open = interest !== null;
const stage = showing ? safeStage(showing.pipelineStage) : null;
const stageIdx = stage ? PIPELINE_STAGES.indexOf(stage) : -1;
const reached = (target: PipelineStage) =>
stageIdx !== -1 && PIPELINE_STAGES.indexOf(target) <= stageIdx;
const berthLabel = showing
? showing.berthMooringNumber
? `Berth ${showing.berthMooringNumber}`
: 'General interest'
: '';
const yachtLabel = showing?.yachtName ?? null;
const activity = showing ? lastActivityFor(showing) : null;
const fullHref = showing ? (`/${portSlug}/interests/${showing.id}` as Route) : ('/' as Route);
const leadLabel = fullDetail?.leadCategory
? (LEAD_CATEGORY_LABELS[fullDetail.leadCategory] ?? fullDetail.leadCategory)
: null;
const sourceLabel = fullDetail?.source
? fullDetail.source.replace(/\b\w/g, (m) => m.toUpperCase())
: null;
const lastContactDate = formatDate(fullDetail?.dateLastContact);
const notesPreview = fullDetail?.notes?.trim() || null;
return (
<Drawer
open={open}
onOpenChange={(next) => {
if (!next) onClose();
}}
>
<DrawerContent className="max-h-[85vh]">
<DrawerHeader>
<div className="flex items-start justify-between gap-3">
<div className="min-w-0 flex-1">
<DrawerTitle className="truncate">{berthLabel}</DrawerTitle>
{yachtLabel ? (
<p className="mt-0.5 truncate text-sm text-muted-foreground">{yachtLabel}</p>
) : null}
</div>
{stage ? (
<span
className={cn(
'shrink-0 rounded-full px-2.5 py-1 text-xs font-medium',
STAGE_BADGE[stage],
)}
>
{STAGE_LABELS[stage]}
</span>
) : null}
</div>
</DrawerHeader>
<div className="space-y-5 overflow-y-auto px-4 pb-4">
{/* Pipeline-stepper segmented bar — the same primitive used on the
row card, so the at-a-glance progress hint is consistent
across surfaces. */}
{stage ? (
<div>
<p className="mb-1.5 text-xs font-medium uppercase tracking-wide text-muted-foreground">
Pipeline progress
</p>
<StageStepper current={stage} />
</div>
) : null}
{/* Milestones — three sections matching the full interest detail
page (EOI / Deposit / Contract). Done-state is derived from
the pipeline stage so seed data without per-step dates still
renders correctly. The full milestone columns + per-step
actions live behind "Open full page". */}
<section>
<p className="mb-2 text-xs font-medium uppercase tracking-wide text-muted-foreground">
Milestones
</p>
<div className="space-y-3">
<div className="rounded-lg border border-border bg-card/50 p-3">
<p className="mb-1 text-sm font-semibold">EOI</p>
<ul>
<MilestoneRow
label="EOI sent"
done={reached('eoi_sent') || !!fullDetail?.dateEoiSent}
date={formatDate(fullDetail?.dateEoiSent)}
/>
<MilestoneRow
label="EOI signed"
done={reached('eoi_signed') || !!fullDetail?.dateEoiSigned}
date={formatDate(fullDetail?.dateEoiSigned)}
/>
</ul>
</div>
<div className="rounded-lg border border-border bg-card/50 p-3">
<p className="mb-1 text-sm font-semibold">Deposit</p>
<ul>
<MilestoneRow
label="Deposit received"
done={reached('deposit_10pct') || !!fullDetail?.dateDepositReceived}
date={formatDate(fullDetail?.dateDepositReceived)}
/>
</ul>
</div>
<div className="rounded-lg border border-border bg-card/50 p-3">
<p className="mb-1 text-sm font-semibold">Contract</p>
<ul>
<MilestoneRow
label="Contract sent"
done={reached('contract_sent') || !!fullDetail?.dateContractSent}
date={formatDate(fullDetail?.dateContractSent)}
/>
<MilestoneRow
label="Contract signed"
done={reached('contract_signed') || !!fullDetail?.dateContractSigned}
date={formatDate(fullDetail?.dateContractSigned)}
/>
</ul>
</div>
</div>
</section>
{/* Compact key/value pairs — lead category, source, last contact,
activity. Each row collapses cleanly when its value is
missing so the drawer scales from sparse seed data to full
records without empty placeholders. */}
<dl className="grid grid-cols-[max-content_1fr] gap-x-4 gap-y-1.5 text-sm">
{leadLabel ? (
<>
<dt className="text-muted-foreground">Lead</dt>
<dd className="text-right font-medium">{leadLabel}</dd>
</>
) : null}
{sourceLabel ? (
<>
<dt className="text-muted-foreground">Source</dt>
<dd className="text-right font-medium">{sourceLabel}</dd>
</>
) : null}
{lastContactDate ? (
<>
<dt className="text-muted-foreground">Last contact</dt>
<dd className="text-right font-medium">{lastContactDate}</dd>
</>
) : null}
{activity ? (
<>
<dt className="text-muted-foreground">Last activity</dt>
<dd className="text-right font-medium">{activity}</dd>
</>
) : null}
</dl>
{notesPreview ? (
<section>
<p className="mb-1.5 text-xs font-medium uppercase tracking-wide text-muted-foreground">
Notes
</p>
<p className="line-clamp-3 text-sm text-foreground/90 whitespace-pre-wrap">
{notesPreview}
</p>
</section>
) : null}
<Button asChild className="w-full" size="lg">
<Link href={fullHref}>
Open full page
<ArrowRight className="ml-1.5 size-4" aria-hidden />
</Link>
</Button>
</div>
</DrawerContent>
</Drawer>
);
}
function InterestSkeleton() {
return (
<div className="rounded-xl border border-border bg-card p-4 shadow-sm">
<Skeleton className="h-4 w-32" />
<Skeleton className="mt-2 h-3 w-24" />
<Skeleton className="mt-3 h-2 w-48" />
</div>
);
}
interface ClientInterestsTabProps {
clientId: string;
}
export function ClientInterestsTab({ clientId }: ClientInterestsTabProps) {
const routeParams = useParams<{ portSlug: string }>();
const portSlug = routeParams?.portSlug ?? '';
const [createOpen, setCreateOpen] = useState(false);
const [previewInterest, setPreviewInterest] = useState<ClientInterestRow | null>(null);
const { data, isLoading, isError } = useClientInterests(clientId);
if (isLoading) {
return (
<div className="space-y-3">
<InterestSkeleton />
<InterestSkeleton />
</div>
);
}
if (isError) {
return <p className="text-sm text-destructive">Could not load interests for this client.</p>;
}
const interests = data?.data ?? [];
if (interests.length === 0) {
return (
<>
<EmptyState
title="No interests yet"
description="When this client expresses interest in a berth, the sales process will appear here."
action={{
label: 'Add interest',
onClick: () => setCreateOpen(true),
}}
/>
<InterestForm open={createOpen} onOpenChange={setCreateOpen} defaultClientId={clientId} />
</>
);
}
const active = interests.filter((i) => !i.archivedAt);
const archived = interests.filter((i) => i.archivedAt);
return (
<div className="space-y-6">
<div className="flex justify-end">
<Button size="sm" onClick={() => setCreateOpen(true)}>
<Plus className="mr-1.5 size-3.5" />
Add interest
</Button>
</div>
{active.length > 0 ? (
<div className="space-y-3">
{active.map((i) => (
<InterestRowItem key={i.id} interest={i} onOpen={setPreviewInterest} />
))}
</div>
) : null}
{archived.length > 0 ? (
<div className="space-y-3">
<h4 className="text-xs font-medium uppercase tracking-wide text-muted-foreground">
Archived
</h4>
<div className="space-y-3 opacity-60">
{archived.map((i) => (
<InterestRowItem key={i.id} interest={i} onOpen={setPreviewInterest} />
))}
</div>
</div>
) : null}
<InterestPreviewDrawer
interest={previewInterest}
portSlug={portSlug}
onClose={() => setPreviewInterest(null)}
/>
<InterestForm open={createOpen} onOpenChange={setCreateOpen} defaultClientId={clientId} />
</div>
);
}

View File

@@ -9,6 +9,8 @@ import { InlineTimezoneField } from '@/components/shared/inline-timezone-field';
import { InlineTagEditor } from '@/components/shared/inline-tag-editor';
import { NotesList } from '@/components/shared/notes-list';
import type { CountryCode } from '@/lib/i18n/countries';
import { ClientInterestsTab } from '@/components/clients/client-interests-tab';
import { ClientPipelineSummary } from '@/components/clients/client-pipeline-summary';
import { ClientYachtsTab } from '@/components/clients/client-yachts-tab';
import { ClientCompaniesTab } from '@/components/clients/client-companies-tab';
import { ClientReservationsTab } from '@/components/clients/client-reservations-tab';
@@ -131,82 +133,82 @@ function OverviewTab({
};
return (
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
{/* Personal Info */}
<div className="space-y-1">
<h3 className="text-sm font-medium mb-2">Personal Information</h3>
<dl>
<EditableRow label="Full Name">
<InlineEditableField value={client.fullName} onSave={save('fullName')} />
</EditableRow>
<EditableRow label="Nationality">
<InlineCountryField
value={client.nationalityIso ?? null}
onSave={async (iso) => {
await mutation.mutateAsync({ nationalityIso: iso });
}}
data-testid="client-nationality-inline"
/>
</EditableRow>
<EditableRow label="Preferred Language">
<InlineEditableField
value={client.preferredLanguage}
onSave={save('preferredLanguage')}
/>
</EditableRow>
<EditableRow label="Timezone">
<InlineTimezoneField
value={client.timezone}
countryHint={(client.nationalityIso as CountryCode | null) ?? null}
onSave={async (tz) => {
await mutation.mutateAsync({ timezone: tz });
}}
data-testid="client-timezone-inline"
/>
</EditableRow>
<EditableRow label="Preferred Contact">
<InlineEditableField
variant="select"
options={CONTACT_METHOD_OPTIONS}
value={client.preferredContactMethod}
onSave={save('preferredContactMethod')}
/>
</EditableRow>
</dl>
<div className="space-y-6">
<div className="rounded-xl border border-border bg-card p-4 shadow-sm">
<ClientPipelineSummary clientId={clientId} variant="panel" />
</div>
{/* Contacts */}
<div className="space-y-1">
<h3 className="text-sm font-medium mb-2">Contact Details</h3>
<ContactsEditor clientId={clientId} contacts={client.contacts ?? []} />
</div>
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
{/* Personal Info */}
<div className="space-y-1">
<h3 className="text-sm font-medium mb-2">Personal Information</h3>
<dl>
<EditableRow label="Full Name">
<InlineEditableField value={client.fullName} onSave={save('fullName')} />
</EditableRow>
<EditableRow label="Nationality">
<InlineCountryField
value={client.nationalityIso ?? null}
onSave={async (iso) => {
await mutation.mutateAsync({ nationalityIso: iso });
}}
data-testid="client-nationality-inline"
/>
</EditableRow>
<EditableRow label="Timezone">
<InlineTimezoneField
value={client.timezone}
countryHint={(client.nationalityIso as CountryCode | null) ?? null}
onSave={async (tz) => {
await mutation.mutateAsync({ timezone: tz });
}}
data-testid="client-timezone-inline"
/>
</EditableRow>
<EditableRow label="Preferred Contact">
<InlineEditableField
variant="select"
options={CONTACT_METHOD_OPTIONS}
value={client.preferredContactMethod}
onSave={save('preferredContactMethod')}
/>
</EditableRow>
</dl>
</div>
{/* Source */}
<div className="space-y-1">
<h3 className="text-sm font-medium mb-2">Source</h3>
<dl>
<EditableRow label="Source">
<InlineEditableField
variant="select"
options={SOURCE_OPTIONS}
value={client.source}
onSave={save('source')}
/>
</EditableRow>
<EditableRow label="Source Details">
<InlineEditableField value={client.sourceDetails} onSave={save('sourceDetails')} />
</EditableRow>
</dl>
</div>
{/* Contacts */}
<div className="space-y-1">
<h3 className="text-sm font-medium mb-2">Contact Details</h3>
<ContactsEditor clientId={clientId} contacts={client.contacts ?? []} />
</div>
{/* Tags */}
<div className="space-y-1">
<h3 className="text-sm font-medium mb-2">Tags</h3>
<InlineTagEditor
endpoint={`/api/v1/clients/${clientId}/tags`}
currentTags={client.tags ?? []}
invalidateKey={['clients', clientId]}
/>
{/* Source */}
<div className="space-y-1">
<h3 className="text-sm font-medium mb-2">Source</h3>
<dl>
<EditableRow label="Source">
<InlineEditableField
variant="select"
options={SOURCE_OPTIONS}
value={client.source}
onSave={save('source')}
/>
</EditableRow>
<EditableRow label="Source Details">
<InlineEditableField value={client.sourceDetails} onSave={save('sourceDetails')} />
</EditableRow>
</dl>
</div>
{/* Tags */}
<div className="space-y-1">
<h3 className="text-sm font-medium mb-2">Tags</h3>
<InlineTagEditor
endpoint={`/api/v1/clients/${clientId}/tags`}
currentTags={client.tags ?? []}
invalidateKey={['clients', clientId]}
/>
</div>
</div>
</div>
);
@@ -219,6 +221,11 @@ export function getClientTabs({ clientId, currentUserId, client }: ClientTabsOpt
label: 'Overview',
content: <OverviewTab clientId={clientId} client={client} />,
},
{
id: 'interests',
label: 'Interests',
content: <ClientInterestsTab clientId={clientId} />,
},
{
id: 'yachts',
label: 'Yachts',
@@ -251,15 +258,6 @@ export function getClientTabs({ clientId, currentUserId, client }: ClientTabsOpt
/>
),
},
{
id: 'interests',
label: 'Interests',
content: (
<div className="text-center py-12 text-muted-foreground">
<p>Interests will appear here once created.</p>
</div>
),
},
{
id: 'notes',
label: 'Notes',

View File

@@ -155,6 +155,7 @@ function ContactRow({
onRemove: () => void;
}) {
const Icon = CHANNEL_ICONS[contact.channel] ?? MoreHorizontal;
const [phoneEditing, setPhoneEditing] = useState(false);
async function togglePrimary() {
try {
@@ -174,17 +175,31 @@ function ContactRow({
}
return (
<div className="group flex items-center gap-2 p-2 rounded-lg border bg-muted/30 text-sm">
{/* Left: channel + value */}
<div className="flex items-center gap-2 flex-1 min-w-0">
<div
data-editing={phoneEditing ? 'true' : undefined}
className={cn(
'group rounded-lg border text-sm transition-all duration-150',
// Active-edit dilation: lift the row out of the muted baseline with a
// soft primary ring + slightly brighter surface. Single visual signal
// replaces the need for any "now editing" label.
phoneEditing
? 'bg-card border-primary/30 ring-2 ring-primary/15 shadow-sm p-3 gap-3'
: 'bg-muted/30 p-2 gap-2',
// Stack value editor / action cluster on mobile; single row on sm+.
'flex flex-col sm:flex-row sm:items-center',
)}
>
{/* Top / left: channel + value */}
<div className="flex min-w-0 flex-1 items-center gap-2">
<ChannelPicker value={contact.channel} onChange={changeChannel}>
<Icon className="h-3.5 w-3.5 text-muted-foreground" />
</ChannelPicker>
<div className="min-w-0">
<div className="min-w-0 flex-1">
{contact.channel === 'phone' || contact.channel === 'whatsapp' ? (
<InlinePhoneField
e164={contact.valueE164 ?? null}
country={contact.valueCountry ?? null}
onEditingChange={setPhoneEditing}
onSave={async ({ e164, country }) => {
if (!e164) {
toast.error('Phone number is required');
@@ -208,42 +223,46 @@ function ContactRow({
</div>
</div>
{/* Right: tag + actions */}
<div className="flex items-center gap-2 shrink-0">
<div className="w-28 text-xs text-muted-foreground text-right">
<InlineEditableField
value={
contact.label && contact.label.toLowerCase() !== 'primary' ? contact.label : null
}
emptyText="Add tag"
placeholder="work, home…"
onSave={async (v) => {
await onUpdate({ label: v });
}}
/>
{/* Bottom / right: tag + actions. Hidden while the phone editor is active
to keep focus on the form — no chips fighting for space, no noise. */}
{!phoneEditing ? (
<div className="flex shrink-0 items-center justify-end gap-2">
<div className="w-28 text-right text-xs text-muted-foreground">
<InlineEditableField
value={
contact.label && contact.label.toLowerCase() !== 'primary' ? contact.label : null
}
emptyText="Add tag"
placeholder="work, home…"
onSave={async (v) => {
await onUpdate({ label: v });
}}
/>
</div>
<button
type="button"
onClick={togglePrimary}
title={contact.isPrimary ? 'Primary' : 'Make primary'}
className={cn(
'rounded p-1 transition-colors hover:bg-background/60',
contact.isPrimary ? 'text-primary' : 'text-muted-foreground/50',
)}
>
<Star className={cn('h-3.5 w-3.5', contact.isPrimary && 'fill-current')} />
</button>
<button
type="button"
onClick={onRemove}
title="Remove"
// Trash is opacity-0 on desktop hover-only; on touch, always show.
className="rounded p-1 text-muted-foreground/50 transition-all hover:bg-background/60 hover:text-destructive sm:opacity-0 sm:group-hover:opacity-100"
>
<Trash2 className="h-3.5 w-3.5" />
</button>
</div>
<button
type="button"
onClick={togglePrimary}
title={contact.isPrimary ? 'Primary' : 'Make primary'}
className={cn(
'p-1 rounded hover:bg-background/60 transition-colors',
contact.isPrimary ? 'text-primary' : 'text-muted-foreground/50',
)}
>
<Star className={cn('h-3.5 w-3.5', contact.isPrimary && 'fill-current')} />
</button>
<button
type="button"
onClick={onRemove}
title="Remove"
className="p-1 rounded text-muted-foreground/50 hover:text-destructive hover:bg-background/60 opacity-0 group-hover:opacity-100 transition-all"
>
<Trash2 className="h-3.5 w-3.5" />
</button>
</div>
) : null}
</div>
);
}
@@ -330,7 +349,9 @@ function NewContactForm({
const submitDisabled = saving || (isPhoneChannel ? !phoneValue?.e164 : !value.trim());
return (
<div className="flex items-center gap-2 p-2 rounded-lg border bg-muted/30 text-sm">
// Single row on sm+; wraps onto multiple lines below 640px so the channel
// picker, value field, label, and buttons each get their own usable width.
<div className="flex flex-wrap items-center gap-2 rounded-lg border bg-muted/30 p-2 text-sm">
<Select
value={channel}
onValueChange={(next) => {
@@ -353,7 +374,7 @@ function NewContactForm({
</Select>
{isPhoneChannel ? (
<div className="flex-1 min-w-0">
<div className="min-w-0 flex-1 basis-full sm:basis-auto">
<PhoneInput
value={phoneValue}
onChange={(v) => setPhoneValue(v)}
@@ -365,7 +386,7 @@ function NewContactForm({
value={value}
onChange={(e) => setValue(e.target.value)}
placeholder={channel === 'email' ? 'name@example.com' : 'value'}
className="h-7 text-sm flex-1 min-w-0"
className="h-7 min-w-0 flex-1 basis-full text-sm sm:basis-auto"
autoFocus
disabled={saving}
onKeyDown={(e) => {
@@ -382,7 +403,7 @@ function NewContactForm({
value={label}
onChange={(e) => setLabel(e.target.value)}
placeholder="tag (optional)"
className="h-7 text-xs w-28"
className="h-7 w-28 text-xs"
disabled={saving}
onKeyDown={(e) => {
if (e.key === 'Enter') {
@@ -393,12 +414,14 @@ function NewContactForm({
}}
/>
<Button type="button" size="sm" onClick={submit} disabled={submitDisabled}>
{saving ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : 'Save'}
</Button>
<Button type="button" size="sm" variant="ghost" onClick={onCancel} disabled={saving}>
Cancel
</Button>
<div className="ml-auto flex gap-2">
<Button type="button" size="sm" onClick={submit} disabled={submitDisabled}>
{saving ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : 'Save'}
</Button>
<Button type="button" size="sm" variant="ghost" onClick={onCancel} disabled={saving}>
Cancel
</Button>
</div>
</div>
);
}

View File

@@ -28,11 +28,10 @@ function formatPercent(value: number): string {
function KpiTileSkeleton() {
return (
<div className="relative overflow-hidden rounded-xl border border-border bg-card p-5 shadow-sm">
<div className="relative overflow-hidden rounded-xl border border-border bg-card p-3 shadow-sm sm:p-5">
<div className="absolute inset-x-0 top-0 h-1 bg-muted" aria-hidden />
<Skeleton className="h-3 w-24" />
<Skeleton className="mt-3 h-7 w-32" />
<Skeleton className="mt-2 h-3 w-12" />
<Skeleton className="h-3 w-20" />
<Skeleton className="mt-2 h-6 w-24 sm:mt-3 sm:h-7" />
</div>
);
}

View File

@@ -67,8 +67,11 @@ export function MyRemindersRail() {
return `/${portSlug}/reminders`;
}
// `h-full` only at xl: where the dashboard grid pairs this rail with
// a sibling chart column. On mobile (stacked) it produced a weirdly
// tall empty card.
return (
<Card className="h-full">
<Card className="xl: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">

View File

@@ -0,0 +1,104 @@
'use client';
import { useEffect } from 'react';
type Edge = 'top' | 'bottom' | 'left' | 'right';
interface ToolbarState {
edge: Edge;
ratio: number;
collapsed: boolean;
enabled: boolean;
defaultAction?: string;
}
interface ReactGrabAPI {
setToolbarState: (state: Partial<ToolbarState>) => void;
onToolbarStateChange: (cb: (state: ToolbarState) => void) => () => void;
}
declare global {
interface Window {
__REACT_GRAB__?: ReactGrabAPI;
}
}
const MOBILE_QUERY = '(max-width: 1023.98px)';
const DESKTOP_KEY = 'react-grab-toolbar-state-desktop';
const MOBILE_KEY = 'react-grab-toolbar-state-mobile';
const DESKTOP_DEFAULT: Partial<ToolbarState> = {
edge: 'bottom',
ratio: 0.5,
collapsed: false,
};
const MOBILE_DEFAULT: Partial<ToolbarState> = {
edge: 'right',
ratio: 0.5,
collapsed: false,
};
export function ReactGrabViewportSync() {
useEffect(() => {
if (process.env.NODE_ENV !== 'development') return;
const cleanups: Array<() => void> = [];
let pollId: number | undefined;
const wireUp = (api: ReactGrabAPI) => {
const mql = window.matchMedia(MOBILE_QUERY);
const keyFor = () => (mql.matches ? MOBILE_KEY : DESKTOP_KEY);
const defaultFor = () => (mql.matches ? MOBILE_DEFAULT : DESKTOP_DEFAULT);
let suppressNextWrite = false;
const apply = () => {
const stored = localStorage.getItem(keyFor());
suppressNextWrite = true;
api.setToolbarState(stored ? (JSON.parse(stored) as ToolbarState) : defaultFor());
};
apply();
const unsubscribe = api.onToolbarStateChange((state) => {
if (suppressNextWrite) {
suppressNextWrite = false;
return;
}
localStorage.setItem(keyFor(), JSON.stringify(state));
});
mql.addEventListener('change', apply);
cleanups.push(unsubscribe, () => mql.removeEventListener('change', apply));
};
const tryWire = () => {
const api = window.__REACT_GRAB__;
if (!api) return false;
wireUp(api);
return true;
};
if (!tryWire()) {
pollId = window.setInterval(() => {
if (tryWire() && pollId !== undefined) {
window.clearInterval(pollId);
pollId = undefined;
}
}, 100);
window.setTimeout(() => {
if (pollId !== undefined) {
window.clearInterval(pollId);
pollId = undefined;
}
}, 5000);
}
return () => {
if (pollId !== undefined) window.clearInterval(pollId);
cleanups.forEach((fn) => fn());
};
}, []);
return null;
}

View File

@@ -2,7 +2,7 @@
import Link from 'next/link';
import { usePathname } from 'next/navigation';
import { LayoutDashboard, Users, Ship, Anchor, Menu } from 'lucide-react';
import { Anchor, FileSignature, LayoutDashboard, Menu, Users } from 'lucide-react';
import { cn } from '@/lib/utils';
@@ -12,11 +12,27 @@ type TabSpec = {
segment: string; // route segment after /[portSlug]/
};
// Bottom nav ordering, left → right:
// Dashboard — daily overview
// Berths — marina inventory grid (touches sales + ops both)
// Clients — the address book / dedup surface (centered: it's the
// primary mental anchor for "find this person", with
// interests living as a tab on the client detail rather
// than a peer in the bottom nav)
// Documents — signature tracking (chase signers, EOI queue)
// More — overflow drawer (Interests, Yachts, Companies, …)
//
// Interests is intentionally NOT in the bottom row — having both Clients
// and Interests as peer tabs created a Clients-vs-Interests confusion
// for sales reps, and the per-client interests tab + the new bottom-sheet
// drawer cover the day-to-day deal review without needing a dedicated tab.
// Yachts stays out for the same reason as before: it's an asset record
// most often reached from inside an interest or client, not browsed.
const TABS: TabSpec[] = [
{ label: 'Dashboard', icon: LayoutDashboard, segment: 'dashboard' },
{ label: 'Clients', icon: Users, segment: 'clients' },
{ label: 'Yachts', icon: Ship, segment: 'yachts' },
{ label: 'Berths', icon: Anchor, segment: 'berths' },
{ label: 'Clients', icon: Users, segment: 'clients' },
{ label: 'Documents', icon: FileSignature, segment: 'documents' },
];
export function MobileBottomTabs({ onMoreClick }: { onMoreClick: () => void }) {

View File

@@ -3,17 +3,17 @@
import Link from 'next/link';
import { usePathname } from 'next/navigation';
import {
Building2,
Bookmark,
Receipt,
FileText,
FolderOpen,
Mail,
Bell,
ShieldAlert,
BarChart3,
Bell,
Bookmark,
Building2,
FileText,
Mail,
Receipt,
Settings,
Shield,
ShieldAlert,
Ship,
} from 'lucide-react';
import {
@@ -30,12 +30,17 @@ type MoreItem = {
segment: string;
};
// Order: most-likely overflow targets first. Interests is here (rather
// than the bottom row) to dodge the Clients-vs-Interests UX confusion;
// reps reach the active deals via the Interests tab on a client detail
// (or via the new bottom-sheet drawer). Yachts is asset-record traffic
// best reached contextually from inside an interest or client.
const MORE_ITEMS: MoreItem[] = [
{ label: 'Companies', icon: Building2, segment: 'companies' },
{ label: 'Interests', icon: Bookmark, segment: 'interests' },
{ label: 'Yachts', icon: Ship, segment: 'yachts' },
{ label: 'Companies', icon: Building2, segment: 'companies' },
{ label: 'Invoices', icon: FileText, segment: 'invoices' },
{ label: 'Expenses', icon: Receipt, segment: 'expenses' },
{ label: 'Documents', icon: FolderOpen, segment: 'documents' },
{ label: 'Email', icon: Mail, segment: 'email' },
{ label: 'Alerts', icon: ShieldAlert, segment: 'alerts' },
{ label: 'Reports', icon: BarChart3, segment: 'reports' },

View File

@@ -1,6 +1,6 @@
'use client';
import { useState } from 'react';
import { useRef, useState } from 'react';
import { useMutation, useQueryClient } from '@tanstack/react-query';
import { Loader2, MapPin, Plus, Star, Trash2 } from 'lucide-react';
import { toast } from 'sonner';
@@ -225,6 +225,14 @@ function Field({ label, children }: { label: string; children: React.ReactNode }
);
}
/** Regional-indicator emoji flag for an ISO alpha-2 code (e.g. 'FR' → 🇫🇷). */
function flagEmoji(code: string | null | undefined): string {
if (!code || code.length !== 2) return '';
const A = 0x1f1e6;
const a = 'A'.charCodeAt(0);
return String.fromCodePoint(A + code.charCodeAt(0) - a, A + code.charCodeAt(1) - a);
}
function CountryFieldInline({
value,
onSave,
@@ -233,20 +241,34 @@ function CountryFieldInline({
onSave: (iso: string | null) => Promise<void>;
}) {
const [editing, setEditing] = useState(false);
// Tracks whether a value was picked this edit cycle so the open-change
// handler doesn't double-exit while commit is still in flight.
const pickedRef = useRef(false);
if (editing) {
return (
<CountryCombobox
value={value ?? null}
onChange={async (iso) => {
pickedRef.current = true;
setEditing(false);
await onSave(iso ?? null);
}}
clearable
className="w-full"
// Drop the user straight into the picker — no extra click on the
// trigger required.
defaultOpen
onOpenChange={(open) => {
// Auto-exit edit mode when the popover closes without a pick so
// the user isn't stuck staring at a "Select country…" trigger.
if (!open && !pickedRef.current) setEditing(false);
if (open) pickedRef.current = false;
}}
/>
);
}
const display = value ? getCountryName(value, 'en') : null;
const display = value ? `${flagEmoji(value)} ${getCountryName(value, 'en')}` : null;
return (
<button
type="button"
@@ -268,17 +290,25 @@ function SubdivisionFieldInline({
onSave: (code: string | null) => Promise<void>;
}) {
const [editing, setEditing] = useState(false);
const pickedRef = useRef(false);
if (editing) {
return (
<SubdivisionCombobox
value={value ?? null}
country={country}
onChange={async (code) => {
pickedRef.current = true;
setEditing(false);
await onSave(code ?? null);
}}
clearable
className="w-full"
defaultOpen
onOpenChange={(open) => {
if (!open && !pickedRef.current) setEditing(false);
if (open) pickedRef.current = false;
}}
/>
);
}

View File

@@ -30,6 +30,12 @@ interface CountryComboboxProps {
clearable?: boolean;
id?: string;
'data-testid'?: string;
/** Open the dropdown on first render. Used by inline-edit wrappers so the
* user lands directly in the picker after clicking the edit affordance. */
defaultOpen?: boolean;
/** Notified whenever the dropdown opens/closes. Inline-edit wrappers use
* this to auto-exit edit mode when the user dismisses without picking. */
onOpenChange?: (open: boolean) => void;
}
/**
@@ -58,8 +64,14 @@ export function CountryCombobox({
clearable = true,
id,
'data-testid': testId,
defaultOpen = false,
onOpenChange,
}: CountryComboboxProps) {
const [open, setOpen] = useState(false);
const [open, setOpen] = useState(defaultOpen);
const handleOpenChange = (next: boolean) => {
setOpen(next);
onOpenChange?.(next);
};
const effectiveLocale = locale ?? (typeof navigator !== 'undefined' ? navigator.language : 'en');
// Pre-build the options list once per locale change so the cmdk filter
@@ -75,7 +87,7 @@ export function CountryCombobox({
const selected = value ? options.find((o) => o.code === value) : undefined;
return (
<Popover open={open} onOpenChange={setOpen}>
<Popover open={open} onOpenChange={handleOpenChange}>
<PopoverTrigger asChild>
<Button
id={id}

View File

@@ -1,6 +1,6 @@
'use client';
import { useState } from 'react';
import { useRef, useState } from 'react';
import { Loader2, Pencil } from 'lucide-react';
import { toast } from 'sonner';
@@ -31,8 +31,12 @@ export function InlineCountryField({
}: InlineCountryFieldProps) {
const [editing, setEditing] = useState(false);
const [saving, setSaving] = useState(false);
// Set true when the user picks a value from the dropdown, so the
// popover-close handler knows commit() will exit edit mode itself.
const pickedRef = useRef(false);
async function commit(next: CountryCode | null) {
pickedRef.current = true;
if (next === (value ?? null)) {
setEditing(false);
return;
@@ -51,7 +55,23 @@ export function InlineCountryField({
if (editing) {
return (
<div className={cn('flex items-center gap-1', className)}>
<CountryCombobox value={value} onChange={(iso) => void commit(iso)} data-testid={testId} />
<CountryCombobox
value={value}
onChange={(iso) => void commit(iso)}
data-testid={testId}
defaultOpen
onOpenChange={(open) => {
// When the dropdown closes without a selection, leave edit mode
// so the user isn't stuck staring at the trigger button. If a
// pick happened, commit() handles the exit (and may need to keep
// edit mode briefly to show the saving spinner).
if (!open && !pickedRef.current) {
setEditing(false);
}
// Reset for the next open cycle.
if (open) pickedRef.current = false;
}}
/>
{saving && <Loader2 className="h-3 w-3 animate-spin text-muted-foreground" />}
</div>
);

View File

@@ -17,6 +17,12 @@ interface InlinePhoneFieldProps {
/** Falls back to this country if `country` isn't set. */
defaultCountry?: CountryCode;
onSave: (next: { e164: string | null; country: CountryCode }) => Promise<void>;
/**
* Notifies the parent when the field enters/exits edit mode. Lets the row
* dim or hide noise (tag chips, action buttons) while the user is focused
* on the editor.
*/
onEditingChange?: (editing: boolean) => void;
emptyText?: string;
disabled?: boolean;
className?: string;
@@ -28,12 +34,13 @@ export function InlinePhoneField({
country,
defaultCountry,
onSave,
onEditingChange,
emptyText = '—',
disabled,
className,
'data-testid': testId,
}: InlinePhoneFieldProps) {
const [editing, setEditing] = useState(false);
const [editing, setEditingRaw] = useState(false);
const [draft, setDraft] = useState<PhoneInputValue | null>(() => {
if (!e164 && !country) return null;
return {
@@ -43,6 +50,11 @@ export function InlinePhoneField({
});
const [saving, setSaving] = useState(false);
function setEditing(next: boolean) {
setEditingRaw(next);
onEditingChange?.(next);
}
async function commit() {
const next = draft ?? { e164: null, country: defaultCountry ?? 'US' };
if (next.e164 === (e164 ?? null) && next.country === (country ?? null)) {
@@ -62,39 +74,50 @@ export function InlinePhoneField({
if (editing) {
return (
<div className={cn('flex items-center gap-1', className)}>
// Two clean lines: country picker + number on top, action pair below.
<div className={cn('flex w-full flex-col gap-2.5', className)}>
<PhoneInput
value={draft}
onChange={(v) => setDraft(v)}
defaultCountry={defaultCountry}
data-testid={testId}
/>
<button
type="button"
onClick={() => void commit()}
disabled={saving}
className="rounded px-2 py-1 text-xs font-medium hover:bg-muted disabled:opacity-50"
>
{saving ? <Loader2 className="h-3 w-3 animate-spin" /> : 'Save'}
</button>
<button
type="button"
onClick={() => {
setDraft(
e164 || country
? {
e164: e164 ?? null,
country: (country as CountryCode | null) ?? defaultCountry ?? 'US',
}
: null,
);
setEditing(false);
}}
disabled={saving}
className="rounded px-2 py-1 text-xs text-muted-foreground hover:bg-muted disabled:opacity-50"
>
Cancel
</button>
<div className="flex items-center justify-end gap-1.5">
<button
type="button"
onClick={() => {
setDraft(
e164 || country
? {
e164: e164 ?? null,
country: (country as CountryCode | null) ?? defaultCountry ?? 'US',
}
: null,
);
setEditing(false);
}}
disabled={saving}
className={cn(
'inline-flex h-8 items-center rounded-md px-3 text-xs font-medium',
'text-muted-foreground transition-colors hover:bg-muted hover:text-foreground',
'disabled:opacity-50',
)}
>
Cancel
</button>
<button
type="button"
onClick={() => void commit()}
disabled={saving}
className={cn(
'inline-flex h-8 min-w-[64px] items-center justify-center rounded-md px-3',
'bg-primary text-xs font-semibold text-primary-foreground shadow-sm',
'transition-colors hover:bg-primary/90 disabled:opacity-50',
)}
>
{saving ? <Loader2 className="size-3.5 animate-spin" /> : 'Save'}
</button>
</div>
</div>
);
}

View File

@@ -1,6 +1,6 @@
'use client';
import { useState } from 'react';
import { useRef, useState } from 'react';
import { Loader2, Pencil } from 'lucide-react';
import { toast } from 'sonner';
@@ -31,8 +31,12 @@ export function InlineTimezoneField({
}: InlineTimezoneFieldProps) {
const [editing, setEditing] = useState(false);
const [saving, setSaving] = useState(false);
// Set true when the user picks a value from the dropdown, so the
// popover-close handler knows commit() will exit edit mode itself.
const pickedRef = useRef(false);
async function commit(next: string | null) {
pickedRef.current = true;
if (next === (value ?? null)) {
setEditing(false);
return;
@@ -56,6 +60,16 @@ export function InlineTimezoneField({
onChange={(tz) => void commit(tz)}
countryHint={countryHint ?? undefined}
data-testid={testId}
defaultOpen
onOpenChange={(open) => {
// Auto-exit edit mode when the dropdown closes without a pick,
// so the user isn't stuck looking at the trigger. commit() owns
// the exit when a value was selected.
if (!open && !pickedRef.current) {
setEditing(false);
}
if (open) pickedRef.current = false;
}}
/>
{saving && <Loader2 className="h-3 w-3 animate-spin text-muted-foreground" />}
</div>

View File

@@ -32,6 +32,11 @@ interface SubdivisionComboboxProps {
clearable?: boolean;
id?: string;
'data-testid'?: string;
/** Open the dropdown on first render. Used by inline-edit wrappers. */
defaultOpen?: boolean;
/** Notified whenever the dropdown opens/closes. Inline-edit wrappers use
* this to auto-exit edit mode when the user dismisses without picking. */
onOpenChange?: (open: boolean) => void;
}
export function SubdivisionCombobox({
@@ -44,8 +49,14 @@ export function SubdivisionCombobox({
clearable = true,
id,
'data-testid': testId,
defaultOpen = false,
onOpenChange,
}: SubdivisionComboboxProps) {
const [open, setOpen] = useState(false);
const [open, setOpen] = useState(defaultOpen);
const handleOpenChange = (next: boolean) => {
setOpen(next);
onOpenChange?.(next);
};
const options = useMemo(() => {
if (!country) return [];
@@ -64,7 +75,7 @@ export function SubdivisionCombobox({
else triggerLabel = placeholder;
return (
<Popover open={open} onOpenChange={setOpen}>
<Popover open={open} onOpenChange={handleOpenChange}>
<PopoverTrigger asChild>
<Button
id={id}

View File

@@ -29,6 +29,11 @@ interface TimezoneComboboxProps {
clearable?: boolean;
id?: string;
'data-testid'?: string;
/** Open the dropdown on first render. Used by inline-edit wrappers. */
defaultOpen?: boolean;
/** Notified whenever the dropdown opens/closes. Inline-edit wrappers use
* this to auto-exit edit mode when the user dismisses without picking. */
onOpenChange?: (open: boolean) => void;
}
export function TimezoneCombobox({
@@ -41,8 +46,14 @@ export function TimezoneCombobox({
clearable = true,
id,
'data-testid': testId,
defaultOpen = false,
onOpenChange,
}: TimezoneComboboxProps) {
const [open, setOpen] = useState(false);
const [open, setOpen] = useState(defaultOpen);
const handleOpenChange = (next: boolean) => {
setOpen(next);
onOpenChange?.(next);
};
const allOptions = useMemo(() => {
return listAllTimezones().map((tz) => ({
@@ -66,7 +77,7 @@ export function TimezoneCombobox({
const selectedLabel = value ? formatTimezoneLabel(value) : placeholder;
return (
<Popover open={open} onOpenChange={setOpen}>
<Popover open={open} onOpenChange={handleOpenChange}>
<PopoverTrigger asChild>
<Button
id={id}

View File

@@ -45,7 +45,7 @@ export function KPITile({
<div
data-testid="kpi-tile"
className={cn(
'group relative overflow-hidden rounded-xl border border-border bg-gradient-brand-soft p-5 shadow-sm transition-all duration-base ease-smooth hover:shadow-md',
'group relative overflow-hidden rounded-xl border border-border bg-gradient-brand-soft p-3 shadow-sm transition-all duration-base ease-smooth hover:shadow-md sm:p-5',
className,
)}
{...props}
@@ -53,10 +53,12 @@ export function KPITile({
<div className={cn('absolute inset-x-0 top-0 h-1', ACCENT_STRIPES[accent])} aria-hidden />
<div className="flex items-start justify-between gap-4">
<div className="min-w-0">
<div className="text-xs font-medium uppercase tracking-wide text-muted-foreground">
<div className="text-[10px] font-medium uppercase tracking-wide text-muted-foreground sm:text-xs">
{title}
</div>
<div className="mt-2 text-2xl font-semibold tabular-nums text-foreground">{value}</div>
<div className="mt-1 truncate text-lg font-semibold tabular-nums text-foreground sm:mt-2 sm:text-2xl">
{value}
</div>
{typeof delta === 'number' ? (
<div className={cn('mt-1 text-xs font-medium', deltaClass)}>
{deltaPrefix}

View File

@@ -58,10 +58,11 @@ export function buildPipelineInputs(
'open',
'details_sent',
'in_communication',
'visited',
'signed_eoi_nda',
'eoi_sent',
'eoi_signed',
'deposit_10pct',
'contract',
'contract_sent',
'contract_signed',
'completed',
];
@@ -73,9 +74,7 @@ export function buildPipelineInputs(
});
// Include stages not in standard order
const unknownStages = Object.keys(data.stageCounts).filter(
(s) => !stageOrder.includes(s),
);
const unknownStages = Object.keys(data.stageCounts).filter((s) => !stageOrder.includes(s));
for (const stage of unknownStages) {
summaryLines.push(`${stage}: ${data.stageCounts[stage]} interest(s)`);
}

View File

@@ -50,18 +50,16 @@ export const revenueReportTemplate: Template = {
],
};
export function buildRevenueInputs(
data: RevenueData,
portName?: string,
): Record<string, string>[] {
export function buildRevenueInputs(data: RevenueData, portName?: string): Record<string, string>[] {
const stageOrder = [
'open',
'details_sent',
'in_communication',
'visited',
'signed_eoi_nda',
'eoi_sent',
'eoi_signed',
'deposit_10pct',
'contract',
'contract_sent',
'contract_signed',
'completed',
];

View File

@@ -1,4 +1,4 @@
import { and, count, eq, ilike, inArray, isNull } from 'drizzle-orm';
import { and, count, desc, eq, ilike, inArray, isNull } from 'drizzle-orm';
import { db } from '@/lib/db';
import {
@@ -11,6 +11,8 @@ import {
import { companies, companyMemberships } from '@/lib/db/schema/companies';
import { yachts } from '@/lib/db/schema/yachts';
import { berthReservations } from '@/lib/db/schema/reservations';
import { interests } from '@/lib/db/schema/interests';
import { berths } from '@/lib/db/schema/berths';
import { tags } from '@/lib/db/schema/system';
import { createAuditLog, type AuditMeta } from '@/lib/audit';
import { NotFoundError, ValidationError } from '@/lib/errors';
@@ -81,7 +83,7 @@ export async function listClients(portId: string, query: ListClientsInput) {
const ids = result.data.map((r) => r.id);
const [yachtCounts, companyCounts] = await Promise.all([
const [yachtCounts, companyCounts, interestRows, interestCounts] = await Promise.all([
db
.select({ ownerId: yachts.currentOwnerId, count: count() })
.from(yachts)
@@ -99,18 +101,67 @@ export async function listClients(portId: string, query: ListClientsInput) {
.from(companyMemberships)
.where(and(inArray(companyMemberships.clientId, ids), isNull(companyMemberships.endDate)))
.groupBy(companyMemberships.clientId),
db
.select({
clientId: interests.clientId,
pipelineStage: interests.pipelineStage,
updatedAt: interests.updatedAt,
mooringNumber: berths.mooringNumber,
})
.from(interests)
.leftJoin(berths, eq(berths.id, interests.berthId))
.where(
and(
eq(interests.portId, portId),
inArray(interests.clientId, ids),
isNull(interests.archivedAt),
),
)
.orderBy(desc(interests.updatedAt)),
db
.select({ clientId: interests.clientId, count: count() })
.from(interests)
.where(
and(
eq(interests.portId, portId),
inArray(interests.clientId, ids),
isNull(interests.archivedAt),
),
)
.groupBy(interests.clientId),
]);
const yachtCountMap = new Map(yachtCounts.map((r) => [r.ownerId, r.count]));
const companyCountMap = new Map(companyCounts.map((r) => [r.clientId, r.count]));
const interestCountMap = new Map(interestCounts.map((r) => [r.clientId, r.count]));
// interestRows is sorted desc by updatedAt; first hit per clientId is the latest.
const latestInterestMap = new Map<string, { stage: string; mooringNumber: string | null }>();
for (const row of interestRows) {
if (!latestInterestMap.has(row.clientId)) {
latestInterestMap.set(row.clientId, {
stage: row.pipelineStage,
mooringNumber: row.mooringNumber,
});
}
}
return {
...result,
data: result.data.map((row) => ({
...row,
yachtCount: yachtCountMap.get(row.id) ?? 0,
companyCount: companyCountMap.get(row.id) ?? 0,
})),
data: result.data.map((row) => {
const latest = latestInterestMap.get(row.id);
return {
...row,
yachtCount: yachtCountMap.get(row.id) ?? 0,
companyCount: companyCountMap.get(row.id) ?? 0,
interestCount: interestCountMap.get(row.id) ?? 0,
latestInterest: latest
? {
stage: latest.stage,
mooringNumber: latest.mooringNumber,
}
: null,
};
}),
};
}

View File

@@ -635,10 +635,11 @@ export function makeCreateInterestInput(overrides?: {
| 'open'
| 'details_sent'
| 'in_communication'
| 'visited'
| 'signed_eoi_nda'
| 'eoi_sent'
| 'eoi_signed'
| 'deposit_10pct'
| 'contract'
| 'contract_sent'
| 'contract_signed'
| 'completed';
}) {
return {

View File

@@ -181,7 +181,7 @@ describe('alert engine', () => {
await db.insert(interests).values({
portId: port.id,
clientId: client.id,
pipelineStage: 'visited',
pipelineStage: 'in_communication',
leadCategory: 'hot_lead',
dateLastContact: stale,
updatedAt: stale,

View File

@@ -170,7 +170,7 @@ describe('Pipeline Transitions', () => {
await import('@/lib/services/interests.service');
const meta = makeAuditMeta({ portId });
await changeInterestStage(interestId, portId, { pipelineStage: 'signed_eoi_nda' }, meta);
await changeInterestStage(interestId, portId, { pipelineStage: 'eoi_signed' }, meta);
const updated = await getInterestById(interestId, portId);
expect(updated.dateEoiSigned).not.toBeNull();
@@ -181,7 +181,7 @@ describe('Pipeline Transitions', () => {
await import('@/lib/services/interests.service');
const meta = makeAuditMeta({ portId });
await changeInterestStage(interestId, portId, { pipelineStage: 'contract' }, meta);
await changeInterestStage(interestId, portId, { pipelineStage: 'contract_signed' }, meta);
const updated = await getInterestById(interestId, portId);
expect(updated.dateContractSigned).not.toBeNull();

View File

@@ -142,7 +142,7 @@ describe('calculateInterestScore', () => {
portId: 'p1',
clientId: 'c1',
createdAt: daysAgo(10),
pipelineStage: 'contract',
pipelineStage: 'contract_signed',
eoiStatus: 'signed',
contractStatus: 'signed',
depositStatus: 'received',