Implemented KYB, compliance decisions, integration, and testing
This commit is contained in:
+42
-4
@@ -1,7 +1,8 @@
|
||||
import type { User } from '@merchantflow/contracts';
|
||||
import type { Prisma } from '@merchantflow/database';
|
||||
import type { Capabilities } from '@merchantflow/contracts';
|
||||
import { workflowActions, type Evidence } from './workflow-policy.js';
|
||||
import { workflowActions, validApproval, canReopenKyb, type Evidence } from './workflow-policy.js';
|
||||
import { activationCodes, isIntegrationCheck, reviewPolicyVersion } from '@merchantflow/contracts';
|
||||
import { ApiError } from './shared.js';
|
||||
export function merchantScope(user: User): Prisma.MerchantWhereInput {
|
||||
switch (user.role) {
|
||||
@@ -29,16 +30,53 @@ export function capabilities(user: User, merchant: Evidence): Capabilities {
|
||||
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 locked =
|
||||
merchant.reviews.some((review) => review.decision === 'PENDING') ||
|
||||
(merchant.reviews[0]?.decision === 'APPROVED' &&
|
||||
(merchant.reviews[0].policyVersion >= reviewPolicyVersion || merchant.status !== 'KYB'));
|
||||
const actions = workflowActions(user, merchant);
|
||||
const terminal = ['LIVE', 'REJECTED'].includes(merchant.status);
|
||||
const reopen = canReopenKyb(merchant);
|
||||
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',
|
||||
reopenKyb: sales && reopen,
|
||||
activationCodes:
|
||||
sales && validApproval(merchant)
|
||||
? activationCodes.filter((code) =>
|
||||
isIntegrationCheck(code)
|
||||
? merchant.status === 'INTEGRATION'
|
||||
: merchant.status === 'TESTING',
|
||||
)
|
||||
: [],
|
||||
handoff: {
|
||||
owner: terminal
|
||||
? 'NONE'
|
||||
: merchant.status === 'COMPLIANCE_REVIEW'
|
||||
? 'COMPLIANCE_OFFICER'
|
||||
: !merchant.ownerId
|
||||
? 'HEAD_OF_SALES'
|
||||
: 'ACCOUNT_MANAGER',
|
||||
ownerId: terminal || merchant.status === 'COMPLIANCE_REVIEW' ? null : merchant.ownerId,
|
||||
action: terminal
|
||||
? 'COMPLETE'
|
||||
: merchant.status === 'COMPLIANCE_REVIEW'
|
||||
? 'REVIEW'
|
||||
: !merchant.ownerId
|
||||
? 'ASSIGN'
|
||||
: reopen
|
||||
? 'REOPEN_KYB'
|
||||
: merchant.status === 'KYB'
|
||||
? 'COLLECT'
|
||||
: merchant.status === 'INTEGRATION'
|
||||
? 'INTEGRATE'
|
||||
: merchant.status === 'TESTING'
|
||||
? 'TEST'
|
||||
: 'COMMERCIAL',
|
||||
},
|
||||
activityKinds:
|
||||
user.role === 'COMPLIANCE_OFFICER'
|
||||
? (['KYB_NOTE'] as const)
|
||||
|
||||
+67
-8
@@ -1,6 +1,11 @@
|
||||
import { Controller, Get, Inject, Param, Query, Req, UseGuards } from '@nestjs/common';
|
||||
import { PrismaClient, type Prisma } from '@merchantflow/database';
|
||||
import { statuses, merchantQuerySchema, taskQuerySchema } from '@merchantflow/contracts';
|
||||
import {
|
||||
statuses,
|
||||
merchantQuerySchema,
|
||||
taskQuerySchema,
|
||||
reviewQueueQuerySchema,
|
||||
} from '@merchantflow/contracts';
|
||||
import { SessionGuard } from './auth.js';
|
||||
import { DATABASE, ApiError, type AuthRequest } from './shared.js';
|
||||
import { capabilities, merchantScope, taskScope } from './access.js';
|
||||
@@ -185,6 +190,10 @@ export class CrmController {
|
||||
cycle: true,
|
||||
decision: true,
|
||||
reason: true,
|
||||
policyVersion: true,
|
||||
riskLevel: true,
|
||||
corrections: true,
|
||||
snapshot: true,
|
||||
submittedAt: true,
|
||||
decidedAt: true,
|
||||
submittedBy: { select: { name: true } },
|
||||
@@ -202,6 +211,7 @@ export class CrmController {
|
||||
const history = await merchantHistory(merchant, tx);
|
||||
return {
|
||||
...merchant,
|
||||
activationChecks: evidence.reviews.flatMap((review) => review.activationChecks),
|
||||
activities: merchant.activities.map(({ metadata: _metadata, ...activity }) => activity),
|
||||
capabilities: capabilities(req.user, evidence),
|
||||
history,
|
||||
@@ -244,13 +254,60 @@ export class CrmController {
|
||||
orderBy: [{ status: 'asc' }, { dueAt: 'asc' }],
|
||||
});
|
||||
}
|
||||
@Get('review-queue') reviewQueue(@Req() req: AuthRequest) {
|
||||
@Get('review-queue') async reviewQueue(@Req() req: AuthRequest, @Query() query: unknown) {
|
||||
if (req.user.role !== 'COMPLIANCE_OFFICER') throw new ApiError('FORBIDDEN', 403);
|
||||
return this.db.merchant.findMany({
|
||||
where: { AND: [merchantScope(req.user), { status: 'COMPLIANCE_REVIEW' }] },
|
||||
select: merchantSelect,
|
||||
orderBy: [{ stageEnteredAt: 'asc' }, { id: 'asc' }],
|
||||
});
|
||||
const { search, ownerId, waiting } = reviewQueueQuerySchema.parse(query);
|
||||
const base: Prisma.ComplianceReviewWhereInput = {
|
||||
decision: 'PENDING',
|
||||
merchant: { AND: [merchantScope(req.user), { status: 'COMPLIANCE_REVIEW' }] },
|
||||
};
|
||||
return this.db.$transaction(
|
||||
async (tx) => {
|
||||
const pendingCount = await tx.complianceReview.count({ where: base });
|
||||
const owners = await tx.user.findMany({
|
||||
where: { role: 'ACCOUNT_MANAGER' },
|
||||
select: { id: true, name: true },
|
||||
orderBy: { name: 'asc' },
|
||||
});
|
||||
const items = await tx.complianceReview.findMany({
|
||||
where: {
|
||||
AND: [
|
||||
base,
|
||||
{
|
||||
...(waiting !== 'ALL'
|
||||
? { submittedAt: { lte: new Date(Date.now() - Number(waiting) * 3600000) } }
|
||||
: {}),
|
||||
merchant: {
|
||||
...(ownerId ? { ownerId: ownerId === 'unassigned' ? null : ownerId } : {}),
|
||||
...(search
|
||||
? {
|
||||
OR: ['name', 'legalName', 'contactName', 'contactEmail', 'website'].map(
|
||||
(field) => ({ [field]: { contains: search, mode: 'insensitive' } }),
|
||||
),
|
||||
}
|
||||
: {}),
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
cycle: true,
|
||||
policyVersion: true,
|
||||
submittedAt: true,
|
||||
merchant: { select: merchantSelect },
|
||||
},
|
||||
orderBy: [{ submittedAt: 'asc' }, { id: 'asc' }],
|
||||
});
|
||||
return {
|
||||
items,
|
||||
pendingCount,
|
||||
filteredCount: items.length,
|
||||
owners,
|
||||
};
|
||||
},
|
||||
{ isolationLevel: 'RepeatableRead' },
|
||||
);
|
||||
}
|
||||
@Get('dashboard') async dashboard(@Req() req: AuthRequest) {
|
||||
const scope = merchantScope(req.user);
|
||||
@@ -271,7 +328,9 @@ export class CrmController {
|
||||
recentActivities,
|
||||
] = await this.db.$transaction([
|
||||
this.db.merchant.count({ where: scope }),
|
||||
this.db.merchant.count({ where: { AND: [scope, { status: 'COMPLIANCE_REVIEW' }] } }),
|
||||
this.db.complianceReview.count({
|
||||
where: { decision: 'PENDING', merchant: { AND: [scope, { status: 'COMPLIANCE_REVIEW' }] } },
|
||||
}),
|
||||
this.db.task.count({
|
||||
where: { ...taskScope(req.user), status: 'OPEN', dueAt: { lt: new Date() } },
|
||||
}),
|
||||
|
||||
@@ -4,7 +4,7 @@ import type { Request, Response } from 'express';
|
||||
import { z } from 'zod';
|
||||
import { PrismaClient } from '@merchantflow/database';
|
||||
import {
|
||||
documentCodes,
|
||||
requiredDocumentCodes,
|
||||
publicLeadKeySchema,
|
||||
publicLeadSchema,
|
||||
type PublicLead,
|
||||
@@ -127,7 +127,10 @@ export class PublicLeadService {
|
||||
createdAt: now,
|
||||
stageEnteredAt: now,
|
||||
checklist: {
|
||||
create: documentCodes.map((documentCode) => ({ documentCode, state: 'MISSING' })),
|
||||
create: requiredDocumentCodes.map((documentCode) => ({
|
||||
documentCode,
|
||||
state: 'MISSING',
|
||||
})),
|
||||
},
|
||||
events: { create: { fromStatus: null, toStatus: 'NEW_LEAD', occurredAt: now } },
|
||||
activities: {
|
||||
|
||||
@@ -8,6 +8,11 @@ import {
|
||||
countryCodes,
|
||||
industries,
|
||||
successfulStages,
|
||||
isRequiredDocument,
|
||||
requiredDocumentCodes,
|
||||
activationCodes,
|
||||
isIntegrationCheck,
|
||||
reviewPolicyVersion,
|
||||
type BlockingReason,
|
||||
type User,
|
||||
type WorkflowAction,
|
||||
@@ -18,7 +23,18 @@ export const evidenceInclude = {
|
||||
include: { changes: { orderBy: [{ occurredAt: 'asc' as const }, { id: 'asc' as const }] } },
|
||||
},
|
||||
reviews: {
|
||||
include: { reviewer: { select: { role: true } } },
|
||||
include: {
|
||||
reviewer: { select: { role: true } },
|
||||
activationChecks: {
|
||||
orderBy: { code: 'asc' as const },
|
||||
include: {
|
||||
changes: {
|
||||
include: { actor: { select: { name: true } } },
|
||||
orderBy: [{ occurredAt: 'asc' as const }, { id: 'asc' as const }],
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
orderBy: { cycle: 'desc' as const },
|
||||
},
|
||||
activities: { select: { kind: true } },
|
||||
@@ -28,16 +44,22 @@ export type Evidence = Prisma.MerchantGetPayload<{ include: typeof evidenceInclu
|
||||
export 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',
|
||||
)
|
||||
merchant.checklist
|
||||
.filter((item) => isRequiredDocument(item.documentCode))
|
||||
.every(
|
||||
(item) =>
|
||||
item.changes.filter((change) => change.occurredAt <= at).at(-1)?.toState === 'RECEIVED',
|
||||
)
|
||||
);
|
||||
}
|
||||
export function validApproval(merchant: Evidence) {
|
||||
const review = merchant.reviews[0];
|
||||
return !!(
|
||||
review?.decision === 'APPROVED' &&
|
||||
review.policyVersion === reviewPolicyVersion &&
|
||||
review.riskLevel &&
|
||||
review.reason?.trim() &&
|
||||
!merchant.reviews.some((cycle) => cycle.decision === 'PENDING') &&
|
||||
review.reviewer?.role === 'COMPLIANCE_OFFICER' &&
|
||||
review.decidedAt &&
|
||||
review.decidedAt >= review.submittedAt &&
|
||||
@@ -45,6 +67,22 @@ export function validApproval(merchant: Evidence) {
|
||||
snapshotsEqual(review.snapshot, reviewSnapshot(merchant))
|
||||
);
|
||||
}
|
||||
export function canReopenKyb(merchant: Evidence) {
|
||||
return (
|
||||
['INTEGRATION', 'TESTING'].includes(merchant.status) &&
|
||||
!merchant.reviews.some((review) => review.decision === 'PENDING') &&
|
||||
(!merchant.reviews[0] || merchant.reviews[0].policyVersion < reviewPolicyVersion)
|
||||
);
|
||||
}
|
||||
export function incompleteActivation(merchant: Evidence, includeTesting: boolean) {
|
||||
const review = merchant.reviews[0];
|
||||
return activationCodes.filter((code) => {
|
||||
if (!includeTesting && !isIntegrationCheck(code)) return false;
|
||||
const expected = isIntegrationCheck(code) ? 'COMPLETE' : 'PASSED';
|
||||
const check = review?.activationChecks.find((item) => item.code === code);
|
||||
return !check || check.state !== expected || check.changes.at(-1)?.toState !== expected;
|
||||
});
|
||||
}
|
||||
export function qualificationFields(merchant: Evidence) {
|
||||
const fields: string[] = [];
|
||||
for (const field of ['name', 'website', 'contactName', 'contactEmail'] as const)
|
||||
@@ -63,8 +101,7 @@ export function workflowActions(user: User, merchant: Evidence): WorkflowAction[
|
||||
if (merchant.status === 'COMPLIANCE_REVIEW') {
|
||||
const blockers: BlockingReason[] =
|
||||
user.role === 'COMPLIANCE_OFFICER' ? [] : [{ code: 'COMPLIANCE_ONLY' }];
|
||||
if (!merchant.reviews.some((review) => review.decision === 'PENDING'))
|
||||
blockers.push({ code: 'REVIEW_PENDING' });
|
||||
if (merchant.reviews[0]?.decision !== 'PENDING') blockers.push({ code: 'REVIEW_PENDING' });
|
||||
return [
|
||||
{
|
||||
kind: 'REVIEW',
|
||||
@@ -91,12 +128,23 @@ export function workflowActions(user: User, merchant: Evidence): WorkflowAction[
|
||||
}
|
||||
if (toStatus === 'COMPLIANCE_REVIEW') {
|
||||
if (!receivedHistory(merchant, new Date()))
|
||||
blockingReasons.push({ code: 'DOCUMENTS_REQUIRED' });
|
||||
blockingReasons.push({
|
||||
code: 'DOCUMENTS_REQUIRED',
|
||||
items: requiredDocumentCodes.filter((code) => {
|
||||
const item = merchant.checklist.find((entry) => entry.documentCode === code);
|
||||
return !item || item.state !== 'RECEIVED' || item.changes.at(-1)?.toState !== 'RECEIVED';
|
||||
}),
|
||||
});
|
||||
if (merchant.reviews.some((r) => r.decision === 'PENDING'))
|
||||
blockingReasons.push({ code: 'REVIEW_PENDING' });
|
||||
}
|
||||
if (['TESTING', 'LIVE'].includes(toStatus) && !validApproval(merchant))
|
||||
blockingReasons.push({ code: 'APPROVAL_REQUIRED' });
|
||||
if (canReopenKyb(merchant)) blockingReasons.push({ code: 'POLICY_UPGRADE_REQUIRED' });
|
||||
if (['TESTING', 'LIVE'].includes(toStatus)) {
|
||||
const items = incompleteActivation(merchant, toStatus === 'LIVE');
|
||||
if (items.length) blockingReasons.push({ code: 'ACTIVATION_CHECKS_REQUIRED', items });
|
||||
}
|
||||
const actions: WorkflowAction[] = [
|
||||
{
|
||||
kind: 'ADVANCE',
|
||||
|
||||
+113
-8
@@ -15,7 +15,13 @@ import {
|
||||
taskInputSchema,
|
||||
transitionSchema,
|
||||
merchantCreateSchema,
|
||||
documentCodes,
|
||||
requiredDocumentCodes,
|
||||
isRequiredDocument,
|
||||
activationCodes,
|
||||
activationEditSchema,
|
||||
isIntegrationCheck,
|
||||
reviewPolicyVersion,
|
||||
versionSchema,
|
||||
} from '@merchantflow/contracts';
|
||||
import { SessionGuard } from './auth.js';
|
||||
import { capabilities, merchantScope, requireSales, taskScope } from './access.js';
|
||||
@@ -25,6 +31,8 @@ import {
|
||||
evidenceInclude,
|
||||
receivedHistory,
|
||||
workflowActions,
|
||||
canReopenKyb,
|
||||
validApproval,
|
||||
type Evidence,
|
||||
} from './workflow-policy.js';
|
||||
|
||||
@@ -138,7 +146,7 @@ export class WorkflowController {
|
||||
status: 'NEW_LEAD',
|
||||
createdAt: now,
|
||||
stageEnteredAt: now,
|
||||
checklist: { create: documentCodes.map((documentCode) => ({ documentCode })) },
|
||||
checklist: { create: requiredDocumentCodes.map((documentCode) => ({ documentCode })) },
|
||||
events: {
|
||||
create: {
|
||||
fromStatus: null,
|
||||
@@ -234,6 +242,7 @@ export class WorkflowController {
|
||||
data: {
|
||||
merchantId: id,
|
||||
cycle: (merchant.reviews[0]?.cycle ?? 0) + 1,
|
||||
policyVersion: reviewPolicyVersion,
|
||||
submittedById: req.user.id,
|
||||
submittedAt,
|
||||
snapshot: reviewSnapshot(merchant),
|
||||
@@ -256,6 +265,7 @@ export class WorkflowController {
|
||||
requireSales(req.user);
|
||||
if (!capabilities(req.user, merchant).collectChecklist)
|
||||
throw new ApiError('REVIEW_LOCKED', 409);
|
||||
if (!isRequiredDocument(item.documentCode)) throw new ApiError('REVIEW_LOCKED', 409);
|
||||
await tx.kybChecklistItem.updateMany({
|
||||
where: { id: itemId, merchantId: id },
|
||||
data: { state, note },
|
||||
@@ -276,23 +286,32 @@ export class WorkflowController {
|
||||
@Param('reviewId') reviewId: string,
|
||||
@Body() body: unknown,
|
||||
) {
|
||||
const { version, decision, reason, corrections } = reviewDecisionSchema.parse(body);
|
||||
const { version, decision, reason, corrections, riskLevel } = 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')
|
||||
if (
|
||||
merchant.status !== 'COMPLIANCE_REVIEW' ||
|
||||
review.decision !== 'PENDING' ||
|
||||
merchant.reviews[0]?.id !== reviewId
|
||||
)
|
||||
throw new ApiError('WORKFLOW_INVALID', 409);
|
||||
if (!snapshotsEqual(review.snapshot, reviewSnapshot(merchant)))
|
||||
if (!snapshotsEqual(review.snapshot, reviewSnapshot(merchant, review.policyVersion)))
|
||||
throw new ApiError('CONFLICT', 409);
|
||||
if (decision === 'APPROVED' && !receivedHistory(merchant, review.submittedAt))
|
||||
if (
|
||||
decision === 'APPROVED' &&
|
||||
(review.policyVersion !== reviewPolicyVersion ||
|
||||
!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);
|
||||
if (!isRequiredDocument(item.documentCode)) throw new ApiError('VALIDATION_ERROR', 400);
|
||||
await tx.kybChecklistItem.updateMany({
|
||||
where: { id: item.id, merchantId: id },
|
||||
data: { state: 'NEEDS_CORRECTION', note: correction.note },
|
||||
data: { state: 'NEEDS_CORRECTION' },
|
||||
});
|
||||
await tx.checklistChange.create({
|
||||
data: {
|
||||
@@ -306,8 +325,27 @@ export class WorkflowController {
|
||||
}
|
||||
await tx.complianceReview.updateMany({
|
||||
where: { id: reviewId, merchantId: id, decision: 'PENDING' },
|
||||
data: { decision, reason: reason || null, reviewerId: req.user.id, decidedAt: new Date() },
|
||||
data: {
|
||||
decision,
|
||||
reason,
|
||||
riskLevel: riskLevel ?? null,
|
||||
corrections: corrections.map((correction) => ({
|
||||
...correction,
|
||||
documentCode: merchant.checklist.find((item) => item.id === correction.itemId)!
|
||||
.documentCode,
|
||||
})),
|
||||
reviewerId: req.user.id,
|
||||
decidedAt: new Date(),
|
||||
},
|
||||
});
|
||||
if (decision === 'APPROVED')
|
||||
await tx.activationCheck.createMany({
|
||||
data: activationCodes.map((code) => ({
|
||||
reviewId,
|
||||
code,
|
||||
state: isIntegrationCheck(code) ? ('INCOMPLETE' as const) : ('NOT_RUN' as const),
|
||||
})),
|
||||
});
|
||||
await this.stage(
|
||||
tx,
|
||||
req,
|
||||
@@ -319,6 +357,73 @@ export class WorkflowController {
|
||||
reviewId,
|
||||
decision,
|
||||
reason,
|
||||
riskLevel: riskLevel ?? null,
|
||||
});
|
||||
});
|
||||
}
|
||||
@Post(':id/reopen-kyb') reopenKyb(
|
||||
@Req() req: AuthRequest,
|
||||
@Param('id') id: string,
|
||||
@Body() body: unknown,
|
||||
) {
|
||||
const { version } = versionSchema.strict().parse(body);
|
||||
return this.mutate(req, id, version, async (tx, merchant) => {
|
||||
requireSales(req.user);
|
||||
if (!canReopenKyb(merchant)) throw new ApiError('WORKFLOW_INVALID', 409);
|
||||
await tx.kybChecklistItem.upsert({
|
||||
where: {
|
||||
merchantId_documentCode: { merchantId: id, documentCode: 'AUTHORIZED_REPRESENTATIVE' },
|
||||
},
|
||||
create: { merchantId: id, documentCode: 'AUTHORIZED_REPRESENTATIVE' },
|
||||
update: {},
|
||||
});
|
||||
await this.stage(
|
||||
tx,
|
||||
req,
|
||||
merchant,
|
||||
'KYB',
|
||||
'Updated KYB requirements require a new Compliance review.',
|
||||
);
|
||||
});
|
||||
}
|
||||
@Patch(':id/activation-checks/:code') activation(
|
||||
@Req() req: AuthRequest,
|
||||
@Param('id') id: string,
|
||||
@Param('code') code: string,
|
||||
@Body() body: unknown,
|
||||
) {
|
||||
const { version, reviewId, state, note } = activationEditSchema.parse(body);
|
||||
return this.mutate(req, id, version, async (tx, merchant) => {
|
||||
requireSales(req.user);
|
||||
if (!validApproval(merchant) || merchant.reviews[0]?.id !== reviewId)
|
||||
throw new ApiError('WORKFLOW_INVALID', 409);
|
||||
const review = merchant.reviews[0]!;
|
||||
const check = review.activationChecks.find((item) => item.code === code);
|
||||
if (!check) throw new ApiError('NOT_FOUND', 404);
|
||||
if (!capabilities(req.user, merchant).activationCodes.includes(check.code))
|
||||
throw new ApiError('REVIEW_LOCKED', 409);
|
||||
if (
|
||||
!(
|
||||
isIntegrationCheck(code) ? ['INCOMPLETE', 'COMPLETE'] : ['NOT_RUN', 'PASSED', 'FAILED']
|
||||
).includes(state)
|
||||
)
|
||||
throw new ApiError('VALIDATION_ERROR', 400);
|
||||
await tx.activationCheck.update({ where: { id: check.id }, data: { state, note } });
|
||||
await tx.activationCheckChange.create({
|
||||
data: {
|
||||
checkId: check.id,
|
||||
actorId: req.user.id,
|
||||
fromState: check.state,
|
||||
toState: state,
|
||||
note,
|
||||
},
|
||||
});
|
||||
await this.audit(tx, req, id, `Demo check updated: ${code}`, {
|
||||
reviewId,
|
||||
checkId: check.id,
|
||||
fromState: check.state,
|
||||
toState: state,
|
||||
note,
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
@@ -0,0 +1,590 @@
|
||||
import { before, after, afterEach, test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import { createDatabase, reviewSnapshot } from '@merchantflow/database';
|
||||
import {
|
||||
merchantDetailSchema,
|
||||
requiredDocumentCodes,
|
||||
reviewQueueSchema,
|
||||
} from '@merchantflow/contracts';
|
||||
import { createApp } from '../dist/app.js';
|
||||
|
||||
if (!process.env.DATABASE_URL?.endsWith('/merchantflow_test'))
|
||||
throw new Error('Only the isolated test database is allowed');
|
||||
const db = createDatabase(process.env.DATABASE_URL);
|
||||
const created = new Set();
|
||||
const cookies = {};
|
||||
let app, base;
|
||||
async function request(
|
||||
path,
|
||||
actor = 'head',
|
||||
body,
|
||||
method = body === undefined ? 'GET' : 'POST',
|
||||
headers = {},
|
||||
) {
|
||||
const response = await fetch(`${base}${path}`, {
|
||||
method,
|
||||
headers: {
|
||||
origin: process.env.APP_ORIGIN,
|
||||
...(cookies[actor] ? { cookie: cookies[actor] } : {}),
|
||||
...(body === undefined ? {} : { 'content-type': 'application/json' }),
|
||||
...headers,
|
||||
},
|
||||
...(body === undefined ? {} : { body: JSON.stringify(body) }),
|
||||
});
|
||||
return { status: response.status, body: await response.json(), headers: response.headers };
|
||||
}
|
||||
before(async () => {
|
||||
app = await createApp();
|
||||
await app.listen(0, '127.0.0.1');
|
||||
base = `${await app.getUrl()}/api`;
|
||||
for (const account of ['head', 'alex', 'sam', 'compliance']) {
|
||||
const result = await request('/auth/login', null, {
|
||||
email: `${account}@merchantflow.test`,
|
||||
password: 'MerchantFlow123!',
|
||||
});
|
||||
assert.equal(result.status, 201);
|
||||
cookies[account] = result.headers.get('set-cookie').split(';')[0];
|
||||
}
|
||||
});
|
||||
afterEach(async () => {
|
||||
await db.merchant.deleteMany({ where: { id: { in: [...created] } } });
|
||||
created.clear();
|
||||
});
|
||||
after(async () => {
|
||||
await app?.close();
|
||||
await db.$disconnect();
|
||||
});
|
||||
const input = (extra = {}) => ({
|
||||
name: `Sales ${randomUUID()}`,
|
||||
contactName: 'Unique Contact',
|
||||
contactEmail: '[email protected]',
|
||||
...extra,
|
||||
});
|
||||
async function create(actor = 'head', extra = {}) {
|
||||
const result = await request('/merchants', actor, input(extra));
|
||||
assert.equal(result.status, 201, JSON.stringify(result.body));
|
||||
created.add(result.body.id);
|
||||
return result.body.id;
|
||||
}
|
||||
async function detail(id, actor = 'head') {
|
||||
const result = await request(`/merchants/${id}`, actor);
|
||||
assert.equal(result.status, 200);
|
||||
return merchantDetailSchema.parse(result.body);
|
||||
}
|
||||
async function change(id, path, body, actor = 'head', method = 'PATCH') {
|
||||
const m = await detail(id);
|
||||
return request(`/merchants/${id}${path}`, actor, { version: m.version, ...body }, method);
|
||||
}
|
||||
const move = (id, toStatus, actor = 'head', reason) =>
|
||||
change(
|
||||
id,
|
||||
'/transitions',
|
||||
{ toStatus, ...(reason === undefined ? {} : { reason }) },
|
||||
actor,
|
||||
'POST',
|
||||
);
|
||||
const log = (id, kind = 'CALL', text = 'Contacted the primary contact') =>
|
||||
change(id, '/activities', { kind, text }, 'head', 'POST');
|
||||
|
||||
const approvedDecision = {
|
||||
decision: 'APPROVED',
|
||||
riskLevel: 'MEDIUM',
|
||||
reason: 'Ownership and representative authority verified.',
|
||||
};
|
||||
async function ready() {
|
||||
const id = await create('alex', {
|
||||
website: 'gates.test',
|
||||
country: 'GB',
|
||||
industry: 'SOFTWARE',
|
||||
estimatedMonthlyVolumeUsd: '0',
|
||||
});
|
||||
await log(id);
|
||||
for (const stage of ['CONTACTED', 'QUALIFIED', 'KYB'])
|
||||
assert.equal((await move(id, stage, 'alex')).status, 201);
|
||||
for (const item of (await detail(id)).checklist)
|
||||
assert.equal(
|
||||
(
|
||||
await change(
|
||||
id,
|
||||
`/checklist/${item.id}`,
|
||||
{ state: 'RECEIVED', note: `Collected ${item.documentCode}` },
|
||||
'alex',
|
||||
)
|
||||
).status,
|
||||
200,
|
||||
);
|
||||
return id;
|
||||
}
|
||||
async function submitted() {
|
||||
const id = await ready();
|
||||
assert.equal((await move(id, 'COMPLIANCE_REVIEW', 'alex')).status, 201);
|
||||
return id;
|
||||
}
|
||||
async function decide(id, body = approvedDecision, actor = 'compliance', reviewId) {
|
||||
return change(
|
||||
id,
|
||||
`/reviews/${reviewId ?? (await detail(id)).reviews[0].id}/decision`,
|
||||
body,
|
||||
actor,
|
||||
'POST',
|
||||
);
|
||||
}
|
||||
async function approved() {
|
||||
const id = await submitted();
|
||||
assert.equal((await decide(id)).status, 201);
|
||||
return id;
|
||||
}
|
||||
async function check(id, code, state, actor = 'alex', overrides = {}) {
|
||||
return change(
|
||||
id,
|
||||
`/activation-checks/${code}`,
|
||||
{ reviewId: (await detail(id)).reviews[0].id, state, note: 'Recorded demo only', ...overrides },
|
||||
actor,
|
||||
);
|
||||
}
|
||||
|
||||
test('new checklist, review snapshots, correction notes and approval validation remain distinct and immutable', async () => {
|
||||
const id = await ready();
|
||||
let m = await detail(id);
|
||||
assert.deepEqual(
|
||||
m.checklist.map((item) => item.documentCode).sort(),
|
||||
[...requiredDocumentCodes].sort(),
|
||||
);
|
||||
const item = m.checklist[0];
|
||||
await change(id, `/checklist/${item.id}`, {
|
||||
state: 'MISSING',
|
||||
note: 'Waiting for signed original',
|
||||
});
|
||||
assert.equal((await move(id, 'COMPLIANCE_REVIEW')).status, 409);
|
||||
await change(id, `/checklist/${item.id}`, {
|
||||
state: 'RECEIVED',
|
||||
note: 'Received signed original',
|
||||
});
|
||||
await move(id, 'COMPLIANCE_REVIEW');
|
||||
m = await detail(id);
|
||||
const original = m.reviews[0];
|
||||
for (const body of [
|
||||
{ decision: 'APPROVED', reason: 'Verified' },
|
||||
{ decision: 'APPROVED', riskLevel: 'LOW', reason: ' ' },
|
||||
{ decision: 'APPROVED', riskLevel: 'INVALID', reason: 'Verified' },
|
||||
{ decision: 'CORRECTIONS', reason: 'Update' },
|
||||
{ decision: 'REJECTED', reason: ' ' },
|
||||
])
|
||||
assert.equal((await decide(id, body)).status, 400);
|
||||
assert.equal(
|
||||
(await change(id, `/checklist/${item.id}`, { state: 'MISSING', note: 'Overwrite' })).status,
|
||||
409,
|
||||
);
|
||||
assert.equal(
|
||||
(
|
||||
await decide(id, {
|
||||
decision: 'CORRECTIONS',
|
||||
reason: 'Use the current form',
|
||||
corrections: [{ itemId: item.id, note: 'Add the current date and signature' }],
|
||||
})
|
||||
).status,
|
||||
201,
|
||||
);
|
||||
m = await detail(id);
|
||||
assert.equal(m.status, 'KYB');
|
||||
assert.equal(m.checklist.find((row) => row.id === item.id).note, 'Received signed original');
|
||||
assert.equal(m.checklist.find((row) => row.id === item.id).state, 'NEEDS_CORRECTION');
|
||||
assert.equal(m.reviews[0].corrections[0].note, 'Add the current date and signature');
|
||||
assert.deepEqual(m.reviews[0].snapshot, original.snapshot);
|
||||
const corrected = m.reviews[0];
|
||||
await change(id, `/checklist/${item.id}`, { state: 'RECEIVED', note: 'Current form received' });
|
||||
await move(id, 'COMPLIANCE_REVIEW');
|
||||
assert.equal((await decide(id, approvedDecision, 'compliance', original.id)).status, 409);
|
||||
assert.equal((await detail(id)).reviews[0].decision, 'PENDING');
|
||||
assert.equal((await decide(id)).status, 201);
|
||||
m = await detail(id);
|
||||
assert.deepEqual(m.reviews[1], corrected);
|
||||
assert.equal(m.reviews[0].riskLevel, 'MEDIUM');
|
||||
assert.equal(m.reviews[0].policyVersion, 2);
|
||||
assert.equal(m.reviews[0].cycle, 2);
|
||||
});
|
||||
|
||||
test('stage-specific activation checks gate every transition, preserve history and reject role/field/cycle bypasses', async () => {
|
||||
const id = await approved();
|
||||
const before = await detail(id);
|
||||
for (const actor of ['head', 'alex']) {
|
||||
assert.equal((await decide(id, approvedDecision, actor)).status, 403);
|
||||
assert.equal((await move(id, 'LIVE', actor)).status, 409);
|
||||
assert.equal((await change(id, '', { riskLevel: 'LOW', status: 'LIVE' }, actor)).status, 400);
|
||||
}
|
||||
assert.equal((await check(id, 'API_CONNECTION', 'COMPLETE', 'compliance')).status, 403);
|
||||
assert.equal((await check(id, 'API_CONNECTION', 'COMPLETE', 'sam')).status, 404);
|
||||
assert.equal((await check(id, 'API_CONNECTION', 'PASSED')).status, 400);
|
||||
assert.equal((await check(id, 'TEST_PAYMENT', 'PASSED')).status, 409);
|
||||
assert.equal(
|
||||
(await check(id, 'API_CONNECTION', 'COMPLETE', 'alex', { reviewId: 'other-cycle' })).status,
|
||||
409,
|
||||
);
|
||||
assert.equal((await move(id, 'TESTING')).status, 409);
|
||||
assert.equal((await check(id, 'API_CONNECTION', 'COMPLETE')).status, 200);
|
||||
assert.equal((await move(id, 'TESTING')).status, 409);
|
||||
assert.equal((await check(id, 'WEBHOOK_SETUP', 'COMPLETE', 'head')).status, 200);
|
||||
assert.equal((await move(id, 'TESTING')).status, 201);
|
||||
assert.equal((await check(id, 'API_CONNECTION', 'INCOMPLETE')).status, 409);
|
||||
assert.equal((await move(id, 'LIVE')).status, 409);
|
||||
assert.equal((await check(id, 'TEST_PAYMENT', 'FAILED')).status, 200);
|
||||
assert.equal((await check(id, 'RECONCILIATION', 'PASSED')).status, 200);
|
||||
assert.equal((await move(id, 'LIVE')).status, 409);
|
||||
assert.equal((await check(id, 'TEST_PAYMENT', 'PASSED')).status, 200);
|
||||
assert.equal((await move(id, 'LIVE')).status, 201);
|
||||
assert.equal((await check(id, 'RECONCILIATION', 'FAILED')).status, 409);
|
||||
const live = await detail(id);
|
||||
assert.equal(live.status, 'LIVE');
|
||||
assert.deepEqual(live.reviews, before.reviews);
|
||||
assert.equal(live.activationChecks.find((row) => row.code === 'TEST_PAYMENT').changes.length, 2);
|
||||
assert.ok(live.activationChecks.every((row) => row.changes.length && row.changes[0].actor.name));
|
||||
assert.equal(live.capabilities.handoff.owner, 'NONE');
|
||||
});
|
||||
|
||||
test('older approval and old check evidence cannot authorize a newer pending review or a mismatched snapshot', async () => {
|
||||
const id = await approved();
|
||||
await check(id, 'API_CONNECTION', 'COMPLETE');
|
||||
await check(id, 'WEBHOOK_SETUP', 'COMPLETE');
|
||||
const old = (await detail(id)).reviews[0];
|
||||
const next = await db.complianceReview.create({
|
||||
data: { merchantId: id, cycle: 2, submittedById: 'user-head', snapshot: old.snapshot },
|
||||
});
|
||||
assert.equal((await move(id, 'TESTING')).status, 409);
|
||||
assert.deepEqual((await detail(id)).capabilities.activationCodes, []);
|
||||
await db.merchant.update({ where: { id }, data: { status: 'COMPLIANCE_REVIEW' } });
|
||||
assert.equal((await decide(id, approvedDecision, 'compliance', old.id)).status, 409);
|
||||
assert.equal((await decide(id)).status, 201);
|
||||
assert.equal((await move(id, 'TESTING')).status, 409);
|
||||
assert.equal(
|
||||
(await check(id, 'API_CONNECTION', 'COMPLETE', 'head', { reviewId: old.id })).status,
|
||||
409,
|
||||
);
|
||||
const m = await detail(id);
|
||||
assert.ok(
|
||||
m.activationChecks
|
||||
.filter((row) => row.reviewId === next.id)
|
||||
.every((row) => !row.changes.length),
|
||||
);
|
||||
await db.merchant.update({ where: { id }, data: { legalName: 'Changed after approval' } });
|
||||
assert.equal((await check(id, 'API_CONNECTION', 'COMPLETE')).status, 409);
|
||||
assert.equal((await move(id, 'TESTING')).status, 409);
|
||||
});
|
||||
|
||||
test('concurrent submissions, decisions and check writes claim the version once', async () => {
|
||||
const id = await ready();
|
||||
let m = await detail(id);
|
||||
const submissions = await Promise.all(
|
||||
[1, 2].map(() =>
|
||||
request(`/merchants/${id}/transitions`, 'alex', {
|
||||
version: m.version,
|
||||
toStatus: 'COMPLIANCE_REVIEW',
|
||||
}),
|
||||
),
|
||||
);
|
||||
assert.deepEqual(submissions.map((result) => result.status).sort(), [201, 409]);
|
||||
m = await detail(id);
|
||||
const decisions = await Promise.all(
|
||||
[1, 2].map(() =>
|
||||
request(`/merchants/${id}/reviews/${m.reviews[0].id}/decision`, 'compliance', {
|
||||
version: m.version,
|
||||
...approvedDecision,
|
||||
}),
|
||||
),
|
||||
);
|
||||
assert.deepEqual(decisions.map((result) => result.status).sort(), [201, 409]);
|
||||
m = await detail(id);
|
||||
const writes = await Promise.all(
|
||||
['COMPLETE', 'INCOMPLETE'].map((state) =>
|
||||
request(
|
||||
`/merchants/${id}/activation-checks/API_CONNECTION`,
|
||||
'alex',
|
||||
{ version: m.version, reviewId: m.reviews[0].id, state, note: state },
|
||||
'PATCH',
|
||||
),
|
||||
),
|
||||
);
|
||||
assert.deepEqual(writes.map((result) => result.status).sort(), [200, 409]);
|
||||
assert.equal(
|
||||
(await detail(id)).activationChecks.find((row) => row.code === 'API_CONNECTION').changes.length,
|
||||
1,
|
||||
);
|
||||
});
|
||||
|
||||
async function legacy(status) {
|
||||
const id = await create('alex');
|
||||
await db.kybChecklistItem.deleteMany({ where: { merchantId: id } });
|
||||
await db.kybChecklistItem.createMany({
|
||||
data: ['INCORPORATION', 'OWNERSHIP', 'UBO_IDENTIFICATION', 'BUSINESS_ACTIVITY'].map(
|
||||
(documentCode) => ({
|
||||
merchantId: id,
|
||||
documentCode,
|
||||
state: 'RECEIVED',
|
||||
note: 'Preserve legacy note',
|
||||
}),
|
||||
),
|
||||
});
|
||||
const at = new Date(Date.now() - 3600000);
|
||||
let m = await db.merchant.update({
|
||||
where: { id },
|
||||
data: { status },
|
||||
include: { checklist: true },
|
||||
});
|
||||
for (const item of m.checklist)
|
||||
await db.checklistChange.create({
|
||||
data: {
|
||||
itemId: item.id,
|
||||
actorId: 'user-manager1',
|
||||
toState: 'RECEIVED',
|
||||
occurredAt: new Date(at.getTime() - 1000),
|
||||
},
|
||||
});
|
||||
const review = await db.complianceReview.create({
|
||||
data: {
|
||||
merchantId: id,
|
||||
cycle: 1,
|
||||
policyVersion: 1,
|
||||
decision: status === 'COMPLIANCE_REVIEW' ? 'PENDING' : 'APPROVED',
|
||||
submittedById: 'user-manager1',
|
||||
submittedAt: at,
|
||||
snapshot: reviewSnapshot(m, 1),
|
||||
...(status === 'COMPLIANCE_REVIEW' ? {} : { reviewerId: 'user-compliance', decidedAt: at }),
|
||||
},
|
||||
});
|
||||
// The additive migration creates a missing record, without changing old evidence.
|
||||
await db.kybChecklistItem.create({
|
||||
data: { merchantId: id, documentCode: 'AUTHORIZED_REPRESENTATIVE' },
|
||||
});
|
||||
return { id, review };
|
||||
}
|
||||
|
||||
test('legacy approval returns to KYB without rewriting decisions and requires fresh evidence', async () => {
|
||||
for (const stage of ['INTEGRATION', 'TESTING']) {
|
||||
const { id, review } = await legacy(stage);
|
||||
assert.equal((await move(id, stage === 'INTEGRATION' ? 'TESTING' : 'LIVE')).status, 409);
|
||||
assert.equal((await change(id, '/reopen-kyb', {}, 'compliance', 'POST')).status, 403);
|
||||
assert.equal((await change(id, '/reopen-kyb', {}, 'sam', 'POST')).status, 404);
|
||||
assert.equal((await change(id, '/reopen-kyb', {}, 'alex', 'POST')).status, 201);
|
||||
let m = await detail(id);
|
||||
assert.equal(m.capabilities.collectChecklist, true);
|
||||
assert.equal(m.capabilities.editIdentity, true);
|
||||
assert.equal((await move(id, 'COMPLIANCE_REVIEW')).status, 409);
|
||||
const archived = m.checklist.find((row) => row.documentCode === 'UBO_IDENTIFICATION');
|
||||
assert.equal(
|
||||
(await change(id, `/checklist/${archived.id}`, { state: 'RECEIVED', note: 'reinterpret' }))
|
||||
.status,
|
||||
409,
|
||||
);
|
||||
const representative = m.checklist.find(
|
||||
(row) => row.documentCode === 'AUTHORIZED_REPRESENTATIVE',
|
||||
);
|
||||
await change(id, `/checklist/${representative.id}`, {
|
||||
state: 'RECEIVED',
|
||||
note: 'Authority verified',
|
||||
});
|
||||
assert.equal((await move(id, 'COMPLIANCE_REVIEW')).status, 201);
|
||||
assert.equal((await decide(id)).status, 201);
|
||||
m = await detail(id);
|
||||
assert.equal(m.reviews[0].snapshot.checklist.length, 3);
|
||||
assert.deepEqual(await db.complianceReview.findUnique({ where: { id: review.id } }), review);
|
||||
assert.equal(m.checklist.find((row) => row.id === archived.id).note, 'Preserve legacy note');
|
||||
}
|
||||
});
|
||||
|
||||
test('legacy pending review accepts corrections or rejection, never an approval under obsolete requirements', async () => {
|
||||
const { id, review } = await legacy('COMPLIANCE_REVIEW');
|
||||
assert.equal((await decide(id)).status, 409);
|
||||
const item = (await detail(id)).checklist.find(
|
||||
(row) => row.documentCode === 'AUTHORIZED_REPRESENTATIVE',
|
||||
);
|
||||
assert.equal(
|
||||
(
|
||||
await decide(id, {
|
||||
decision: 'CORRECTIONS',
|
||||
reason: 'Apply current KYB requirements',
|
||||
corrections: [
|
||||
{ itemId: item.id, note: 'Collect authorized-representative identification' },
|
||||
],
|
||||
})
|
||||
).status,
|
||||
201,
|
||||
);
|
||||
assert.deepEqual((await detail(id)).reviews[0].snapshot, review.snapshot);
|
||||
await change(id, `/checklist/${item.id}`, { state: 'RECEIVED', note: null });
|
||||
await move(id, 'COMPLIANCE_REVIEW');
|
||||
assert.equal((await decide(id)).status, 201);
|
||||
const second = await legacy('COMPLIANCE_REVIEW');
|
||||
assert.equal(
|
||||
(await decide(second.id, { decision: 'REJECTED', reason: 'Authority cannot be established' }))
|
||||
.status,
|
||||
201,
|
||||
);
|
||||
assert.equal((await detail(second.id)).status, 'REJECTED');
|
||||
assert.equal((await move(second.id, 'KYB')).status, 409);
|
||||
});
|
||||
|
||||
test('queue counts pending cycles, combines filters, and exposes review IDs and submission times', async () => {
|
||||
const first = await submitted();
|
||||
const second = await submitted();
|
||||
const old = new Date(Date.now() - 73 * 3600000);
|
||||
await db.complianceReview.update({
|
||||
where: { id: (await detail(first)).reviews[0].id },
|
||||
data: { submittedAt: old },
|
||||
});
|
||||
await db.merchant.update({
|
||||
where: { id: first },
|
||||
data: { name: 'Queue Specific Old', ownerId: 'user-manager2' },
|
||||
});
|
||||
for (const actor of ['head', 'alex', 'sam'])
|
||||
assert.equal((await request('/review-queue', actor)).status, 403);
|
||||
assert.equal((await request('/review-queue?waiting=invalid', 'compliance')).status, 400);
|
||||
const all = reviewQueueSchema.parse((await request('/review-queue', 'compliance')).body);
|
||||
const filtered = reviewQueueSchema.parse(
|
||||
(
|
||||
await request(
|
||||
'/review-queue?search=Queue%20Specific&ownerId=user-manager2&waiting=72',
|
||||
'compliance',
|
||||
)
|
||||
).body,
|
||||
);
|
||||
assert.equal(filtered.pendingCount, all.pendingCount);
|
||||
assert.equal(filtered.filteredCount, 1);
|
||||
assert.equal(filtered.items[0].merchant.id, first);
|
||||
assert.equal(filtered.items[0].submittedAt, old.toISOString());
|
||||
assert.ok(filtered.items[0].id && filtered.items[0].cycle === 1);
|
||||
assert.equal(
|
||||
(await request('/review-queue?search=Queue%20Specific&ownerId=user-manager1', 'compliance'))
|
||||
.body.filteredCount,
|
||||
0,
|
||||
);
|
||||
await decide(second);
|
||||
assert.equal(
|
||||
(await request('/review-queue', 'compliance')).body.pendingCount,
|
||||
all.pendingCount - 1,
|
||||
);
|
||||
});
|
||||
|
||||
test('invalid correction children and injected activation failure roll back the complete mutation', async () => {
|
||||
const id = await submitted();
|
||||
let m = await detail(id);
|
||||
const before = m;
|
||||
assert.equal(
|
||||
(
|
||||
await decide(id, {
|
||||
decision: 'CORRECTIONS',
|
||||
reason: 'Fix records',
|
||||
corrections: [
|
||||
{ itemId: m.checklist[0].id, note: 'First valid correction' },
|
||||
{ itemId: 'foreign-item', note: 'Wrong merchant' },
|
||||
],
|
||||
})
|
||||
).status,
|
||||
404,
|
||||
);
|
||||
assert.deepEqual(await detail(id), before);
|
||||
await decide(id);
|
||||
m = await detail(id);
|
||||
// Inject failure with a transaction-local PostgreSQL trigger, scoped to this fixture.
|
||||
await db.$executeRawUnsafe(
|
||||
`CREATE FUNCTION reject_demo_change() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN IF NEW."note" = 'trigger rollback' THEN RAISE EXCEPTION 'test rollback'; END IF; RETURN NEW; END $$`,
|
||||
);
|
||||
await db.$executeRawUnsafe(
|
||||
`CREATE TRIGGER reject_demo_change BEFORE INSERT ON "ActivationCheckChange" FOR EACH ROW EXECUTE FUNCTION reject_demo_change()`,
|
||||
);
|
||||
try {
|
||||
assert.equal(
|
||||
(await check(id, 'API_CONNECTION', 'COMPLETE', 'alex', { note: 'trigger rollback' })).status,
|
||||
500,
|
||||
);
|
||||
assert.deepEqual(await detail(id), m);
|
||||
} finally {
|
||||
await db.$executeRawUnsafe('DROP TRIGGER reject_demo_change ON "ActivationCheckChange"');
|
||||
await db.$executeRawUnsafe('DROP FUNCTION reject_demo_change()');
|
||||
}
|
||||
});
|
||||
|
||||
test('additive migrations preserve existing decisions, collection history and terminal merchants', async () => {
|
||||
const { createRequire } = await import('node:module');
|
||||
const { readFileSync } = await import('node:fs');
|
||||
const require = createRequire(
|
||||
new URL('../../../packages/database/package.json', import.meta.url),
|
||||
);
|
||||
const { Client } = require('pg');
|
||||
const client = new Client({ connectionString: process.env.DATABASE_URL });
|
||||
const schema = `gated_upgrade_${randomUUID().replaceAll('-', '')}`;
|
||||
await client.connect();
|
||||
try {
|
||||
await client.query(`CREATE SCHEMA "${schema}"`);
|
||||
await client.query(`SET search_path TO "${schema}"`);
|
||||
const apply = (migration) =>
|
||||
client.query(
|
||||
readFileSync(
|
||||
new URL(
|
||||
`../../../packages/database/prisma/migrations/${migration}/migration.sql`,
|
||||
import.meta.url,
|
||||
),
|
||||
'utf8',
|
||||
),
|
||||
);
|
||||
for (const migration of [
|
||||
'202609240001_foundation',
|
||||
'202609240002_onboarding',
|
||||
'202609240003_public_leads',
|
||||
'202609240004_sales_workspace',
|
||||
])
|
||||
await apply(migration);
|
||||
await client.query(
|
||||
`INSERT INTO "User" (id, email, name, "passwordHash", role) VALUES ('sales', 'sales@test', 'Sales', 'preserve-hash', 'ACCOUNT_MANAGER'), ('compliance', 'compliance@test', 'Compliance', 'preserve-hash', 'COMPLIANCE_OFFICER')`,
|
||||
);
|
||||
await client.query(
|
||||
`INSERT INTO "Merchant" (id, name, "contactName", "contactEmail", "ownerId", status) VALUES ('unfinished', 'Old company', 'Contact', 'contact@test', 'sales', 'INTEGRATION'), ('terminal', 'Live company', 'Contact', 'contact@test', 'sales', 'LIVE')`,
|
||||
);
|
||||
await client.query(
|
||||
`INSERT INTO "KybChecklistItem" (id, "merchantId", "documentCode", state, note) VALUES ('original', 'unfinished', 'UBO_IDENTIFICATION', 'RECEIVED', 'Original evidence note')`,
|
||||
);
|
||||
await client.query(
|
||||
`INSERT INTO "ChecklistChange" (id, "itemId", "actorId", "toState", note) VALUES ('change', 'original', 'sales', 'RECEIVED', 'Historical note')`,
|
||||
);
|
||||
await client.query(
|
||||
`INSERT INTO "ComplianceReview" (id, "merchantId", cycle, "submittedById", "reviewerId", decision, "decidedAt", snapshot) VALUES ('review', 'unfinished', 1, 'sales', 'compliance', 'APPROVED', CURRENT_TIMESTAMP, '{"company":{"name":"Old company"},"checklist":[]}')`,
|
||||
);
|
||||
const originalReview = (await client.query('SELECT * FROM "ComplianceReview"')).rows[0];
|
||||
const originalItems = (await client.query('SELECT * FROM "KybChecklistItem"')).rows;
|
||||
const originalChanges = (await client.query('SELECT * FROM "ChecklistChange"')).rows;
|
||||
const merchants = (await client.query('SELECT * FROM "Merchant" ORDER BY id')).rows;
|
||||
await apply('202609240005_gated_onboarding');
|
||||
await apply('202609240006_kyb_upgrade');
|
||||
const upgradedReview = (await client.query('SELECT * FROM "ComplianceReview"')).rows[0];
|
||||
assert.deepEqual(upgradedReview, {
|
||||
...originalReview,
|
||||
policyVersion: 1,
|
||||
riskLevel: null,
|
||||
corrections: [],
|
||||
});
|
||||
assert.deepEqual(
|
||||
(await client.query('SELECT * FROM "KybChecklistItem" WHERE id = \'original\'')).rows,
|
||||
originalItems,
|
||||
);
|
||||
assert.deepEqual((await client.query('SELECT * FROM "ChecklistChange"')).rows, originalChanges);
|
||||
const added = (
|
||||
await client.query(
|
||||
'SELECT * FROM "KybChecklistItem" WHERE "documentCode" = \'AUTHORIZED_REPRESENTATIVE\'',
|
||||
)
|
||||
).rows;
|
||||
assert.equal(added.length, 1);
|
||||
assert.equal(added[0].merchantId, 'unfinished');
|
||||
assert.equal(added[0].state, 'MISSING');
|
||||
assert.deepEqual(
|
||||
(await client.query('SELECT * FROM "Merchant" ORDER BY id')).rows,
|
||||
merchants.map((merchant) => ({
|
||||
...merchant,
|
||||
version: merchant.version + (merchant.id === 'unfinished' ? 1 : 0),
|
||||
})),
|
||||
);
|
||||
assert.equal((await client.query('SELECT count(*) FROM "ActivationCheck"')).rows[0].count, '0');
|
||||
} finally {
|
||||
await client.query('SET search_path TO public');
|
||||
await client.query(`DROP SCHEMA "${schema}" CASCADE`);
|
||||
await client.end();
|
||||
}
|
||||
});
|
||||
@@ -3,7 +3,7 @@ import assert from 'node:assert/strict';
|
||||
import { createHash } from 'node:crypto';
|
||||
import { spawnSync } from 'node:child_process';
|
||||
import { createDatabase } from '@merchantflow/database';
|
||||
import { roles, statuses, documentCodes } from '@merchantflow/contracts';
|
||||
import { roles, statuses, documentCodes, requiredDocumentCodes } from '@merchantflow/contracts';
|
||||
import {
|
||||
Role,
|
||||
MerchantStatus,
|
||||
@@ -133,7 +133,7 @@ for (const [account, total] of [
|
||||
for (const m of expected) {
|
||||
const detail = (await request(`/merchants/${m.id}`, cookie)).body;
|
||||
assert.equal(detail.id, m.id);
|
||||
assert.equal(detail.checklist.length, 4);
|
||||
assert.equal(detail.checklist.length, 3);
|
||||
assert.ok(detail.events.every((e) => e.merchant.id === m.id));
|
||||
assert.ok(detail.tasks.every((t) => t.merchant.id === m.id));
|
||||
assert.ok(!JSON.stringify(detail).includes('passwordHash'));
|
||||
@@ -197,10 +197,10 @@ test('filters are validated and review queue is oldest first', async () => {
|
||||
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;
|
||||
const queue = (await request('/review-queue', cookies.compliance)).body.items;
|
||||
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));
|
||||
assert.ok(queue.every((m) => m.merchant.status === 'COMPLIANCE_REVIEW'));
|
||||
assert.ok(new Date(queue[0].submittedAt) <= new Date(queue[1].submittedAt));
|
||||
});
|
||||
test('seed is repeatable without modifying records; history includes correction and terminal outcomes', async () => {
|
||||
const snapshot = await db.merchant.findMany({
|
||||
@@ -271,7 +271,7 @@ async function fixture(id, status = 'NEW_LEAD', ownerId = 'user-manager1') {
|
||||
contactEmail: '[email protected]',
|
||||
ownerId,
|
||||
status,
|
||||
checklist: { create: documentCodes.map((documentCode) => ({ documentCode })) },
|
||||
checklist: { create: requiredDocumentCodes.map((documentCode) => ({ documentCode })) },
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -313,7 +313,16 @@ test('manager lookup and both directions of direct record/child/mutation attacks
|
||||
{ version: hidden.version, state: 'RECEIVED', note: null },
|
||||
'PATCH',
|
||||
],
|
||||
['/reviews/unknown/decision', { version: hidden.version, decision: 'APPROVED' }, 'POST'],
|
||||
[
|
||||
'/reviews/unknown/decision',
|
||||
{
|
||||
version: hidden.version,
|
||||
decision: 'APPROVED',
|
||||
riskLevel: 'LOW',
|
||||
reason: 'Evidence verified',
|
||||
},
|
||||
'POST',
|
||||
],
|
||||
['/activities', { version: hidden.version, kind: 'NOTE', text: 'Forbidden' }, 'POST'],
|
||||
[
|
||||
`/activities/${hidden.activities[0].id}`,
|
||||
@@ -507,7 +516,12 @@ test('corrections, resubmission, approval and activation preserve one merchant a
|
||||
await mutate(
|
||||
`/merchants/${id}/reviews/${first.id}/decision`,
|
||||
cookie,
|
||||
{ version: m.version, decision: 'APPROVED' },
|
||||
{
|
||||
version: m.version,
|
||||
decision: 'APPROVED',
|
||||
riskLevel: 'LOW',
|
||||
reason: 'Evidence verified',
|
||||
},
|
||||
'POST',
|
||||
)
|
||||
).status,
|
||||
@@ -562,7 +576,12 @@ test('corrections, resubmission, approval and activation preserve one merchant a
|
||||
await mutate(
|
||||
`/merchants/${id}/reviews/${m.reviews[0].id}/decision`,
|
||||
comp,
|
||||
{ version: m.version, decision: 'APPROVED', reason: 'All checks passed' },
|
||||
{
|
||||
version: m.version,
|
||||
decision: 'APPROVED',
|
||||
riskLevel: 'LOW',
|
||||
reason: 'All checks passed',
|
||||
},
|
||||
'POST',
|
||||
)
|
||||
).status,
|
||||
@@ -591,7 +610,37 @@ test('corrections, resubmission, approval and activation preserve one merchant a
|
||||
200,
|
||||
);
|
||||
assert.equal((await move('TESTING', comp)).status, 403);
|
||||
assert.equal((await move('TESTING')).status, 409);
|
||||
for (const code of ['API_CONNECTION', 'WEBHOOK_SETUP']) {
|
||||
const current = await detail();
|
||||
assert.equal(
|
||||
(
|
||||
await mutate(`/merchants/${id}/activation-checks/${code}`, sales, {
|
||||
version: current.version,
|
||||
reviewId: current.reviews[0].id,
|
||||
state: 'COMPLETE',
|
||||
note: 'Demo only',
|
||||
})
|
||||
).status,
|
||||
200,
|
||||
);
|
||||
}
|
||||
assert.equal((await move('TESTING')).status, 201);
|
||||
assert.equal((await move('LIVE', head)).status, 409);
|
||||
for (const code of ['TEST_PAYMENT', 'RECONCILIATION']) {
|
||||
const current = await detail();
|
||||
assert.equal(
|
||||
(
|
||||
await mutate(`/merchants/${id}/activation-checks/${code}`, sales, {
|
||||
version: current.version,
|
||||
reviewId: current.reviews[0].id,
|
||||
state: 'PASSED',
|
||||
note: 'Demo only',
|
||||
})
|
||||
).status,
|
||||
200,
|
||||
);
|
||||
}
|
||||
assert.equal((await move('LIVE', head)).status, 201);
|
||||
assert.equal((await move('REJECTED')).status, 409);
|
||||
m = await detail();
|
||||
@@ -603,7 +652,12 @@ test('corrections, resubmission, approval and activation preserve one merchant a
|
||||
await mutate(
|
||||
`/merchants/${id}/reviews/${first.id}/decision`,
|
||||
comp,
|
||||
{ version: m.version, decision: 'APPROVED' },
|
||||
{
|
||||
version: m.version,
|
||||
decision: 'APPROVED',
|
||||
riskLevel: 'LOW',
|
||||
reason: 'Evidence verified',
|
||||
},
|
||||
'POST',
|
||||
)
|
||||
).status,
|
||||
|
||||
@@ -82,7 +82,7 @@ test('public submission persists complete onboarding context and respects CRM pe
|
||||
assert.equal(merchant.industry, 'OTHER');
|
||||
assert.equal(merchant.website, 'https://example.test/');
|
||||
assert.equal(merchant.estimatedMonthlyVolumeUsd.toFixed(2), '1234.50');
|
||||
assert.equal(merchant.checklist.length, 4);
|
||||
assert.equal(merchant.checklist.length, 3);
|
||||
assert.ok(
|
||||
merchant.checklist.every((item) => item.state === 'MISSING' && item.changes.length === 0),
|
||||
);
|
||||
|
||||
@@ -96,7 +96,7 @@ test('staff creation is atomic, minimally required, role-bound and strict', asyn
|
||||
assert.equal(m.website, null);
|
||||
assert.equal(m.country, null);
|
||||
assert.equal(m.industry, null);
|
||||
assert.equal(m.checklist.length, 4);
|
||||
assert.equal(m.checklist.length, 3);
|
||||
assert.ok(m.checklist.every((item) => item.state === 'MISSING'));
|
||||
assert.equal(m.events.length, 1);
|
||||
assert.equal(m.activities.length, 1);
|
||||
@@ -313,8 +313,11 @@ test('every rejection role and stage rule is enforced, with terminal outcomes an
|
||||
merchantId: clone,
|
||||
cycle: 1,
|
||||
decision: 'APPROVED',
|
||||
riskLevel: 'LOW',
|
||||
reason: 'Approval retained during commercial closure',
|
||||
submittedById: 'user-head',
|
||||
reviewerId: 'user-compliance',
|
||||
submittedAt: new Date(Date.now() - 1000),
|
||||
decidedAt: new Date(),
|
||||
snapshot: approved.reviews[0].snapshot,
|
||||
},
|
||||
|
||||
Reference in New Issue
Block a user