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:
2026-05-14 03:39:21 +02:00
parent b10bf9bf8e
commit 6b28459c45
110 changed files with 5402 additions and 796 deletions

View File

@@ -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);
});
});

View File

@@ -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 () => {

View File

@@ -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 });

View File

@@ -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,
},

View File

@@ -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({

View File

@@ -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' }),
);
});
});

View File

@@ -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);
});
});