474 lines
18 KiB
JavaScript
474 lines
18 KiB
JavaScript
import { before, after, afterEach, test } from 'node:test';
|
|
import assert from 'node:assert/strict';
|
|
import { randomUUID } from 'node:crypto';
|
|
import { createDatabase } from '@merchantflow/database';
|
|
import {
|
|
merchantDetailSchema,
|
|
pipelineBoardSchema,
|
|
merchantFiltersSchema,
|
|
statuses,
|
|
} 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');
|
|
|
|
test('staff creation is atomic, minimally required, role-bound and strict', async () => {
|
|
const unassigned = await create();
|
|
let m = await detail(unassigned);
|
|
assert.equal(m.status, 'NEW_LEAD');
|
|
assert.equal(m.owner, null);
|
|
assert.equal(m.website, null);
|
|
assert.equal(m.country, null);
|
|
assert.equal(m.industry, null);
|
|
assert.equal(m.checklist.length, 4);
|
|
assert.ok(m.checklist.every((item) => item.state === 'MISSING'));
|
|
assert.equal(m.events.length, 1);
|
|
assert.equal(m.activities.length, 1);
|
|
assert.equal(m.activities[0].actor.name, 'Elena Carter');
|
|
assert.equal(m.history.length, 1); // Initial stage and creation audit represent one event.
|
|
assert.equal(m.version, 0);
|
|
assert.ok(!JSON.stringify(m).includes('publicSubmission'));
|
|
const assigned = await create('head', {
|
|
ownerId: 'user-manager2',
|
|
website: 'example.test',
|
|
country: 'gb',
|
|
industry: 'SOFTWARE',
|
|
estimatedMonthlyVolumeUsd: '0',
|
|
});
|
|
m = await detail(assigned);
|
|
assert.equal(m.owner.id, 'user-manager2');
|
|
assert.equal(m.country, 'GB');
|
|
assert.equal(m.estimatedMonthlyVolumeUsd, '0');
|
|
const self = await create('alex');
|
|
assert.equal((await detail(self)).owner.id, 'user-manager1');
|
|
for (const ownerId of ['user-manager2', null])
|
|
assert.equal((await request('/merchants', 'alex', input({ ownerId }))).status, 403);
|
|
assert.equal((await request('/merchants', 'compliance', input())).status, 403);
|
|
assert.equal((await request('/merchants', null, input())).status, 401);
|
|
assert.equal(
|
|
(await request('/merchants', 'head', input(), 'POST', { origin: 'https://untrusted.test' }))
|
|
.status,
|
|
403,
|
|
);
|
|
assert.equal((await request('/merchants', 'head', input({ ownerId: 'user-head' }))).status, 400);
|
|
for (const field of ['status', 'actorId', 'reviewerId', 'publicSubmissionKey', 'version'])
|
|
assert.equal(
|
|
(await request('/merchants', 'head', input({ [field]: 'injected' }))).status,
|
|
400,
|
|
field,
|
|
);
|
|
for (const field of ['name', 'contactName', 'contactEmail'])
|
|
assert.equal((await request('/merchants', 'head', input({ [field]: '' }))).status, 400, field);
|
|
assert.equal((await request(`/merchants/${self}`, 'sam')).status, 404);
|
|
assert.equal((await request(`/merchants/${assigned}`, 'alex')).status, 404);
|
|
});
|
|
|
|
test('search, combined filters, pagination and metadata apply ownership scope before counts', async () => {
|
|
const prefix = `Directory-${randomUUID()}`;
|
|
const ids = [];
|
|
for (let index = 0; index < 10; index++)
|
|
ids.push(
|
|
await create('alex', {
|
|
name: `${prefix} ${index}`,
|
|
contactName: `${prefix} Contact`,
|
|
contactEmail: `${prefix.toLowerCase()}@example.test`,
|
|
country: 'GB',
|
|
industry: 'SOFTWARE',
|
|
website: 'search.example.test',
|
|
}),
|
|
);
|
|
const hidden = await create('sam', {
|
|
name: `${prefix} Hidden`,
|
|
country: 'JP',
|
|
industry: 'TRAVEL',
|
|
});
|
|
const unassigned = await create('head', { name: `${prefix} Unassigned` });
|
|
await change(ids[0], '', { legalName: `${prefix} Legal` });
|
|
for (const search of [
|
|
`${prefix} 1`,
|
|
`${prefix} Contact`,
|
|
`${prefix.toLowerCase()}@example.test`,
|
|
`${prefix} Legal`,
|
|
]) {
|
|
const result = await request(`/merchants?search=${encodeURIComponent(search)}`, 'alex');
|
|
assert.equal(result.status, 200);
|
|
assert.ok(result.body.total > 0);
|
|
assert.ok(result.body.items.every((m) => m.owner.id === 'user-manager1'));
|
|
}
|
|
const query = `search=${prefix}&country=GB&industry=SOFTWARE&status=NEW_LEAD`;
|
|
const page1 = (await request(`/merchants?${query}`, 'alex')).body;
|
|
const page2 = (await request(`/merchants?${query}&page=2`, 'alex')).body;
|
|
assert.equal(page1.total, 10);
|
|
assert.equal(page1.items.length, 8);
|
|
assert.equal(page2.items.length, 2);
|
|
assert.equal(new Set([...page1.items, ...page2.items].map((m) => m.id)).size, 10);
|
|
assert.equal((await request(`/merchants?${query}&page=10000`, 'alex')).body.page, 2);
|
|
assert.equal((await request(`/merchants?${query}&ownerId=user-manager2`, 'alex')).status, 403);
|
|
assert.equal(
|
|
(await request(`/merchants?search=${prefix}&ownerId=user-manager2`, 'head')).body.items[0].id,
|
|
hidden,
|
|
);
|
|
assert.equal(
|
|
(await request(`/merchants?search=${prefix}&ownerId=unassigned`, 'compliance')).body.items[0]
|
|
.id,
|
|
unassigned,
|
|
);
|
|
assert.equal((await request(`/merchants?search=${prefix}&country=JP`, 'alex')).body.total, 0);
|
|
for (const invalid of ['country=ZZ', 'industry=INVALID', 'status=Live', 'page=1.5', 'page=-1'])
|
|
assert.equal((await request(`/merchants?${invalid}`)).status, 400);
|
|
const ownFilters = merchantFiltersSchema.parse(
|
|
(await request('/merchants/filters', 'alex')).body,
|
|
);
|
|
assert.equal(ownFilters.canFilterOwner, false);
|
|
assert.deepEqual(ownFilters.owners, []);
|
|
assert.equal(ownFilters.canCreate, true);
|
|
const expectedCountries = [
|
|
...new Set(
|
|
(
|
|
await db.merchant.findMany({ where: { ownerId: 'user-manager1', country: { not: null } } })
|
|
).map((m) => m.country),
|
|
),
|
|
].sort();
|
|
assert.deepEqual(ownFilters.countries, expectedCountries);
|
|
const complianceFilters = merchantFiltersSchema.parse(
|
|
(await request('/merchants/filters', 'compliance')).body,
|
|
);
|
|
assert.equal(complianceFilters.canFilterOwner, true);
|
|
assert.equal(complianceFilters.canCreate, false);
|
|
assert.equal((await request('/users/assignable-managers', 'compliance')).status, 403);
|
|
});
|
|
|
|
test('commercial gates expose the same blockers as mutations and accept a zero volume', async () => {
|
|
const id = await create();
|
|
const action = async () =>
|
|
(await detail(id)).capabilities.actions.find((a) => a.kind === 'ADVANCE');
|
|
assert.deepEqual(
|
|
(await action()).blockingReasons.map((b) => b.code),
|
|
['ASSIGNMENT_REQUIRED', 'CONTACT_REQUIRED'],
|
|
);
|
|
let result = await move(id, 'CONTACTED');
|
|
assert.equal(result.status, 409);
|
|
assert.deepEqual(result.body.blockingReasons, (await action()).blockingReasons);
|
|
assert.equal((await detail(id)).version, 0);
|
|
await change(id, '/assignment', { ownerId: 'user-manager1' });
|
|
await log(id, 'MEETING');
|
|
assert.equal((await move(id, 'CONTACTED', 'alex')).status, 409);
|
|
await log(id, 'EMAIL');
|
|
assert.equal((await action()).enabled, true);
|
|
assert.equal((await move(id, 'CONTACTED', 'alex')).status, 201);
|
|
assert.equal((await move(id, 'QUALIFIED', 'alex')).status, 409);
|
|
assert.deepEqual(
|
|
(await action()).blockingReasons[0].fields.sort(),
|
|
['website', 'country', 'industry', 'estimatedMonthlyVolumeUsd'].sort(),
|
|
);
|
|
await change(
|
|
id,
|
|
'',
|
|
{ website: 'sales.test', country: 'GB', industry: 'OTHER', estimatedMonthlyVolumeUsd: '0' },
|
|
'alex',
|
|
);
|
|
assert.equal((await move(id, 'QUALIFIED', 'alex')).status, 201);
|
|
assert.equal((await move(id, 'KYB', 'alex')).status, 201);
|
|
result = await move(id, 'COMPLIANCE_REVIEW', 'alex');
|
|
assert.equal(result.status, 409);
|
|
assert.equal(result.body.blockingReasons[0].code, 'DOCUMENTS_REQUIRED');
|
|
const m = await detail(id);
|
|
assert.equal(m.events.filter((event) => event.toStatus === 'CONTACTED').length, 1);
|
|
assert.equal(
|
|
m.history.filter((entry) => entry.kind === 'STAGE' && entry.toStatus === 'CONTACTED').length,
|
|
1,
|
|
);
|
|
for (const payload of [
|
|
{ status: 'LIVE' },
|
|
{ ownerId: 'user-manager2' },
|
|
{ actorId: 'user-head' },
|
|
])
|
|
assert.equal((await change(id, '', payload, 'alex')).status, 400);
|
|
assert.equal((await move(id, 'LIVE', 'alex')).status, 409);
|
|
assert.equal((await move(id, 'TESTING', 'compliance')).status, 403);
|
|
const pipe = pipelineBoardSchema.parse((await request('/pipeline', 'alex')).body);
|
|
assert.deepEqual(
|
|
pipe.find((row) => row.id === id).capabilities,
|
|
(await detail(id, 'alex')).capabilities,
|
|
);
|
|
});
|
|
|
|
test('every rejection role and stage rule is enforced, with terminal outcomes and preserved compliance records', async () => {
|
|
for (const stage of statuses) {
|
|
for (const actor of ['head', 'alex', 'compliance']) {
|
|
const id = await create('alex');
|
|
await db.merchant.update({ where: { id }, data: { status: stage } });
|
|
const allowed =
|
|
(['NEW_LEAD', 'CONTACTED', 'QUALIFIED'].includes(stage) && actor !== 'compliance') ||
|
|
(['KYB', 'INTEGRATION', 'TESTING'].includes(stage) && actor === 'head');
|
|
assert.equal(
|
|
(await move(id, 'REJECTED', actor, ' Business no longer proceeding ')).status,
|
|
allowed
|
|
? 201
|
|
: actor === 'compliance' ||
|
|
stage === 'COMPLIANCE_REVIEW' ||
|
|
!['LIVE', 'REJECTED'].includes(stage)
|
|
? 403
|
|
: 409,
|
|
`${stage}/${actor}`,
|
|
);
|
|
const m = await detail(id);
|
|
assert.equal(m.status, allowed ? 'REJECTED' : stage);
|
|
if (allowed) {
|
|
assert.equal(m.events[0].note, 'Business no longer proceeding');
|
|
assert.equal(m.capabilities.actions.length, 0);
|
|
assert.equal((await move(id, 'NEW_LEAD', actor)).status, 409);
|
|
}
|
|
}
|
|
}
|
|
const id = await create('alex');
|
|
for (const reason of [undefined, '', ' '])
|
|
assert.equal((await move(id, 'REJECTED', 'alex', reason)).status, 400);
|
|
assert.equal((await detail(id)).version, 0);
|
|
// Head closure of an approved merchant must retain the original immutable decision.
|
|
const approved = await db.merchant.findFirst({
|
|
where: { status: 'INTEGRATION' },
|
|
include: { reviews: true },
|
|
});
|
|
const clone = await create('alex');
|
|
await db.merchant.update({ where: { id: clone }, data: { status: 'INTEGRATION' } });
|
|
const review = await db.complianceReview.create({
|
|
data: {
|
|
merchantId: clone,
|
|
cycle: 1,
|
|
decision: 'APPROVED',
|
|
submittedById: 'user-head',
|
|
reviewerId: 'user-compliance',
|
|
decidedAt: new Date(),
|
|
snapshot: approved.reviews[0].snapshot,
|
|
},
|
|
});
|
|
assert.equal((await move(clone, 'REJECTED', 'head', 'Commercial terms declined')).status, 201);
|
|
assert.deepEqual(await db.complianceReview.findUnique({ where: { id: review.id } }), review);
|
|
});
|
|
|
|
test('qualification and assignment gates cannot be bypassed; approved integration evidence is still required', async () => {
|
|
for (const stage of ['QUALIFIED', 'INTEGRATION', 'TESTING']) {
|
|
const id = await create('head', stage === 'QUALIFIED' ? {} : { ownerId: 'user-manager1' });
|
|
await db.merchant.update({ where: { id }, data: { status: stage } });
|
|
const target = stage === 'QUALIFIED' ? 'KYB' : stage === 'INTEGRATION' ? 'TESTING' : 'LIVE';
|
|
const result = await move(id, target);
|
|
assert.equal(result.status, 409);
|
|
assert.equal(
|
|
result.body.blockingReasons[0].code,
|
|
stage === 'QUALIFIED' ? 'ASSIGNMENT_REQUIRED' : 'APPROVAL_REQUIRED',
|
|
);
|
|
}
|
|
});
|
|
|
|
test('ownership handoff retains attribution and persists typed chronological history', async () => {
|
|
const id = await create('alex');
|
|
await log(id, 'NOTE', 'Durable note');
|
|
await log(id, 'CALL', 'Durable call');
|
|
const open = await db.task.create({
|
|
data: {
|
|
merchantId: id,
|
|
title: 'Transfer me',
|
|
assigneeId: 'user-manager1',
|
|
creatorId: 'user-head',
|
|
dueAt: new Date(),
|
|
},
|
|
});
|
|
const done = await db.task.create({
|
|
data: {
|
|
merchantId: id,
|
|
title: 'Keep attribution',
|
|
status: 'DONE',
|
|
assigneeId: 'user-manager1',
|
|
creatorId: 'user-manager1',
|
|
completedById: 'user-head',
|
|
completedAt: new Date(),
|
|
dueAt: new Date(),
|
|
},
|
|
});
|
|
const comp = await db.task.create({
|
|
data: {
|
|
merchantId: id,
|
|
title: 'Personal review',
|
|
kind: 'COMPLIANCE',
|
|
assigneeId: 'user-compliance',
|
|
creatorId: 'user-compliance',
|
|
dueAt: new Date(),
|
|
},
|
|
});
|
|
const original = await detail(id);
|
|
assert.equal((await change(id, '/assignment', { ownerId: 'user-manager2' })).status, 200);
|
|
assert.equal((await db.task.findUnique({ where: { id: open.id } })).assigneeId, 'user-manager2');
|
|
assert.deepEqual(await db.task.findUnique({ where: { id: done.id } }), done);
|
|
assert.deepEqual(await db.task.findUnique({ where: { id: comp.id } }), comp);
|
|
assert.equal((await request(`/merchants/${id}`, 'alex')).status, 404);
|
|
assert.equal(
|
|
(
|
|
await request(`/merchants/${id}/activities`, 'alex', {
|
|
version: original.version,
|
|
kind: 'NOTE',
|
|
text: 'Former owner',
|
|
})
|
|
).status,
|
|
404,
|
|
);
|
|
const m = await detail(id, 'sam');
|
|
const ownership = m.history.find((entry) => entry.kind === 'OWNERSHIP');
|
|
assert.equal(ownership.previousOwner.id, 'user-manager1');
|
|
assert.equal(ownership.owner.id, 'user-manager2');
|
|
assert.equal(ownership.actor.name, 'Elena Carter');
|
|
assert.deepEqual(
|
|
m.history.map((entry) => entry.occurredAt),
|
|
[...m.history.map((entry) => entry.occurredAt)].sort().reverse(),
|
|
);
|
|
for (const activity of original.activities)
|
|
assert.deepEqual(m.activities.find((entry) => entry.id === activity.id).actor, activity.actor);
|
|
assert.ok(!JSON.stringify(m).includes('previousOwnerId'));
|
|
assert.ok(
|
|
m.history.some((entry) => entry.kind === 'INTERACTION' && entry.text === 'Durable call'),
|
|
);
|
|
assert.deepEqual((await detail(id, 'sam')).history, m.history);
|
|
});
|
|
|
|
test('conflicting transitions, ownership and activity writes commit at most once', async () => {
|
|
const id = await create('alex');
|
|
await log(id);
|
|
let m = await detail(id);
|
|
const results = await Promise.all([
|
|
request(`/merchants/${id}/transitions`, 'alex', { version: m.version, toStatus: 'CONTACTED' }),
|
|
request(
|
|
`/merchants/${id}/assignment`,
|
|
'head',
|
|
{ version: m.version, ownerId: 'user-manager2' },
|
|
'PATCH',
|
|
),
|
|
request(`/merchants/${id}/activities`, 'alex', {
|
|
version: m.version,
|
|
kind: 'EMAIL',
|
|
text: 'Concurrent outreach',
|
|
}),
|
|
]);
|
|
assert.equal(results.filter((r) => r.status < 300).length, 1);
|
|
assert.ok(results.filter((r) => r.status >= 300).every((r) => [404, 409].includes(r.status)));
|
|
assert.equal((await detail(id)).version, m.version + 1);
|
|
assert.equal(
|
|
(
|
|
await request(`/merchants/${id}/transitions`, 'head', {
|
|
version: m.version,
|
|
toStatus: 'REJECTED',
|
|
reason: 'Stale closure',
|
|
})
|
|
).status,
|
|
409,
|
|
);
|
|
m = await detail(id);
|
|
const rejection = await Promise.all(
|
|
[1, 2].map(() =>
|
|
request(`/merchants/${id}/transitions`, 'head', {
|
|
version: m.version,
|
|
toStatus: 'REJECTED',
|
|
reason: 'Closure',
|
|
}),
|
|
),
|
|
);
|
|
assert.deepEqual(rejection.map((r) => r.status).sort(), [201, 409]);
|
|
assert.equal(
|
|
(await detail(id)).events.filter((event) => event.toStatus === 'REJECTED').length,
|
|
1,
|
|
);
|
|
});
|
|
|
|
test('failed audit writes roll back merchant creation and stage changes completely', async () => {
|
|
const id = await create('alex');
|
|
await log(id);
|
|
const original = await detail(id);
|
|
await db.$executeRaw`CREATE FUNCTION fail_sales_audit() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN IF NEW.text = 'NEW_LEAD → CONTACTED' OR NEW.text = 'Merchant created' THEN RAISE EXCEPTION 'Injected sales failure'; END IF; RETURN NEW; END $$`;
|
|
await db.$executeRaw`CREATE TRIGGER sales_audit_failure BEFORE INSERT ON "Activity" FOR EACH ROW EXECUTE FUNCTION fail_sales_audit()`;
|
|
try {
|
|
assert.equal((await move(id, 'CONTACTED', 'alex')).status, 500);
|
|
assert.deepEqual(await detail(id), original);
|
|
const name = `Rollback-${randomUUID()}`;
|
|
assert.equal((await request('/merchants', 'head', input({ name }))).status, 500);
|
|
assert.equal(await db.merchant.count({ where: { name } }), 0);
|
|
} finally {
|
|
await db.$executeRaw`DROP TRIGGER sales_audit_failure ON "Activity"`;
|
|
await db.$executeRaw`DROP FUNCTION fail_sales_audit()`;
|
|
}
|
|
});
|