Implemented the database, authentication, access rules, and seed data

This commit is contained in:
Oleksandr Prokhorenko
2026-09-24 19:08:55 +03:00
parent 3aa47d825f
commit 5de240fda3
27 changed files with 3793 additions and 277 deletions
+41 -1
View File
@@ -1,14 +1,54 @@
import type { User } from '@merchantflow/contracts';
import type { Prisma } from '@merchantflow/database';
import { successfulStages, type Status } from '@merchantflow/contracts';
import { ApiError } from './shared.js';
export function merchantScope(user: User): Prisma.MerchantWhereInput {
switch (user.role) {
case 'HEAD_OF_SALES':
return {};
case 'COMPLIANCE_OFFICER':
return { status: { in: ['KYB', 'COMPLIANCE_REVIEW'] } };
return {};
case 'ACCOUNT_MANAGER':
return { ownerId: user.id };
default:
return { id: '__no_access__' };
}
}
export function taskScope(user: User): Prisma.TaskWhereInput {
return {
merchant: merchantScope(user),
...(user.role === 'COMPLIANCE_OFFICER' ? { assigneeId: user.id, kind: 'COMPLIANCE' } : {}),
};
}
export function requireSales(user: User) {
if (!['HEAD_OF_SALES', 'ACCOUNT_MANAGER'].includes(user.role))
throw new ApiError('FORBIDDEN', 403);
}
export function capabilities(
user: User,
merchant: { status: Status; ownerId: string | null; reviews: { decision: string }[] },
) {
const sales =
user.role === 'HEAD_OF_SALES' ||
(user.role === 'ACCOUNT_MANAGER' && merchant.ownerId === user.id);
const locked = merchant.reviews.some((review) =>
['PENDING', 'APPROVED'].includes(review.decision),
);
const index = successfulStages.findIndex((stage) => stage === merchant.status);
return {
editCommercial: sales,
editIdentity: sales && !locked,
assign: user.role === 'HEAD_OF_SALES',
collectChecklist: sales && merchant.status === 'KYB' && !locked,
review: user.role === 'COMPLIANCE_OFFICER' && merchant.status === 'COMPLIANCE_REVIEW',
activityKinds:
user.role === 'COMPLIANCE_OFFICER'
? (['KYB_NOTE'] as const)
: (['NOTE', 'CALL', 'EMAIL', 'MEETING'] as const),
manageTaskKind: user.role === 'COMPLIANCE_OFFICER' ? 'COMPLIANCE' : 'COMMERCIAL',
nextStage:
sales && merchant.ownerId && index >= 0 && merchant.status !== 'COMPLIANCE_REVIEW'
? (successfulStages[index + 1] ?? null)
: null,
};
}
+2 -1
View File
@@ -12,6 +12,7 @@ import cookieParser from 'cookie-parser';
import { createDatabase, PrismaClient } from '@merchantflow/database';
import { AuthController, AuthService, SessionGuard } from './auth.js';
import { CrmController } from './crm.js';
import { WorkflowController } from './workflow.js';
import { DATABASE, ApiError, ErrorFilter } from './shared.js';
import { env } from './env.js';
@Controller('health')
@@ -34,7 +35,7 @@ class DatabaseLifecycle implements OnApplicationShutdown {
}
}
@Module({
controllers: [HealthController, AuthController, CrmController],
controllers: [HealthController, AuthController, CrmController, WorkflowController],
providers: [
{ provide: DATABASE, useFactory: () => createDatabase(env.DATABASE_URL) },
DatabaseLifecycle,
+16 -8
View File
@@ -45,17 +45,23 @@ export class AuthService {
async login(body: unknown, request: Request, response: Response) {
this.checkOrigin(request);
const input = loginSchema.parse(body);
const key = request.ip ?? 'local';
const now = Date.now();
for (const [ip, value] of this.attempts) if (value.until <= now) this.attempts.delete(ip);
const attempt = this.attempts.get(key) ?? { count: 0, until: now + 300000 };
if (attempt.count >= 20) throw new ApiError('TOO_MANY_REQUESTS', 429);
attempt.count++;
this.attempts.set(key, attempt);
for (const [key, value] of this.attempts) if (value.until <= now) this.attempts.delete(key);
for (const [key, limit] of [
[`ip:${request.ip ?? 'local'}`, 100],
[`email:${input.email}`, 20],
] as const) {
const attempt = this.attempts.get(key) ?? { count: 0, until: now + 300000 };
if (attempt.count >= limit || (!this.attempts.has(key) && this.attempts.size >= 10000)) {
response.setHeader('Retry-After', Math.max(1, Math.ceil((attempt.until - now) / 1000)));
throw new ApiError('TOO_MANY_REQUESTS', 429);
}
attempt.count++;
this.attempts.set(key, attempt);
}
const user = await this.db.user.findUnique({ where: { email: input.email } });
const valid = verifyPassword(input.password, user?.passwordHash ?? dummyHash);
if (!user || !valid) throw new ApiError('INVALID_CREDENTIALS', 401);
this.attempts.delete(key);
await this.revoke(request.cookies?.[cookieName]);
await this.db.session.deleteMany({ where: { expiresAt: { lt: new Date() } } });
const token = randomBytes(32).toString('hex');
@@ -77,7 +83,8 @@ export class AuthService {
allowed.add(origin.origin);
}
if (
(req.headers.origin && !allowed.has(req.headers.origin)) ||
!req.headers.origin ||
!allowed.has(req.headers.origin) ||
req.headers['sec-fetch-site'] === 'cross-site'
)
throw new ApiError('FORBIDDEN', 403);
@@ -94,6 +101,7 @@ export class SessionGuard implements CanActivate {
async canActivate(context: ExecutionContext) {
const req = context.switchToHttp().getRequest<AuthRequest>();
req.user = await this.auth.current(req.cookies?.[cookieName]);
if (!['GET', 'HEAD', 'OPTIONS'].includes(req.method)) this.auth.checkOrigin(req);
return true;
}
}
+83 -8
View File
@@ -3,7 +3,7 @@ import { PrismaClient, type Prisma } from '@merchantflow/database';
import { statuses, merchantQuerySchema, taskQuerySchema } from '@merchantflow/contracts';
import { SessionGuard } from './auth.js';
import { DATABASE, ApiError, type AuthRequest } from './shared.js';
import { merchantScope } from './access.js';
import { capabilities, merchantScope, taskScope } from './access.js';
const merchantSelect = {
id: true,
name: true,
@@ -12,6 +12,16 @@ const merchantSelect = {
country: true,
contactName: true,
contactEmail: true,
legalName: true,
registrationNumber: true,
address: true,
contactPhone: true,
contactTitle: true,
estimatedMonthlyVolumeUsd: true,
source: true,
version: true,
updatedAt: true,
ownerId: true,
status: true,
createdAt: true,
stageEnteredAt: true,
@@ -30,16 +40,38 @@ const taskSelect = {
id: true,
title: true,
status: true,
kind: true,
createdAt: true,
updatedAt: true,
dueAt: true,
remindAt: true,
completedAt: true,
merchant: { select: { id: true, name: true } },
assignee: { select: { name: true } },
assignee: { select: { id: true, name: true } },
creator: { select: { name: true } },
completedBy: { select: { name: true } },
} as const;
const activitySelect = {
id: true,
kind: true,
text: true,
occurredAt: true,
updatedAt: true,
actor: { select: { id: true, name: true } },
merchant: { select: { id: true, name: true } },
} as const;
@UseGuards(SessionGuard)
@Controller()
export class CrmController {
constructor(@Inject(DATABASE) private readonly db: PrismaClient) {}
@Get('users/assignable-managers') managers(@Req() req: AuthRequest) {
if (req.user.role !== 'HEAD_OF_SALES') throw new ApiError('FORBIDDEN', 403);
return this.db.user.findMany({
where: { role: 'ACCOUNT_MANAGER' },
select: { id: true, name: true, email: true },
orderBy: { name: 'asc' },
});
}
@Get('merchants') async merchants(@Req() req: AuthRequest, @Query() query: unknown) {
const { page, search, status } = merchantQuerySchema.parse(query);
const where: Prisma.MerchantWhereInput = {
@@ -52,6 +84,9 @@ export class CrmController {
OR: [
{ name: { contains: search, mode: 'insensitive' as const } },
{ contactEmail: { contains: search, mode: 'insensitive' as const } },
{ legalName: { contains: search, mode: 'insensitive' as const } },
{ contactName: { contains: search, mode: 'insensitive' as const } },
{ website: { contains: search, mode: 'insensitive' as const } },
],
},
]
@@ -76,7 +111,23 @@ export class CrmController {
select: {
...merchantSelect,
checklist: {
select: { id: true, documentCode: true, state: true, note: true },
select: {
id: true,
documentCode: true,
state: true,
note: true,
changes: {
select: {
id: true,
fromState: true,
toState: true,
note: true,
occurredAt: true,
actor: { select: { name: true } },
},
orderBy: [{ occurredAt: 'desc' }, { id: 'asc' }],
},
},
orderBy: { documentCode: 'asc' },
},
notes: {
@@ -84,11 +135,25 @@ export class CrmController {
orderBy: { createdAt: 'desc' },
},
events: { select: eventSelect, orderBy: { occurredAt: 'desc' } },
tasks: { select: taskSelect, orderBy: { dueAt: 'asc' } },
tasks: { where: taskScope(req.user), select: taskSelect, orderBy: { dueAt: 'asc' } },
activities: { select: activitySelect, orderBy: [{ occurredAt: 'desc' }, { id: 'asc' }] },
reviews: {
select: {
id: true,
cycle: true,
decision: true,
reason: true,
submittedAt: true,
decidedAt: true,
submittedBy: { select: { name: true } },
reviewer: { select: { name: true } },
},
orderBy: { cycle: 'desc' },
},
},
});
if (!merchant) throw new ApiError('NOT_FOUND', 404);
return merchant;
return { ...merchant, capabilities: capabilities(req.user, merchant) };
}
@Get('pipeline') pipeline(@Req() req: AuthRequest) {
return this.db.merchant.findMany({
@@ -99,7 +164,7 @@ export class CrmController {
}
@Get('tasks') tasks(@Req() req: AuthRequest, @Query() query: unknown) {
const { filter } = taskQuerySchema.parse(query);
const where: Prisma.TaskWhereInput = { merchant: merchantScope(req.user) };
const where: Prisma.TaskWhereInput = taskScope(req.user);
if (filter === 'DONE') where.status = 'DONE';
if (['OPEN', 'OVERDUE', 'UPCOMING'].includes(filter)) where.status = 'OPEN';
if (filter === 'OVERDUE') where.dueAt = { lt: new Date() };
@@ -134,10 +199,13 @@ export class CrmController {
distribution,
recentEvents,
upcomingTasks,
recentActivities,
] = await this.db.$transaction([
this.db.merchant.count({ where: scope }),
this.db.merchant.count({ where: { AND: [scope, { status: 'COMPLIANCE_REVIEW' }] } }),
this.db.task.count({ where: { merchant: scope, status: 'OPEN', dueAt: { lt: new Date() } } }),
this.db.task.count({
where: { ...taskScope(req.user), status: 'OPEN', dueAt: { lt: new Date() } },
}),
this.db.statusEvent.count({
where: {
merchant: scope,
@@ -153,11 +221,17 @@ export class CrmController {
take: 6,
}),
this.db.task.findMany({
where: { merchant: scope, status: 'OPEN' },
where: { ...taskScope(req.user), status: 'OPEN' },
select: taskSelect,
orderBy: { dueAt: 'asc' },
take: 4,
}),
this.db.activity.findMany({
where: { merchant: scope },
select: activitySelect,
orderBy: [{ occurredAt: 'desc' }, { id: 'asc' }],
take: 8,
}),
]);
return {
merchantCount,
@@ -170,6 +244,7 @@ export class CrmController {
})),
recentEvents,
upcomingTasks,
recentActivities,
};
}
}
+386
View File
@@ -0,0 +1,386 @@
import { Body, Controller, Inject, Param, Patch, Post, Req, UseGuards } from '@nestjs/common';
import {
PrismaClient,
type Prisma,
checklistComplete,
reviewSnapshot,
reviewedFields,
snapshotsEqual,
} from '@merchantflow/database';
import {
activityInputSchema,
assignmentSchema,
checklistEditSchema,
merchantEditSchema,
reviewDecisionSchema,
taskInputSchema,
transitionSchema,
successfulStages,
} from '@merchantflow/contracts';
import { SessionGuard } from './auth.js';
import { capabilities, merchantScope, requireSales, taskScope } from './access.js';
import { ApiError, DATABASE, type AuthRequest } from './shared.js';
const evidenceInclude = {
checklist: { include: { changes: { orderBy: { occurredAt: 'asc' as const } } } },
reviews: {
include: { reviewer: { select: { role: true } } },
orderBy: { cycle: 'desc' as const },
},
} as const;
type Evidence = Prisma.MerchantGetPayload<{ include: typeof evidenceInclude }>;
function receivedHistory(merchant: Evidence, at: Date) {
return (
checklistComplete(merchant.checklist) &&
merchant.checklist.every(
(item) =>
item.changes.filter((change) => change.occurredAt <= at).at(-1)?.toState === 'RECEIVED',
)
);
}
function validApproval(merchant: Evidence) {
const review = merchant.reviews[0];
return (
review?.decision === 'APPROVED' &&
review.reviewer?.role === 'COMPLIANCE_OFFICER' &&
review.decidedAt &&
review.decidedAt >= review.submittedAt &&
receivedHistory(merchant, review.submittedAt) &&
snapshotsEqual(review.snapshot, reviewSnapshot(merchant))
);
}
@UseGuards(SessionGuard)
@Controller('merchants')
export class WorkflowController {
constructor(@Inject(DATABASE) private readonly db: PrismaClient) {}
private async mutate(
req: AuthRequest,
id: string,
version: number,
action: (tx: Prisma.TransactionClient, merchant: Evidence) => Promise<void>,
) {
await this.db.$transaction(async (tx) => {
const scope = { AND: [merchantScope(req.user), { id }] };
const merchant = await tx.merchant.findFirst({ where: scope, include: evidenceInclude });
if (!merchant) throw new ApiError('NOT_FOUND', 404);
// This conditional write locks the parent and rechecks ownership/version after any wait.
// Every child mutation and ownership change takes the same lock before writing.
const claimed = await tx.merchant.updateMany({
where: { AND: [scope, { version }] },
data: { version: { increment: 1 } },
});
if (!claimed.count) {
if (!(await tx.merchant.findFirst({ where: scope, select: { id: true } })))
throw new ApiError('NOT_FOUND', 404);
throw new ApiError('CONFLICT', 409);
}
await action(tx, merchant);
});
return { ok: true };
}
private async audit(
tx: Prisma.TransactionClient,
req: AuthRequest,
merchantId: string,
text: string,
metadata?: Prisma.InputJsonValue,
) {
await tx.activity.create({
data: { merchantId, actorId: req.user.id, kind: 'AUDIT', text, metadata },
});
}
private async stage(
tx: Prisma.TransactionClient,
req: AuthRequest,
merchant: Evidence,
toStatus: Evidence['status'],
note?: string,
) {
const occurredAt = new Date();
await tx.merchant.updateMany({
where: { AND: [merchantScope(req.user), { id: merchant.id }] },
data: { status: toStatus, stageEnteredAt: occurredAt },
});
await tx.statusEvent.create({
data: {
merchantId: merchant.id,
actorId: req.user.id,
fromStatus: merchant.status,
toStatus,
occurredAt,
note,
},
});
await this.audit(tx, req, merchant.id, `${merchant.status} → ${toStatus}`, {
fromStatus: merchant.status,
toStatus,
note: note ?? null,
});
}
@Patch(':id') edit(@Req() req: AuthRequest, @Param('id') id: string, @Body() body: unknown) {
const { version, ...data } = merchantEditSchema.parse(body);
return this.mutate(req, id, version, async (tx, merchant) => {
requireSales(req.user);
if (!Object.keys(data).length) throw new ApiError('VALIDATION_ERROR', 400);
if (
!capabilities(req.user, merchant).editIdentity &&
reviewedFields.some((key) => data[key] !== undefined && data[key] !== merchant[key])
)
throw new ApiError('REVIEW_LOCKED', 409);
await tx.merchant.updateMany({ where: { AND: [merchantScope(req.user), { id }] }, data });
await this.audit(tx, req, id, 'Merchant details updated', { fields: Object.keys(data) });
});
}
@Patch(':id/assignment') assign(
@Req() req: AuthRequest,
@Param('id') id: string,
@Body() body: unknown,
) {
const { version, ownerId } = assignmentSchema.parse(body);
return this.mutate(req, id, version, async (tx, merchant) => {
if (req.user.role !== 'HEAD_OF_SALES') throw new ApiError('FORBIDDEN', 403);
if (
!(await tx.user.findFirst({
where: { id: ownerId, role: 'ACCOUNT_MANAGER' },
select: { id: true },
}))
)
throw new ApiError('VALIDATION_ERROR', 400);
await tx.merchant.updateMany({ where: { id }, data: { ownerId } });
await tx.task.updateMany({
where: { merchantId: id, kind: 'COMMERCIAL', status: 'OPEN' },
data: { assigneeId: ownerId },
});
await this.audit(tx, req, id, 'Manager assignment updated', {
previousOwnerId: merchant.ownerId,
ownerId,
});
});
}
@Post(':id/transitions') transition(
@Req() req: AuthRequest,
@Param('id') id: string,
@Body() body: unknown,
) {
const { version, toStatus } = transitionSchema.parse(body);
return this.mutate(req, id, version, async (tx, merchant) => {
requireSales(req.user);
const index = successfulStages.findIndex((stage) => stage === merchant.status);
if (
!merchant.ownerId ||
index < 0 ||
successfulStages[index + 1] !== toStatus ||
merchant.status === 'COMPLIANCE_REVIEW'
)
throw new ApiError('WORKFLOW_INVALID', 409);
if (toStatus === 'COMPLIANCE_REVIEW') {
const submittedAt = new Date();
if (
!receivedHistory(merchant, submittedAt) ||
merchant.reviews.some((r) => r.decision === 'PENDING')
)
throw new ApiError('WORKFLOW_INVALID', 409);
await tx.complianceReview.create({
data: {
merchantId: id,
cycle: (merchant.reviews[0]?.cycle ?? 0) + 1,
submittedById: req.user.id,
submittedAt,
snapshot: reviewSnapshot(merchant),
},
});
}
if (['TESTING', 'LIVE'].includes(toStatus) && !validApproval(merchant))
throw new ApiError('WORKFLOW_INVALID', 409);
await this.stage(tx, req, merchant, toStatus);
});
}
@Patch(':id/checklist/:itemId') checklist(
@Req() req: AuthRequest,
@Param('id') id: string,
@Param('itemId') itemId: string,
@Body() body: unknown,
) {
const { version, state, note } = checklistEditSchema.parse(body);
return this.mutate(req, id, version, async (tx, merchant) => {
const item = merchant.checklist.find((item) => item.id === itemId);
if (!item) throw new ApiError('NOT_FOUND', 404);
requireSales(req.user);
if (!capabilities(req.user, merchant).collectChecklist)
throw new ApiError('REVIEW_LOCKED', 409);
await tx.kybChecklistItem.updateMany({
where: { id: itemId, merchantId: id },
data: { state, note },
});
await tx.checklistChange.create({
data: { itemId, actorId: req.user.id, fromState: item.state, toState: state, note },
});
await this.audit(tx, req, id, `Checklist updated: ${item.documentCode}`, {
itemId,
fromState: item.state,
toState: state,
});
});
}
@Post(':id/reviews/:reviewId/decision') decide(
@Req() req: AuthRequest,
@Param('id') id: string,
@Param('reviewId') reviewId: string,
@Body() body: unknown,
) {
const { version, decision, reason, corrections } = reviewDecisionSchema.parse(body);
return this.mutate(req, id, version, async (tx, merchant) => {
const review = merchant.reviews.find((review) => review.id === reviewId);
if (!review) throw new ApiError('NOT_FOUND', 404);
if (req.user.role !== 'COMPLIANCE_OFFICER') throw new ApiError('FORBIDDEN', 403);
if (merchant.status !== 'COMPLIANCE_REVIEW' || review.decision !== 'PENDING')
throw new ApiError('WORKFLOW_INVALID', 409);
if (!snapshotsEqual(review.snapshot, reviewSnapshot(merchant)))
throw new ApiError('CONFLICT', 409);
if (decision === 'APPROVED' && !receivedHistory(merchant, review.submittedAt))
throw new ApiError('WORKFLOW_INVALID', 409);
for (const correction of corrections) {
const item = merchant.checklist.find((item) => item.id === correction.itemId);
if (!item) throw new ApiError('NOT_FOUND', 404);
await tx.kybChecklistItem.updateMany({
where: { id: item.id, merchantId: id },
data: { state: 'NEEDS_CORRECTION', note: correction.note },
});
await tx.checklistChange.create({
data: {
itemId: item.id,
actorId: req.user.id,
fromState: item.state,
toState: 'NEEDS_CORRECTION',
note: correction.note,
},
});
}
await tx.complianceReview.updateMany({
where: { id: reviewId, merchantId: id, decision: 'PENDING' },
data: { decision, reason: reason || null, reviewerId: req.user.id, decidedAt: new Date() },
});
await this.stage(
tx,
req,
merchant,
decision === 'APPROVED' ? 'INTEGRATION' : decision === 'CORRECTIONS' ? 'KYB' : 'REJECTED',
reason || undefined,
);
await this.audit(tx, req, id, `Compliance review: ${decision}`, {
reviewId,
decision,
reason,
});
});
}
@Post(':id/activities') createActivity(
@Req() req: AuthRequest,
@Param('id') id: string,
@Body() body: unknown,
) {
return this.saveActivity(req, id, undefined, body);
}
@Patch(':id/activities/:activityId') editActivity(
@Req() req: AuthRequest,
@Param('id') id: string,
@Param('activityId') activityId: string,
@Body() body: unknown,
) {
return this.saveActivity(req, id, activityId, body);
}
private saveActivity(
req: AuthRequest,
id: string,
activityId: string | undefined,
body: unknown,
) {
const { version, kind, text } = activityInputSchema.parse(body);
return this.mutate(req, id, version, async (tx, merchant) => {
const allowed: readonly string[] = capabilities(req.user, merchant).activityKinds;
if (!allowed.includes(kind)) throw new ApiError('FORBIDDEN', 403);
if (activityId) {
const activity = await tx.activity.findFirst({
where: { id: activityId, merchantId: id, merchant: merchantScope(req.user) },
});
if (!activity) throw new ApiError('NOT_FOUND', 404);
if (!allowed.includes(activity.kind)) throw new ApiError('FORBIDDEN', 403);
await tx.activity.updateMany({
where: { id: activityId, merchantId: id },
data: { kind, text },
});
await this.audit(tx, req, id, 'Activity edited', {
activityId,
previousText: activity.text,
previousKind: activity.kind,
});
} else {
await tx.activity.create({ data: { merchantId: id, actorId: req.user.id, kind, text } });
}
});
}
@Post(':id/tasks') createTask(
@Req() req: AuthRequest,
@Param('id') id: string,
@Body() body: unknown,
) {
return this.saveTask(req, id, undefined, body);
}
@Patch(':id/tasks/:taskId') editTask(
@Req() req: AuthRequest,
@Param('id') id: string,
@Param('taskId') taskId: string,
@Body() body: unknown,
) {
return this.saveTask(req, id, taskId, body);
}
private saveTask(req: AuthRequest, id: string, taskId: string | undefined, body: unknown) {
const { version, title, dueAt, remindAt, status } = taskInputSchema.parse(body);
return this.mutate(req, id, version, async (tx, merchant) => {
const kind = req.user.role === 'COMPLIANCE_OFFICER' ? 'COMPLIANCE' : 'COMMERCIAL';
const existing = taskId
? await tx.task.findFirst({
where: { AND: [taskScope(req.user), { id: taskId, merchantId: id }] },
})
: null;
if (taskId && !existing) throw new ApiError('NOT_FOUND', 404);
if (existing && existing.kind !== kind) throw new ApiError('FORBIDDEN', 403);
const completion =
status === 'DONE'
? {
completedAt: existing?.status === 'DONE' ? existing.completedAt : new Date(),
completedById: existing?.status === 'DONE' ? existing.completedById : req.user.id,
}
: { completedAt: null, completedById: null };
const data = {
title,
dueAt: new Date(dueAt),
remindAt: remindAt ? new Date(remindAt) : null,
status,
...completion,
};
if (existing)
await tx.task.updateMany({
where: { AND: [taskScope(req.user), { id: existing.id, merchantId: id }] },
data,
});
else
await tx.task.create({
data: {
...data,
kind,
creatorId: req.user.id,
merchantId: id,
assigneeId: kind === 'COMPLIANCE' ? req.user.id : (merchant.ownerId ?? req.user.id),
},
});
await this.audit(tx, req, id, existing ? 'Task updated' : 'Task created', {
taskId: taskId ?? null,
title,
status,
});
});
}
}
+799 -16
View File
@@ -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);
});
+1 -3
View File
@@ -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__' });
});
@@ -0,0 +1,753 @@
import { useId, useState } from 'react';
import { useForm } from 'react-hook-form';
import { useMutation, useQuery } from '@tanstack/react-query';
import { Link } from 'react-router';
import { useTranslation } from 'react-i18next';
import { z } from 'zod';
import {
activityInputSchema,
assignmentSchema,
checklistEditSchema,
industries,
managerListSchema,
merchantEditSchema,
mutationResultSchema,
reviewDecisionSchema,
sources,
statuses,
taskInputSchema,
type MerchantDetail,
type Task,
} from '@merchantflow/contracts';
import {
Sheet,
SheetContent,
SheetTitle,
SheetDescription,
} from '@merchantflow/ui/components/sheet';
import { Input } from '@merchantflow/ui/components/input';
import { NativeSelect } from '@merchantflow/ui/components/native-select';
import { FormField } from '@merchantflow/ui/components/form-field';
import { api, ApiError, queryClient } from '../lib/api';
import { useFormat } from '../lib/format';
import { Button, SectionHeader, TaskRow } from './shared';
type Field = {
name: string;
label?: string;
type?: string;
options?: { value: string; label: string }[];
disabled?: boolean;
};
type EditorProps = {
title: string;
description?: string;
fields: Field[];
initial: Record<string, string>;
schema: z.ZodType;
build: (values: Record<string, string>) => unknown;
submit: (body: unknown) => void;
close: () => void;
pending: boolean;
};
function Editor({
title,
description,
fields,
initial,
schema,
build,
submit,
close,
pending,
}: EditorProps) {
const { t } = useTranslation();
const id = useId();
const form = useForm<Record<string, string>>({ defaultValues: initial });
const [errors, setErrors] = useState<Record<string, string>>({});
return (
<Sheet
open
onOpenChange={(open) => {
if (!open && !pending) close();
}}
>
<SheetContent
closeLabel={t('common.close')}
className="w-full! overflow-y-auto p-5 sm:max-w-xl! sm:p-8"
>
<SheetTitle className="pr-10 text-xl">{title}</SheetTitle>
<SheetDescription>{description ?? t('merchants.details')}</SheetDescription>
<form
noValidate
className="space-y-5"
onSubmit={form.handleSubmit((values) => {
const result = schema.safeParse(build(values));
if (!result.success) {
const messages: Record<string, string> = {};
for (const issue of result.error.issues)
messages[String(issue.path[0] ?? 'form')] = t('validation.invalid');
setErrors(messages);
return;
}
setErrors({});
submit(result.data);
})}
>
<fieldset disabled={pending} className="space-y-5">
{fields.map((field) => {
const fieldId = `${id}-${field.name}`;
const props = {
id: fieldId,
...form.register(field.name),
disabled: field.disabled,
'aria-invalid': !!errors[field.name],
'aria-describedby': errors[field.name] ? `${fieldId}-error` : undefined,
};
return (
<FormField
key={field.name}
id={fieldId}
label={field.label ?? t(`workflow.${field.name}`)}
error={errors[field.name]}
>
{field.options ? (
<NativeSelect {...props}>
{field.options.map((option) => (
<option key={option.value} value={option.value}>
{option.label}
</option>
))}
</NativeSelect>
) : field.type === 'textarea' ? (
<textarea
{...props}
rows={4}
className="min-h-28 w-full resize-y rounded-lg border bg-background px-3 py-2 text-sm"
/>
) : (
<Input {...props} type={field.type ?? 'text'} />
)}
</FormField>
);
})}
{Object.keys(errors).some((key) => !fields.some((field) => field.name === key)) && (
<p role="alert" className="text-sm text-destructive">
{t('errors.VALIDATION_ERROR')}
</p>
)}
<div className="flex flex-wrap gap-3 border-t pt-5">
<Button type="submit">{t(pending ? 'workflow.saving' : 'workflow.save')}</Button>
<Button type="button" variant="outline" onClick={close}>
{t('workflow.cancel')}
</Button>
</div>
</fieldset>
</form>
</SheetContent>
</Sheet>
);
}
function useAction(merchant: MerchantDetail, close?: () => void) {
const { t } = useTranslation();
const mutation = useMutation({
mutationFn: ({
path,
body,
method = 'PATCH',
}: {
path: string;
body: unknown;
method?: string;
}) =>
api(`/merchants/${merchant.id}${path}`, mutationResultSchema, {
method,
body: JSON.stringify(body),
}),
onSuccess: async () => {
close?.();
await queryClient.invalidateQueries({
predicate: (query) => query.queryKey[0] !== 'session',
});
},
onError: async () => {
close?.();
await queryClient.invalidateQueries({ queryKey: ['merchant', merchant.id] });
},
});
return {
...mutation,
feedback: mutation.isError ? (
<p role="alert" className="rounded-lg bg-rose-50 p-3 text-sm text-destructive">
{t(`errors.${mutation.error instanceof ApiError ? mutation.error.code : 'INTERNAL_ERROR'}`)}
</p>
) : mutation.isSuccess ? (
<p role="status" className="text-xs text-muted-foreground">
{t('workflow.saved')}
</p>
) : null,
};
}
const identityFields = [
'name',
'legalName',
'registrationNumber',
'address',
'website',
'country',
'industry',
];
const commercialFields = [
'contactName',
'contactEmail',
'contactPhone',
'contactTitle',
'estimatedMonthlyVolumeUsd',
'source',
];
export function MerchantControls({ merchant: m }: { merchant: MerchantDetail }) {
const { t } = useTranslation();
const [mode, setMode] = useState<'edit' | 'assign' | null>(null);
const action = useAction(m, () => setMode(null));
const managers = useQuery({
queryKey: ['assignable-managers'],
queryFn: ({ signal }) => api('/users/assignable-managers', managerListSchema, { signal }),
enabled: m.capabilities.assign,
});
const fields: Field[] = [...identityFields, ...commercialFields].map((name) => ({
name,
disabled: identityFields.includes(name) && !m.capabilities.editIdentity,
type: name === 'contactEmail' ? 'email' : name === 'website' ? 'url' : 'text',
options:
name === 'industry'
? industries.map((value) => ({ value, label: t(`industry.${value}`) }))
: name === 'source'
? [
{ value: '', label: '—' },
...sources.map((value) => ({ value, label: t(`workflow.${value}`) })),
]
: undefined,
}));
const initial = Object.fromEntries(
fields.map(({ name }) => [name, String(m[name as keyof MerchantDetail] ?? '')]),
);
return (
<div className="mb-6 space-y-3">
<div className="flex flex-wrap gap-2">
{m.capabilities.editCommercial && (
<Button
variant="outline"
onClick={() => {
action.reset();
setMode('edit');
}}
>
{t('workflow.editMerchant')}
</Button>
)}
{m.capabilities.assign && (
<Button
variant="outline"
disabled={!managers.data}
onClick={() => {
action.reset();
setMode('assign');
}}
>
{t('workflow.assign')}
</Button>
)}
{m.capabilities.nextStage && (
<Button
disabled={action.isPending}
onClick={() =>
action.mutate({
path: '/transitions',
method: 'POST',
body: { version: m.version, toStatus: m.capabilities.nextStage },
})
}
>
{t('workflow.advance', { stage: t(`statuses.${m.capabilities.nextStage}`) })}
</Button>
)}
</div>
{managers.isError && (
<p role="alert" className="text-sm text-destructive">
{t('errors.NETWORK')}{' '}
<Button variant="ghost" onClick={() => void managers.refetch()}>
{t('common.retry')}
</Button>
</p>
)}
{action.feedback}
{mode === 'edit' && (
<Editor
title={t('workflow.editMerchant')}
description={!m.capabilities.editIdentity ? t('workflow.identityLocked') : undefined}
fields={fields}
initial={initial}
schema={merchantEditSchema}
build={(values) => ({
version: m.version,
...Object.fromEntries(
Object.entries(values)
.filter(
([key, value]) =>
value !== initial[key] &&
(!identityFields.includes(key) || m.capabilities.editIdentity),
)
.map(([key, value]) => [
key,
['registrationNumber', 'address', 'contactPhone', 'contactTitle'].includes(key) &&
!value
? null
: value,
]),
),
})}
submit={(body) => action.mutate({ path: '', body })}
close={() => setMode(null)}
pending={action.isPending}
/>
)}
{mode === 'assign' && (
<Editor
title={t('workflow.assign')}
description={t('workflow.taskOwnership')}
fields={[
{
name: 'ownerId',
options: (managers.data ?? []).map((user) => ({ value: user.id, label: user.name })),
},
]}
initial={{ ownerId: m.owner?.id ?? managers.data?.[0]?.id ?? '' }}
schema={assignmentSchema}
build={(values) => ({ ...values, version: m.version })}
submit={(body) => action.mutate({ path: '/assignment', body })}
close={() => setMode(null)}
pending={action.isPending}
/>
)}
</div>
);
}
export function ChecklistControl({
merchant: m,
item,
}: {
merchant: MerchantDetail;
item: MerchantDetail['checklist'][number];
}) {
const { t } = useTranslation();
const f = useFormat();
const [open, setOpen] = useState(false);
const action = useAction(m, () => setOpen(false));
return (
<div className="mt-3 space-y-2">
{m.capabilities.collectChecklist && (
<Button
variant="outline"
onClick={() => {
action.reset();
setOpen(true);
}}
>
{t('workflow.checklistEdit')}
</Button>
)}
{action.feedback}
<details className="text-xs text-muted-foreground">
<summary className="min-h-11 cursor-pointer py-3">{t('workflow.checklistHistory')}</summary>
<ol className="space-y-3 border-l pl-3">
{item.changes.map((change) => (
<li key={change.id}>
<span>
{t(`checklist.${change.toState}`)} · {change.actor.name} ·{' '}
{f.date(change.occurredAt)}
</span>
{change.note && <p className="mt-1 whitespace-pre-wrap">{change.note}</p>}
</li>
))}
</ol>
</details>
{open && (
<Editor
title={t('workflow.checklistEdit')}
description={t(`documents.${item.documentCode}`)}
fields={[
{
name: 'state',
options: ['MISSING', 'RECEIVED'].map((value) => ({
value,
label: t(`checklist.${value}`),
})),
},
{ name: 'note', type: 'textarea' },
]}
initial={{
state: item.state === 'RECEIVED' ? 'RECEIVED' : 'MISSING',
note: item.note ?? '',
}}
schema={checklistEditSchema}
build={(values) => ({ ...values, note: values.note || null, version: m.version })}
submit={(body) => action.mutate({ path: `/checklist/${item.id}`, body })}
close={() => setOpen(false)}
pending={action.isPending}
/>
)}
</div>
);
}
export function ReviewHistory({ merchant: m }: { merchant: MerchantDetail }) {
const { t } = useTranslation();
const f = useFormat();
const [open, setOpen] = useState(false);
const action = useAction(m, () => setOpen(false));
const pending = m.reviews.find((review) => review.decision === 'PENDING');
return (
<section className="surface">
<SectionHeader
title={t('workflow.reviews')}
action={
m.capabilities.review &&
pending && (
<Button
onClick={() => {
action.reset();
setOpen(true);
}}
>
{t('workflow.decide')}
</Button>
)
}
/>
<div className="space-y-4 p-5 sm:p-6">
{action.feedback}
{!m.reviews.length && (
<p className="text-sm text-muted-foreground">{t('review.emptyText')}</p>
)}
{m.reviews.map((review) => (
<article key={review.id} className="rounded-lg border p-4">
<p className="text-sm font-semibold">
{t('workflow.cycle', { cycle: review.cycle })} · {t(`workflow.${review.decision}`)}
</p>
<p className="mt-2 text-xs text-muted-foreground">
{t('workflow.submitted', {
name: review.submittedBy.name,
date: f.date(review.submittedAt),
})}
</p>
{review.reviewer && review.decidedAt && (
<p className="mt-1 text-xs text-muted-foreground">
{t('workflow.reviewed', {
name: review.reviewer.name,
date: f.date(review.decidedAt),
})}
</p>
)}
{review.reason && (
<p className="mt-3 whitespace-pre-wrap text-sm leading-relaxed">{review.reason}</p>
)}
</article>
))}
</div>
{open && pending && (
<Editor
title={t('workflow.decide')}
description={t('workflow.correctionHint')}
fields={[
{
name: 'decision',
options: ['APPROVED', 'CORRECTIONS', 'REJECTED'].map((value) => ({
value,
label: t(`workflow.${value}`),
})),
},
{ name: 'reason', type: 'textarea' },
...m.checklist.map((item) => ({
name: `correction_${item.id}`,
label: t(`documents.${item.documentCode}`),
type: 'textarea',
})),
]}
initial={{ decision: 'APPROVED', reason: '' }}
schema={reviewDecisionSchema}
build={(values) => ({
version: m.version,
decision: values.decision,
reason: values.reason,
corrections:
values.decision === 'CORRECTIONS'
? m.checklist
.filter((item) => values[`correction_${item.id}`]?.trim())
.map((item) => ({ itemId: item.id, note: values[`correction_${item.id}`] }))
: [],
})}
submit={(body) =>
action.mutate({ path: `/reviews/${pending.id}/decision`, method: 'POST', body })
}
close={() => setOpen(false)}
pending={action.isPending}
/>
)}
</section>
);
}
function useActivityText() {
const { t } = useTranslation();
return (activity: MerchantDetail['activities'][number]) => {
if (activity.kind !== 'AUDIT') return activity.text;
const labels: Record<string, string> = {
'Merchant details updated': 'detailsUpdated',
'Manager assignment updated': 'assignmentUpdated',
'Activity edited': 'activityEdited',
'Task updated': 'taskUpdated',
'Task created': 'taskCreated',
};
if (labels[activity.text]) return t(`workflow.${labels[activity.text]}`);
const stages = activity.text.split(' → ');
if (stages.length === 2 && stages.every((stage) => statuses.some((code) => code === stage)))
return stages.map((stage) => t(`statuses.${stage}`)).join(' → ');
if (activity.text.startsWith('Checklist updated: '))
return t('workflow.checklistUpdated', {
document: t(`documents.${activity.text.slice(19)}`),
});
if (activity.text.startsWith('Compliance review: '))
return t('workflow.reviewDecided', { decision: t(`workflow.${activity.text.slice(19)}`) });
return activity.text;
};
}
export function InteractionHistory({ merchant: m }: { merchant: MerchantDetail }) {
const { t } = useTranslation();
const f = useFormat();
const [edit, setEdit] = useState<string | null>(null);
const action = useAction(m, () => setEdit(null));
const existing = m.activities.find((activity) => activity.id === edit);
const describe = useActivityText();
const audit = m.activities.filter((activity) => activity.kind === 'AUDIT');
return (
<section className="surface">
<SectionHeader
title={t('workflow.activities')}
action={
<Button
variant="outline"
onClick={() => {
action.reset();
setEdit('new');
}}
>
{t('workflow.addActivity')}
</Button>
}
/>
<div className="space-y-4 p-5 sm:p-6">
{action.feedback}
{m.activities
.filter((activity) => activity.kind !== 'AUDIT')
.map((activity) => (
<article key={activity.id} className="rounded-lg bg-background p-4">
<p className="mb-2 text-xs text-muted-foreground">
{t(`workflow.${activity.kind}`)} · {activity.actor.name} ·{' '}
{f.date(activity.occurredAt)}
</p>
<p className="whitespace-pre-wrap break-words text-sm leading-relaxed">
{activity.text}
</p>
{m.capabilities.activityKinds.some((kind) => kind === activity.kind) && (
<Button
className="mt-2"
variant="ghost"
onClick={() => {
action.reset();
setEdit(activity.id);
}}
>
{t('workflow.editActivity')}
</Button>
)}
</article>
))}
{!!audit.length && (
<details className="border-t pt-2">
<summary className="min-h-11 cursor-pointer py-3 text-sm font-medium">
{t('workflow.auditHistory', { count: audit.length })}
</summary>
<ol className="divide-y">
{audit.map((activity) => (
<li key={activity.id} className="py-3">
<p className="text-sm">{describe(activity)}</p>
<p className="mt-1 text-xs text-muted-foreground">
{activity.actor.name} · {f.date(activity.occurredAt)}
</p>
</li>
))}
</ol>
</details>
)}
</div>
{edit && (
<Editor
title={t(existing ? 'workflow.editActivity' : 'workflow.addActivity')}
fields={[
{
name: 'kind',
options: m.capabilities.activityKinds.map((value) => ({
value,
label: t(`workflow.${value}`),
})),
},
{ name: 'text', type: 'textarea' },
]}
initial={{
kind: existing?.kind ?? m.capabilities.activityKinds[0]!,
text: existing?.text ?? '',
}}
schema={activityInputSchema}
build={(values) => ({ ...values, version: m.version })}
submit={(body) =>
action.mutate({
path: `/activities${existing ? `/${existing.id}` : ''}`,
method: existing ? 'PATCH' : 'POST',
body,
})
}
close={() => setEdit(null)}
pending={action.isPending}
/>
)}
</section>
);
}
const localDate = (value: string) => {
const date = new Date(value);
return new Date(date.getTime() - date.getTimezoneOffset() * 60000).toISOString().slice(0, 16);
};
const isoDate = (value: string) => {
const date = new Date(value);
return Number.isFinite(date.getTime()) ? date.toISOString() : '';
};
export function MerchantTasks({ merchant: m }: { merchant: MerchantDetail }) {
const { t } = useTranslation();
const [edit, setEdit] = useState<string | null>(null);
const action = useAction(m, () => setEdit(null));
const existing = m.tasks.find((task) => task.id === edit);
const complete = (task: Task) =>
action.mutate({
path: `/tasks/${task.id}`,
body: {
version: m.version,
title: task.title,
dueAt: task.dueAt,
remindAt: task.remindAt,
status: 'DONE',
},
});
return (
<section className="surface" id="tasks">
<SectionHeader
title={t('merchants.tasks')}
description={t('workflow.taskOwnership')}
action={
<Button
variant="outline"
onClick={() => {
action.reset();
setEdit('new');
}}
>
{t('workflow.addTask')}
</Button>
}
/>
<div className="p-5">{action.feedback}</div>
{m.tasks.map((task) => (
<div key={task.id} className="border-t">
<TaskRow task={task} />
{task.kind === m.capabilities.manageTaskKind && (
<div className="flex flex-wrap gap-2 px-5 pb-4">
<Button
variant="outline"
onClick={() => {
action.reset();
setEdit(task.id);
}}
>
{t('workflow.editTask')}
</Button>
{task.status === 'OPEN' && (
<Button variant="ghost" disabled={action.isPending} onClick={() => complete(task)}>
{t('workflow.complete')}
</Button>
)}
</div>
)}
</div>
))}
{edit && (
<Editor
title={t(existing ? 'workflow.editTask' : 'workflow.addTask')}
fields={[
{ name: 'title' },
{ name: 'dueAt', type: 'datetime-local' },
{ name: 'remindAt', type: 'datetime-local' },
{
name: 'status',
options: ['OPEN', 'DONE'].map((value) => ({ value, label: t(`tasks.${value}`) })),
},
]}
initial={{
title: existing?.title ?? '',
dueAt: localDate(existing?.dueAt ?? new Date(Date.now() + 86400000).toISOString()),
remindAt: existing?.remindAt ? localDate(existing.remindAt) : '',
status: existing?.status ?? 'OPEN',
}}
schema={taskInputSchema}
build={(values) => ({
...values,
version: m.version,
dueAt: isoDate(values.dueAt!),
remindAt: values.remindAt ? isoDate(values.remindAt) : null,
})}
submit={(body) =>
action.mutate({
path: `/tasks${existing ? `/${existing.id}` : ''}`,
method: existing ? 'PATCH' : 'POST',
body,
})
}
close={() => setEdit(null)}
pending={action.isPending}
/>
)}
</section>
);
}
export function RecentInteractions({ activities }: { activities: MerchantDetail['activities'] }) {
const { t } = useTranslation();
const f = useFormat();
const describe = useActivityText();
return (
<div className="divide-y px-5 sm:px-6">
{activities.map((activity) => (
<article key={activity.id} className="py-4">
<Link
className="text-sm font-semibold hover:underline"
to={`/app/merchants/${activity.merchant.id}`}
>
{activity.merchant.name}
</Link>
<p className="mt-1 text-xs text-muted-foreground">
{t(`workflow.${activity.kind}`)} · {activity.actor.name} ·{' '}
{f.relative(activity.occurredAt)}
</p>
<p className="mt-2 whitespace-pre-wrap break-words text-sm leading-relaxed">
{describe(activity)}
</p>
</article>
))}
</div>
);
}
+1 -1
View File
@@ -234,7 +234,7 @@ export function MerchantCard({ merchant }: { merchant: Merchant }) {
/>
</div>
<div className="mt-5 flex items-center justify-between gap-2 text-xs text-muted-foreground">
<span>{merchant.owner.name.split(' ')[0]}</span>
<span>{merchant.owner?.name.split(' ')[0] ?? t('workflow.unassigned')}</span>
<span className="flex items-center gap-1">
<Clock3 className="size-3" aria-hidden="true" />
{f.relative(merchant.stageEnteredAt)}
+3 -3
View File
@@ -40,9 +40,9 @@ export async function api<T>(
}
if (!response.ok) {
const body = await response.json().catch(() => ({}));
if (response.status === 401 && !path.startsWith('/auth/')) {
await queryClient.cancelQueries();
queryClient.clear();
if (response.status === 401 && path !== '/auth/login') {
await queryClient.cancelQueries({ predicate: (query) => query.queryKey[0] !== 'session' });
queryClient.removeQueries({ predicate: (query) => query.queryKey[0] !== 'session' });
queryClient.setQueryData(['session'], null);
}
throw new ApiError(
+8
View File
@@ -10,6 +10,14 @@ export function useFormat() {
shortDate: (value: string | Date) =>
new Intl.DateTimeFormat(locale, { day: 'numeric', month: 'short' }).format(new Date(value)),
number: (value: number) => new Intl.NumberFormat(locale).format(value),
usd: (value: string | null) =>
value === null
? '—'
: new Intl.NumberFormat(locale, {
style: 'currency',
currency: 'USD',
maximumFractionDigits: 2,
}).format(Number(value)),
country: (code: string) => new Intl.DisplayNames([locale], { type: 'region' }).of(code),
relative: (value: string) => {
const hours = Math.round((new Date(value).getTime() - Date.now()) / 3600000);
+12 -2
View File
@@ -1,4 +1,6 @@
import { workflowEn, workflowRu } from './workflow-locales';
export const en = {
workflow: workflowEn,
common: {
workspace: 'Workspace',
team: 'Merchant workspace',
@@ -115,6 +117,10 @@ export const en = {
invalid: 'Please check this value.',
},
errors: {
CONFLICT: 'This record changed. Review the latest information and try again.',
WORKFLOW_INVALID:
'This action requires a valid stage, complete documents and approval where applicable.',
REVIEW_LOCKED: 'This information is locked during or after review.',
UNAUTHORIZED: 'Sign in to continue.',
INVALID_CREDENTIALS: 'The email or password is incorrect.',
FORBIDDEN: 'You do not have access to this view.',
@@ -152,7 +158,7 @@ export const en = {
emptyActivity: 'No activity to show yet',
scopeHead: 'Your entire merchant portfolio',
scopeManager: 'Your assigned merchants',
scopeCompliance: 'Merchants in KYB and Compliance Review',
scopeCompliance: 'Merchant context across the portfolio · personal compliance tasks',
},
merchants: {
title: 'Merchants',
@@ -233,6 +239,7 @@ export const en = {
},
};
export const ru = {
workflow: workflowRu,
common: {
workspace: 'Рабочее пространство',
team: 'Работа с мерчантами',
@@ -351,6 +358,9 @@ export const ru = {
invalid: 'Проверьте это значение.',
},
errors: {
CONFLICT: 'Запись изменилась. Проверьте актуальные данные и повторите действие.',
WORKFLOW_INVALID: 'Проверьте этап, готовность документов и наличие одобрения.',
REVIEW_LOCKED: 'Эти данные защищены от изменений во время и после проверки.',
UNAUTHORIZED: 'Войдите, чтобы продолжить.',
INVALID_CREDENTIALS: 'Неверная почта или пароль.',
FORBIDDEN: 'У вас нет доступа к этому разделу.',
@@ -388,7 +398,7 @@ export const ru = {
emptyActivity: 'Событий пока нет',
scopeHead: 'Весь портфель мерчантов',
scopeManager: 'Закреплённые за вами мерчанты',
scopeCompliance: 'Мерчанты на KYB и комплаенс-проверке',
scopeCompliance: 'Контекст всех мерчантов · личные комплаенс-задачи',
},
merchants: {
title: 'Мерчанты',
+42 -18
View File
@@ -1,3 +1,11 @@
import {
MerchantControls,
ChecklistControl,
ReviewHistory,
InteractionHistory,
MerchantTasks,
RecentInteractions,
} from '../components/merchant-workflow';
import { useEffect, useState } from 'react';
import { Link, useOutletContext, useParams, useSearchParams } from 'react-router';
import { keepPreviousData, useQuery } from '@tanstack/react-query';
@@ -174,7 +182,7 @@ export function Dashboard() {
title={t('dashboard.activity')}
description={t('dashboard.activityText')}
/>
<ActivityFeed events={data.recentEvents} />
<RecentInteractions activities={data.recentActivities} />
</section>
<section className="surface self-start">
<SectionHeader
@@ -255,7 +263,9 @@ function MerchantTable({ merchants }: { merchants: Merchant[] }) {
<TableCell className="text-xs text-muted-foreground">
{f.country(m.country)}
</TableCell>
<TableCell className="text-xs">{m.owner.name}</TableCell>
<TableCell className="text-xs">
{m.owner?.name ?? t('workflow.unassigned')}
</TableCell>
<TableCell className="pr-6 text-right text-xs text-muted-foreground">
{f.shortDate(m.createdAt)}
</TableCell>
@@ -279,7 +289,9 @@ function MerchantTable({ merchants }: { merchants: Merchant[] }) {
</div>
<div className="mt-4 flex flex-wrap items-center justify-between gap-2">
<StatusBadge status={m.status} />
<span className="text-xs text-muted-foreground">{m.owner.name}</span>
<span className="text-xs text-muted-foreground">
{m.owner?.name ?? t('workflow.unassigned')}
</span>
</div>
</Link>
))}
@@ -459,6 +471,7 @@ export function MerchantDetail() {
</p>
</div>
</div>
<MerchantControls merchant={m} />
<div className="grid gap-6 xl:grid-cols-[1.15fr_1fr]">
<div className="min-w-0 space-y-6">
<section className="surface">
@@ -468,8 +481,28 @@ export function MerchantDetail() {
/>
<dl className="grid grid-cols-1 gap-5 p-5 sm:grid-cols-2 sm:p-6">
{[
{ label: t('common.owner'), value: m.owner.name },
{
label: t('common.owner'),
value: m.owner?.name ?? t('workflow.unassigned'),
},
{ label: t('merchants.contact'), value: m.contactName },
...(
[
'legalName',
'registrationNumber',
'address',
'contactPhone',
'contactTitle',
] as const
).map((key) => ({ label: t(`workflow.${key}`), value: m[key] ?? '—' })),
{
label: t('workflow.estimatedMonthlyVolumeUsd'),
value: f.usd(m.estimatedMonthlyVolumeUsd),
},
{
label: t('workflow.source'),
value: m.source ? t(`workflow.${m.source}`) : '—',
},
{
label: t('merchants.website'),
value: (
@@ -505,6 +538,7 @@ export function MerchantDetail() {
))}
</dl>
</section>
<ReviewHistory merchant={m} />
<section id="checklist" className="surface">
<SectionHeader
title={t('merchants.checklist')}
@@ -541,6 +575,7 @@ export function MerchantDetail() {
{t(`checklist.${doc.state}`)}
</Badge>
</div>
<ChecklistControl merchant={m} item={doc} />
{doc.note && (
<p className="mt-2 text-xs leading-relaxed text-muted-foreground">
{doc.note}
@@ -580,19 +615,8 @@ export function MerchantDetail() {
/>
<ActivityFeed events={m.events} detail />
</section>
<section className="surface">
<SectionHeader
title={t('merchants.tasks')}
description={t('merchants.tasksText')}
/>
<div className="mt-4">
{m.tasks.length ? (
m.tasks.map((task) => <TaskRow key={task.id} task={task} />)
) : (
<EmptyState title={t('merchants.noTasks')} />
)}
</div>
</section>
<MerchantTasks merchant={m} />
<InteractionHistory merchant={m} />
</div>
</div>
</>
@@ -787,7 +811,7 @@ export function ReviewQueue() {
{m.name}
</Link>
<p className="mt-1 text-xs text-muted-foreground">
{m.owner.name} · {t(`industry.${m.industry}`)}
{m.owner?.name ?? t('workflow.unassigned')} · {t(`industry.${m.industry}`)}
</p>
</div>
</div>
+2 -2
View File
@@ -147,8 +147,8 @@ export function Login() {
const demos = [
{ email: 'head', role: 'HEAD_OF_SALES' },
{ email: 'compliance', role: 'COMPLIANCE_OFFICER' },
{ email: 'manager1', role: 'ACCOUNT_MANAGER', name: 'Alex' },
{ email: 'manager2', role: 'ACCOUNT_MANAGER', name: 'Maria' },
{ email: 'alex', role: 'ACCOUNT_MANAGER', name: 'Alex' },
{ email: 'sam', role: 'ACCOUNT_MANAGER', name: 'Sam' },
];
return (
<div className="grid min-h-dvh bg-white lg:grid-cols-2">
+157
View File
@@ -0,0 +1,157 @@
export const workflowEn = {
auditHistory: 'Audit history ({{count}})',
detailsUpdated: 'Merchant details updated',
assignmentUpdated: 'Manager assignment updated',
activityEdited: 'Interaction edited',
taskUpdated: 'Task updated',
taskCreated: 'Task created',
checklistUpdated: 'Checklist updated: {{document}}',
reviewDecided: 'Compliance review: {{decision}}',
unassigned: 'Unassigned',
edit: 'Edit',
save: 'Save changes',
saving: 'Saving…',
cancel: 'Cancel',
saved: 'Changes saved.',
editMerchant: 'Edit merchant',
assign: 'Assign manager',
ownerId: 'Account manager',
advance: 'Move to {{stage}}',
identityLocked:
'Reviewed company and KYB information is locked. Contact and commercial details can still be updated.',
checklistEdit: 'Update document',
checklistHistory: 'Document history',
state: 'Document status',
note: 'Note',
reviews: 'Compliance reviews',
decide: 'Record decision',
decision: 'Decision',
reason: 'Decision reason',
correctionHint:
'For a correction request, describe the change needed for each affected document.',
APPROVED: 'Approved',
PENDING: 'Pending',
REJECTED: 'Rejected',
CORRECTIONS: 'Corrections requested',
cycle: 'Review {{cycle}}',
submitted: 'Submitted by {{name}} on {{date}}',
reviewed: 'Reviewed by {{name}} on {{date}}',
activities: 'Interactions and audit trail',
addActivity: 'Log interaction',
editActivity: 'Edit interaction',
kind: 'Interaction type',
text: 'Details',
NOTE: 'Note',
CALL: 'Call',
EMAIL: 'Email',
MEETING: 'Meeting',
KYB_NOTE: 'KYB note',
AUDIT: 'System history',
addTask: 'Add task',
editTask: 'Edit task',
complete: 'Complete task',
title: 'Task title',
dueAt: 'Due date and time',
remindAt: 'Reminder date and time',
status: 'Task status',
taskOwnership: 'Commercial tasks follow the assigned manager. Compliance tasks are personal.',
COMMERCIAL: 'Commercial',
COMPLIANCE: 'Compliance',
name: 'Company name',
legalName: 'Legal company name',
registrationNumber: 'Registration number',
address: 'Company address',
website: 'Website',
country: 'Country code',
industry: 'Industry',
contactName: 'Primary contact',
contactEmail: 'Contact email',
contactPhone: 'Contact phone',
contactTitle: 'Contact title',
estimatedMonthlyVolumeUsd: 'Estimated monthly processing (USD)',
source: 'Lead source',
INBOUND: 'Inbound enquiry',
OUTBOUND: 'Outbound outreach',
REFERRAL: 'Referral',
PARTNER: 'Partner',
EVENT: 'Event',
};
export const workflowRu: Record<keyof typeof workflowEn, string> = {
auditHistory: 'Журнал действий ({{count}})',
detailsUpdated: 'Данные мерчанта обновлены',
assignmentUpdated: 'Назначение менеджера изменено',
activityEdited: 'Взаимодействие изменено',
taskUpdated: 'Задача обновлена',
taskCreated: 'Задача создана',
checklistUpdated: 'Документ обновлён: {{document}}',
reviewDecided: 'Комплаенс-проверка: {{decision}}',
unassigned: 'Не назначен',
edit: 'Изменить',
save: 'Сохранить изменения',
saving: 'Сохраняем…',
cancel: 'Отмена',
saved: 'Изменения сохранены.',
editMerchant: 'Изменить мерчанта',
assign: 'Назначить менеджера',
ownerId: 'Аккаунт-менеджер',
advance: 'Перевести: {{stage}}',
identityLocked:
'Проверенные данные компании и KYB защищены от изменений. Контактные и коммерческие данные можно обновлять.',
checklistEdit: 'Обновить документ',
checklistHistory: 'История документа',
state: 'Статус документа',
note: 'Заметка',
reviews: 'Комплаенс-проверки',
decide: 'Записать решение',
decision: 'Решение',
reason: 'Основание решения',
correctionHint:
'Для запроса исправлений укажите необходимые изменения для каждого затронутого документа.',
APPROVED: 'Одобрено',
PENDING: 'Ожидает решения',
REJECTED: 'Отклонено',
CORRECTIONS: 'Запрошены исправления',
cycle: 'Проверка {{cycle}}',
submitted: 'Отправлено: {{name}}, {{date}}',
reviewed: 'Проверено: {{name}}, {{date}}',
activities: 'Взаимодействия и журнал действий',
addActivity: 'Добавить взаимодействие',
editActivity: 'Изменить взаимодействие',
kind: 'Тип взаимодействия',
text: 'Подробности',
NOTE: 'Заметка',
CALL: 'Звонок',
EMAIL: 'Письмо',
MEETING: 'Встреча',
KYB_NOTE: 'Заметка KYB',
AUDIT: 'Системная история',
addTask: 'Добавить задачу',
editTask: 'Изменить задачу',
complete: 'Выполнить задачу',
title: 'Название задачи',
dueAt: 'Дата и время выполнения',
remindAt: 'Дата и время напоминания',
status: 'Статус задачи',
taskOwnership:
'Коммерческие задачи закреплены за менеджером мерчанта. Комплаенс-задачи — личные.',
COMMERCIAL: 'Коммерческая',
COMPLIANCE: 'Комплаенс',
name: 'Название компании',
legalName: 'Юридическое название',
registrationNumber: 'Регистрационный номер',
address: 'Адрес компании',
website: 'Сайт',
country: 'Код страны',
industry: 'Отрасль',
contactName: 'Основной контакт',
contactEmail: 'Email контакта',
contactPhone: 'Телефон контакта',
contactTitle: 'Должность контакта',
estimatedMonthlyVolumeUsd: 'Месячный объём обработки (USD)',
source: 'Источник лида',
INBOUND: 'Входящий запрос',
OUTBOUND: 'Исходящий контакт',
REFERRAL: 'Рекомендация',
PARTNER: 'Партнёр',
EVENT: 'Мероприятие',
};