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
+19 -4
View File
@@ -94,7 +94,7 @@ The landing page at `/` is mobile-first and available in English and Russian, wi
The shared schema trims names, lowercases email, validates country/industry codes and HTTP(S) websites, and accepts scheme-less websites by adding HTTPS. USD amounts remain decimal strings, from zero to `999999999999.99`, with at most two fractional digits; decimal commas are accepted without thousands separators. Email providers are not blocked or externally verified. Unexpected business fields are rejected. The shared schema trims names, lowercases email, validates country/industry codes and HTTP(S) websites, and accepts scheme-less websites by adding HTTPS. USD amounts remain decimal strings, from zero to `999999999999.99`, with at most two fractional digits; decimal commas are accepted without thousands separators. Email providers are not blocked or externally verified. Unexpected business fields are rejected.
A successful request returns **202 `{ "ok": true }`** and atomically creates an unassigned `NEW_LEAD`, source `LANDING_PAGE`, four missing KYB items, an initial stage event and an immutable creation activity. Public creation has a null actor, displayed as System/Система; staff actions retain their authenticated actor. Existing role scopes and assignment requirements apply immediately. A successful request returns **202 `{ "ok": true }`** and atomically creates an unassigned `NEW_LEAD`, source `LANDING_PAGE`, three missing KYB checklist records, an initial stage event and an immutable creation activity. Public creation has a null actor, displayed as System/Система; staff actions retain their authenticated actor. Existing role scopes and assignment requirements apply immediately.
A unique database submission key and normalized payload hash protect retries across concurrency and restarts. Reusing the key with the same payload returns the same response; a changed payload returns `409 IDEMPOTENCY_CONFLICT`. Keys and hashes are not exposed by CRM responses. The frontend reuses its key for unchanged retries, including uncertain network failures; changing normalized business details selects another key. Form values and keys stay in component memory, so navigating away or reloading starts a fresh form. A unique database submission key and normalized payload hash protect retries across concurrency and restarts. Reusing the key with the same payload returns the same response; a changed payload returns `409 IDEMPOTENCY_CONFLICT`. Keys and hashes are not exposed by CRM responses. The frontend reuses its key for unchanged retries, including uncertain network failures; changing normalized business details selects another key. Form values and keys stay in component memory, so navigating away or reloading starts a fresh form.
@@ -142,9 +142,9 @@ The [product brief](docs/product-brief.md) and [implementation checklist](docs/i
Head of Sales can edit commercial details for the portfolio, assign/reassign Account Managers, collect KYB documents, and manage commercial activities/tasks. Managers can perform commercial actions only for currently assigned merchants and cannot change ownership. Compliance can read merchant context and KYB across every stage, record reviews and KYB notes, and manage only personal compliance tasks. Head and managers can view related compliance tasks but cannot change them. Query predicates enforce these scopes on lists, search, totals, dashboard, detail children, and mutation targets. Head of Sales can edit commercial details for the portfolio, assign/reassign Account Managers, collect KYB documents, and manage commercial activities/tasks. Managers can perform commercial actions only for currently assigned merchants and cannot change ownership. Compliance can read merchant context and KYB across every stage, record reviews and KYB notes, and manage only personal compliance tasks. Head and managers can view related compliance tasks but cannot change them. Query predicates enforce these scopes on lists, search, totals, dashboard, detail children, and mutation targets.
Only adjacent commercial stage advances are accepted. A manager must be assigned before leaving New Lead. Contacted requires a logged call or email. Qualified requires company name, website, contact name/email, country, industry and an estimated volume; zero is valid. In KYB, Sales records missing/received documents. Submission requires all four documents to have received-history evidence and creates one pending review. Company/KYB fields freeze while that review is pending. Compliance can approve (atomically advancing to Integration), reject with a reason, or request document-specific corrections (returning to KYB). Resubmission creates a new review cycle. Decisions and system history cannot be edited. Only adjacent commercial stage advances are accepted, plus the explicit legacy return-to-KYB action described below. A manager must be assigned before leaving New Lead. Contacted requires a logged call or email. Qualified requires company name, website, contact name/email, country, industry and an estimated volume; zero is valid. In KYB, Head or the assigned Manager records Missing/Received status and collection notes for company registration, ownership structure and authorized-representative identification. These are checklist records, with no uploads. Submission requires all three required checklist records to have received-history evidence and creates one pending review. Company/KYB fields freeze while that review is pending. Compliance can approve with Low/Medium/High risk and a required rationale (atomically advancing to Integration), reject with a reason, or request item-specific corrections stored with the review, separately from collection notes (returning to KYB). Resubmission creates a new review cycle. Decisions and system history cannot be edited.
Approval permanently locks the reviewed company identity, website, country, industry and KYB items in this milestone. Contact details, estimated volume, source and authorized assignment remain editable. Either the Head or assigned manager may move Integration → Testing → Live when the current company/checklist matches valid approval evidence. Live and Rejected have no outgoing stage actions. Reassignment transfers open commercial tasks to the new manager; completed task attribution and Compliance ownership remain intact. Current-policy approval locks the reviewed company identity, website, country, industry and KYB items in this milestone. Contact details, estimated volume, source and authorized assignment remain editable. Either the Head or assigned manager may move Integration → Testing → Live when the current company/checklist matches the latest valid approval and the stage’s demo checks are complete. Integration requires API connection and webhook setup marked Complete; Testing requires test payment and reconciliation marked Passed. Checks retain their own notes and change history and are bound to that review cycle. Updates are allowed only in the corresponding stage; no real payments or external services are called. Live and Rejected have no outgoing stage actions. Reassignment transfers open commercial tasks to the new manager; completed task attribution and Compliance ownership remain intact.
All mutation bodies carry the merchant's current integer `version`. Transactions conditionally claim that version and recheck database ownership before writing the merchant or any child records. A stale action returns `409 CONFLICT`; the UI refreshes before another attempt. Hidden resources return 404, forbidden visible actions return 403, and invalid workflow actions return 409. General edits reject unexpected fields such as owner, stage, actor or reviewer. All mutation bodies carry the merchant's current integer `version`. Transactions conditionally claim that version and recheck database ownership before writing the merchant or any child records. A stale action returns `409 CONFLICT`; the UI refreshes before another attempt. Hidden resources return 404, forbidden visible actions return 403, and invalid workflow actions return 409. General edits reject unexpected fields such as owner, stage, actor or reviewer.
@@ -169,7 +169,7 @@ The old manager account IDs are retained while the original addresses become `al
## Daily sales workspace ## Daily sales workspace
Head can add merchants from the directory and optionally assign a manager. Managers create merchants assigned to themselves. Company name, contact name and email are required; website, country, industry and volume can be supplied later. Compliance has no creation access. New leads begin at `NEW_LEAD` with four missing KYB items and an attributed creation history. The API rejects caller-supplied stage, audit identity and public-submission fields. Head can add merchants from the directory and optionally assign a manager. Managers create merchants assigned to themselves. Company name, contact name and email are required; website, country, industry and volume can be supplied later. Compliance has no creation access. New leads begin at `NEW_LEAD` with three missing KYB checklist records and an attributed creation history. The API rejects caller-supplied stage, audit identity and public-submission fields.
Directory search matches company/legal name, contact name, email and website. `status`, ISO `country`, canonical `industry`, and `ownerId` combine with search. Head and Compliance may use `ownerId=unassigned` or a manager ID. Manager owner filters return 403. All records, totals and filter options use the same authorization scope. Results retain eight-record pages and clamp excessive page numbers to the last available page. Search, filters and pagination survive URL sharing, reload and browser navigation. Directory search matches company/legal name, contact name, email and website. `status`, ISO `country`, canonical `industry`, and `ownerId` combine with search. Head and Compliance may use `ownerId=unassigned` or a manager ID. Manager owner filters return 403. All records, totals and filter options use the same authorization scope. Results retain eight-record pages and clamp excessive page numbers to the last available page. Search, filters and pagination survive URL sharing, reload and browser navigation.
@@ -188,3 +188,18 @@ Merchant detail uses `?tab=overview|activity|onboarding|tasks`; existing `#check
The desktop pipeline has horizontally scrollable stage columns, including Rejected. Mobile displays only the selected `?stage=` with counts and merchant cards. Explicit progression and rejection actions are available on cards and detail pages. API-provided explanations appear next to blocked controls. EN/RU labels, keyboard tabs, focus handling, touch targets and reduced-motion support are retained. The desktop pipeline has horizontally scrollable stage columns, including Rejected. Mobile displays only the selected `?stage=` with counts and merchant cards. Explicit progression and rejection actions are available on cards and detail pages. API-provided explanations appear next to blocked controls. EN/RU labels, keyboard tabs, focus handling, touch targets and reduced-motion support are retained.
Migration `202609240004_sales_workspace` only makes website, country and industry nullable. Apply with `pnpm db:migrate`; no reseed or database reset is required. Public consultation validation remains fully required and unchanged. Migration `202609240004_sales_workspace` only makes website, country and industry nullable. Apply with `pnpm db:migrate`; no reseed or database reset is required. Public consultation validation remains fully required and unchanged.
### Gated onboarding API and upgrades
Current review policy version 2 requires exactly three active KYB records. `documentCodes` retains legacy codes for historical reads; `requiredDocumentCodes` defines the current creation/submission requirements. The latest approved cycle must have a Compliance reviewer, valid timestamps, risk, rationale, received-history evidence and matching company/checklist snapshot. Any pending cycle invalidates activation.
| Method | Route | Contract |
| ------ | ---------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| GET | `/api/review-queue?search=…&ownerId=…&waiting=ALL\|24\|72` | Compliance only; `{items, pendingCount, filteredCount, owners}`. Each item contains review ID, cycle, policy version, submitted timestamp and merchant. Oldest submitted first. `ownerId=unassigned` is supported. |
| POST | `/api/merchants/:id/reviews/:reviewId/decision` | `{version, decision, reason, riskLevel?, corrections?}`. Approval requires risk and rationale; corrections require `{itemId,note}` entries; rejection requires a reason. Only the latest pending cycle is decidable. |
| PATCH | `/api/merchants/:id/activation-checks/:code` | `{version, reviewId, state, note}`. Codes: API_CONNECTION, WEBHOOK_SETUP, TEST_PAYMENT, RECONCILIATION. Integration states: INCOMPLETE/COMPLETE; testing states: NOT_RUN/PASSED/FAILED. |
| POST | `/api/merchants/:id/reopen-kyb` | `{version}`. Head or assigned Manager may return legacy Integration/Testing records without a pending review to KYB. |
Merchant detail includes review snapshots, risk and immutable correction notes, activation check history, and server-derived handoff/edit capabilities. Review links use `?tab=onboarding#review-<id>` and remain valid after decisions.
Apply the two new additive migrations with `pnpm db:migrate`; do not reset or reseed development data. Old review cycles retain policy version 1 and their original evidence. Legacy beneficial-owner ID and business-activity items become read-only historical requirements. Unfinished merchants receive a new Missing representative-identification record; terminal records remain untouched. Old pending reviews require corrections/resubmission or rejection. Old approvals cannot authorize further activation: use Return to KYB for re-review. Existing decisions, notes, timestamps and passwords are preserved, and no risk or demo results are inferred for existing fixtures. Fresh fixtures include current-policy approval/check evidence; seed reruns preserve existing records.
+42 -4
View File
@@ -1,7 +1,8 @@
import type { User } from '@merchantflow/contracts'; import type { User } from '@merchantflow/contracts';
import type { Prisma } from '@merchantflow/database'; import type { Prisma } from '@merchantflow/database';
import type { Capabilities } from '@merchantflow/contracts'; 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'; import { ApiError } from './shared.js';
export function merchantScope(user: User): Prisma.MerchantWhereInput { export function merchantScope(user: User): Prisma.MerchantWhereInput {
switch (user.role) { switch (user.role) {
@@ -29,16 +30,53 @@ export function capabilities(user: User, merchant: Evidence): Capabilities {
const sales = const sales =
user.role === 'HEAD_OF_SALES' || user.role === 'HEAD_OF_SALES' ||
(user.role === 'ACCOUNT_MANAGER' && merchant.ownerId === user.id); (user.role === 'ACCOUNT_MANAGER' && merchant.ownerId === user.id);
const locked = merchant.reviews.some((review) => const locked =
['PENDING', 'APPROVED'].includes(review.decision), 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 actions = workflowActions(user, merchant);
const terminal = ['LIVE', 'REJECTED'].includes(merchant.status);
const reopen = canReopenKyb(merchant);
return { return {
editCommercial: sales, editCommercial: sales,
editIdentity: sales && !locked, editIdentity: sales && !locked,
assign: user.role === 'HEAD_OF_SALES', assign: user.role === 'HEAD_OF_SALES',
collectChecklist: sales && merchant.status === 'KYB' && !locked, collectChecklist: sales && merchant.status === 'KYB' && !locked,
review: user.role === 'COMPLIANCE_OFFICER' && merchant.status === 'COMPLIANCE_REVIEW', 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: activityKinds:
user.role === 'COMPLIANCE_OFFICER' user.role === 'COMPLIANCE_OFFICER'
? (['KYB_NOTE'] as const) ? (['KYB_NOTE'] as const)
+67 -8
View File
@@ -1,6 +1,11 @@
import { Controller, Get, Inject, Param, Query, Req, UseGuards } from '@nestjs/common'; import { Controller, Get, Inject, Param, Query, Req, UseGuards } from '@nestjs/common';
import { PrismaClient, type Prisma } from '@merchantflow/database'; 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 { SessionGuard } from './auth.js';
import { DATABASE, ApiError, type AuthRequest } from './shared.js'; import { DATABASE, ApiError, type AuthRequest } from './shared.js';
import { capabilities, merchantScope, taskScope } from './access.js'; import { capabilities, merchantScope, taskScope } from './access.js';
@@ -185,6 +190,10 @@ export class CrmController {
cycle: true, cycle: true,
decision: true, decision: true,
reason: true, reason: true,
policyVersion: true,
riskLevel: true,
corrections: true,
snapshot: true,
submittedAt: true, submittedAt: true,
decidedAt: true, decidedAt: true,
submittedBy: { select: { name: true } }, submittedBy: { select: { name: true } },
@@ -202,6 +211,7 @@ export class CrmController {
const history = await merchantHistory(merchant, tx); const history = await merchantHistory(merchant, tx);
return { return {
...merchant, ...merchant,
activationChecks: evidence.reviews.flatMap((review) => review.activationChecks),
activities: merchant.activities.map(({ metadata: _metadata, ...activity }) => activity), activities: merchant.activities.map(({ metadata: _metadata, ...activity }) => activity),
capabilities: capabilities(req.user, evidence), capabilities: capabilities(req.user, evidence),
history, history,
@@ -244,13 +254,60 @@ export class CrmController {
orderBy: [{ status: 'asc' }, { dueAt: 'asc' }], 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); if (req.user.role !== 'COMPLIANCE_OFFICER') throw new ApiError('FORBIDDEN', 403);
return this.db.merchant.findMany({ const { search, ownerId, waiting } = reviewQueueQuerySchema.parse(query);
where: { AND: [merchantScope(req.user), { status: 'COMPLIANCE_REVIEW' }] }, const base: Prisma.ComplianceReviewWhereInput = {
select: merchantSelect, decision: 'PENDING',
orderBy: [{ stageEnteredAt: 'asc' }, { id: 'asc' }], 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) { @Get('dashboard') async dashboard(@Req() req: AuthRequest) {
const scope = merchantScope(req.user); const scope = merchantScope(req.user);
@@ -271,7 +328,9 @@ export class CrmController {
recentActivities, recentActivities,
] = await this.db.$transaction([ ] = await this.db.$transaction([
this.db.merchant.count({ where: scope }), 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({ this.db.task.count({
where: { ...taskScope(req.user), status: 'OPEN', dueAt: { lt: new Date() } }, 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 { z } from 'zod';
import { PrismaClient } from '@merchantflow/database'; import { PrismaClient } from '@merchantflow/database';
import { import {
documentCodes, requiredDocumentCodes,
publicLeadKeySchema, publicLeadKeySchema,
publicLeadSchema, publicLeadSchema,
type PublicLead, type PublicLead,
@@ -127,7 +127,10 @@ export class PublicLeadService {
createdAt: now, createdAt: now,
stageEnteredAt: now, stageEnteredAt: now,
checklist: { checklist: {
create: documentCodes.map((documentCode) => ({ documentCode, state: 'MISSING' })), create: requiredDocumentCodes.map((documentCode) => ({
documentCode,
state: 'MISSING',
})),
}, },
events: { create: { fromStatus: null, toStatus: 'NEW_LEAD', occurredAt: now } }, events: { create: { fromStatus: null, toStatus: 'NEW_LEAD', occurredAt: now } },
activities: { activities: {
+56 -8
View File
@@ -8,6 +8,11 @@ import {
countryCodes, countryCodes,
industries, industries,
successfulStages, successfulStages,
isRequiredDocument,
requiredDocumentCodes,
activationCodes,
isIntegrationCheck,
reviewPolicyVersion,
type BlockingReason, type BlockingReason,
type User, type User,
type WorkflowAction, type WorkflowAction,
@@ -18,7 +23,18 @@ export const evidenceInclude = {
include: { changes: { orderBy: [{ occurredAt: 'asc' as const }, { id: 'asc' as const }] } }, include: { changes: { orderBy: [{ occurredAt: 'asc' as const }, { id: 'asc' as const }] } },
}, },
reviews: { 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 }, orderBy: { cycle: 'desc' as const },
}, },
activities: { select: { kind: true } }, activities: { select: { kind: true } },
@@ -28,16 +44,22 @@ export type Evidence = Prisma.MerchantGetPayload<{ include: typeof evidenceInclu
export function receivedHistory(merchant: Evidence, at: Date) { export function receivedHistory(merchant: Evidence, at: Date) {
return ( return (
checklistComplete(merchant.checklist) && checklistComplete(merchant.checklist) &&
merchant.checklist.every( merchant.checklist
(item) => .filter((item) => isRequiredDocument(item.documentCode))
item.changes.filter((change) => change.occurredAt <= at).at(-1)?.toState === 'RECEIVED', .every(
) (item) =>
item.changes.filter((change) => change.occurredAt <= at).at(-1)?.toState === 'RECEIVED',
)
); );
} }
export function validApproval(merchant: Evidence) { export function validApproval(merchant: Evidence) {
const review = merchant.reviews[0]; const review = merchant.reviews[0];
return !!( return !!(
review?.decision === 'APPROVED' && review?.decision === 'APPROVED' &&
review.policyVersion === reviewPolicyVersion &&
review.riskLevel &&
review.reason?.trim() &&
!merchant.reviews.some((cycle) => cycle.decision === 'PENDING') &&
review.reviewer?.role === 'COMPLIANCE_OFFICER' && review.reviewer?.role === 'COMPLIANCE_OFFICER' &&
review.decidedAt && review.decidedAt &&
review.decidedAt >= review.submittedAt && review.decidedAt >= review.submittedAt &&
@@ -45,6 +67,22 @@ export function validApproval(merchant: Evidence) {
snapshotsEqual(review.snapshot, reviewSnapshot(merchant)) 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) { export function qualificationFields(merchant: Evidence) {
const fields: string[] = []; const fields: string[] = [];
for (const field of ['name', 'website', 'contactName', 'contactEmail'] as const) 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') { if (merchant.status === 'COMPLIANCE_REVIEW') {
const blockers: BlockingReason[] = const blockers: BlockingReason[] =
user.role === 'COMPLIANCE_OFFICER' ? [] : [{ code: 'COMPLIANCE_ONLY' }]; user.role === 'COMPLIANCE_OFFICER' ? [] : [{ code: 'COMPLIANCE_ONLY' }];
if (!merchant.reviews.some((review) => review.decision === 'PENDING')) if (merchant.reviews[0]?.decision !== 'PENDING') blockers.push({ code: 'REVIEW_PENDING' });
blockers.push({ code: 'REVIEW_PENDING' });
return [ return [
{ {
kind: 'REVIEW', kind: 'REVIEW',
@@ -91,12 +128,23 @@ export function workflowActions(user: User, merchant: Evidence): WorkflowAction[
} }
if (toStatus === 'COMPLIANCE_REVIEW') { if (toStatus === 'COMPLIANCE_REVIEW') {
if (!receivedHistory(merchant, new Date())) 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')) if (merchant.reviews.some((r) => r.decision === 'PENDING'))
blockingReasons.push({ code: 'REVIEW_PENDING' }); blockingReasons.push({ code: 'REVIEW_PENDING' });
} }
if (['TESTING', 'LIVE'].includes(toStatus) && !validApproval(merchant)) if (['TESTING', 'LIVE'].includes(toStatus) && !validApproval(merchant))
blockingReasons.push({ code: 'APPROVAL_REQUIRED' }); 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[] = [ const actions: WorkflowAction[] = [
{ {
kind: 'ADVANCE', kind: 'ADVANCE',
+113 -8
View File
@@ -15,7 +15,13 @@ import {
taskInputSchema, taskInputSchema,
transitionSchema, transitionSchema,
merchantCreateSchema, merchantCreateSchema,
documentCodes, requiredDocumentCodes,
isRequiredDocument,
activationCodes,
activationEditSchema,
isIntegrationCheck,
reviewPolicyVersion,
versionSchema,
} from '@merchantflow/contracts'; } from '@merchantflow/contracts';
import { SessionGuard } from './auth.js'; import { SessionGuard } from './auth.js';
import { capabilities, merchantScope, requireSales, taskScope } from './access.js'; import { capabilities, merchantScope, requireSales, taskScope } from './access.js';
@@ -25,6 +31,8 @@ import {
evidenceInclude, evidenceInclude,
receivedHistory, receivedHistory,
workflowActions, workflowActions,
canReopenKyb,
validApproval,
type Evidence, type Evidence,
} from './workflow-policy.js'; } from './workflow-policy.js';
@@ -138,7 +146,7 @@ export class WorkflowController {
status: 'NEW_LEAD', status: 'NEW_LEAD',
createdAt: now, createdAt: now,
stageEnteredAt: now, stageEnteredAt: now,
checklist: { create: documentCodes.map((documentCode) => ({ documentCode })) }, checklist: { create: requiredDocumentCodes.map((documentCode) => ({ documentCode })) },
events: { events: {
create: { create: {
fromStatus: null, fromStatus: null,
@@ -234,6 +242,7 @@ export class WorkflowController {
data: { data: {
merchantId: id, merchantId: id,
cycle: (merchant.reviews[0]?.cycle ?? 0) + 1, cycle: (merchant.reviews[0]?.cycle ?? 0) + 1,
policyVersion: reviewPolicyVersion,
submittedById: req.user.id, submittedById: req.user.id,
submittedAt, submittedAt,
snapshot: reviewSnapshot(merchant), snapshot: reviewSnapshot(merchant),
@@ -256,6 +265,7 @@ export class WorkflowController {
requireSales(req.user); requireSales(req.user);
if (!capabilities(req.user, merchant).collectChecklist) if (!capabilities(req.user, merchant).collectChecklist)
throw new ApiError('REVIEW_LOCKED', 409); throw new ApiError('REVIEW_LOCKED', 409);
if (!isRequiredDocument(item.documentCode)) throw new ApiError('REVIEW_LOCKED', 409);
await tx.kybChecklistItem.updateMany({ await tx.kybChecklistItem.updateMany({
where: { id: itemId, merchantId: id }, where: { id: itemId, merchantId: id },
data: { state, note }, data: { state, note },
@@ -276,23 +286,32 @@ export class WorkflowController {
@Param('reviewId') reviewId: string, @Param('reviewId') reviewId: string,
@Body() body: unknown, @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) => { return this.mutate(req, id, version, async (tx, merchant) => {
const review = merchant.reviews.find((review) => review.id === reviewId); const review = merchant.reviews.find((review) => review.id === reviewId);
if (!review) throw new ApiError('NOT_FOUND', 404); if (!review) throw new ApiError('NOT_FOUND', 404);
if (req.user.role !== 'COMPLIANCE_OFFICER') throw new ApiError('FORBIDDEN', 403); 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); 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); 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); throw new ApiError('WORKFLOW_INVALID', 409);
for (const correction of corrections) { for (const correction of corrections) {
const item = merchant.checklist.find((item) => item.id === correction.itemId); const item = merchant.checklist.find((item) => item.id === correction.itemId);
if (!item) throw new ApiError('NOT_FOUND', 404); if (!item) throw new ApiError('NOT_FOUND', 404);
if (!isRequiredDocument(item.documentCode)) throw new ApiError('VALIDATION_ERROR', 400);
await tx.kybChecklistItem.updateMany({ await tx.kybChecklistItem.updateMany({
where: { id: item.id, merchantId: id }, where: { id: item.id, merchantId: id },
data: { state: 'NEEDS_CORRECTION', note: correction.note }, data: { state: 'NEEDS_CORRECTION' },
}); });
await tx.checklistChange.create({ await tx.checklistChange.create({
data: { data: {
@@ -306,8 +325,27 @@ export class WorkflowController {
} }
await tx.complianceReview.updateMany({ await tx.complianceReview.updateMany({
where: { id: reviewId, merchantId: id, decision: 'PENDING' }, 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( await this.stage(
tx, tx,
req, req,
@@ -319,6 +357,73 @@ export class WorkflowController {
reviewId, reviewId,
decision, decision,
reason, 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 { createHash } from 'node:crypto';
import { spawnSync } from 'node:child_process'; import { spawnSync } from 'node:child_process';
import { createDatabase } from '@merchantflow/database'; import { createDatabase } from '@merchantflow/database';
import { roles, statuses, documentCodes } from '@merchantflow/contracts'; import { roles, statuses, documentCodes, requiredDocumentCodes } from '@merchantflow/contracts';
import { import {
Role, Role,
MerchantStatus, MerchantStatus,
@@ -133,7 +133,7 @@ for (const [account, total] of [
for (const m of expected) { for (const m of expected) {
const detail = (await request(`/merchants/${m.id}`, cookie)).body; const detail = (await request(`/merchants/${m.id}`, cookie)).body;
assert.equal(detail.id, m.id); 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.events.every((e) => e.merchant.id === m.id));
assert.ok(detail.tasks.every((t) => t.merchant.id === m.id)); assert.ok(detail.tasks.every((t) => t.merchant.id === m.id));
assert.ok(!JSON.stringify(detail).includes('passwordHash')); 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')); assert.ok(done.every((t) => t.status === 'DONE'));
const overdue = (await request('/tasks?filter=OVERDUE', cookie)).body; const overdue = (await request('/tasks?filter=OVERDUE', cookie)).body;
assert.ok(overdue.every((t) => t.status === 'OPEN' && new Date(t.dueAt) < new Date())); 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.equal(queue.length, 6);
assert.ok(queue.every((m) => m.status === 'COMPLIANCE_REVIEW')); assert.ok(queue.every((m) => m.merchant.status === 'COMPLIANCE_REVIEW'));
assert.ok(new Date(queue[0].stageEnteredAt) <= new Date(queue[1].stageEnteredAt)); 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 () => { test('seed is repeatable without modifying records; history includes correction and terminal outcomes', async () => {
const snapshot = await db.merchant.findMany({ const snapshot = await db.merchant.findMany({
@@ -271,7 +271,7 @@ async function fixture(id, status = 'NEW_LEAD', ownerId = 'user-manager1') {
contactEmail: '[email protected]', contactEmail: '[email protected]',
ownerId, ownerId,
status, 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 }, { version: hidden.version, state: 'RECEIVED', note: null },
'PATCH', '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', { version: hidden.version, kind: 'NOTE', text: 'Forbidden' }, 'POST'],
[ [
`/activities/${hidden.activities[0].id}`, `/activities/${hidden.activities[0].id}`,
@@ -507,7 +516,12 @@ test('corrections, resubmission, approval and activation preserve one merchant a
await mutate( await mutate(
`/merchants/${id}/reviews/${first.id}/decision`, `/merchants/${id}/reviews/${first.id}/decision`,
cookie, cookie,
{ version: m.version, decision: 'APPROVED' }, {
version: m.version,
decision: 'APPROVED',
riskLevel: 'LOW',
reason: 'Evidence verified',
},
'POST', 'POST',
) )
).status, ).status,
@@ -562,7 +576,12 @@ test('corrections, resubmission, approval and activation preserve one merchant a
await mutate( await mutate(
`/merchants/${id}/reviews/${m.reviews[0].id}/decision`, `/merchants/${id}/reviews/${m.reviews[0].id}/decision`,
comp, comp,
{ version: m.version, decision: 'APPROVED', reason: 'All checks passed' }, {
version: m.version,
decision: 'APPROVED',
riskLevel: 'LOW',
reason: 'All checks passed',
},
'POST', 'POST',
) )
).status, ).status,
@@ -591,7 +610,37 @@ test('corrections, resubmission, approval and activation preserve one merchant a
200, 200,
); );
assert.equal((await move('TESTING', comp)).status, 403); 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('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('LIVE', head)).status, 201);
assert.equal((await move('REJECTED')).status, 409); assert.equal((await move('REJECTED')).status, 409);
m = await detail(); m = await detail();
@@ -603,7 +652,12 @@ test('corrections, resubmission, approval and activation preserve one merchant a
await mutate( await mutate(
`/merchants/${id}/reviews/${first.id}/decision`, `/merchants/${id}/reviews/${first.id}/decision`,
comp, comp,
{ version: m.version, decision: 'APPROVED' }, {
version: m.version,
decision: 'APPROVED',
riskLevel: 'LOW',
reason: 'Evidence verified',
},
'POST', 'POST',
) )
).status, ).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.industry, 'OTHER');
assert.equal(merchant.website, 'https://example.test/'); assert.equal(merchant.website, 'https://example.test/');
assert.equal(merchant.estimatedMonthlyVolumeUsd.toFixed(2), '1234.50'); assert.equal(merchant.estimatedMonthlyVolumeUsd.toFixed(2), '1234.50');
assert.equal(merchant.checklist.length, 4); assert.equal(merchant.checklist.length, 3);
assert.ok( assert.ok(
merchant.checklist.every((item) => item.state === 'MISSING' && item.changes.length === 0), 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.website, null);
assert.equal(m.country, null); assert.equal(m.country, null);
assert.equal(m.industry, 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.ok(m.checklist.every((item) => item.state === 'MISSING'));
assert.equal(m.events.length, 1); assert.equal(m.events.length, 1);
assert.equal(m.activities.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, merchantId: clone,
cycle: 1, cycle: 1,
decision: 'APPROVED', decision: 'APPROVED',
riskLevel: 'LOW',
reason: 'Approval retained during commercial closure',
submittedById: 'user-head', submittedById: 'user-head',
reviewerId: 'user-compliance', reviewerId: 'user-compliance',
submittedAt: new Date(Date.now() - 1000),
decidedAt: new Date(), decidedAt: new Date(),
snapshot: approved.reviews[0].snapshot, snapshot: approved.reviews[0].snapshot,
}, },
+21 -99
View File
@@ -9,7 +9,7 @@ import {
industries, industries,
managerListSchema, managerListSchema,
merchantEditSchema, merchantEditSchema,
reviewDecisionSchema, isRequiredDocument,
sources, sources,
statuses, statuses,
taskInputSchema, taskInputSchema,
@@ -180,7 +180,7 @@ export function ChecklistControl({
const action = useAction(m, () => setOpen(false)); const action = useAction(m, () => setOpen(false));
return ( return (
<div className="mt-3 space-y-2"> <div className="mt-3 space-y-2">
{m.capabilities.collectChecklist && ( {m.capabilities.collectChecklist && isRequiredDocument(item.documentCode) && (
<Button <Button
variant="outline" variant="outline"
onClick={() => { onClick={() => {
@@ -191,6 +191,22 @@ export function ChecklistControl({
{t('workflow.checklistEdit')} {t('workflow.checklistEdit')}
</Button> </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} {action.feedback}
<details className="text-xs text-muted-foreground"> <details className="text-xs text-muted-foreground">
<summary className="min-h-11 cursor-pointer py-3">{t('workflow.checklistHistory')}</summary> <summary className="min-h-11 cursor-pointer py-3">{t('workflow.checklistHistory')}</summary>
@@ -235,103 +251,7 @@ export function ChecklistControl({
</div> </div>
); );
} }
export function ReviewHistory({ merchant: m }: { merchant: MerchantDetail }) { export { ReviewHistory } from './onboarding';
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 function useActivityText() { export function useActivityText() {
const { t } = useTranslation(); const { t } = useTranslation();
return (activity: Pick<MerchantDetail['activities'][number], 'kind' | 'text'>) => { return (activity: Pick<MerchantDetail['activities'][number], 'kind' | 'text'>) => {
@@ -349,6 +269,8 @@ export function useActivityText() {
const stages = activity.text.split(' → '); const stages = activity.text.split(' → ');
if (stages.length === 2 && stages.every((stage) => statuses.some((code) => code === stage))) if (stages.length === 2 && stages.every((stage) => statuses.some((code) => code === stage)))
return stages.map((stage) => t(`statuses.${stage}`)).join(' → '); 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: ')) if (activity.text.startsWith('Checklist updated: '))
return t('workflow.checklistUpdated', { return t('workflow.checklistUpdated', {
document: t(`documents.${activity.text.slice(19)}`), 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 { Button, LinkButton } from './shared';
import { Editor, useAction, type Field } from './workflow-form'; 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 { t, i18n } = useTranslation();
const [now, setNow] = useState(() => Date.now()); const [now, setNow] = useState(() => Date.now());
useEffect(() => { 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 hours = Math.max(0, Math.floor((now - new Date(since).getTime()) / 3600000));
const duration = const duration =
hours < 1 hours < 1
? t('workspace.lessThanHour') ? t(waiting ? 'onboarding.lessThanHour' : 'workspace.lessThanHour')
: new Intl.NumberFormat(i18n.language, { : new Intl.NumberFormat(i18n.language, {
style: 'unit', style: 'unit',
unit: hours >= 24 ? 'day' : 'hour', unit: hours >= 24 ? 'day' : 'hour',
@@ -38,7 +38,7 @@ export function StageAge({ since }: { since: string }) {
}).format(hours >= 24 ? Math.floor(hours / 24) : hours); }).format(hours >= 24 ? Math.floor(hours / 24) : hours);
return ( return (
<span title={new Date(since).toLocaleString(i18n.language)}> <span title={new Date(since).toLocaleString(i18n.language)}>
{t('workspace.timeInStage', { duration })} {t(waiting ? 'onboarding.waitingFor' : 'workspace.timeInStage', { duration })}
</span> </span>
); );
} }
@@ -197,7 +197,7 @@ export function StageActions({
}} }}
> >
{item.kind === 'REJECT' {item.kind === 'REJECT'
? t('workspace.reject') ? t(business ? 'onboarding.businessClosure' : 'workspace.reject')
: item.kind === 'REVIEW' : item.kind === 'REVIEW'
? t('workflow.decide') ? t('workflow.decide')
: t('workflow.advance', { stage: t(`statuses.${item.toStatus}`) })} : t('workflow.advance', { stage: t(`statuses.${item.toStatus}`) })}
@@ -208,6 +208,9 @@ export function StageActions({
{item.blockingReasons.map((reason) => ( {item.blockingReasons.map((reason) => (
<li key={reason.code}> <li key={reason.code}>
{t(`workspace.blockers.${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?.length
? ` ${reason.fields.map((field) => t(`workflow.${field}`)).join(', ')}.` ? ` ${reason.fields.map((field) => t(`workflow.${field}`)).join(', ')}.`
: ''} : ''}
@@ -221,7 +224,7 @@ export function StageActions({
{!reject && action.feedback} {!reject && action.feedback}
{reject && ( {reject && (
<Editor <Editor
title={t('workspace.reject')} title={t(business ? 'onboarding.businessClosure' : 'workspace.reject')}
description={t(business ? 'workspace.businessReasonHint' : 'workspace.rejectHint')} description={t(business ? 'workspace.businessReasonHint' : 'workspace.rejectHint')}
fields={[ fields={[
{ {
+3 -1
View File
@@ -75,14 +75,16 @@ export function LinkButton({
children, children,
variant = 'default', variant = 'default',
className, className,
state,
}: { }: {
to: string; to: string;
state?: { returnTo: string };
children: ReactNode; children: ReactNode;
variant?: 'default' | 'outline' | 'ghost'; variant?: 'default' | 'outline' | 'ghost';
className?: string; className?: string;
}) { }) {
return ( return (
<Link to={to} className={cn(buttonVariants({ variant }), className)}> <Link to={to} state={state} className={cn(buttonVariants({ variant }), className)}>
{children} {children}
</Link> </Link>
); );
+17 -5
View File
@@ -26,7 +26,8 @@ export type Field = {
type EditorProps = { type EditorProps = {
title: string; title: string;
description?: string; description?: string;
fields: Field[]; fields: Field[] | ((values: Record<string, string>) => Field[]);
submitLabel?: string | ((values: Record<string, string>) => string);
initial: Record<string, string>; initial: Record<string, string>;
schema: z.ZodType; schema: z.ZodType;
build: (values: Record<string, string>) => unknown; build: (values: Record<string, string>) => unknown;
@@ -46,10 +47,13 @@ export function Editor({
close, close,
pending, pending,
feedback, feedback,
submitLabel,
}: EditorProps) { }: EditorProps) {
const { t } = useTranslation(); const { t } = useTranslation();
const id = useId(); const id = useId();
const form = useForm<Record<string, string>>({ defaultValues: initial }); 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>>({}); const [errors, setErrors] = useState<Record<string, string>>({});
return ( return (
<Sheet <Sheet
@@ -76,7 +80,7 @@ export function Editor({
issue.message.startsWith('validation.') ? issue.message : 'validation.invalid', issue.message.startsWith('validation.') ? issue.message : 'validation.invalid',
); );
setErrors(messages); setErrors(messages);
const first = fields.find((field) => messages[field.name]); const first = visibleFields.find((field) => messages[field.name]);
if (first) form.setFocus(first.name); if (first) form.setFocus(first.name);
return; return;
} }
@@ -86,7 +90,7 @@ export function Editor({
> >
{feedback} {feedback}
<fieldset disabled={pending} className="space-y-5"> <fieldset disabled={pending} className="space-y-5">
{fields.map((field) => { {visibleFields.map((field) => {
const fieldId = `${id}-${field.name}`; const fieldId = `${id}-${field.name}`;
const props = { const props = {
id: fieldId, id: fieldId,
@@ -122,13 +126,21 @@ export function Editor({
</FormField> </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"> <p role="alert" className="text-sm text-destructive">
{t('errors.VALIDATION_ERROR')} {t('errors.VALIDATION_ERROR')}
</p> </p>
)} )}
<div className="flex flex-wrap gap-3 border-t pt-5"> <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}> <Button type="button" variant="outline" onClick={close}>
{t('workflow.cancel')} {t('workflow.cancel')}
</Button> </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 { salesEn, salesRu } from './sales-locales';
import { workflowEn, workflowRu } from './workflow-locales'; import { workflowEn, workflowRu } from './workflow-locales';
import { landingEn, landingRu } from './landing-locales'; import { landingEn, landingRu } from './landing-locales';
export const en = { export const en = {
onboarding: onboardingEn,
workflow: workflowEn, workflow: workflowEn,
workspace: salesEn, workspace: salesEn,
common: { common: {
@@ -169,7 +171,7 @@ export const en = {
overview: 'Merchant overview', overview: 'Merchant overview',
details: 'The essentials, all together.', details: 'The essentials, all together.',
checklist: 'KYB checklist', 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', notes: 'Team notes',
notesText: 'Context from the people closest to the relationship.', notesText: 'Context from the people closest to the relationship.',
history: 'Journey history', history: 'Journey history',
@@ -182,8 +184,9 @@ export const en = {
noTasks: 'No related tasks yet', noTasks: 'No related tasks yet',
}, },
documents: { documents: {
INCORPORATION: 'Certificate of incorporation', INCORPORATION: 'Company registration',
OWNERSHIP: 'Ownership structure', OWNERSHIP: 'Ownership structure',
AUTHORIZED_REPRESENTATIVE: 'Authorized representative identification',
UBO_IDENTIFICATION: 'Beneficial owner identification', UBO_IDENTIFICATION: 'Beneficial owner identification',
BUSINESS_ACTIVITY: 'Business activity description', BUSINESS_ACTIVITY: 'Business activity description',
}, },
@@ -229,10 +232,11 @@ export const en = {
empty: 'The queue is clear', empty: 'The queue is clear',
emptyText: 'Merchants appear here when they reach Compliance Review.', emptyText: 'Merchants appear here when they reach Compliance Review.',
entered: 'Entered review', entered: 'Entered review',
view: 'View checklist', view: 'Open review',
}, },
}; };
export const ru = { export const ru = {
onboarding: onboardingRu,
workflow: workflowRu, workflow: workflowRu,
workspace: salesRu, workspace: salesRu,
common: { common: {
@@ -401,7 +405,7 @@ export const ru = {
overview: 'О мерчанте', overview: 'О мерчанте',
details: 'Главное — в одном месте.', details: 'Главное — в одном месте.',
checklist: 'Чек-лист KYB', checklist: 'Чек-лист KYB',
checklistText: 'Готовность документов к следующей проверке.', checklistText: 'Статусы и заметки о сборе KYB отделом продаж. Без загрузки файлов.',
notes: 'Заметки команды', notes: 'Заметки команды',
notesText: 'Контекст от тех, кто работает с мерчантом.', notesText: 'Контекст от тех, кто работает с мерчантом.',
history: 'История этапов', history: 'История этапов',
@@ -414,6 +418,7 @@ export const ru = {
noTasks: 'Связанных задач пока нет', noTasks: 'Связанных задач пока нет',
}, },
documents: { documents: {
AUTHORIZED_REPRESENTATIVE: 'Идентификация уполномоченного представителя',
INCORPORATION: 'Свидетельство о регистрации', INCORPORATION: 'Свидетельство о регистрации',
OWNERSHIP: 'Структура собственности', OWNERSHIP: 'Структура собственности',
UBO_IDENTIFICATION: 'Идентификация бенефициаров', UBO_IDENTIFICATION: 'Идентификация бенефициаров',
@@ -465,6 +470,6 @@ export const ru = {
empty: 'Очередь пуста', empty: 'Очередь пуста',
emptyText: 'Мерчанты появятся здесь на этапе комплаенс-проверки.', emptyText: 'Мерчанты появятся здесь на этапе комплаенс-проверки.',
entered: 'Начало проверки', 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 { import {
MerchantControls, MerchantControls,
ChecklistControl, ChecklistControl,
@@ -32,7 +34,7 @@ import {
dashboardSchema, dashboardSchema,
merchantListSchema, merchantListSchema,
merchantDetailSchema, merchantDetailSchema,
pipelineSchema, reviewQueueSchema,
pipelineBoardSchema, pipelineBoardSchema,
merchantFiltersSchema, merchantFiltersSchema,
taskListSchema, taskListSchema,
@@ -599,6 +601,7 @@ export function MerchantDetail() {
</p> </p>
</div> </div>
</div> </div>
<OnboardingHandoff merchant={m} />
<MerchantControls merchant={m} /> <MerchantControls merchant={m} />
<div <div
role="tablist" role="tablist"
@@ -728,6 +731,15 @@ export function MerchantDetail() {
title={t('merchants.checklist')} title={t('merchants.checklist')}
description={t('merchants.checklistText')} 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"> <div className="mt-4">
{m.checklist.map((doc) => ( {m.checklist.map((doc) => (
<div key={doc.id} className="flex gap-3 border-t px-5 py-4 sm:px-6"> <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> </div>
</section> </section>
<ActivationChecklist merchant={m} />
</> </>
)} )}
{tab === 'tasks' && <MerchantTasks merchant={m} />} {tab === 'tasks' && <MerchantTasks merchant={m} />}
@@ -919,12 +932,21 @@ export function ReviewQueue() {
const user = useOutletContext<User>(); const user = useOutletContext<User>();
const { t } = useTranslation(); const { t } = useTranslation();
const f = useFormat(); const f = useFormat();
const [params, setParams] = useSearchParams();
const filters = reviewParams(params);
const serialized = filters.toString();
const allowed = canSeeReviewQueue(user.role); const allowed = canSeeReviewQueue(user.role);
const query = useQuery({ const query = useQuery({
queryKey: ['review-queue'], queryKey: ['review-queue', serialized],
queryFn: ({ signal }) => api('/review-queue', pipelineSchema, { signal }), queryFn: ({ signal }) => api(`/review-queue?${serialized}`, reviewQueueSchema, { signal }),
enabled: allowed, 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 />; if (!allowed) return <NotFound forbidden />;
return ( return (
<> <>
@@ -933,59 +955,115 @@ export function ReviewQueue() {
description={t('review.description')} description={t('review.description')}
eyebrow={t('review.eyebrow')} 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}> <QueryBoundary query={query}>
{(merchants) => ( {(data) => (
<section className="surface overflow-hidden"> <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"> <div className="flex flex-wrap items-center justify-between gap-3 border-b p-5 sm:p-6">
<h2 className="text-sm font-semibold"> <div>
{t('review.count', { count: merchants.length })} <h2 className="text-sm font-semibold">
</h2> {t('review.count', { count: data.pendingCount })}
<span className="inline-flex items-center gap-1.5 text-xs text-muted-foreground"> </h2>
<Clock3 className="size-3.5" /> <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')} {t('review.order')}
</span> </span>
{serialized && (
<Button variant="ghost" onClick={() => setParams({})}>
{t('common.clear')}
</Button>
)}
</div> </div>
{merchants.length ? ( {data.items.length ? (
merchants.map((m) => ( data.items.map((review) => (
<div <article
key={m.id} 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" 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"> <div className="flex min-w-0 items-center gap-3">
<Avatar name={m.name} /> <Avatar name={review.merchant.name} />
<div> <div className="min-w-0">
<Link <Link
to={`/app/merchants/${m.id}`} className="break-words text-sm font-semibold hover:underline"
className="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> </Link>
<p className="mt-1 text-xs text-muted-foreground"> <p className="mt-1 text-xs text-muted-foreground">
{m.owner?.name ?? t('workflow.unassigned')} ·{' '} {review.merchant.owner?.name ?? t('workflow.unassigned')} ·{' '}
{m.industry ? t(`industry.${m.industry}`) : '—'} {t('workflow.cycle', { cycle: review.cycle })}
</p> </p>
</div> </div>
</div> </div>
<div className="flex flex-wrap items-center justify-between gap-4"> <div className="flex flex-wrap items-center justify-between gap-4">
<div> <div>
<p className="mb-1 text-[10px] text-muted-foreground"> <p className="text-sm">
{t('review.entered')} <StageAge since={review.submittedAt} waiting />
</p>
<p className="mt-1 text-xs text-muted-foreground">
{f.dateTime(review.submittedAt)}
</p> </p>
<p className="text-xs">{f.date(m.stageEnteredAt)}</p>
</div> </div>
<LinkButton <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" variant="outline"
className="text-xs"
> >
{t('review.view')} {t('review.view')}
<ArrowRight className="size-3.5" /> <ArrowRight className="size-4" />
</LinkButton> </LinkButton>
</div> </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> </section>
)} )}
+6 -2
View File
@@ -34,10 +34,12 @@ export const salesEn = {
ASSIGNMENT_REQUIRED: 'Assign a manager before progressing.', ASSIGNMENT_REQUIRED: 'Assign a manager before progressing.',
CONTACT_REQUIRED: 'Log a call or email before moving to Contacted.', CONTACT_REQUIRED: 'Log a call or email before moving to Contacted.',
QUALIFICATION_INCOMPLETE: 'Complete the following fields:', 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.', REVIEW_PENDING: 'A single pending review is required; check the onboarding section.',
APPROVAL_REQUIRED: 'Matching compliance approval and document evidence are required.', APPROVAL_REQUIRED: 'Matching compliance approval and document evidence are required.',
COMPLIANCE_ONLY: 'Only Compliance can decide the outcome of this review.', 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.', SALES_ONLY: 'Only the Head or assigned manager can advance commercial stages.',
}, },
}; };
@@ -76,10 +78,12 @@ export const salesRu = {
ASSIGNMENT_REQUIRED: 'Назначьте менеджера для перехода дальше.', ASSIGNMENT_REQUIRED: 'Назначьте менеджера для перехода дальше.',
CONTACT_REQUIRED: 'Запишите звонок или письмо перед переходом к контакту.', CONTACT_REQUIRED: 'Запишите звонок или письмо перед переходом к контакту.',
QUALIFICATION_INCOMPLETE: 'Заполните следующие поля:', QUALIFICATION_INCOMPLETE: 'Заполните следующие поля:',
DOCUMENTS_REQUIRED: 'Получите все четыре документа KYB перед отправкой на проверку.', DOCUMENTS_REQUIRED: 'Получите все три обязательных пункта KYB перед отправкой на проверку.',
REVIEW_PENDING: 'Нужна одна активная проверка. Откройте раздел онбординга.', REVIEW_PENDING: 'Нужна одна активная проверка. Откройте раздел онбординга.',
APPROVAL_REQUIRED: 'Нужны актуальное одобрение комплаенса и история документов.', APPROVAL_REQUIRED: 'Нужны актуальное одобрение комплаенса и история документов.',
COMPLIANCE_ONLY: 'Только комплаенс может принять решение по проверке.', COMPLIANCE_ONLY: 'Только комплаенс может принять решение по проверке.',
ACTIVATION_CHECKS_REQUIRED: 'Выполните обязательные демо-проверки:',
POLICY_UPGRADE_REQUIRED: 'Вернитесь в KYB для новой проверки по текущим требованиям.',
SALES_ONLY: 'Коммерческие этапы меняет руководитель или назначенный менеджер.', SALES_ONLY: 'Коммерческие этапы меняет руководитель или назначенный менеджер.',
}, },
} satisfies { } satisfies {
+8 -8
View File
@@ -23,10 +23,10 @@ export const workflowEn = {
advance: 'Move to {{stage}}', advance: 'Move to {{stage}}',
identityLocked: identityLocked:
'Reviewed company and KYB information is locked. Contact and commercial details can still be updated.', 'Reviewed company and KYB information is locked. Contact and commercial details can still be updated.',
checklistEdit: 'Update document', checklistEdit: 'Update collection',
checklistHistory: 'Document history', checklistHistory: 'Collection history',
state: 'Document status', state: 'Collection status',
note: 'Note', note: 'Collection notes',
reviews: 'Compliance reviews', reviews: 'Compliance reviews',
decide: 'Record decision', decide: 'Record decision',
decision: 'Decision', decision: 'Decision',
@@ -105,10 +105,10 @@ export const workflowRu: Record<keyof typeof workflowEn, string> = {
advance: 'Перевести: {{stage}}', advance: 'Перевести: {{stage}}',
identityLocked: identityLocked:
'Проверенные данные компании и KYB защищены от изменений. Контактные и коммерческие данные можно обновлять.', 'Проверенные данные компании и KYB защищены от изменений. Контактные и коммерческие данные можно обновлять.',
checklistEdit: 'Обновить документ', checklistEdit: 'Обновить сбор',
checklistHistory: 'История документа', checklistHistory: 'История сбора',
state: 'Статус документа', state: 'Статус сбора',
note: 'Заметка', note: 'Заметки о сборе',
reviews: 'Комплаенс-проверки', reviews: 'Комплаенс-проверки',
decide: 'Записать решение', decide: 'Записать решение',
decision: 'Решение', decision: 'Решение',
+16
View File
@@ -75,3 +75,19 @@ No staff registration, merchant deletion UI, merchant portal, uploads, payment p
- [x] Retained form values on failure, accessible controls and bilingual feedback - [x] Retained form values on failure, accessible controls and bilingual feedback
Verification: all 32 integration tests passed against the isolated PostgreSQL service, including role/stage rejection cases, filters, creation, races and injected transaction rollback. All 19 browser tests passed, covering EN/RU at mobile and desktop sizes, real API creation/filtering/history, pipeline progression and rejection, ownership isolation, stale-editor preservation and the existing compliance journeys. Build, lint, typecheck, 17 unit tests, formatting and whitespace checks passed. The additive sales migration was applied to development without a reset or reseed. Verification: all 32 integration tests passed against the isolated PostgreSQL service, including role/stage rejection cases, filters, creation, races and injected transaction rollback. All 19 browser tests passed, covering EN/RU at mobile and desktop sizes, real API creation/filtering/history, pipeline progression and rejection, ownership isolation, stale-editor preservation and the existing compliance journeys. Build, lint, typecheck, 17 unit tests, formatting and whitespace checks passed. The additive sales migration was applied to development without a reset or reseed.
## Gated onboarding completion
- [x] Three current KYB collection records: company registration, ownership structure and authorized-representative identification; legacy requirements remain read-only history
- [x] Sales collection status/notes restricted to Head or assigned Manager in KYB, with received-history submission evidence and pending-review locks
- [x] Compliance-only approval with risk/rationale, actionable corrections stored separately from collection notes, and rejection with a reason
- [x] Numbered immutable review snapshots and outcomes; only the latest current-policy approval authorizes activation; open forms remain bound to their original cycle
- [x] Four persisted demo activation checks with stage-specific editing, approved-cycle attribution and change history; no external payment/processing calls
- [x] Compliance queue with pending/filtered counts, elapsed waiting time, URL-persisted search/manager/age filters and direct review-cycle links
- [x] Server-derived next owner, required action and specific blockers; distinct business closure and Compliance decisions; responsive EN/RU UI
- [x] Additive legacy upgrade and explicit return-to-KYB recovery; existing decisions and collection history remain unchanged
- [x] Fresh fixture approval/check evidence, preserved existing fixture edits and passwords, and repeatable seed behavior
Verification: 41 integration tests passed, including a populated legacy-schema migration, correction/resubmission, stale decisions, older approval/check evidence, concurrent writes, authorization bypasses, queue filters and transaction rollback. All 20 unit/contract/localization tests, build, lint, typecheck, formatting and whitespace checks passed. All 24 browser tests passed. Browser verification covers the complete successful journey through Live, rejection, conflict preservation, direct review links, queue filtering, EN/RU and mobile/desktop layouts. Screenshots were visually inspected.
Applied migrations `202609240005_gated_onboarding` and `202609240006_kyb_upgrade` to development without a reset or reseed. Before/after checksums confirmed original company data, review decisions/snapshots, collection notes/history, activities, stage events, tasks and password hashes were unchanged for all 45 merchants. Only new missing representative records and unfinished merchant concurrency versions were added. Local health, authentication, detail capabilities and queue authorization passed for all four demo accounts; smoke-test sessions were signed out afterward.
+10 -4
View File
@@ -12,13 +12,13 @@ NestJS authorization and database predicates apply to all reads, searches, count
New Lead → Contacted → Qualified → KYB → Compliance Review → Integration → Testing → Live. Rejected is an alternate terminal outcome; neither Live nor Rejected has outgoing stage actions. The same merchant ID persists throughout. New Lead → Contacted → Qualified → KYB → Compliance Review → Integration → Testing → Live. Rejected is an alternate terminal outcome; neither Live nor Rejected has outgoing stage actions. The same merchant ID persists throughout.
Assignment is required before leaving New Lead and before entering KYB. Contacted requires a persisted call or email; a note or meeting does not qualify. Qualified requires company name, website, primary contact name/email, country, industry and estimated monthly volume (zero is valid). Head or the assigned Manager may reject New Lead, Contacted or Qualified with a reason. Only Head may close KYB, Integration or Testing for a recorded business reason; this preserves any compliance decision. Only Compliance can decide rejection during Compliance Review. Sales collects the four KYB documents. All must have received-history evidence before submission creates a pending review. Reviewed company/KYB fields freeze during review. Compliance approval advances to Integration; rejection requires a reason; corrections require a reason and item-specific notes and return the merchant to KYB. Resubmission creates another review cycle. Decisions are immutable. Assignment is required before leaving New Lead and before entering KYB. Contacted requires a persisted call or email; a note or meeting does not qualify. Qualified requires company name, website, primary contact name/email, country, industry and estimated monthly volume (zero is valid). Head or the assigned Manager may reject New Lead, Contacted or Qualified with a reason. Only Head may close KYB, Integration or Testing for a recorded business reason; this preserves any compliance decision. Only Compliance can decide rejection during Compliance Review. Head or the assigned Manager collects three KYB checklist records: company registration, ownership structure and authorized-representative identification. These are collection statuses and notes, not uploaded files. All must have received-history evidence before submission creates a pending review. Reviewed company/KYB fields freeze during review. Compliance approval requires a Low/Medium/High risk level and nonblank rationale and advances to Integration; rejection requires a reason; corrections require a reason and immutable item-specific notes separate from Sales collection notes and return the merchant to KYB. Resubmission creates another review cycle. Decisions are immutable.
Reviewed company identity, website, country, industry and KYB items remain locked after approval. Contact details, volume estimates, source and authorized ownership can change. Head or the assigned manager may advance Integration → Testing → Live only with matching approval/checklist evidence. Reassignment transfers open commercial tasks, preserving completed attribution and personal Compliance tasks. Reviewed company identity, website, country, industry and KYB items remain locked after approval. Contact details, volume estimates, source and authorized ownership can change. Head or the assigned manager may advance Integration → Testing only with a valid latest-cycle approval and completed API-connection/webhook-setup demo checks. Testing → Live additionally requires passing test-payment and reconciliation demo checks. Check states, notes, actors and timestamps are persisted against the approved review cycle, with immutable change history. Checks can be edited only during their own stage. No real payments or external processing calls occur. An old approval or check result cannot satisfy a newer cycle. Reassignment transfers open commercial tasks, preserving completed attribution and personal Compliance tasks.
## Journeys and records ## Journeys and records
Landing → email/password login → role-scoped dashboard → merchant search/filter → detail, editing, assignment, checklist, reviews, interactions, history and tasks. The directory searches company, contact, email and website and combines stage, country, industry and authorized owner filters with eight-record pagination. Search/filter/page state is stored in the URL. Head and Compliance may filter by manager or Unassigned; Managers remain scoped to their own merchants. Desktop uses tables and pipeline columns; mobile uses directory cards and exactly one selected pipeline stage. Detail has URL-addressable Overview, Activity, Onboarding and Tasks tabs; Activity merges notes, interactions, ownership, stage events and compliance outcomes into one newest-first history. Explicit stage controls display server-derived blocking reasons. Pipeline, Tasks and Compliance Review Queue provide dedicated views. Tasks can be created, edited and completed from merchant details; reminders stay in the app. Landing → email/password login → role-scoped dashboard → merchant search/filter → detail, editing, assignment, checklist, reviews, interactions, history and tasks. The directory searches company, contact, email and website and combines stage, country, industry and authorized owner filters with eight-record pagination. Search/filter/page state is stored in the URL. Head and Compliance may filter by manager or Unassigned; Managers remain scoped to their own merchants. Desktop uses tables and pipeline columns; mobile uses directory cards and exactly one selected pipeline stage. Detail has URL-addressable Overview, Activity, Onboarding and Tasks tabs; Activity merges notes, interactions, ownership, stage events and compliance outcomes into one newest-first history. Explicit stage controls display server-derived blocking reasons. Pipeline, Tasks and Compliance Review Queue provide dedicated views. The Compliance-only queue shows total pending and filtered counts, elapsed waiting time, manager/search/24-hour/72-hour filters stored in the URL, and links to individual review cycles. Merchant detail shows the next owner, required action and server-derived blockers; commercial closure remains visibly distinct from Compliance rejection. Tasks can be created, edited and completed from merchant details; reminders stay in the app.
Staff creation requires company name, primary-contact name and email; website, country, industry and volume may be completed later. Merchants include company and primary-contact details, website, country, industry, decimal USD volume estimates, source, nullable manager, stage, timestamps and a concurrency version. Related models retain activities, stage events, checklist changes, review snapshots and task attribution. Mutations and audit history commit atomically and reject stale versions. Staff creation requires company name, primary-contact name and email; website, country, industry and volume may be completed later. Merchants include company and primary-contact details, website, country, industry, decimal USD volume estimates, source, nullable manager, stage, timestamps and a concurrency version. Related models retain activities, stage events, checklist changes, review snapshots and task attribution. Mutations and audit history commit atomically and reject stale versions.
@@ -26,7 +26,7 @@ Staff creation requires company name, primary-contact name and email; website, c
The public landing page introduces merchant crypto-payment onboarding in EN/RU with an inline consultation form. Company name, contact name, work email, website, country, industry and estimated monthly USD volume are required. Industries include Other; zero is a valid volume estimate. The staff-login link remains available on mobile. The public landing page introduces merchant crypto-payment onboarding in EN/RU with an inline consultation form. Company name, contact name, work email, website, country, industry and estimated monthly USD volume are required. Industries include Other; zero is a valid volume estimate. The staff-login link remains available on mobile.
`POST /api/public/leads` requires a trusted Origin and a UUID `Idempotency-Key`. Accepted submissions atomically create an unassigned New Lead with source `LANDING_PAGE`, four missing KYB items, an initial stage event and a system-attributed creation activity. Database uniqueness prevents duplicate records on retries, including concurrent requests and API restarts. A changed payload under the same key returns a conflict. Filled honeypots receive the same generic acceptance without creating records. `POST /api/public/leads` requires a trusted Origin and a UUID `Idempotency-Key`. Accepted submissions atomically create an unassigned New Lead with source `LANDING_PAGE`, three missing KYB checklist records, an initial stage event and a system-attributed creation activity. Database uniqueness prevents duplicate records on retries, including concurrent requests and API restarts. A changed payload under the same key returns a conflict. Filled honeypots receive the same generic acceptance without creating records.
The endpoint validates on the server and uses bounded process-local IP/email limits. The form preserves inputs after errors, translates field feedback, announces submission states and respects Retry-After. Lead details remain in component memory; only language is stored in the browser. No external notifications are sent. The endpoint validates on the server and uses bounded process-local IP/email limits. The form preserves inputs after errors, translates field feedback, announces submission states and respects Retry-After. Lead details remain in component memory; only language is stored in the browser. No external notifications are sent.
@@ -43,3 +43,9 @@ Seeding uses stable IDs, a stored date anchor and a version marker. It preserves
English is the default; EN/RU selection persists in browser storage. Dates use the selected locale and viewer's time zone. Names and notes remain verbatim; canonical status/role labels are translated. Retain the light neutral UI, lime accents, visible focus, touch-sized controls and reduced-motion support. English is the default; EN/RU selection persists in browser storage. Dates use the selected locale and viewer's time zone. Names and notes remain verbatim; canonical status/role labels are translated. Retain the light neutral UI, lime accents, visible focus, touch-sized controls and reduced-motion support.
No merchant deletion UI, staff registration, merchant self-service, real payments, external KYB integration, uploads, external notifications or deployment. No merchant deletion UI, staff registration, merchant self-service, real payments, external KYB integration, uploads, external notifications or deployment.
## Current requirements and historical records
Review policy version 2 uses the three current KYB requirements. Legacy beneficial-owner ID and business-activity checklist records and every historical review snapshot/decision remain readable and unchanged. Additive migrations mark old cycles as version 1, leave their risk unset, and add a missing authorized-representative item to unfinished merchants. No previous identification is reinterpreted and no approval or demo result is invented.
Legacy pending cycles may receive corrections or rejection but cannot be approved under obsolete requirements. Head or the assigned Manager can explicitly return legacy Integration/Testing merchants to KYB for collection and a fresh review. This audited exception preserves prior approvals. Current-policy approvals lock reviewed fields; Live and Rejected remain terminal.
+67
View File
@@ -139,3 +139,70 @@ describe('daily sales contracts', () => {
).toBe('unassigned'); ).toBe('unassigned');
}); });
}); });
describe('gated onboarding contracts', () => {
it('requires risk and rationale only for approval and actionable notes for corrections', async () => {
const { reviewDecisionSchema } = await import('./index.js');
const approve = {
version: 1,
decision: 'APPROVED',
reason: 'Evidence verified',
riskLevel: 'LOW',
};
expect(reviewDecisionSchema.safeParse(approve).success).toBe(true);
for (const patch of [
{ riskLevel: undefined },
{ riskLevel: 'NONE' },
{ reason: ' ' },
{ reviewerId: 'injected' },
])
expect(reviewDecisionSchema.safeParse({ ...approve, ...patch }).success).toBe(false);
expect(
reviewDecisionSchema.safeParse({ version: 1, decision: 'REJECTED', reason: 'Cannot verify' })
.success,
).toBe(true);
expect(
reviewDecisionSchema.safeParse({
version: 1,
decision: 'REJECTED',
reason: 'Cannot verify',
riskLevel: 'LOW',
}).success,
).toBe(false);
const correction = {
version: 1,
decision: 'CORRECTIONS',
reason: 'Current record required',
corrections: [{ itemId: 'item', note: 'Provide a current signature' }],
};
expect(reviewDecisionSchema.safeParse(correction).success).toBe(true);
for (const corrections of [
[],
[{ itemId: 'item', note: ' ' }],
[...correction.corrections, ...correction.corrections],
])
expect(reviewDecisionSchema.safeParse({ ...correction, corrections }).success).toBe(false);
});
it('keeps exactly three active requirements without losing legacy codes', async () => {
const { documentCodes, requiredDocumentCodes, reviewQueueQuerySchema, activationEditSchema } =
await import('./index.js');
expect(requiredDocumentCodes).toEqual([
'INCORPORATION',
'OWNERSHIP',
'AUTHORIZED_REPRESENTATIVE',
]);
expect(documentCodes).toContain('UBO_IDENTIFICATION');
expect(documentCodes).toContain('BUSINESS_ACTIVITY');
expect(reviewQueueQuerySchema.safeParse({ waiting: '25' }).success).toBe(false);
expect(reviewQueueQuerySchema.parse({}).waiting).toBe('ALL');
expect(
activationEditSchema.safeParse({
version: 1,
reviewId: 'cycle',
state: 'PASSED',
note: null,
actorId: 'injected',
}).success,
).toBe(false);
});
});
+115 -2
View File
@@ -58,7 +58,13 @@ export const apiErrorSchema = z.object({
code: z.enum(errorCodes), code: z.enum(errorCodes),
issues: z.array(z.object({ path: z.string(), code: z.string() })).optional(), issues: z.array(z.object({ path: z.string(), code: z.string() })).optional(),
blockingReasons: z blockingReasons: z
.array(z.object({ code: z.string(), fields: z.array(z.string()).optional() })) .array(
z.object({
code: z.string(),
fields: z.array(z.string()).optional(),
items: z.array(z.string()).optional(),
}),
)
.optional(), .optional(),
}); });
export const userSchema = z.object({ export const userSchema = z.object({
@@ -130,7 +136,27 @@ export const documentCodes = [
'OWNERSHIP', 'OWNERSHIP',
'UBO_IDENTIFICATION', 'UBO_IDENTIFICATION',
'BUSINESS_ACTIVITY', 'BUSINESS_ACTIVITY',
'AUTHORIZED_REPRESENTATIVE',
] as const; ] as const;
export const requiredDocumentCodes = [
'INCORPORATION',
'OWNERSHIP',
'AUTHORIZED_REPRESENTATIVE',
] as const;
export const reviewPolicyVersion = 2;
export const riskLevels = ['LOW', 'MEDIUM', 'HIGH'] as const;
export const activationCodes = [
'API_CONNECTION',
'WEBHOOK_SETUP',
'TEST_PAYMENT',
'RECONCILIATION',
] as const;
export const activationStates = ['INCOMPLETE', 'COMPLETE', 'NOT_RUN', 'PASSED', 'FAILED'] as const;
export const integrationCodes = ['API_CONNECTION', 'WEBHOOK_SETUP'] as const;
export const isRequiredDocument = (code: string) =>
requiredDocumentCodes.some((value) => value === code);
export const isIntegrationCheck = (code: string) =>
integrationCodes.some((value) => value === code);
export const activityKinds = ['NOTE', 'CALL', 'EMAIL', 'MEETING', 'KYB_NOTE'] as const; export const activityKinds = ['NOTE', 'CALL', 'EMAIL', 'MEETING', 'KYB_NOTE'] as const;
export const activitySchema = z.object({ export const activitySchema = z.object({
id: z.string(), id: z.string(),
@@ -143,6 +169,22 @@ export const activitySchema = z.object({
}); });
export const reviewSchema = z.object({ export const reviewSchema = z.object({
id: z.string(), id: z.string(),
policyVersion: z.number().int(),
riskLevel: z.enum(riskLevels).nullable(),
corrections: z.array(
z.object({ itemId: z.string(), documentCode: z.enum(documentCodes), note: z.string() }),
),
snapshot: z.object({
company: z.record(z.string(), z.string().nullable()),
checklist: z.array(
z.object({
id: z.string(),
documentCode: z.enum(documentCodes),
state: z.enum(['MISSING', 'RECEIVED', 'NEEDS_CORRECTION']),
note: z.string().nullable(),
}),
),
}),
cycle: z.number(), cycle: z.number(),
decision: z.enum(['PENDING', 'APPROVED', 'CORRECTIONS', 'REJECTED']), decision: z.enum(['PENDING', 'APPROVED', 'CORRECTIONS', 'REJECTED']),
reason: z.string().nullable(), reason: z.string().nullable(),
@@ -161,8 +203,11 @@ export const blockingReasonSchema = z.object({
'APPROVAL_REQUIRED', 'APPROVAL_REQUIRED',
'COMPLIANCE_ONLY', 'COMPLIANCE_ONLY',
'SALES_ONLY', 'SALES_ONLY',
'ACTIVATION_CHECKS_REQUIRED',
'POLICY_UPGRADE_REQUIRED',
]), ]),
fields: z.array(z.string()).optional(), fields: z.array(z.string()).optional(),
items: z.array(z.string()).optional(),
}); });
export const workflowActionSchema = z.object({ export const workflowActionSchema = z.object({
kind: z.enum(['ADVANCE', 'REJECT', 'REVIEW']), kind: z.enum(['ADVANCE', 'REJECT', 'REVIEW']),
@@ -179,6 +224,22 @@ export const capabilitiesSchema = z.object({
assign: z.boolean(), assign: z.boolean(),
collectChecklist: z.boolean(), collectChecklist: z.boolean(),
review: z.boolean(), review: z.boolean(),
reopenKyb: z.boolean(),
activationCodes: z.array(z.enum(activationCodes)),
handoff: z.object({
owner: z.enum(['HEAD_OF_SALES', 'ACCOUNT_MANAGER', 'COMPLIANCE_OFFICER', 'NONE']),
ownerId: z.string().nullable(),
action: z.enum([
'ASSIGN',
'COMMERCIAL',
'COLLECT',
'REVIEW',
'INTEGRATE',
'TEST',
'REOPEN_KYB',
'COMPLETE',
]),
}),
activityKinds: z.array(z.enum(activityKinds)), activityKinds: z.array(z.enum(activityKinds)),
manageTaskKind: z.enum(['COMMERCIAL', 'COMPLIANCE']), manageTaskKind: z.enum(['COMMERCIAL', 'COMPLIANCE']),
nextStage: statusSchema.nullable(), nextStage: statusSchema.nullable(),
@@ -219,6 +280,25 @@ export const historyEntrySchema = z.discriminatedUnion('kind', [
]); ]);
export type HistoryEntry = z.infer<typeof historyEntrySchema>; export type HistoryEntry = z.infer<typeof historyEntrySchema>;
export const merchantDetailSchema = merchantSchema.extend({ export const merchantDetailSchema = merchantSchema.extend({
activationChecks: z.array(
z.object({
id: z.string(),
reviewId: z.string(),
code: z.enum(activationCodes),
state: z.enum(activationStates),
note: z.string().nullable(),
changes: z.array(
z.object({
id: z.string(),
fromState: z.enum(activationStates),
toState: z.enum(activationStates),
note: z.string().nullable(),
occurredAt: date,
actor: z.object({ name: z.string() }),
}),
),
}),
),
checklist: z.array( checklist: z.array(
z.object({ z.object({
id: z.string(), id: z.string(),
@@ -264,6 +344,27 @@ export const dashboardSchema = z.object({
recentActivities: z.array(activitySchema), recentActivities: z.array(activitySchema),
}); });
export const pipelineSchema = z.array(merchantSchema); export const pipelineSchema = z.array(merchantSchema);
export const reviewQueueQuerySchema = z
.object({
search: merchantQuerySchema.shape.search,
ownerId: merchantQuerySchema.shape.ownerId,
waiting: z.enum(['ALL', '24', '72']).default('ALL'),
})
.strict();
export const reviewQueueSchema = z.object({
pendingCount: z.number(),
filteredCount: z.number(),
owners: z.array(z.object({ id: z.string(), name: z.string() })),
items: z.array(
z.object({
id: z.string(),
cycle: z.number(),
policyVersion: z.number(),
submittedAt: date,
merchant: merchantSchema,
}),
),
});
export const pipelineBoardSchema = z.array( export const pipelineBoardSchema = z.array(
merchantSchema.extend({ capabilities: capabilitiesSchema }), merchantSchema.extend({ capabilities: capabilitiesSchema }),
); );
@@ -402,6 +503,7 @@ export const checklistEditSchema = versionSchema
export const reviewDecisionSchema = versionSchema export const reviewDecisionSchema = versionSchema
.extend({ .extend({
decision: z.enum(['APPROVED', 'REJECTED', 'CORRECTIONS']), decision: z.enum(['APPROVED', 'REJECTED', 'CORRECTIONS']),
riskLevel: z.enum(riskLevels).optional(),
reason: z.string().max(2000).default(''), reason: z.string().max(2000).default(''),
corrections: z corrections: z
.array( .array(
@@ -420,8 +522,12 @@ export const reviewDecisionSchema = versionSchema
}) })
.strict() .strict()
.superRefine((v, ctx) => { .superRefine((v, ctx) => {
if (v.decision !== 'APPROVED' && !v.reason.trim()) if (!v.reason.trim())
ctx.addIssue({ code: 'custom', path: ['reason'], message: 'validation.required' }); ctx.addIssue({ code: 'custom', path: ['reason'], message: 'validation.required' });
if (v.decision === 'APPROVED' && !v.riskLevel)
ctx.addIssue({ code: 'custom', path: ['riskLevel'], message: 'validation.required' });
if (v.decision !== 'APPROVED' && v.riskLevel)
ctx.addIssue({ code: 'custom', path: ['riskLevel'], message: 'validation.invalid' });
if (v.decision === 'CORRECTIONS' && !v.corrections.length) if (v.decision === 'CORRECTIONS' && !v.corrections.length)
ctx.addIssue({ code: 'custom', path: ['corrections'], message: 'validation.required' }); ctx.addIssue({ code: 'custom', path: ['corrections'], message: 'validation.required' });
if (v.decision !== 'CORRECTIONS' && v.corrections.length) if (v.decision !== 'CORRECTIONS' && v.corrections.length)
@@ -429,6 +535,13 @@ export const reviewDecisionSchema = versionSchema
if (new Set(v.corrections.map((c) => c.itemId)).size !== v.corrections.length) if (new Set(v.corrections.map((c) => c.itemId)).size !== v.corrections.length)
ctx.addIssue({ code: 'custom', path: ['corrections'], message: 'validation.invalid' }); ctx.addIssue({ code: 'custom', path: ['corrections'], message: 'validation.invalid' });
}); });
export const activationEditSchema = versionSchema
.extend({
reviewId: text,
state: z.enum(activationStates),
note: z.string().max(2000).nullable(),
})
.strict();
export const activityInputSchema = versionSchema export const activityInputSchema = versionSchema
.extend({ .extend({
kind: z.enum(activityKinds), kind: z.enum(activityKinds),
@@ -0,0 +1,28 @@
ALTER TYPE "DocumentCode" ADD VALUE 'AUTHORIZED_REPRESENTATIVE';
CREATE TYPE "RiskLevel" AS ENUM ('LOW', 'MEDIUM', 'HIGH');
CREATE TYPE "ActivationCode" AS ENUM ('API_CONNECTION', 'WEBHOOK_SETUP', 'TEST_PAYMENT', 'RECONCILIATION');
CREATE TYPE "ActivationState" AS ENUM ('INCOMPLETE', 'COMPLETE', 'NOT_RUN', 'PASSED', 'FAILED');
ALTER TABLE "ComplianceReview" ADD COLUMN "policyVersion" INTEGER NOT NULL DEFAULT 1,
ADD COLUMN "riskLevel" "RiskLevel",
ADD COLUMN "corrections" JSONB NOT NULL DEFAULT '[]';
ALTER TABLE "ComplianceReview" ALTER COLUMN "policyVersion" SET DEFAULT 2;
ALTER TABLE "ComplianceReview" ADD CONSTRAINT "ComplianceReview_current_approval" CHECK (
"policyVersion" < 2 OR "decision" <> 'APPROVED' OR
("riskLevel" IS NOT NULL AND "reason" IS NOT NULL AND length(trim("reason")) > 0)
);
CREATE TABLE "ActivationCheck" (
"id" TEXT PRIMARY KEY, "reviewId" TEXT NOT NULL REFERENCES "ComplianceReview"("id") ON DELETE CASCADE ON UPDATE CASCADE,
"code" "ActivationCode" NOT NULL, "state" "ActivationState" NOT NULL, "note" TEXT,
CONSTRAINT "ActivationCheck_state_for_code" CHECK (
("code" IN ('API_CONNECTION', 'WEBHOOK_SETUP') AND "state" IN ('INCOMPLETE', 'COMPLETE')) OR
("code" IN ('TEST_PAYMENT', 'RECONCILIATION') AND "state" IN ('NOT_RUN', 'PASSED', 'FAILED'))
)
);
CREATE UNIQUE INDEX "ActivationCheck_reviewId_code_key" ON "ActivationCheck"("reviewId", "code");
CREATE TABLE "ActivationCheckChange" (
"id" TEXT PRIMARY KEY, "checkId" TEXT NOT NULL REFERENCES "ActivationCheck"("id") ON DELETE CASCADE ON UPDATE CASCADE,
"actorId" TEXT NOT NULL REFERENCES "User"("id") ON DELETE RESTRICT ON UPDATE CASCADE,
"fromState" "ActivationState" NOT NULL, "toState" "ActivationState" NOT NULL, "note" TEXT,
"occurredAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP
);
CREATE INDEX "ActivationCheckChange_checkId_occurredAt_idx" ON "ActivationCheckChange"("checkId", "occurredAt");
@@ -0,0 +1,7 @@
-- A new missing record is not evidence of collection. Historical rows/snapshots remain intact.
INSERT INTO "KybChecklistItem" ("id", "merchantId", "documentCode", "state", "updatedAt")
SELECT gen_random_uuid()::text, "id", 'AUTHORIZED_REPRESENTATIVE', 'MISSING', CURRENT_TIMESTAMP
FROM "Merchant" WHERE "status" NOT IN ('LIVE', 'REJECTED')
ON CONFLICT ("merchantId", "documentCode") DO NOTHING;
-- Invalidate any editor opened against the old policy; preserve company/stage timestamps.
UPDATE "Merchant" SET "version" = "version" + 1 WHERE "status" NOT IN ('LIVE', 'REJECTED');
+46
View File
@@ -32,6 +32,25 @@ enum DocumentCode {
OWNERSHIP OWNERSHIP
UBO_IDENTIFICATION UBO_IDENTIFICATION
BUSINESS_ACTIVITY BUSINESS_ACTIVITY
AUTHORIZED_REPRESENTATIVE
}
enum RiskLevel {
LOW
MEDIUM
HIGH
}
enum ActivationCode {
API_CONNECTION
WEBHOOK_SETUP
TEST_PAYMENT
RECONCILIATION
}
enum ActivationState {
INCOMPLETE
COMPLETE
NOT_RUN
PASSED
FAILED
} }
enum TaskStatus { enum TaskStatus {
OPEN OPEN
@@ -70,6 +89,7 @@ model User {
completedTasks Task[] @relation("TaskCompleter") completedTasks Task[] @relation("TaskCompleter")
activities Activity[] activities Activity[]
checklistChanges ChecklistChange[] checklistChanges ChecklistChange[]
activationChanges ActivationCheckChange[]
submittedReviews ComplianceReview[] @relation("ReviewSubmitter") submittedReviews ComplianceReview[] @relation("ReviewSubmitter")
decidedReviews ComplianceReview[] @relation("ReviewReviewer") decidedReviews ComplianceReview[] @relation("ReviewReviewer")
createdAt DateTime @default(now()) createdAt DateTime @default(now())
@@ -202,6 +222,10 @@ model ComplianceReview {
id String @id @default(uuid()) id String @id @default(uuid())
merchantId String merchantId String
cycle Int cycle Int
policyVersion Int @default(2)
riskLevel RiskLevel?
corrections Json @default("[]")
activationChecks ActivationCheck[]
submittedById String submittedById String
reviewerId String? reviewerId String?
decision ReviewDecision @default(PENDING) decision ReviewDecision @default(PENDING)
@@ -215,6 +239,28 @@ model ComplianceReview {
@@unique([merchantId, cycle]) @@unique([merchantId, cycle])
@@index([decision, submittedAt]) @@index([decision, submittedAt])
} }
model ActivationCheck {
id String @id @default(uuid())
reviewId String
code ActivationCode
state ActivationState
note String?
review ComplianceReview @relation(fields: [reviewId], references: [id], onDelete: Cascade)
changes ActivationCheckChange[]
@@unique([reviewId, code])
}
model ActivationCheckChange {
id String @id @default(uuid())
checkId String
actorId String
fromState ActivationState
toState ActivationState
note String?
occurredAt DateTime @default(now())
check ActivationCheck @relation(fields: [checkId], references: [id], onDelete: Cascade)
actor User @relation(fields: [actorId], references: [id])
@@index([checkId, occurredAt])
}
model DemoSeedState { model DemoSeedState {
id String @id id String @id
anchorAt DateTime @default(now()) anchorAt DateTime @default(now())
+69 -6
View File
@@ -1,5 +1,13 @@
import { config } from 'dotenv'; import { config } from 'dotenv';
import { documentCodes, sources, successfulStages, type Status } from '@merchantflow/contracts'; import {
documentCodes,
requiredDocumentCodes,
activationCodes,
isIntegrationCheck,
sources,
successfulStages,
type Status,
} from '@merchantflow/contracts';
import { createDatabase, type Prisma } from './index.js'; import { createDatabase, type Prisma } from './index.js';
import { hashPassword } from './password.js'; import { hashPassword } from './password.js';
import { reviewSnapshot } from './workflow.js'; import { reviewSnapshot } from './workflow.js';
@@ -296,7 +304,7 @@ async function createMerchant(tx: Prisma.TransactionClient, index: number, ancho
})), })),
}, },
checklist: { checklist: {
create: documentCodes.map((documentCode, j) => ({ create: requiredDocumentCodes.map((documentCode, j) => ({
id: `${id}-doc-${j}`, id: `${id}-doc-${j}`,
documentCode, documentCode,
state: state:
@@ -371,6 +379,11 @@ async function enrich(
anchor: number, anchor: number,
) { ) {
const actorId = m.ownerId ?? 'user-head'; const actorId = m.ownerId ?? 'user-head';
const policyVersion = m.checklist.some(
(item) => item.documentCode === 'AUTHORIZED_REPRESENTATIVE',
)
? 2
: 1;
const allReceived = m.checklist.map((item) => ({ ...item, state: 'RECEIVED', note: null })); const allReceived = m.checklist.map((item) => ({ ...item, state: 'RECEIVED', note: null }));
for (const item of m.checklist) for (const item of m.checklist)
await tx.checklistChange.create({ await tx.checklistChange.create({
@@ -417,6 +430,18 @@ async function enrich(
id: `${m.id}-review-${cycle}`, id: `${m.id}-review-${cycle}`,
merchantId: m.id, merchantId: m.id,
cycle, cycle,
policyVersion,
riskLevel: policyVersion === 2 && decision === 'APPROVED' ? 'LOW' : null,
corrections:
policyVersion === 2 && decision === 'CORRECTIONS'
? m.checklist
.filter((item) => item.documentCode === 'AUTHORIZED_REPRESENTATIVE')
.map((item) => ({
itemId: item.id,
documentCode: item.documentCode,
note: 'Provide a signed identification record for the authorized representative.',
}))
: [],
submittedById: actorId, submittedById: actorId,
reviewerId: next ? 'user-compliance' : null, reviewerId: next ? 'user-compliance' : null,
decision, decision,
@@ -429,16 +454,54 @@ async function enrich(
? (next?.note ?? ? (next?.note ??
'Unable to verify the beneficial owner; the submitted register conflicts with the ownership declaration.') 'Unable to verify the beneficial owner; the submitted register conflicts with the ownership declaration.')
: decision === 'APPROVED' : decision === 'APPROVED'
? 'Company registration, ownership, UBO identification and business activity checks passed.' ? policyVersion === 2
? 'Company registration, ownership and authorized-representative identification checks passed.'
: 'Company registration, ownership, UBO identification and business activity checks passed.'
: null, : null,
snapshot: reviewSnapshot({ ...m, checklist: allReceived }), snapshot: reviewSnapshot({ ...m, checklist: allReceived }, policyVersion),
}, },
}); });
if (decision === 'APPROVED' && policyVersion === 2) {
for (const code of activationCodes) {
const stage = isIntegrationCheck(code) ? 'TESTING' : 'LIVE';
const event = m.events.find((entry) => entry.toStatus === stage);
const initial = isIntegrationCheck(code) ? ('INCOMPLETE' as const) : ('NOT_RUN' as const);
const state = event
? isIntegrationCheck(code)
? ('COMPLETE' as const)
: ('PASSED' as const)
: initial;
await tx.activationCheck.create({
data: {
id: `${m.id}-${cycle}-${code}`,
reviewId: `${m.id}-review-${cycle}`,
code,
state,
note: event ? 'Fictional demo check recorded for this onboarding cycle.' : null,
...(event
? {
changes: {
create: {
actorId,
fromState: initial,
toState: state,
note: 'Fictional demo check recorded for this onboarding cycle.',
occurredAt: new Date(event.occurredAt.getTime() - 1),
},
},
}
: {}),
},
});
}
}
if (decision === 'CORRECTIONS') if (decision === 'CORRECTIONS')
for (const item of m.checklist.filter((item) => for (const item of m.checklist.filter((item) =>
['UBO_IDENTIFICATION', 'BUSINESS_ACTIVITY'].includes(item.documentCode), ['UBO_IDENTIFICATION', 'BUSINESS_ACTIVITY', 'AUTHORIZED_REPRESENTATIVE'].includes(
item.documentCode,
),
)) { )) {
const state = item.documentCode === 'UBO_IDENTIFICATION' ? 'NEEDS_CORRECTION' : 'MISSING'; const state = item.documentCode !== 'BUSINESS_ACTIVITY' ? 'NEEDS_CORRECTION' : 'MISSING';
await tx.checklistChange.create({ await tx.checklistChange.create({
data: { data: {
id: `${item.id}-correction-${cycle}`, id: `${item.id}-correction-${cycle}`,
+9 -7
View File
@@ -1,4 +1,4 @@
import { documentCodes } from '@merchantflow/contracts'; import { requiredDocumentCodes, isRequiredDocument } from '@merchantflow/contracts';
export const reviewedFields = [ export const reviewedFields = [
'name', 'name',
@@ -13,20 +13,22 @@ type ReviewedMerchant = Record<(typeof reviewedFields)[number], string | null> &
checklist: { id: string; documentCode: string; state: string; note: string | null }[]; checklist: { id: string; documentCode: string; state: string; note: string | null }[];
}; };
// Stable, minimal evidence: commercial estimates/contact edits do not invalidate approval. // Stable, minimal evidence: commercial estimates/contact edits do not invalidate approval.
export function reviewSnapshot(merchant: ReviewedMerchant) { export function reviewSnapshot(merchant: ReviewedMerchant, policyVersion = 2) {
return { return {
company: Object.fromEntries(reviewedFields.map((key) => [key, merchant[key]])), company: Object.fromEntries(reviewedFields.map((key) => [key, merchant[key]])),
checklist: [...merchant.checklist] checklist: [...merchant.checklist]
.filter((item) =>
policyVersion >= 2
? isRequiredDocument(item.documentCode)
: item.documentCode !== 'AUTHORIZED_REPRESENTATIVE',
)
.sort((a, b) => a.documentCode.localeCompare(b.documentCode)) .sort((a, b) => a.documentCode.localeCompare(b.documentCode))
.map(({ id, documentCode, state, note }) => ({ id, documentCode, state, note })), .map(({ id, documentCode, state, note }) => ({ id, documentCode, state, note })),
}; };
} }
export function checklistComplete(items: { documentCode: string; state: string }[]) { export function checklistComplete(items: { documentCode: string; state: string }[]) {
return ( return requiredDocumentCodes.every((code) =>
items.length === documentCodes.length && items.some((item) => item.documentCode === code && item.state === 'RECEIVED'),
documentCodes.every((code) =>
items.some((item) => item.documentCode === code && item.state === 'RECEIVED'),
)
); );
} }
export function snapshotsEqual(a: unknown, b: unknown): boolean { export function snapshotsEqual(a: unknown, b: unknown): boolean {
+1
View File
@@ -28,5 +28,6 @@ if (mode === 'integration')
'apps/api/test/integration.test.mjs', 'apps/api/test/integration.test.mjs',
'apps/api/test/public-leads.test.mjs', 'apps/api/test/public-leads.test.mjs',
'apps/api/test/sales-workspace.test.mjs', 'apps/api/test/sales-workspace.test.mjs',
'apps/api/test/gated-onboarding.test.mjs',
]); ]);
else run('pnpm', ['exec', 'playwright', 'test']); else run('pnpm', ['exec', 'playwright', 'test']);
+1 -1
View File
@@ -110,7 +110,7 @@ try {
})), })),
}, },
checklist: { checklist: {
create: documentCodes.map((documentCode, j) => ({ create: documentCodes.slice(0, 4).map((documentCode, j) => ({
id: `${id}-doc-${j}`, id: `${id}-doc-${j}`,
documentCode, documentCode,
state: state:
+1 -1
View File
@@ -169,7 +169,7 @@ for (const language of ['en', 'ru'])
expect(merchants[0]?.ownerId).toBeNull(); expect(merchants[0]?.ownerId).toBeNull();
expect(merchants[0]?.activities).toHaveLength(1); expect(merchants[0]?.activities).toHaveLength(1);
expect(merchants[0]?.events).toHaveLength(1); expect(merchants[0]?.events).toHaveLength(1);
expect(merchants[0]?.checklist).toHaveLength(4); expect(merchants[0]?.checklist).toHaveLength(3);
expect(runtimeErrors).toEqual([]); expect(runtimeErrors).toEqual([]);
}); });
}); });
+224
View File
@@ -0,0 +1,224 @@
import { test, expect, type APIRequestContext } from '@playwright/test';
import { createDatabase } from '../packages/database/dist/index.js';
const origin = 'http://127.0.0.1:5174';
async function login(request: APIRequestContext, actor: string) {
const result = await request.post('/api/auth/login', {
headers: { origin },
data: { email: `${actor}@merchantflow.test`, password: 'MerchantFlow123!' },
});
expect(result.status()).toBe(201);
}
async function pending(request: APIRequestContext, name: string) {
await login(request, 'head');
const created = await request.post('/api/merchants', {
headers: { origin },
data: {
name,
contactName: 'Queue Contact',
contactEmail: '[email protected]',
website: 'https://queue.test',
country: 'GB',
industry: 'SOFTWARE',
estimatedMonthlyVolumeUsd: '0',
ownerId: 'user-manager1',
},
});
expect(created.status()).toBe(201);
const { id } = await created.json();
const detail = async () => (await request.get(`/api/merchants/${id}`)).json();
const mutate = async (path: string, data: object, method = 'POST') => {
const response = await request.fetch(`/api/merchants/${id}${path}`, {
method,
headers: { origin },
data: { version: (await detail()).version, ...data },
});
expect(response.ok()).toBe(true);
};
await mutate('/activities', { kind: 'CALL', text: 'Confirmed onboarding requirements' });
for (const toStatus of ['CONTACTED', 'QUALIFIED', 'KYB'])
await mutate('/transitions', { toStatus });
for (const item of (await detail()).checklist)
await mutate(
`/checklist/${item.id}`,
{ state: 'RECEIVED', note: 'Received for review' },
'PATCH',
);
await mutate('/transitions', { toStatus: 'COMPLIANCE_REVIEW' });
return await detail();
}
async function remove(id: string) {
if (!process.env.DATABASE_URL?.endsWith('/merchantflow_test'))
throw new Error('Test database only');
const db = createDatabase(process.env.DATABASE_URL);
try {
await db.merchant.delete({ where: { id } });
} finally {
await db.$disconnect();
}
}
for (const language of ['en', 'ru'])
for (const width of [390, 1440]) {
test(`Compliance queue, review validation and rejection ${language} ${width}px`, async ({
page,
}, info) => {
await page.setViewportSize({ width, height: 1000 });
await page.addInitScript(
(lang) => localStorage.setItem('merchantflow.language', lang),
language,
);
const name = `Queue specimen ${language} ${width}`;
const merchant = await pending(page.request, name);
try {
await login(page.request, 'compliance');
await page.goto('/app/review-queue');
const search = page.getByRole('textbox', { name: /Search merchants|Поиск мерчантов/ });
await search.fill(name);
await page
.getByRole('combobox', { name: /Account manager|Аккаунт-менеджер/ })
.selectOption('user-manager1');
await expect(page.locator('article')).toHaveCount(1);
await expect(page.locator('article')).toContainText(/Waiting|Ожидание/);
await page
.getByRole('combobox', { name: /Waiting time|Время ожидания/ })
.selectOption('24');
await expect(page.locator('article')).toHaveCount(0);
await expect(page).toHaveURL(/waiting=24/);
await page.reload();
await expect(search).toHaveValue(name);
await page
.getByRole('combobox', { name: /Waiting time|Время ожидания/ })
.selectOption('ALL');
await expect(page.locator('article')).toHaveCount(1);
expect(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth)).toBe(
true,
);
await page.screenshot({ path: info.outputPath('review-queue.png'), fullPage: true });
const pendingId = merchant.reviews[0].id;
await page.getByRole('link', { name: /Open review|Открыть проверку/ }).click();
await expect(page).toHaveURL(new RegExp(`tab=onboarding#review-${pendingId}`));
await expect(page.locator(`#review-${pendingId}`)).toBeFocused();
await expect(
page.getByRole('button', { name: /Update collection|Обновить сбор/ }),
).toHaveCount(0);
await page
.getByRole('button', { name: /Record decision|Записать решение/, exact: true })
.click();
const dialog = page.getByRole('dialog');
await dialog.getByRole('button', { name: /^(Approve|Одобрить)$/ }).click();
await expect(dialog.getByLabel(/Risk level|Уровень риска/)).toHaveAttribute(
'aria-invalid',
'true',
);
await dialog.getByLabel(/Decision$|^Решение$/).selectOption('REJECTED');
await expect(dialog.getByLabel(/Risk level|Уровень риска/)).toHaveCount(0);
await dialog.getByRole('button', { name: /^(Reject|Отклонить)$/ }).click();
const reason = dialog.getByLabel(/Rejection reason|Причина отклонения/);
await expect(reason).toHaveAttribute('aria-invalid', 'true');
await reason.fill('Representative authority could not be confirmed.');
await page.route(
'**/api/merchants/*/reviews/*/decision',
(route) =>
route.fulfill({
status: 409,
contentType: 'application/json',
body: JSON.stringify({ code: 'CONFLICT' }),
}),
{ times: 1 },
);
await dialog.getByRole('button', { name: /^(Reject|Отклонить)$/ }).click();
await expect(dialog.getByRole('alert')).toBeVisible();
await expect(reason).toHaveValue('Representative authority could not be confirmed.');
await dialog.getByRole('button', { name: /^(Reject|Отклонить)$/ }).click();
await expect(dialog).not.toBeVisible();
await expect
.poll(
async () =>
(await (await page.request.get(`/api/merchants/${merchant.id}`)).json()).status,
)
.toBe('REJECTED');
await page.reload();
await expect(page.locator(`#review-${pendingId}`)).toContainText(
'Representative authority could not be confirmed.',
);
await expect(
page.getByRole('button', { name: /Record decision|Записать решение/ }),
).toHaveCount(0);
expect(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth)).toBe(
true,
);
await page.screenshot({ path: info.outputPath('rejected-review.png'), fullPage: true });
} finally {
await remove(merchant.id);
}
});
}
test('an open decision form stays bound to its original cycle after another reviewer requests changes and Sales resubmits', async ({
page,
browser,
}) => {
const merchant = await pending(page.request, 'Stale decision form specimen');
const staff = await browser.newContext({ baseURL: origin });
try {
await login(staff.request, 'head');
await login(page.request, 'compliance');
await page.goto(`/app/merchants/${merchant.id}?tab=onboarding`);
await page.getByRole('button', { name: 'Record decision', exact: true }).click();
const dialog = page.getByRole('dialog');
await dialog.getByLabel('Risk level', { exact: true }).selectOption('LOW');
await dialog
.getByLabel('Approval rationale (required)', { exact: true })
.fill('Assessment of the original submission.');
const reviewId = merchant.reviews[0].id;
const itemId = merchant.checklist[0].id;
const correction = await page.request.post(
`/api/merchants/${merchant.id}/reviews/${reviewId}/decision`,
{
headers: { origin },
data: {
version: merchant.version,
decision: 'CORRECTIONS',
reason: 'A newer record is required',
corrections: [{ itemId, note: 'Collect the updated record' }],
},
},
);
expect(correction.status()).toBe(201);
const detail = async () => (await staff.request.get(`/api/merchants/${merchant.id}`)).json();
const collect = await staff.request.patch(`/api/merchants/${merchant.id}/checklist/${itemId}`, {
headers: { origin },
data: {
version: (await detail()).version,
state: 'RECEIVED',
note: 'New submission evidence',
},
});
expect(collect.status()).toBe(200);
const submit = await staff.request.post(`/api/merchants/${merchant.id}/transitions`, {
headers: { origin },
data: { version: (await detail()).version, toStatus: 'COMPLIANCE_REVIEW' },
});
expect(submit.status()).toBe(201);
const newReviewId = (await detail()).reviews[0].id;
expect(newReviewId).not.toBe(reviewId);
for (let attempt = 0; attempt < 2; attempt++) {
const response = page.waitForResponse((response) =>
response.url().includes(`/reviews/${reviewId}/decision`),
);
await dialog.getByRole('button', { name: 'Approve', exact: true }).click();
expect((await response).status()).toBe(409);
await expect(dialog.getByRole('alert')).toBeVisible();
await expect(dialog.getByLabel('Approval rationale (required)', { exact: true })).toHaveValue(
'Assessment of the original submission.',
);
}
const current = await detail();
expect(current.status).toBe('COMPLIANCE_REVIEW');
expect(current.reviews[0].decision).toBe('PENDING');
expect(current.reviews[0].id).toBe(newReviewId);
} finally {
await staff.close();
await remove(merchant.id);
}
});
+34 -11
View File
@@ -130,7 +130,7 @@ test('account switching removes old data, manager isolation and Compliance navig
expect((await (await page.request.get('/api/dashboard')).json()).merchantCount).toBe(45); expect((await (await page.request.get('/api/dashboard')).json()).merchantCount).toBe(45);
await page.getByRole('link', { name: 'Review queue', exact: true }).click(); await page.getByRole('link', { name: 'Review queue', exact: true }).click();
await expect(page.getByRole('heading', { name: '6 merchants awaiting review' })).toBeVisible(); await expect(page.getByRole('heading', { name: '6 merchants awaiting review' })).toBeVisible();
await page.getByRole('link', { name: 'View checklist' }).first().click(); await page.getByRole('link', { name: 'Open review' }).first().click();
await expect(page.getByRole('heading', { name: 'KYB checklist' })).toBeVisible(); await expect(page.getByRole('heading', { name: 'KYB checklist' })).toBeVisible();
await page.goto('/app/merchants/merchant-15'); await page.goto('/app/merchants/merchant-15');
await expect(page.locator('h1')).toHaveText('Sunday Market'); await expect(page.locator('h1')).toHaveText('Sunday Market');
@@ -264,11 +264,11 @@ test('Head assignment, manager editing, Compliance decisions and manager activat
await advance('Qualified'); await advance('Qualified');
await advance('KYB'); await advance('KYB');
await page.getByRole('tab', { name: 'Onboarding', exact: true }).click(); await page.getByRole('tab', { name: 'Onboarding', exact: true }).click();
for (let i = 0; i < 4; i++) { for (let i = 0; i < 3; i++) {
await page.getByRole('button', { name: 'Update document', exact: true }).nth(i).click(); await page.getByRole('button', { name: 'Update collection', exact: true }).nth(i).click();
await page await page
.getByRole('dialog') .getByRole('dialog')
.getByLabel('Document status', { exact: true }) .getByLabel('Collection status', { exact: true })
.selectOption('RECEIVED'); .selectOption('RECEIVED');
await save(); await save();
} }
@@ -283,26 +283,30 @@ test('Head assignment, manager editing, Compliance decisions and manager activat
.selectOption('CORRECTIONS'); .selectOption('CORRECTIONS');
await page await page
.getByRole('dialog') .getByRole('dialog')
.getByLabel('Decision reason', { exact: true }) .getByLabel('Required changes (required)', { exact: true })
.fill('The ownership declaration needs a current signature.'); .fill('The ownership declaration needs a current signature.');
await page await page
.getByRole('dialog') .getByRole('dialog')
.getByLabel('Ownership structure', { exact: true }) .getByLabel('Ownership structure', { exact: true })
.fill('Please sign and date the declaration.'); .fill('Please sign and date the declaration.');
await save(); await page
.getByRole('dialog')
.getByRole('button', { name: 'Request changes', exact: true })
.click();
await expect(page.getByRole('dialog')).not.toBeVisible();
await switchAccount('alex'); await switchAccount('alex');
await page.getByRole('tab', { name: 'Onboarding', exact: true }).click(); await page.getByRole('tab', { name: 'Onboarding', exact: true }).click();
const ownership = page const ownership = page
.locator('#checklist > div > div') .locator('#checklist > div > div')
.filter({ hasText: 'Ownership structure' }); .filter({ hasText: 'Ownership structure' });
await ownership.getByRole('button', { name: 'Update document', exact: true }).click(); await ownership.getByRole('button', { name: 'Update collection', exact: true }).click();
await page await page
.getByRole('dialog') .getByRole('dialog')
.getByLabel('Document status', { exact: true }) .getByLabel('Collection status', { exact: true })
.selectOption('RECEIVED'); .selectOption('RECEIVED');
await page await page
.getByRole('dialog') .getByRole('dialog')
.getByLabel('Note', { exact: true }) .getByLabel('Collection notes', { exact: true })
.fill('Updated signature received.'); .fill('Updated signature received.');
await save(); await save();
await advance('Compliance Review'); await advance('Compliance Review');
@@ -311,9 +315,11 @@ test('Head assignment, manager editing, Compliance decisions and manager activat
await page.getByRole('button', { name: 'Record decision', exact: true }).click(); await page.getByRole('button', { name: 'Record decision', exact: true }).click();
await page await page
.getByRole('dialog') .getByRole('dialog')
.getByLabel('Decision reason', { exact: true }) .getByLabel('Approval rationale (required)', { exact: true })
.fill('All evidence checked and approved.'); .fill('All evidence checked and approved.');
await save(); await page.getByRole('dialog').getByLabel('Risk level', { exact: true }).selectOption('LOW');
await page.getByRole('dialog').getByRole('button', { name: 'Approve', exact: true }).click();
await expect(page.getByRole('dialog')).not.toBeVisible();
await expect(page.getByRole('button', { name: 'Edit merchant', exact: true })).toHaveCount(0); await expect(page.getByRole('button', { name: 'Edit merchant', exact: true })).toHaveCount(0);
await switchAccount('alex'); await switchAccount('alex');
await page.getByRole('button', { name: 'Edit merchant', exact: true }).click(); await page.getByRole('button', { name: 'Edit merchant', exact: true }).click();
@@ -321,7 +327,24 @@ test('Head assignment, manager editing, Compliance decisions and manager activat
page.getByRole('dialog').getByLabel('Legal company name', { exact: true }), page.getByRole('dialog').getByLabel('Legal company name', { exact: true }),
).toBeDisabled(); ).toBeDisabled();
await page.getByRole('button', { name: 'Cancel', exact: true }).click(); await page.getByRole('button', { name: 'Cancel', exact: true }).click();
await page.getByRole('tab', { name: 'Onboarding', exact: true }).click();
const check = async (name: string, result: string) => {
const row = page
.locator('article')
.filter({ has: page.getByRole('heading', { name, exact: true }) });
await row.getByRole('button', { name: 'Update demo check' }).click();
await page.getByRole('dialog').getByLabel('Result', { exact: true }).selectOption(result);
await save();
};
await expect(page.getByRole('button', { name: 'Move to Testing', exact: true })).toBeDisabled();
await check('API connection', 'COMPLETE');
await check('Webhook setup', 'COMPLETE');
await advance('Testing'); await advance('Testing');
await expect(page.getByRole('button', { name: 'Move to Live', exact: true })).toBeDisabled();
await check('Test payment', 'FAILED');
await check('Reconciliation', 'PASSED');
await expect(page.getByRole('button', { name: 'Move to Live', exact: true })).toBeDisabled();
await check('Test payment', 'PASSED');
await advance('Live'); await advance('Live');
await noOverflow(page); await noOverflow(page);
await page.screenshot({ path: info.outputPath('approved-live-merchant.png'), fullPage: true }); await page.screenshot({ path: info.outputPath('approved-live-merchant.png'), fullPage: true });