Implemented the database, authentication, access rules, and seed data
This commit is contained in:
@@ -19,6 +19,7 @@ async function request(path, cookie, options = {}) {
|
||||
...options,
|
||||
headers: {
|
||||
...(cookie ? { cookie } : {}),
|
||||
origin: process.env.APP_ORIGIN ?? 'http://localhost:5173',
|
||||
...(options.body ? { 'content-type': 'application/json' } : {}),
|
||||
...options.headers,
|
||||
},
|
||||
@@ -36,7 +37,7 @@ before(async () => {
|
||||
app = await createApp();
|
||||
await app.listen(0, '127.0.0.1');
|
||||
base = (await app.getUrl()) + '/api';
|
||||
for (const account of ['head', 'compliance', 'manager1', 'manager2']) {
|
||||
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];
|
||||
@@ -88,17 +89,17 @@ test('login validates, sets protected cookies, and rejects incorrect credentials
|
||||
);
|
||||
});
|
||||
for (const [account, total] of [
|
||||
['head', 18],
|
||||
['manager1', 9],
|
||||
['manager2', 9],
|
||||
['compliance', 4],
|
||||
['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'
|
||||
? account === 'head' || ['KYB', 'COMPLIANCE_REVIEW'].includes(m.status)
|
||||
: m.ownerId === `user-${account}`,
|
||||
? true
|
||||
: m.ownerId === (account === 'alex' ? 'user-manager1' : 'user-manager2'),
|
||||
);
|
||||
assert.equal(expected.length, total);
|
||||
const ids = expected.map((m) => m.id);
|
||||
@@ -117,7 +118,17 @@ for (const [account, total] of [
|
||||
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.equal(
|
||||
tasks.length,
|
||||
await db.task.count({
|
||||
where: {
|
||||
merchantId: { in: ids },
|
||||
...(account === 'compliance'
|
||||
? { kind: 'COMPLIANCE', assigneeId: 'user-compliance' }
|
||||
: {}),
|
||||
},
|
||||
}),
|
||||
);
|
||||
assert.ok(tasks.every((t) => ids.includes(t.merchant.id)));
|
||||
for (const m of expected) {
|
||||
const detail = (await request(`/merchants/${m.id}`, cookie)).body;
|
||||
@@ -136,7 +147,14 @@ for (const [account, total] of [
|
||||
assert.equal(
|
||||
dashboard.overdueTasks,
|
||||
await db.task.count({
|
||||
where: { merchantId: { in: ids }, status: 'OPEN', dueAt: { lt: new Date() } },
|
||||
where: {
|
||||
merchantId: { in: ids },
|
||||
...(account === 'compliance'
|
||||
? { kind: 'COMPLIANCE', assigneeId: 'user-compliance' }
|
||||
: {}),
|
||||
status: 'OPEN',
|
||||
dueAt: { lt: new Date() },
|
||||
},
|
||||
}),
|
||||
);
|
||||
assert.equal(
|
||||
@@ -174,13 +192,13 @@ test('filters are validated and review queue is oldest first', async () => {
|
||||
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);
|
||||
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;
|
||||
assert.equal(queue.length, 2);
|
||||
assert.equal(queue.length, 6);
|
||||
assert.ok(queue.every((m) => m.status === 'COMPLIANCE_REVIEW'));
|
||||
assert.ok(new Date(queue[0].stageEnteredAt) <= new Date(queue[1].stageEnteredAt));
|
||||
});
|
||||
@@ -195,7 +213,7 @@ test('seed is repeatable without modifying records; history includes correction
|
||||
});
|
||||
assert.equal(result.status, 0, result.stderr);
|
||||
assert.equal(await db.user.count(), 4);
|
||||
assert.equal(await db.merchant.count(), 18);
|
||||
assert.equal(await db.merchant.count(), 45);
|
||||
assert.deepEqual(
|
||||
await db.merchant.findMany({
|
||||
orderBy: { id: 'asc' },
|
||||
@@ -211,7 +229,7 @@ test('seed is repeatable without modifying records; history includes correction
|
||||
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 r = await login('alex');
|
||||
const cookie = r.response.headers.get('set-cookie').split(';')[0];
|
||||
const token = cookie.split('=')[1];
|
||||
await db.session.update({
|
||||
@@ -219,14 +237,779 @@ test('expired, logged-out and replaced sessions cannot be reused', async () => {
|
||||
data: { expiresAt: new Date(0) },
|
||||
});
|
||||
assert.equal((await request('/auth/me', cookie)).status, 401);
|
||||
const fresh = await login('manager1');
|
||||
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.manager2, {
|
||||
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.manager2)).status, 401);
|
||||
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',
|
||||
legalName: 'Workflow Test Ltd',
|
||||
website: 'https://workflow.example',
|
||||
industry: 'SOFTWARE',
|
||||
country: 'GB',
|
||||
contactName: 'Test Contact',
|
||||
contactEmail: '[email protected]',
|
||||
ownerId,
|
||||
status,
|
||||
checklist: { create: documentCodes.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' }, '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 },
|
||||
'POST',
|
||||
);
|
||||
try {
|
||||
assert.equal((await move('LIVE')).status, 409);
|
||||
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' },
|
||||
'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', 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, 201);
|
||||
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' },
|
||||
'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 = before.tasks.find((t) => t.kind === 'COMPLIANCE');
|
||||
assert.equal(
|
||||
(
|
||||
await mutate(`/merchants/${id}/tasks/${personal.id}`, head, {
|
||||
...task,
|
||||
version: before.version,
|
||||
})
|
||||
).status,
|
||||
403,
|
||||
);
|
||||
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(after.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);
|
||||
});
|
||||
|
||||
@@ -14,8 +14,6 @@ test('every role receives its exact merchant scope', () => {
|
||||
assert.deepEqual(merchantScope({ role: 'ACCOUNT_MANAGER', id: 'manager-1' }), {
|
||||
ownerId: 'manager-1',
|
||||
});
|
||||
assert.deepEqual(merchantScope({ role: 'COMPLIANCE_OFFICER' }), {
|
||||
status: { in: ['KYB', 'COMPLIANCE_REVIEW'] },
|
||||
});
|
||||
assert.deepEqual(merchantScope({ role: 'COMPLIANCE_OFFICER' }), {});
|
||||
assert.deepEqual(merchantScope({ role: 'unexpected' }), { id: '__no_access__' });
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user