refactor(sales): consolidate pipeline stages + wire EOI auto-advance

The 8→9 stage refresh from earlier today only updated constants.ts and the DB —
20 component/service files still hardcoded the old enum, leaving labels blank,
filter dropdowns wrong, kanban columns mismatched, and the analytics funnel
silently dropping new-stage rows. The platform also never advanced
pipelineStage on EOI lifecycle events: documents.service.ts wrote eoiStatus
but left the user-visible stage stuck.

This commit closes both gaps:

  1. Single source of truth in src/lib/constants.ts — adds STAGE_LABELS,
     STAGE_BADGE, STAGE_DOT, STAGE_WEIGHTS, STAGE_TRANSITIONS plus
     stageLabel / stageBadgeClass / stageDotClass / safeStage /
     canTransitionStage helpers. components/clients/pipeline-constants.ts
     becomes a re-export shim so existing imports keep working.

  2. 18 stale-enum surfaces migrated — interest list (table, card, filters,
     form, stage picker), pipeline board, client card, berth interests tab,
     portal client interests page, dashboard pipeline / funnel / revenue-
     forecast charts, settings pipeline_weights default, dashboard.service
     weights, analytics.service funnel stages, alert-rules stale-interest
     filter, interest-scoring stage rank.

  3. Documents tab wired into interest detail — replaced the placeholder in
     interest-tabs.tsx with InterestDocumentsTab + InterestFilesTab so the
     EOI launcher is back where salespeople work.

  4. Auto-advance — new advanceStageIfBehind() in interests.service.ts
     (forward-only, no-op if interest is already past the target). Called
     from documents.service.ts on send (→ eoi_sent), Documenso completed
     webhook (→ eoi_signed), and manual signed-EOI upload (→ eoi_signed).

  5. Transition guard — canTransitionStage() blocks egregious skips
     (e.g. completed → open, open → contract_signed). Enforced in
     changeInterestStage before the DB write.

Tests updated to reflect the 9-stage model. tsc clean, vitest 832/832,
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-01 23:33:53 +02:00
parent 0d357731ad
commit 886119cbde
26 changed files with 577 additions and 419 deletions

View File

@@ -5,28 +5,19 @@ import type { Metadata } from 'next';
import { getPortalSession } from '@/lib/portal/auth'; import { getPortalSession } from '@/lib/portal/auth';
import { getClientInterests } from '@/lib/services/portal.service'; import { getClientInterests } from '@/lib/services/portal.service';
import { Badge } from '@/components/ui/badge'; import { Badge } from '@/components/ui/badge';
import { stageLabel, safeStage, type PipelineStage } from '@/lib/constants';
export const metadata: Metadata = { title: 'Interests' }; export const metadata: Metadata = { title: 'Interests' };
const STAGE_LABELS: Record<string, string> = { const STAGE_VARIANT: Record<PipelineStage, 'default' | 'secondary' | 'destructive' | 'outline'> = {
open: 'Open',
details_sent: 'Details Sent',
in_communication: 'In Communication',
visited: 'Visited',
signed_eoi_nda: 'EOI / NDA Signed',
deposit_10pct: 'Deposit Received',
contract: 'Contract Stage',
completed: 'Completed',
};
const STAGE_COLORS: Record<string, 'default' | 'secondary' | 'destructive' | 'outline'> = {
open: 'secondary', open: 'secondary',
details_sent: 'secondary', details_sent: 'secondary',
in_communication: 'default', in_communication: 'default',
visited: 'default', eoi_sent: 'default',
signed_eoi_nda: 'default', eoi_signed: 'default',
deposit_10pct: 'default', deposit_10pct: 'default',
contract: 'default', contract_sent: 'default',
contract_signed: 'default',
completed: 'outline', completed: 'outline',
}; };
@@ -40,9 +31,7 @@ export default async function PortalInterestsPage() {
<div className="space-y-6"> <div className="space-y-6">
<div> <div>
<h1 className="text-2xl font-semibold text-gray-900">Berth Interests</h1> <h1 className="text-2xl font-semibold text-gray-900">Berth Interests</h1>
<p className="text-sm text-gray-500 mt-1"> <p className="text-sm text-gray-500 mt-1">Your berth enquiries and applications</p>
Your berth enquiries and applications
</p>
</div> </div>
{interests.length === 0 ? ( {interests.length === 0 ? (
@@ -56,10 +45,7 @@ export default async function PortalInterestsPage() {
) : ( ) : (
<div className="space-y-3"> <div className="space-y-3">
{interests.map((interest) => ( {interests.map((interest) => (
<div <div key={interest.id} className="bg-white rounded-lg border p-5">
key={interest.id}
className="bg-white rounded-lg border p-5"
>
<div className="flex items-start justify-between gap-4"> <div className="flex items-start justify-between gap-4">
<div className="flex-1 min-w-0"> <div className="flex-1 min-w-0">
<div className="flex items-center gap-2 mb-1"> <div className="flex items-center gap-2 mb-1">
@@ -98,8 +84,8 @@ export default async function PortalInterestsPage() {
)} )}
</div> </div>
</div> </div>
<Badge variant={STAGE_COLORS[interest.pipelineStage] ?? 'default'}> <Badge variant={STAGE_VARIANT[safeStage(interest.pipelineStage)]}>
{STAGE_LABELS[interest.pipelineStage] ?? interest.pipelineStage} {stageLabel(interest.pipelineStage)}
</Badge> </Badge>
</div> </div>
</div> </div>

View File

@@ -68,9 +68,11 @@ const KNOWN_SETTINGS: Array<{
open: 0.05, open: 0.05,
details_sent: 0.1, details_sent: 0.1,
in_communication: 0.2, in_communication: 0.2,
signed_eoi_nda: 0.4, eoi_sent: 0.4,
deposit_10pct: 0.6, eoi_signed: 0.6,
contract: 0.8, deposit_10pct: 0.75,
contract_sent: 0.85,
contract_signed: 0.95,
completed: 1.0, completed: 1.0,
}, },
}, },

View File

@@ -19,6 +19,7 @@ import {
import { TableSkeleton } from '@/components/shared/loading-skeleton'; import { TableSkeleton } from '@/components/shared/loading-skeleton';
import { EmptyState } from '@/components/shared/empty-state'; import { EmptyState } from '@/components/shared/empty-state';
import { Bookmark } from 'lucide-react'; import { Bookmark } from 'lucide-react';
import { PIPELINE_STAGES, stageLabel } from '@/lib/constants';
import type { InterestRow } from '@/components/interests/interest-columns'; import type { InterestRow } from '@/components/interests/interest-columns';
interface BerthInterestsTabProps { interface BerthInterestsTabProps {
@@ -28,27 +29,10 @@ interface BerthInterestsTabProps {
type StageFilter = 'all' | 'active' | 'lost'; type StageFilter = 'all' | 'active' | 'lost';
type SortMode = 'newest' | 'stage' | 'category'; type SortMode = 'newest' | 'stage' | 'category';
const STAGE_LABELS: Record<string, string> = { function stageRank(stage: string): number {
open: 'Open', const idx = PIPELINE_STAGES.indexOf(stage as (typeof PIPELINE_STAGES)[number]);
details_sent: 'Details Sent', return idx === -1 ? 99 : idx;
in_communication: 'In Communication', }
visited: 'Visited',
signed_eoi_nda: 'Signed EOI/NDA',
deposit_10pct: 'Deposit 10%',
contract: 'Contract',
completed: 'Completed',
};
const STAGE_ORDER: Record<string, number> = {
open: 0,
details_sent: 1,
in_communication: 2,
visited: 3,
signed_eoi_nda: 4,
deposit_10pct: 5,
contract: 6,
completed: 7,
};
const CATEGORY_RANK: Record<string, number> = { const CATEGORY_RANK: Record<string, number> = {
hot_lead: 0, hot_lead: 0,
@@ -104,8 +88,8 @@ export function BerthInterestsTab({ berthId }: BerthInterestsTabProps) {
}); });
const sorted = [...filtered].sort((a, b) => { const sorted = [...filtered].sort((a, b) => {
if (sortMode === 'stage') { if (sortMode === 'stage') {
const sa = STAGE_ORDER[a.pipelineStage] ?? 99; const sa = stageRank(a.pipelineStage);
const sb = STAGE_ORDER[b.pipelineStage] ?? 99; const sb = stageRank(b.pipelineStage);
if (sa !== sb) return sb - sa; // furthest along first if (sa !== sb) return sb - sa; // furthest along first
} }
if (sortMode === 'category') { if (sortMode === 'category') {
@@ -189,7 +173,7 @@ export function BerthInterestsTab({ berthId }: BerthInterestsTabProps) {
</td> </td>
<td className="px-3 py-2"> <td className="px-3 py-2">
<Badge variant="secondary" className="font-normal"> <Badge variant="secondary" className="font-normal">
{STAGE_LABELS[i.pipelineStage] ?? i.pipelineStage} {stageLabel(i.pipelineStage)}
</Badge> </Badge>
</td> </td>
<td className="px-3 py-2 text-muted-foreground"> <td className="px-3 py-2 text-muted-foreground">

View File

@@ -17,6 +17,7 @@ import {
deriveInitials, deriveInitials,
} from '@/components/shared/list-card'; } from '@/components/shared/list-card';
import { getCountryName } from '@/lib/i18n/countries'; import { getCountryName } from '@/lib/i18n/countries';
import { stageBadgeClass, stageLabel } from '@/lib/constants';
import type { ClientRow } from './client-columns'; import type { ClientRow } from './client-columns';
const SOURCE_LABELS: Record<string, string> = { const SOURCE_LABELS: Record<string, string> = {
@@ -37,15 +38,20 @@ export function ClientCard({ client, portSlug, onEdit, onArchive }: ClientCardPr
const primary = client.contacts?.find((c) => c.isPrimary); const primary = client.contacts?.find((c) => c.isPrimary);
const nationality = client.nationalityIso ? getCountryName(client.nationalityIso, 'en') : null; const nationality = client.nationalityIso ? getCountryName(client.nationalityIso, 'en') : null;
const sourceLabel = client.source ? (SOURCE_LABELS[client.source] ?? client.source) : null; const sourceLabel = client.source ? (SOURCE_LABELS[client.source] ?? client.source) : null;
const yachtCount = client.yachtCount ?? 0;
const companyCount = client.companyCount ?? 0;
const tags = client.tags ?? []; const tags = client.tags ?? [];
const meta = [nationality, sourceLabel].filter(Boolean) as string[]; const meta = [nationality, sourceLabel].filter(Boolean) as string[];
const counts: string[] = [];
if (yachtCount > 0) counts.push(`${yachtCount} ${yachtCount === 1 ? 'yacht' : 'yachts'}`); const interest = client.latestInterest ?? null;
if (companyCount > 0) const interestCount = client.interestCount ?? 0;
counts.push(`${companyCount} ${companyCount === 1 ? 'company' : 'companies'}`); const interestBerthLabel = interest
? interest.mooringNumber
? `Berth ${interest.mooringNumber}`
: 'General interest'
: null;
const interestStageLabel = interest ? stageLabel(interest.stage) : null;
const interestStageBadge = interest ? stageBadgeClass(interest.stage) : null;
const extraInterests = interestCount > 1 ? interestCount - 1 : 0;
return ( return (
<ListCard <ListCard
@@ -102,8 +108,19 @@ export function ClientCard({ client, portSlug, onEdit, onArchive }: ClientCardPr
</div> </div>
) : null} ) : null}
{counts.length > 0 ? ( {interest ? (
<p className="mt-0.5 text-xs text-muted-foreground">{counts.join(' · ')}</p> <div className="mt-1 flex items-center gap-1.5 text-xs text-muted-foreground">
<span className="truncate">{interestBerthLabel}</span>
<span aria-hidden>·</span>
<span
className={`shrink-0 rounded-full px-1.5 py-0.5 text-[10px] font-medium ${interestStageBadge}`}
>
{interestStageLabel}
</span>
{extraInterests > 0 ? (
<span className="shrink-0 text-muted-foreground/80">+{extraInterests}</span>
) : null}
</div>
) : null} ) : null}
{tags.length > 0 ? ( {tags.length > 0 ? (

View File

@@ -0,0 +1,14 @@
// Re-export from the canonical source so legacy imports keep working.
export {
PIPELINE_STAGES,
STAGE_LABELS,
STAGE_BADGE,
STAGE_DOT,
STAGE_WEIGHTS,
STAGE_TRANSITIONS,
safeStage,
stageLabel,
stageBadgeClass,
stageDotClass,
type PipelineStage,
} from '@/lib/constants';

View File

@@ -1,19 +1,12 @@
'use client'; 'use client';
import { useQuery } from '@tanstack/react-query'; import { useQuery } from '@tanstack/react-query';
import { import { Bar, BarChart, CartesianGrid, ResponsiveContainer, Tooltip, XAxis, YAxis } from 'recharts';
Bar,
BarChart,
CartesianGrid,
ResponsiveContainer,
Tooltip,
XAxis,
YAxis,
} from 'recharts';
import { apiFetch } from '@/lib/api/client'; import { apiFetch } from '@/lib/api/client';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'; import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { CardSkeleton } from '@/components/shared/loading-skeleton'; import { CardSkeleton } from '@/components/shared/loading-skeleton';
import { stageLabel } from '@/lib/constants';
import { WidgetErrorBoundary } from './widget-error-boundary'; import { WidgetErrorBoundary } from './widget-error-boundary';
interface PipelineRow { interface PipelineRow {
@@ -21,17 +14,6 @@ interface PipelineRow {
count: number; count: number;
} }
const STAGE_LABELS: Record<string, string> = {
open: 'Open',
details_sent: 'Details Sent',
in_communication: 'In Communication',
visited: 'Visited',
signed_eoi_nda: 'Signed EOI/NDA',
deposit_10pct: 'Deposit 10%',
contract: 'Contract',
completed: 'Completed',
};
function PipelineChartInner() { function PipelineChartInner() {
const { data, isLoading } = useQuery<PipelineRow[]>({ const { data, isLoading } = useQuery<PipelineRow[]>({
queryKey: ['dashboard', 'pipeline'], queryKey: ['dashboard', 'pipeline'],
@@ -45,7 +27,7 @@ function PipelineChartInner() {
} }
const chartData = (data ?? []).map((row) => ({ const chartData = (data ?? []).map((row) => ({
stage: STAGE_LABELS[row.stage] ?? row.stage, stage: stageLabel(row.stage),
count: row.count, count: row.count,
})); }));

View File

@@ -4,21 +4,11 @@ import { Bar, BarChart, CartesianGrid, ResponsiveContainer, Tooltip, XAxis, YAxi
import { CardSkeleton } from '@/components/shared/loading-skeleton'; import { CardSkeleton } from '@/components/shared/loading-skeleton';
import { EmptyState } from '@/components/shared/empty-state'; import { EmptyState } from '@/components/shared/empty-state';
import { stageLabel } from '@/lib/constants';
import { ChartCard } from './chart-card'; import { ChartCard } from './chart-card';
import { useFunnel } from './use-analytics'; import { useFunnel } from './use-analytics';
import type { DateRange } from '@/lib/services/analytics.service'; import type { DateRange } from '@/lib/services/analytics.service';
const STAGE_LABELS: Record<string, string> = {
open: 'Open',
details_sent: 'Details Sent',
in_communication: 'In Communication',
visited: 'Visited',
signed_eoi_nda: 'Signed EOI/NDA',
deposit_10pct: 'Deposit 10%',
contract: 'Contract',
completed: 'Completed',
};
interface Props { interface Props {
range: DateRange; range: DateRange;
} }
@@ -28,7 +18,7 @@ export function PipelineFunnelChart({ range }: Props) {
const stages = data?.stages ?? []; const stages = data?.stages ?? [];
const chartData = stages.map((s) => ({ const chartData = stages.map((s) => ({
stage: STAGE_LABELS[s.stage] ?? s.stage, stage: stageLabel(s.stage),
count: s.count, count: s.count,
conversionPct: s.conversionPct, conversionPct: s.conversionPct,
})); }));

View File

@@ -6,6 +6,7 @@ import { apiFetch } from '@/lib/api/client';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'; import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge'; import { Badge } from '@/components/ui/badge';
import { CardSkeleton } from '@/components/shared/loading-skeleton'; import { CardSkeleton } from '@/components/shared/loading-skeleton';
import { stageLabel } from '@/lib/constants';
import { WidgetErrorBoundary } from './widget-error-boundary'; import { WidgetErrorBoundary } from './widget-error-boundary';
interface StageBreakdownRow { interface StageBreakdownRow {
@@ -20,17 +21,6 @@ interface ForecastData {
weightsSource: 'db' | 'default'; weightsSource: 'db' | 'default';
} }
const STAGE_LABELS: Record<string, string> = {
open: 'Open',
details_sent: 'Details Sent',
in_communication: 'In Communication',
visited: 'Visited',
signed_eoi_nda: 'Signed EOI/NDA',
deposit_10pct: 'Deposit 10%',
contract: 'Contract',
completed: 'Completed',
};
function formatCurrency(value: number): string { function formatCurrency(value: number): string {
return new Intl.NumberFormat('en-US', { return new Intl.NumberFormat('en-US', {
style: 'currency', style: 'currency',
@@ -66,9 +56,7 @@ function RevenueForecastInner() {
<CardContent className="space-y-4"> <CardContent className="space-y-4">
<div> <div>
<p className="text-xs text-muted-foreground">Weighted Pipeline Value</p> <p className="text-xs text-muted-foreground">Weighted Pipeline Value</p>
<p className="text-2xl font-bold"> <p className="text-2xl font-bold">{formatCurrency(data?.totalWeightedValue ?? 0)}</p>
{formatCurrency(data?.totalWeightedValue ?? 0)}
</p>
</div> </div>
{activeStages.length > 0 && ( {activeStages.length > 0 && (
@@ -76,12 +64,10 @@ function RevenueForecastInner() {
{activeStages.map((s) => ( {activeStages.map((s) => (
<div key={s.stage} className="flex items-center justify-between text-sm"> <div key={s.stage} className="flex items-center justify-between text-sm">
<span className="text-muted-foreground"> <span className="text-muted-foreground">
{STAGE_LABELS[s.stage] ?? s.stage} {stageLabel(s.stage)}
<span className="ml-1 text-xs">({s.count})</span> <span className="ml-1 text-xs">({s.count})</span>
</span> </span>
<span className="font-medium tabular-nums"> <span className="font-medium tabular-nums">{formatCurrency(s.weightedValue)}</span>
{formatCurrency(s.weightedValue)}
</span>
</div> </div>
))} ))}
</div> </div>

View File

@@ -17,43 +17,9 @@ import {
deriveInitials, deriveInitials,
} 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 type { InterestRow } from './interest-columns'; import type { InterestRow } from './interest-columns';
const STAGE_LABELS: Record<string, string> = {
open: 'Open',
details_sent: 'Details Sent',
in_communication: 'In Communication',
visited: 'Visited',
signed_eoi_nda: 'Signed EOI/NDA',
deposit_10pct: 'Deposit 10%',
contract: 'Contract',
completed: 'Completed',
};
/** Pill colors (used for the stage badge in the meta row). */
const STAGE_PILL: Record<string, string> = {
open: 'bg-slate-100 text-slate-700',
details_sent: 'bg-blue-100 text-blue-700',
in_communication: 'bg-sky-100 text-sky-700',
visited: 'bg-violet-100 text-violet-700',
signed_eoi_nda: 'bg-amber-100 text-amber-700',
deposit_10pct: 'bg-orange-100 text-orange-700',
contract: 'bg-green-100 text-green-700',
completed: 'bg-emerald-100 text-emerald-700',
};
/** Accent-bar colors — saturate progressively so the pipeline depth reads at a glance. */
const STAGE_ACCENT: Record<string, string> = {
open: 'bg-slate-300',
details_sent: 'bg-blue-400',
in_communication: 'bg-sky-400',
visited: 'bg-violet-400',
signed_eoi_nda: 'bg-amber-400',
deposit_10pct: 'bg-orange-400',
contract: 'bg-green-500',
completed: 'bg-emerald-500',
};
const CATEGORY_LABELS: Record<string, string> = { const CATEGORY_LABELS: Record<string, string> = {
general_interest: 'General', general_interest: 'General',
specific_qualified: 'Qualified', specific_qualified: 'Qualified',
@@ -75,9 +41,9 @@ interface InterestCardProps {
} }
export function InterestCard({ interest, portSlug, onEdit, onArchive }: InterestCardProps) { export function InterestCard({ interest, portSlug, onEdit, onArchive }: InterestCardProps) {
const stageLabel = STAGE_LABELS[interest.pipelineStage] ?? interest.pipelineStage; const stageLabel = toStageLabel(interest.pipelineStage);
const stagePill = STAGE_PILL[interest.pipelineStage] ?? 'bg-gray-100 text-gray-700'; const stagePill = stageBadgeClass(interest.pipelineStage);
const accentClass = STAGE_ACCENT[interest.pipelineStage] ?? 'bg-slate-300'; const accentClass = stageDotClass(interest.pipelineStage);
const isHotLead = interest.leadCategory === 'hot_lead'; const isHotLead = interest.leadCategory === 'hot_lead';
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;

View File

@@ -14,6 +14,7 @@ import {
} from '@/components/ui/dropdown-menu'; } from '@/components/ui/dropdown-menu';
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';
export interface InterestRow { export interface InterestRow {
id: string; id: string;
@@ -29,28 +30,6 @@ export interface InterestRow {
tags?: Array<{ id: string; name: string; color: string }>; tags?: Array<{ id: string; name: string; color: string }>;
} }
const STAGE_LABELS: Record<string, string> = {
open: 'Open',
details_sent: 'Details Sent',
in_communication: 'In Communication',
visited: 'Visited',
signed_eoi_nda: 'Signed EOI/NDA',
deposit_10pct: 'Deposit 10%',
contract: 'Contract',
completed: 'Completed',
};
const STAGE_COLORS: Record<string, string> = {
open: 'bg-slate-100 text-slate-700',
details_sent: 'bg-blue-100 text-blue-700',
in_communication: 'bg-sky-100 text-sky-700',
visited: 'bg-violet-100 text-violet-700',
signed_eoi_nda: 'bg-amber-100 text-amber-700',
deposit_10pct: 'bg-orange-100 text-orange-700',
contract: 'bg-green-100 text-green-700',
completed: 'bg-emerald-100 text-emerald-700',
};
const CATEGORY_LABELS: Record<string, string> = { const CATEGORY_LABELS: Record<string, string> = {
general_interest: 'General Interest', general_interest: 'General Interest',
specific_qualified: 'Specific Qualified', specific_qualified: 'Specific Qualified',
@@ -117,9 +96,9 @@ export function getInterestColumns({
const stage = getValue() as string; const stage = getValue() as string;
return ( return (
<span <span
className={`inline-flex items-center rounded-full px-2 py-0.5 text-xs font-medium ${STAGE_COLORS[stage] ?? 'bg-gray-100 text-gray-700'}`} className={`inline-flex items-center rounded-full px-2 py-0.5 text-xs font-medium ${stageBadgeClass(stage)}`}
> >
{STAGE_LABELS[stage] ?? stage} {stageLabel(stage)}
</span> </span>
); );
}, },
@@ -205,10 +184,7 @@ export function getInterestColumns({
<Pencil className="mr-2 h-3.5 w-3.5" /> <Pencil className="mr-2 h-3.5 w-3.5" />
Edit Edit
</DropdownMenuItem> </DropdownMenuItem>
<DropdownMenuItem <DropdownMenuItem className="text-destructive" onClick={() => onArchive(row.original)}>
className="text-destructive"
onClick={() => onArchive(row.original)}
>
<Archive className="mr-2 h-3.5 w-3.5" /> <Archive className="mr-2 h-3.5 w-3.5" />
Archive Archive
</DropdownMenuItem> </DropdownMenuItem>

View File

@@ -1,16 +1,5 @@
import type { FilterDefinition } from '@/components/shared/filter-bar'; import type { FilterDefinition } from '@/components/shared/filter-bar';
import { PIPELINE_STAGES, LEAD_CATEGORIES } from '@/lib/constants'; import { PIPELINE_STAGES, STAGE_LABELS, LEAD_CATEGORIES } from '@/lib/constants';
const STAGE_LABELS: Record<string, string> = {
open: 'Open',
details_sent: 'Details Sent',
in_communication: 'In Communication',
visited: 'Visited',
signed_eoi_nda: 'Signed EOI/NDA',
deposit_10pct: 'Deposit 10%',
contract: 'Contract',
completed: 'Completed',
};
const CATEGORY_LABELS: Record<string, string> = { const CATEGORY_LABELS: Record<string, string> = {
general_interest: 'General Interest', general_interest: 'General Interest',
@@ -30,7 +19,7 @@ export const interestFilterDefinitions: FilterDefinition[] = [
label: 'Stage', label: 'Stage',
type: 'multi-select', type: 'multi-select',
options: PIPELINE_STAGES.map((s) => ({ options: PIPELINE_STAGES.map((s) => ({
label: STAGE_LABELS[s] ?? s, label: STAGE_LABELS[s],
value: s, value: s,
})), })),
}, },

View File

@@ -35,20 +35,9 @@ import { YachtPicker } from '@/components/yachts/yacht-picker';
import { apiFetch } from '@/lib/api/client'; import { apiFetch } from '@/lib/api/client';
import { useEntityOptions } from '@/hooks/use-entity-options'; import { useEntityOptions } from '@/hooks/use-entity-options';
import { createInterestSchema, type CreateInterestInput } from '@/lib/validators/interests'; import { createInterestSchema, type CreateInterestInput } from '@/lib/validators/interests';
import { PIPELINE_STAGES, LEAD_CATEGORIES } from '@/lib/constants'; import { PIPELINE_STAGES, STAGE_LABELS, LEAD_CATEGORIES } from '@/lib/constants';
import { cn } from '@/lib/utils'; import { cn } from '@/lib/utils';
const STAGE_LABELS: Record<string, string> = {
open: 'Open',
details_sent: 'Details Sent',
in_communication: 'In Communication',
visited: 'Visited',
signed_eoi_nda: 'Signed EOI/NDA',
deposit_10pct: 'Deposit 10%',
contract: 'Contract',
completed: 'Completed',
};
const CATEGORY_LABELS: Record<string, string> = { const CATEGORY_LABELS: Record<string, string> = {
general_interest: 'General Interest', general_interest: 'General Interest',
specific_qualified: 'Specific Qualified', specific_qualified: 'Specific Qualified',
@@ -58,6 +47,11 @@ const CATEGORY_LABELS: Record<string, string> = {
interface InterestFormProps { interface InterestFormProps {
open: boolean; open: boolean;
onOpenChange: (open: boolean) => void; onOpenChange: (open: boolean) => void;
/**
* Pre-fill clientId when launching the form from a client detail page.
* Ignored when `interest` is provided (edit mode).
*/
defaultClientId?: string;
interest?: { interest?: {
id: string; id: string;
clientId: string; clientId: string;
@@ -75,7 +69,7 @@ interface InterestFormProps {
}; };
} }
export function InterestForm({ open, onOpenChange, interest }: InterestFormProps) { export function InterestForm({ open, onOpenChange, defaultClientId, interest }: InterestFormProps) {
const queryClient = useQueryClient(); const queryClient = useQueryClient();
const isEdit = !!interest; const isEdit = !!interest;
@@ -140,14 +134,14 @@ export function InterestForm({ open, onOpenChange, interest }: InterestFormProps
}); });
} else if (!interest && open) { } else if (!interest && open) {
reset({ reset({
clientId: '', clientId: defaultClientId ?? '',
yachtId: undefined, yachtId: undefined,
pipelineStage: 'open', pipelineStage: 'open',
reminderEnabled: false, reminderEnabled: false,
tagIds: [], tagIds: [],
}); });
} }
}, [interest, open, reset]); }, [interest, defaultClientId, open, reset]);
const mutation = useMutation({ const mutation = useMutation({
mutationFn: async (data: CreateInterestInput) => { mutationFn: async (data: CreateInterestInput) => {
@@ -347,7 +341,7 @@ export function InterestForm({ open, onOpenChange, interest }: InterestFormProps
<SelectContent> <SelectContent>
{PIPELINE_STAGES.map((s) => ( {PIPELINE_STAGES.map((s) => (
<SelectItem key={s} value={s}> <SelectItem key={s} value={s}>
{STAGE_LABELS[s] ?? s} {STAGE_LABELS[s]}
</SelectItem> </SelectItem>
))} ))}
</SelectContent> </SelectContent>

View File

@@ -22,18 +22,7 @@ import {
SelectValue, SelectValue,
} from '@/components/ui/select'; } from '@/components/ui/select';
import { apiFetch } from '@/lib/api/client'; import { apiFetch } from '@/lib/api/client';
import { PIPELINE_STAGES } from '@/lib/constants'; import { PIPELINE_STAGES, STAGE_LABELS, stageLabel } from '@/lib/constants';
const STAGE_LABELS: Record<string, string> = {
open: 'Open',
details_sent: 'Details Sent',
in_communication: 'In Communication',
visited: 'Visited',
signed_eoi_nda: 'Signed EOI/NDA',
deposit_10pct: 'Deposit 10%',
contract: 'Contract',
completed: 'Completed',
};
interface InterestStagePickerProps { interface InterestStagePickerProps {
open: boolean; open: boolean;
@@ -76,9 +65,7 @@ export function InterestStagePicker({
<div className="space-y-4 py-2"> <div className="space-y-4 py-2">
<div className="space-y-1"> <div className="space-y-1">
<Label>Current Stage</Label> <Label>Current Stage</Label>
<p className="text-sm text-muted-foreground"> <p className="text-sm text-muted-foreground">{stageLabel(currentStage)}</p>
{STAGE_LABELS[currentStage] ?? currentStage}
</p>
</div> </div>
<div className="space-y-1"> <div className="space-y-1">
@@ -90,7 +77,7 @@ export function InterestStagePicker({
<SelectContent> <SelectContent>
{PIPELINE_STAGES.map((s) => ( {PIPELINE_STAGES.map((s) => (
<SelectItem key={s} value={s}> <SelectItem key={s} value={s}>
{STAGE_LABELS[s] ?? s} {STAGE_LABELS[s]}
</SelectItem> </SelectItem>
))} ))}
</SelectContent> </SelectContent>

View File

@@ -1,16 +1,21 @@
'use client'; 'use client';
import { format } from 'date-fns'; import { format, formatDistanceToNowStrict } from 'date-fns';
import { useMutation, useQueryClient } from '@tanstack/react-query'; import { useMutation, useQueryClient } from '@tanstack/react-query';
import { CheckCircle2, Circle, FileSignature, Send, Wallet } from 'lucide-react';
import type { DetailTab } from '@/components/shared/detail-layout'; import type { DetailTab } from '@/components/shared/detail-layout';
import { Button } from '@/components/ui/button';
import { NotesList } from '@/components/shared/notes-list'; import { NotesList } from '@/components/shared/notes-list';
import { InlineEditableField } from '@/components/shared/inline-editable-field'; import { InlineEditableField } from '@/components/shared/inline-editable-field';
import { InlineTagEditor } from '@/components/shared/inline-tag-editor'; import { InlineTagEditor } from '@/components/shared/inline-tag-editor';
import { RecommendationList } from '@/components/interests/recommendation-list'; import { RecommendationList } from '@/components/interests/recommendation-list';
import { InterestTimeline } from '@/components/interests/interest-timeline'; import { InterestTimeline } from '@/components/interests/interest-timeline';
import { InterestDocumentsTab } from '@/components/interests/interest-documents-tab';
import { InterestFilesTab } from '@/components/interests/interest-files-tab';
import { LEAD_CATEGORIES } from '@/lib/constants'; import { LEAD_CATEGORIES } from '@/lib/constants';
import { apiFetch } from '@/lib/api/client'; import { apiFetch } from '@/lib/api/client';
import { cn } from '@/lib/utils';
type InterestPatchField = 'leadCategory' | 'source' | 'notes'; type InterestPatchField = 'leadCategory' | 'source' | 'notes';
@@ -58,6 +63,21 @@ function useInterestPatch(interestId: string) {
}); });
} }
function useStageMutation(interestId: string) {
const qc = useQueryClient();
return useMutation({
mutationFn: async ({ stage, reason }: { stage: string; reason?: string }) =>
apiFetch(`/api/v1/interests/${interestId}/stage`, {
method: 'PATCH',
body: { pipelineStage: stage, reason },
}),
onSuccess: () => {
qc.invalidateQueries({ queryKey: ['interests', interestId] });
qc.invalidateQueries({ queryKey: ['interests'] });
},
});
}
function EditableRow({ label, children }: { label: string; children: React.ReactNode }) { function EditableRow({ label, children }: { label: string; children: React.ReactNode }) {
return ( return (
<div className="flex gap-2 py-1.5 border-b last:border-0 items-center"> <div className="flex gap-2 py-1.5 border-b last:border-0 items-center">
@@ -82,6 +102,117 @@ function formatDate(date: string | null) {
return format(new Date(date), 'MMM d, yyyy'); return format(new Date(date), 'MMM d, yyyy');
} }
function relativeDate(date: string | null) {
if (!date) return null;
return `${formatDistanceToNowStrict(new Date(date))} ago`;
}
interface MilestoneSectionProps {
title: string;
icon: React.ComponentType<{ className?: string }>;
/** Lifecycle for this milestone, in chronological order. */
steps: Array<{
label: string;
date: string | null;
/** Stage to advance to when the user clicks the action button for this step. */
advanceStage?: string;
/** Optional override for the action label. */
actionLabel?: string;
}>;
status: string | null;
onAdvance: (stage: string) => void;
isPending: boolean;
}
/**
* One milestone section (EOI / Deposit / Contract) — shows a vertical lifecycle
* with completed steps checked, the next step exposing a quick "mark as…"
* button that bumps the pipeline stage. Each stage flip auto-stamps its date
* via the service layer (interests.service.ts). When external systems wire in
* (Documenso webhook, paid invoice → deposit, etc.), they patch the same
* stage endpoint and these checkmarks light up automatically.
*/
function MilestoneSection({
title,
icon: Icon,
steps,
status,
onAdvance,
isPending,
}: MilestoneSectionProps) {
const firstUnsetIdx = steps.findIndex((s) => !s.date);
return (
<section className="rounded-xl border border-border bg-card p-4 shadow-sm">
<header className="mb-3 flex items-center justify-between gap-2">
<div className="flex items-center gap-2">
<Icon className="size-4 text-muted-foreground" />
<h3 className="text-sm font-semibold tracking-tight text-foreground">{title}</h3>
</div>
{status ? (
<span className="rounded-full bg-muted px-2 py-0.5 text-[10px] font-medium uppercase tracking-wide text-muted-foreground">
{status.replace(/_/g, ' ')}
</span>
) : null}
</header>
<ol className="space-y-2">
{steps.map((step, i) => {
const done = !!step.date;
const isNext = !done && i === firstUnsetIdx;
return (
<li key={step.label} className="flex items-start gap-2 text-sm">
{done ? (
<CheckCircle2 className="mt-0.5 size-4 shrink-0 text-emerald-600" />
) : (
<Circle
className={cn(
'mt-0.5 size-4 shrink-0',
isNext ? 'text-foreground/60' : 'text-muted-foreground/40',
)}
/>
)}
<div className="min-w-0 flex-1">
<div className="flex flex-wrap items-center gap-x-2 gap-y-0.5">
<span
className={cn(
'truncate',
done
? 'text-foreground'
: isNext
? 'text-foreground'
: 'text-muted-foreground',
)}
>
{step.label}
</span>
{step.date ? (
<span className="text-xs text-muted-foreground">
{formatDate(step.date)} · {relativeDate(step.date)}
</span>
) : null}
</div>
{isNext && step.advanceStage ? (
<Button
type="button"
variant="outline"
size="sm"
disabled={isPending}
onClick={() => onAdvance(step.advanceStage!)}
className="mt-2 h-7 px-2.5 text-xs"
>
{step.actionLabel ?? `Mark as ${step.label.toLowerCase()}`}
</Button>
) : null}
</div>
</li>
);
})}
</ol>
</section>
);
}
function OverviewTab({ function OverviewTab({
interestId, interestId,
interest, interest,
@@ -90,88 +221,145 @@ function OverviewTab({
interest: InterestTabsOptions['interest']; interest: InterestTabsOptions['interest'];
}) { }) {
const mutation = useInterestPatch(interestId); const mutation = useInterestPatch(interestId);
const stageMutation = useStageMutation(interestId);
const save = (field: InterestPatchField) => async (next: string | null) => { const save = (field: InterestPatchField) => async (next: string | null) => {
await mutation.mutateAsync({ [field]: next }); await mutation.mutateAsync({ [field]: next });
}; };
const advance = (stage: string) =>
stageMutation.mutate({ stage, reason: 'Marked from overview' });
return ( return (
<div className="grid grid-cols-1 md:grid-cols-2 gap-6"> <div className="space-y-6">
{/* Lead & Source (editable) */} {/* Sales-process milestones — the heart of the system. Each section is a
<div className="space-y-1"> mini lifecycle that auto-completes as actions happen on the platform
<h3 className="text-sm font-medium mb-2">Lead</h3> (Documenso webhook, paid deposit invoice, signed contract). Until the
<dl> automation lands, salespeople nudge stages forward via the inline
<EditableRow label="Lead Category"> buttons here, which auto-stamp the milestone date server-side. */}
<InlineEditableField <div className="grid grid-cols-1 gap-4 lg:grid-cols-3">
variant="select" <MilestoneSection
options={LEAD_CATEGORY_OPTIONS} title="EOI"
value={interest.leadCategory} icon={Send}
onSave={save('leadCategory')} status={interest.eoiStatus}
/> isPending={stageMutation.isPending}
</EditableRow> onAdvance={advance}
<EditableRow label="Source"> steps={[
<InlineEditableField value={interest.source} onSave={save('source')} /> {
</EditableRow> label: 'EOI sent',
</dl> date: interest.dateEoiSent,
advanceStage: 'eoi_sent',
actionLabel: 'Mark EOI as sent',
},
{
label: 'EOI signed',
date: interest.dateEoiSigned,
advanceStage: 'eoi_signed',
actionLabel: 'Mark EOI as signed',
},
]}
/>
<MilestoneSection
title="Deposit"
icon={Wallet}
status={interest.depositStatus}
isPending={stageMutation.isPending}
onAdvance={advance}
steps={[
{
label: 'Deposit received',
date: interest.dateDepositReceived,
advanceStage: 'deposit_10pct',
actionLabel: 'Mark deposit received',
},
]}
/>
<MilestoneSection
title="Contract"
icon={FileSignature}
status={interest.contractStatus}
isPending={stageMutation.isPending}
onAdvance={advance}
steps={[
{
label: 'Contract sent',
date: interest.dateContractSent,
advanceStage: 'contract_sent',
actionLabel: 'Mark contract as sent',
},
{
label: 'Contract signed',
date: interest.dateContractSigned,
advanceStage: 'contract_signed',
actionLabel: 'Mark contract as signed',
},
]}
/>
</div> </div>
{/* EOI & Contract Status (read-only — derived) */} <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
<div className="space-y-1"> {/* Lead & Source (editable) */}
<h3 className="text-sm font-medium mb-2">Status</h3>
<dl>
<InfoRow label="EOI Status" value={interest.eoiStatus} />
<InfoRow label="Contract Status" value={interest.contractStatus} />
<InfoRow label="Deposit Status" value={interest.depositStatus} />
<InfoRow label="Reservation Status" value={interest.reservationStatus} />
</dl>
</div>
{/* Key Dates (read-only — set by workflow events) */}
<div className="space-y-1 md:col-span-2">
<h3 className="text-sm font-medium mb-2">Key Dates</h3>
<dl>
<InfoRow label="First Contact" value={formatDate(interest.dateFirstContact)} />
<InfoRow label="Last Contact" value={formatDate(interest.dateLastContact)} />
<InfoRow label="EOI Sent" value={formatDate(interest.dateEoiSent)} />
<InfoRow label="EOI Signed" value={formatDate(interest.dateEoiSigned)} />
<InfoRow label="Contract Sent" value={formatDate(interest.dateContractSent)} />
<InfoRow label="Contract Signed" value={formatDate(interest.dateContractSigned)} />
<InfoRow label="Deposit Received" value={formatDate(interest.dateDepositReceived)} />
</dl>
</div>
{/* Reminder */}
{interest.reminderEnabled && (
<div className="space-y-1"> <div className="space-y-1">
<h3 className="text-sm font-medium mb-2">Reminder</h3> <h3 className="text-sm font-medium mb-2">Lead</h3>
<dl> <dl>
<InfoRow <EditableRow label="Lead Category">
label="Reminder Days" <InlineEditableField
value={interest.reminderDays ? `${interest.reminderDays} days` : null} variant="select"
/> options={LEAD_CATEGORY_OPTIONS}
<InfoRow label="Last Fired" value={formatDate(interest.reminderLastFired)} /> value={interest.leadCategory}
onSave={save('leadCategory')}
/>
</EditableRow>
<EditableRow label="Source">
<InlineEditableField value={interest.source} onSave={save('source')} />
</EditableRow>
</dl> </dl>
</div> </div>
)}
{/* Notes (editable, multiline) */} {/* Contact dates (read-only — kept compact next to Lead) */}
<div className="space-y-1 md:col-span-2"> <div className="space-y-1">
<h3 className="text-sm font-medium mb-2">Notes</h3> <h3 className="text-sm font-medium mb-2">Contact</h3>
<InlineEditableField <dl>
variant="textarea" <InfoRow label="First Contact" value={formatDate(interest.dateFirstContact)} />
value={interest.notes} <InfoRow label="Last Contact" value={formatDate(interest.dateLastContact)} />
onSave={save('notes')} {interest.reservationStatus ? (
emptyText="No notes — click to add" <InfoRow label="Reservation" value={interest.reservationStatus} />
/> ) : null}
</div> </dl>
</div>
{/* Tags */} {/* Reminder */}
<div className="space-y-1 md:col-span-2"> {interest.reminderEnabled && (
<h3 className="text-sm font-medium mb-2">Tags</h3> <div className="space-y-1">
<InlineTagEditor <h3 className="text-sm font-medium mb-2">Reminder</h3>
endpoint={`/api/v1/interests/${interestId}/tags`} <dl>
currentTags={interest.tags ?? []} <InfoRow
invalidateKey={['interests', interestId]} label="Reminder Days"
/> value={interest.reminderDays ? `${interest.reminderDays} days` : null}
/>
<InfoRow label="Last Fired" value={formatDate(interest.reminderLastFired)} />
</dl>
</div>
)}
{/* Notes (editable, multiline) */}
<div className="space-y-1 md:col-span-2">
<h3 className="text-sm font-medium mb-2">Notes</h3>
<InlineEditableField
variant="textarea"
value={interest.notes}
onSave={save('notes')}
emptyText="No notes — click to add"
/>
</div>
{/* Tags */}
<div className="space-y-1 md:col-span-2">
<h3 className="text-sm font-medium mb-2">Tags</h3>
<InlineTagEditor
endpoint={`/api/v1/interests/${interestId}/tags`}
currentTags={interest.tags ?? []}
invalidateKey={['interests', interestId]}
/>
</div>
</div> </div>
</div> </div>
); );
@@ -198,20 +386,12 @@ export function getInterestTabs({
{ {
id: 'documents', id: 'documents',
label: 'Documents', label: 'Documents',
content: ( content: <InterestDocumentsTab interestId={interestId} />,
<div className="text-center py-12 text-muted-foreground">
<p>Documents tab available after document system is built</p>
</div>
),
}, },
{ {
id: 'files', id: 'files',
label: 'Files', label: 'Files',
content: ( content: <InterestFilesTab interestId={interestId} />,
<div className="text-center py-12 text-muted-foreground">
<p>Files tab available after file system is built</p>
</div>
),
}, },
{ {
id: 'recommendations', id: 'recommendations',

View File

@@ -8,18 +8,7 @@ import { DndContext, closestCenter, type DragEndEvent } from '@dnd-kit/core';
import { PipelineColumn } from '@/components/interests/pipeline-column'; import { PipelineColumn } from '@/components/interests/pipeline-column';
import { apiFetch } from '@/lib/api/client'; import { apiFetch } from '@/lib/api/client';
import { usePipelineStore } from '@/stores/pipeline-store'; import { usePipelineStore } from '@/stores/pipeline-store';
import { PIPELINE_STAGES } from '@/lib/constants'; import { PIPELINE_STAGES, STAGE_LABELS } from '@/lib/constants';
const STAGE_LABELS: Record<string, string> = {
open: 'Open',
details_sent: 'Details Sent',
in_communication: 'In Communication',
visited: 'Visited',
signed_eoi_nda: 'Signed EOI/NDA',
deposit_10pct: 'Deposit 10%',
contract: 'Contract',
completed: 'Completed',
};
interface InterestRow { interface InterestRow {
id: string; id: string;
@@ -116,7 +105,7 @@ export function PipelineBoard() {
<PipelineColumn <PipelineColumn
key={stage} key={stage}
stage={stage} stage={stage}
label={STAGE_LABELS[stage] ?? stage} label={STAGE_LABELS[stage]}
items={grouped[stage] ?? []} items={grouped[stage] ?? []}
/> />
))} ))}

View File

@@ -4,15 +4,106 @@ export const PIPELINE_STAGES = [
'open', 'open',
'details_sent', 'details_sent',
'in_communication', 'in_communication',
'visited', 'eoi_sent',
'signed_eoi_nda', 'eoi_signed',
'deposit_10pct', 'deposit_10pct',
'contract', 'contract_sent',
'contract_signed',
'completed', 'completed',
] as const; ] as const;
export type PipelineStage = (typeof PIPELINE_STAGES)[number]; export type PipelineStage = (typeof PIPELINE_STAGES)[number];
export const STAGE_LABELS: Record<PipelineStage, string> = {
open: 'Open',
details_sent: 'Details Sent',
in_communication: 'In Comms',
eoi_sent: 'EOI Sent',
eoi_signed: 'EOI Signed',
deposit_10pct: 'Deposit 10%',
contract_sent: 'Contract Sent',
contract_signed: 'Contract Signed',
completed: 'Completed',
};
export const STAGE_BADGE: Record<PipelineStage, string> = {
open: 'bg-slate-100 text-slate-700',
details_sent: 'bg-blue-100 text-blue-700',
in_communication: 'bg-sky-100 text-sky-700',
eoi_sent: 'bg-indigo-100 text-indigo-700',
eoi_signed: 'bg-amber-100 text-amber-700',
deposit_10pct: 'bg-orange-100 text-orange-700',
contract_sent: 'bg-yellow-100 text-yellow-700',
contract_signed: 'bg-green-100 text-green-700',
completed: 'bg-emerald-100 text-emerald-700',
};
export const STAGE_DOT: Record<PipelineStage, string> = {
open: 'bg-slate-400',
details_sent: 'bg-blue-500',
in_communication: 'bg-sky-500',
eoi_sent: 'bg-indigo-500',
eoi_signed: 'bg-amber-500',
deposit_10pct: 'bg-orange-500',
contract_sent: 'bg-yellow-500',
contract_signed: 'bg-green-500',
completed: 'bg-emerald-500',
};
// Default revenue-forecast probability weights per stage (01).
// Editable per port via settings (`pipeline_weights`); these are the fallbacks.
export const STAGE_WEIGHTS: Record<PipelineStage, number> = {
open: 0.05,
details_sent: 0.1,
in_communication: 0.2,
eoi_sent: 0.4,
eoi_signed: 0.6,
deposit_10pct: 0.75,
contract_sent: 0.85,
contract_signed: 0.95,
completed: 1.0,
};
// Allowed transitions out of each stage. Used by changeInterestStage to guard
// against accidental skips (e.g. dragging a card from Completed back to Open,
// or jumping Open straight to Completed). Forward moves of 1-2 stages are
// permitted; backward moves are limited to the immediate predecessor unless
// the lifecycle (EOI/contract chain) needs an explicit rewind.
export const STAGE_TRANSITIONS: Record<PipelineStage, readonly PipelineStage[]> = {
open: ['details_sent', 'in_communication', 'eoi_sent', 'eoi_signed'],
details_sent: ['open', 'in_communication', 'eoi_sent', 'eoi_signed'],
in_communication: ['open', 'details_sent', 'eoi_sent', 'eoi_signed'],
eoi_sent: ['in_communication', 'eoi_signed', 'deposit_10pct'],
eoi_signed: ['eoi_sent', 'deposit_10pct', 'contract_sent', 'contract_signed'],
deposit_10pct: ['eoi_signed', 'contract_sent', 'contract_signed'],
contract_sent: ['eoi_signed', 'deposit_10pct', 'contract_signed'],
contract_signed: ['contract_sent', 'deposit_10pct', 'completed'],
completed: ['contract_signed'],
};
export function canTransitionStage(from: string, to: string): boolean {
if (from === to) return true;
const fromStage = safeStage(from);
const toStage = safeStage(to);
return STAGE_TRANSITIONS[fromStage].includes(toStage);
}
export function safeStage(value: string | null | undefined): PipelineStage {
return PIPELINE_STAGES.includes(value as PipelineStage) ? (value as PipelineStage) : 'open';
}
export function stageLabel(stage: string | null | undefined): string {
return STAGE_LABELS[safeStage(stage)];
}
export function stageBadgeClass(stage: string | null | undefined): string {
return STAGE_BADGE[safeStage(stage)];
}
export function stageDotClass(stage: string | null | undefined): string {
return STAGE_DOT[safeStage(stage)];
}
// ─── Berth Statuses ────────────────────────────────────────────────────────── // ─── Berth Statuses ──────────────────────────────────────────────────────────
export const BERTH_STATUSES = ['available', 'under_offer', 'sold'] as const; export const BERTH_STATUSES = ['available', 'under_offer', 'sold'] as const;
@@ -21,23 +112,13 @@ export type BerthStatus = (typeof BERTH_STATUSES)[number];
// ─── Lead Categories ───────────────────────────────────────────────────────── // ─── Lead Categories ─────────────────────────────────────────────────────────
export const LEAD_CATEGORIES = [ export const LEAD_CATEGORIES = ['general_interest', 'specific_qualified', 'hot_lead'] as const;
'general_interest',
'specific_qualified',
'hot_lead',
] as const;
export type LeadCategory = (typeof LEAD_CATEGORIES)[number]; export type LeadCategory = (typeof LEAD_CATEGORIES)[number];
// ─── Document Types ────────────────────────────────────────────────────────── // ─── Document Types ──────────────────────────────────────────────────────────
export const DOCUMENT_TYPES = [ export const DOCUMENT_TYPES = ['eoi', 'contract', 'nda', 'reservation_agreement', 'other'] as const;
'eoi',
'contract',
'nda',
'reservation_agreement',
'other',
] as const;
export type DocumentType = (typeof DOCUMENT_TYPES)[number]; export type DocumentType = (typeof DOCUMENT_TYPES)[number];

View File

@@ -862,11 +862,9 @@ export async function seedPortData(portId: string, portSlug: string): Promise<Se
// ── 7. Interests (15) ────────────────────────────────────────────────── // ── 7. Interests (15) ──────────────────────────────────────────────────
// Spread across pipeline stages. // Spread across pipeline stages.
// Valid stages (from interests schema comment): // Valid stages (see PIPELINE_STAGES in src/lib/constants.ts):
// open, details_sent, in_communication, visited, signed_eoi_nda, // open, details_sent, in_communication, eoi_sent, eoi_signed,
// deposit_10pct, contract, completed // deposit_10pct, contract_sent, contract_signed, completed
// The task spec mentions "open, qualified, hot, won, lost" as logical buckets;
// map those loosely onto actual stages so we cover variety.
const interestPlan: Array<{ const interestPlan: Array<{
clientIdx: number; clientIdx: number;
berthIdx: number | null; berthIdx: number | null;
@@ -875,10 +873,11 @@ export async function seedPortData(portId: string, portSlug: string): Promise<Se
| 'open' | 'open'
| 'details_sent' | 'details_sent'
| 'in_communication' | 'in_communication'
| 'visited' | 'eoi_sent'
| 'signed_eoi_nda' | 'eoi_signed'
| 'deposit_10pct' | 'deposit_10pct'
| 'contract' | 'contract_sent'
| 'contract_signed'
| 'completed'; | 'completed';
leadCategory: 'general_interest' | 'specific_qualified' | 'hot_lead'; leadCategory: 'general_interest' | 'specific_qualified' | 'hot_lead';
source: 'website' | 'manual' | 'referral' | 'broker'; source: 'website' | 'manual' | 'referral' | 'broker';
@@ -916,7 +915,7 @@ export async function seedPortData(portId: string, portSlug: string): Promise<Se
clientIdx: 3, clientIdx: 3,
berthIdx: 3, berthIdx: 3,
yachtIdx: 6, yachtIdx: 6,
pipelineStage: 'visited', pipelineStage: 'eoi_sent',
leadCategory: 'specific_qualified', leadCategory: 'specific_qualified',
source: 'referral', source: 'referral',
daysAgoFirst: 40, daysAgoFirst: 40,
@@ -934,7 +933,7 @@ export async function seedPortData(portId: string, portSlug: string): Promise<Se
clientIdx: 5, clientIdx: 5,
berthIdx: 5, berthIdx: 5,
yachtIdx: 3, yachtIdx: 3,
pipelineStage: 'signed_eoi_nda', pipelineStage: 'eoi_signed',
leadCategory: 'hot_lead', leadCategory: 'hot_lead',
source: 'manual', source: 'manual',
daysAgoFirst: 55, daysAgoFirst: 55,
@@ -952,7 +951,7 @@ export async function seedPortData(portId: string, portSlug: string): Promise<Se
clientIdx: 0, clientIdx: 0,
berthIdx: 7, berthIdx: 7,
yachtIdx: 5, yachtIdx: 5,
pipelineStage: 'contract', pipelineStage: 'contract_signed',
leadCategory: 'hot_lead', leadCategory: 'hot_lead',
source: 'broker', source: 'broker',
daysAgoFirst: 90, daysAgoFirst: 90,
@@ -1017,7 +1016,7 @@ export async function seedPortData(portId: string, portSlug: string): Promise<Se
clientIdx: 6, clientIdx: 6,
berthIdx: 9, berthIdx: 9,
yachtIdx: 4, yachtIdx: 4,
pipelineStage: 'visited', pipelineStage: 'eoi_sent',
leadCategory: 'specific_qualified', leadCategory: 'specific_qualified',
source: 'broker', source: 'broker',
daysAgoFirst: 45, daysAgoFirst: 45,

View File

@@ -74,7 +74,9 @@ async function reservationNoAgreement(portId: string): Promise<AlertCandidate[]>
// Pipeline stuck in mid-funnel stages with no contact for 14+ days. // Pipeline stuck in mid-funnel stages with no contact for 14+ days.
async function interestStale(portId: string): Promise<AlertCandidate[]> { async function interestStale(portId: string): Promise<AlertCandidate[]> {
const STALE_STAGES = ['details_sent', 'in_communication', 'visited']; // Mid-funnel stages where silence is a problem. EOI/deposit/contract stages
// have their own dedicated alerts (eoi.unsigned_long, deposit_overdue, etc.).
const STALE_STAGES = ['details_sent', 'in_communication', 'eoi_sent'];
const rows = await db const rows = await db
.select({ .select({
id: interests.id, id: interests.id,

View File

@@ -12,6 +12,7 @@ import { analyticsSnapshots } from '@/lib/db/schema/insights';
import { interests } from '@/lib/db/schema/interests'; import { interests } from '@/lib/db/schema/interests';
import { invoices } from '@/lib/db/schema/financial'; import { invoices } from '@/lib/db/schema/financial';
import { berthReservations } from '@/lib/db/schema/reservations'; import { berthReservations } from '@/lib/db/schema/reservations';
import { PIPELINE_STAGES } from '@/lib/constants';
export type DateRange = '7d' | '30d' | '90d' | 'today'; export type DateRange = '7d' | '30d' | '90d' | 'today';
@@ -117,17 +118,6 @@ function rangeToDays(range: DateRange): number {
// ─── Computations ───────────────────────────────────────────────────────────── // ─── Computations ─────────────────────────────────────────────────────────────
const PIPELINE_STAGES = [
'open',
'details_sent',
'in_communication',
'visited',
'signed_eoi_nda',
'deposit_10pct',
'contract',
'completed',
] as const;
export async function computePipelineFunnel( export async function computePipelineFunnel(
portId: string, portId: string,
range: DateRange, range: DateRange,

View File

@@ -5,20 +5,9 @@ import { clients } from '@/lib/db/schema/clients';
import { interests } from '@/lib/db/schema/interests'; import { interests } from '@/lib/db/schema/interests';
import { berths } from '@/lib/db/schema/berths'; import { berths } from '@/lib/db/schema/berths';
import { systemSettings, auditLogs } from '@/lib/db/schema/system'; import { systemSettings, auditLogs } from '@/lib/db/schema/system';
import { PIPELINE_STAGES } from '@/lib/constants'; import { PIPELINE_STAGES, STAGE_WEIGHTS } from '@/lib/constants';
// ─── Default pipeline weights ──────────────────────────────────────────────── const DEFAULT_PIPELINE_WEIGHTS: Record<string, number> = STAGE_WEIGHTS;
const DEFAULT_PIPELINE_WEIGHTS: Record<string, number> = {
open: 0.05,
details_sent: 0.10,
in_communication: 0.20,
visited: 0.35,
signed_eoi_nda: 0.50,
deposit_10pct: 0.70,
contract: 0.90,
completed: 1.00,
};
// ─── KPIs ───────────────────────────────────────────────────────────────────── // ─── KPIs ─────────────────────────────────────────────────────────────────────
@@ -98,10 +87,7 @@ export async function getRevenueForecast(portId: string) {
let weightsSource: 'db' | 'default' = 'default'; let weightsSource: 'db' | 'default' = 'default';
const settingRow = await db.query.systemSettings.findFirst({ const settingRow = await db.query.systemSettings.findFirst({
where: and( where: and(eq(systemSettings.key, 'pipeline_weights'), eq(systemSettings.portId, portId)),
eq(systemSettings.key, 'pipeline_weights'),
eq(systemSettings.portId, portId),
),
}); });
if (settingRow?.value) { if (settingRow?.value) {
@@ -155,10 +141,7 @@ export async function getRevenueForecast(portId: string) {
weightedValue: stageMap[stage]?.weightedValue ?? 0, weightedValue: stageMap[stage]?.weightedValue ?? 0,
})); }));
const totalWeightedValue = stageBreakdown.reduce( const totalWeightedValue = stageBreakdown.reduce((acc, s) => acc + s.weightedValue, 0);
(acc, s) => acc + s.weightedValue,
0,
);
return { return {
totalWeightedValue, totalWeightedValue,

View File

@@ -24,6 +24,7 @@ import { minioClient, buildStoragePath } from '@/lib/minio';
import { env } from '@/lib/env'; import { env } from '@/lib/env';
import { logger } from '@/lib/logger'; import { logger } from '@/lib/logger';
import { evaluateRule } from '@/lib/services/berth-rules-engine'; import { evaluateRule } from '@/lib/services/berth-rules-engine';
import { advanceStageIfBehind } from '@/lib/services/interests.service';
import { import {
createDocument as documensoCreate, createDocument as documensoCreate,
sendDocument as documensoSend, sendDocument as documensoSend,
@@ -596,6 +597,9 @@ export async function sendForSigning(documentId: string, portId: string, meta: A
// Trigger berth rules // Trigger berth rules
void evaluateRule('eoi_sent', interest.id, portId, meta); void evaluateRule('eoi_sent', interest.id, portId, meta);
// Advance pipeline stage to eoi_sent (no-op if already further along).
void advanceStageIfBehind(interest.id, portId, 'eoi_sent', meta, 'EOI sent for signing');
} }
// Create document event // Create document event
@@ -686,6 +690,15 @@ export async function uploadSignedManually(
if (interest) { if (interest) {
void evaluateRule('eoi_signed', doc.interestId, portId, meta); void evaluateRule('eoi_signed', doc.interestId, portId, meta);
// Advance to eoi_signed (no-op if already past it).
void advanceStageIfBehind(
doc.interestId,
portId,
'eoi_signed',
meta,
'Signed EOI uploaded manually',
);
} }
} }
@@ -877,12 +890,22 @@ export async function handleDocumentCompleted(eventData: { documentId: string })
.where(eq(interests.id, doc.interestId)); .where(eq(interests.id, doc.interestId));
if (interest) { if (interest) {
void evaluateRule('eoi_signed', doc.interestId, doc.portId, { const systemMeta: AuditMeta = {
userId: 'system', userId: 'system',
portId: doc.portId, portId: doc.portId,
ipAddress: '0.0.0.0', ipAddress: '0.0.0.0',
userAgent: 'webhook', userAgent: 'webhook',
}); };
void evaluateRule('eoi_signed', doc.interestId, doc.portId, systemMeta);
// Advance to eoi_signed (no-op if interest already past it).
void advanceStageIfBehind(
doc.interestId,
doc.portId,
'eoi_signed',
systemMeta,
'EOI signed via Documenso',
);
} }
} }

View File

@@ -6,6 +6,7 @@ import { interests, interestNotes } from '@/lib/db/schema/interests';
import { reminders } from '@/lib/db/schema/operations'; import { reminders } from '@/lib/db/schema/operations';
import { emailThreads } from '@/lib/db/schema/email'; import { emailThreads } from '@/lib/db/schema/email';
import { logger } from '@/lib/logger'; import { logger } from '@/lib/logger';
import { PIPELINE_STAGES } from '@/lib/constants';
// ─── Types ──────────────────────────────────────────────────────────────────── // ─── Types ────────────────────────────────────────────────────────────────────
@@ -42,19 +43,8 @@ function scorePipelineAge(createdAt: Date): number {
} }
function scoreStageSpeed(createdAt: Date, pipelineStage: string): number { function scoreStageSpeed(createdAt: Date, pipelineStage: string): number {
// Approximate stage index based on known pipeline order const idx = PIPELINE_STAGES.indexOf(pipelineStage as (typeof PIPELINE_STAGES)[number]);
const STAGE_ORDER: Record<string, number> = { const stageIndex = idx === -1 ? 0 : idx;
open: 0,
details_sent: 1,
in_communication: 2,
visited: 3,
signed_eoi_nda: 4,
deposit_10pct: 5,
contract: 6,
completed: 7,
};
const stageIndex = STAGE_ORDER[pipelineStage] ?? 0;
if (stageIndex === 0) { if (stageIndex === 0) {
// Still at open — no progression // Still at open — no progression
return 0; return 0;

View File

@@ -14,6 +14,7 @@ import { setEntityTags } from '@/lib/services/entity-tags.helper';
import { buildListQuery } from '@/lib/db/query-builder'; import { buildListQuery } from '@/lib/db/query-builder';
import { diffEntity } from '@/lib/entity-diff'; import { diffEntity } from '@/lib/entity-diff';
import { softDelete, restore, withTransaction } from '@/lib/db/utils'; import { softDelete, restore, withTransaction } from '@/lib/db/utils';
import { PIPELINE_STAGES, canTransitionStage, type PipelineStage } from '@/lib/constants';
import type { import type {
CreateInterestInput, CreateInterestInput,
UpdateInterestInput, UpdateInterestInput,
@@ -459,6 +460,15 @@ export async function changeInterestStage(
throw new ValidationError('yachtId is required before leaving stage=open'); throw new ValidationError('yachtId is required before leaving stage=open');
} }
// Block egregious skips. The transition table allows reasonable forward
// jumps (e.g. open → eoi_sent) while rejecting things like completed → open
// or open → contract_signed. Same-stage no-ops are allowed.
if (!canTransitionStage(existing.pipelineStage, data.pipelineStage)) {
throw new ValidationError(
`Cannot move interest from "${existing.pipelineStage}" directly to "${data.pipelineStage}".`,
);
}
const oldStage = existing.pipelineStage; const oldStage = existing.pipelineStage;
const [updated] = await db const [updated] = await db
@@ -469,9 +479,11 @@ export async function changeInterestStage(
// BR-133: Auto-populate milestones based on stage // BR-133: Auto-populate milestones based on stage
const milestoneUpdates: Record<string, unknown> = {}; const milestoneUpdates: Record<string, unknown> = {};
if (data.pipelineStage === 'signed_eoi_nda') milestoneUpdates.dateEoiSigned = new Date(); if (data.pipelineStage === 'eoi_sent') milestoneUpdates.dateEoiSent = new Date();
if (data.pipelineStage === 'contract') milestoneUpdates.dateContractSigned = new Date(); if (data.pipelineStage === 'eoi_signed') milestoneUpdates.dateEoiSigned = new Date();
if (data.pipelineStage === 'deposit_10pct') milestoneUpdates.dateDepositReceived = new Date(); if (data.pipelineStage === 'deposit_10pct') milestoneUpdates.dateDepositReceived = new Date();
if (data.pipelineStage === 'contract_sent') milestoneUpdates.dateContractSent = new Date();
if (data.pipelineStage === 'contract_signed') milestoneUpdates.dateContractSigned = new Date();
if (Object.keys(milestoneUpdates).length > 0) { if (Object.keys(milestoneUpdates).length > 0) {
await db await db
.update(interests) .update(interests)
@@ -527,6 +539,45 @@ export async function changeInterestStage(
return updated!; return updated!;
} }
// ─── Advance Stage If Behind ─────────────────────────────────────────────────
//
// Moves an interest forward to `target` if (and only if) it is currently behind
// it in the pipeline order. Used by lifecycle events (EOI sent, EOI signed,
// deposit recorded, contract signed) so the user-visible stage tracks reality
// without overwriting a more advanced state — e.g. a late-arriving signed-EOI
// webhook on an interest that has already moved on to `contract_sent` is a
// no-op rather than a regression.
//
// Returns true when the stage was changed.
export async function advanceStageIfBehind(
interestId: string,
portId: string,
target: PipelineStage,
meta: AuditMeta,
reason?: string,
): Promise<boolean> {
const existing = await db.query.interests.findFirst({
where: and(eq(interests.id, interestId), eq(interests.portId, portId)),
});
if (!existing) return false;
const currentIdx = PIPELINE_STAGES.indexOf(existing.pipelineStage as PipelineStage);
const targetIdx = PIPELINE_STAGES.indexOf(target);
if (currentIdx === -1 || targetIdx === -1 || currentIdx >= targetIdx) {
return false;
}
// yachtId gate: changeInterestStage requires a yacht before leaving `open`.
// EOI events imply a yacht is in the picture, but if the data is missing we
// bail rather than throw — the EOI itself shouldn't fail because of this.
if (existing.pipelineStage === 'open' && !existing.yachtId) {
return false;
}
await changeInterestStage(interestId, portId, { pipelineStage: target, reason }, meta);
return true;
}
// ─── Archive / Restore ──────────────────────────────────────────────────────── // ─── Archive / Restore ────────────────────────────────────────────────────────
export async function archiveInterest(id: string, portId: string, meta: AuditMeta) { export async function archiveInterest(id: string, portId: string, meta: AuditMeta) {

View File

@@ -30,7 +30,14 @@ describe('analytics service', () => {
const port = await makePort(); const port = await makePort();
const client = await makeClient({ portId: port.id }); const client = await makeClient({ portId: port.id });
// 3 open, 2 details_sent, 1 visited // 3 open, 2 details_sent, 1 visited
for (const stage of ['open', 'open', 'open', 'details_sent', 'details_sent', 'visited']) { for (const stage of [
'open',
'open',
'open',
'details_sent',
'details_sent',
'in_communication',
]) {
await db.insert(interests).values({ await db.insert(interests).values({
portId: port.id, portId: port.id,
clientId: client.id, clientId: client.id,
@@ -42,7 +49,7 @@ describe('analytics service', () => {
const open = result.stages.find((s) => s.stage === 'open'); const open = result.stages.find((s) => s.stage === 'open');
const details = result.stages.find((s) => s.stage === 'details_sent'); const details = result.stages.find((s) => s.stage === 'details_sent');
const visited = result.stages.find((s) => s.stage === 'visited'); const visited = result.stages.find((s) => s.stage === 'in_communication');
expect(open?.count).toBe(3); expect(open?.count).toBe(3);
expect(open?.conversionPct).toBe(100); expect(open?.conversionPct).toBe(100);
expect(details?.count).toBe(2); expect(details?.count).toBe(2);
@@ -54,7 +61,7 @@ describe('analytics service', () => {
it('returns zeros when port has no interests', async () => { it('returns zeros when port has no interests', async () => {
const port = await makePort(); const port = await makePort();
const result = await computePipelineFunnel(port.id, '30d'); const result = await computePipelineFunnel(port.id, '30d');
expect(result.stages).toHaveLength(8); expect(result.stages).toHaveLength(9);
expect(result.stages.every((s) => s.count === 0)).toBe(true); expect(result.stages.every((s) => s.count === 0)).toBe(true);
}); });
}); });

View File

@@ -1,13 +1,9 @@
import { describe, it, expect } from 'vitest'; import { describe, it, expect } from 'vitest';
import { import { PIPELINE_STAGES, BERTH_STATUSES, NOTIFICATION_TYPES } from '@/lib/constants';
PIPELINE_STAGES,
BERTH_STATUSES,
NOTIFICATION_TYPES,
} from '@/lib/constants';
describe('PIPELINE_STAGES', () => { describe('PIPELINE_STAGES', () => {
it('has exactly 8 entries', () => { it('has exactly 9 entries', () => {
expect(PIPELINE_STAGES).toHaveLength(8); expect(PIPELINE_STAGES).toHaveLength(9);
}); });
it('starts with "open"', () => { it('starts with "open"', () => {
@@ -23,25 +19,18 @@ describe('PIPELINE_STAGES', () => {
'open', 'open',
'details_sent', 'details_sent',
'in_communication', 'in_communication',
'visited', 'eoi_sent',
'signed_eoi_nda', 'eoi_signed',
'deposit_10pct', 'deposit_10pct',
'contract', 'contract_sent',
'contract_signed',
'completed', 'completed',
]); ]);
}); });
it('is a readonly (frozen) tuple — cannot be mutated at runtime', () => { it('is a readonly tuple — type-level immutability via `as const`', () => {
expect(() => { const arr = PIPELINE_STAGES as unknown as string[];
// TypeScript readonly doesn't prevent runtime mutation of `as const` arrays, expect(arr).toHaveLength(9);
// but they are not Object.frozen. The important thing is the `as const` means
// the type system protects it. We verify immutability via the TypeScript type
// and check the array is not a plain mutable array.
const arr = PIPELINE_STAGES as unknown as string[];
// Attempting splice on a readonly const-asserted array at runtime won't throw
// but the values should be what we defined.
expect(arr).toHaveLength(8);
}).not.toThrow();
}); });
it('has no duplicate entries', () => { it('has no duplicate entries', () => {

View File

@@ -115,10 +115,11 @@ describe('createInterestSchema', () => {
'open', 'open',
'details_sent', 'details_sent',
'in_communication', 'in_communication',
'visited', 'eoi_sent',
'signed_eoi_nda', 'eoi_signed',
'deposit_10pct', 'deposit_10pct',
'contract', 'contract_sent',
'contract_signed',
'completed', 'completed',
]; ];
for (const stage of stages) { for (const stage of stages) {
@@ -143,7 +144,7 @@ describe('createInterestSchema', () => {
describe('changeStageSchema', () => { describe('changeStageSchema', () => {
it('accepts a valid stage', () => { it('accepts a valid stage', () => {
expect(changeStageSchema.safeParse({ pipelineStage: 'visited' }).success).toBe(true); expect(changeStageSchema.safeParse({ pipelineStage: 'in_communication' }).success).toBe(true);
}); });
it('rejects invalid stage', () => { it('rejects invalid stage', () => {