Files
pn-new-crm/tests/integration/pipeline-transitions.test.ts
Matt Ciaccio 49d92234dd fix(test): align stage names with consolidated pipeline enum
Followup to 886119c (refactor(sales): consolidate pipeline stages) — the
runtime enum was renamed but a few test fixtures and PDF report templates
still referenced the legacy names, leaving them broken at the type level
(36 tsc errors before this fix).

Renames in this commit:
  visited        -> in_communication (alerts test) / removed (PDF reports)
  signed_eoi_nda -> eoi_signed
  contract       -> contract_signed (interests test) / contract_sent (factory)

Affected files: pipeline-report, revenue-report, makeCreateInterestInput
factory, alerts-engine, pipeline-transitions, interest-scoring.

Verification: tsc clean, 858/858 vitest passing.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-03 16:14:04 +02:00

217 lines
7.5 KiB
TypeScript

/**
* Pipeline transition integration tests.
*
* Verifies:
* - An interest can advance through all 8 pipeline stages
* - Each transition is logged in audit_logs with action='update'
* - Backward transitions are permitted
* - Milestone auto-population (BR-133)
* - Socket event name is 'interest:stageChanged'
*
* Skips gracefully when TEST_DATABASE_URL is not reachable.
*/
import { describe, it, expect, beforeAll, afterAll, vi } from 'vitest';
import { PIPELINE_STAGES } from '@/lib/constants';
import {
makeAuditMeta,
makeCreateClientInput,
makeCreateInterestInput,
} from '../helpers/factories';
// External side-effects mocked so the test stays self-contained.
vi.mock('@/lib/socket/server', () => ({ emitToRoom: vi.fn() }));
vi.mock('@/lib/queue', () => ({
getQueue: () => ({ add: vi.fn().mockResolvedValue(undefined) }),
}));
const TEST_DB_URL =
process.env.TEST_DATABASE_URL || 'postgresql://test:test@localhost:5433/portnimara_test';
// ─── DB Availability Check ────────────────────────────────────────────────────
let dbAvailable = false;
beforeAll(async () => {
try {
const postgres = (await import('postgres')).default;
const sql = postgres(TEST_DB_URL, { max: 1, idle_timeout: 3, connect_timeout: 3 });
await sql`SELECT 1`;
await sql.end();
dbAvailable = true;
} catch {
console.warn('[pipeline-transitions] Test database not available — skipping integration tests');
}
});
function itDb(name: string, fn: () => Promise<void>) {
it(name, async () => {
if (!dbAvailable) return;
await fn();
});
}
// ─── Helpers ─────────────────────────────────────────────────────────────────
async function seedPort(): Promise<string> {
const postgres = (await import('postgres')).default;
const sql = postgres(TEST_DB_URL, { max: 1 });
const portId = crypto.randomUUID();
await sql`
INSERT INTO ports (id, name, slug, country, currency, timezone)
VALUES (${portId}, 'Pipeline Test Port', ${'pipeline-' + portId.slice(0, 8)}, 'AU', 'AUD', 'UTC')
`;
await sql.end();
return portId;
}
async function cleanupPort(portId: string): Promise<void> {
const postgres = (await import('postgres')).default;
const sql = postgres(TEST_DB_URL, { max: 1 });
await sql`DELETE FROM ports WHERE id = ${portId}`;
await sql.end();
}
async function getLatestAuditLog(
portId: string,
entityId: string,
): Promise<Record<string, unknown> | null> {
const postgres = (await import('postgres')).default;
const sql = postgres(TEST_DB_URL, { max: 1 });
const rows = await sql<Record<string, unknown>[]>`
SELECT * FROM audit_logs
WHERE port_id = ${portId} AND entity_id = ${entityId}
ORDER BY created_at DESC
LIMIT 1
`;
await sql.end();
return rows[0] ?? null;
}
// ─── Tests ────────────────────────────────────────────────────────────────────
describe('Pipeline Transitions', () => {
let portId: string;
let interestId: string;
beforeAll(async () => {
if (!dbAvailable) return;
portId = await seedPort();
const { createClient } = await import('@/lib/services/clients.service');
const meta = makeAuditMeta({ portId });
const client = await createClient(
portId,
makeCreateClientInput({ fullName: 'Pipeline Test Client' }),
meta,
);
const { createInterest } = await import('@/lib/services/interests.service');
const interest = await createInterest(
portId,
makeCreateInterestInput({ clientId: client.id }),
meta,
);
interestId = interest.id;
});
afterAll(async () => {
if (!dbAvailable) return;
await cleanupPort(portId);
});
itDb('advances through all 8 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);
const updated = await getInterestById(interestId, portId);
expect(updated.pipelineStage).toBe(stage);
}
});
itDb('each stage transition creates an audit log entry with action=update', async () => {
const { changeInterestStage } = await import('@/lib/services/interests.service');
const meta = makeAuditMeta({ portId });
await changeInterestStage(interestId, portId, { pipelineStage: 'open' }, meta);
// Allow async audit log to flush
await new Promise((r) => setTimeout(r, 100));
const log = await getLatestAuditLog(portId, interestId);
expect(log).not.toBeNull();
expect(log!.action).toBe('update');
expect(log!.entity_type).toBe('interest');
const newValue = log!.new_value as Record<string, unknown>;
expect(newValue.pipelineStage).toBe('open');
});
itDb('backward transition: completed → open is permitted', 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);
const updated = await getInterestById(interestId, portId);
expect(updated.pipelineStage).toBe('open');
});
itDb('BR-133: advancing to signed_eoi_nda auto-populates dateEoiSigned', async () => {
const { changeInterestStage, getInterestById } =
await import('@/lib/services/interests.service');
const meta = makeAuditMeta({ portId });
await changeInterestStage(interestId, portId, { pipelineStage: 'eoi_signed' }, meta);
const updated = await getInterestById(interestId, portId);
expect(updated.dateEoiSigned).not.toBeNull();
});
itDb('BR-133: advancing to contract auto-populates dateContractSigned', async () => {
const { changeInterestStage, getInterestById } =
await import('@/lib/services/interests.service');
const meta = makeAuditMeta({ portId });
await changeInterestStage(interestId, portId, { pipelineStage: 'contract_signed' }, meta);
const updated = await getInterestById(interestId, portId);
expect(updated.dateContractSigned).not.toBeNull();
});
itDb('BR-133: advancing to deposit_10pct 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);
const updated = await getInterestById(interestId, portId);
expect(updated.dateDepositReceived).not.toBeNull();
});
itDb('stage change emits interest:stageChanged socket event', async () => {
const { emitToRoom } = await import('@/lib/socket/server');
const { changeInterestStage } = await import('@/lib/services/interests.service');
const meta = makeAuditMeta({ portId });
vi.clearAllMocks();
await changeInterestStage(interestId, portId, { pipelineStage: 'details_sent' }, meta);
expect(emitToRoom).toHaveBeenCalledWith(
`port:${portId}`,
'interest:stageChanged',
expect.objectContaining({ interestId, newStage: 'details_sent' }),
);
});
});