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

@@ -4,15 +4,106 @@ export const PIPELINE_STAGES = [
'open',
'details_sent',
'in_communication',
'visited',
'signed_eoi_nda',
'eoi_sent',
'eoi_signed',
'deposit_10pct',
'contract',
'contract_sent',
'contract_signed',
'completed',
] as const;
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 ──────────────────────────────────────────────────────────
export const BERTH_STATUSES = ['available', 'under_offer', 'sold'] as const;
@@ -21,23 +112,13 @@ export type BerthStatus = (typeof BERTH_STATUSES)[number];
// ─── Lead Categories ─────────────────────────────────────────────────────────
export const LEAD_CATEGORIES = [
'general_interest',
'specific_qualified',
'hot_lead',
] as const;
export const LEAD_CATEGORIES = ['general_interest', 'specific_qualified', 'hot_lead'] as const;
export type LeadCategory = (typeof LEAD_CATEGORIES)[number];
// ─── Document Types ──────────────────────────────────────────────────────────
export const DOCUMENT_TYPES = [
'eoi',
'contract',
'nda',
'reservation_agreement',
'other',
] as const;
export const DOCUMENT_TYPES = ['eoi', 'contract', 'nda', 'reservation_agreement', 'other'] as const;
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) ──────────────────────────────────────────────────
// Spread across pipeline stages.
// Valid stages (from interests schema comment):
// open, details_sent, in_communication, visited, signed_eoi_nda,
// deposit_10pct, contract, completed
// The task spec mentions "open, qualified, hot, won, lost" as logical buckets;
// map those loosely onto actual stages so we cover variety.
// Valid stages (see PIPELINE_STAGES in src/lib/constants.ts):
// open, details_sent, in_communication, eoi_sent, eoi_signed,
// deposit_10pct, contract_sent, contract_signed, completed
const interestPlan: Array<{
clientIdx: number;
berthIdx: number | null;
@@ -875,10 +873,11 @@ export async function seedPortData(portId: string, portSlug: string): Promise<Se
| 'open'
| 'details_sent'
| 'in_communication'
| 'visited'
| 'signed_eoi_nda'
| 'eoi_sent'
| 'eoi_signed'
| 'deposit_10pct'
| 'contract'
| 'contract_sent'
| 'contract_signed'
| 'completed';
leadCategory: 'general_interest' | 'specific_qualified' | 'hot_lead';
source: 'website' | 'manual' | 'referral' | 'broker';
@@ -916,7 +915,7 @@ export async function seedPortData(portId: string, portSlug: string): Promise<Se
clientIdx: 3,
berthIdx: 3,
yachtIdx: 6,
pipelineStage: 'visited',
pipelineStage: 'eoi_sent',
leadCategory: 'specific_qualified',
source: 'referral',
daysAgoFirst: 40,
@@ -934,7 +933,7 @@ export async function seedPortData(portId: string, portSlug: string): Promise<Se
clientIdx: 5,
berthIdx: 5,
yachtIdx: 3,
pipelineStage: 'signed_eoi_nda',
pipelineStage: 'eoi_signed',
leadCategory: 'hot_lead',
source: 'manual',
daysAgoFirst: 55,
@@ -952,7 +951,7 @@ export async function seedPortData(portId: string, portSlug: string): Promise<Se
clientIdx: 0,
berthIdx: 7,
yachtIdx: 5,
pipelineStage: 'contract',
pipelineStage: 'contract_signed',
leadCategory: 'hot_lead',
source: 'broker',
daysAgoFirst: 90,
@@ -1017,7 +1016,7 @@ export async function seedPortData(portId: string, portSlug: string): Promise<Se
clientIdx: 6,
berthIdx: 9,
yachtIdx: 4,
pipelineStage: 'visited',
pipelineStage: 'eoi_sent',
leadCategory: 'specific_qualified',
source: 'broker',
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.
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
.select({
id: interests.id,

View File

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

View File

@@ -5,20 +5,9 @@ import { clients } from '@/lib/db/schema/clients';
import { interests } from '@/lib/db/schema/interests';
import { berths } from '@/lib/db/schema/berths';
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> = {
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,
};
const DEFAULT_PIPELINE_WEIGHTS: Record<string, number> = STAGE_WEIGHTS;
// ─── KPIs ─────────────────────────────────────────────────────────────────────
@@ -98,10 +87,7 @@ export async function getRevenueForecast(portId: string) {
let weightsSource: 'db' | 'default' = 'default';
const settingRow = await db.query.systemSettings.findFirst({
where: and(
eq(systemSettings.key, 'pipeline_weights'),
eq(systemSettings.portId, portId),
),
where: and(eq(systemSettings.key, 'pipeline_weights'), eq(systemSettings.portId, portId)),
});
if (settingRow?.value) {
@@ -155,10 +141,7 @@ export async function getRevenueForecast(portId: string) {
weightedValue: stageMap[stage]?.weightedValue ?? 0,
}));
const totalWeightedValue = stageBreakdown.reduce(
(acc, s) => acc + s.weightedValue,
0,
);
const totalWeightedValue = stageBreakdown.reduce((acc, s) => acc + s.weightedValue, 0);
return {
totalWeightedValue,

View File

@@ -24,6 +24,7 @@ import { minioClient, buildStoragePath } from '@/lib/minio';
import { env } from '@/lib/env';
import { logger } from '@/lib/logger';
import { evaluateRule } from '@/lib/services/berth-rules-engine';
import { advanceStageIfBehind } from '@/lib/services/interests.service';
import {
createDocument as documensoCreate,
sendDocument as documensoSend,
@@ -596,6 +597,9 @@ export async function sendForSigning(documentId: string, portId: string, meta: A
// Trigger berth rules
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
@@ -686,6 +690,15 @@ export async function uploadSignedManually(
if (interest) {
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));
if (interest) {
void evaluateRule('eoi_signed', doc.interestId, doc.portId, {
const systemMeta: AuditMeta = {
userId: 'system',
portId: doc.portId,
ipAddress: '0.0.0.0',
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 { emailThreads } from '@/lib/db/schema/email';
import { logger } from '@/lib/logger';
import { PIPELINE_STAGES } from '@/lib/constants';
// ─── Types ────────────────────────────────────────────────────────────────────
@@ -42,19 +43,8 @@ function scorePipelineAge(createdAt: Date): number {
}
function scoreStageSpeed(createdAt: Date, pipelineStage: string): number {
// Approximate stage index based on known pipeline order
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 stageIndex = STAGE_ORDER[pipelineStage] ?? 0;
const idx = PIPELINE_STAGES.indexOf(pipelineStage as (typeof PIPELINE_STAGES)[number]);
const stageIndex = idx === -1 ? 0 : idx;
if (stageIndex === 0) {
// Still at open — no progression
return 0;

View File

@@ -14,6 +14,7 @@ import { setEntityTags } from '@/lib/services/entity-tags.helper';
import { buildListQuery } from '@/lib/db/query-builder';
import { diffEntity } from '@/lib/entity-diff';
import { softDelete, restore, withTransaction } from '@/lib/db/utils';
import { PIPELINE_STAGES, canTransitionStage, type PipelineStage } from '@/lib/constants';
import type {
CreateInterestInput,
UpdateInterestInput,
@@ -459,6 +460,15 @@ export async function changeInterestStage(
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 [updated] = await db
@@ -469,9 +479,11 @@ export async function changeInterestStage(
// BR-133: Auto-populate milestones based on stage
const milestoneUpdates: Record<string, unknown> = {};
if (data.pipelineStage === 'signed_eoi_nda') milestoneUpdates.dateEoiSigned = new Date();
if (data.pipelineStage === 'contract') milestoneUpdates.dateContractSigned = new Date();
if (data.pipelineStage === 'eoi_sent') milestoneUpdates.dateEoiSent = new Date();
if (data.pipelineStage === 'eoi_signed') milestoneUpdates.dateEoiSigned = 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) {
await db
.update(interests)
@@ -527,6 +539,45 @@ export async function changeInterestStage(
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 ────────────────────────────────────────────────────────
export async function archiveInterest(id: string, portId: string, meta: AuditMeta) {