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:
@@ -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,
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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) {
|
||||
|
||||
Reference in New Issue
Block a user