Files
pn-new-crm/tests/integration/pipeline-transitions.test.ts
Matt 221ae5784e chore(autonomous-session): consolidate uncommitted work from prior session
Bundles the prior autonomous-session output that was sitting unstaged:

- Em-dash sweep across src/ + tests/ (en-dash/em-dash to hyphen, ~2280 instances)
- country-flag-icons rollout (CountryFlag component, replaces emoji glyphs that
  never rendered on Windows; lazy-loads the 3x2 SVG index as a single chunk
  after the per-subpath dynamic-import approach silently failed in webpack)
- Admin IA Phase 1+2: 7-domain regroup, 41 to 38 pages, /admin/berths index,
  redirects (ocr to ai, reports to dashboard, invitations to users),
  docs/admin-ia-proposal.md
- Per-template email tester (registry + endpoint + UI on Email admin page)
- Cancel-document mode picker (delete-from-Documenso vs keep-for-audit)
- Dashboard PDF report: 25 widgets, SVG charts, date-range picker, 11 resolvers
- Customize-widgets per-region sortables at xl+ (charts/rails/feed); single
  flat sortable below xl when the layout stacks; per-viewport saved orders
- Audit doc updates capturing each shipped item
- Lint fixes: react-compiler immutability in DonutChart (reduce instead of
  let-reassign), set-state-in-effect disables in CountryFlag and
  UploadForSigning preview-bytes effect, unused 'confirm' destructures in
  interest contract + reservation tabs, unescaped apostrophe in test-template
  card copy
2026-05-23 00:52:59 +02:00

249 lines
8.1 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 7 pipeline stages sequentially', async () => {
const { changeInterestStage, getInterestById } =
await import('@/lib/services/interests.service');
const meta = makeAuditMeta({ portId });
for (const stage of PIPELINE_STAGES) {
// 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);
}
});
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: 'enquiry' }, 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('enquiry');
});
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: '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('enquiry');
});
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', override: true, reason: 'milestone backfill test' },
meta,
);
const updated = await getInterestById(interestId, portId);
expect(updated.dateEoiSent).not.toBeNull();
});
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', override: true, reason: 'milestone backfill test' },
meta,
);
const updated = await getInterestById(interestId, portId);
expect(updated.dateContractSent).not.toBeNull();
});
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_paid', override: true, reason: 'milestone backfill test' },
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: 'qualified' }, meta);
expect(emitToRoom).toHaveBeenCalledWith(
`port:${portId}`,
'interest:stageChanged',
expect.objectContaining({ interestId, newStage: 'qualified' }),
);
});
});