Implemented the database, authentication, access rules, and seed data
This commit is contained in:
+41
-1
@@ -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
@@ -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
@@ -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
@@ -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,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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,
|
||||
});
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -19,6 +19,7 @@ async function request(path, cookie, options = {}) {
|
||||
...options,
|
||||
headers: {
|
||||
...(cookie ? { cookie } : {}),
|
||||
origin: process.env.APP_ORIGIN ?? 'http://localhost:5173',
|
||||
...(options.body ? { 'content-type': 'application/json' } : {}),
|
||||
...options.headers,
|
||||
},
|
||||
@@ -36,7 +37,7 @@ before(async () => {
|
||||
app = await createApp();
|
||||
await app.listen(0, '127.0.0.1');
|
||||
base = (await app.getUrl()) + '/api';
|
||||
for (const account of ['head', 'compliance', 'manager1', 'manager2']) {
|
||||
for (const account of ['head', 'compliance', 'alex', 'sam']) {
|
||||
const r = await login(account);
|
||||
assert.equal(r.status, 201);
|
||||
cookies[account] = r.response.headers.get('set-cookie').split(';')[0];
|
||||
@@ -88,17 +89,17 @@ test('login validates, sets protected cookies, and rejects incorrect credentials
|
||||
);
|
||||
});
|
||||
for (const [account, total] of [
|
||||
['head', 18],
|
||||
['manager1', 9],
|
||||
['manager2', 9],
|
||||
['compliance', 4],
|
||||
['head', 45],
|
||||
['alex', 20],
|
||||
['sam', 20],
|
||||
['compliance', 45],
|
||||
])
|
||||
test(`${account}: all reads, details, history, tasks and metrics respect the scope`, async () => {
|
||||
const cookie = cookies[account];
|
||||
const expected = (await db.merchant.findMany()).filter((m) =>
|
||||
account === 'head' || account === 'compliance'
|
||||
? account === 'head' || ['KYB', 'COMPLIANCE_REVIEW'].includes(m.status)
|
||||
: m.ownerId === `user-${account}`,
|
||||
? true
|
||||
: m.ownerId === (account === 'alex' ? 'user-manager1' : 'user-manager2'),
|
||||
);
|
||||
assert.equal(expected.length, total);
|
||||
const ids = expected.map((m) => m.id);
|
||||
@@ -117,7 +118,17 @@ for (const [account, total] of [
|
||||
const pipeline = (await request('/pipeline', cookie)).body;
|
||||
assert.deepEqual(pipeline.map((m) => m.id).sort(), [...ids].sort());
|
||||
const tasks = (await request('/tasks', cookie)).body;
|
||||
assert.equal(tasks.length, total * 2);
|
||||
assert.equal(
|
||||
tasks.length,
|
||||
await db.task.count({
|
||||
where: {
|
||||
merchantId: { in: ids },
|
||||
...(account === 'compliance'
|
||||
? { kind: 'COMPLIANCE', assigneeId: 'user-compliance' }
|
||||
: {}),
|
||||
},
|
||||
}),
|
||||
);
|
||||
assert.ok(tasks.every((t) => ids.includes(t.merchant.id)));
|
||||
for (const m of expected) {
|
||||
const detail = (await request(`/merchants/${m.id}`, cookie)).body;
|
||||
@@ -136,7 +147,14 @@ for (const [account, total] of [
|
||||
assert.equal(
|
||||
dashboard.overdueTasks,
|
||||
await db.task.count({
|
||||
where: { merchantId: { in: ids }, status: 'OPEN', dueAt: { lt: new Date() } },
|
||||
where: {
|
||||
merchantId: { in: ids },
|
||||
...(account === 'compliance'
|
||||
? { kind: 'COMPLIANCE', assigneeId: 'user-compliance' }
|
||||
: {}),
|
||||
status: 'OPEN',
|
||||
dueAt: { lt: new Date() },
|
||||
},
|
||||
}),
|
||||
);
|
||||
assert.equal(
|
||||
@@ -174,13 +192,13 @@ test('filters are validated and review queue is oldest first', async () => {
|
||||
assert.equal((await request(`/merchants?${query}`, cookie)).status, 400);
|
||||
assert.equal((await request('/tasks?filter=invalid', cookie)).status, 400);
|
||||
const live = (await request('/merchants?status=LIVE', cookie)).body;
|
||||
assert.equal(live.total, 2);
|
||||
assert.equal(live.total, 5);
|
||||
const done = (await request('/tasks?filter=DONE', cookie)).body;
|
||||
assert.ok(done.every((t) => t.status === 'DONE'));
|
||||
const overdue = (await request('/tasks?filter=OVERDUE', cookie)).body;
|
||||
assert.ok(overdue.every((t) => t.status === 'OPEN' && new Date(t.dueAt) < new Date()));
|
||||
const queue = (await request('/review-queue', cookies.compliance)).body;
|
||||
assert.equal(queue.length, 2);
|
||||
assert.equal(queue.length, 6);
|
||||
assert.ok(queue.every((m) => m.status === 'COMPLIANCE_REVIEW'));
|
||||
assert.ok(new Date(queue[0].stageEnteredAt) <= new Date(queue[1].stageEnteredAt));
|
||||
});
|
||||
@@ -195,7 +213,7 @@ test('seed is repeatable without modifying records; history includes correction
|
||||
});
|
||||
assert.equal(result.status, 0, result.stderr);
|
||||
assert.equal(await db.user.count(), 4);
|
||||
assert.equal(await db.merchant.count(), 18);
|
||||
assert.equal(await db.merchant.count(), 45);
|
||||
assert.deepEqual(
|
||||
await db.merchant.findMany({
|
||||
orderBy: { id: 'asc' },
|
||||
@@ -211,7 +229,7 @@ test('seed is repeatable without modifying records; history includes correction
|
||||
assert.ok(!snapshot.some((m) => m.events.some((e) => e.fromStatus === 'LIVE')));
|
||||
});
|
||||
test('expired, logged-out and replaced sessions cannot be reused', async () => {
|
||||
const r = await login('manager1');
|
||||
const r = await login('alex');
|
||||
const cookie = r.response.headers.get('set-cookie').split(';')[0];
|
||||
const token = cookie.split('=')[1];
|
||||
await db.session.update({
|
||||
@@ -219,14 +237,779 @@ test('expired, logged-out and replaced sessions cannot be reused', async () => {
|
||||
data: { expiresAt: new Date(0) },
|
||||
});
|
||||
assert.equal((await request('/auth/me', cookie)).status, 401);
|
||||
const fresh = await login('manager1');
|
||||
const fresh = await login('alex');
|
||||
const freshCookie = fresh.response.headers.get('set-cookie').split(';')[0];
|
||||
assert.equal((await request('/auth/logout', freshCookie, { method: 'POST' })).status, 201);
|
||||
assert.equal((await request('/pipeline', freshCookie)).status, 401);
|
||||
const replacement = await request('/auth/login', cookies.manager2, {
|
||||
const replacement = await request('/auth/login', cookies.sam, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ email: '[email protected]', password: 'MerchantFlow123!' }),
|
||||
});
|
||||
assert.equal(replacement.status, 201);
|
||||
assert.equal((await request('/auth/me', cookies.manager2)).status, 401);
|
||||
assert.equal((await request('/auth/me', cookies.sam)).status, 401);
|
||||
});
|
||||
|
||||
async function freshCookie(account) {
|
||||
const response = await login(account);
|
||||
assert.equal(response.status, 201);
|
||||
return response.response.headers.get('set-cookie').split(';')[0];
|
||||
}
|
||||
async function mutate(path, cookie, data, method = 'PATCH') {
|
||||
return request(path, cookie, { method, body: JSON.stringify(data) });
|
||||
}
|
||||
async function fixture(id, status = 'NEW_LEAD', ownerId = 'user-manager1') {
|
||||
return db.merchant.create({
|
||||
data: {
|
||||
id,
|
||||
name: 'Workflow Test',
|
||||
legalName: 'Workflow Test Ltd',
|
||||
website: 'https://workflow.example',
|
||||
industry: 'SOFTWARE',
|
||||
country: 'GB',
|
||||
contactName: 'Test Contact',
|
||||
contactEmail: '[email protected]',
|
||||
ownerId,
|
||||
status,
|
||||
checklist: { create: documentCodes.map((documentCode) => ({ documentCode })) },
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
test('manager lookup and both directions of direct record/child/mutation attacks are scoped', async () => {
|
||||
const head = await freshCookie('head');
|
||||
const comp = await freshCookie('compliance');
|
||||
const alex = await freshCookie('alex');
|
||||
const sam = await freshCookie('sam');
|
||||
const managers = await request('/users/assignable-managers', head);
|
||||
assert.deepEqual(managers.body.map((u) => u.email).sort(), [
|
||||
'[email protected]',
|
||||
'[email protected]',
|
||||
]);
|
||||
for (const cookie of [alex, sam, comp])
|
||||
assert.equal((await request('/users/assignable-managers', cookie)).status, 403);
|
||||
assert.equal((await request('/users/assignable-managers')).status, 401);
|
||||
for (const [cookie, hiddenId, ownId] of [
|
||||
[alex, 'merchant-02', 'merchant-01'],
|
||||
[sam, 'merchant-01', 'merchant-02'],
|
||||
]) {
|
||||
const hidden = await db.merchant.findUniqueOrThrow({
|
||||
where: { id: hiddenId },
|
||||
include: { tasks: true, activities: true, checklist: true },
|
||||
});
|
||||
const taskBody = {
|
||||
version: hidden.version,
|
||||
title: 'Forbidden',
|
||||
dueAt: new Date().toISOString(),
|
||||
remindAt: null,
|
||||
status: 'OPEN',
|
||||
};
|
||||
for (const [suffix, body, method] of [
|
||||
['', { version: hidden.version, contactName: 'Forbidden' }, 'PATCH'],
|
||||
['/assignment', { version: hidden.version, ownerId: 'user-manager1' }, 'PATCH'],
|
||||
['/transitions', { version: hidden.version, toStatus: 'CONTACTED' }, 'POST'],
|
||||
[
|
||||
`/checklist/${hidden.checklist[0].id}`,
|
||||
{ version: hidden.version, state: 'RECEIVED', note: null },
|
||||
'PATCH',
|
||||
],
|
||||
['/reviews/unknown/decision', { version: hidden.version, decision: 'APPROVED' }, 'POST'],
|
||||
['/activities', { version: hidden.version, kind: 'NOTE', text: 'Forbidden' }, 'POST'],
|
||||
[
|
||||
`/activities/${hidden.activities[0].id}`,
|
||||
{ version: hidden.version, kind: 'NOTE', text: 'Forbidden' },
|
||||
'PATCH',
|
||||
],
|
||||
['/tasks', taskBody, 'POST'],
|
||||
[`/tasks/${hidden.tasks[0].id}`, taskBody, 'PATCH'],
|
||||
])
|
||||
assert.equal(
|
||||
(await mutate(`/merchants/${hiddenId}${suffix}`, cookie, body, method)).status,
|
||||
404,
|
||||
suffix,
|
||||
);
|
||||
const own = (await request(`/merchants/${ownId}`, cookie)).body;
|
||||
assert.equal(
|
||||
(
|
||||
await mutate(`/merchants/${ownId}/tasks/${hidden.tasks[0].id}`, cookie, {
|
||||
...taskBody,
|
||||
version: own.version,
|
||||
})
|
||||
).status,
|
||||
404,
|
||||
);
|
||||
assert.equal(
|
||||
(
|
||||
await mutate(`/merchants/${ownId}/activities/${hidden.activities[0].id}`, cookie, {
|
||||
version: own.version,
|
||||
kind: 'NOTE',
|
||||
text: 'Forbidden',
|
||||
})
|
||||
).status,
|
||||
404,
|
||||
);
|
||||
assert.equal(
|
||||
(
|
||||
await mutate(`/merchants/${ownId}/assignment`, cookie, {
|
||||
version: own.version,
|
||||
ownerId: 'user-manager2',
|
||||
})
|
||||
).status,
|
||||
403,
|
||||
);
|
||||
assert.equal(
|
||||
(
|
||||
await mutate(`/merchants/${ownId}`, cookie, {
|
||||
version: own.version,
|
||||
ownerId: 'user-manager2',
|
||||
})
|
||||
).status,
|
||||
400,
|
||||
);
|
||||
assert.equal((await request(`/merchants/${hiddenId}`, cookie)).status, 404);
|
||||
assert.equal(
|
||||
(await request(`/merchants?search=${encodeURIComponent(hidden.name)}`, cookie)).body.total,
|
||||
0,
|
||||
);
|
||||
}
|
||||
const visible = (await request('/merchants/merchant-15', comp)).body;
|
||||
assert.equal(visible.status, 'LIVE');
|
||||
for (const [suffix, body, method] of [
|
||||
['', { version: visible.version, source: 'PARTNER' }, 'PATCH'],
|
||||
['/assignment', { version: visible.version, ownerId: 'user-manager2' }, 'PATCH'],
|
||||
['/transitions', { version: visible.version, toStatus: 'LIVE' }, 'POST'],
|
||||
['/activities', { version: visible.version, kind: 'CALL', text: 'forbidden' }, 'POST'],
|
||||
])
|
||||
assert.equal(
|
||||
(await mutate(`/merchants/${visible.id}${suffix}`, comp, body, method)).status,
|
||||
403,
|
||||
);
|
||||
});
|
||||
|
||||
test('origin checks cover every mutation and no registration endpoint exists', async () => {
|
||||
const cookie = await freshCookie('head');
|
||||
const merchant = (await request('/merchants/merchant-01', cookie)).body;
|
||||
for (const origin of ['', 'null', 'https://untrusted.example']) {
|
||||
for (const [path, method, body] of [
|
||||
['/auth/login', 'POST', { email: '[email protected]', password: 'MerchantFlow123!' }],
|
||||
['/auth/logout', 'POST', undefined],
|
||||
['/merchants/merchant-01', 'PATCH', { version: merchant.version, contactName: 'Bad origin' }],
|
||||
['/merchants/merchant-01/tasks', 'POST', { version: merchant.version }],
|
||||
])
|
||||
assert.equal(
|
||||
(
|
||||
await request(path, cookie, {
|
||||
method,
|
||||
headers: { origin },
|
||||
...(body ? { body: JSON.stringify(body) } : {}),
|
||||
})
|
||||
).status,
|
||||
403,
|
||||
);
|
||||
}
|
||||
assert.equal(
|
||||
(
|
||||
await request('/auth/logout', cookie, {
|
||||
method: 'POST',
|
||||
headers: { 'sec-fetch-site': 'cross-site' },
|
||||
})
|
||||
).status,
|
||||
403,
|
||||
);
|
||||
assert.equal((await request('/auth/register', null, { method: 'POST', body: '{}' })).status, 404);
|
||||
assert.equal(
|
||||
(
|
||||
await mutate('/merchants/merchant-01', null, {
|
||||
version: merchant.version,
|
||||
contactName: 'Anonymous',
|
||||
})
|
||||
).status,
|
||||
401,
|
||||
);
|
||||
});
|
||||
|
||||
test('corrections, resubmission, approval and activation preserve one merchant and immutable evidence', async () => {
|
||||
const id = 'workflow-cycle';
|
||||
await fixture(id);
|
||||
const sales = await freshCookie('alex');
|
||||
const head = await freshCookie('head');
|
||||
const comp = await freshCookie('compliance');
|
||||
const detail = async () => (await request(`/merchants/${id}`, sales)).body;
|
||||
const move = async (toStatus, cookie = sales) =>
|
||||
mutate(
|
||||
`/merchants/${id}/transitions`,
|
||||
cookie,
|
||||
{ version: (await detail()).version, toStatus },
|
||||
'POST',
|
||||
);
|
||||
try {
|
||||
assert.equal((await move('LIVE')).status, 409);
|
||||
for (const stage of ['CONTACTED', 'QUALIFIED', 'KYB'])
|
||||
assert.equal((await move(stage)).status, 201);
|
||||
assert.equal((await move('COMPLIANCE_REVIEW')).status, 409);
|
||||
let m = await detail();
|
||||
for (const item of m.checklist) {
|
||||
assert.equal(
|
||||
(
|
||||
await mutate(`/merchants/${id}/checklist/${item.id}`, sales, {
|
||||
version: (await detail()).version,
|
||||
state: 'RECEIVED',
|
||||
note: null,
|
||||
})
|
||||
).status,
|
||||
200,
|
||||
);
|
||||
}
|
||||
assert.equal((await move('COMPLIANCE_REVIEW')).status, 201);
|
||||
m = await detail();
|
||||
const first = m.reviews[0];
|
||||
assert.equal(
|
||||
(
|
||||
await mutate(`/merchants/${id}`, head, {
|
||||
version: m.version,
|
||||
legalName: 'Changed during review',
|
||||
})
|
||||
).status,
|
||||
409,
|
||||
);
|
||||
assert.equal(
|
||||
(
|
||||
await mutate(`/merchants/${id}/checklist/${m.checklist[0].id}`, sales, {
|
||||
version: m.version,
|
||||
state: 'MISSING',
|
||||
note: null,
|
||||
})
|
||||
).status,
|
||||
409,
|
||||
);
|
||||
for (const cookie of [sales, head])
|
||||
assert.equal(
|
||||
(
|
||||
await mutate(
|
||||
`/merchants/${id}/reviews/${first.id}/decision`,
|
||||
cookie,
|
||||
{ version: m.version, decision: 'APPROVED' },
|
||||
'POST',
|
||||
)
|
||||
).status,
|
||||
403,
|
||||
);
|
||||
assert.equal(
|
||||
(
|
||||
await mutate(
|
||||
`/merchants/${id}/reviews/${first.id}/decision`,
|
||||
comp,
|
||||
{ version: m.version, decision: 'REJECTED', reason: ' ' },
|
||||
'POST',
|
||||
)
|
||||
).status,
|
||||
400,
|
||||
);
|
||||
assert.equal(
|
||||
(
|
||||
await mutate(
|
||||
`/merchants/${id}/reviews/${first.id}/decision`,
|
||||
comp,
|
||||
{
|
||||
version: m.version,
|
||||
decision: 'CORRECTIONS',
|
||||
reason: 'Updated signature required',
|
||||
corrections: [{ itemId: m.checklist[0].id, note: 'Please sign the latest version' }],
|
||||
},
|
||||
'POST',
|
||||
)
|
||||
).status,
|
||||
201,
|
||||
);
|
||||
m = await detail();
|
||||
assert.equal(m.status, 'KYB');
|
||||
assert.equal(m.checklist[0].state, 'NEEDS_CORRECTION');
|
||||
assert.equal((await move('COMPLIANCE_REVIEW')).status, 409);
|
||||
assert.equal(
|
||||
(
|
||||
await mutate(`/merchants/${id}/checklist/${m.checklist[0].id}`, sales, {
|
||||
version: m.version,
|
||||
state: 'RECEIVED',
|
||||
note: 'Signed version received',
|
||||
})
|
||||
).status,
|
||||
200,
|
||||
);
|
||||
assert.equal((await move('COMPLIANCE_REVIEW')).status, 201);
|
||||
m = await detail();
|
||||
assert.equal(m.reviews.length, 2);
|
||||
assert.equal(
|
||||
(
|
||||
await mutate(
|
||||
`/merchants/${id}/reviews/${m.reviews[0].id}/decision`,
|
||||
comp,
|
||||
{ version: m.version, decision: 'APPROVED', reason: 'All checks passed' },
|
||||
'POST',
|
||||
)
|
||||
).status,
|
||||
201,
|
||||
);
|
||||
m = await detail();
|
||||
assert.equal(m.status, 'INTEGRATION');
|
||||
const reviewSnapshot = await db.complianceReview.findUnique({ where: { id: m.reviews[0].id } });
|
||||
assert.equal(
|
||||
(
|
||||
await mutate(`/merchants/${id}`, head, {
|
||||
version: m.version,
|
||||
website: 'https://changed.example',
|
||||
})
|
||||
).status,
|
||||
409,
|
||||
);
|
||||
assert.equal(
|
||||
(
|
||||
await mutate(`/merchants/${id}`, sales, {
|
||||
version: m.version,
|
||||
contactPhone: '+44 20 7946 0000',
|
||||
estimatedMonthlyVolumeUsd: '125000.25',
|
||||
})
|
||||
).status,
|
||||
200,
|
||||
);
|
||||
assert.equal((await move('TESTING', comp)).status, 403);
|
||||
assert.equal((await move('TESTING')).status, 201);
|
||||
assert.equal((await move('LIVE', head)).status, 201);
|
||||
assert.equal((await move('REJECTED')).status, 409);
|
||||
m = await detail();
|
||||
assert.equal(m.id, id);
|
||||
assert.equal(m.status, 'LIVE');
|
||||
assert.equal(m.estimatedMonthlyVolumeUsd, '125000.25');
|
||||
assert.equal(
|
||||
(
|
||||
await mutate(
|
||||
`/merchants/${id}/reviews/${first.id}/decision`,
|
||||
comp,
|
||||
{ version: m.version, decision: 'APPROVED' },
|
||||
'POST',
|
||||
)
|
||||
).status,
|
||||
409,
|
||||
);
|
||||
assert.deepEqual(
|
||||
await db.complianceReview.findUnique({ where: { id: m.reviews[0].id } }),
|
||||
reviewSnapshot,
|
||||
);
|
||||
assert.equal(m.events.length, 9);
|
||||
assert.ok(m.activities.some((a) => a.kind === 'AUDIT'));
|
||||
} finally {
|
||||
await db.merchant.delete({ where: { id } });
|
||||
}
|
||||
});
|
||||
|
||||
test('missing approval prevents activation; rejection is terminal; concurrent decisions commit once', async () => {
|
||||
const sales = await freshCookie('alex');
|
||||
const comp = await freshCookie('compliance');
|
||||
await fixture('workflow-evidence', 'TESTING');
|
||||
await fixture('workflow-reject', 'KYB');
|
||||
try {
|
||||
assert.equal(
|
||||
(
|
||||
await mutate(
|
||||
'/merchants/workflow-evidence/transitions',
|
||||
sales,
|
||||
{ version: 0, toStatus: 'LIVE' },
|
||||
'POST',
|
||||
)
|
||||
).status,
|
||||
409,
|
||||
);
|
||||
const get = async () => (await request('/merchants/workflow-reject', sales)).body;
|
||||
for (const item of (await get()).checklist)
|
||||
await mutate(`/merchants/workflow-reject/checklist/${item.id}`, sales, {
|
||||
version: (await get()).version,
|
||||
state: 'RECEIVED',
|
||||
note: null,
|
||||
});
|
||||
await mutate(
|
||||
'/merchants/workflow-reject/transitions',
|
||||
sales,
|
||||
{ version: (await get()).version, toStatus: 'COMPLIANCE_REVIEW' },
|
||||
'POST',
|
||||
);
|
||||
const m = await get();
|
||||
const decisions = await Promise.all(
|
||||
[
|
||||
'Rejected: contradictory ownership evidence',
|
||||
'Rejected: incomplete business registration',
|
||||
].map((reason) =>
|
||||
mutate(
|
||||
`/merchants/${m.id}/reviews/${m.reviews[0].id}/decision`,
|
||||
comp,
|
||||
{ version: m.version, decision: 'REJECTED', reason },
|
||||
'POST',
|
||||
),
|
||||
),
|
||||
);
|
||||
assert.deepEqual(decisions.map((r) => r.status).sort(), [201, 409]);
|
||||
assert.equal((await get()).status, 'REJECTED');
|
||||
assert.equal(
|
||||
await db.statusEvent.count({ where: { merchantId: m.id, toStatus: 'REJECTED' } }),
|
||||
1,
|
||||
);
|
||||
assert.equal(
|
||||
(
|
||||
await mutate(
|
||||
`/merchants/${m.id}/transitions`,
|
||||
sales,
|
||||
{ version: (await get()).version, toStatus: 'KYB' },
|
||||
'POST',
|
||||
)
|
||||
).status,
|
||||
409,
|
||||
);
|
||||
} finally {
|
||||
await db.merchant.deleteMany({
|
||||
where: { id: { in: ['workflow-evidence', 'workflow-reject'] } },
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
test('reassignment transfers open commercial tasks; concurrent writes and former-owner access fail', async () => {
|
||||
const id = 'workflow-handoff';
|
||||
await fixture(id);
|
||||
const head = await freshCookie('head');
|
||||
const alex = await freshCookie('alex');
|
||||
const sam = await freshCookie('sam');
|
||||
const comp = await freshCookie('compliance');
|
||||
const get = async (cookie = head) => (await request(`/merchants/${id}`, cookie)).body;
|
||||
const task = {
|
||||
title: 'Handoff task',
|
||||
dueAt: new Date(Date.now() + 86400000).toISOString(),
|
||||
remindAt: null,
|
||||
status: 'OPEN',
|
||||
};
|
||||
try {
|
||||
for (const [cookie, status] of [
|
||||
[alex, 'OPEN'],
|
||||
[alex, 'DONE'],
|
||||
[comp, 'OPEN'],
|
||||
])
|
||||
assert.equal(
|
||||
(
|
||||
await mutate(
|
||||
`/merchants/${id}/tasks`,
|
||||
cookie,
|
||||
{ ...task, status, version: (await get()).version },
|
||||
'POST',
|
||||
)
|
||||
).status,
|
||||
201,
|
||||
);
|
||||
const before = await get();
|
||||
assert.equal((await get(comp)).tasks.length, 1);
|
||||
const personal = before.tasks.find((t) => t.kind === 'COMPLIANCE');
|
||||
assert.equal(
|
||||
(
|
||||
await mutate(`/merchants/${id}/tasks/${personal.id}`, head, {
|
||||
...task,
|
||||
version: before.version,
|
||||
})
|
||||
).status,
|
||||
403,
|
||||
);
|
||||
const commercial = before.tasks.find((t) => t.kind === 'COMMERCIAL');
|
||||
assert.equal(
|
||||
(
|
||||
await mutate(`/merchants/${id}/tasks/${commercial.id}`, comp, {
|
||||
...task,
|
||||
version: before.version,
|
||||
})
|
||||
).status,
|
||||
404,
|
||||
);
|
||||
const results = await Promise.all([
|
||||
mutate(`/merchants/${id}/assignment`, head, {
|
||||
version: before.version,
|
||||
ownerId: 'user-manager2',
|
||||
}),
|
||||
mutate(`/merchants/${id}`, alex, {
|
||||
version: before.version,
|
||||
contactTitle: 'Concurrent update',
|
||||
}),
|
||||
]);
|
||||
assert.equal(results.filter((r) => r.status === 200).length, 1);
|
||||
if (results[0].status !== 200)
|
||||
assert.equal(
|
||||
(
|
||||
await mutate(`/merchants/${id}/assignment`, head, {
|
||||
version: (await get()).version,
|
||||
ownerId: 'user-manager2',
|
||||
})
|
||||
).status,
|
||||
200,
|
||||
);
|
||||
const after = await get(sam);
|
||||
assert.equal(after.owner.id, 'user-manager2');
|
||||
assert.ok(
|
||||
after.tasks
|
||||
.filter((t) => t.kind === 'COMMERCIAL' && t.status === 'OPEN')
|
||||
.every((t) => t.assignee.id === 'user-manager2'),
|
||||
);
|
||||
assert.ok(
|
||||
after.tasks
|
||||
.filter((t) => t.status === 'DONE')
|
||||
.every((t) => t.assignee.id === 'user-manager1'),
|
||||
);
|
||||
assert.equal(after.tasks.find((t) => t.kind === 'COMPLIANCE').assignee.id, 'user-compliance');
|
||||
assert.equal((await request(`/merchants/${id}`, alex)).status, 404);
|
||||
assert.equal(
|
||||
(
|
||||
await mutate(`/merchants/${id}`, alex, {
|
||||
version: after.version,
|
||||
contactName: 'Former owner',
|
||||
})
|
||||
).status,
|
||||
404,
|
||||
);
|
||||
assert.equal(
|
||||
(
|
||||
await mutate(`/merchants/${id}`, sam, {
|
||||
version: before.version,
|
||||
contactName: 'Stale update',
|
||||
})
|
||||
).status,
|
||||
409,
|
||||
);
|
||||
const audit = after.activities.find((a) => a.kind === 'AUDIT');
|
||||
assert.equal(
|
||||
(
|
||||
await mutate(`/merchants/${id}/activities/${audit.id}`, head, {
|
||||
version: after.version,
|
||||
kind: 'NOTE',
|
||||
text: 'Rewrite history',
|
||||
})
|
||||
).status,
|
||||
403,
|
||||
);
|
||||
} finally {
|
||||
await db.merchant.delete({ where: { id } });
|
||||
}
|
||||
});
|
||||
|
||||
test('seed histories, ownership balance, approval evidence, tasks and edited records survive reseeding', async () => {
|
||||
const { reviewSnapshot, snapshotsEqual, verifyPassword } = await import('@merchantflow/database');
|
||||
const merchants = await db.merchant.findMany({
|
||||
include: {
|
||||
checklist: { include: { changes: { orderBy: { occurredAt: 'asc' } } } },
|
||||
reviews: { orderBy: { cycle: 'desc' }, include: { reviewer: true } },
|
||||
events: { orderBy: { occurredAt: 'asc' } },
|
||||
},
|
||||
});
|
||||
assert.equal(merchants.filter((m) => !m.ownerId && m.status === 'NEW_LEAD').length, 5);
|
||||
for (const ownerId of ['user-manager1', 'user-manager2'])
|
||||
assert.equal(merchants.filter((m) => m.ownerId === ownerId).length, 20);
|
||||
const anchor = (await db.demoSeedState.findUniqueOrThrow({ where: { id: 'merchantflow-v2' } }))
|
||||
.anchorAt;
|
||||
assert.ok(merchants.some((m) => anchor.getTime() - m.createdAt.getTime() >= 90 * 86400000));
|
||||
for (const m of merchants) {
|
||||
assert.equal(m.events.at(-1).toStatus, m.status);
|
||||
assert.equal(m.events.at(-1).occurredAt.getTime(), m.stageEnteredAt.getTime());
|
||||
if (['INTEGRATION', 'TESTING', 'LIVE'].includes(m.status)) {
|
||||
const review = m.reviews[0];
|
||||
assert.equal(review.decision, 'APPROVED');
|
||||
assert.equal(review.reviewer.role, 'COMPLIANCE_OFFICER');
|
||||
assert.ok(review.decidedAt >= review.submittedAt);
|
||||
assert.ok(snapshotsEqual(review.snapshot, reviewSnapshot(m)));
|
||||
assert.ok(
|
||||
m.checklist.every(
|
||||
(item) =>
|
||||
item.changes.filter((change) => change.occurredAt <= review.submittedAt).at(-1)
|
||||
?.toState === 'RECEIVED',
|
||||
),
|
||||
);
|
||||
}
|
||||
if (m.status === 'REJECTED') assert.ok(m.reviews[0].reason.trim());
|
||||
}
|
||||
for (const user of await db.user.findMany()) {
|
||||
assert.notEqual(user.passwordHash, 'MerchantFlow123!');
|
||||
assert.ok(verifyPassword('MerchantFlow123!', user.passwordHash));
|
||||
}
|
||||
const merchant = await db.merchant.findUniqueOrThrow({ where: { id: 'merchant-01' } });
|
||||
const user = await db.user.findUniqueOrThrow({ where: { id: 'user-manager1' } });
|
||||
const task = await db.task.findFirstOrThrow({ where: { merchantId: merchant.id } });
|
||||
try {
|
||||
await db.merchant.update({
|
||||
where: { id: merchant.id },
|
||||
data: { name: 'Keep my edited merchant', estimatedMonthlyVolumeUsd: '777.77' },
|
||||
});
|
||||
await db.task.update({ where: { id: task.id }, data: { title: 'Keep my edited task' } });
|
||||
await db.user.update({
|
||||
where: { id: user.id },
|
||||
data: { passwordHash: 'intentionally-changed-by-test' },
|
||||
});
|
||||
const snapshot = await db.merchant.findUnique({
|
||||
where: { id: merchant.id },
|
||||
include: {
|
||||
tasks: true,
|
||||
activities: true,
|
||||
checklist: { include: { changes: true } },
|
||||
reviews: true,
|
||||
events: true,
|
||||
},
|
||||
});
|
||||
for (let i = 0; i < 2; i++)
|
||||
assert.equal(
|
||||
spawnSync('pnpm', ['--filter', '@merchantflow/database', 'seed'], {
|
||||
env: process.env,
|
||||
encoding: 'utf8',
|
||||
}).status,
|
||||
0,
|
||||
);
|
||||
assert.deepEqual(
|
||||
await db.merchant.findUnique({
|
||||
where: { id: merchant.id },
|
||||
include: {
|
||||
tasks: true,
|
||||
activities: true,
|
||||
checklist: { include: { changes: true } },
|
||||
reviews: true,
|
||||
events: true,
|
||||
},
|
||||
}),
|
||||
snapshot,
|
||||
);
|
||||
assert.equal(
|
||||
(await db.user.findUnique({ where: { id: user.id } })).passwordHash,
|
||||
'intentionally-changed-by-test',
|
||||
);
|
||||
assert.equal(await db.merchant.count(), 45);
|
||||
} finally {
|
||||
await db.merchant.update({
|
||||
where: { id: merchant.id },
|
||||
data: {
|
||||
name: merchant.name,
|
||||
estimatedMonthlyVolumeUsd: merchant.estimatedMonthlyVolumeUsd,
|
||||
updatedAt: merchant.updatedAt,
|
||||
},
|
||||
});
|
||||
await db.task.update({
|
||||
where: { id: task.id },
|
||||
data: { title: task.title, updatedAt: task.updatedAt },
|
||||
});
|
||||
await db.user.update({
|
||||
where: { id: user.id },
|
||||
data: { passwordHash: user.passwordHash, updatedAt: user.updatedAt },
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
test('login limits are enforced with Retry-After without revealing account existence', async () => {
|
||||
for (let i = 0; i < 20; i++)
|
||||
assert.equal((await login('nonexistent-rate-limit', 'wrong')).status, 401);
|
||||
const limited = await login('nonexistent-rate-limit', 'wrong');
|
||||
assert.equal(limited.status, 429);
|
||||
assert.ok(Number(limited.response.headers.get('retry-after')) > 0);
|
||||
});
|
||||
|
||||
test('legacy upgrade preserves edits and identities, enriches matching fixtures only, and repeats safely', async () => {
|
||||
// This test runs last and can only operate on the guarded disposable database.
|
||||
await db.merchant.deleteMany();
|
||||
await db.demoSeedState.deleteMany();
|
||||
await db.user.update({
|
||||
where: { id: 'user-manager1' },
|
||||
data: { email: '[email protected]' },
|
||||
});
|
||||
await db.user.update({
|
||||
where: { id: 'user-manager2' },
|
||||
data: { email: '[email protected]', name: 'Maria Chen' },
|
||||
});
|
||||
const hashes = (await db.user.findMany({ orderBy: { id: 'asc' } })).map(
|
||||
(user) => user.passwordHash,
|
||||
);
|
||||
const old = spawnSync('node', ['tests/fixtures/legacy-demo.mjs'], {
|
||||
env: process.env,
|
||||
encoding: 'utf8',
|
||||
});
|
||||
assert.equal(old.status, 0, old.stderr);
|
||||
await db.merchant.update({
|
||||
where: { id: 'merchant-02' },
|
||||
data: { name: 'Edited legacy company' },
|
||||
});
|
||||
await db.task.update({
|
||||
where: { id: 'merchant-03-task-1' },
|
||||
data: { title: 'Edited legacy task' },
|
||||
});
|
||||
const include = {
|
||||
checklist: { include: { changes: true } },
|
||||
activities: true,
|
||||
reviews: true,
|
||||
notes: true,
|
||||
tasks: true,
|
||||
events: true,
|
||||
};
|
||||
const edited = await db.merchant.findMany({
|
||||
where: { id: { in: ['merchant-02', 'merchant-03'] } },
|
||||
include,
|
||||
orderBy: { id: 'asc' },
|
||||
});
|
||||
const oldFields = {
|
||||
id: true,
|
||||
name: true,
|
||||
website: true,
|
||||
country: true,
|
||||
industry: true,
|
||||
contactName: true,
|
||||
contactEmail: true,
|
||||
ownerId: true,
|
||||
status: true,
|
||||
createdAt: true,
|
||||
stageEnteredAt: true,
|
||||
events: { orderBy: { id: 'asc' } },
|
||||
notes: { orderBy: { id: 'asc' } },
|
||||
};
|
||||
const before = await db.merchant.findMany({ select: oldFields, orderBy: { id: 'asc' } });
|
||||
const upgraded = spawnSync('pnpm', ['--filter', '@merchantflow/database', 'seed'], {
|
||||
env: process.env,
|
||||
encoding: 'utf8',
|
||||
});
|
||||
assert.equal(upgraded.status, 0, upgraded.stderr);
|
||||
assert.match(upgraded.stderr, /Preserved edited.*merchant-02/);
|
||||
assert.match(upgraded.stderr, /Preserved edited.*merchant-03/);
|
||||
assert.deepEqual(
|
||||
await db.merchant.findMany({
|
||||
where: { id: { in: before.map((m) => m.id) } },
|
||||
select: oldFields,
|
||||
orderBy: { id: 'asc' },
|
||||
}),
|
||||
before,
|
||||
);
|
||||
assert.deepEqual(
|
||||
await db.merchant.findMany({
|
||||
where: { id: { in: ['merchant-02', 'merchant-03'] } },
|
||||
include,
|
||||
orderBy: { id: 'asc' },
|
||||
}),
|
||||
edited,
|
||||
);
|
||||
assert.equal(await db.merchant.count(), 45);
|
||||
assert.equal(
|
||||
(await db.user.findUnique({ where: { id: 'user-manager1' } })).email,
|
||||
'[email protected]',
|
||||
);
|
||||
assert.equal(
|
||||
(await db.user.findUnique({ where: { id: 'user-manager2' } })).email,
|
||||
'[email protected]',
|
||||
);
|
||||
assert.deepEqual(
|
||||
(await db.user.findMany({ orderBy: { id: 'asc' } })).map((user) => user.passwordHash),
|
||||
hashes,
|
||||
);
|
||||
for (const m of await db.merchant.findMany({
|
||||
where: { status: { in: ['INTEGRATION', 'TESTING', 'LIVE'] } },
|
||||
include: { reviews: true },
|
||||
}))
|
||||
assert.ok(m.reviews.some((r) => r.decision === 'APPROVED'));
|
||||
const snapshot = await db.merchant.findMany({ include, orderBy: { id: 'asc' } });
|
||||
assert.equal(
|
||||
spawnSync('pnpm', ['--filter', '@merchantflow/database', 'seed'], {
|
||||
env: process.env,
|
||||
encoding: 'utf8',
|
||||
}).status,
|
||||
0,
|
||||
);
|
||||
assert.deepEqual(await db.merchant.findMany({ include, orderBy: { id: 'asc' } }), snapshot);
|
||||
});
|
||||
|
||||
@@ -14,8 +14,6 @@ test('every role receives its exact merchant scope', () => {
|
||||
assert.deepEqual(merchantScope({ role: 'ACCOUNT_MANAGER', id: 'manager-1' }), {
|
||||
ownerId: 'manager-1',
|
||||
});
|
||||
assert.deepEqual(merchantScope({ role: 'COMPLIANCE_OFFICER' }), {
|
||||
status: { in: ['KYB', 'COMPLIANCE_REVIEW'] },
|
||||
});
|
||||
assert.deepEqual(merchantScope({ role: 'COMPLIANCE_OFFICER' }), {});
|
||||
assert.deepEqual(merchantScope({ role: 'unexpected' }), { id: '__no_access__' });
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user