diff --git a/README.md b/README.md index 7cd6f1e..e5bc5d9 100644 --- a/README.md +++ b/README.md @@ -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. -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. @@ -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. -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. @@ -169,7 +169,7 @@ The old manager account IDs are retained while the original addresses become `al ## 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. @@ -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. 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-` 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. diff --git a/apps/api/src/access.ts b/apps/api/src/access.ts index d277e8f..e667378 100644 --- a/apps/api/src/access.ts +++ b/apps/api/src/access.ts @@ -1,7 +1,8 @@ import type { User } from '@merchantflow/contracts'; import type { Prisma } from '@merchantflow/database'; import type { Capabilities } from '@merchantflow/contracts'; -import { workflowActions, type Evidence } from './workflow-policy.js'; +import { workflowActions, validApproval, canReopenKyb, type Evidence } from './workflow-policy.js'; +import { activationCodes, isIntegrationCheck, reviewPolicyVersion } from '@merchantflow/contracts'; import { ApiError } from './shared.js'; export function merchantScope(user: User): Prisma.MerchantWhereInput { switch (user.role) { @@ -29,16 +30,53 @@ export function capabilities(user: User, merchant: Evidence): Capabilities { const sales = user.role === 'HEAD_OF_SALES' || (user.role === 'ACCOUNT_MANAGER' && merchant.ownerId === user.id); - const locked = merchant.reviews.some((review) => - ['PENDING', 'APPROVED'].includes(review.decision), - ); + const locked = + merchant.reviews.some((review) => review.decision === 'PENDING') || + (merchant.reviews[0]?.decision === 'APPROVED' && + (merchant.reviews[0].policyVersion >= reviewPolicyVersion || merchant.status !== 'KYB')); const actions = workflowActions(user, merchant); + const terminal = ['LIVE', 'REJECTED'].includes(merchant.status); + const reopen = canReopenKyb(merchant); return { editCommercial: sales, editIdentity: sales && !locked, assign: user.role === 'HEAD_OF_SALES', collectChecklist: sales && merchant.status === 'KYB' && !locked, review: user.role === 'COMPLIANCE_OFFICER' && merchant.status === 'COMPLIANCE_REVIEW', + reopenKyb: sales && reopen, + activationCodes: + sales && validApproval(merchant) + ? activationCodes.filter((code) => + isIntegrationCheck(code) + ? merchant.status === 'INTEGRATION' + : merchant.status === 'TESTING', + ) + : [], + handoff: { + owner: terminal + ? 'NONE' + : merchant.status === 'COMPLIANCE_REVIEW' + ? 'COMPLIANCE_OFFICER' + : !merchant.ownerId + ? 'HEAD_OF_SALES' + : 'ACCOUNT_MANAGER', + ownerId: terminal || merchant.status === 'COMPLIANCE_REVIEW' ? null : merchant.ownerId, + action: terminal + ? 'COMPLETE' + : merchant.status === 'COMPLIANCE_REVIEW' + ? 'REVIEW' + : !merchant.ownerId + ? 'ASSIGN' + : reopen + ? 'REOPEN_KYB' + : merchant.status === 'KYB' + ? 'COLLECT' + : merchant.status === 'INTEGRATION' + ? 'INTEGRATE' + : merchant.status === 'TESTING' + ? 'TEST' + : 'COMMERCIAL', + }, activityKinds: user.role === 'COMPLIANCE_OFFICER' ? (['KYB_NOTE'] as const) diff --git a/apps/api/src/crm.ts b/apps/api/src/crm.ts index 6a22a8f..b5314d8 100644 --- a/apps/api/src/crm.ts +++ b/apps/api/src/crm.ts @@ -1,6 +1,11 @@ import { Controller, Get, Inject, Param, Query, Req, UseGuards } from '@nestjs/common'; import { PrismaClient, type Prisma } from '@merchantflow/database'; -import { statuses, merchantQuerySchema, taskQuerySchema } from '@merchantflow/contracts'; +import { + statuses, + merchantQuerySchema, + taskQuerySchema, + reviewQueueQuerySchema, +} from '@merchantflow/contracts'; import { SessionGuard } from './auth.js'; import { DATABASE, ApiError, type AuthRequest } from './shared.js'; import { capabilities, merchantScope, taskScope } from './access.js'; @@ -185,6 +190,10 @@ export class CrmController { cycle: true, decision: true, reason: true, + policyVersion: true, + riskLevel: true, + corrections: true, + snapshot: true, submittedAt: true, decidedAt: true, submittedBy: { select: { name: true } }, @@ -202,6 +211,7 @@ export class CrmController { const history = await merchantHistory(merchant, tx); return { ...merchant, + activationChecks: evidence.reviews.flatMap((review) => review.activationChecks), activities: merchant.activities.map(({ metadata: _metadata, ...activity }) => activity), capabilities: capabilities(req.user, evidence), history, @@ -244,13 +254,60 @@ export class CrmController { orderBy: [{ status: 'asc' }, { dueAt: 'asc' }], }); } - @Get('review-queue') reviewQueue(@Req() req: AuthRequest) { + @Get('review-queue') async reviewQueue(@Req() req: AuthRequest, @Query() query: unknown) { if (req.user.role !== 'COMPLIANCE_OFFICER') throw new ApiError('FORBIDDEN', 403); - return this.db.merchant.findMany({ - where: { AND: [merchantScope(req.user), { status: 'COMPLIANCE_REVIEW' }] }, - select: merchantSelect, - orderBy: [{ stageEnteredAt: 'asc' }, { id: 'asc' }], - }); + const { search, ownerId, waiting } = reviewQueueQuerySchema.parse(query); + const base: Prisma.ComplianceReviewWhereInput = { + decision: 'PENDING', + merchant: { AND: [merchantScope(req.user), { status: 'COMPLIANCE_REVIEW' }] }, + }; + return this.db.$transaction( + async (tx) => { + const pendingCount = await tx.complianceReview.count({ where: base }); + const owners = await tx.user.findMany({ + where: { role: 'ACCOUNT_MANAGER' }, + select: { id: true, name: true }, + orderBy: { name: 'asc' }, + }); + const items = await tx.complianceReview.findMany({ + where: { + AND: [ + base, + { + ...(waiting !== 'ALL' + ? { submittedAt: { lte: new Date(Date.now() - Number(waiting) * 3600000) } } + : {}), + merchant: { + ...(ownerId ? { ownerId: ownerId === 'unassigned' ? null : ownerId } : {}), + ...(search + ? { + OR: ['name', 'legalName', 'contactName', 'contactEmail', 'website'].map( + (field) => ({ [field]: { contains: search, mode: 'insensitive' } }), + ), + } + : {}), + }, + }, + ], + }, + select: { + id: true, + cycle: true, + policyVersion: true, + submittedAt: true, + merchant: { select: merchantSelect }, + }, + orderBy: [{ submittedAt: 'asc' }, { id: 'asc' }], + }); + return { + items, + pendingCount, + filteredCount: items.length, + owners, + }; + }, + { isolationLevel: 'RepeatableRead' }, + ); } @Get('dashboard') async dashboard(@Req() req: AuthRequest) { const scope = merchantScope(req.user); @@ -271,7 +328,9 @@ export class CrmController { recentActivities, ] = await this.db.$transaction([ this.db.merchant.count({ where: scope }), - this.db.merchant.count({ where: { AND: [scope, { status: 'COMPLIANCE_REVIEW' }] } }), + this.db.complianceReview.count({ + where: { decision: 'PENDING', merchant: { AND: [scope, { status: 'COMPLIANCE_REVIEW' }] } }, + }), this.db.task.count({ where: { ...taskScope(req.user), status: 'OPEN', dueAt: { lt: new Date() } }, }), diff --git a/apps/api/src/public-leads.ts b/apps/api/src/public-leads.ts index 0a9b396..6ad63d9 100644 --- a/apps/api/src/public-leads.ts +++ b/apps/api/src/public-leads.ts @@ -4,7 +4,7 @@ import type { Request, Response } from 'express'; import { z } from 'zod'; import { PrismaClient } from '@merchantflow/database'; import { - documentCodes, + requiredDocumentCodes, publicLeadKeySchema, publicLeadSchema, type PublicLead, @@ -127,7 +127,10 @@ export class PublicLeadService { createdAt: now, stageEnteredAt: now, checklist: { - create: documentCodes.map((documentCode) => ({ documentCode, state: 'MISSING' })), + create: requiredDocumentCodes.map((documentCode) => ({ + documentCode, + state: 'MISSING', + })), }, events: { create: { fromStatus: null, toStatus: 'NEW_LEAD', occurredAt: now } }, activities: { diff --git a/apps/api/src/workflow-policy.ts b/apps/api/src/workflow-policy.ts index e51f8b9..91404b6 100644 --- a/apps/api/src/workflow-policy.ts +++ b/apps/api/src/workflow-policy.ts @@ -8,6 +8,11 @@ import { countryCodes, industries, successfulStages, + isRequiredDocument, + requiredDocumentCodes, + activationCodes, + isIntegrationCheck, + reviewPolicyVersion, type BlockingReason, type User, type WorkflowAction, @@ -18,7 +23,18 @@ export const evidenceInclude = { include: { changes: { orderBy: [{ occurredAt: 'asc' as const }, { id: 'asc' as const }] } }, }, reviews: { - include: { reviewer: { select: { role: true } } }, + include: { + reviewer: { select: { role: true } }, + activationChecks: { + orderBy: { code: 'asc' as const }, + include: { + changes: { + include: { actor: { select: { name: true } } }, + orderBy: [{ occurredAt: 'asc' as const }, { id: 'asc' as const }], + }, + }, + }, + }, orderBy: { cycle: 'desc' as const }, }, activities: { select: { kind: true } }, @@ -28,16 +44,22 @@ export type Evidence = Prisma.MerchantGetPayload<{ include: typeof evidenceInclu export function receivedHistory(merchant: Evidence, at: Date) { return ( checklistComplete(merchant.checklist) && - merchant.checklist.every( - (item) => - item.changes.filter((change) => change.occurredAt <= at).at(-1)?.toState === 'RECEIVED', - ) + merchant.checklist + .filter((item) => isRequiredDocument(item.documentCode)) + .every( + (item) => + item.changes.filter((change) => change.occurredAt <= at).at(-1)?.toState === 'RECEIVED', + ) ); } export function validApproval(merchant: Evidence) { const review = merchant.reviews[0]; return !!( review?.decision === 'APPROVED' && + review.policyVersion === reviewPolicyVersion && + review.riskLevel && + review.reason?.trim() && + !merchant.reviews.some((cycle) => cycle.decision === 'PENDING') && review.reviewer?.role === 'COMPLIANCE_OFFICER' && review.decidedAt && review.decidedAt >= review.submittedAt && @@ -45,6 +67,22 @@ export function validApproval(merchant: Evidence) { snapshotsEqual(review.snapshot, reviewSnapshot(merchant)) ); } +export function canReopenKyb(merchant: Evidence) { + return ( + ['INTEGRATION', 'TESTING'].includes(merchant.status) && + !merchant.reviews.some((review) => review.decision === 'PENDING') && + (!merchant.reviews[0] || merchant.reviews[0].policyVersion < reviewPolicyVersion) + ); +} +export function incompleteActivation(merchant: Evidence, includeTesting: boolean) { + const review = merchant.reviews[0]; + return activationCodes.filter((code) => { + if (!includeTesting && !isIntegrationCheck(code)) return false; + const expected = isIntegrationCheck(code) ? 'COMPLETE' : 'PASSED'; + const check = review?.activationChecks.find((item) => item.code === code); + return !check || check.state !== expected || check.changes.at(-1)?.toState !== expected; + }); +} export function qualificationFields(merchant: Evidence) { const fields: string[] = []; for (const field of ['name', 'website', 'contactName', 'contactEmail'] as const) @@ -63,8 +101,7 @@ export function workflowActions(user: User, merchant: Evidence): WorkflowAction[ if (merchant.status === 'COMPLIANCE_REVIEW') { const blockers: BlockingReason[] = user.role === 'COMPLIANCE_OFFICER' ? [] : [{ code: 'COMPLIANCE_ONLY' }]; - if (!merchant.reviews.some((review) => review.decision === 'PENDING')) - blockers.push({ code: 'REVIEW_PENDING' }); + if (merchant.reviews[0]?.decision !== 'PENDING') blockers.push({ code: 'REVIEW_PENDING' }); return [ { kind: 'REVIEW', @@ -91,12 +128,23 @@ export function workflowActions(user: User, merchant: Evidence): WorkflowAction[ } if (toStatus === 'COMPLIANCE_REVIEW') { if (!receivedHistory(merchant, new Date())) - blockingReasons.push({ code: 'DOCUMENTS_REQUIRED' }); + blockingReasons.push({ + code: 'DOCUMENTS_REQUIRED', + items: requiredDocumentCodes.filter((code) => { + const item = merchant.checklist.find((entry) => entry.documentCode === code); + return !item || item.state !== 'RECEIVED' || item.changes.at(-1)?.toState !== 'RECEIVED'; + }), + }); if (merchant.reviews.some((r) => r.decision === 'PENDING')) blockingReasons.push({ code: 'REVIEW_PENDING' }); } if (['TESTING', 'LIVE'].includes(toStatus) && !validApproval(merchant)) blockingReasons.push({ code: 'APPROVAL_REQUIRED' }); + if (canReopenKyb(merchant)) blockingReasons.push({ code: 'POLICY_UPGRADE_REQUIRED' }); + if (['TESTING', 'LIVE'].includes(toStatus)) { + const items = incompleteActivation(merchant, toStatus === 'LIVE'); + if (items.length) blockingReasons.push({ code: 'ACTIVATION_CHECKS_REQUIRED', items }); + } const actions: WorkflowAction[] = [ { kind: 'ADVANCE', diff --git a/apps/api/src/workflow.ts b/apps/api/src/workflow.ts index 36b0e77..5494e38 100644 --- a/apps/api/src/workflow.ts +++ b/apps/api/src/workflow.ts @@ -15,7 +15,13 @@ import { taskInputSchema, transitionSchema, merchantCreateSchema, - documentCodes, + requiredDocumentCodes, + isRequiredDocument, + activationCodes, + activationEditSchema, + isIntegrationCheck, + reviewPolicyVersion, + versionSchema, } from '@merchantflow/contracts'; import { SessionGuard } from './auth.js'; import { capabilities, merchantScope, requireSales, taskScope } from './access.js'; @@ -25,6 +31,8 @@ import { evidenceInclude, receivedHistory, workflowActions, + canReopenKyb, + validApproval, type Evidence, } from './workflow-policy.js'; @@ -138,7 +146,7 @@ export class WorkflowController { status: 'NEW_LEAD', createdAt: now, stageEnteredAt: now, - checklist: { create: documentCodes.map((documentCode) => ({ documentCode })) }, + checklist: { create: requiredDocumentCodes.map((documentCode) => ({ documentCode })) }, events: { create: { fromStatus: null, @@ -234,6 +242,7 @@ export class WorkflowController { data: { merchantId: id, cycle: (merchant.reviews[0]?.cycle ?? 0) + 1, + policyVersion: reviewPolicyVersion, submittedById: req.user.id, submittedAt, snapshot: reviewSnapshot(merchant), @@ -256,6 +265,7 @@ export class WorkflowController { requireSales(req.user); if (!capabilities(req.user, merchant).collectChecklist) throw new ApiError('REVIEW_LOCKED', 409); + if (!isRequiredDocument(item.documentCode)) throw new ApiError('REVIEW_LOCKED', 409); await tx.kybChecklistItem.updateMany({ where: { id: itemId, merchantId: id }, data: { state, note }, @@ -276,23 +286,32 @@ export class WorkflowController { @Param('reviewId') reviewId: string, @Body() body: unknown, ) { - const { version, decision, reason, corrections } = reviewDecisionSchema.parse(body); + const { version, decision, reason, corrections, riskLevel } = reviewDecisionSchema.parse(body); return this.mutate(req, id, version, async (tx, merchant) => { const review = merchant.reviews.find((review) => review.id === reviewId); if (!review) throw new ApiError('NOT_FOUND', 404); if (req.user.role !== 'COMPLIANCE_OFFICER') throw new ApiError('FORBIDDEN', 403); - if (merchant.status !== 'COMPLIANCE_REVIEW' || review.decision !== 'PENDING') + if ( + merchant.status !== 'COMPLIANCE_REVIEW' || + review.decision !== 'PENDING' || + merchant.reviews[0]?.id !== reviewId + ) throw new ApiError('WORKFLOW_INVALID', 409); - if (!snapshotsEqual(review.snapshot, reviewSnapshot(merchant))) + if (!snapshotsEqual(review.snapshot, reviewSnapshot(merchant, review.policyVersion))) throw new ApiError('CONFLICT', 409); - if (decision === 'APPROVED' && !receivedHistory(merchant, review.submittedAt)) + if ( + decision === 'APPROVED' && + (review.policyVersion !== reviewPolicyVersion || + !receivedHistory(merchant, review.submittedAt)) + ) throw new ApiError('WORKFLOW_INVALID', 409); for (const correction of corrections) { const item = merchant.checklist.find((item) => item.id === correction.itemId); if (!item) throw new ApiError('NOT_FOUND', 404); + if (!isRequiredDocument(item.documentCode)) throw new ApiError('VALIDATION_ERROR', 400); await tx.kybChecklistItem.updateMany({ where: { id: item.id, merchantId: id }, - data: { state: 'NEEDS_CORRECTION', note: correction.note }, + data: { state: 'NEEDS_CORRECTION' }, }); await tx.checklistChange.create({ data: { @@ -306,8 +325,27 @@ export class WorkflowController { } await tx.complianceReview.updateMany({ where: { id: reviewId, merchantId: id, decision: 'PENDING' }, - data: { decision, reason: reason || null, reviewerId: req.user.id, decidedAt: new Date() }, + data: { + decision, + reason, + riskLevel: riskLevel ?? null, + corrections: corrections.map((correction) => ({ + ...correction, + documentCode: merchant.checklist.find((item) => item.id === correction.itemId)! + .documentCode, + })), + reviewerId: req.user.id, + decidedAt: new Date(), + }, }); + if (decision === 'APPROVED') + await tx.activationCheck.createMany({ + data: activationCodes.map((code) => ({ + reviewId, + code, + state: isIntegrationCheck(code) ? ('INCOMPLETE' as const) : ('NOT_RUN' as const), + })), + }); await this.stage( tx, req, @@ -319,6 +357,73 @@ export class WorkflowController { reviewId, decision, reason, + riskLevel: riskLevel ?? null, + }); + }); + } + @Post(':id/reopen-kyb') reopenKyb( + @Req() req: AuthRequest, + @Param('id') id: string, + @Body() body: unknown, + ) { + const { version } = versionSchema.strict().parse(body); + return this.mutate(req, id, version, async (tx, merchant) => { + requireSales(req.user); + if (!canReopenKyb(merchant)) throw new ApiError('WORKFLOW_INVALID', 409); + await tx.kybChecklistItem.upsert({ + where: { + merchantId_documentCode: { merchantId: id, documentCode: 'AUTHORIZED_REPRESENTATIVE' }, + }, + create: { merchantId: id, documentCode: 'AUTHORIZED_REPRESENTATIVE' }, + update: {}, + }); + await this.stage( + tx, + req, + merchant, + 'KYB', + 'Updated KYB requirements require a new Compliance review.', + ); + }); + } + @Patch(':id/activation-checks/:code') activation( + @Req() req: AuthRequest, + @Param('id') id: string, + @Param('code') code: string, + @Body() body: unknown, + ) { + const { version, reviewId, state, note } = activationEditSchema.parse(body); + return this.mutate(req, id, version, async (tx, merchant) => { + requireSales(req.user); + if (!validApproval(merchant) || merchant.reviews[0]?.id !== reviewId) + throw new ApiError('WORKFLOW_INVALID', 409); + const review = merchant.reviews[0]!; + const check = review.activationChecks.find((item) => item.code === code); + if (!check) throw new ApiError('NOT_FOUND', 404); + if (!capabilities(req.user, merchant).activationCodes.includes(check.code)) + throw new ApiError('REVIEW_LOCKED', 409); + if ( + !( + isIntegrationCheck(code) ? ['INCOMPLETE', 'COMPLETE'] : ['NOT_RUN', 'PASSED', 'FAILED'] + ).includes(state) + ) + throw new ApiError('VALIDATION_ERROR', 400); + await tx.activationCheck.update({ where: { id: check.id }, data: { state, note } }); + await tx.activationCheckChange.create({ + data: { + checkId: check.id, + actorId: req.user.id, + fromState: check.state, + toState: state, + note, + }, + }); + await this.audit(tx, req, id, `Demo check updated: ${code}`, { + reviewId, + checkId: check.id, + fromState: check.state, + toState: state, + note, }); }); } diff --git a/apps/api/test/gated-onboarding.test.mjs b/apps/api/test/gated-onboarding.test.mjs new file mode 100644 index 0000000..ebbb8ff --- /dev/null +++ b/apps/api/test/gated-onboarding.test.mjs @@ -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: 'unique@sales.test', + ...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(); + } +}); diff --git a/apps/api/test/integration.test.mjs b/apps/api/test/integration.test.mjs index fa3b377..b61126b 100644 --- a/apps/api/test/integration.test.mjs +++ b/apps/api/test/integration.test.mjs @@ -3,7 +3,7 @@ import assert from 'node:assert/strict'; import { createHash } from 'node:crypto'; import { spawnSync } from 'node:child_process'; import { createDatabase } from '@merchantflow/database'; -import { roles, statuses, documentCodes } from '@merchantflow/contracts'; +import { roles, statuses, documentCodes, requiredDocumentCodes } from '@merchantflow/contracts'; import { Role, MerchantStatus, @@ -133,7 +133,7 @@ for (const [account, total] of [ for (const m of expected) { const detail = (await request(`/merchants/${m.id}`, cookie)).body; assert.equal(detail.id, m.id); - assert.equal(detail.checklist.length, 4); + assert.equal(detail.checklist.length, 3); assert.ok(detail.events.every((e) => e.merchant.id === m.id)); assert.ok(detail.tasks.every((t) => t.merchant.id === m.id)); assert.ok(!JSON.stringify(detail).includes('passwordHash')); @@ -197,10 +197,10 @@ test('filters are validated and review queue is oldest first', async () => { assert.ok(done.every((t) => t.status === 'DONE')); const overdue = (await request('/tasks?filter=OVERDUE', cookie)).body; assert.ok(overdue.every((t) => t.status === 'OPEN' && new Date(t.dueAt) < new Date())); - const queue = (await request('/review-queue', cookies.compliance)).body; + const queue = (await request('/review-queue', cookies.compliance)).body.items; assert.equal(queue.length, 6); - assert.ok(queue.every((m) => m.status === 'COMPLIANCE_REVIEW')); - assert.ok(new Date(queue[0].stageEnteredAt) <= new Date(queue[1].stageEnteredAt)); + assert.ok(queue.every((m) => m.merchant.status === 'COMPLIANCE_REVIEW')); + assert.ok(new Date(queue[0].submittedAt) <= new Date(queue[1].submittedAt)); }); test('seed is repeatable without modifying records; history includes correction and terminal outcomes', async () => { const snapshot = await db.merchant.findMany({ @@ -271,7 +271,7 @@ async function fixture(id, status = 'NEW_LEAD', ownerId = 'user-manager1') { contactEmail: 'test@workflow.example', ownerId, status, - checklist: { create: documentCodes.map((documentCode) => ({ documentCode })) }, + checklist: { create: requiredDocumentCodes.map((documentCode) => ({ documentCode })) }, }, }); } @@ -313,7 +313,16 @@ test('manager lookup and both directions of direct record/child/mutation attacks { version: hidden.version, state: 'RECEIVED', note: null }, 'PATCH', ], - ['/reviews/unknown/decision', { version: hidden.version, decision: 'APPROVED' }, 'POST'], + [ + '/reviews/unknown/decision', + { + version: hidden.version, + decision: 'APPROVED', + riskLevel: 'LOW', + reason: 'Evidence verified', + }, + 'POST', + ], ['/activities', { version: hidden.version, kind: 'NOTE', text: 'Forbidden' }, 'POST'], [ `/activities/${hidden.activities[0].id}`, @@ -507,7 +516,12 @@ test('corrections, resubmission, approval and activation preserve one merchant a await mutate( `/merchants/${id}/reviews/${first.id}/decision`, cookie, - { version: m.version, decision: 'APPROVED' }, + { + version: m.version, + decision: 'APPROVED', + riskLevel: 'LOW', + reason: 'Evidence verified', + }, 'POST', ) ).status, @@ -562,7 +576,12 @@ test('corrections, resubmission, approval and activation preserve one merchant a await mutate( `/merchants/${id}/reviews/${m.reviews[0].id}/decision`, comp, - { version: m.version, decision: 'APPROVED', reason: 'All checks passed' }, + { + version: m.version, + decision: 'APPROVED', + riskLevel: 'LOW', + reason: 'All checks passed', + }, 'POST', ) ).status, @@ -591,7 +610,37 @@ test('corrections, resubmission, approval and activation preserve one merchant a 200, ); assert.equal((await move('TESTING', comp)).status, 403); + assert.equal((await move('TESTING')).status, 409); + for (const code of ['API_CONNECTION', 'WEBHOOK_SETUP']) { + const current = await detail(); + assert.equal( + ( + await mutate(`/merchants/${id}/activation-checks/${code}`, sales, { + version: current.version, + reviewId: current.reviews[0].id, + state: 'COMPLETE', + note: 'Demo only', + }) + ).status, + 200, + ); + } assert.equal((await move('TESTING')).status, 201); + assert.equal((await move('LIVE', head)).status, 409); + for (const code of ['TEST_PAYMENT', 'RECONCILIATION']) { + const current = await detail(); + assert.equal( + ( + await mutate(`/merchants/${id}/activation-checks/${code}`, sales, { + version: current.version, + reviewId: current.reviews[0].id, + state: 'PASSED', + note: 'Demo only', + }) + ).status, + 200, + ); + } assert.equal((await move('LIVE', head)).status, 201); assert.equal((await move('REJECTED')).status, 409); m = await detail(); @@ -603,7 +652,12 @@ test('corrections, resubmission, approval and activation preserve one merchant a await mutate( `/merchants/${id}/reviews/${first.id}/decision`, comp, - { version: m.version, decision: 'APPROVED' }, + { + version: m.version, + decision: 'APPROVED', + riskLevel: 'LOW', + reason: 'Evidence verified', + }, 'POST', ) ).status, diff --git a/apps/api/test/public-leads.test.mjs b/apps/api/test/public-leads.test.mjs index 4d2fcfb..1999e7b 100644 --- a/apps/api/test/public-leads.test.mjs +++ b/apps/api/test/public-leads.test.mjs @@ -82,7 +82,7 @@ test('public submission persists complete onboarding context and respects CRM pe assert.equal(merchant.industry, 'OTHER'); assert.equal(merchant.website, 'https://example.test/'); assert.equal(merchant.estimatedMonthlyVolumeUsd.toFixed(2), '1234.50'); - assert.equal(merchant.checklist.length, 4); + assert.equal(merchant.checklist.length, 3); assert.ok( merchant.checklist.every((item) => item.state === 'MISSING' && item.changes.length === 0), ); diff --git a/apps/api/test/sales-workspace.test.mjs b/apps/api/test/sales-workspace.test.mjs index 348f5e5..69c7156 100644 --- a/apps/api/test/sales-workspace.test.mjs +++ b/apps/api/test/sales-workspace.test.mjs @@ -96,7 +96,7 @@ test('staff creation is atomic, minimally required, role-bound and strict', asyn assert.equal(m.website, null); assert.equal(m.country, null); assert.equal(m.industry, null); - assert.equal(m.checklist.length, 4); + assert.equal(m.checklist.length, 3); assert.ok(m.checklist.every((item) => item.state === 'MISSING')); assert.equal(m.events.length, 1); assert.equal(m.activities.length, 1); @@ -313,8 +313,11 @@ test('every rejection role and stage rule is enforced, with terminal outcomes an merchantId: clone, cycle: 1, decision: 'APPROVED', + riskLevel: 'LOW', + reason: 'Approval retained during commercial closure', submittedById: 'user-head', reviewerId: 'user-compliance', + submittedAt: new Date(Date.now() - 1000), decidedAt: new Date(), snapshot: approved.reviews[0].snapshot, }, diff --git a/apps/web/src/components/merchant-workflow.tsx b/apps/web/src/components/merchant-workflow.tsx index 35ec5d3..6f4fb2e 100644 --- a/apps/web/src/components/merchant-workflow.tsx +++ b/apps/web/src/components/merchant-workflow.tsx @@ -9,7 +9,7 @@ import { industries, managerListSchema, merchantEditSchema, - reviewDecisionSchema, + isRequiredDocument, sources, statuses, taskInputSchema, @@ -180,7 +180,7 @@ export function ChecklistControl({ const action = useAction(m, () => setOpen(false)); return (
- {m.capabilities.collectChecklist && ( + {m.capabilities.collectChecklist && isRequiredDocument(item.documentCode) && ( )} + {!isRequiredDocument(item.documentCode) && ( +

{t('onboarding.legacyItem')}

+ )} + {m.reviews[0]?.decision === 'CORRECTIONS' && + item.state !== 'RECEIVED' && + m.reviews[0].corrections + .filter((correction) => correction.itemId === item.id) + .map((correction) => ( +

+ {t('onboarding.correctionNote')}: + {correction.note} +

+ ))} {action.feedback}
{t('workflow.checklistHistory')} @@ -235,103 +251,7 @@ export function ChecklistControl({
); } -export function ReviewHistory({ merchant: m }: { merchant: MerchantDetail }) { - const { t } = useTranslation(); - const f = useFormat(); - const [open, setOpen] = useState(false); - const action = useAction(m, () => setOpen(false)); - const pending = m.reviews.find((review) => review.decision === 'PENDING'); - return ( -
- { - action.reset(); - setOpen(true); - }} - > - {t('workflow.decide')} - - ) - } - /> -
- {action.feedback} - {!m.reviews.length && ( -

{t('review.emptyText')}

- )} - {m.reviews.map((review) => ( -
-

- {t('workflow.cycle', { cycle: review.cycle })} · {t(`workflow.${review.decision}`)} -

-

- {t('workflow.submitted', { - name: review.submittedBy.name, - date: f.date(review.submittedAt), - })} -

- {review.reviewer && review.decidedAt && ( -

- {t('workflow.reviewed', { - name: review.reviewer.name, - date: f.date(review.decidedAt), - })} -

- )} - {review.reason && ( -

{review.reason}

- )} -
- ))} -
- {open && pending && ( - ({ - 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} - /> - )} -
- ); -} +export { ReviewHistory } from './onboarding'; export function useActivityText() { const { t } = useTranslation(); return (activity: Pick) => { @@ -349,6 +269,8 @@ export function useActivityText() { const stages = activity.text.split(' → '); if (stages.length === 2 && stages.every((stage) => statuses.some((code) => code === stage))) return stages.map((stage) => t(`statuses.${stage}`)).join(' → '); + if (activity.text.startsWith('Demo check updated: ')) + return t('onboarding.checkUpdated', { check: t(`onboarding.${activity.text.slice(20)}`) }); if (activity.text.startsWith('Checklist updated: ')) return t('workflow.checklistUpdated', { document: t(`documents.${activity.text.slice(19)}`), diff --git a/apps/web/src/components/onboarding.tsx b/apps/web/src/components/onboarding.tsx new file mode 100644 index 0000000..5999d5e --- /dev/null +++ b/apps/web/src/components/onboarding.tsx @@ -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 ( +
+
+
+

{t('onboarding.nextOwner')}

+

{owner}

+
+
+

{t('onboarding.requiredAction')}

+

{t(`onboarding.actions.${handoff.action}`)}

+
+
+ {m.capabilities.reopenKyb && ( + + )} + {action.feedback} +
+ ); +} + +export function ReviewHistory({ merchant: m }: { merchant: MerchantDetail }) { + const { t } = useTranslation(); + const f = useFormat(); + const location = useLocation(); + const [reviewId, setReviewId] = useState(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): 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 ( +
+ { + action.reset(); + setReviewId(pending.id); + }} + > + {t('workflow.decide')} + + ) + } + /> +
+ {action.feedback} + {legacy && ( +

{t('onboarding.legacyReview')}

+ )} + {!m.reviews.length && ( +

{t('onboarding.noReviews')}

+ )} + {m.reviews.map((review) => ( +
+

+ {t('workflow.cycle', { cycle: review.cycle })} · {t(`workflow.${review.decision}`)} +

+ {review.policyVersion < reviewPolicyVersion && ( +

{t('onboarding.legacyCycle')}

+ )} +

+ {t('workflow.submitted', { + name: review.submittedBy.name, + date: f.dateTime(review.submittedAt), + })} +

+ {review.reviewer && review.decidedAt && ( +

+ {t('workflow.reviewed', { + name: review.reviewer.name, + date: f.dateTime(review.decidedAt), + })} +

+ )} + {review.riskLevel && ( +

+ {t('onboarding.riskLevel')}: {t(`onboarding.risk.${review.riskLevel}`)} +

+ )} + {review.reason && ( +

{review.reason}

+ )} + {review.corrections.map((correction) => ( +

+ {t(`documents.${correction.documentCode}`)}: + {correction.note} +

+ ))} +
+ + {t('onboarding.submittedEvidence')} + +
+ {Object.entries(review.snapshot.company).map(([field, value]) => ( +
+
{t(`workflow.${field}`)}
+
{value ?? '—'}
+
+ ))} +
+
    + {review.snapshot.checklist.map((item) => ( +
  • +

    + {t(`documents.${item.documentCode}`)} · {t(`checklist.${item.state}`)} +

    + {item.note && ( +

    + {item.note} +

    + )} +
  • + ))} +
+
+
+ ))} +
+ {selected && ( + ({ + 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}`)} + /> + )} +
+ ); +} + +export function ActivationChecklist({ merchant: m }: { merchant: MerchantDetail }) { + const { t } = useTranslation(); + const f = useFormat(); + const [edit, setEdit] = useState(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 ( +
+ +
+ {action.feedback} + {!checks.length && ( +

{t('onboarding.approvalFirst')}

+ )} + {checks.map((check) => { + const current = check.reviewId === m.reviews[0]?.id; + const cycle = m.reviews.find((review) => review.id === check.reviewId)?.cycle; + return ( +
+
+

{t(`onboarding.${check.code}`)}

+ + {t(`onboarding.${check.state}`)} + +
+

+ {t( + isIntegrationCheck(check.code) ? 'onboarding.integration' : 'onboarding.testing', + )}{' '} + · {t('workflow.cycle', { cycle })} + {!current ? ` · ${t('onboarding.historicalCheck')}` : ''} +

+ {check.note && ( +

{check.note}

+ )} + {current && m.capabilities.activationCodes.includes(check.code) ? ( + + ) : ( +

{t('onboarding.checkLocked')}

+ )} +
+ + {t('onboarding.checkHistory')} + +
    + {check.changes.map((change) => ( +
  1. + {t(`onboarding.${change.toState}`)} · {change.actor.name} ·{' '} + {f.dateTime(change.occurredAt)} + {change.note && ( +

    {change.note}

    + )} +
  2. + ))} +
+
+
+ ); + })} +
+ {item && ( + ({ 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} + /> + )} +
+ ); +} diff --git a/apps/web/src/components/sales-workspace.tsx b/apps/web/src/components/sales-workspace.tsx index 63097df..6571196 100644 --- a/apps/web/src/components/sales-workspace.tsx +++ b/apps/web/src/components/sales-workspace.tsx @@ -20,7 +20,7 @@ import { useFormat } from '../lib/format'; import { Button, LinkButton } from './shared'; import { Editor, useAction, type Field } from './workflow-form'; -export function StageAge({ since }: { since: string }) { +export function StageAge({ since, waiting = false }: { since: string; waiting?: boolean }) { const { t, i18n } = useTranslation(); const [now, setNow] = useState(() => Date.now()); useEffect(() => { @@ -30,7 +30,7 @@ export function StageAge({ since }: { since: string }) { const hours = Math.max(0, Math.floor((now - new Date(since).getTime()) / 3600000)); const duration = hours < 1 - ? t('workspace.lessThanHour') + ? t(waiting ? 'onboarding.lessThanHour' : 'workspace.lessThanHour') : new Intl.NumberFormat(i18n.language, { style: 'unit', unit: hours >= 24 ? 'day' : 'hour', @@ -38,7 +38,7 @@ export function StageAge({ since }: { since: string }) { }).format(hours >= 24 ? Math.floor(hours / 24) : hours); return ( - {t('workspace.timeInStage', { duration })} + {t(waiting ? 'onboarding.waitingFor' : 'workspace.timeInStage', { duration })} ); } @@ -197,7 +197,7 @@ export function StageActions({ }} > {item.kind === 'REJECT' - ? t('workspace.reject') + ? t(business ? 'onboarding.businessClosure' : 'workspace.reject') : item.kind === 'REVIEW' ? t('workflow.decide') : t('workflow.advance', { stage: t(`statuses.${item.toStatus}`) })} @@ -208,6 +208,9 @@ export function StageActions({ {item.blockingReasons.map((reason) => (
  • {t(`workspace.blockers.${reason.code}`)} + {reason.items?.length + ? ` ${reason.items.map((code) => t(reason.code === 'DOCUMENTS_REQUIRED' ? `documents.${code}` : `onboarding.${code}`)).join(', ')}.` + : ''} {reason.fields?.length ? ` ${reason.fields.map((field) => t(`workflow.${field}`)).join(', ')}.` : ''} @@ -221,7 +224,7 @@ export function StageActions({ {!reject && action.feedback} {reject && ( + {children} ); diff --git a/apps/web/src/components/workflow-form.tsx b/apps/web/src/components/workflow-form.tsx index 9463d57..607af98 100644 --- a/apps/web/src/components/workflow-form.tsx +++ b/apps/web/src/components/workflow-form.tsx @@ -26,7 +26,8 @@ export type Field = { type EditorProps = { title: string; description?: string; - fields: Field[]; + fields: Field[] | ((values: Record) => Field[]); + submitLabel?: string | ((values: Record) => string); initial: Record; schema: z.ZodType; build: (values: Record) => unknown; @@ -46,10 +47,13 @@ export function Editor({ close, pending, feedback, + submitLabel, }: EditorProps) { const { t } = useTranslation(); const id = useId(); const form = useForm>({ defaultValues: initial }); + const values = form.watch(); + const visibleFields = typeof fields === 'function' ? fields(values) : fields; const [errors, setErrors] = useState>({}); return ( messages[field.name]); + const first = visibleFields.find((field) => messages[field.name]); if (first) form.setFocus(first.name); return; } @@ -86,7 +90,7 @@ export function Editor({ > {feedback}
    - {fields.map((field) => { + {visibleFields.map((field) => { const fieldId = `${id}-${field.name}`; const props = { id: fieldId, @@ -122,13 +126,21 @@ export function Editor({ ); })} - {Object.keys(errors).some((key) => !fields.some((field) => field.name === key)) && ( + {Object.keys(errors).some( + (key) => !visibleFields.some((field) => field.name === key), + ) && (

    {t('errors.VALIDATION_ERROR')}

    )}
    - + diff --git a/apps/web/src/lib/review-params.test.ts b/apps/web/src/lib/review-params.test.ts new file mode 100644 index 0000000..ec322a6 --- /dev/null +++ b/apps/web/src/lib/review-params.test.ts @@ -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, + ); +}); diff --git a/apps/web/src/lib/review-params.ts b/apps/web/src/lib/review-params.ts new file mode 100644 index 0000000..3db1433 --- /dev/null +++ b/apps/web/src/lib/review-params.ts @@ -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; +} diff --git a/apps/web/src/locales.ts b/apps/web/src/locales.ts index 093af66..5544f70 100644 --- a/apps/web/src/locales.ts +++ b/apps/web/src/locales.ts @@ -1,7 +1,9 @@ +import { onboardingEn, onboardingRu } from './onboarding-locales'; import { salesEn, salesRu } from './sales-locales'; import { workflowEn, workflowRu } from './workflow-locales'; import { landingEn, landingRu } from './landing-locales'; export const en = { + onboarding: onboardingEn, workflow: workflowEn, workspace: salesEn, common: { @@ -169,7 +171,7 @@ export const en = { overview: 'Merchant overview', details: 'The essentials, all together.', checklist: 'KYB checklist', - checklistText: 'Document readiness for the next review.', + checklistText: 'Sales collection records and notes for the next review. No file uploads.', notes: 'Team notes', notesText: 'Context from the people closest to the relationship.', history: 'Journey history', @@ -182,8 +184,9 @@ export const en = { noTasks: 'No related tasks yet', }, documents: { - INCORPORATION: 'Certificate of incorporation', + INCORPORATION: 'Company registration', OWNERSHIP: 'Ownership structure', + AUTHORIZED_REPRESENTATIVE: 'Authorized representative identification', UBO_IDENTIFICATION: 'Beneficial owner identification', BUSINESS_ACTIVITY: 'Business activity description', }, @@ -229,10 +232,11 @@ export const en = { empty: 'The queue is clear', emptyText: 'Merchants appear here when they reach Compliance Review.', entered: 'Entered review', - view: 'View checklist', + view: 'Open review', }, }; export const ru = { + onboarding: onboardingRu, workflow: workflowRu, workspace: salesRu, common: { @@ -401,7 +405,7 @@ export const ru = { overview: 'О мерчанте', details: 'Главное — в одном месте.', checklist: 'Чек-лист KYB', - checklistText: 'Готовность документов к следующей проверке.', + checklistText: 'Статусы и заметки о сборе KYB отделом продаж. Без загрузки файлов.', notes: 'Заметки команды', notesText: 'Контекст от тех, кто работает с мерчантом.', history: 'История этапов', @@ -414,6 +418,7 @@ export const ru = { noTasks: 'Связанных задач пока нет', }, documents: { + AUTHORIZED_REPRESENTATIVE: 'Идентификация уполномоченного представителя', INCORPORATION: 'Свидетельство о регистрации', OWNERSHIP: 'Структура собственности', UBO_IDENTIFICATION: 'Идентификация бенефициаров', @@ -465,6 +470,6 @@ export const ru = { empty: 'Очередь пуста', emptyText: 'Мерчанты появятся здесь на этапе комплаенс-проверки.', entered: 'Начало проверки', - view: 'Открыть чек-лист', + view: 'Открыть проверку', }, }; diff --git a/apps/web/src/onboarding-locales.ts b/apps/web/src/onboarding-locales.ts new file mode 100644 index 0000000..951f373 --- /dev/null +++ b/apps/web/src/onboarding-locales.ts @@ -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; +}; diff --git a/apps/web/src/pages/crm.tsx b/apps/web/src/pages/crm.tsx index 77dba74..3c10ef6 100644 --- a/apps/web/src/pages/crm.tsx +++ b/apps/web/src/pages/crm.tsx @@ -1,3 +1,5 @@ +import { ActivationChecklist, OnboardingHandoff } from '../components/onboarding'; +import { reviewParams } from '../lib/review-params'; import { MerchantControls, ChecklistControl, @@ -32,7 +34,7 @@ import { dashboardSchema, merchantListSchema, merchantDetailSchema, - pipelineSchema, + reviewQueueSchema, pipelineBoardSchema, merchantFiltersSchema, taskListSchema, @@ -599,6 +601,7 @@ export function MerchantDetail() {

    +
    + {!m.capabilities.collectChecklist && ( +

    + {t( + m.status === 'COMPLIANCE_REVIEW' + ? 'onboarding.collectionPending' + : 'onboarding.collectionLocked', + )} +

    + )}
    {m.checklist.map((doc) => (
    @@ -770,6 +782,7 @@ export function MerchantDetail() { ))}
    + )} {tab === 'tasks' && } @@ -919,12 +932,21 @@ export function ReviewQueue() { const user = useOutletContext(); const { t } = useTranslation(); const f = useFormat(); + const [params, setParams] = useSearchParams(); + const filters = reviewParams(params); + const serialized = filters.toString(); const allowed = canSeeReviewQueue(user.role); const query = useQuery({ - queryKey: ['review-queue'], - queryFn: ({ signal }) => api('/review-queue', pipelineSchema, { signal }), + queryKey: ['review-queue', serialized], + queryFn: ({ signal }) => api(`/review-queue?${serialized}`, reviewQueueSchema, { signal }), enabled: allowed, }); + const update = (key: string, value: string) => { + const next = new URLSearchParams(filters); + if (value && value !== 'ALL') next.set(key, value); + else next.delete(key); + setParams(next, { replace: key === 'search' }); + }; if (!allowed) return ; return ( <> @@ -933,59 +955,115 @@ export function ReviewQueue() { description={t('review.description')} eyebrow={t('review.eyebrow')} /> +
    + + + +
    - {(merchants) => ( + {(data) => (
    -
    -

    - {t('review.count', { count: merchants.length })} -

    - - +
    +
    +

    + {t('review.count', { count: data.pendingCount })} +

    +

    + {t('onboarding.filteredCount', { count: data.filteredCount })} +

    +
    + + {t('review.order')} + {serialized && ( + + )}
    - {merchants.length ? ( - merchants.map((m) => ( -
    ( +
    -
    - -
    +
    + +
    - {m.name} + {review.merchant.name}

    - {m.owner?.name ?? t('workflow.unassigned')} ·{' '} - {m.industry ? t(`industry.${m.industry}`) : '—'} + {review.merchant.owner?.name ?? t('workflow.unassigned')} ·{' '} + {t('workflow.cycle', { cycle: review.cycle })}

    -

    - {t('review.entered')} +

    + +

    +

    + {f.dateTime(review.submittedAt)}

    -

    {f.date(m.stageEnteredAt)}

    {t('review.view')} - +
    -
    +
    )) ) : ( - + )}
    )} diff --git a/apps/web/src/sales-locales.ts b/apps/web/src/sales-locales.ts index 71298d0..5b53b24 100644 --- a/apps/web/src/sales-locales.ts +++ b/apps/web/src/sales-locales.ts @@ -34,10 +34,12 @@ export const salesEn = { ASSIGNMENT_REQUIRED: 'Assign a manager before progressing.', CONTACT_REQUIRED: 'Log a call or email before moving to Contacted.', QUALIFICATION_INCOMPLETE: 'Complete the following fields:', - DOCUMENTS_REQUIRED: 'Receive all four KYB documents before submitting for review.', + DOCUMENTS_REQUIRED: 'Receive all three required KYB items before submitting for review.', REVIEW_PENDING: 'A single pending review is required; check the onboarding section.', APPROVAL_REQUIRED: 'Matching compliance approval and document evidence are required.', COMPLIANCE_ONLY: 'Only Compliance can decide the outcome of this review.', + ACTIVATION_CHECKS_REQUIRED: 'Complete the required demo checks:', + POLICY_UPGRADE_REQUIRED: 'Return to KYB for a new review under the current requirements.', SALES_ONLY: 'Only the Head or assigned manager can advance commercial stages.', }, }; @@ -76,10 +78,12 @@ export const salesRu = { ASSIGNMENT_REQUIRED: 'Назначьте менеджера для перехода дальше.', CONTACT_REQUIRED: 'Запишите звонок или письмо перед переходом к контакту.', QUALIFICATION_INCOMPLETE: 'Заполните следующие поля:', - DOCUMENTS_REQUIRED: 'Получите все четыре документа KYB перед отправкой на проверку.', + DOCUMENTS_REQUIRED: 'Получите все три обязательных пункта KYB перед отправкой на проверку.', REVIEW_PENDING: 'Нужна одна активная проверка. Откройте раздел онбординга.', APPROVAL_REQUIRED: 'Нужны актуальное одобрение комплаенса и история документов.', COMPLIANCE_ONLY: 'Только комплаенс может принять решение по проверке.', + ACTIVATION_CHECKS_REQUIRED: 'Выполните обязательные демо-проверки:', + POLICY_UPGRADE_REQUIRED: 'Вернитесь в KYB для новой проверки по текущим требованиям.', SALES_ONLY: 'Коммерческие этапы меняет руководитель или назначенный менеджер.', }, } satisfies { diff --git a/apps/web/src/workflow-locales.ts b/apps/web/src/workflow-locales.ts index 9107c00..e60db34 100644 --- a/apps/web/src/workflow-locales.ts +++ b/apps/web/src/workflow-locales.ts @@ -23,10 +23,10 @@ export const workflowEn = { advance: 'Move to {{stage}}', identityLocked: 'Reviewed company and KYB information is locked. Contact and commercial details can still be updated.', - checklistEdit: 'Update document', - checklistHistory: 'Document history', - state: 'Document status', - note: 'Note', + checklistEdit: 'Update collection', + checklistHistory: 'Collection history', + state: 'Collection status', + note: 'Collection notes', reviews: 'Compliance reviews', decide: 'Record decision', decision: 'Decision', @@ -105,10 +105,10 @@ export const workflowRu: Record = { advance: 'Перевести: {{stage}}', identityLocked: 'Проверенные данные компании и KYB защищены от изменений. Контактные и коммерческие данные можно обновлять.', - checklistEdit: 'Обновить документ', - checklistHistory: 'История документа', - state: 'Статус документа', - note: 'Заметка', + checklistEdit: 'Обновить сбор', + checklistHistory: 'История сбора', + state: 'Статус сбора', + note: 'Заметки о сборе', reviews: 'Комплаенс-проверки', decide: 'Записать решение', decision: 'Решение', diff --git a/docs/implementation-checklist.md b/docs/implementation-checklist.md index 28c598e..4806a7e 100644 --- a/docs/implementation-checklist.md +++ b/docs/implementation-checklist.md @@ -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 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. diff --git a/docs/product-brief.md b/docs/product-brief.md index c05e22d..8a7de10 100644 --- a/docs/product-brief.md +++ b/docs/product-brief.md @@ -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. -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 -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. @@ -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. -`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. @@ -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. 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. diff --git a/packages/contracts/src/index.test.ts b/packages/contracts/src/index.test.ts index d24945f..ebfc922 100644 --- a/packages/contracts/src/index.test.ts +++ b/packages/contracts/src/index.test.ts @@ -139,3 +139,70 @@ describe('daily sales contracts', () => { ).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); + }); +}); diff --git a/packages/contracts/src/index.ts b/packages/contracts/src/index.ts index a59af31..0910908 100644 --- a/packages/contracts/src/index.ts +++ b/packages/contracts/src/index.ts @@ -58,7 +58,13 @@ export const apiErrorSchema = z.object({ code: z.enum(errorCodes), issues: z.array(z.object({ path: z.string(), code: z.string() })).optional(), 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(), }); export const userSchema = z.object({ @@ -130,7 +136,27 @@ export const documentCodes = [ 'OWNERSHIP', 'UBO_IDENTIFICATION', 'BUSINESS_ACTIVITY', + 'AUTHORIZED_REPRESENTATIVE', ] 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 activitySchema = z.object({ id: z.string(), @@ -143,6 +169,22 @@ export const activitySchema = z.object({ }); export const reviewSchema = z.object({ 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(), decision: z.enum(['PENDING', 'APPROVED', 'CORRECTIONS', 'REJECTED']), reason: z.string().nullable(), @@ -161,8 +203,11 @@ export const blockingReasonSchema = z.object({ 'APPROVAL_REQUIRED', 'COMPLIANCE_ONLY', 'SALES_ONLY', + 'ACTIVATION_CHECKS_REQUIRED', + 'POLICY_UPGRADE_REQUIRED', ]), fields: z.array(z.string()).optional(), + items: z.array(z.string()).optional(), }); export const workflowActionSchema = z.object({ kind: z.enum(['ADVANCE', 'REJECT', 'REVIEW']), @@ -179,6 +224,22 @@ export const capabilitiesSchema = z.object({ assign: z.boolean(), collectChecklist: 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)), manageTaskKind: z.enum(['COMMERCIAL', 'COMPLIANCE']), nextStage: statusSchema.nullable(), @@ -219,6 +280,25 @@ export const historyEntrySchema = z.discriminatedUnion('kind', [ ]); export type HistoryEntry = z.infer; 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( z.object({ id: z.string(), @@ -264,6 +344,27 @@ export const dashboardSchema = z.object({ recentActivities: z.array(activitySchema), }); 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( merchantSchema.extend({ capabilities: capabilitiesSchema }), ); @@ -402,6 +503,7 @@ export const checklistEditSchema = versionSchema export const reviewDecisionSchema = versionSchema .extend({ decision: z.enum(['APPROVED', 'REJECTED', 'CORRECTIONS']), + riskLevel: z.enum(riskLevels).optional(), reason: z.string().max(2000).default(''), corrections: z .array( @@ -420,8 +522,12 @@ export const reviewDecisionSchema = versionSchema }) .strict() .superRefine((v, ctx) => { - if (v.decision !== 'APPROVED' && !v.reason.trim()) + if (!v.reason.trim()) 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) ctx.addIssue({ code: 'custom', path: ['corrections'], message: 'validation.required' }); 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) 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 .extend({ kind: z.enum(activityKinds), diff --git a/packages/database/prisma/migrations/202609240005_gated_onboarding/migration.sql b/packages/database/prisma/migrations/202609240005_gated_onboarding/migration.sql new file mode 100644 index 0000000..6376fd8 --- /dev/null +++ b/packages/database/prisma/migrations/202609240005_gated_onboarding/migration.sql @@ -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"); diff --git a/packages/database/prisma/migrations/202609240006_kyb_upgrade/migration.sql b/packages/database/prisma/migrations/202609240006_kyb_upgrade/migration.sql new file mode 100644 index 0000000..00b5316 --- /dev/null +++ b/packages/database/prisma/migrations/202609240006_kyb_upgrade/migration.sql @@ -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'); diff --git a/packages/database/prisma/schema.prisma b/packages/database/prisma/schema.prisma index 32efe19..d9a7648 100644 --- a/packages/database/prisma/schema.prisma +++ b/packages/database/prisma/schema.prisma @@ -32,6 +32,25 @@ enum DocumentCode { OWNERSHIP UBO_IDENTIFICATION 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 { OPEN @@ -70,6 +89,7 @@ model User { completedTasks Task[] @relation("TaskCompleter") activities Activity[] checklistChanges ChecklistChange[] + activationChanges ActivationCheckChange[] submittedReviews ComplianceReview[] @relation("ReviewSubmitter") decidedReviews ComplianceReview[] @relation("ReviewReviewer") createdAt DateTime @default(now()) @@ -202,6 +222,10 @@ model ComplianceReview { id String @id @default(uuid()) merchantId String cycle Int + policyVersion Int @default(2) + riskLevel RiskLevel? + corrections Json @default("[]") + activationChecks ActivationCheck[] submittedById String reviewerId String? decision ReviewDecision @default(PENDING) @@ -215,6 +239,28 @@ model ComplianceReview { @@unique([merchantId, cycle]) @@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 { id String @id anchorAt DateTime @default(now()) diff --git a/packages/database/src/seed.ts b/packages/database/src/seed.ts index 928f0d0..93ce4c4 100644 --- a/packages/database/src/seed.ts +++ b/packages/database/src/seed.ts @@ -1,5 +1,13 @@ 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 { hashPassword } from './password.js'; import { reviewSnapshot } from './workflow.js'; @@ -296,7 +304,7 @@ async function createMerchant(tx: Prisma.TransactionClient, index: number, ancho })), }, checklist: { - create: documentCodes.map((documentCode, j) => ({ + create: requiredDocumentCodes.map((documentCode, j) => ({ id: `${id}-doc-${j}`, documentCode, state: @@ -371,6 +379,11 @@ async function enrich( anchor: number, ) { 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 })); for (const item of m.checklist) await tx.checklistChange.create({ @@ -417,6 +430,18 @@ async function enrich( id: `${m.id}-review-${cycle}`, merchantId: m.id, 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, reviewerId: next ? 'user-compliance' : null, decision, @@ -429,16 +454,54 @@ async function enrich( ? (next?.note ?? 'Unable to verify the beneficial owner; the submitted register conflicts with the ownership declaration.') : 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, - 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') 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({ data: { id: `${item.id}-correction-${cycle}`, diff --git a/packages/database/src/workflow.ts b/packages/database/src/workflow.ts index adcec43..1854699 100644 --- a/packages/database/src/workflow.ts +++ b/packages/database/src/workflow.ts @@ -1,4 +1,4 @@ -import { documentCodes } from '@merchantflow/contracts'; +import { requiredDocumentCodes, isRequiredDocument } from '@merchantflow/contracts'; export const reviewedFields = [ 'name', @@ -13,20 +13,22 @@ type ReviewedMerchant = Record<(typeof reviewedFields)[number], string | null> & checklist: { id: string; documentCode: string; state: string; note: string | null }[]; }; // Stable, minimal evidence: commercial estimates/contact edits do not invalidate approval. -export function reviewSnapshot(merchant: ReviewedMerchant) { +export function reviewSnapshot(merchant: ReviewedMerchant, policyVersion = 2) { return { company: Object.fromEntries(reviewedFields.map((key) => [key, merchant[key]])), checklist: [...merchant.checklist] + .filter((item) => + policyVersion >= 2 + ? isRequiredDocument(item.documentCode) + : item.documentCode !== 'AUTHORIZED_REPRESENTATIVE', + ) .sort((a, b) => a.documentCode.localeCompare(b.documentCode)) .map(({ id, documentCode, state, note }) => ({ id, documentCode, state, note })), }; } export function checklistComplete(items: { documentCode: string; state: string }[]) { - return ( - items.length === documentCodes.length && - documentCodes.every((code) => - items.some((item) => item.documentCode === code && item.state === 'RECEIVED'), - ) + return requiredDocumentCodes.every((code) => + items.some((item) => item.documentCode === code && item.state === 'RECEIVED'), ); } export function snapshotsEqual(a: unknown, b: unknown): boolean { diff --git a/scripts/test-database.mjs b/scripts/test-database.mjs index b7ffda8..4e922fd 100644 --- a/scripts/test-database.mjs +++ b/scripts/test-database.mjs @@ -28,5 +28,6 @@ if (mode === 'integration') 'apps/api/test/integration.test.mjs', 'apps/api/test/public-leads.test.mjs', 'apps/api/test/sales-workspace.test.mjs', + 'apps/api/test/gated-onboarding.test.mjs', ]); else run('pnpm', ['exec', 'playwright', 'test']); diff --git a/tests/fixtures/legacy-demo.mjs b/tests/fixtures/legacy-demo.mjs index 25eba35..5b5e73c 100644 --- a/tests/fixtures/legacy-demo.mjs +++ b/tests/fixtures/legacy-demo.mjs @@ -110,7 +110,7 @@ try { })), }, checklist: { - create: documentCodes.map((documentCode, j) => ({ + create: documentCodes.slice(0, 4).map((documentCode, j) => ({ id: `${id}-doc-${j}`, documentCode, state: diff --git a/tests/landing.spec.ts b/tests/landing.spec.ts index cee1905..dc73f2c 100644 --- a/tests/landing.spec.ts +++ b/tests/landing.spec.ts @@ -169,7 +169,7 @@ for (const language of ['en', 'ru']) expect(merchants[0]?.ownerId).toBeNull(); expect(merchants[0]?.activities).toHaveLength(1); expect(merchants[0]?.events).toHaveLength(1); - expect(merchants[0]?.checklist).toHaveLength(4); + expect(merchants[0]?.checklist).toHaveLength(3); expect(runtimeErrors).toEqual([]); }); }); diff --git a/tests/onboarding.spec.ts b/tests/onboarding.spec.ts new file mode 100644 index 0000000..4774601 --- /dev/null +++ b/tests/onboarding.spec.ts @@ -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: 'queue@company.test', + 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); + } +}); diff --git a/tests/workspace.spec.ts b/tests/workspace.spec.ts index 4d40665..cffe492 100644 --- a/tests/workspace.spec.ts +++ b/tests/workspace.spec.ts @@ -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); await page.getByRole('link', { name: 'Review queue', exact: true }).click(); 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 page.goto('/app/merchants/merchant-15'); 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('KYB'); await page.getByRole('tab', { name: 'Onboarding', exact: true }).click(); - for (let i = 0; i < 4; i++) { - await page.getByRole('button', { name: 'Update document', exact: true }).nth(i).click(); + for (let i = 0; i < 3; i++) { + await page.getByRole('button', { name: 'Update collection', exact: true }).nth(i).click(); await page .getByRole('dialog') - .getByLabel('Document status', { exact: true }) + .getByLabel('Collection status', { exact: true }) .selectOption('RECEIVED'); await save(); } @@ -283,26 +283,30 @@ test('Head assignment, manager editing, Compliance decisions and manager activat .selectOption('CORRECTIONS'); await page .getByRole('dialog') - .getByLabel('Decision reason', { exact: true }) + .getByLabel('Required changes (required)', { exact: true }) .fill('The ownership declaration needs a current signature.'); await page .getByRole('dialog') .getByLabel('Ownership structure', { exact: true }) .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 page.getByRole('tab', { name: 'Onboarding', exact: true }).click(); const ownership = page .locator('#checklist > div > div') .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 .getByRole('dialog') - .getByLabel('Document status', { exact: true }) + .getByLabel('Collection status', { exact: true }) .selectOption('RECEIVED'); await page .getByRole('dialog') - .getByLabel('Note', { exact: true }) + .getByLabel('Collection notes', { exact: true }) .fill('Updated signature received.'); await save(); 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('dialog') - .getByLabel('Decision reason', { exact: true }) + .getByLabel('Approval rationale (required)', { exact: true }) .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 switchAccount('alex'); 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 }), ).toBeDisabled(); 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 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 noOverflow(page); await page.screenshot({ path: info.outputPath('approved-live-merchant.png'), fullPage: true });