Implemented KYB, compliance decisions, integration, and testing

This commit is contained in:
Oleksandr Prokhorenko
2026-09-24 21:31:42 +03:00
parent 382f6e8841
commit 1f8721e742
36 changed files with 2279 additions and 233 deletions
+42 -4
View File
@@ -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
View File
@@ -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() } },
}),
+5 -2
View File
@@ -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: {
+56 -8
View File
@@ -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
View File
@@ -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,
});
});
}
+590
View File
@@ -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();
}
});
+64 -10
View File
@@ -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,
+1 -1
View File
@@ -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),
);
+4 -1
View File
@@ -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,
},
+21 -99
View File
@@ -9,7 +9,7 @@ import {
industries,
managerListSchema,
merchantEditSchema,
reviewDecisionSchema,
isRequiredDocument,
sources,
statuses,
taskInputSchema,
@@ -180,7 +180,7 @@ export function ChecklistControl({
const action = useAction(m, () => setOpen(false));
return (
<div className="mt-3 space-y-2">
{m.capabilities.collectChecklist && (
{m.capabilities.collectChecklist && isRequiredDocument(item.documentCode) && (
<Button
variant="outline"
onClick={() => {
@@ -191,6 +191,22 @@ export function ChecklistControl({
{t('workflow.checklistEdit')}
</Button>
)}
{!isRequiredDocument(item.documentCode) && (
<p className="text-xs text-muted-foreground">{t('onboarding.legacyItem')}</p>
)}
{m.reviews[0]?.decision === 'CORRECTIONS' &&
item.state !== 'RECEIVED' &&
m.reviews[0].corrections
.filter((correction) => correction.itemId === item.id)
.map((correction) => (
<p
key={correction.itemId}
className="rounded-lg bg-amber-50 p-3 text-sm whitespace-pre-wrap"
>
<strong>{t('onboarding.correctionNote')}: </strong>
{correction.note}
</p>
))}
{action.feedback}
<details className="text-xs text-muted-foreground">
<summary className="min-h-11 cursor-pointer py-3">{t('workflow.checklistHistory')}</summary>
@@ -235,103 +251,7 @@ export function ChecklistControl({
</div>
);
}
export function ReviewHistory({ merchant: m }: { merchant: MerchantDetail }) {
const { t } = useTranslation();
const f = useFormat();
const [open, setOpen] = useState(false);
const action = useAction(m, () => setOpen(false));
const pending = m.reviews.find((review) => review.decision === 'PENDING');
return (
<section className="surface">
<SectionHeader
title={t('workflow.reviews')}
action={
m.capabilities.review &&
pending && (
<Button
onClick={() => {
action.reset();
setOpen(true);
}}
>
{t('workflow.decide')}
</Button>
)
}
/>
<div className="space-y-4 p-5 sm:p-6">
{action.feedback}
{!m.reviews.length && (
<p className="text-sm text-muted-foreground">{t('review.emptyText')}</p>
)}
{m.reviews.map((review) => (
<article key={review.id} className="rounded-lg border p-4">
<p className="text-sm font-semibold">
{t('workflow.cycle', { cycle: review.cycle })} · {t(`workflow.${review.decision}`)}
</p>
<p className="mt-2 text-xs text-muted-foreground">
{t('workflow.submitted', {
name: review.submittedBy.name,
date: f.date(review.submittedAt),
})}
</p>
{review.reviewer && review.decidedAt && (
<p className="mt-1 text-xs text-muted-foreground">
{t('workflow.reviewed', {
name: review.reviewer.name,
date: f.date(review.decidedAt),
})}
</p>
)}
{review.reason && (
<p className="mt-3 whitespace-pre-wrap text-sm leading-relaxed">{review.reason}</p>
)}
</article>
))}
</div>
{open && pending && (
<Editor
title={t('workflow.decide')}
description={t('workflow.correctionHint')}
fields={[
{
name: 'decision',
options: ['APPROVED', 'CORRECTIONS', 'REJECTED'].map((value) => ({
value,
label: t(`workflow.${value}`),
})),
},
{ name: 'reason', type: 'textarea' },
...m.checklist.map((item) => ({
name: `correction_${item.id}`,
label: t(`documents.${item.documentCode}`),
type: 'textarea',
})),
]}
initial={{ decision: 'APPROVED', reason: '' }}
schema={reviewDecisionSchema}
build={(values) => ({
version: m.version,
decision: values.decision,
reason: values.reason,
corrections:
values.decision === 'CORRECTIONS'
? m.checklist
.filter((item) => values[`correction_${item.id}`]?.trim())
.map((item) => ({ itemId: item.id, note: values[`correction_${item.id}`] }))
: [],
})}
submit={(body) =>
action.mutate({ path: `/reviews/${pending.id}/decision`, method: 'POST', body })
}
close={() => setOpen(false)}
pending={action.isPending}
feedback={action.feedback}
/>
)}
</section>
);
}
export { ReviewHistory } from './onboarding';
export function useActivityText() {
const { t } = useTranslation();
return (activity: Pick<MerchantDetail['activities'][number], 'kind' | 'text'>) => {
@@ -349,6 +269,8 @@ export function useActivityText() {
const stages = activity.text.split(' → ');
if (stages.length === 2 && stages.every((stage) => statuses.some((code) => code === stage)))
return stages.map((stage) => t(`statuses.${stage}`)).join(' → ');
if (activity.text.startsWith('Demo check updated: '))
return t('onboarding.checkUpdated', { check: t(`onboarding.${activity.text.slice(20)}`) });
if (activity.text.startsWith('Checklist updated: '))
return t('workflow.checklistUpdated', {
document: t(`documents.${activity.text.slice(19)}`),
+342
View File
@@ -0,0 +1,342 @@
import { useEffect, useState } from 'react';
import { useLocation } from 'react-router';
import { useTranslation } from 'react-i18next';
import {
activationEditSchema,
isIntegrationCheck,
isRequiredDocument,
reviewDecisionSchema,
reviewPolicyVersion,
riskLevels,
type MerchantDetail,
} from '@merchantflow/contracts';
import { Editor, useAction, type Field } from './workflow-form';
import { useFormat } from '../lib/format';
import { Button, SectionHeader } from './shared';
export function OnboardingHandoff({ merchant: m }: { merchant: MerchantDetail }) {
const { t } = useTranslation();
const action = useAction(m);
const handoff = m.capabilities.handoff;
const owner =
handoff.owner === 'ACCOUNT_MANAGER'
? m.owner?.name
: handoff.owner === 'NONE'
? t('onboarding.noNextOwner')
: t(`roles.${handoff.owner}`);
return (
<section
aria-label={t('onboarding.nextStep')}
className="mb-5 rounded-xl border bg-muted/40 p-4 sm:p-5"
>
<div className="flex flex-wrap items-start justify-between gap-4">
<div>
<p className="text-xs text-muted-foreground">{t('onboarding.nextOwner')}</p>
<p className="mt-1 text-sm font-semibold">{owner}</p>
</div>
<div className="max-w-xl">
<p className="text-xs text-muted-foreground">{t('onboarding.requiredAction')}</p>
<p className="mt-1 text-sm">{t(`onboarding.actions.${handoff.action}`)}</p>
</div>
</div>
{m.capabilities.reopenKyb && (
<Button
className="mt-4"
disabled={action.isPending}
onClick={() =>
action.mutate({ path: '/reopen-kyb', method: 'POST', body: { version: m.version } })
}
>
{t('onboarding.reopen')}
</Button>
)}
{action.feedback}
</section>
);
}
export function ReviewHistory({ merchant: m }: { merchant: MerchantDetail }) {
const { t } = useTranslation();
const f = useFormat();
const location = useLocation();
const [reviewId, setReviewId] = useState<string | null>(null);
const action = useAction(m, () => setReviewId(null));
const pending = m.reviews[0]?.decision === 'PENDING' ? m.reviews[0] : undefined;
const selected = m.reviews.find((review) => review.id === reviewId);
const legacy =
(selected ?? pending)?.policyVersion !== undefined &&
(selected ?? pending)!.policyVersion < reviewPolicyVersion;
useEffect(() => {
if (location.hash.startsWith('#review-'))
document.getElementById(location.hash.slice(1))?.focus();
}, [location.hash]);
const fields = (values: Record<string, string>): Field[] => [
{
name: 'decision',
options: (legacy ? ['CORRECTIONS', 'REJECTED'] : ['APPROVED', 'CORRECTIONS', 'REJECTED']).map(
(value) => ({ value, label: t(`onboarding.decisions.${value}`) }),
),
},
...(values.decision === 'APPROVED'
? [
{
name: 'riskLevel',
label: t('onboarding.riskLevel'),
options: [
{ value: '', label: t('onboarding.chooseRisk') },
...riskLevels.map((value) => ({ value, label: t(`onboarding.risk.${value}`) })),
],
},
]
: []),
{ name: 'reason', label: t(`onboarding.reason.${values.decision}`), type: 'textarea' },
...(values.decision === 'CORRECTIONS'
? m.checklist
.filter((item) => isRequiredDocument(item.documentCode))
.map((item) => ({
name: `correction_${item.id}`,
label: t(`documents.${item.documentCode}`),
type: 'textarea',
}))
: []),
];
return (
<section className="surface" id="reviews">
<SectionHeader
title={t('workflow.reviews')}
description={t('onboarding.complianceOnly')}
action={
m.capabilities.review &&
pending && (
<Button
onClick={() => {
action.reset();
setReviewId(pending.id);
}}
>
{t('workflow.decide')}
</Button>
)
}
/>
<div className="space-y-4 p-5 sm:p-6">
{action.feedback}
{legacy && (
<p className="rounded-lg bg-amber-50 p-3 text-sm">{t('onboarding.legacyReview')}</p>
)}
{!m.reviews.length && (
<p className="text-sm text-muted-foreground">{t('onboarding.noReviews')}</p>
)}
{m.reviews.map((review) => (
<article
id={`review-${review.id}`}
tabIndex={-1}
key={review.id}
className="scroll-mt-8 rounded-lg border p-4"
>
<p className="text-sm font-semibold">
{t('workflow.cycle', { cycle: review.cycle })} · {t(`workflow.${review.decision}`)}
</p>
{review.policyVersion < reviewPolicyVersion && (
<p className="mt-1 text-xs text-muted-foreground">{t('onboarding.legacyCycle')}</p>
)}
<p className="mt-2 text-xs text-muted-foreground">
{t('workflow.submitted', {
name: review.submittedBy.name,
date: f.dateTime(review.submittedAt),
})}
</p>
{review.reviewer && review.decidedAt && (
<p className="mt-1 text-xs text-muted-foreground">
{t('workflow.reviewed', {
name: review.reviewer.name,
date: f.dateTime(review.decidedAt),
})}
</p>
)}
{review.riskLevel && (
<p className="mt-3 text-sm font-medium">
{t('onboarding.riskLevel')}: {t(`onboarding.risk.${review.riskLevel}`)}
</p>
)}
{review.reason && (
<p className="mt-3 whitespace-pre-wrap break-words text-sm">{review.reason}</p>
)}
{review.corrections.map((correction) => (
<p key={correction.itemId} className="mt-3 whitespace-pre-wrap break-words text-sm">
<strong>{t(`documents.${correction.documentCode}`)}: </strong>
{correction.note}
</p>
))}
<details className="mt-3 text-sm">
<summary className="min-h-11 cursor-pointer py-3">
{t('onboarding.submittedEvidence')}
</summary>
<dl className="grid gap-3 rounded-lg bg-muted/40 p-3 sm:grid-cols-2">
{Object.entries(review.snapshot.company).map(([field, value]) => (
<div key={field}>
<dt className="text-xs text-muted-foreground">{t(`workflow.${field}`)}</dt>
<dd className="mt-1 break-words">{value ?? '—'}</dd>
</div>
))}
</dl>
<ul className="mt-3 space-y-3">
{review.snapshot.checklist.map((item) => (
<li key={item.id}>
<p>
{t(`documents.${item.documentCode}`)} · {t(`checklist.${item.state}`)}
</p>
{item.note && (
<p className="mt-1 whitespace-pre-wrap break-words text-muted-foreground">
{item.note}
</p>
)}
</li>
))}
</ul>
</details>
</article>
))}
</div>
{selected && (
<Editor
title={t('workflow.decide')}
description={t(legacy ? 'onboarding.legacyReview' : 'workflow.correctionHint')}
fields={fields}
initial={{ decision: legacy ? 'CORRECTIONS' : 'APPROVED', reason: '', riskLevel: '' }}
schema={reviewDecisionSchema}
build={(values) => ({
version: m.version,
decision: values.decision,
reason: values.reason,
...(values.decision === 'APPROVED' ? { riskLevel: values.riskLevel || undefined } : {}),
corrections:
values.decision === 'CORRECTIONS'
? m.checklist
.filter(
(item) =>
isRequiredDocument(item.documentCode) &&
values[`correction_${item.id}`]?.trim(),
)
.map((item) => ({ itemId: item.id, note: values[`correction_${item.id}`] }))
: [],
})}
submit={(body) =>
action.mutate({ path: `/reviews/${selected.id}/decision`, method: 'POST', body })
}
close={() => setReviewId(null)}
pending={action.isPending}
feedback={action.feedback}
submitLabel={(values) => t(`onboarding.decisions.${values.decision}`)}
/>
)}
</section>
);
}
export function ActivationChecklist({ merchant: m }: { merchant: MerchantDetail }) {
const { t } = useTranslation();
const f = useFormat();
const [edit, setEdit] = useState<string | null>(null);
const action = useAction(m, () => setEdit(null));
const checks = m.activationChecks;
const item = checks.find((check) => check.id === edit);
if (!checks.length && !['INTEGRATION', 'TESTING', 'LIVE'].includes(m.status)) return null;
return (
<section className="surface">
<SectionHeader
title={t('onboarding.activationTitle')}
description={t('onboarding.demoOnly')}
/>
<div className="space-y-4 p-5 sm:p-6">
{action.feedback}
{!checks.length && (
<p className="text-sm text-muted-foreground">{t('onboarding.approvalFirst')}</p>
)}
{checks.map((check) => {
const current = check.reviewId === m.reviews[0]?.id;
const cycle = m.reviews.find((review) => review.id === check.reviewId)?.cycle;
return (
<article key={check.id} className="rounded-lg border p-4">
<div className="flex flex-wrap items-center justify-between gap-3">
<h3 className="text-sm font-semibold">{t(`onboarding.${check.code}`)}</h3>
<span className="rounded-md bg-muted px-2 py-1 text-xs">
{t(`onboarding.${check.state}`)}
</span>
</div>
<p className="mt-1 text-xs text-muted-foreground">
{t(
isIntegrationCheck(check.code) ? 'onboarding.integration' : 'onboarding.testing',
)}{' '}
· {t('workflow.cycle', { cycle })}
{!current ? ` · ${t('onboarding.historicalCheck')}` : ''}
</p>
{check.note && (
<p className="mt-3 whitespace-pre-wrap break-words text-sm">{check.note}</p>
)}
{current && m.capabilities.activationCodes.includes(check.code) ? (
<Button
variant="outline"
className="mt-3"
onClick={() => {
action.reset();
setEdit(check.id);
}}
>
{t('onboarding.updateCheck')}
</Button>
) : (
<p className="mt-3 text-xs text-muted-foreground">{t('onboarding.checkLocked')}</p>
)}
<details className="mt-2 text-xs text-muted-foreground">
<summary className="min-h-11 cursor-pointer py-3">
{t('onboarding.checkHistory')}
</summary>
<ol className="space-y-3">
{check.changes.map((change) => (
<li key={change.id}>
{t(`onboarding.${change.toState}`)} · {change.actor.name} ·{' '}
{f.dateTime(change.occurredAt)}
{change.note && (
<p className="mt-1 whitespace-pre-wrap break-words">{change.note}</p>
)}
</li>
))}
</ol>
</details>
</article>
);
})}
</div>
{item && (
<Editor
title={t('onboarding.updateCheck')}
description={`${t(`onboarding.${item.code}`)}. ${t('onboarding.demoOnly')}`}
fields={[
{
name: 'state',
label: t('onboarding.result'),
options: (isIntegrationCheck(item.code)
? ['INCOMPLETE', 'COMPLETE']
: ['NOT_RUN', 'PASSED', 'FAILED']
).map((value) => ({ value, label: t(`onboarding.${value}`) })),
},
{ name: 'note', label: t('onboarding.checkNote'), type: 'textarea' },
]}
initial={{ state: item.state, note: item.note ?? '' }}
schema={activationEditSchema}
build={(values) => ({
version: m.version,
reviewId: item.reviewId,
state: values.state,
note: values.note || null,
})}
submit={(body) => action.mutate({ path: `/activation-checks/${item.code}`, body })}
close={() => setEdit(null)}
pending={action.isPending}
feedback={action.feedback}
/>
)}
</section>
);
}
+8 -5
View File
@@ -20,7 +20,7 @@ import { useFormat } from '../lib/format';
import { Button, LinkButton } from './shared';
import { Editor, useAction, type Field } from './workflow-form';
export function StageAge({ since }: { since: string }) {
export function StageAge({ since, waiting = false }: { since: string; waiting?: boolean }) {
const { t, i18n } = useTranslation();
const [now, setNow] = useState(() => Date.now());
useEffect(() => {
@@ -30,7 +30,7 @@ export function StageAge({ since }: { since: string }) {
const hours = Math.max(0, Math.floor((now - new Date(since).getTime()) / 3600000));
const duration =
hours < 1
? t('workspace.lessThanHour')
? t(waiting ? 'onboarding.lessThanHour' : 'workspace.lessThanHour')
: new Intl.NumberFormat(i18n.language, {
style: 'unit',
unit: hours >= 24 ? 'day' : 'hour',
@@ -38,7 +38,7 @@ export function StageAge({ since }: { since: string }) {
}).format(hours >= 24 ? Math.floor(hours / 24) : hours);
return (
<span title={new Date(since).toLocaleString(i18n.language)}>
{t('workspace.timeInStage', { duration })}
{t(waiting ? 'onboarding.waitingFor' : 'workspace.timeInStage', { duration })}
</span>
);
}
@@ -197,7 +197,7 @@ export function StageActions({
}}
>
{item.kind === 'REJECT'
? t('workspace.reject')
? t(business ? 'onboarding.businessClosure' : 'workspace.reject')
: item.kind === 'REVIEW'
? t('workflow.decide')
: t('workflow.advance', { stage: t(`statuses.${item.toStatus}`) })}
@@ -208,6 +208,9 @@ export function StageActions({
{item.blockingReasons.map((reason) => (
<li key={reason.code}>
{t(`workspace.blockers.${reason.code}`)}
{reason.items?.length
? ` ${reason.items.map((code) => t(reason.code === 'DOCUMENTS_REQUIRED' ? `documents.${code}` : `onboarding.${code}`)).join(', ')}.`
: ''}
{reason.fields?.length
? ` ${reason.fields.map((field) => t(`workflow.${field}`)).join(', ')}.`
: ''}
@@ -221,7 +224,7 @@ export function StageActions({
{!reject && action.feedback}
{reject && (
<Editor
title={t('workspace.reject')}
title={t(business ? 'onboarding.businessClosure' : 'workspace.reject')}
description={t(business ? 'workspace.businessReasonHint' : 'workspace.rejectHint')}
fields={[
{
+3 -1
View File
@@ -75,14 +75,16 @@ export function LinkButton({
children,
variant = 'default',
className,
state,
}: {
to: string;
state?: { returnTo: string };
children: ReactNode;
variant?: 'default' | 'outline' | 'ghost';
className?: string;
}) {
return (
<Link to={to} className={cn(buttonVariants({ variant }), className)}>
<Link to={to} state={state} className={cn(buttonVariants({ variant }), className)}>
{children}
</Link>
);
+17 -5
View File
@@ -26,7 +26,8 @@ export type Field = {
type EditorProps = {
title: string;
description?: string;
fields: Field[];
fields: Field[] | ((values: Record<string, string>) => Field[]);
submitLabel?: string | ((values: Record<string, string>) => string);
initial: Record<string, string>;
schema: z.ZodType;
build: (values: Record<string, string>) => unknown;
@@ -46,10 +47,13 @@ export function Editor({
close,
pending,
feedback,
submitLabel,
}: EditorProps) {
const { t } = useTranslation();
const id = useId();
const form = useForm<Record<string, string>>({ defaultValues: initial });
const values = form.watch();
const visibleFields = typeof fields === 'function' ? fields(values) : fields;
const [errors, setErrors] = useState<Record<string, string>>({});
return (
<Sheet
@@ -76,7 +80,7 @@ export function Editor({
issue.message.startsWith('validation.') ? issue.message : 'validation.invalid',
);
setErrors(messages);
const first = fields.find((field) => messages[field.name]);
const first = visibleFields.find((field) => messages[field.name]);
if (first) form.setFocus(first.name);
return;
}
@@ -86,7 +90,7 @@ export function Editor({
>
{feedback}
<fieldset disabled={pending} className="space-y-5">
{fields.map((field) => {
{visibleFields.map((field) => {
const fieldId = `${id}-${field.name}`;
const props = {
id: fieldId,
@@ -122,13 +126,21 @@ export function Editor({
</FormField>
);
})}
{Object.keys(errors).some((key) => !fields.some((field) => field.name === key)) && (
{Object.keys(errors).some(
(key) => !visibleFields.some((field) => field.name === key),
) && (
<p role="alert" className="text-sm text-destructive">
{t('errors.VALIDATION_ERROR')}
</p>
)}
<div className="flex flex-wrap gap-3 border-t pt-5">
<Button type="submit">{t(pending ? 'workflow.saving' : 'workflow.save')}</Button>
<Button type="submit">
{pending
? t('workflow.saving')
: typeof submitLabel === 'function'
? submitLabel(values)
: (submitLabel ?? t('workflow.save'))}
</Button>
<Button type="button" variant="outline" onClick={close}>
{t('workflow.cancel')}
</Button>
+11
View File
@@ -0,0 +1,11 @@
import { expect, it } from 'vitest';
import { reviewParams } from './review-params';
it('preserves shareable review filters and drops invalid or unrelated inputs', () => {
expect(
reviewParams(new URLSearchParams('search=Acme&ownerId=unassigned&waiting=72')).toString(),
).toBe('search=Acme&ownerId=unassigned&waiting=72');
expect(reviewParams(new URLSearchParams('waiting=25&status=LIVE&ownerId=')).toString()).toBe('');
expect(reviewParams(new URLSearchParams('search=' + 'x'.repeat(101))).get('search')).toHaveLength(
100,
);
});
+11
View File
@@ -0,0 +1,11 @@
import { reviewQueueQuerySchema } from '@merchantflow/contracts';
export function reviewParams(input: URLSearchParams) {
const result = new URLSearchParams();
const search = input.get('search')?.slice(0, 100);
if (search) result.set('search', search);
for (const key of ['ownerId', 'waiting'] as const) {
const parsed = reviewQueueQuerySchema.shape[key].safeParse(input.get(key) ?? undefined);
if (parsed.success && parsed.data && parsed.data !== 'ALL') result.set(key, parsed.data);
}
return result;
}
+10 -5
View File
@@ -1,7 +1,9 @@
import { onboardingEn, onboardingRu } from './onboarding-locales';
import { salesEn, salesRu } from './sales-locales';
import { workflowEn, workflowRu } from './workflow-locales';
import { landingEn, landingRu } from './landing-locales';
export const en = {
onboarding: onboardingEn,
workflow: workflowEn,
workspace: salesEn,
common: {
@@ -169,7 +171,7 @@ export const en = {
overview: 'Merchant overview',
details: 'The essentials, all together.',
checklist: 'KYB checklist',
checklistText: 'Document readiness for the next review.',
checklistText: 'Sales collection records and notes for the next review. No file uploads.',
notes: 'Team notes',
notesText: 'Context from the people closest to the relationship.',
history: 'Journey history',
@@ -182,8 +184,9 @@ export const en = {
noTasks: 'No related tasks yet',
},
documents: {
INCORPORATION: 'Certificate of incorporation',
INCORPORATION: 'Company registration',
OWNERSHIP: 'Ownership structure',
AUTHORIZED_REPRESENTATIVE: 'Authorized representative identification',
UBO_IDENTIFICATION: 'Beneficial owner identification',
BUSINESS_ACTIVITY: 'Business activity description',
},
@@ -229,10 +232,11 @@ export const en = {
empty: 'The queue is clear',
emptyText: 'Merchants appear here when they reach Compliance Review.',
entered: 'Entered review',
view: 'View checklist',
view: 'Open review',
},
};
export const ru = {
onboarding: onboardingRu,
workflow: workflowRu,
workspace: salesRu,
common: {
@@ -401,7 +405,7 @@ export const ru = {
overview: 'О мерчанте',
details: 'Главное — в одном месте.',
checklist: 'Чек-лист KYB',
checklistText: 'Готовность документов к следующей проверке.',
checklistText: 'Статусы и заметки о сборе KYB отделом продаж. Без загрузки файлов.',
notes: 'Заметки команды',
notesText: 'Контекст от тех, кто работает с мерчантом.',
history: 'История этапов',
@@ -414,6 +418,7 @@ export const ru = {
noTasks: 'Связанных задач пока нет',
},
documents: {
AUTHORIZED_REPRESENTATIVE: 'Идентификация уполномоченного представителя',
INCORPORATION: 'Свидетельство о регистрации',
OWNERSHIP: 'Структура собственности',
UBO_IDENTIFICATION: 'Идентификация бенефициаров',
@@ -465,6 +470,6 @@ export const ru = {
empty: 'Очередь пуста',
emptyText: 'Мерчанты появятся здесь на этапе комплаенс-проверки.',
entered: 'Начало проверки',
view: 'Открыть чек-лист',
view: 'Открыть проверку',
},
};
+145
View File
@@ -0,0 +1,145 @@
export const onboardingEn = {
nextStep: 'Next step',
nextOwner: 'Next owner',
requiredAction: 'Required action',
noNextOwner: 'No further handoff',
actions: {
ASSIGN: 'Head of Sales must assign a manager before onboarding can continue.',
COMMERCIAL: 'Complete the commercial prerequisites shown below.',
COLLECT: 'Collect the three required KYB items, record notes, and submit to Compliance.',
REVIEW:
'Compliance must review the submitted evidence and record a decision. Collection is locked.',
INTEGRATE: 'Record the API connection and webhook setup demo checks, then advance to Testing.',
TEST: 'Record passing test-payment and reconciliation demo checks, then advance to Live.',
REOPEN_KYB:
'This earlier approval does not cover the current requirements. Return to KYB and submit a new review.',
COMPLETE: 'Onboarding is closed. The recorded history remains available.',
},
reopen: 'Return to KYB for re-review',
businessClosure: 'Close for business reason',
legacyItem: 'Historical requirement · read only',
correctionNote: 'Compliance correction',
complianceOnly:
'Compliance owns assessment and decisions. Sales owns collection and commercial onboarding.',
legacyReview:
'This review uses earlier requirements. Request changes so Sales can collect authorized-representative identification and resubmit, or reject with a reason.',
legacyCycle: 'Earlier requirements · retained as history',
noReviews: 'No submission yet. Sales must complete the KYB collection checklist.',
submittedEvidence: 'Evidence submitted for this cycle',
riskLevel: 'Risk level',
chooseRisk: 'Select a risk level',
risk: { LOW: 'Low', MEDIUM: 'Medium', HIGH: 'High' },
decisions: { APPROVED: 'Approve', CORRECTIONS: 'Request changes', REJECTED: 'Reject' },
reason: {
APPROVED: 'Approval rationale (required)',
CORRECTIONS: 'Required changes (required)',
REJECTED: 'Rejection reason (required)',
},
activationTitle: 'Commercial activation · demo checks',
demoOnly:
'Manually recorded demo checks. No payment is executed and no external processing service is called.',
approvalFirst: 'A current Compliance approval is required before demo checks can be recorded.',
integration: 'Integration',
testing: 'Testing',
API_CONNECTION: 'API connection',
WEBHOOK_SETUP: 'Webhook setup',
TEST_PAYMENT: 'Test payment',
RECONCILIATION: 'Reconciliation',
INCOMPLETE: 'Incomplete',
COMPLETE: 'Complete',
NOT_RUN: 'Not run',
PASSED: 'Passed',
FAILED: 'Failed',
updateCheck: 'Update demo check',
checkNote: 'Demo check notes',
result: 'Result',
checkHistory: 'Check history',
historicalCheck: 'Historical evidence',
checkLocked: 'Read only outside this check’s stage and approval cycle.',
checkUpdated: 'Demo check updated: {{check}}',
collectionPending: 'Collection is locked while Compliance reviews this submission.',
collectionLocked:
'Only Head or the assigned Manager can maintain collection while the merchant is in KYB.',
queueFilters: 'Compliance queue filters',
search: 'Search merchants',
waitingTime: 'Waiting time',
waitingFor: 'Waiting {{duration}}',
waiting: { ALL: 'Any waiting time', '24': 'At least 24 hours', '72': 'At least 72 hours' },
lessThanHour: 'less than 1 hour',
filteredCount: '{{count}} matching reviews',
filteredCount_one: '{{count}} matching review',
};
export const onboardingRu = {
nextStep: 'Следующий шаг',
nextOwner: 'Кто действует дальше',
requiredAction: 'Необходимое действие',
noNextOwner: 'Передача не требуется',
actions: {
ASSIGN: 'Руководитель продаж должен назначить менеджера для продолжения онбординга.',
COMMERCIAL: 'Выполните коммерческие условия, указанные ниже.',
COLLECT:
'Соберите три обязательных пункта KYB, добавьте заметки и отправьте на комплаенс-проверку.',
REVIEW: 'Комплаенс должен проверить отправленные данные и записать решение. Сбор заблокирован.',
INTEGRATE: 'Отметьте демо-проверки API и вебхуков, затем перейдите к тестированию.',
TEST: 'Отметьте успешные демо-проверки тестового платежа и сверки, затем запустите мерчанта.',
REOPEN_KYB:
'Предыдущее одобрение не покрывает текущие требования. Вернитесь в KYB и отправьте новую проверку.',
COMPLETE: 'Онбординг завершён. История остаётся доступной.',
},
reopen: 'Вернуть в KYB для повторной проверки',
businessClosure: 'Закрыть по бизнес-причине',
legacyItem: 'Прежнее требование · только чтение',
correctionNote: 'Замечание комплаенса',
complianceOnly:
'Комплаенс отвечает за оценку и решения. Продажи — за сбор и коммерческий онбординг.',
legacyReview:
'Эта проверка использует прежние требования. Запросите исправления для сбора идентификации уполномоченного представителя и повторной отправки либо отклоните с причиной.',
legacyCycle: 'Прежние требования · сохранено в истории',
noReviews: 'Пока нет отправок. Продажи должны заполнить чек-лист сбора KYB.',
submittedEvidence: 'Данные, отправленные в этом цикле',
riskLevel: 'Уровень риска',
chooseRisk: 'Выберите уровень риска',
risk: { LOW: 'Низкий', MEDIUM: 'Средний', HIGH: 'Высокий' },
decisions: { APPROVED: 'Одобрить', CORRECTIONS: 'Запросить исправления', REJECTED: 'Отклонить' },
reason: {
APPROVED: 'Обоснование одобрения (обязательно)',
CORRECTIONS: 'Необходимые исправления (обязательно)',
REJECTED: 'Причина отклонения (обязательно)',
},
activationTitle: 'Коммерческий запуск · демо-проверки',
demoOnly:
'Демо-проверки отмечаются вручную. Платежи не выполняются, внешние платёжные сервисы не вызываются.',
approvalFirst: 'Для демо-проверок необходимо актуальное одобрение комплаенса.',
integration: 'Интеграция',
testing: 'Тестирование',
API_CONNECTION: 'Подключение API',
WEBHOOK_SETUP: 'Настройка вебхуков',
TEST_PAYMENT: 'Тестовый платёж',
RECONCILIATION: 'Сверка',
INCOMPLETE: 'Не завершено',
COMPLETE: 'Завершено',
NOT_RUN: 'Не выполнялось',
PASSED: 'Пройдено',
FAILED: 'Не пройдено',
updateCheck: 'Обновить демо-проверку',
checkNote: 'Заметки демо-проверки',
result: 'Результат',
checkHistory: 'История проверки',
historicalCheck: 'Исторические данные',
checkLocked: 'Изменения доступны только на этапе этой проверки и в текущем цикле одобрения.',
checkUpdated: 'Демо-проверка обновлена: {{check}}',
collectionPending: 'Сбор заблокирован, пока комплаенс проверяет эту отправку.',
collectionLocked: 'Сбор на этапе KYB ведёт только руководитель или назначенный менеджер.',
queueFilters: 'Фильтры очереди комплаенса',
search: 'Поиск мерчантов',
waitingTime: 'Время ожидания',
waitingFor: 'Ожидание: {{duration}}',
waiting: { ALL: 'Любое время ожидания', '24': 'Не менее 24 часов', '72': 'Не менее 72 часов' },
lessThanHour: 'менее 1 часа',
filteredCount: 'Подходящих проверок: {{count}}',
filteredCount_one: 'Подходящая проверка: {{count}}',
} satisfies {
[K in keyof typeof onboardingEn]: (typeof onboardingEn)[K] extends string
? string
: Record<keyof (typeof onboardingEn)[K], string>;
};
+108 -30
View File
@@ -1,3 +1,5 @@
import { ActivationChecklist, OnboardingHandoff } from '../components/onboarding';
import { reviewParams } from '../lib/review-params';
import {
MerchantControls,
ChecklistControl,
@@ -32,7 +34,7 @@ import {
dashboardSchema,
merchantListSchema,
merchantDetailSchema,
pipelineSchema,
reviewQueueSchema,
pipelineBoardSchema,
merchantFiltersSchema,
taskListSchema,
@@ -599,6 +601,7 @@ export function MerchantDetail() {
</p>
</div>
</div>
<OnboardingHandoff merchant={m} />
<MerchantControls merchant={m} />
<div
role="tablist"
@@ -728,6 +731,15 @@ export function MerchantDetail() {
title={t('merchants.checklist')}
description={t('merchants.checklistText')}
/>
{!m.capabilities.collectChecklist && (
<p className="px-5 pt-4 text-sm text-muted-foreground sm:px-6">
{t(
m.status === 'COMPLIANCE_REVIEW'
? 'onboarding.collectionPending'
: 'onboarding.collectionLocked',
)}
</p>
)}
<div className="mt-4">
{m.checklist.map((doc) => (
<div key={doc.id} className="flex gap-3 border-t px-5 py-4 sm:px-6">
@@ -770,6 +782,7 @@ export function MerchantDetail() {
))}
</div>
</section>
<ActivationChecklist merchant={m} />
</>
)}
{tab === 'tasks' && <MerchantTasks merchant={m} />}
@@ -919,12 +932,21 @@ export function ReviewQueue() {
const user = useOutletContext<User>();
const { t } = useTranslation();
const f = useFormat();
const [params, setParams] = useSearchParams();
const filters = reviewParams(params);
const serialized = filters.toString();
const allowed = canSeeReviewQueue(user.role);
const query = useQuery({
queryKey: ['review-queue'],
queryFn: ({ signal }) => api('/review-queue', pipelineSchema, { signal }),
queryKey: ['review-queue', serialized],
queryFn: ({ signal }) => api(`/review-queue?${serialized}`, reviewQueueSchema, { signal }),
enabled: allowed,
});
const update = (key: string, value: string) => {
const next = new URLSearchParams(filters);
if (value && value !== 'ALL') next.set(key, value);
else next.delete(key);
setParams(next, { replace: key === 'search' });
};
if (!allowed) return <NotFound forbidden />;
return (
<>
@@ -933,59 +955,115 @@ export function ReviewQueue() {
description={t('review.description')}
eyebrow={t('review.eyebrow')}
/>
<section aria-label={t('onboarding.queueFilters')} className="mb-5 grid gap-3 sm:grid-cols-3">
<label className="space-y-2 text-xs text-muted-foreground">
<span>{t('onboarding.search')}</span>
<Input
value={filters.get('search') ?? ''}
maxLength={100}
onChange={(event) => update('search', event.target.value)}
/>
</label>
<label className="space-y-2 text-xs text-muted-foreground">
<span>{t('common.owner')}</span>
<NativeSelect
className="w-full"
value={filters.get('ownerId') ?? ''}
onChange={(event) => update('ownerId', event.target.value)}
>
<option value="">{t('workspace.allOwners')}</option>
<option value="unassigned">{t('workflow.unassigned')}</option>
{query.data?.owners.map((owner) => (
<option key={owner.id} value={owner.id}>
{owner.name}
</option>
))}
</NativeSelect>
</label>
<label className="space-y-2 text-xs text-muted-foreground">
<span>{t('onboarding.waitingTime')}</span>
<NativeSelect
className="w-full"
value={filters.get('waiting') ?? 'ALL'}
onChange={(event) => update('waiting', event.target.value)}
>
{['ALL', '24', '72'].map((value) => (
<option key={value} value={value}>
{t(`onboarding.waiting.${value}`)}
</option>
))}
</NativeSelect>
</label>
</section>
<QueryBoundary query={query}>
{(merchants) => (
{(data) => (
<section className="surface overflow-hidden">
<div className="flex flex-wrap items-center justify-between gap-2 border-b px-5 py-5 sm:px-6">
<h2 className="text-sm font-semibold">
{t('review.count', { count: merchants.length })}
</h2>
<span className="inline-flex items-center gap-1.5 text-xs text-muted-foreground">
<Clock3 className="size-3.5" />
<div className="flex flex-wrap items-center justify-between gap-3 border-b p-5 sm:p-6">
<div>
<h2 className="text-sm font-semibold">
{t('review.count', { count: data.pendingCount })}
</h2>
<p className="mt-1 text-xs text-muted-foreground" role="status">
{t('onboarding.filteredCount', { count: data.filteredCount })}
</p>
</div>
<span className="inline-flex items-center gap-2 text-xs text-muted-foreground">
<Clock3 className="size-4" />
{t('review.order')}
</span>
{serialized && (
<Button variant="ghost" onClick={() => setParams({})}>
{t('common.clear')}
</Button>
)}
</div>
{merchants.length ? (
merchants.map((m) => (
<div
key={m.id}
{data.items.length ? (
data.items.map((review) => (
<article
key={review.id}
className="flex flex-col gap-5 border-b p-5 last:border-0 sm:flex-row sm:items-center sm:justify-between sm:p-6"
>
<div className="flex items-center gap-3">
<Avatar name={m.name} />
<div>
<div className="flex min-w-0 items-center gap-3">
<Avatar name={review.merchant.name} />
<div className="min-w-0">
<Link
to={`/app/merchants/${m.id}`}
className="text-sm font-semibold hover:underline"
className="break-words text-sm font-semibold hover:underline"
to={`/app/merchants/${review.merchant.id}?tab=onboarding#review-${review.id}`}
state={{ returnTo: `/app/review-queue?${serialized}` }}
>
{m.name}
{review.merchant.name}
</Link>
<p className="mt-1 text-xs text-muted-foreground">
{m.owner?.name ?? t('workflow.unassigned')} ·{' '}
{m.industry ? t(`industry.${m.industry}`) : '—'}
{review.merchant.owner?.name ?? t('workflow.unassigned')} ·{' '}
{t('workflow.cycle', { cycle: review.cycle })}
</p>
</div>
</div>
<div className="flex flex-wrap items-center justify-between gap-4">
<div>
<p className="mb-1 text-[10px] text-muted-foreground">
{t('review.entered')}
<p className="text-sm">
<StageAge since={review.submittedAt} waiting />
</p>
<p className="mt-1 text-xs text-muted-foreground">
{f.dateTime(review.submittedAt)}
</p>
<p className="text-xs">{f.date(m.stageEnteredAt)}</p>
</div>
<LinkButton
to={`/app/merchants/${m.id}#checklist`}
to={`/app/merchants/${review.merchant.id}?tab=onboarding#review-${review.id}`}
state={{ returnTo: `/app/review-queue?${serialized}` }}
variant="outline"
className="text-xs"
>
{t('review.view')}
<ArrowRight className="size-3.5" />
<ArrowRight className="size-4" />
</LinkButton>
</div>
</div>
</article>
))
) : (
<EmptyState title={t('review.empty')} description={t('review.emptyText')} />
<EmptyState
title={t(serialized ? 'common.noResults' : 'review.empty')}
description={t(serialized ? 'common.noResultsText' : 'review.emptyText')}
/>
)}
</section>
)}
+6 -2
View File
@@ -34,10 +34,12 @@ export const salesEn = {
ASSIGNMENT_REQUIRED: 'Assign a manager before progressing.',
CONTACT_REQUIRED: 'Log a call or email before moving to Contacted.',
QUALIFICATION_INCOMPLETE: 'Complete the following fields:',
DOCUMENTS_REQUIRED: 'Receive all four KYB documents before submitting for review.',
DOCUMENTS_REQUIRED: 'Receive all three required KYB items before submitting for review.',
REVIEW_PENDING: 'A single pending review is required; check the onboarding section.',
APPROVAL_REQUIRED: 'Matching compliance approval and document evidence are required.',
COMPLIANCE_ONLY: 'Only Compliance can decide the outcome of this review.',
ACTIVATION_CHECKS_REQUIRED: 'Complete the required demo checks:',
POLICY_UPGRADE_REQUIRED: 'Return to KYB for a new review under the current requirements.',
SALES_ONLY: 'Only the Head or assigned manager can advance commercial stages.',
},
};
@@ -76,10 +78,12 @@ export const salesRu = {
ASSIGNMENT_REQUIRED: 'Назначьте менеджера для перехода дальше.',
CONTACT_REQUIRED: 'Запишите звонок или письмо перед переходом к контакту.',
QUALIFICATION_INCOMPLETE: 'Заполните следующие поля:',
DOCUMENTS_REQUIRED: 'Получите все четыре документа KYB перед отправкой на проверку.',
DOCUMENTS_REQUIRED: 'Получите все три обязательных пункта KYB перед отправкой на проверку.',
REVIEW_PENDING: 'Нужна одна активная проверка. Откройте раздел онбординга.',
APPROVAL_REQUIRED: 'Нужны актуальное одобрение комплаенса и история документов.',
COMPLIANCE_ONLY: 'Только комплаенс может принять решение по проверке.',
ACTIVATION_CHECKS_REQUIRED: 'Выполните обязательные демо-проверки:',
POLICY_UPGRADE_REQUIRED: 'Вернитесь в KYB для новой проверки по текущим требованиям.',
SALES_ONLY: 'Коммерческие этапы меняет руководитель или назначенный менеджер.',
},
} satisfies {
+8 -8
View File
@@ -23,10 +23,10 @@ export const workflowEn = {
advance: 'Move to {{stage}}',
identityLocked:
'Reviewed company and KYB information is locked. Contact and commercial details can still be updated.',
checklistEdit: 'Update document',
checklistHistory: 'Document history',
state: 'Document status',
note: 'Note',
checklistEdit: 'Update collection',
checklistHistory: 'Collection history',
state: 'Collection status',
note: 'Collection notes',
reviews: 'Compliance reviews',
decide: 'Record decision',
decision: 'Decision',
@@ -105,10 +105,10 @@ export const workflowRu: Record<keyof typeof workflowEn, string> = {
advance: 'Перевести: {{stage}}',
identityLocked:
'Проверенные данные компании и KYB защищены от изменений. Контактные и коммерческие данные можно обновлять.',
checklistEdit: 'Обновить документ',
checklistHistory: 'История документа',
state: 'Статус документа',
note: 'Заметка',
checklistEdit: 'Обновить сбор',
checklistHistory: 'История сбора',
state: 'Статус сбора',
note: 'Заметки о сборе',
reviews: 'Комплаенс-проверки',
decide: 'Записать решение',
decision: 'Решение',