233 lines
9.1 KiB
JavaScript
233 lines
9.1 KiB
JavaScript
import { before, after, test } from 'node:test';
|
|
import assert from 'node:assert/strict';
|
|
import { createHash } from 'node:crypto';
|
|
import { spawnSync } from 'node:child_process';
|
|
import { createDatabase } from '@merchantflow/database';
|
|
import { roles, statuses, documentCodes } from '@merchantflow/contracts';
|
|
import {
|
|
Role,
|
|
MerchantStatus,
|
|
DocumentCode,
|
|
} from '../../../packages/database/dist/generated/prisma/enums.js';
|
|
if (!process.env.DATABASE_URL?.endsWith('/merchantflow_test'))
|
|
throw new Error('Integration tests require the isolated merchantflow_test database');
|
|
const db = createDatabase(process.env.DATABASE_URL);
|
|
let app, base;
|
|
const cookies = {};
|
|
async function request(path, cookie, options = {}) {
|
|
const response = await fetch(`${base}${path}`, {
|
|
...options,
|
|
headers: {
|
|
...(cookie ? { cookie } : {}),
|
|
...(options.body ? { 'content-type': 'application/json' } : {}),
|
|
...options.headers,
|
|
},
|
|
});
|
|
return { status: response.status, body: await response.json(), response };
|
|
}
|
|
async function login(account, password = 'MerchantFlow123!') {
|
|
return request('/auth/login', null, {
|
|
method: 'POST',
|
|
body: JSON.stringify({ email: `${account}@merchantflow.test`, password }),
|
|
});
|
|
}
|
|
before(async () => {
|
|
const { createApp } = await import('../dist/app.js');
|
|
app = await createApp();
|
|
await app.listen(0, '127.0.0.1');
|
|
base = (await app.getUrl()) + '/api';
|
|
for (const account of ['head', 'compliance', 'manager1', 'manager2']) {
|
|
const r = await login(account);
|
|
assert.equal(r.status, 201);
|
|
cookies[account] = r.response.headers.get('set-cookie').split(';')[0];
|
|
}
|
|
});
|
|
after(async () => {
|
|
await app?.close();
|
|
await db.$disconnect();
|
|
});
|
|
test('Prisma and browser contracts agree on canonical codes', () => {
|
|
assert.deepEqual(Object.values(Role), [...roles]);
|
|
assert.deepEqual(Object.values(MerchantStatus), [...statuses]);
|
|
assert.deepEqual(Object.values(DocumentCode), [...documentCodes]);
|
|
});
|
|
test('health checks the database and every CRM endpoint requires a session', async () => {
|
|
assert.deepEqual((await request('/health')).body, { status: 'ok', database: 'connected' });
|
|
for (const path of [
|
|
'/auth/me',
|
|
'/dashboard',
|
|
'/merchants',
|
|
'/merchants/merchant-01',
|
|
'/pipeline',
|
|
'/tasks',
|
|
'/review-queue',
|
|
])
|
|
assert.equal((await request(path)).status, 401, path);
|
|
});
|
|
test('login validates, sets protected cookies, and rejects incorrect credentials and cross-origin writes', async () => {
|
|
assert.equal((await login('head', 'incorrect')).status, 401);
|
|
const invalid = await request('/auth/login', null, {
|
|
method: 'POST',
|
|
body: '{"email":"wrong","password":""}',
|
|
});
|
|
assert.equal(invalid.status, 400);
|
|
assert.equal(invalid.body.code, 'VALIDATION_ERROR');
|
|
const r = await login('head');
|
|
const cookie = r.response.headers.get('set-cookie');
|
|
assert.match(cookie, /HttpOnly/i);
|
|
assert.match(cookie, /SameSite=Lax/i);
|
|
assert.match(cookie, /Path=\/api/i);
|
|
assert.equal(
|
|
(
|
|
await request('/auth/logout', cookies.head, {
|
|
method: 'POST',
|
|
headers: { origin: 'https://untrusted.example' },
|
|
})
|
|
).status,
|
|
403,
|
|
);
|
|
});
|
|
for (const [account, total] of [
|
|
['head', 18],
|
|
['manager1', 9],
|
|
['manager2', 9],
|
|
['compliance', 4],
|
|
])
|
|
test(`${account}: all reads, details, history, tasks and metrics respect the scope`, async () => {
|
|
const cookie = cookies[account];
|
|
const expected = (await db.merchant.findMany()).filter((m) =>
|
|
account === 'head' || account === 'compliance'
|
|
? account === 'head' || ['KYB', 'COMPLIANCE_REVIEW'].includes(m.status)
|
|
: m.ownerId === `user-${account}`,
|
|
);
|
|
assert.equal(expected.length, total);
|
|
const ids = expected.map((m) => m.id);
|
|
const list = await request('/merchants', cookie);
|
|
assert.equal(list.status, 200);
|
|
assert.equal(list.body.total, total);
|
|
assert.ok(list.body.items.every((m) => ids.includes(m.id)));
|
|
assert.equal(list.body.items.length, Math.min(total, 8));
|
|
if (total > 8) {
|
|
const second = await request('/merchants?page=2', cookie);
|
|
assert.ok(second.body.items.length > 0);
|
|
assert.ok(
|
|
second.body.items.every((m) => !list.body.items.some((first) => first.id === m.id)),
|
|
);
|
|
}
|
|
const pipeline = (await request('/pipeline', cookie)).body;
|
|
assert.deepEqual(pipeline.map((m) => m.id).sort(), [...ids].sort());
|
|
const tasks = (await request('/tasks', cookie)).body;
|
|
assert.equal(tasks.length, total * 2);
|
|
assert.ok(tasks.every((t) => ids.includes(t.merchant.id)));
|
|
for (const m of expected) {
|
|
const detail = (await request(`/merchants/${m.id}`, cookie)).body;
|
|
assert.equal(detail.id, m.id);
|
|
assert.equal(detail.checklist.length, 4);
|
|
assert.ok(detail.events.every((e) => e.merchant.id === m.id));
|
|
assert.ok(detail.tasks.every((t) => t.merchant.id === m.id));
|
|
assert.ok(!JSON.stringify(detail).includes('passwordHash'));
|
|
}
|
|
const dashboard = (await request('/dashboard', cookie)).body;
|
|
assert.equal(dashboard.merchantCount, total);
|
|
assert.equal(
|
|
dashboard.reviewCount,
|
|
expected.filter((m) => m.status === 'COMPLIANCE_REVIEW').length,
|
|
);
|
|
assert.equal(
|
|
dashboard.overdueTasks,
|
|
await db.task.count({
|
|
where: { merchantId: { in: ids }, status: 'OPEN', dueAt: { lt: new Date() } },
|
|
}),
|
|
);
|
|
assert.equal(
|
|
dashboard.transitionsLast30Days,
|
|
await db.statusEvent.count({
|
|
where: {
|
|
merchantId: { in: ids },
|
|
fromStatus: { not: null },
|
|
occurredAt: { gte: new Date(Date.now() - 30 * 86400000) },
|
|
},
|
|
}),
|
|
);
|
|
assert.equal(
|
|
dashboard.distribution.reduce((sum, x) => sum + x.count, 0),
|
|
total,
|
|
);
|
|
assert.ok(dashboard.recentEvents.every((e) => ids.includes(e.merchant.id)));
|
|
assert.ok(dashboard.upcomingTasks.every((t) => ids.includes(t.merchant.id)));
|
|
const hidden = (await db.merchant.findMany()).find((m) => !ids.includes(m.id));
|
|
if (hidden) {
|
|
assert.equal((await request(`/merchants/${hidden.id}`, cookie)).status, 404);
|
|
assert.equal(
|
|
(await request(`/merchants?search=${encodeURIComponent(hidden.name)}`, cookie)).body.total,
|
|
0,
|
|
);
|
|
}
|
|
assert.equal(
|
|
(await request('/review-queue', cookie)).status,
|
|
account === 'compliance' ? 200 : 403,
|
|
);
|
|
});
|
|
test('filters are validated and review queue is oldest first', async () => {
|
|
const cookie = cookies.head;
|
|
for (const query of ['page=-1', 'status=Live', 'page=1.5'])
|
|
assert.equal((await request(`/merchants?${query}`, cookie)).status, 400);
|
|
assert.equal((await request('/tasks?filter=invalid', cookie)).status, 400);
|
|
const live = (await request('/merchants?status=LIVE', cookie)).body;
|
|
assert.equal(live.total, 2);
|
|
const done = (await request('/tasks?filter=DONE', cookie)).body;
|
|
assert.ok(done.every((t) => t.status === 'DONE'));
|
|
const overdue = (await request('/tasks?filter=OVERDUE', cookie)).body;
|
|
assert.ok(overdue.every((t) => t.status === 'OPEN' && new Date(t.dueAt) < new Date()));
|
|
const queue = (await request('/review-queue', cookies.compliance)).body;
|
|
assert.equal(queue.length, 2);
|
|
assert.ok(queue.every((m) => m.status === 'COMPLIANCE_REVIEW'));
|
|
assert.ok(new Date(queue[0].stageEnteredAt) <= new Date(queue[1].stageEnteredAt));
|
|
});
|
|
test('seed is repeatable without modifying records; history includes correction and terminal outcomes', async () => {
|
|
const snapshot = await db.merchant.findMany({
|
|
orderBy: { id: 'asc' },
|
|
include: { events: { orderBy: { id: 'asc' } } },
|
|
});
|
|
const result = spawnSync('pnpm', ['--filter', '@merchantflow/database', 'seed'], {
|
|
env: process.env,
|
|
encoding: 'utf8',
|
|
});
|
|
assert.equal(result.status, 0, result.stderr);
|
|
assert.equal(await db.user.count(), 4);
|
|
assert.equal(await db.merchant.count(), 18);
|
|
assert.deepEqual(
|
|
await db.merchant.findMany({
|
|
orderBy: { id: 'asc' },
|
|
include: { events: { orderBy: { id: 'asc' } } },
|
|
}),
|
|
snapshot,
|
|
);
|
|
assert.ok(
|
|
snapshot.some((m) =>
|
|
m.events.some((e) => e.fromStatus === 'COMPLIANCE_REVIEW' && e.toStatus === 'KYB'),
|
|
),
|
|
);
|
|
assert.ok(!snapshot.some((m) => m.events.some((e) => e.fromStatus === 'LIVE')));
|
|
});
|
|
test('expired, logged-out and replaced sessions cannot be reused', async () => {
|
|
const r = await login('manager1');
|
|
const cookie = r.response.headers.get('set-cookie').split(';')[0];
|
|
const token = cookie.split('=')[1];
|
|
await db.session.update({
|
|
where: { id: createHash('sha256').update(token).digest('hex') },
|
|
data: { expiresAt: new Date(0) },
|
|
});
|
|
assert.equal((await request('/auth/me', cookie)).status, 401);
|
|
const fresh = await login('manager1');
|
|
const freshCookie = fresh.response.headers.get('set-cookie').split(';')[0];
|
|
assert.equal((await request('/auth/logout', freshCookie, { method: 'POST' })).status, 201);
|
|
assert.equal((await request('/pipeline', freshCookie)).status, 401);
|
|
const replacement = await request('/auth/login', cookies.manager2, {
|
|
method: 'POST',
|
|
body: JSON.stringify({ email: '[email protected]', password: 'MerchantFlow123!' }),
|
|
});
|
|
assert.equal(replacement.status, 201);
|
|
assert.equal((await request('/auth/me', cookies.manager2)).status, 401);
|
|
});
|