|
|
|
@@ -0,0 +1,590 @@
|
|
|
|
|
import { before, after, afterEach, test } from 'node:test';
|
|
|
|
|
import assert from 'node:assert/strict';
|
|
|
|
|
import { randomUUID } from 'node:crypto';
|
|
|
|
|
import { createDatabase, reviewSnapshot } from '@merchantflow/database';
|
|
|
|
|
import {
|
|
|
|
|
merchantDetailSchema,
|
|
|
|
|
requiredDocumentCodes,
|
|
|
|
|
reviewQueueSchema,
|
|
|
|
|
} from '@merchantflow/contracts';
|
|
|
|
|
import { createApp } from '../dist/app.js';
|
|
|
|
|
|
|
|
|
|
if (!process.env.DATABASE_URL?.endsWith('/merchantflow_test'))
|
|
|
|
|
throw new Error('Only the isolated test database is allowed');
|
|
|
|
|
const db = createDatabase(process.env.DATABASE_URL);
|
|
|
|
|
const created = new Set();
|
|
|
|
|
const cookies = {};
|
|
|
|
|
let app, base;
|
|
|
|
|
async function request(
|
|
|
|
|
path,
|
|
|
|
|
actor = 'head',
|
|
|
|
|
body,
|
|
|
|
|
method = body === undefined ? 'GET' : 'POST',
|
|
|
|
|
headers = {},
|
|
|
|
|
) {
|
|
|
|
|
const response = await fetch(`${base}${path}`, {
|
|
|
|
|
method,
|
|
|
|
|
headers: {
|
|
|
|
|
origin: process.env.APP_ORIGIN,
|
|
|
|
|
...(cookies[actor] ? { cookie: cookies[actor] } : {}),
|
|
|
|
|
...(body === undefined ? {} : { 'content-type': 'application/json' }),
|
|
|
|
|
...headers,
|
|
|
|
|
},
|
|
|
|
|
...(body === undefined ? {} : { body: JSON.stringify(body) }),
|
|
|
|
|
});
|
|
|
|
|
return { status: response.status, body: await response.json(), headers: response.headers };
|
|
|
|
|
}
|
|
|
|
|
before(async () => {
|
|
|
|
|
app = await createApp();
|
|
|
|
|
await app.listen(0, '127.0.0.1');
|
|
|
|
|
base = `${await app.getUrl()}/api`;
|
|
|
|
|
for (const account of ['head', 'alex', 'sam', 'compliance']) {
|
|
|
|
|
const result = await request('/auth/login', null, {
|
|
|
|
|
email: `${account}@merchantflow.test`,
|
|
|
|
|
password: 'MerchantFlow123!',
|
|
|
|
|
});
|
|
|
|
|
assert.equal(result.status, 201);
|
|
|
|
|
cookies[account] = result.headers.get('set-cookie').split(';')[0];
|
|
|
|
|
}
|
|
|
|
|
});
|
|
|
|
|
afterEach(async () => {
|
|
|
|
|
await db.merchant.deleteMany({ where: { id: { in: [...created] } } });
|
|
|
|
|
created.clear();
|
|
|
|
|
});
|
|
|
|
|
after(async () => {
|
|
|
|
|
await app?.close();
|
|
|
|
|
await db.$disconnect();
|
|
|
|
|
});
|
|
|
|
|
const input = (extra = {}) => ({
|
|
|
|
|
name: `Sales ${randomUUID()}`,
|
|
|
|
|
contactName: 'Unique Contact',
|
|
|
|
|
contactEmail: '[email protected]',
|
|
|
|
|
...extra,
|
|
|
|
|
});
|
|
|
|
|
async function create(actor = 'head', extra = {}) {
|
|
|
|
|
const result = await request('/merchants', actor, input(extra));
|
|
|
|
|
assert.equal(result.status, 201, JSON.stringify(result.body));
|
|
|
|
|
created.add(result.body.id);
|
|
|
|
|
return result.body.id;
|
|
|
|
|
}
|
|
|
|
|
async function detail(id, actor = 'head') {
|
|
|
|
|
const result = await request(`/merchants/${id}`, actor);
|
|
|
|
|
assert.equal(result.status, 200);
|
|
|
|
|
return merchantDetailSchema.parse(result.body);
|
|
|
|
|
}
|
|
|
|
|
async function change(id, path, body, actor = 'head', method = 'PATCH') {
|
|
|
|
|
const m = await detail(id);
|
|
|
|
|
return request(`/merchants/${id}${path}`, actor, { version: m.version, ...body }, method);
|
|
|
|
|
}
|
|
|
|
|
const move = (id, toStatus, actor = 'head', reason) =>
|
|
|
|
|
change(
|
|
|
|
|
id,
|
|
|
|
|
'/transitions',
|
|
|
|
|
{ toStatus, ...(reason === undefined ? {} : { reason }) },
|
|
|
|
|
actor,
|
|
|
|
|
'POST',
|
|
|
|
|
);
|
|
|
|
|
const log = (id, kind = 'CALL', text = 'Contacted the primary contact') =>
|
|
|
|
|
change(id, '/activities', { kind, text }, 'head', 'POST');
|
|
|
|
|
|
|
|
|
|
const approvedDecision = {
|
|
|
|
|
decision: 'APPROVED',
|
|
|
|
|
riskLevel: 'MEDIUM',
|
|
|
|
|
reason: 'Ownership and representative authority verified.',
|
|
|
|
|
};
|
|
|
|
|
async function ready() {
|
|
|
|
|
const id = await create('alex', {
|
|
|
|
|
website: 'gates.test',
|
|
|
|
|
country: 'GB',
|
|
|
|
|
industry: 'SOFTWARE',
|
|
|
|
|
estimatedMonthlyVolumeUsd: '0',
|
|
|
|
|
});
|
|
|
|
|
await log(id);
|
|
|
|
|
for (const stage of ['CONTACTED', 'QUALIFIED', 'KYB'])
|
|
|
|
|
assert.equal((await move(id, stage, 'alex')).status, 201);
|
|
|
|
|
for (const item of (await detail(id)).checklist)
|
|
|
|
|
assert.equal(
|
|
|
|
|
(
|
|
|
|
|
await change(
|
|
|
|
|
id,
|
|
|
|
|
`/checklist/${item.id}`,
|
|
|
|
|
{ state: 'RECEIVED', note: `Collected ${item.documentCode}` },
|
|
|
|
|
'alex',
|
|
|
|
|
)
|
|
|
|
|
).status,
|
|
|
|
|
200,
|
|
|
|
|
);
|
|
|
|
|
return id;
|
|
|
|
|
}
|
|
|
|
|
async function submitted() {
|
|
|
|
|
const id = await ready();
|
|
|
|
|
assert.equal((await move(id, 'COMPLIANCE_REVIEW', 'alex')).status, 201);
|
|
|
|
|
return id;
|
|
|
|
|
}
|
|
|
|
|
async function decide(id, body = approvedDecision, actor = 'compliance', reviewId) {
|
|
|
|
|
return change(
|
|
|
|
|
id,
|
|
|
|
|
`/reviews/${reviewId ?? (await detail(id)).reviews[0].id}/decision`,
|
|
|
|
|
body,
|
|
|
|
|
actor,
|
|
|
|
|
'POST',
|
|
|
|
|
);
|
|
|
|
|
}
|
|
|
|
|
async function approved() {
|
|
|
|
|
const id = await submitted();
|
|
|
|
|
assert.equal((await decide(id)).status, 201);
|
|
|
|
|
return id;
|
|
|
|
|
}
|
|
|
|
|
async function check(id, code, state, actor = 'alex', overrides = {}) {
|
|
|
|
|
return change(
|
|
|
|
|
id,
|
|
|
|
|
`/activation-checks/${code}`,
|
|
|
|
|
{ reviewId: (await detail(id)).reviews[0].id, state, note: 'Recorded demo only', ...overrides },
|
|
|
|
|
actor,
|
|
|
|
|
);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
test('new checklist, review snapshots, correction notes and approval validation remain distinct and immutable', async () => {
|
|
|
|
|
const id = await ready();
|
|
|
|
|
let m = await detail(id);
|
|
|
|
|
assert.deepEqual(
|
|
|
|
|
m.checklist.map((item) => item.documentCode).sort(),
|
|
|
|
|
[...requiredDocumentCodes].sort(),
|
|
|
|
|
);
|
|
|
|
|
const item = m.checklist[0];
|
|
|
|
|
await change(id, `/checklist/${item.id}`, {
|
|
|
|
|
state: 'MISSING',
|
|
|
|
|
note: 'Waiting for signed original',
|
|
|
|
|
});
|
|
|
|
|
assert.equal((await move(id, 'COMPLIANCE_REVIEW')).status, 409);
|
|
|
|
|
await change(id, `/checklist/${item.id}`, {
|
|
|
|
|
state: 'RECEIVED',
|
|
|
|
|
note: 'Received signed original',
|
|
|
|
|
});
|
|
|
|
|
await move(id, 'COMPLIANCE_REVIEW');
|
|
|
|
|
m = await detail(id);
|
|
|
|
|
const original = m.reviews[0];
|
|
|
|
|
for (const body of [
|
|
|
|
|
{ decision: 'APPROVED', reason: 'Verified' },
|
|
|
|
|
{ decision: 'APPROVED', riskLevel: 'LOW', reason: ' ' },
|
|
|
|
|
{ decision: 'APPROVED', riskLevel: 'INVALID', reason: 'Verified' },
|
|
|
|
|
{ decision: 'CORRECTIONS', reason: 'Update' },
|
|
|
|
|
{ decision: 'REJECTED', reason: ' ' },
|
|
|
|
|
])
|
|
|
|
|
assert.equal((await decide(id, body)).status, 400);
|
|
|
|
|
assert.equal(
|
|
|
|
|
(await change(id, `/checklist/${item.id}`, { state: 'MISSING', note: 'Overwrite' })).status,
|
|
|
|
|
409,
|
|
|
|
|
);
|
|
|
|
|
assert.equal(
|
|
|
|
|
(
|
|
|
|
|
await decide(id, {
|
|
|
|
|
decision: 'CORRECTIONS',
|
|
|
|
|
reason: 'Use the current form',
|
|
|
|
|
corrections: [{ itemId: item.id, note: 'Add the current date and signature' }],
|
|
|
|
|
})
|
|
|
|
|
).status,
|
|
|
|
|
201,
|
|
|
|
|
);
|
|
|
|
|
m = await detail(id);
|
|
|
|
|
assert.equal(m.status, 'KYB');
|
|
|
|
|
assert.equal(m.checklist.find((row) => row.id === item.id).note, 'Received signed original');
|
|
|
|
|
assert.equal(m.checklist.find((row) => row.id === item.id).state, 'NEEDS_CORRECTION');
|
|
|
|
|
assert.equal(m.reviews[0].corrections[0].note, 'Add the current date and signature');
|
|
|
|
|
assert.deepEqual(m.reviews[0].snapshot, original.snapshot);
|
|
|
|
|
const corrected = m.reviews[0];
|
|
|
|
|
await change(id, `/checklist/${item.id}`, { state: 'RECEIVED', note: 'Current form received' });
|
|
|
|
|
await move(id, 'COMPLIANCE_REVIEW');
|
|
|
|
|
assert.equal((await decide(id, approvedDecision, 'compliance', original.id)).status, 409);
|
|
|
|
|
assert.equal((await detail(id)).reviews[0].decision, 'PENDING');
|
|
|
|
|
assert.equal((await decide(id)).status, 201);
|
|
|
|
|
m = await detail(id);
|
|
|
|
|
assert.deepEqual(m.reviews[1], corrected);
|
|
|
|
|
assert.equal(m.reviews[0].riskLevel, 'MEDIUM');
|
|
|
|
|
assert.equal(m.reviews[0].policyVersion, 2);
|
|
|
|
|
assert.equal(m.reviews[0].cycle, 2);
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
test('stage-specific activation checks gate every transition, preserve history and reject role/field/cycle bypasses', async () => {
|
|
|
|
|
const id = await approved();
|
|
|
|
|
const before = await detail(id);
|
|
|
|
|
for (const actor of ['head', 'alex']) {
|
|
|
|
|
assert.equal((await decide(id, approvedDecision, actor)).status, 403);
|
|
|
|
|
assert.equal((await move(id, 'LIVE', actor)).status, 409);
|
|
|
|
|
assert.equal((await change(id, '', { riskLevel: 'LOW', status: 'LIVE' }, actor)).status, 400);
|
|
|
|
|
}
|
|
|
|
|
assert.equal((await check(id, 'API_CONNECTION', 'COMPLETE', 'compliance')).status, 403);
|
|
|
|
|
assert.equal((await check(id, 'API_CONNECTION', 'COMPLETE', 'sam')).status, 404);
|
|
|
|
|
assert.equal((await check(id, 'API_CONNECTION', 'PASSED')).status, 400);
|
|
|
|
|
assert.equal((await check(id, 'TEST_PAYMENT', 'PASSED')).status, 409);
|
|
|
|
|
assert.equal(
|
|
|
|
|
(await check(id, 'API_CONNECTION', 'COMPLETE', 'alex', { reviewId: 'other-cycle' })).status,
|
|
|
|
|
409,
|
|
|
|
|
);
|
|
|
|
|
assert.equal((await move(id, 'TESTING')).status, 409);
|
|
|
|
|
assert.equal((await check(id, 'API_CONNECTION', 'COMPLETE')).status, 200);
|
|
|
|
|
assert.equal((await move(id, 'TESTING')).status, 409);
|
|
|
|
|
assert.equal((await check(id, 'WEBHOOK_SETUP', 'COMPLETE', 'head')).status, 200);
|
|
|
|
|
assert.equal((await move(id, 'TESTING')).status, 201);
|
|
|
|
|
assert.equal((await check(id, 'API_CONNECTION', 'INCOMPLETE')).status, 409);
|
|
|
|
|
assert.equal((await move(id, 'LIVE')).status, 409);
|
|
|
|
|
assert.equal((await check(id, 'TEST_PAYMENT', 'FAILED')).status, 200);
|
|
|
|
|
assert.equal((await check(id, 'RECONCILIATION', 'PASSED')).status, 200);
|
|
|
|
|
assert.equal((await move(id, 'LIVE')).status, 409);
|
|
|
|
|
assert.equal((await check(id, 'TEST_PAYMENT', 'PASSED')).status, 200);
|
|
|
|
|
assert.equal((await move(id, 'LIVE')).status, 201);
|
|
|
|
|
assert.equal((await check(id, 'RECONCILIATION', 'FAILED')).status, 409);
|
|
|
|
|
const live = await detail(id);
|
|
|
|
|
assert.equal(live.status, 'LIVE');
|
|
|
|
|
assert.deepEqual(live.reviews, before.reviews);
|
|
|
|
|
assert.equal(live.activationChecks.find((row) => row.code === 'TEST_PAYMENT').changes.length, 2);
|
|
|
|
|
assert.ok(live.activationChecks.every((row) => row.changes.length && row.changes[0].actor.name));
|
|
|
|
|
assert.equal(live.capabilities.handoff.owner, 'NONE');
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
test('older approval and old check evidence cannot authorize a newer pending review or a mismatched snapshot', async () => {
|
|
|
|
|
const id = await approved();
|
|
|
|
|
await check(id, 'API_CONNECTION', 'COMPLETE');
|
|
|
|
|
await check(id, 'WEBHOOK_SETUP', 'COMPLETE');
|
|
|
|
|
const old = (await detail(id)).reviews[0];
|
|
|
|
|
const next = await db.complianceReview.create({
|
|
|
|
|
data: { merchantId: id, cycle: 2, submittedById: 'user-head', snapshot: old.snapshot },
|
|
|
|
|
});
|
|
|
|
|
assert.equal((await move(id, 'TESTING')).status, 409);
|
|
|
|
|
assert.deepEqual((await detail(id)).capabilities.activationCodes, []);
|
|
|
|
|
await db.merchant.update({ where: { id }, data: { status: 'COMPLIANCE_REVIEW' } });
|
|
|
|
|
assert.equal((await decide(id, approvedDecision, 'compliance', old.id)).status, 409);
|
|
|
|
|
assert.equal((await decide(id)).status, 201);
|
|
|
|
|
assert.equal((await move(id, 'TESTING')).status, 409);
|
|
|
|
|
assert.equal(
|
|
|
|
|
(await check(id, 'API_CONNECTION', 'COMPLETE', 'head', { reviewId: old.id })).status,
|
|
|
|
|
409,
|
|
|
|
|
);
|
|
|
|
|
const m = await detail(id);
|
|
|
|
|
assert.ok(
|
|
|
|
|
m.activationChecks
|
|
|
|
|
.filter((row) => row.reviewId === next.id)
|
|
|
|
|
.every((row) => !row.changes.length),
|
|
|
|
|
);
|
|
|
|
|
await db.merchant.update({ where: { id }, data: { legalName: 'Changed after approval' } });
|
|
|
|
|
assert.equal((await check(id, 'API_CONNECTION', 'COMPLETE')).status, 409);
|
|
|
|
|
assert.equal((await move(id, 'TESTING')).status, 409);
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
test('concurrent submissions, decisions and check writes claim the version once', async () => {
|
|
|
|
|
const id = await ready();
|
|
|
|
|
let m = await detail(id);
|
|
|
|
|
const submissions = await Promise.all(
|
|
|
|
|
[1, 2].map(() =>
|
|
|
|
|
request(`/merchants/${id}/transitions`, 'alex', {
|
|
|
|
|
version: m.version,
|
|
|
|
|
toStatus: 'COMPLIANCE_REVIEW',
|
|
|
|
|
}),
|
|
|
|
|
),
|
|
|
|
|
);
|
|
|
|
|
assert.deepEqual(submissions.map((result) => result.status).sort(), [201, 409]);
|
|
|
|
|
m = await detail(id);
|
|
|
|
|
const decisions = await Promise.all(
|
|
|
|
|
[1, 2].map(() =>
|
|
|
|
|
request(`/merchants/${id}/reviews/${m.reviews[0].id}/decision`, 'compliance', {
|
|
|
|
|
version: m.version,
|
|
|
|
|
...approvedDecision,
|
|
|
|
|
}),
|
|
|
|
|
),
|
|
|
|
|
);
|
|
|
|
|
assert.deepEqual(decisions.map((result) => result.status).sort(), [201, 409]);
|
|
|
|
|
m = await detail(id);
|
|
|
|
|
const writes = await Promise.all(
|
|
|
|
|
['COMPLETE', 'INCOMPLETE'].map((state) =>
|
|
|
|
|
request(
|
|
|
|
|
`/merchants/${id}/activation-checks/API_CONNECTION`,
|
|
|
|
|
'alex',
|
|
|
|
|
{ version: m.version, reviewId: m.reviews[0].id, state, note: state },
|
|
|
|
|
'PATCH',
|
|
|
|
|
),
|
|
|
|
|
),
|
|
|
|
|
);
|
|
|
|
|
assert.deepEqual(writes.map((result) => result.status).sort(), [200, 409]);
|
|
|
|
|
assert.equal(
|
|
|
|
|
(await detail(id)).activationChecks.find((row) => row.code === 'API_CONNECTION').changes.length,
|
|
|
|
|
1,
|
|
|
|
|
);
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
async function legacy(status) {
|
|
|
|
|
const id = await create('alex');
|
|
|
|
|
await db.kybChecklistItem.deleteMany({ where: { merchantId: id } });
|
|
|
|
|
await db.kybChecklistItem.createMany({
|
|
|
|
|
data: ['INCORPORATION', 'OWNERSHIP', 'UBO_IDENTIFICATION', 'BUSINESS_ACTIVITY'].map(
|
|
|
|
|
(documentCode) => ({
|
|
|
|
|
merchantId: id,
|
|
|
|
|
documentCode,
|
|
|
|
|
state: 'RECEIVED',
|
|
|
|
|
note: 'Preserve legacy note',
|
|
|
|
|
}),
|
|
|
|
|
),
|
|
|
|
|
});
|
|
|
|
|
const at = new Date(Date.now() - 3600000);
|
|
|
|
|
let m = await db.merchant.update({
|
|
|
|
|
where: { id },
|
|
|
|
|
data: { status },
|
|
|
|
|
include: { checklist: true },
|
|
|
|
|
});
|
|
|
|
|
for (const item of m.checklist)
|
|
|
|
|
await db.checklistChange.create({
|
|
|
|
|
data: {
|
|
|
|
|
itemId: item.id,
|
|
|
|
|
actorId: 'user-manager1',
|
|
|
|
|
toState: 'RECEIVED',
|
|
|
|
|
occurredAt: new Date(at.getTime() - 1000),
|
|
|
|
|
},
|
|
|
|
|
});
|
|
|
|
|
const review = await db.complianceReview.create({
|
|
|
|
|
data: {
|
|
|
|
|
merchantId: id,
|
|
|
|
|
cycle: 1,
|
|
|
|
|
policyVersion: 1,
|
|
|
|
|
decision: status === 'COMPLIANCE_REVIEW' ? 'PENDING' : 'APPROVED',
|
|
|
|
|
submittedById: 'user-manager1',
|
|
|
|
|
submittedAt: at,
|
|
|
|
|
snapshot: reviewSnapshot(m, 1),
|
|
|
|
|
...(status === 'COMPLIANCE_REVIEW' ? {} : { reviewerId: 'user-compliance', decidedAt: at }),
|
|
|
|
|
},
|
|
|
|
|
});
|
|
|
|
|
// The additive migration creates a missing record, without changing old evidence.
|
|
|
|
|
await db.kybChecklistItem.create({
|
|
|
|
|
data: { merchantId: id, documentCode: 'AUTHORIZED_REPRESENTATIVE' },
|
|
|
|
|
});
|
|
|
|
|
return { id, review };
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
test('legacy approval returns to KYB without rewriting decisions and requires fresh evidence', async () => {
|
|
|
|
|
for (const stage of ['INTEGRATION', 'TESTING']) {
|
|
|
|
|
const { id, review } = await legacy(stage);
|
|
|
|
|
assert.equal((await move(id, stage === 'INTEGRATION' ? 'TESTING' : 'LIVE')).status, 409);
|
|
|
|
|
assert.equal((await change(id, '/reopen-kyb', {}, 'compliance', 'POST')).status, 403);
|
|
|
|
|
assert.equal((await change(id, '/reopen-kyb', {}, 'sam', 'POST')).status, 404);
|
|
|
|
|
assert.equal((await change(id, '/reopen-kyb', {}, 'alex', 'POST')).status, 201);
|
|
|
|
|
let m = await detail(id);
|
|
|
|
|
assert.equal(m.capabilities.collectChecklist, true);
|
|
|
|
|
assert.equal(m.capabilities.editIdentity, true);
|
|
|
|
|
assert.equal((await move(id, 'COMPLIANCE_REVIEW')).status, 409);
|
|
|
|
|
const archived = m.checklist.find((row) => row.documentCode === 'UBO_IDENTIFICATION');
|
|
|
|
|
assert.equal(
|
|
|
|
|
(await change(id, `/checklist/${archived.id}`, { state: 'RECEIVED', note: 'reinterpret' }))
|
|
|
|
|
.status,
|
|
|
|
|
409,
|
|
|
|
|
);
|
|
|
|
|
const representative = m.checklist.find(
|
|
|
|
|
(row) => row.documentCode === 'AUTHORIZED_REPRESENTATIVE',
|
|
|
|
|
);
|
|
|
|
|
await change(id, `/checklist/${representative.id}`, {
|
|
|
|
|
state: 'RECEIVED',
|
|
|
|
|
note: 'Authority verified',
|
|
|
|
|
});
|
|
|
|
|
assert.equal((await move(id, 'COMPLIANCE_REVIEW')).status, 201);
|
|
|
|
|
assert.equal((await decide(id)).status, 201);
|
|
|
|
|
m = await detail(id);
|
|
|
|
|
assert.equal(m.reviews[0].snapshot.checklist.length, 3);
|
|
|
|
|
assert.deepEqual(await db.complianceReview.findUnique({ where: { id: review.id } }), review);
|
|
|
|
|
assert.equal(m.checklist.find((row) => row.id === archived.id).note, 'Preserve legacy note');
|
|
|
|
|
}
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
test('legacy pending review accepts corrections or rejection, never an approval under obsolete requirements', async () => {
|
|
|
|
|
const { id, review } = await legacy('COMPLIANCE_REVIEW');
|
|
|
|
|
assert.equal((await decide(id)).status, 409);
|
|
|
|
|
const item = (await detail(id)).checklist.find(
|
|
|
|
|
(row) => row.documentCode === 'AUTHORIZED_REPRESENTATIVE',
|
|
|
|
|
);
|
|
|
|
|
assert.equal(
|
|
|
|
|
(
|
|
|
|
|
await decide(id, {
|
|
|
|
|
decision: 'CORRECTIONS',
|
|
|
|
|
reason: 'Apply current KYB requirements',
|
|
|
|
|
corrections: [
|
|
|
|
|
{ itemId: item.id, note: 'Collect authorized-representative identification' },
|
|
|
|
|
],
|
|
|
|
|
})
|
|
|
|
|
).status,
|
|
|
|
|
201,
|
|
|
|
|
);
|
|
|
|
|
assert.deepEqual((await detail(id)).reviews[0].snapshot, review.snapshot);
|
|
|
|
|
await change(id, `/checklist/${item.id}`, { state: 'RECEIVED', note: null });
|
|
|
|
|
await move(id, 'COMPLIANCE_REVIEW');
|
|
|
|
|
assert.equal((await decide(id)).status, 201);
|
|
|
|
|
const second = await legacy('COMPLIANCE_REVIEW');
|
|
|
|
|
assert.equal(
|
|
|
|
|
(await decide(second.id, { decision: 'REJECTED', reason: 'Authority cannot be established' }))
|
|
|
|
|
.status,
|
|
|
|
|
201,
|
|
|
|
|
);
|
|
|
|
|
assert.equal((await detail(second.id)).status, 'REJECTED');
|
|
|
|
|
assert.equal((await move(second.id, 'KYB')).status, 409);
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
test('queue counts pending cycles, combines filters, and exposes review IDs and submission times', async () => {
|
|
|
|
|
const first = await submitted();
|
|
|
|
|
const second = await submitted();
|
|
|
|
|
const old = new Date(Date.now() - 73 * 3600000);
|
|
|
|
|
await db.complianceReview.update({
|
|
|
|
|
where: { id: (await detail(first)).reviews[0].id },
|
|
|
|
|
data: { submittedAt: old },
|
|
|
|
|
});
|
|
|
|
|
await db.merchant.update({
|
|
|
|
|
where: { id: first },
|
|
|
|
|
data: { name: 'Queue Specific Old', ownerId: 'user-manager2' },
|
|
|
|
|
});
|
|
|
|
|
for (const actor of ['head', 'alex', 'sam'])
|
|
|
|
|
assert.equal((await request('/review-queue', actor)).status, 403);
|
|
|
|
|
assert.equal((await request('/review-queue?waiting=invalid', 'compliance')).status, 400);
|
|
|
|
|
const all = reviewQueueSchema.parse((await request('/review-queue', 'compliance')).body);
|
|
|
|
|
const filtered = reviewQueueSchema.parse(
|
|
|
|
|
(
|
|
|
|
|
await request(
|
|
|
|
|
'/review-queue?search=Queue%20Specific&ownerId=user-manager2&waiting=72',
|
|
|
|
|
'compliance',
|
|
|
|
|
)
|
|
|
|
|
).body,
|
|
|
|
|
);
|
|
|
|
|
assert.equal(filtered.pendingCount, all.pendingCount);
|
|
|
|
|
assert.equal(filtered.filteredCount, 1);
|
|
|
|
|
assert.equal(filtered.items[0].merchant.id, first);
|
|
|
|
|
assert.equal(filtered.items[0].submittedAt, old.toISOString());
|
|
|
|
|
assert.ok(filtered.items[0].id && filtered.items[0].cycle === 1);
|
|
|
|
|
assert.equal(
|
|
|
|
|
(await request('/review-queue?search=Queue%20Specific&ownerId=user-manager1', 'compliance'))
|
|
|
|
|
.body.filteredCount,
|
|
|
|
|
0,
|
|
|
|
|
);
|
|
|
|
|
await decide(second);
|
|
|
|
|
assert.equal(
|
|
|
|
|
(await request('/review-queue', 'compliance')).body.pendingCount,
|
|
|
|
|
all.pendingCount - 1,
|
|
|
|
|
);
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
test('invalid correction children and injected activation failure roll back the complete mutation', async () => {
|
|
|
|
|
const id = await submitted();
|
|
|
|
|
let m = await detail(id);
|
|
|
|
|
const before = m;
|
|
|
|
|
assert.equal(
|
|
|
|
|
(
|
|
|
|
|
await decide(id, {
|
|
|
|
|
decision: 'CORRECTIONS',
|
|
|
|
|
reason: 'Fix records',
|
|
|
|
|
corrections: [
|
|
|
|
|
{ itemId: m.checklist[0].id, note: 'First valid correction' },
|
|
|
|
|
{ itemId: 'foreign-item', note: 'Wrong merchant' },
|
|
|
|
|
],
|
|
|
|
|
})
|
|
|
|
|
).status,
|
|
|
|
|
404,
|
|
|
|
|
);
|
|
|
|
|
assert.deepEqual(await detail(id), before);
|
|
|
|
|
await decide(id);
|
|
|
|
|
m = await detail(id);
|
|
|
|
|
// Inject failure with a transaction-local PostgreSQL trigger, scoped to this fixture.
|
|
|
|
|
await db.$executeRawUnsafe(
|
|
|
|
|
`CREATE FUNCTION reject_demo_change() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN IF NEW."note" = 'trigger rollback' THEN RAISE EXCEPTION 'test rollback'; END IF; RETURN NEW; END $$`,
|
|
|
|
|
);
|
|
|
|
|
await db.$executeRawUnsafe(
|
|
|
|
|
`CREATE TRIGGER reject_demo_change BEFORE INSERT ON "ActivationCheckChange" FOR EACH ROW EXECUTE FUNCTION reject_demo_change()`,
|
|
|
|
|
);
|
|
|
|
|
try {
|
|
|
|
|
assert.equal(
|
|
|
|
|
(await check(id, 'API_CONNECTION', 'COMPLETE', 'alex', { note: 'trigger rollback' })).status,
|
|
|
|
|
500,
|
|
|
|
|
);
|
|
|
|
|
assert.deepEqual(await detail(id), m);
|
|
|
|
|
} finally {
|
|
|
|
|
await db.$executeRawUnsafe('DROP TRIGGER reject_demo_change ON "ActivationCheckChange"');
|
|
|
|
|
await db.$executeRawUnsafe('DROP FUNCTION reject_demo_change()');
|
|
|
|
|
}
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
test('additive migrations preserve existing decisions, collection history and terminal merchants', async () => {
|
|
|
|
|
const { createRequire } = await import('node:module');
|
|
|
|
|
const { readFileSync } = await import('node:fs');
|
|
|
|
|
const require = createRequire(
|
|
|
|
|
new URL('../../../packages/database/package.json', import.meta.url),
|
|
|
|
|
);
|
|
|
|
|
const { Client } = require('pg');
|
|
|
|
|
const client = new Client({ connectionString: process.env.DATABASE_URL });
|
|
|
|
|
const schema = `gated_upgrade_${randomUUID().replaceAll('-', '')}`;
|
|
|
|
|
await client.connect();
|
|
|
|
|
try {
|
|
|
|
|
await client.query(`CREATE SCHEMA "${schema}"`);
|
|
|
|
|
await client.query(`SET search_path TO "${schema}"`);
|
|
|
|
|
const apply = (migration) =>
|
|
|
|
|
client.query(
|
|
|
|
|
readFileSync(
|
|
|
|
|
new URL(
|
|
|
|
|
`../../../packages/database/prisma/migrations/${migration}/migration.sql`,
|
|
|
|
|
import.meta.url,
|
|
|
|
|
),
|
|
|
|
|
'utf8',
|
|
|
|
|
),
|
|
|
|
|
);
|
|
|
|
|
for (const migration of [
|
|
|
|
|
'202609240001_foundation',
|
|
|
|
|
'202609240002_onboarding',
|
|
|
|
|
'202609240003_public_leads',
|
|
|
|
|
'202609240004_sales_workspace',
|
|
|
|
|
])
|
|
|
|
|
await apply(migration);
|
|
|
|
|
await client.query(
|
|
|
|
|
`INSERT INTO "User" (id, email, name, "passwordHash", role) VALUES ('sales', 'sales@test', 'Sales', 'preserve-hash', 'ACCOUNT_MANAGER'), ('compliance', 'compliance@test', 'Compliance', 'preserve-hash', 'COMPLIANCE_OFFICER')`,
|
|
|
|
|
);
|
|
|
|
|
await client.query(
|
|
|
|
|
`INSERT INTO "Merchant" (id, name, "contactName", "contactEmail", "ownerId", status) VALUES ('unfinished', 'Old company', 'Contact', 'contact@test', 'sales', 'INTEGRATION'), ('terminal', 'Live company', 'Contact', 'contact@test', 'sales', 'LIVE')`,
|
|
|
|
|
);
|
|
|
|
|
await client.query(
|
|
|
|
|
`INSERT INTO "KybChecklistItem" (id, "merchantId", "documentCode", state, note) VALUES ('original', 'unfinished', 'UBO_IDENTIFICATION', 'RECEIVED', 'Original evidence note')`,
|
|
|
|
|
);
|
|
|
|
|
await client.query(
|
|
|
|
|
`INSERT INTO "ChecklistChange" (id, "itemId", "actorId", "toState", note) VALUES ('change', 'original', 'sales', 'RECEIVED', 'Historical note')`,
|
|
|
|
|
);
|
|
|
|
|
await client.query(
|
|
|
|
|
`INSERT INTO "ComplianceReview" (id, "merchantId", cycle, "submittedById", "reviewerId", decision, "decidedAt", snapshot) VALUES ('review', 'unfinished', 1, 'sales', 'compliance', 'APPROVED', CURRENT_TIMESTAMP, '{"company":{"name":"Old company"},"checklist":[]}')`,
|
|
|
|
|
);
|
|
|
|
|
const originalReview = (await client.query('SELECT * FROM "ComplianceReview"')).rows[0];
|
|
|
|
|
const originalItems = (await client.query('SELECT * FROM "KybChecklistItem"')).rows;
|
|
|
|
|
const originalChanges = (await client.query('SELECT * FROM "ChecklistChange"')).rows;
|
|
|
|
|
const merchants = (await client.query('SELECT * FROM "Merchant" ORDER BY id')).rows;
|
|
|
|
|
await apply('202609240005_gated_onboarding');
|
|
|
|
|
await apply('202609240006_kyb_upgrade');
|
|
|
|
|
const upgradedReview = (await client.query('SELECT * FROM "ComplianceReview"')).rows[0];
|
|
|
|
|
assert.deepEqual(upgradedReview, {
|
|
|
|
|
...originalReview,
|
|
|
|
|
policyVersion: 1,
|
|
|
|
|
riskLevel: null,
|
|
|
|
|
corrections: [],
|
|
|
|
|
});
|
|
|
|
|
assert.deepEqual(
|
|
|
|
|
(await client.query('SELECT * FROM "KybChecklistItem" WHERE id = \'original\'')).rows,
|
|
|
|
|
originalItems,
|
|
|
|
|
);
|
|
|
|
|
assert.deepEqual((await client.query('SELECT * FROM "ChecklistChange"')).rows, originalChanges);
|
|
|
|
|
const added = (
|
|
|
|
|
await client.query(
|
|
|
|
|
'SELECT * FROM "KybChecklistItem" WHERE "documentCode" = \'AUTHORIZED_REPRESENTATIVE\'',
|
|
|
|
|
)
|
|
|
|
|
).rows;
|
|
|
|
|
assert.equal(added.length, 1);
|
|
|
|
|
assert.equal(added[0].merchantId, 'unfinished');
|
|
|
|
|
assert.equal(added[0].state, 'MISSING');
|
|
|
|
|
assert.deepEqual(
|
|
|
|
|
(await client.query('SELECT * FROM "Merchant" ORDER BY id')).rows,
|
|
|
|
|
merchants.map((merchant) => ({
|
|
|
|
|
...merchant,
|
|
|
|
|
version: merchant.version + (merchant.id === 'unfinished' ? 1 : 0),
|
|
|
|
|
})),
|
|
|
|
|
);
|
|
|
|
|
assert.equal((await client.query('SELECT count(*) FROM "ActivationCheck"')).rows[0].count, '0');
|
|
|
|
|
} finally {
|
|
|
|
|
await client.query('SET search_path TO public');
|
|
|
|
|
await client.query(`DROP SCHEMA "${schema}" CASCADE`);
|
|
|
|
|
await client.end();
|
|
|
|
|
}
|
|
|
|
|
});
|