Built merchant management, activity history, and the pipeline
This commit is contained in:
@@ -262,6 +262,7 @@ async function fixture(id, status = 'NEW_LEAD', ownerId = 'user-manager1') {
|
||||
data: {
|
||||
id,
|
||||
name: 'Workflow Test',
|
||||
estimatedMonthlyVolumeUsd: '10000',
|
||||
legalName: 'Workflow Test Ltd',
|
||||
website: 'https://workflow.example',
|
||||
industry: 'SOFTWARE',
|
||||
@@ -438,11 +439,30 @@ test('corrections, resubmission, approval and activation preserve one merchant a
|
||||
mutate(
|
||||
`/merchants/${id}/transitions`,
|
||||
cookie,
|
||||
{ version: (await detail()).version, toStatus },
|
||||
{
|
||||
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);
|
||||
|
||||
@@ -0,0 +1,282 @@
|
||||
import { beforeEach, afterEach, after, test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import { createDatabase } from '@merchantflow/database';
|
||||
import { merchantDetailSchema, dashboardSchema } 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 keys = new Set();
|
||||
let app, base;
|
||||
const origin = process.env.APP_ORIGIN;
|
||||
const input = () => ({
|
||||
name: 'Public lead integration',
|
||||
contactName: 'Test Contact',
|
||||
contactEmail: `lead-${randomUUID()}@example.test`,
|
||||
website: 'example.test',
|
||||
country: 'GB',
|
||||
industry: 'OTHER',
|
||||
estimatedMonthlyVolumeUsd: '1234,50',
|
||||
companyFax: '',
|
||||
});
|
||||
function key() {
|
||||
const value = randomUUID();
|
||||
keys.add(value);
|
||||
return value;
|
||||
}
|
||||
async function start() {
|
||||
app = await createApp();
|
||||
await app.listen(0, '127.0.0.1');
|
||||
base = `${await app.getUrl()}/api`;
|
||||
}
|
||||
async function request(path, body, headers = {}, method = 'POST', url = base) {
|
||||
const response = await fetch(`${url}${path}`, {
|
||||
method,
|
||||
headers: {
|
||||
origin,
|
||||
...(body !== undefined ? { 'content-type': 'application/json' } : {}),
|
||||
...headers,
|
||||
},
|
||||
...(body !== undefined ? { body: JSON.stringify(body) } : {}),
|
||||
});
|
||||
return { status: response.status, body: await response.json(), headers: response.headers };
|
||||
}
|
||||
const submit = (data, id, headers = {}, url = base) =>
|
||||
request('/public/leads', data, { 'Idempotency-Key': id, ...headers }, 'POST', url);
|
||||
async function cookie(account) {
|
||||
const result = await request('/auth/login', {
|
||||
email: `${account}@merchantflow.test`,
|
||||
password: 'MerchantFlow123!',
|
||||
});
|
||||
assert.equal(result.status, 201);
|
||||
return result.headers.get('set-cookie').split(';')[0];
|
||||
}
|
||||
beforeEach(start);
|
||||
afterEach(async () => {
|
||||
await app?.close();
|
||||
await db.merchant.deleteMany({ where: { publicSubmissionKey: { in: [...keys] } } });
|
||||
keys.clear();
|
||||
});
|
||||
after(() => db.$disconnect());
|
||||
|
||||
test('public submission persists complete onboarding context and respects CRM permissions', async () => {
|
||||
const id = key(),
|
||||
data = input();
|
||||
const result = await submit(data, id);
|
||||
assert.equal(result.status, 202);
|
||||
assert.deepEqual(result.body, { ok: true });
|
||||
const merchant = await db.merchant.findUnique({
|
||||
where: { publicSubmissionKey: id },
|
||||
include: { activities: true, events: true, checklist: { include: { changes: true } } },
|
||||
});
|
||||
assert.equal(merchant.status, 'NEW_LEAD');
|
||||
assert.equal(merchant.ownerId, null);
|
||||
assert.equal(merchant.source, 'LANDING_PAGE');
|
||||
assert.equal(merchant.version, 0);
|
||||
assert.equal(merchant.name, data.name);
|
||||
assert.equal(merchant.contactName, data.contactName);
|
||||
assert.equal(merchant.contactEmail, data.contactEmail);
|
||||
assert.equal(merchant.country, 'GB');
|
||||
assert.equal(merchant.industry, 'OTHER');
|
||||
assert.equal(merchant.website, 'https://example.test/');
|
||||
assert.equal(merchant.estimatedMonthlyVolumeUsd.toFixed(2), '1234.50');
|
||||
assert.equal(merchant.checklist.length, 4);
|
||||
assert.ok(
|
||||
merchant.checklist.every((item) => item.state === 'MISSING' && item.changes.length === 0),
|
||||
);
|
||||
assert.equal(merchant.activities.length, 1);
|
||||
assert.equal(merchant.activities[0].actorId, null);
|
||||
assert.equal(merchant.activities[0].kind, 'AUDIT');
|
||||
assert.equal(merchant.events.length, 1);
|
||||
assert.equal(merchant.events[0].actorId, null);
|
||||
assert.equal(merchant.events[0].fromStatus, null);
|
||||
assert.equal(merchant.events[0].toStatus, 'NEW_LEAD');
|
||||
const head = await cookie('head'),
|
||||
compliance = await cookie('compliance'),
|
||||
alex = await cookie('alex'),
|
||||
sam = await cookie('sam');
|
||||
for (const staff of [head, compliance]) {
|
||||
const detail = await request(`/merchants/${merchant.id}`, undefined, { cookie: staff }, 'GET');
|
||||
assert.equal(detail.status, 200);
|
||||
assert.equal(merchantDetailSchema.safeParse(detail.body).success, true);
|
||||
assert.equal(detail.body.activities[0].actor, null);
|
||||
assert.ok(!JSON.stringify(detail.body).includes('publicSubmission'));
|
||||
const dashboard = await request('/dashboard', undefined, { cookie: staff }, 'GET');
|
||||
assert.equal(dashboardSchema.safeParse(dashboard.body).success, true);
|
||||
}
|
||||
for (const staff of [alex, sam]) {
|
||||
assert.equal(
|
||||
(await request(`/merchants/${merchant.id}`, undefined, { cookie: staff }, 'GET')).status,
|
||||
404,
|
||||
);
|
||||
const list = await request(
|
||||
`/merchants?search=${encodeURIComponent(data.contactEmail)}`,
|
||||
undefined,
|
||||
{ cookie: staff },
|
||||
'GET',
|
||||
);
|
||||
assert.equal(list.body.total, 0);
|
||||
}
|
||||
assert.equal(
|
||||
(
|
||||
await request(
|
||||
`/merchants/${merchant.id}/transitions`,
|
||||
{ version: 0, toStatus: 'CONTACTED' },
|
||||
{ cookie: head },
|
||||
)
|
||||
).status,
|
||||
409,
|
||||
);
|
||||
assert.equal(
|
||||
(
|
||||
await request(
|
||||
`/merchants/${merchant.id}/assignment`,
|
||||
{ version: 0, ownerId: 'user-manager1' },
|
||||
{ cookie: head },
|
||||
'PATCH',
|
||||
)
|
||||
).status,
|
||||
200,
|
||||
);
|
||||
assert.equal(
|
||||
(
|
||||
await request(
|
||||
`/merchants/${merchant.id}/activities`,
|
||||
{ version: 1, kind: 'EMAIL', text: 'Responded to the public enquiry' },
|
||||
{ cookie: alex },
|
||||
)
|
||||
).status,
|
||||
201,
|
||||
);
|
||||
assert.equal(
|
||||
(
|
||||
await request(
|
||||
`/merchants/${merchant.id}/transitions`,
|
||||
{ version: 2, toStatus: 'CONTACTED' },
|
||||
{ cookie: alex },
|
||||
)
|
||||
).status,
|
||||
201,
|
||||
);
|
||||
assert.equal(
|
||||
(
|
||||
await request(
|
||||
`/merchants/${merchant.id}/activities/${merchant.activities[0].id}`,
|
||||
{ version: 3, kind: 'NOTE', text: 'attempt to edit audit' },
|
||||
{ cookie: head },
|
||||
'PATCH',
|
||||
)
|
||||
).status,
|
||||
403,
|
||||
);
|
||||
});
|
||||
|
||||
test('sequential, concurrent and post-restart retries create exactly one lead', async () => {
|
||||
const id = key(),
|
||||
data = input();
|
||||
const other = await createApp();
|
||||
await other.listen(0, '127.0.0.1');
|
||||
try {
|
||||
const results = await Promise.all([
|
||||
submit(data, id),
|
||||
submit(data, id),
|
||||
submit(data, id, {}, `${await other.getUrl()}/api`),
|
||||
]);
|
||||
assert.ok(results.every((result) => result.status === 202));
|
||||
assert.equal((await submit({ ...data, estimatedMonthlyVolumeUsd: '1234.50' }, id)).status, 202);
|
||||
} finally {
|
||||
await other.close();
|
||||
}
|
||||
await app.close();
|
||||
await start();
|
||||
assert.equal((await submit(data, id)).status, 202);
|
||||
assert.equal((await submit({ ...data, name: 'Changed payload' }, id)).status, 409);
|
||||
const matches = await db.merchant.findMany({
|
||||
where: { publicSubmissionKey: id },
|
||||
include: { activities: true, events: true },
|
||||
});
|
||||
assert.equal(matches.length, 1);
|
||||
assert.equal(matches[0].activities.length, 1);
|
||||
assert.equal(matches[0].events.length, 1);
|
||||
});
|
||||
|
||||
test('honeypots always accept valid envelopes without creating any related records', async () => {
|
||||
const before = [
|
||||
await db.merchant.count(),
|
||||
await db.activity.count(),
|
||||
await db.statusEvent.count(),
|
||||
await db.kybChecklistItem.count(),
|
||||
];
|
||||
for (let i = 0; i < 12; i++) {
|
||||
const result = await submit(
|
||||
i % 2 ? { ...input(), companyFax: 'spam' } : { companyFax: ' ', contactEmail: 'invalid' },
|
||||
key(),
|
||||
);
|
||||
assert.equal(result.status, 202);
|
||||
assert.deepEqual(result.body, { ok: true });
|
||||
}
|
||||
assert.deepEqual(
|
||||
[
|
||||
await db.merchant.count(),
|
||||
await db.activity.count(),
|
||||
await db.statusEvent.count(),
|
||||
await db.kybChecklistItem.count(),
|
||||
],
|
||||
before,
|
||||
);
|
||||
});
|
||||
|
||||
test('origin, key and body checks reject invalid submissions without persisting', async () => {
|
||||
const id = key();
|
||||
for (const headers of [
|
||||
{ origin: 'https://untrusted.example' },
|
||||
{ origin: '' },
|
||||
{ 'sec-fetch-site': 'cross-site' },
|
||||
])
|
||||
assert.equal((await submit(input(), id, headers)).status, 403);
|
||||
assert.equal((await submit(input(), 'invalid')).status, 400);
|
||||
assert.equal((await request('/public/leads', input())).status, 400);
|
||||
for (const data of [
|
||||
{ ...input(), country: 'ZZ' },
|
||||
{ ...input(), ownerId: 'user-head' },
|
||||
{ ...input(), estimatedMonthlyVolumeUsd: '-1' },
|
||||
{ ...input(), companyFax: 42 },
|
||||
])
|
||||
assert.equal((await submit(data, id)).status, 400);
|
||||
assert.equal(await db.merchant.count({ where: { publicSubmissionKey: id } }), 0);
|
||||
});
|
||||
|
||||
test('email quotas allow successful replays and IP quotas include invalid attempts', async () => {
|
||||
const data = input(),
|
||||
first = key();
|
||||
assert.equal((await submit(data, first)).status, 202);
|
||||
for (let i = 0; i < 2; i++) assert.equal((await submit(data, key())).status, 202);
|
||||
assert.equal((await submit(data, first)).status, 202);
|
||||
const result = await submit(data, key());
|
||||
assert.equal(result.status, 429);
|
||||
assert.ok(Number(result.headers.get('retry-after')) > 0);
|
||||
await app.close();
|
||||
await start();
|
||||
for (let i = 0; i < 10; i++) assert.equal((await submit({}, key())).status, 400);
|
||||
const limited = await submit(input(), key(), { 'x-forwarded-for': '1.2.3.4' });
|
||||
assert.equal(limited.status, 429);
|
||||
assert.ok(Number(limited.headers.get('retry-after')) > 0);
|
||||
});
|
||||
|
||||
test('a failed creation activity rolls back the lead and its children; retry remains safe', async () => {
|
||||
const id = key(),
|
||||
data = { ...input(), name: 'Force rollback integration' };
|
||||
await db.$executeRaw`CREATE FUNCTION fail_public_lead_activity() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN IF EXISTS (SELECT 1 FROM "Merchant" WHERE id = NEW."merchantId" AND name = 'Force rollback integration') THEN RAISE EXCEPTION 'Injected test failure'; END IF; RETURN NEW; END $$`;
|
||||
await db.$executeRaw`CREATE TRIGGER fail_public_lead_activity BEFORE INSERT ON "Activity" FOR EACH ROW EXECUTE FUNCTION fail_public_lead_activity()`;
|
||||
try {
|
||||
assert.equal((await submit(data, id)).status, 500);
|
||||
assert.equal(await db.merchant.count({ where: { publicSubmissionKey: id } }), 0);
|
||||
} finally {
|
||||
await db.$executeRaw`DROP TRIGGER fail_public_lead_activity ON "Activity"`;
|
||||
await db.$executeRaw`DROP FUNCTION fail_public_lead_activity()`;
|
||||
}
|
||||
assert.equal((await submit(data, id)).status, 202);
|
||||
assert.equal(await db.merchant.count({ where: { publicSubmissionKey: id } }), 1);
|
||||
});
|
||||
@@ -0,0 +1,473 @@
|
||||
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()`;
|
||||
}
|
||||
});
|
||||
@@ -2,6 +2,7 @@ import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { merchantScope } from '../dist/access.js';
|
||||
import { hashPassword, verifyPassword } from '@merchantflow/database';
|
||||
import { LeadRateLimiter } from '../dist/public-leads.js';
|
||||
test('passwords use distinct salts and reject incorrect values', () => {
|
||||
const hash = hashPassword('example-password');
|
||||
assert.notEqual(hash, hashPassword('example-password'));
|
||||
@@ -9,6 +10,22 @@ test('passwords use distinct salts and reject incorrect values', () => {
|
||||
assert.equal(verifyPassword('wrong', hash), false);
|
||||
assert.equal(verifyPassword('wrong', 'broken'), false);
|
||||
});
|
||||
test('public lead limits expire, bound storage and reserve each submission once', () => {
|
||||
let now = 0;
|
||||
const limiter = new LeadRateLimiter(() => now, 3);
|
||||
for (let i = 0; i < 10; i++) assert.equal(limiter.attemptIp('127.0.0.1'), 0);
|
||||
assert.equal(limiter.attemptIp('127.0.0.1'), 900);
|
||||
for (let i = 0; i < 3; i++) assert.equal(limiter.reserveEmail('[email protected]', String(i)), 0);
|
||||
assert.equal(limiter.reserveEmail('[email protected]', '0'), 0);
|
||||
assert.equal(limiter.reserveEmail('[email protected]', 'new'), 900);
|
||||
limiter.releaseEmail('[email protected]', '0');
|
||||
assert.equal(limiter.reserveEmail('[email protected]', 'new'), 0);
|
||||
assert.equal(limiter.attemptIp('another'), 0);
|
||||
assert.equal(limiter.attemptIp('map-full'), 900);
|
||||
now = 900001;
|
||||
assert.equal(limiter.attemptIp('map-full'), 0);
|
||||
assert.equal(limiter.reserveEmail('[email protected]', 'another'), 0);
|
||||
});
|
||||
test('every role receives its exact merchant scope', () => {
|
||||
assert.deepEqual(merchantScope({ role: 'HEAD_OF_SALES' }), {});
|
||||
assert.deepEqual(merchantScope({ role: 'ACCOUNT_MANAGER', id: 'manager-1' }), {
|
||||
|
||||
Reference in New Issue
Block a user