Added tasks, reminders, and role-specific dashboards

This commit is contained in:
Oleksandr Prokhorenko
2026-09-24 22:18:41 +03:00
parent 1f8721e742
commit 9ccbac4aca
33 changed files with 2583 additions and 511 deletions
+8 -5
View File
@@ -125,7 +125,7 @@ for (const [account, total] of [
merchantId: { in: ids },
...(account === 'compliance'
? { kind: 'COMPLIANCE', assigneeId: 'user-compliance' }
: {}),
: { kind: 'COMMERCIAL' }),
},
}),
);
@@ -151,7 +151,7 @@ for (const [account, total] of [
merchantId: { in: ids },
...(account === 'compliance'
? { kind: 'COMPLIANCE', assigneeId: 'user-compliance' }
: {}),
: { kind: 'COMMERCIAL' }),
status: 'OPEN',
dueAt: { lt: new Date() },
},
@@ -775,7 +775,7 @@ test('reassignment transfers open commercial tasks; concurrent writes and former
);
const before = await get();
assert.equal((await get(comp)).tasks.length, 1);
const personal = before.tasks.find((t) => t.kind === 'COMPLIANCE');
const personal = (await get(comp)).tasks.find((t) => t.kind === 'COMPLIANCE');
assert.equal(
(
await mutate(`/merchants/${id}/tasks/${personal.id}`, head, {
@@ -783,7 +783,7 @@ test('reassignment transfers open commercial tasks; concurrent writes and former
version: before.version,
})
).status,
403,
404,
);
const commercial = before.tasks.find((t) => t.kind === 'COMMERCIAL');
assert.equal(
@@ -828,7 +828,10 @@ test('reassignment transfers open commercial tasks; concurrent writes and former
.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 get(comp)).tasks.find((t) => t.kind === 'COMPLIANCE').assignee.id,
'user-compliance',
);
assert.equal((await request(`/merchants/${id}`, alex)).status, 404);
assert.equal(
(
+441
View File
@@ -0,0 +1,441 @@
import { before, after, test } from 'node:test';
import assert from 'node:assert/strict';
import { createDatabase } from '@merchantflow/database';
import { dashboardSchema, taskListSchema } from '@merchantflow/contracts';
if (!process.env.DATABASE_URL?.endsWith('/merchantflow_test'))
throw new Error('Isolated test database required');
const db = createDatabase(process.env.DATABASE_URL);
let app, base;
const cookies = {};
async function start() {
const { createApp } = await import('../dist/app.js');
app = await createApp();
await app.listen(0, '127.0.0.1');
base = (await app.getUrl()) + '/api';
}
async function request(path, account = 'head', body, method = body ? 'POST' : 'GET') {
const response = await fetch(base + path, {
method,
headers: {
origin: process.env.APP_ORIGIN ?? 'http://localhost:5173',
...(cookies[account] ? { cookie: cookies[account] } : {}),
...(body ? { 'content-type': 'application/json' } : {}),
},
...(body ? { body: JSON.stringify(body) } : {}),
});
return { status: response.status, body: await response.json(), headers: response.headers };
}
async function login(account) {
const r = await request('/auth/login', account, {
email: `${account}@merchantflow.test`,
password: 'MerchantFlow123!',
});
assert.equal(r.status, 201);
cookies[account] = r.headers.get('set-cookie').split(';')[0];
}
before(async () => {
await start();
for (const a of ['head', 'alex', 'sam', 'compliance']) await login(a);
});
after(async () => {
await db.merchant.deleteMany({ where: { id: { startsWith: 'tasks-check-' } } });
await db.user.deleteMany({ where: { id: 'tasks-empty-manager' } });
await app?.close();
await db.$disconnect();
});
async function fixture(id, ownerId = 'user-manager1') {
return db.merchant.create({
data: {
id,
name: id,
contactName: 'Test',
contactEmail: '[email protected]',
ownerId,
createdAt: new Date(),
status: 'NEW_LEAD',
},
});
}
async function detail(id, account = 'head') {
const r = await request(`/merchants/${id}`, account);
assert.equal(r.status, 200);
return r.body;
}
async function save(id, account, fields, taskId) {
const m = await detail(id, account);
return request(
`/merchants/${id}/tasks${taskId ? '/' + taskId : ''}`,
account,
{ version: m.version, ...fields },
taskId ? 'PATCH' : 'POST',
);
}
const input = (overrides = {}) => ({
title: 'Actionable task',
dueAt: new Date(Date.now() + 86400000).toISOString(),
remindAt: new Date(Date.now() - 1000).toISOString(),
status: 'OPEN',
...overrides,
});
test('seed dashboards and drilldowns match independent scoped records and earliest Live events', async () => {
const rows = await db.merchant.findMany({
include: { events: true, tasks: true, reviews: true },
});
assert.equal(rows.length, 45);
for (const [account, owner] of [
['head', null],
['alex', 'user-manager1'],
['sam', 'user-manager2'],
['compliance', null],
]) {
const response = await request('/dashboard', account);
assert.equal(response.status, 200);
const d = dashboardSchema.parse(response.body);
const visible = rows.filter((m) => !owner || m.ownerId === owner);
const asOf = new Date(d.asOf),
start = new Date(d.periodStart);
const live = visible.filter((m) => m.status === 'LIVE').length;
const durations = visible.flatMap((m) => {
const first = m.events
.filter((e) => e.toStatus === 'LIVE')
.sort((a, b) => a.occurredAt - b.occurredAt)[0];
return first ? [(first.occurredAt - m.createdAt) / 86400000] : [];
});
assert.equal(d.merchantCount, visible.length);
assert.equal(d.liveMerchants, live);
assert.equal(d.activation.rate, live / visible.length);
assert.equal(d.onboardingDuration.sampleCount, durations.length);
assert.equal(
d.onboardingDuration.averageDays,
durations.reduce((a, b) => a + b, 0) / durations.length,
);
assert.equal(
d.newLeads,
visible.filter((m) => m.createdAt >= start && m.createdAt <= asOf).length,
);
assert.equal(
d.activeOnboarding,
visible.filter((m) =>
['KYB', 'COMPLIANCE_REVIEW', 'INTEGRATION', 'TESTING'].includes(m.status),
).length,
);
for (const row of d.distribution)
assert.equal(row.count, visible.filter((m) => m.status === row.status).length);
assert.equal(
d.distribution.reduce((n, s) => n + s.count, 0),
visible.length,
);
const tasks = visible
.flatMap((m) => m.tasks)
.filter((t) =>
account === 'compliance'
? t.kind === 'COMPLIANCE' && t.assigneeId === 'user-compliance'
: t.kind === 'COMMERCIAL',
);
assert.equal(d.overdueTasks, tasks.filter((t) => t.status === 'OPEN' && t.dueAt < asOf).length);
assert.equal(
(
await request(
`/merchants?${new URLSearchParams({ createdFrom: d.periodStart, createdTo: d.asOf })}`,
account,
)
).body.total,
d.newLeads,
);
assert.equal(
(await request('/merchants?cohort=ACTIVE_ONBOARDING', account)).body.total,
d.activeOnboarding,
);
assert.equal(
(await request('/merchants?cohort=REACHED_LIVE', account)).body.total,
d.onboardingDuration.sampleCount,
);
if (owner)
assert.deepEqual(
d.workload.map((w) => w.id),
[owner],
);
for (const w of d.workload) {
assert.equal(w.merchants, visible.filter((m) => m.ownerId === w.id).length);
assert.equal(
w.openTasks,
tasks.filter((t) => t.assigneeId === w.id && t.status === 'OPEN').length,
);
}
if (account === 'compliance') {
const expected = visible
.flatMap((m) => m.reviews)
.filter((r) => r.decision !== 'PENDING' && r.decidedAt >= start && r.decidedAt <= asOf);
assert.equal(d.decisionsLast30Days, expected.length);
const history = await request(
`/review-queue?${new URLSearchParams({ view: 'DECISIONS', decidedFrom: d.periodStart, decidedTo: d.asOf })}`,
account,
);
assert.equal(history.body.filteredCount, expected.length);
assert.deepEqual(
d.oldestReviews.map((r) => r.id),
visible
.flatMap((m) =>
m.status === 'COMPLIANCE_REVIEW'
? m.reviews.filter((r) => r.decision === 'PENDING')
: [],
)
.sort((a, b) => a.submittedAt - b.submittedAt || a.id.localeCompare(b.id))
.slice(0, 5)
.map((r) => r.id),
);
}
}
});
test('task endpoints enforce manager isolation and private Compliance tasks', async () => {
for (const [account, other, ownId, hiddenId] of [
['alex', 'sam', 'merchant-01', 'merchant-02'],
['sam', 'alex', 'merchant-02', 'merchant-01'],
]) {
const hidden = await detail(hiddenId, other);
const task = hidden.tasks[0];
assert.equal((await request(`/merchants/${hiddenId}`, account)).status, 404);
assert.deepEqual((await request(`/tasks?merchantId=${hiddenId}`, account)).body, []);
assert.equal(
(
await request(`/merchants/${hiddenId}/tasks`, account, {
version: hidden.version,
...input(),
})
).status,
404,
);
assert.equal(
(
await request(
`/merchants/${ownId}/tasks/${task.id}`,
account,
{ version: (await detail(ownId, account)).version, ...input() },
'PATCH',
)
).status,
404,
);
assert.equal(
(await request(`/tasks/${task.id}/reminder-dismissal`, account, { reminderRevision: 0 }))
.status,
404,
);
assert.equal((await request(`/tasks?assigneeId=${task.assignee.id}`, account)).status, 403);
const list = taskListSchema.parse((await request('/tasks', account)).body);
assert.ok(list.every((t) => t.kind === 'COMMERCIAL'));
assert.equal(
(await request(`/merchants?search=${encodeURIComponent(hidden.name)}`, account)).body.total,
0,
);
}
const id = 'tasks-check-private';
await fixture(id);
assert.equal((await save(id, 'compliance', input())).status, 201);
const privateTask = (await detail(id, 'compliance')).tasks[0];
for (const account of ['head', 'alex']) {
assert.equal((await detail(id, account)).tasks.length, 0);
assert.ok(!(await detail(id, account)).history.some((entry) => entry.text === 'Task created'));
assert.equal((await save(id, account, input(), privateTask.id)).status, 404);
assert.ok(!(await request('/reminders', account)).body.some((t) => t.id === privateTask.id));
}
assert.equal((await request('/reminders', 'anonymous')).status, 401);
assert.equal(
(await request(`/tasks/${privateTask.id}/reminder-dismissal`, 'head', { reminderRevision: 0 }))
.status,
404,
);
await db.merchant.delete({ where: { id } });
});
test('reminder timing, dismissal, completion, rescheduling and API restart persist correctly', async (t) => {
const id = 'tasks-check-reminders';
await fixture(id);
const now = Date.now();
t.mock.timers.enable({ apis: ['Date'], now });
const fields = input({
dueAt: new Date(now + 3600000).toISOString(),
remindAt: new Date(now + 1000).toISOString(),
});
assert.equal((await save(id, 'alex', fields)).status, 201);
let task = (await detail(id, 'alex')).tasks[0];
const inbox = async () =>
(await request('/reminders', 'alex')).body.filter((x) => x.id === task.id);
assert.equal((await inbox()).length, 0);
t.mock.timers.setTime(now + 1000);
assert.equal((await inbox()).length, 1);
t.mock.timers.setTime(now + 1001);
assert.equal((await inbox()).length, 1);
assert.equal(
(
await request(`/tasks/${task.id}/reminder-dismissal`, 'alex', {
reminderRevision: task.reminderRevision,
})
).status,
201,
);
assert.equal(
(
await request(`/tasks/${task.id}/reminder-dismissal`, 'alex', {
reminderRevision: task.reminderRevision,
})
).status,
201,
);
assert.equal((await inbox()).length, 0);
await app.close();
await start();
assert.equal((await inbox()).length, 0);
assert.equal((await save(id, 'alex', { ...fields, status: 'DONE' }, task.id)).status, 200);
assert.equal((await save(id, 'alex', fields, task.id)).status, 200);
assert.equal((await inbox()).length, 0);
const changed = { ...fields, remindAt: new Date(now).toISOString() };
assert.equal((await save(id, 'alex', changed, task.id)).status, 200);
assert.equal((await inbox()).length, 1);
assert.equal(
(
await request(`/tasks/${task.id}/reminder-dismissal`, 'alex', {
reminderRevision: task.reminderRevision,
})
).status,
409,
);
assert.equal((await save(id, 'alex', { ...changed, status: 'DONE' }, task.id)).status, 200);
assert.equal((await inbox()).length, 0);
assert.equal((await save(id, 'alex', changed, task.id)).status, 200);
assert.equal((await inbox()).length, 1);
const reopened = await db.task.findUniqueOrThrow({ where: { id: task.id } });
assert.equal(reopened.completedAt, null);
assert.equal(reopened.completedById, null);
assert.equal((await save(id, 'alex', { ...changed, remindAt: null }, task.id)).status, 200);
assert.equal((await inbox()).length, 0);
t.mock.timers.reset();
await db.merchant.delete({ where: { id } });
});
test('reassignment transfers only open sales tasks and reopening preserves prior completion in audit', async () => {
const id = 'tasks-check-handoff';
await fixture(id);
const fields = input();
for (const [account, status] of [
['alex', 'OPEN'],
['alex', 'DONE'],
['compliance', 'OPEN'],
])
assert.equal((await save(id, account, { ...fields, status })).status, 201);
const before = await detail(id);
const open = before.tasks.find((t) => t.status === 'OPEN'),
done = before.tasks.find((t) => t.status === 'DONE');
await request(`/tasks/${open.id}/reminder-dismissal`, 'alex', { reminderRevision: 0 });
const results = await Promise.all([
request(
`/merchants/${id}/assignment`,
'head',
{ version: before.version, ownerId: 'user-manager2' },
'PATCH',
),
request(
`/merchants/${id}/tasks/${open.id}`,
'alex',
{ version: before.version, ...fields, title: 'Racing edit' },
'PATCH',
),
]);
assert.equal(results.filter((r) => r.status === 200).length, 1);
if (results[0].status !== 200)
assert.equal(
(
await request(
`/merchants/${id}/assignment`,
'head',
{ version: (await detail(id)).version, ownerId: 'user-manager2' },
'PATCH',
)
).status,
200,
);
assert.equal((await request(`/merchants/${id}`, 'alex')).status, 404);
assert.equal(
(await request(`/tasks/${open.id}/reminder-dismissal`, 'alex', { reminderRevision: 0 })).status,
404,
);
let after = await detail(id, 'sam');
assert.equal(after.tasks.find((t) => t.id === open.id).assignee.id, 'user-manager2');
assert.equal(after.tasks.find((t) => t.id === done.id).assignee.id, 'user-manager1');
assert.equal((await detail(id, 'compliance')).tasks[0].assignee.id, 'user-compliance');
assert.ok((await request('/reminders', 'sam')).body.some((t) => t.id === open.id));
assert.equal((await save(id, 'sam', { ...fields, status: 'DONE' }, done.id)).status, 403);
assert.equal((await save(id, 'sam', fields, done.id)).status, 200);
after = await detail(id, 'sam');
assert.equal(after.tasks.find((t) => t.id === done.id).assignee.id, 'user-manager2');
const audit = await db.activity.findMany({ where: { merchantId: id, kind: 'AUDIT' } });
assert.ok(
audit.some(
(a) =>
a.metadata?.taskId === done.id &&
a.metadata.previousCompletedById === 'user-manager1' &&
a.metadata.previousCompletedAt,
),
);
await db.merchant.delete({ where: { id } });
});
test('empty portfolios, zero-history metrics, first-Live deduplication and date bounds are honest', async () => {
const original = await db.user.findUniqueOrThrow({ where: { id: 'user-manager1' } });
await db.user.create({
data: {
id: 'tasks-empty-manager',
name: 'Empty manager',
email: '[email protected]',
passwordHash: original.passwordHash,
role: 'ACCOUNT_MANAGER',
},
});
await login('empty');
let d = (await request('/dashboard', 'empty')).body;
assert.equal(d.merchantCount, 0);
assert.equal(d.activation.rate, null);
assert.equal(d.onboardingDuration.averageDays, null);
assert.equal(d.onboardingDuration.sampleCount, 0);
const now = new Date(),
start = new Date(now - 30 * 86400000);
const id = 'tasks-check-metrics';
await fixture(id, 'tasks-empty-manager');
await db.merchant.update({ where: { id }, data: { createdAt: start, status: 'LIVE' } });
d = (await request('/dashboard', 'empty')).body;
assert.equal(d.activation.rate, 1);
assert.equal(d.onboardingDuration.averageDays, null);
for (const days of [5, 8])
await db.statusEvent.create({
data: {
merchantId: id,
toStatus: 'LIVE',
occurredAt: new Date(start.getTime() + days * 86400000),
},
});
d = (await request('/dashboard', 'empty')).body;
assert.equal(d.onboardingDuration.sampleCount, 1);
assert.equal(d.onboardingDuration.averageDays, 5);
assert.equal(
(
await request(
`/merchants?${new URLSearchParams({ createdFrom: start.toISOString(), createdTo: start.toISOString() })}`,
'empty',
)
).body.total,
1,
);
assert.equal(
(
await request(
`/merchants?${new URLSearchParams({ createdFrom: new Date(start.getTime() + 1).toISOString() })}`,
'empty',
)
).body.total,
0,
);
await db.merchant.delete({ where: { id } });
await db.user.delete({ where: { id: 'tasks-empty-manager' } });
});
+24
View File
@@ -34,3 +34,27 @@ test('every role receives its exact merchant scope', () => {
assert.deepEqual(merchantScope({ role: 'COMPLIANCE_OFFICER' }), {});
assert.deepEqual(merchantScope({ role: 'unexpected' }), { id: '__no_access__' });
});
test('task day boundaries use the viewer time zone through DST and include exact due instants', async () => {
const { localDayBounds, taskWhere } = await import('../dist/task-policy.js');
for (const [date, hours] of [
['2026-03-08T12:00:00Z', 23],
['2026-11-01T12:00:00Z', 25],
]) {
const { start, end } = localDayBounds(new Date(date), 'America/New_York');
assert.equal((end - start) / 3600000, hours);
}
const now = new Date('2026-09-24T22:00:00Z');
const { start, end } = localDayBounds(now, 'Europe/Kyiv');
assert.equal(start.toISOString(), '2026-09-24T21:00:00.000Z');
assert.equal(end.toISOString(), '2026-09-25T21:00:00.000Z');
const user = { id: 'manager', role: 'ACCOUNT_MANAGER' };
assert.deepEqual(
taskWhere(user, { filter: 'TODAY', timeZone: 'Europe/Kyiv' }, now).AND[1].dueAt,
{ gte: start, lt: end },
);
assert.deepEqual(
taskWhere(user, { filter: 'UPCOMING', timeZone: 'Europe/Kyiv' }, now).AND[1].dueAt,
{ gte: end },
);
});