feat(pipeline): 9→7 stage refactor + v1.1 hardening wave
Replaces the legacy 9-stage pipeline with 7 canonical stages
(enquiry → qualified → eoi → reservation → deposit_paid → contract →
nurturing) plus three doc sub-status columns (eoi_doc_status,
reservation_doc_status, contract_doc_status) that track sent/signed
within a single stage instead of branching it.
Schema (migration 0062):
- interests gains assigned_to, deposit_expected_amount/currency,
three doc-status columns, two documenso-id columns, and
date_reservation_signed.
- New tables: qualification_criteria (per-port admin-configurable),
interest_qualifications (per-interest state), payments (deposit /
balance / refund records keyed to interest + client).
- Default qualification criteria seeded for every existing port.
- Dummy-data UPDATEs collapse Sent/Signed pairs and 'completed' into
the new stage + doc-status + outcome shape.
Migration 0063 adds interest_contact_log.voice_transcript and
template_used columns for v1.1-A/B (quick-template buttons + voice
transcription via Web Speech API).
v1.1 phase work bundled here:
- A/B: Quick-template buttons (Call / Visit / Email) + mic toggle on
the contact-log compose dialog (useVoiceTranscription hook).
- C: berth-rules-engine wraps state writes in pg_advisory_xact_lock
with an idempotent re-read; emits rule_evaluated audit traces.
- D: Documenso webhook: reservation/contract sub-status stamping
moved out of the PDF-download try-block so a download failure
no longer swallows the stamp. New integration test coverage.
- E: /admin/qualification-criteria CRUD page + admin component.
- F: default_new_interest_owner exposed in System Settings.
- G: recentActivityCount + active_engagement deal-pulse signal
surfaced as a chip on interests + hot-deals card.
- H: interest_assigned notification on assignedTo change (skips
self-assign, uses a dedupe key).
Plus the supporting components: AssignedToChip, DealPulseChip,
PaymentsSection, QualificationChecklist, MultiEoiChip,
SkipAheadBanner, WonStatusPanel, InterestBerthStatusBanner,
SupplementalInfoRequestButton, UserPicker.
Tests: 1370/1370 vitest pass (added deal-health unit suite +
expanded constants/validators/pipeline-transitions coverage). tsc
clean, eslint clean.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -649,19 +649,17 @@ export function makeCreateClientInput(overrides?: { fullName?: string; portId?:
|
||||
export function makeCreateInterestInput(overrides?: {
|
||||
clientId?: string;
|
||||
pipelineStage?:
|
||||
| 'open'
|
||||
| 'details_sent'
|
||||
| 'in_communication'
|
||||
| 'eoi_sent'
|
||||
| 'eoi_signed'
|
||||
| 'deposit_10pct'
|
||||
| 'contract_sent'
|
||||
| 'contract_signed'
|
||||
| 'completed';
|
||||
| 'enquiry'
|
||||
| 'qualified'
|
||||
| 'nurturing'
|
||||
| 'eoi'
|
||||
| 'reservation'
|
||||
| 'deposit_paid'
|
||||
| 'contract';
|
||||
}) {
|
||||
return {
|
||||
clientId: overrides?.clientId ?? crypto.randomUUID(),
|
||||
pipelineStage: overrides?.pipelineStage ?? ('open' as const),
|
||||
pipelineStage: overrides?.pipelineStage ?? ('enquiry' as const),
|
||||
reminderEnabled: false,
|
||||
tagIds: [] as string[],
|
||||
};
|
||||
|
||||
@@ -29,14 +29,14 @@ describe('analytics service', () => {
|
||||
it('aggregates interests by stage with conversion percentages', async () => {
|
||||
const port = await makePort();
|
||||
const client = await makeClient({ portId: port.id });
|
||||
// 3 open, 2 details_sent, 1 visited
|
||||
// 3 enquiry, 2 qualified, 1 nurturing
|
||||
for (const stage of [
|
||||
'open',
|
||||
'open',
|
||||
'open',
|
||||
'details_sent',
|
||||
'details_sent',
|
||||
'in_communication',
|
||||
'enquiry',
|
||||
'enquiry',
|
||||
'enquiry',
|
||||
'qualified',
|
||||
'qualified',
|
||||
'nurturing',
|
||||
]) {
|
||||
await db.insert(interests).values({
|
||||
portId: port.id,
|
||||
@@ -47,21 +47,21 @@ describe('analytics service', () => {
|
||||
|
||||
const result = await computePipelineFunnel(port.id, '30d');
|
||||
|
||||
const open = result.stages.find((s) => s.stage === 'open');
|
||||
const details = result.stages.find((s) => s.stage === 'details_sent');
|
||||
const visited = result.stages.find((s) => s.stage === 'in_communication');
|
||||
expect(open?.count).toBe(3);
|
||||
expect(open?.conversionPct).toBe(100);
|
||||
expect(details?.count).toBe(2);
|
||||
expect(details?.conversionPct).toBeCloseTo(66.7, 0);
|
||||
expect(visited?.count).toBe(1);
|
||||
expect(visited?.conversionPct).toBeCloseTo(33.3, 0);
|
||||
const enquiry = result.stages.find((s) => s.stage === 'enquiry');
|
||||
const qualified = result.stages.find((s) => s.stage === 'qualified');
|
||||
const nurturing = result.stages.find((s) => s.stage === 'nurturing');
|
||||
expect(enquiry?.count).toBe(3);
|
||||
expect(enquiry?.conversionPct).toBe(100);
|
||||
expect(qualified?.count).toBe(2);
|
||||
expect(qualified?.conversionPct).toBeCloseTo(66.7, 0);
|
||||
expect(nurturing?.count).toBe(1);
|
||||
expect(nurturing?.conversionPct).toBeCloseTo(33.3, 0);
|
||||
});
|
||||
|
||||
it('returns zeros when port has no interests', async () => {
|
||||
const port = await makePort();
|
||||
const result = await computePipelineFunnel(port.id, '30d');
|
||||
expect(result.stages).toHaveLength(9);
|
||||
expect(result.stages).toHaveLength(7);
|
||||
expect(result.stages.every((s) => s.count === 0)).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -236,7 +236,7 @@ describe('CRUD Audit — Interests', () => {
|
||||
const log = logs[0]!;
|
||||
expect(log.entity_type).toBe('interest');
|
||||
const newVal = log.new_value as Record<string, unknown>;
|
||||
expect(newVal.pipelineStage).toBe('open');
|
||||
expect(newVal.pipelineStage).toBe('enquiry');
|
||||
});
|
||||
|
||||
itDb('update generates audit log with action=update', async () => {
|
||||
|
||||
@@ -17,6 +17,7 @@ import { NextRequest } from 'next/server';
|
||||
import { POST as documensoWebhook } from '@/app/api/webhooks/documenso/route';
|
||||
import { db } from '@/lib/db';
|
||||
import { documents, documentEvents } from '@/lib/db/schema/documents';
|
||||
import { interests } from '@/lib/db/schema/interests';
|
||||
import { env } from '@/lib/env';
|
||||
import { makeClient, makePort } from '../helpers/factories';
|
||||
|
||||
@@ -81,6 +82,86 @@ describe('Documenso webhook route', () => {
|
||||
expect(events.length).toBeGreaterThanOrEqual(1);
|
||||
});
|
||||
|
||||
it('DOCUMENT_COMPLETED for a reservation_agreement stamps reservationDocStatus on the linked interest', async () => {
|
||||
const port = await makePort();
|
||||
const client = await makeClient({ portId: port.id });
|
||||
|
||||
const [interest] = await db
|
||||
.insert(interests)
|
||||
.values({
|
||||
portId: port.id,
|
||||
clientId: client.id,
|
||||
pipelineStage: 'reservation',
|
||||
})
|
||||
.returning();
|
||||
|
||||
const documensoId = `docu-resv-${Date.now()}`;
|
||||
await db.insert(documents).values({
|
||||
portId: port.id,
|
||||
clientId: client.id,
|
||||
interestId: interest!.id,
|
||||
documentType: 'reservation_agreement',
|
||||
title: 'Reservation webhook test',
|
||||
status: 'sent',
|
||||
documensoId,
|
||||
createdBy: 'seed',
|
||||
});
|
||||
|
||||
const req = buildRequest(
|
||||
{
|
||||
event: 'DOCUMENT_COMPLETED',
|
||||
payload: { id: documensoId, recipients: [] },
|
||||
},
|
||||
env.DOCUMENSO_WEBHOOK_SECRET,
|
||||
);
|
||||
const res = await documensoWebhook(req);
|
||||
expect(res.status).toBe(200);
|
||||
|
||||
const [updated] = await db.select().from(interests).where(eq(interests.id, interest!.id));
|
||||
expect(updated?.reservationDocStatus).toBe('signed');
|
||||
expect(updated?.dateReservationSigned).not.toBeNull();
|
||||
});
|
||||
|
||||
it('DOCUMENT_COMPLETED for a contract stamps contractDocStatus on the linked interest', async () => {
|
||||
const port = await makePort();
|
||||
const client = await makeClient({ portId: port.id });
|
||||
|
||||
const [interest] = await db
|
||||
.insert(interests)
|
||||
.values({
|
||||
portId: port.id,
|
||||
clientId: client.id,
|
||||
pipelineStage: 'contract',
|
||||
})
|
||||
.returning();
|
||||
|
||||
const documensoId = `docu-contract-${Date.now()}`;
|
||||
await db.insert(documents).values({
|
||||
portId: port.id,
|
||||
clientId: client.id,
|
||||
interestId: interest!.id,
|
||||
documentType: 'contract',
|
||||
title: 'Contract webhook test',
|
||||
status: 'sent',
|
||||
documensoId,
|
||||
createdBy: 'seed',
|
||||
});
|
||||
|
||||
const req = buildRequest(
|
||||
{
|
||||
event: 'DOCUMENT_COMPLETED',
|
||||
payload: { id: documensoId, recipients: [] },
|
||||
},
|
||||
env.DOCUMENSO_WEBHOOK_SECRET,
|
||||
);
|
||||
const res = await documensoWebhook(req);
|
||||
expect(res.status).toBe(200);
|
||||
|
||||
const [updated] = await db.select().from(interests).where(eq(interests.id, interest!.id));
|
||||
expect(updated?.contractDocStatus).toBe('signed');
|
||||
expect(updated?.dateContractSigned).not.toBeNull();
|
||||
});
|
||||
|
||||
it('replays of the same body are no-ops (signatureHash dedup)', async () => {
|
||||
const port = await makePort();
|
||||
const client = await makeClient({ portId: port.id });
|
||||
|
||||
@@ -43,7 +43,7 @@ describe('interests.service — port-scope FK validation', () => {
|
||||
portA.id,
|
||||
{
|
||||
clientId: foreignClient.id,
|
||||
pipelineStage: 'open',
|
||||
pipelineStage: 'enquiry',
|
||||
tagIds: [],
|
||||
reminderEnabled: false,
|
||||
},
|
||||
@@ -64,7 +64,7 @@ describe('interests.service — port-scope FK validation', () => {
|
||||
{
|
||||
clientId: localClient.id,
|
||||
berthId: foreignBerth.id,
|
||||
pipelineStage: 'open',
|
||||
pipelineStage: 'enquiry',
|
||||
tagIds: [],
|
||||
reminderEnabled: false,
|
||||
},
|
||||
@@ -90,7 +90,7 @@ describe('interests.service — port-scope FK validation', () => {
|
||||
{
|
||||
clientId: localClient.id,
|
||||
yachtId: foreignYacht.id,
|
||||
pipelineStage: 'open',
|
||||
pipelineStage: 'enquiry',
|
||||
tagIds: [],
|
||||
reminderEnabled: false,
|
||||
},
|
||||
@@ -109,7 +109,7 @@ describe('interests.service — port-scope FK validation', () => {
|
||||
portA.id,
|
||||
{
|
||||
clientId: localClient.id,
|
||||
pipelineStage: 'open',
|
||||
pipelineStage: 'enquiry',
|
||||
tagIds: [],
|
||||
reminderEnabled: false,
|
||||
},
|
||||
@@ -136,7 +136,7 @@ describe('interests.service — port-scope FK validation', () => {
|
||||
portA.id,
|
||||
{
|
||||
clientId: localClient.id,
|
||||
pipelineStage: 'open',
|
||||
pipelineStage: 'enquiry',
|
||||
tagIds: [],
|
||||
reminderEnabled: false,
|
||||
},
|
||||
|
||||
@@ -63,7 +63,7 @@ describe('interests.service — yacht ownership validation', () => {
|
||||
{
|
||||
clientId: client.id,
|
||||
yachtId: yacht.id,
|
||||
pipelineStage: 'open',
|
||||
pipelineStage: 'enquiry',
|
||||
tagIds: [],
|
||||
reminderEnabled: false,
|
||||
},
|
||||
@@ -89,7 +89,7 @@ describe('interests.service — yacht ownership validation', () => {
|
||||
{
|
||||
clientId: clientB.id,
|
||||
yachtId: yacht.id,
|
||||
pipelineStage: 'open',
|
||||
pipelineStage: 'enquiry',
|
||||
tagIds: [],
|
||||
reminderEnabled: false,
|
||||
},
|
||||
@@ -119,7 +119,7 @@ describe('interests.service — yacht ownership validation', () => {
|
||||
{
|
||||
clientId: client.id,
|
||||
yachtId: yacht.id,
|
||||
pipelineStage: 'open',
|
||||
pipelineStage: 'enquiry',
|
||||
tagIds: [],
|
||||
reminderEnabled: false,
|
||||
},
|
||||
@@ -134,19 +134,19 @@ describe('interests.service — yacht ownership validation', () => {
|
||||
|
||||
const interest = await createInterest(
|
||||
port.id,
|
||||
{ clientId: client.id, pipelineStage: 'open', tagIds: [], reminderEnabled: false },
|
||||
{ clientId: client.id, pipelineStage: 'enquiry', tagIds: [], reminderEnabled: false },
|
||||
makeAuditMeta({ portId: port.id }),
|
||||
);
|
||||
expect(interest.yachtId).toBeNull();
|
||||
expect(interest.pipelineStage).toBe('open');
|
||||
expect(interest.pipelineStage).toBe('enquiry');
|
||||
});
|
||||
|
||||
it('changeInterestStage rejects moving out of "open" when yachtId is null', async () => {
|
||||
it('changeInterestStage rejects moving out of "enquiry" when yachtId is null', async () => {
|
||||
const port = await makePort();
|
||||
const client = await makeClient({ portId: port.id });
|
||||
const interest = await createInterest(
|
||||
port.id,
|
||||
{ clientId: client.id, pipelineStage: 'open', tagIds: [], reminderEnabled: false },
|
||||
{ clientId: client.id, pipelineStage: 'enquiry', tagIds: [], reminderEnabled: false },
|
||||
makeAuditMeta({ portId: port.id }),
|
||||
);
|
||||
|
||||
@@ -154,10 +154,10 @@ describe('interests.service — yacht ownership validation', () => {
|
||||
changeInterestStage(
|
||||
interest.id,
|
||||
port.id,
|
||||
{ pipelineStage: 'details_sent' },
|
||||
{ pipelineStage: 'qualified' },
|
||||
makeAuditMeta({ portId: port.id }),
|
||||
),
|
||||
).rejects.toThrow(/yachtId is required before leaving stage=open/);
|
||||
).rejects.toThrow(/yachtId is required before leaving stage=enquiry/);
|
||||
});
|
||||
|
||||
it('changeInterestStage succeeds when yachtId is set', async () => {
|
||||
@@ -173,7 +173,7 @@ describe('interests.service — yacht ownership validation', () => {
|
||||
{
|
||||
clientId: client.id,
|
||||
yachtId: yacht.id,
|
||||
pipelineStage: 'open',
|
||||
pipelineStage: 'enquiry',
|
||||
tagIds: [],
|
||||
reminderEnabled: false,
|
||||
},
|
||||
@@ -183,10 +183,10 @@ describe('interests.service — yacht ownership validation', () => {
|
||||
const updated = await changeInterestStage(
|
||||
interest.id,
|
||||
port.id,
|
||||
{ pipelineStage: 'details_sent' },
|
||||
{ pipelineStage: 'qualified' },
|
||||
makeAuditMeta({ portId: port.id }),
|
||||
);
|
||||
expect(updated.pipelineStage).toBe('details_sent');
|
||||
expect(updated.pipelineStage).toBe('qualified');
|
||||
});
|
||||
|
||||
it('updateInterest validates yacht ownership when changing yachtId', async () => {
|
||||
@@ -196,7 +196,7 @@ describe('interests.service — yacht ownership validation', () => {
|
||||
// Interest is owned by clientA; yacht belongs to clientB.
|
||||
const interest = await createInterest(
|
||||
port.id,
|
||||
{ clientId: clientA.id, pipelineStage: 'open', tagIds: [], reminderEnabled: false },
|
||||
{ clientId: clientA.id, pipelineStage: 'enquiry', tagIds: [], reminderEnabled: false },
|
||||
makeAuditMeta({ portId: port.id }),
|
||||
);
|
||||
const yachtOfB = await makeYacht({
|
||||
|
||||
@@ -122,13 +122,20 @@ describe('Pipeline Transitions', () => {
|
||||
await cleanupPort(portId);
|
||||
});
|
||||
|
||||
itDb('advances through all 8 pipeline stages sequentially', async () => {
|
||||
itDb('advances through all 7 pipeline stages sequentially', async () => {
|
||||
const { changeInterestStage, getInterestById } =
|
||||
await import('@/lib/services/interests.service');
|
||||
const meta = makeAuditMeta({ portId });
|
||||
|
||||
for (const stage of PIPELINE_STAGES) {
|
||||
await changeInterestStage(interestId, portId, { pipelineStage: stage }, meta);
|
||||
// Skip-ahead jumps are blocked unless override=true; the test runs
|
||||
// through each stage so we override consistently.
|
||||
await changeInterestStage(
|
||||
interestId,
|
||||
portId,
|
||||
{ pipelineStage: stage, override: true, reason: 'sequential walk for test' },
|
||||
meta,
|
||||
);
|
||||
|
||||
const updated = await getInterestById(interestId, portId);
|
||||
expect(updated.pipelineStage).toBe(stage);
|
||||
@@ -139,7 +146,7 @@ describe('Pipeline Transitions', () => {
|
||||
const { changeInterestStage } = await import('@/lib/services/interests.service');
|
||||
const meta = makeAuditMeta({ portId });
|
||||
|
||||
await changeInterestStage(interestId, portId, { pipelineStage: 'open' }, meta);
|
||||
await changeInterestStage(interestId, portId, { pipelineStage: 'enquiry' }, meta);
|
||||
|
||||
// Allow async audit log to flush
|
||||
await new Promise((r) => setTimeout(r, 100));
|
||||
@@ -150,49 +157,74 @@ describe('Pipeline Transitions', () => {
|
||||
expect(log!.entity_type).toBe('interest');
|
||||
|
||||
const newValue = log!.new_value as Record<string, unknown>;
|
||||
expect(newValue.pipelineStage).toBe('open');
|
||||
expect(newValue.pipelineStage).toBe('enquiry');
|
||||
});
|
||||
|
||||
itDb('backward transition: completed → open is permitted', async () => {
|
||||
itDb('backward transition: contract → enquiry is permitted with override', async () => {
|
||||
const { changeInterestStage, getInterestById } =
|
||||
await import('@/lib/services/interests.service');
|
||||
const meta = makeAuditMeta({ portId });
|
||||
|
||||
await changeInterestStage(interestId, portId, { pipelineStage: 'completed' }, meta);
|
||||
await changeInterestStage(interestId, portId, { pipelineStage: 'open' }, meta);
|
||||
await changeInterestStage(
|
||||
interestId,
|
||||
portId,
|
||||
{ pipelineStage: 'contract', override: true, reason: 'jump for backward test' },
|
||||
meta,
|
||||
);
|
||||
await changeInterestStage(
|
||||
interestId,
|
||||
portId,
|
||||
{ pipelineStage: 'enquiry', override: true, reason: 'backward rewind for test' },
|
||||
meta,
|
||||
);
|
||||
|
||||
const updated = await getInterestById(interestId, portId);
|
||||
expect(updated.pipelineStage).toBe('open');
|
||||
expect(updated.pipelineStage).toBe('enquiry');
|
||||
});
|
||||
|
||||
itDb('BR-133: advancing to signed_eoi_nda auto-populates dateEoiSigned', async () => {
|
||||
itDb('BR-133: advancing to eoi auto-populates dateEoiSent', async () => {
|
||||
const { changeInterestStage, getInterestById } =
|
||||
await import('@/lib/services/interests.service');
|
||||
const meta = makeAuditMeta({ portId });
|
||||
|
||||
await changeInterestStage(interestId, portId, { pipelineStage: 'eoi_signed' }, meta);
|
||||
await changeInterestStage(
|
||||
interestId,
|
||||
portId,
|
||||
{ pipelineStage: 'eoi', override: true, reason: 'milestone backfill test' },
|
||||
meta,
|
||||
);
|
||||
|
||||
const updated = await getInterestById(interestId, portId);
|
||||
expect(updated.dateEoiSigned).not.toBeNull();
|
||||
expect(updated.dateEoiSent).not.toBeNull();
|
||||
});
|
||||
|
||||
itDb('BR-133: advancing to contract auto-populates dateContractSigned', async () => {
|
||||
itDb('BR-133: advancing to contract auto-populates dateContractSent', async () => {
|
||||
const { changeInterestStage, getInterestById } =
|
||||
await import('@/lib/services/interests.service');
|
||||
const meta = makeAuditMeta({ portId });
|
||||
|
||||
await changeInterestStage(interestId, portId, { pipelineStage: 'contract_signed' }, meta);
|
||||
await changeInterestStage(
|
||||
interestId,
|
||||
portId,
|
||||
{ pipelineStage: 'contract', override: true, reason: 'milestone backfill test' },
|
||||
meta,
|
||||
);
|
||||
|
||||
const updated = await getInterestById(interestId, portId);
|
||||
expect(updated.dateContractSigned).not.toBeNull();
|
||||
expect(updated.dateContractSent).not.toBeNull();
|
||||
});
|
||||
|
||||
itDb('BR-133: advancing to deposit_10pct auto-populates dateDepositReceived', async () => {
|
||||
itDb('BR-133: advancing to deposit_paid auto-populates dateDepositReceived', async () => {
|
||||
const { changeInterestStage, getInterestById } =
|
||||
await import('@/lib/services/interests.service');
|
||||
const meta = makeAuditMeta({ portId });
|
||||
|
||||
await changeInterestStage(interestId, portId, { pipelineStage: 'deposit_10pct' }, meta);
|
||||
await changeInterestStage(
|
||||
interestId,
|
||||
portId,
|
||||
{ pipelineStage: 'deposit_paid', override: true, reason: 'milestone backfill test' },
|
||||
meta,
|
||||
);
|
||||
|
||||
const updated = await getInterestById(interestId, portId);
|
||||
expect(updated.dateDepositReceived).not.toBeNull();
|
||||
@@ -205,12 +237,12 @@ describe('Pipeline Transitions', () => {
|
||||
|
||||
vi.clearAllMocks();
|
||||
|
||||
await changeInterestStage(interestId, portId, { pipelineStage: 'details_sent' }, meta);
|
||||
await changeInterestStage(interestId, portId, { pipelineStage: 'qualified' }, meta);
|
||||
|
||||
expect(emitToRoom).toHaveBeenCalledWith(
|
||||
`port:${portId}`,
|
||||
'interest:stageChanged',
|
||||
expect.objectContaining({ interestId, newStage: 'details_sent' }),
|
||||
expect.objectContaining({ interestId, newStage: 'qualified' }),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -8,7 +8,11 @@
|
||||
*/
|
||||
import { describe, it, expect, beforeAll, afterAll } from 'vitest';
|
||||
|
||||
import { makeAuditMeta, makeCreateClientInput, makeCreateInterestInput } from '../helpers/factories';
|
||||
import {
|
||||
makeAuditMeta,
|
||||
makeCreateClientInput,
|
||||
makeCreateInterestInput,
|
||||
} from '../helpers/factories';
|
||||
|
||||
const TEST_DB_URL =
|
||||
process.env.TEST_DATABASE_URL || 'postgresql://test:test@localhost:5433/portnimara_test';
|
||||
@@ -84,7 +88,11 @@ describe('Port Scoping — Clients', () => {
|
||||
|
||||
const meta = makeAuditMeta({ portId: portA });
|
||||
|
||||
const client = await createClient(portA, makeCreateClientInput({ fullName: 'Alice Scope' }), meta);
|
||||
const client = await createClient(
|
||||
portA,
|
||||
makeCreateClientInput({ fullName: 'Alice Scope' }),
|
||||
meta,
|
||||
);
|
||||
|
||||
expect(client.portId).toBe(portA);
|
||||
|
||||
@@ -105,7 +113,11 @@ describe('Port Scoping — Clients', () => {
|
||||
const { NotFoundError } = await import('@/lib/errors');
|
||||
|
||||
const meta = makeAuditMeta({ portId: portA });
|
||||
const client = await createClient(portA, makeCreateClientInput({ fullName: 'Bob Scope' }), meta);
|
||||
const client = await createClient(
|
||||
portA,
|
||||
makeCreateClientInput({ fullName: 'Bob Scope' }),
|
||||
meta,
|
||||
);
|
||||
|
||||
await expect(getClientById(client.id, portB)).rejects.toThrow(NotFoundError);
|
||||
});
|
||||
@@ -115,11 +127,15 @@ describe('Port Scoping — Clients', () => {
|
||||
const { NotFoundError } = await import('@/lib/errors');
|
||||
|
||||
const meta = makeAuditMeta({ portId: portA });
|
||||
const client = await createClient(portA, makeCreateClientInput({ fullName: 'Carol Scope' }), meta);
|
||||
const client = await createClient(
|
||||
portA,
|
||||
makeCreateClientInput({ fullName: 'Carol Scope' }),
|
||||
meta,
|
||||
);
|
||||
|
||||
await expect(
|
||||
updateClient(client.id, portB, { fullName: 'Hacked' }, meta),
|
||||
).rejects.toThrow(NotFoundError);
|
||||
await expect(updateClient(client.id, portB, { fullName: 'Hacked' }, meta)).rejects.toThrow(
|
||||
NotFoundError,
|
||||
);
|
||||
});
|
||||
|
||||
itDb('archiveClient on wrong port throws NotFoundError', async () => {
|
||||
@@ -127,7 +143,11 @@ describe('Port Scoping — Clients', () => {
|
||||
const { NotFoundError } = await import('@/lib/errors');
|
||||
|
||||
const meta = makeAuditMeta({ portId: portA });
|
||||
const client = await createClient(portA, makeCreateClientInput({ fullName: 'Dave Scope' }), meta);
|
||||
const client = await createClient(
|
||||
portA,
|
||||
makeCreateClientInput({ fullName: 'Dave Scope' }),
|
||||
meta,
|
||||
);
|
||||
|
||||
await expect(archiveClient(client.id, portB, meta)).rejects.toThrow(NotFoundError);
|
||||
});
|
||||
@@ -144,7 +164,11 @@ describe('Port Scoping — Interests', () => {
|
||||
|
||||
const { createClient } = await import('@/lib/services/clients.service');
|
||||
const meta = makeAuditMeta({ portId: portA });
|
||||
const client = await createClient(portA, makeCreateClientInput({ fullName: 'Scope Test Client' }), meta);
|
||||
const client = await createClient(
|
||||
portA,
|
||||
makeCreateClientInput({ fullName: 'Scope Test Client' }),
|
||||
meta,
|
||||
);
|
||||
clientIdA = client.id;
|
||||
});
|
||||
|
||||
@@ -157,7 +181,11 @@ describe('Port Scoping — Interests', () => {
|
||||
const { createInterest, listInterests } = await import('@/lib/services/interests.service');
|
||||
|
||||
const meta = makeAuditMeta({ portId: portA });
|
||||
const interest = await createInterest(portA, makeCreateInterestInput({ clientId: clientIdA }), meta);
|
||||
const interest = await createInterest(
|
||||
portA,
|
||||
makeCreateInterestInput({ clientId: clientIdA }),
|
||||
meta,
|
||||
);
|
||||
|
||||
expect(interest.portId).toBe(portA);
|
||||
|
||||
@@ -178,20 +206,29 @@ describe('Port Scoping — Interests', () => {
|
||||
const { NotFoundError } = await import('@/lib/errors');
|
||||
|
||||
const meta = makeAuditMeta({ portId: portA });
|
||||
const interest = await createInterest(portA, makeCreateInterestInput({ clientId: clientIdA }), meta);
|
||||
const interest = await createInterest(
|
||||
portA,
|
||||
makeCreateInterestInput({ clientId: clientIdA }),
|
||||
meta,
|
||||
);
|
||||
|
||||
await expect(getInterestById(interest.id, portB)).rejects.toThrow(NotFoundError);
|
||||
});
|
||||
|
||||
itDb('changeInterestStage on wrong port throws NotFoundError', async () => {
|
||||
const { createInterest, changeInterestStage } = await import('@/lib/services/interests.service');
|
||||
const { createInterest, changeInterestStage } =
|
||||
await import('@/lib/services/interests.service');
|
||||
const { NotFoundError } = await import('@/lib/errors');
|
||||
|
||||
const meta = makeAuditMeta({ portId: portA });
|
||||
const interest = await createInterest(portA, makeCreateInterestInput({ clientId: clientIdA }), meta);
|
||||
const interest = await createInterest(
|
||||
portA,
|
||||
makeCreateInterestInput({ clientId: clientIdA }),
|
||||
meta,
|
||||
);
|
||||
|
||||
await expect(
|
||||
changeInterestStage(interest.id, portB, { pipelineStage: 'details_sent' }, meta),
|
||||
changeInterestStage(interest.id, portB, { pipelineStage: 'qualified' }, meta),
|
||||
).rejects.toThrow(NotFoundError);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -2,35 +2,33 @@ import { describe, it, expect } from 'vitest';
|
||||
import { PIPELINE_STAGES, BERTH_STATUSES, NOTIFICATION_TYPES } from '@/lib/constants';
|
||||
|
||||
describe('PIPELINE_STAGES', () => {
|
||||
it('has exactly 9 entries', () => {
|
||||
expect(PIPELINE_STAGES).toHaveLength(9);
|
||||
it('has exactly 7 entries', () => {
|
||||
expect(PIPELINE_STAGES).toHaveLength(7);
|
||||
});
|
||||
|
||||
it('starts with "open"', () => {
|
||||
expect(PIPELINE_STAGES[0]).toBe('open');
|
||||
it('starts with "enquiry"', () => {
|
||||
expect(PIPELINE_STAGES[0]).toBe('enquiry');
|
||||
});
|
||||
|
||||
it('ends with "completed"', () => {
|
||||
expect(PIPELINE_STAGES[PIPELINE_STAGES.length - 1]).toBe('completed');
|
||||
it('ends with "contract"', () => {
|
||||
expect(PIPELINE_STAGES[PIPELINE_STAGES.length - 1]).toBe('contract');
|
||||
});
|
||||
|
||||
it('contains all expected stages in order', () => {
|
||||
expect(PIPELINE_STAGES).toEqual([
|
||||
'open',
|
||||
'details_sent',
|
||||
'in_communication',
|
||||
'eoi_sent',
|
||||
'eoi_signed',
|
||||
'deposit_10pct',
|
||||
'contract_sent',
|
||||
'contract_signed',
|
||||
'completed',
|
||||
'enquiry',
|
||||
'qualified',
|
||||
'nurturing',
|
||||
'eoi',
|
||||
'reservation',
|
||||
'deposit_paid',
|
||||
'contract',
|
||||
]);
|
||||
});
|
||||
|
||||
it('is a readonly tuple — type-level immutability via `as const`', () => {
|
||||
const arr = PIPELINE_STAGES as unknown as string[];
|
||||
expect(arr).toHaveLength(9);
|
||||
expect(arr).toHaveLength(7);
|
||||
});
|
||||
|
||||
it('has no duplicate entries', () => {
|
||||
|
||||
170
tests/unit/deal-health.test.ts
Normal file
170
tests/unit/deal-health.test.ts
Normal file
@@ -0,0 +1,170 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { computeDealHealth } from '@/lib/services/deal-health';
|
||||
|
||||
const daysAgo = (n: number): string => new Date(Date.now() - n * 86_400_000).toISOString();
|
||||
|
||||
describe('computeDealHealth', () => {
|
||||
it('returns baseline 50 + warm pulse when no signals fire', () => {
|
||||
const r = computeDealHealth({ pipelineStage: 'enquiry' });
|
||||
expect(r.score).toBe(50);
|
||||
expect(r.pulse).toBe('warm');
|
||||
expect(r.signals).toEqual([]);
|
||||
});
|
||||
|
||||
it('returns neutral baseline when interest is closed/won', () => {
|
||||
const r = computeDealHealth({
|
||||
pipelineStage: 'contract',
|
||||
outcome: 'won',
|
||||
dateLastContact: daysAgo(2),
|
||||
});
|
||||
expect(r.score).toBe(50);
|
||||
expect(r.signals).toEqual([]);
|
||||
});
|
||||
|
||||
it('returns neutral baseline when interest is archived', () => {
|
||||
const r = computeDealHealth({
|
||||
pipelineStage: 'eoi',
|
||||
archivedAt: daysAgo(10),
|
||||
dateLastContact: daysAgo(2),
|
||||
});
|
||||
expect(r.signals).toEqual([]);
|
||||
});
|
||||
|
||||
it('+20 for contact in last 7 days', () => {
|
||||
const r = computeDealHealth({
|
||||
pipelineStage: 'enquiry',
|
||||
dateLastContact: daysAgo(3),
|
||||
});
|
||||
const sig = r.signals.find((s) => s.id === 'contact_recent');
|
||||
expect(sig?.delta).toBe(20);
|
||||
expect(r.score).toBeGreaterThanOrEqual(70);
|
||||
expect(r.pulse).toBe('hot');
|
||||
});
|
||||
|
||||
it('+10 for contact within 14 days', () => {
|
||||
const r = computeDealHealth({
|
||||
pipelineStage: 'enquiry',
|
||||
dateLastContact: daysAgo(10),
|
||||
});
|
||||
const sig = r.signals.find((s) => s.id === 'contact_warm');
|
||||
expect(sig?.delta).toBe(10);
|
||||
});
|
||||
|
||||
it('-15 when no contact in 30+ days', () => {
|
||||
const r = computeDealHealth({
|
||||
pipelineStage: 'qualified',
|
||||
dateLastContact: daysAgo(40),
|
||||
});
|
||||
const sig = r.signals.find((s) => s.id === 'contact_stale');
|
||||
expect(sig?.delta).toBe(-15);
|
||||
});
|
||||
|
||||
it('-10 when EOI sent >14d ago and still unsigned', () => {
|
||||
const r = computeDealHealth({
|
||||
pipelineStage: 'eoi',
|
||||
dateEoiSent: daysAgo(20),
|
||||
eoiDocStatus: 'sent',
|
||||
});
|
||||
const sig = r.signals.find((s) => s.id === 'eoi_awaiting');
|
||||
expect(sig?.delta).toBe(-10);
|
||||
});
|
||||
|
||||
it('does NOT penalize EOI awaiting when sub-status is signed', () => {
|
||||
const r = computeDealHealth({
|
||||
pipelineStage: 'eoi',
|
||||
dateEoiSent: daysAgo(20),
|
||||
eoiDocStatus: 'signed',
|
||||
});
|
||||
expect(r.signals.find((s) => s.id === 'eoi_awaiting')).toBeUndefined();
|
||||
});
|
||||
|
||||
it('-10 when reservation signed >21d ago but no deposit', () => {
|
||||
const r = computeDealHealth({
|
||||
pipelineStage: 'reservation',
|
||||
dateReservationSigned: daysAgo(25),
|
||||
});
|
||||
const sig = r.signals.find((s) => s.id === 'deposit_pending');
|
||||
expect(sig?.delta).toBe(-10);
|
||||
});
|
||||
|
||||
it('does NOT penalize deposit_pending when deposit already received', () => {
|
||||
const r = computeDealHealth({
|
||||
pipelineStage: 'deposit_paid',
|
||||
dateReservationSigned: daysAgo(25),
|
||||
dateDepositReceived: daysAgo(2),
|
||||
});
|
||||
expect(r.signals.find((s) => s.id === 'deposit_pending')).toBeUndefined();
|
||||
});
|
||||
|
||||
it('stage progress bonus caps at +30', () => {
|
||||
const r = computeDealHealth({
|
||||
pipelineStage: 'contract',
|
||||
contractDocStatus: 'signed',
|
||||
});
|
||||
const sig = r.signals.find((s) => s.id === 'stage_progress');
|
||||
expect(sig?.delta).toBeLessThanOrEqual(30);
|
||||
expect(sig?.delta).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
it('-10 for deals stuck pre-EOI for 30+ days', () => {
|
||||
const r = computeDealHealth({
|
||||
pipelineStage: 'enquiry',
|
||||
dateFirstContact: daysAgo(45),
|
||||
});
|
||||
const sig = r.signals.find((s) => s.id === 'stuck_top_funnel');
|
||||
expect(sig?.delta).toBe(-10);
|
||||
});
|
||||
|
||||
it('clamps score to [0, 100]', () => {
|
||||
const r = computeDealHealth({
|
||||
pipelineStage: 'contract',
|
||||
dateLastContact: daysAgo(2),
|
||||
contractDocStatus: 'signed',
|
||||
});
|
||||
expect(r.score).toBeLessThanOrEqual(100);
|
||||
expect(r.score).toBeGreaterThanOrEqual(0);
|
||||
});
|
||||
|
||||
it('rates a fresh contract-signed deal as hot', () => {
|
||||
const r = computeDealHealth({
|
||||
pipelineStage: 'contract',
|
||||
dateLastContact: daysAgo(1),
|
||||
contractDocStatus: 'signed',
|
||||
});
|
||||
expect(r.pulse).toBe('hot');
|
||||
});
|
||||
|
||||
it('rates a stalled mid-funnel deal with no recent contact as cold', () => {
|
||||
const r = computeDealHealth({
|
||||
pipelineStage: 'qualified',
|
||||
dateFirstContact: daysAgo(60),
|
||||
dateLastContact: daysAgo(45),
|
||||
});
|
||||
expect(r.pulse).toBe('cold');
|
||||
});
|
||||
|
||||
it('+5 active_engagement when recentActivityCount >= 1', () => {
|
||||
const r = computeDealHealth({
|
||||
pipelineStage: 'enquiry',
|
||||
recentActivityCount: 3,
|
||||
});
|
||||
const sig = r.signals.find((s) => s.id === 'active_engagement');
|
||||
expect(sig?.delta).toBe(5);
|
||||
});
|
||||
|
||||
it('skips active_engagement when recentActivityCount is null/undefined', () => {
|
||||
const r = computeDealHealth({
|
||||
pipelineStage: 'enquiry',
|
||||
recentActivityCount: null,
|
||||
});
|
||||
expect(r.signals.find((s) => s.id === 'active_engagement')).toBeUndefined();
|
||||
});
|
||||
|
||||
it('skips active_engagement when recentActivityCount is 0', () => {
|
||||
const r = computeDealHealth({
|
||||
pipelineStage: 'enquiry',
|
||||
recentActivityCount: 0,
|
||||
});
|
||||
expect(r.signals.find((s) => s.id === 'active_engagement')).toBeUndefined();
|
||||
});
|
||||
});
|
||||
@@ -112,15 +112,13 @@ describe('createInterestSchema', () => {
|
||||
|
||||
it('accepts all valid pipeline stages', () => {
|
||||
const stages = [
|
||||
'open',
|
||||
'details_sent',
|
||||
'in_communication',
|
||||
'eoi_sent',
|
||||
'eoi_signed',
|
||||
'deposit_10pct',
|
||||
'contract_sent',
|
||||
'contract_signed',
|
||||
'completed',
|
||||
'enquiry',
|
||||
'qualified',
|
||||
'nurturing',
|
||||
'eoi',
|
||||
'reservation',
|
||||
'deposit_paid',
|
||||
'contract',
|
||||
];
|
||||
for (const stage of stages) {
|
||||
const result = createInterestSchema.safeParse({ clientId: 'c1', pipelineStage: stage });
|
||||
@@ -144,7 +142,7 @@ describe('createInterestSchema', () => {
|
||||
|
||||
describe('changeStageSchema', () => {
|
||||
it('accepts a valid stage', () => {
|
||||
expect(changeStageSchema.safeParse({ pipelineStage: 'in_communication' }).success).toBe(true);
|
||||
expect(changeStageSchema.safeParse({ pipelineStage: 'nurturing' }).success).toBe(true);
|
||||
});
|
||||
|
||||
it('rejects invalid stage', () => {
|
||||
|
||||
Reference in New Issue
Block a user