1093 lines
36 KiB
JavaScript
1093 lines
36 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, requiredDocumentCodes } 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 } : {}),
|
|
origin: process.env.APP_ORIGIN ?? 'http://localhost:5173',
|
|
...(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', 'alex', 'sam']) {
|
|
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', 45],
|
|
['alex', 20],
|
|
['sam', 20],
|
|
['compliance', 45],
|
|
])
|
|
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'
|
|
? true
|
|
: m.ownerId === (account === 'alex' ? 'user-manager1' : 'user-manager2'),
|
|
);
|
|
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,
|
|
await db.task.count({
|
|
where: {
|
|
merchantId: { in: ids },
|
|
...(account === 'compliance'
|
|
? { kind: 'COMPLIANCE', assigneeId: 'user-compliance' }
|
|
: { kind: 'COMMERCIAL' }),
|
|
},
|
|
}),
|
|
);
|
|
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, 3);
|
|
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 },
|
|
...(account === 'compliance'
|
|
? { kind: 'COMPLIANCE', assigneeId: 'user-compliance' }
|
|
: { kind: 'COMMERCIAL' }),
|
|
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, 5);
|
|
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.items;
|
|
assert.equal(queue.length, 6);
|
|
assert.ok(queue.every((m) => m.merchant.status === 'COMPLIANCE_REVIEW'));
|
|
assert.ok(new Date(queue[0].submittedAt) <= new Date(queue[1].submittedAt));
|
|
});
|
|
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(), 45);
|
|
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('alex');
|
|
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('alex');
|
|
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.sam, {
|
|
method: 'POST',
|
|
body: JSON.stringify({ email: '[email protected]', password: 'MerchantFlow123!' }),
|
|
});
|
|
assert.equal(replacement.status, 201);
|
|
assert.equal((await request('/auth/me', cookies.sam)).status, 401);
|
|
});
|
|
|
|
async function freshCookie(account) {
|
|
const response = await login(account);
|
|
assert.equal(response.status, 201);
|
|
return response.response.headers.get('set-cookie').split(';')[0];
|
|
}
|
|
async function mutate(path, cookie, data, method = 'PATCH') {
|
|
return request(path, cookie, { method, body: JSON.stringify(data) });
|
|
}
|
|
async function fixture(id, status = 'NEW_LEAD', ownerId = 'user-manager1') {
|
|
return db.merchant.create({
|
|
data: {
|
|
id,
|
|
name: 'Workflow Test',
|
|
estimatedMonthlyVolumeUsd: '10000',
|
|
legalName: 'Workflow Test Ltd',
|
|
website: 'https://workflow.example',
|
|
industry: 'SOFTWARE',
|
|
country: 'GB',
|
|
contactName: 'Test Contact',
|
|
contactEmail: '[email protected]',
|
|
ownerId,
|
|
status,
|
|
checklist: { create: requiredDocumentCodes.map((documentCode) => ({ documentCode })) },
|
|
},
|
|
});
|
|
}
|
|
|
|
test('manager lookup and both directions of direct record/child/mutation attacks are scoped', async () => {
|
|
const head = await freshCookie('head');
|
|
const comp = await freshCookie('compliance');
|
|
const alex = await freshCookie('alex');
|
|
const sam = await freshCookie('sam');
|
|
const managers = await request('/users/assignable-managers', head);
|
|
assert.deepEqual(managers.body.map((u) => u.email).sort(), [
|
|
'[email protected]',
|
|
'[email protected]',
|
|
]);
|
|
for (const cookie of [alex, sam, comp])
|
|
assert.equal((await request('/users/assignable-managers', cookie)).status, 403);
|
|
assert.equal((await request('/users/assignable-managers')).status, 401);
|
|
for (const [cookie, hiddenId, ownId] of [
|
|
[alex, 'merchant-02', 'merchant-01'],
|
|
[sam, 'merchant-01', 'merchant-02'],
|
|
]) {
|
|
const hidden = await db.merchant.findUniqueOrThrow({
|
|
where: { id: hiddenId },
|
|
include: { tasks: true, activities: true, checklist: true },
|
|
});
|
|
const taskBody = {
|
|
version: hidden.version,
|
|
title: 'Forbidden',
|
|
dueAt: new Date().toISOString(),
|
|
remindAt: null,
|
|
status: 'OPEN',
|
|
};
|
|
for (const [suffix, body, method] of [
|
|
['', { version: hidden.version, contactName: 'Forbidden' }, 'PATCH'],
|
|
['/assignment', { version: hidden.version, ownerId: 'user-manager1' }, 'PATCH'],
|
|
['/transitions', { version: hidden.version, toStatus: 'CONTACTED' }, 'POST'],
|
|
[
|
|
`/checklist/${hidden.checklist[0].id}`,
|
|
{ version: hidden.version, state: 'RECEIVED', note: null },
|
|
'PATCH',
|
|
],
|
|
[
|
|
'/reviews/unknown/decision',
|
|
{
|
|
version: hidden.version,
|
|
decision: 'APPROVED',
|
|
riskLevel: 'LOW',
|
|
reason: 'Evidence verified',
|
|
},
|
|
'POST',
|
|
],
|
|
['/activities', { version: hidden.version, kind: 'NOTE', text: 'Forbidden' }, 'POST'],
|
|
[
|
|
`/activities/${hidden.activities[0].id}`,
|
|
{ version: hidden.version, kind: 'NOTE', text: 'Forbidden' },
|
|
'PATCH',
|
|
],
|
|
['/tasks', taskBody, 'POST'],
|
|
[`/tasks/${hidden.tasks[0].id}`, taskBody, 'PATCH'],
|
|
])
|
|
assert.equal(
|
|
(await mutate(`/merchants/${hiddenId}${suffix}`, cookie, body, method)).status,
|
|
404,
|
|
suffix,
|
|
);
|
|
const own = (await request(`/merchants/${ownId}`, cookie)).body;
|
|
assert.equal(
|
|
(
|
|
await mutate(`/merchants/${ownId}/tasks/${hidden.tasks[0].id}`, cookie, {
|
|
...taskBody,
|
|
version: own.version,
|
|
})
|
|
).status,
|
|
404,
|
|
);
|
|
assert.equal(
|
|
(
|
|
await mutate(`/merchants/${ownId}/activities/${hidden.activities[0].id}`, cookie, {
|
|
version: own.version,
|
|
kind: 'NOTE',
|
|
text: 'Forbidden',
|
|
})
|
|
).status,
|
|
404,
|
|
);
|
|
assert.equal(
|
|
(
|
|
await mutate(`/merchants/${ownId}/assignment`, cookie, {
|
|
version: own.version,
|
|
ownerId: 'user-manager2',
|
|
})
|
|
).status,
|
|
403,
|
|
);
|
|
assert.equal(
|
|
(
|
|
await mutate(`/merchants/${ownId}`, cookie, {
|
|
version: own.version,
|
|
ownerId: 'user-manager2',
|
|
})
|
|
).status,
|
|
400,
|
|
);
|
|
assert.equal((await request(`/merchants/${hiddenId}`, cookie)).status, 404);
|
|
assert.equal(
|
|
(await request(`/merchants?search=${encodeURIComponent(hidden.name)}`, cookie)).body.total,
|
|
0,
|
|
);
|
|
}
|
|
const visible = (await request('/merchants/merchant-15', comp)).body;
|
|
assert.equal(visible.status, 'LIVE');
|
|
for (const [suffix, body, method] of [
|
|
['', { version: visible.version, source: 'PARTNER' }, 'PATCH'],
|
|
['/assignment', { version: visible.version, ownerId: 'user-manager2' }, 'PATCH'],
|
|
['/transitions', { version: visible.version, toStatus: 'LIVE' }, 'POST'],
|
|
['/activities', { version: visible.version, kind: 'CALL', text: 'forbidden' }, 'POST'],
|
|
])
|
|
assert.equal(
|
|
(await mutate(`/merchants/${visible.id}${suffix}`, comp, body, method)).status,
|
|
403,
|
|
);
|
|
});
|
|
|
|
test('origin checks cover every mutation and no registration endpoint exists', async () => {
|
|
const cookie = await freshCookie('head');
|
|
const merchant = (await request('/merchants/merchant-01', cookie)).body;
|
|
for (const origin of ['', 'null', 'https://untrusted.example']) {
|
|
for (const [path, method, body] of [
|
|
['/auth/login', 'POST', { email: '[email protected]', password: 'MerchantFlow123!' }],
|
|
['/auth/logout', 'POST', undefined],
|
|
['/merchants/merchant-01', 'PATCH', { version: merchant.version, contactName: 'Bad origin' }],
|
|
['/merchants/merchant-01/tasks', 'POST', { version: merchant.version }],
|
|
])
|
|
assert.equal(
|
|
(
|
|
await request(path, cookie, {
|
|
method,
|
|
headers: { origin },
|
|
...(body ? { body: JSON.stringify(body) } : {}),
|
|
})
|
|
).status,
|
|
403,
|
|
);
|
|
}
|
|
assert.equal(
|
|
(
|
|
await request('/auth/logout', cookie, {
|
|
method: 'POST',
|
|
headers: { 'sec-fetch-site': 'cross-site' },
|
|
})
|
|
).status,
|
|
403,
|
|
);
|
|
assert.equal((await request('/auth/register', null, { method: 'POST', body: '{}' })).status, 404);
|
|
assert.equal(
|
|
(
|
|
await mutate('/merchants/merchant-01', null, {
|
|
version: merchant.version,
|
|
contactName: 'Anonymous',
|
|
})
|
|
).status,
|
|
401,
|
|
);
|
|
});
|
|
|
|
test('corrections, resubmission, approval and activation preserve one merchant and immutable evidence', async () => {
|
|
const id = 'workflow-cycle';
|
|
await fixture(id);
|
|
const sales = await freshCookie('alex');
|
|
const head = await freshCookie('head');
|
|
const comp = await freshCookie('compliance');
|
|
const detail = async () => (await request(`/merchants/${id}`, sales)).body;
|
|
const move = async (toStatus, cookie = sales) =>
|
|
mutate(
|
|
`/merchants/${id}/transitions`,
|
|
cookie,
|
|
{
|
|
version: (await detail()).version,
|
|
toStatus,
|
|
...(toStatus === 'REJECTED' ? { reason: 'Attempted terminal transition' } : {}),
|
|
},
|
|
'POST',
|
|
);
|
|
try {
|
|
assert.equal((await move('LIVE')).status, 409);
|
|
assert.equal(
|
|
(
|
|
await mutate(
|
|
`/merchants/${id}/activities`,
|
|
sales,
|
|
{
|
|
version: (await detail()).version,
|
|
kind: 'CALL',
|
|
text: 'Confirmed contact before progression',
|
|
},
|
|
'POST',
|
|
)
|
|
).status,
|
|
201,
|
|
);
|
|
for (const stage of ['CONTACTED', 'QUALIFIED', 'KYB'])
|
|
assert.equal((await move(stage)).status, 201);
|
|
assert.equal((await move('COMPLIANCE_REVIEW')).status, 409);
|
|
let m = await detail();
|
|
for (const item of m.checklist) {
|
|
assert.equal(
|
|
(
|
|
await mutate(`/merchants/${id}/checklist/${item.id}`, sales, {
|
|
version: (await detail()).version,
|
|
state: 'RECEIVED',
|
|
note: null,
|
|
})
|
|
).status,
|
|
200,
|
|
);
|
|
}
|
|
assert.equal((await move('COMPLIANCE_REVIEW')).status, 201);
|
|
m = await detail();
|
|
const first = m.reviews[0];
|
|
assert.equal(
|
|
(
|
|
await mutate(`/merchants/${id}`, head, {
|
|
version: m.version,
|
|
legalName: 'Changed during review',
|
|
})
|
|
).status,
|
|
409,
|
|
);
|
|
assert.equal(
|
|
(
|
|
await mutate(`/merchants/${id}/checklist/${m.checklist[0].id}`, sales, {
|
|
version: m.version,
|
|
state: 'MISSING',
|
|
note: null,
|
|
})
|
|
).status,
|
|
409,
|
|
);
|
|
for (const cookie of [sales, head])
|
|
assert.equal(
|
|
(
|
|
await mutate(
|
|
`/merchants/${id}/reviews/${first.id}/decision`,
|
|
cookie,
|
|
{
|
|
version: m.version,
|
|
decision: 'APPROVED',
|
|
riskLevel: 'LOW',
|
|
reason: 'Evidence verified',
|
|
},
|
|
'POST',
|
|
)
|
|
).status,
|
|
403,
|
|
);
|
|
assert.equal(
|
|
(
|
|
await mutate(
|
|
`/merchants/${id}/reviews/${first.id}/decision`,
|
|
comp,
|
|
{ version: m.version, decision: 'REJECTED', reason: ' ' },
|
|
'POST',
|
|
)
|
|
).status,
|
|
400,
|
|
);
|
|
assert.equal(
|
|
(
|
|
await mutate(
|
|
`/merchants/${id}/reviews/${first.id}/decision`,
|
|
comp,
|
|
{
|
|
version: m.version,
|
|
decision: 'CORRECTIONS',
|
|
reason: 'Updated signature required',
|
|
corrections: [{ itemId: m.checklist[0].id, note: 'Please sign the latest version' }],
|
|
},
|
|
'POST',
|
|
)
|
|
).status,
|
|
201,
|
|
);
|
|
m = await detail();
|
|
assert.equal(m.status, 'KYB');
|
|
assert.equal(m.checklist[0].state, 'NEEDS_CORRECTION');
|
|
assert.equal((await move('COMPLIANCE_REVIEW')).status, 409);
|
|
assert.equal(
|
|
(
|
|
await mutate(`/merchants/${id}/checklist/${m.checklist[0].id}`, sales, {
|
|
version: m.version,
|
|
state: 'RECEIVED',
|
|
note: 'Signed version received',
|
|
})
|
|
).status,
|
|
200,
|
|
);
|
|
assert.equal((await move('COMPLIANCE_REVIEW')).status, 201);
|
|
m = await detail();
|
|
assert.equal(m.reviews.length, 2);
|
|
assert.equal(
|
|
(
|
|
await mutate(
|
|
`/merchants/${id}/reviews/${m.reviews[0].id}/decision`,
|
|
comp,
|
|
{
|
|
version: m.version,
|
|
decision: 'APPROVED',
|
|
riskLevel: 'LOW',
|
|
reason: 'All checks passed',
|
|
},
|
|
'POST',
|
|
)
|
|
).status,
|
|
201,
|
|
);
|
|
m = await detail();
|
|
assert.equal(m.status, 'INTEGRATION');
|
|
const reviewSnapshot = await db.complianceReview.findUnique({ where: { id: m.reviews[0].id } });
|
|
assert.equal(
|
|
(
|
|
await mutate(`/merchants/${id}`, head, {
|
|
version: m.version,
|
|
website: 'https://changed.example',
|
|
})
|
|
).status,
|
|
409,
|
|
);
|
|
assert.equal(
|
|
(
|
|
await mutate(`/merchants/${id}`, sales, {
|
|
version: m.version,
|
|
contactPhone: '+44 20 7946 0000',
|
|
estimatedMonthlyVolumeUsd: '125000.25',
|
|
})
|
|
).status,
|
|
200,
|
|
);
|
|
assert.equal((await move('TESTING', comp)).status, 403);
|
|
assert.equal((await move('TESTING')).status, 409);
|
|
for (const code of ['API_CONNECTION', 'WEBHOOK_SETUP']) {
|
|
const current = await detail();
|
|
assert.equal(
|
|
(
|
|
await mutate(`/merchants/${id}/activation-checks/${code}`, sales, {
|
|
version: current.version,
|
|
reviewId: current.reviews[0].id,
|
|
state: 'COMPLETE',
|
|
note: 'Demo only',
|
|
})
|
|
).status,
|
|
200,
|
|
);
|
|
}
|
|
assert.equal((await move('TESTING')).status, 201);
|
|
assert.equal((await move('LIVE', head)).status, 409);
|
|
for (const code of ['TEST_PAYMENT', 'RECONCILIATION']) {
|
|
const current = await detail();
|
|
assert.equal(
|
|
(
|
|
await mutate(`/merchants/${id}/activation-checks/${code}`, sales, {
|
|
version: current.version,
|
|
reviewId: current.reviews[0].id,
|
|
state: 'PASSED',
|
|
note: 'Demo only',
|
|
})
|
|
).status,
|
|
200,
|
|
);
|
|
}
|
|
assert.equal((await move('LIVE', head)).status, 201);
|
|
assert.equal((await move('REJECTED')).status, 409);
|
|
m = await detail();
|
|
assert.equal(m.id, id);
|
|
assert.equal(m.status, 'LIVE');
|
|
assert.equal(m.estimatedMonthlyVolumeUsd, '125000.25');
|
|
assert.equal(
|
|
(
|
|
await mutate(
|
|
`/merchants/${id}/reviews/${first.id}/decision`,
|
|
comp,
|
|
{
|
|
version: m.version,
|
|
decision: 'APPROVED',
|
|
riskLevel: 'LOW',
|
|
reason: 'Evidence verified',
|
|
},
|
|
'POST',
|
|
)
|
|
).status,
|
|
409,
|
|
);
|
|
assert.deepEqual(
|
|
await db.complianceReview.findUnique({ where: { id: m.reviews[0].id } }),
|
|
reviewSnapshot,
|
|
);
|
|
assert.equal(m.events.length, 9);
|
|
assert.ok(m.activities.some((a) => a.kind === 'AUDIT'));
|
|
} finally {
|
|
await db.merchant.delete({ where: { id } });
|
|
}
|
|
});
|
|
|
|
test('missing approval prevents activation; rejection is terminal; concurrent decisions commit once', async () => {
|
|
const sales = await freshCookie('alex');
|
|
const comp = await freshCookie('compliance');
|
|
await fixture('workflow-evidence', 'TESTING');
|
|
await fixture('workflow-reject', 'KYB');
|
|
try {
|
|
assert.equal(
|
|
(
|
|
await mutate(
|
|
'/merchants/workflow-evidence/transitions',
|
|
sales,
|
|
{ version: 0, toStatus: 'LIVE' },
|
|
'POST',
|
|
)
|
|
).status,
|
|
409,
|
|
);
|
|
const get = async () => (await request('/merchants/workflow-reject', sales)).body;
|
|
for (const item of (await get()).checklist)
|
|
await mutate(`/merchants/workflow-reject/checklist/${item.id}`, sales, {
|
|
version: (await get()).version,
|
|
state: 'RECEIVED',
|
|
note: null,
|
|
});
|
|
await mutate(
|
|
'/merchants/workflow-reject/transitions',
|
|
sales,
|
|
{ version: (await get()).version, toStatus: 'COMPLIANCE_REVIEW' },
|
|
'POST',
|
|
);
|
|
const m = await get();
|
|
const decisions = await Promise.all(
|
|
[
|
|
'Rejected: contradictory ownership evidence',
|
|
'Rejected: incomplete business registration',
|
|
].map((reason) =>
|
|
mutate(
|
|
`/merchants/${m.id}/reviews/${m.reviews[0].id}/decision`,
|
|
comp,
|
|
{ version: m.version, decision: 'REJECTED', reason },
|
|
'POST',
|
|
),
|
|
),
|
|
);
|
|
assert.deepEqual(decisions.map((r) => r.status).sort(), [201, 409]);
|
|
assert.equal((await get()).status, 'REJECTED');
|
|
assert.equal(
|
|
await db.statusEvent.count({ where: { merchantId: m.id, toStatus: 'REJECTED' } }),
|
|
1,
|
|
);
|
|
assert.equal(
|
|
(
|
|
await mutate(
|
|
`/merchants/${m.id}/transitions`,
|
|
sales,
|
|
{ version: (await get()).version, toStatus: 'KYB' },
|
|
'POST',
|
|
)
|
|
).status,
|
|
409,
|
|
);
|
|
} finally {
|
|
await db.merchant.deleteMany({
|
|
where: { id: { in: ['workflow-evidence', 'workflow-reject'] } },
|
|
});
|
|
}
|
|
});
|
|
|
|
test('reassignment transfers open commercial tasks; concurrent writes and former-owner access fail', async () => {
|
|
const id = 'workflow-handoff';
|
|
await fixture(id);
|
|
const head = await freshCookie('head');
|
|
const alex = await freshCookie('alex');
|
|
const sam = await freshCookie('sam');
|
|
const comp = await freshCookie('compliance');
|
|
const get = async (cookie = head) => (await request(`/merchants/${id}`, cookie)).body;
|
|
const task = {
|
|
title: 'Handoff task',
|
|
dueAt: new Date(Date.now() + 86400000).toISOString(),
|
|
remindAt: null,
|
|
status: 'OPEN',
|
|
};
|
|
try {
|
|
for (const [cookie, status] of [
|
|
[alex, 'OPEN'],
|
|
[alex, 'DONE'],
|
|
[comp, 'OPEN'],
|
|
])
|
|
assert.equal(
|
|
(
|
|
await mutate(
|
|
`/merchants/${id}/tasks`,
|
|
cookie,
|
|
{ ...task, status, version: (await get()).version },
|
|
'POST',
|
|
)
|
|
).status,
|
|
201,
|
|
);
|
|
const before = await get();
|
|
assert.equal((await get(comp)).tasks.length, 1);
|
|
const personal = (await get(comp)).tasks.find((t) => t.kind === 'COMPLIANCE');
|
|
assert.equal(
|
|
(
|
|
await mutate(`/merchants/${id}/tasks/${personal.id}`, head, {
|
|
...task,
|
|
version: before.version,
|
|
})
|
|
).status,
|
|
404,
|
|
);
|
|
const commercial = before.tasks.find((t) => t.kind === 'COMMERCIAL');
|
|
assert.equal(
|
|
(
|
|
await mutate(`/merchants/${id}/tasks/${commercial.id}`, comp, {
|
|
...task,
|
|
version: before.version,
|
|
})
|
|
).status,
|
|
404,
|
|
);
|
|
const results = await Promise.all([
|
|
mutate(`/merchants/${id}/assignment`, head, {
|
|
version: before.version,
|
|
ownerId: 'user-manager2',
|
|
}),
|
|
mutate(`/merchants/${id}`, alex, {
|
|
version: before.version,
|
|
contactTitle: 'Concurrent update',
|
|
}),
|
|
]);
|
|
assert.equal(results.filter((r) => r.status === 200).length, 1);
|
|
if (results[0].status !== 200)
|
|
assert.equal(
|
|
(
|
|
await mutate(`/merchants/${id}/assignment`, head, {
|
|
version: (await get()).version,
|
|
ownerId: 'user-manager2',
|
|
})
|
|
).status,
|
|
200,
|
|
);
|
|
const after = await get(sam);
|
|
assert.equal(after.owner.id, 'user-manager2');
|
|
assert.ok(
|
|
after.tasks
|
|
.filter((t) => t.kind === 'COMMERCIAL' && t.status === 'OPEN')
|
|
.every((t) => t.assignee.id === 'user-manager2'),
|
|
);
|
|
assert.ok(
|
|
after.tasks
|
|
.filter((t) => t.status === 'DONE')
|
|
.every((t) => t.assignee.id === 'user-manager1'),
|
|
);
|
|
assert.equal(
|
|
(await get(comp)).tasks.find((t) => t.kind === 'COMPLIANCE').assignee.id,
|
|
'user-compliance',
|
|
);
|
|
assert.equal((await request(`/merchants/${id}`, alex)).status, 404);
|
|
assert.equal(
|
|
(
|
|
await mutate(`/merchants/${id}`, alex, {
|
|
version: after.version,
|
|
contactName: 'Former owner',
|
|
})
|
|
).status,
|
|
404,
|
|
);
|
|
assert.equal(
|
|
(
|
|
await mutate(`/merchants/${id}`, sam, {
|
|
version: before.version,
|
|
contactName: 'Stale update',
|
|
})
|
|
).status,
|
|
409,
|
|
);
|
|
const audit = after.activities.find((a) => a.kind === 'AUDIT');
|
|
assert.equal(
|
|
(
|
|
await mutate(`/merchants/${id}/activities/${audit.id}`, head, {
|
|
version: after.version,
|
|
kind: 'NOTE',
|
|
text: 'Rewrite history',
|
|
})
|
|
).status,
|
|
403,
|
|
);
|
|
} finally {
|
|
await db.merchant.delete({ where: { id } });
|
|
}
|
|
});
|
|
|
|
test('seed histories, ownership balance, approval evidence, tasks and edited records survive reseeding', async () => {
|
|
const { reviewSnapshot, snapshotsEqual, verifyPassword } = await import('@merchantflow/database');
|
|
const merchants = await db.merchant.findMany({
|
|
include: {
|
|
checklist: { include: { changes: { orderBy: { occurredAt: 'asc' } } } },
|
|
reviews: { orderBy: { cycle: 'desc' }, include: { reviewer: true } },
|
|
events: { orderBy: { occurredAt: 'asc' } },
|
|
},
|
|
});
|
|
assert.equal(merchants.filter((m) => !m.ownerId && m.status === 'NEW_LEAD').length, 5);
|
|
for (const ownerId of ['user-manager1', 'user-manager2'])
|
|
assert.equal(merchants.filter((m) => m.ownerId === ownerId).length, 20);
|
|
const anchor = (await db.demoSeedState.findUniqueOrThrow({ where: { id: 'merchantflow-v2' } }))
|
|
.anchorAt;
|
|
assert.ok(merchants.some((m) => anchor.getTime() - m.createdAt.getTime() >= 90 * 86400000));
|
|
for (const m of merchants) {
|
|
assert.equal(m.events.at(-1).toStatus, m.status);
|
|
assert.equal(m.events.at(-1).occurredAt.getTime(), m.stageEnteredAt.getTime());
|
|
if (['INTEGRATION', 'TESTING', 'LIVE'].includes(m.status)) {
|
|
const review = m.reviews[0];
|
|
assert.equal(review.decision, 'APPROVED');
|
|
assert.equal(review.reviewer.role, 'COMPLIANCE_OFFICER');
|
|
assert.ok(review.decidedAt >= review.submittedAt);
|
|
assert.ok(snapshotsEqual(review.snapshot, reviewSnapshot(m)));
|
|
assert.ok(
|
|
m.checklist.every(
|
|
(item) =>
|
|
item.changes.filter((change) => change.occurredAt <= review.submittedAt).at(-1)
|
|
?.toState === 'RECEIVED',
|
|
),
|
|
);
|
|
}
|
|
if (m.status === 'REJECTED') assert.ok(m.reviews[0].reason.trim());
|
|
}
|
|
for (const user of await db.user.findMany()) {
|
|
assert.notEqual(user.passwordHash, 'MerchantFlow123!');
|
|
assert.ok(verifyPassword('MerchantFlow123!', user.passwordHash));
|
|
}
|
|
const merchant = await db.merchant.findUniqueOrThrow({ where: { id: 'merchant-01' } });
|
|
const user = await db.user.findUniqueOrThrow({ where: { id: 'user-manager1' } });
|
|
const task = await db.task.findFirstOrThrow({ where: { merchantId: merchant.id } });
|
|
try {
|
|
await db.merchant.update({
|
|
where: { id: merchant.id },
|
|
data: { name: 'Keep my edited merchant', estimatedMonthlyVolumeUsd: '777.77' },
|
|
});
|
|
await db.task.update({ where: { id: task.id }, data: { title: 'Keep my edited task' } });
|
|
await db.user.update({
|
|
where: { id: user.id },
|
|
data: { passwordHash: 'intentionally-changed-by-test' },
|
|
});
|
|
const snapshot = await db.merchant.findUnique({
|
|
where: { id: merchant.id },
|
|
include: {
|
|
tasks: true,
|
|
activities: true,
|
|
checklist: { include: { changes: true } },
|
|
reviews: true,
|
|
events: true,
|
|
},
|
|
});
|
|
for (let i = 0; i < 2; i++)
|
|
assert.equal(
|
|
spawnSync('pnpm', ['--filter', '@merchantflow/database', 'seed'], {
|
|
env: process.env,
|
|
encoding: 'utf8',
|
|
}).status,
|
|
0,
|
|
);
|
|
assert.deepEqual(
|
|
await db.merchant.findUnique({
|
|
where: { id: merchant.id },
|
|
include: {
|
|
tasks: true,
|
|
activities: true,
|
|
checklist: { include: { changes: true } },
|
|
reviews: true,
|
|
events: true,
|
|
},
|
|
}),
|
|
snapshot,
|
|
);
|
|
assert.equal(
|
|
(await db.user.findUnique({ where: { id: user.id } })).passwordHash,
|
|
'intentionally-changed-by-test',
|
|
);
|
|
assert.equal(await db.merchant.count(), 45);
|
|
} finally {
|
|
await db.merchant.update({
|
|
where: { id: merchant.id },
|
|
data: {
|
|
name: merchant.name,
|
|
estimatedMonthlyVolumeUsd: merchant.estimatedMonthlyVolumeUsd,
|
|
updatedAt: merchant.updatedAt,
|
|
},
|
|
});
|
|
await db.task.update({
|
|
where: { id: task.id },
|
|
data: { title: task.title, updatedAt: task.updatedAt },
|
|
});
|
|
await db.user.update({
|
|
where: { id: user.id },
|
|
data: { passwordHash: user.passwordHash, updatedAt: user.updatedAt },
|
|
});
|
|
}
|
|
});
|
|
|
|
test('login limits are enforced with Retry-After without revealing account existence', async () => {
|
|
for (let i = 0; i < 20; i++)
|
|
assert.equal((await login('nonexistent-rate-limit', 'wrong')).status, 401);
|
|
const limited = await login('nonexistent-rate-limit', 'wrong');
|
|
assert.equal(limited.status, 429);
|
|
assert.ok(Number(limited.response.headers.get('retry-after')) > 0);
|
|
});
|
|
|
|
test('legacy upgrade preserves edits and identities, enriches matching fixtures only, and repeats safely', async () => {
|
|
// This test runs last and can only operate on the guarded disposable database.
|
|
await db.merchant.deleteMany();
|
|
await db.demoSeedState.deleteMany();
|
|
await db.user.update({
|
|
where: { id: 'user-manager1' },
|
|
data: { email: '[email protected]' },
|
|
});
|
|
await db.user.update({
|
|
where: { id: 'user-manager2' },
|
|
data: { email: '[email protected]', name: 'Maria Chen' },
|
|
});
|
|
const hashes = (await db.user.findMany({ orderBy: { id: 'asc' } })).map(
|
|
(user) => user.passwordHash,
|
|
);
|
|
const old = spawnSync('node', ['tests/fixtures/legacy-demo.mjs'], {
|
|
env: process.env,
|
|
encoding: 'utf8',
|
|
});
|
|
assert.equal(old.status, 0, old.stderr);
|
|
await db.merchant.update({
|
|
where: { id: 'merchant-02' },
|
|
data: { name: 'Edited legacy company' },
|
|
});
|
|
await db.task.update({
|
|
where: { id: 'merchant-03-task-1' },
|
|
data: { title: 'Edited legacy task' },
|
|
});
|
|
const include = {
|
|
checklist: { include: { changes: true } },
|
|
activities: true,
|
|
reviews: true,
|
|
notes: true,
|
|
tasks: true,
|
|
events: true,
|
|
};
|
|
const edited = await db.merchant.findMany({
|
|
where: { id: { in: ['merchant-02', 'merchant-03'] } },
|
|
include,
|
|
orderBy: { id: 'asc' },
|
|
});
|
|
const oldFields = {
|
|
id: true,
|
|
name: true,
|
|
website: true,
|
|
country: true,
|
|
industry: true,
|
|
contactName: true,
|
|
contactEmail: true,
|
|
ownerId: true,
|
|
status: true,
|
|
createdAt: true,
|
|
stageEnteredAt: true,
|
|
events: { orderBy: { id: 'asc' } },
|
|
notes: { orderBy: { id: 'asc' } },
|
|
};
|
|
const before = await db.merchant.findMany({ select: oldFields, orderBy: { id: 'asc' } });
|
|
const upgraded = spawnSync('pnpm', ['--filter', '@merchantflow/database', 'seed'], {
|
|
env: process.env,
|
|
encoding: 'utf8',
|
|
});
|
|
assert.equal(upgraded.status, 0, upgraded.stderr);
|
|
assert.match(upgraded.stderr, /Preserved edited.*merchant-02/);
|
|
assert.match(upgraded.stderr, /Preserved edited.*merchant-03/);
|
|
assert.deepEqual(
|
|
await db.merchant.findMany({
|
|
where: { id: { in: before.map((m) => m.id) } },
|
|
select: oldFields,
|
|
orderBy: { id: 'asc' },
|
|
}),
|
|
before,
|
|
);
|
|
assert.deepEqual(
|
|
await db.merchant.findMany({
|
|
where: { id: { in: ['merchant-02', 'merchant-03'] } },
|
|
include,
|
|
orderBy: { id: 'asc' },
|
|
}),
|
|
edited,
|
|
);
|
|
assert.equal(await db.merchant.count(), 45);
|
|
assert.equal(
|
|
(await db.user.findUnique({ where: { id: 'user-manager1' } })).email,
|
|
'[email protected]',
|
|
);
|
|
assert.equal(
|
|
(await db.user.findUnique({ where: { id: 'user-manager2' } })).email,
|
|
'[email protected]',
|
|
);
|
|
assert.deepEqual(
|
|
(await db.user.findMany({ orderBy: { id: 'asc' } })).map((user) => user.passwordHash),
|
|
hashes,
|
|
);
|
|
for (const m of await db.merchant.findMany({
|
|
where: { status: { in: ['INTEGRATION', 'TESTING', 'LIVE'] } },
|
|
include: { reviews: true },
|
|
}))
|
|
assert.ok(m.reviews.some((r) => r.decision === 'APPROVED'));
|
|
const snapshot = await db.merchant.findMany({ include, orderBy: { id: 'asc' } });
|
|
assert.equal(
|
|
spawnSync('pnpm', ['--filter', '@merchantflow/database', 'seed'], {
|
|
env: process.env,
|
|
encoding: 'utf8',
|
|
}).status,
|
|
0,
|
|
);
|
|
assert.deepEqual(await db.merchant.findMany({ include, orderBy: { id: 'asc' } }), snapshot);
|
|
});
|