Implemented KYB, compliance decisions, integration, and testing
This commit is contained in:
@@ -0,0 +1,28 @@
|
||||
ALTER TYPE "DocumentCode" ADD VALUE 'AUTHORIZED_REPRESENTATIVE';
|
||||
CREATE TYPE "RiskLevel" AS ENUM ('LOW', 'MEDIUM', 'HIGH');
|
||||
CREATE TYPE "ActivationCode" AS ENUM ('API_CONNECTION', 'WEBHOOK_SETUP', 'TEST_PAYMENT', 'RECONCILIATION');
|
||||
CREATE TYPE "ActivationState" AS ENUM ('INCOMPLETE', 'COMPLETE', 'NOT_RUN', 'PASSED', 'FAILED');
|
||||
ALTER TABLE "ComplianceReview" ADD COLUMN "policyVersion" INTEGER NOT NULL DEFAULT 1,
|
||||
ADD COLUMN "riskLevel" "RiskLevel",
|
||||
ADD COLUMN "corrections" JSONB NOT NULL DEFAULT '[]';
|
||||
ALTER TABLE "ComplianceReview" ALTER COLUMN "policyVersion" SET DEFAULT 2;
|
||||
ALTER TABLE "ComplianceReview" ADD CONSTRAINT "ComplianceReview_current_approval" CHECK (
|
||||
"policyVersion" < 2 OR "decision" <> 'APPROVED' OR
|
||||
("riskLevel" IS NOT NULL AND "reason" IS NOT NULL AND length(trim("reason")) > 0)
|
||||
);
|
||||
CREATE TABLE "ActivationCheck" (
|
||||
"id" TEXT PRIMARY KEY, "reviewId" TEXT NOT NULL REFERENCES "ComplianceReview"("id") ON DELETE CASCADE ON UPDATE CASCADE,
|
||||
"code" "ActivationCode" NOT NULL, "state" "ActivationState" NOT NULL, "note" TEXT,
|
||||
CONSTRAINT "ActivationCheck_state_for_code" CHECK (
|
||||
("code" IN ('API_CONNECTION', 'WEBHOOK_SETUP') AND "state" IN ('INCOMPLETE', 'COMPLETE')) OR
|
||||
("code" IN ('TEST_PAYMENT', 'RECONCILIATION') AND "state" IN ('NOT_RUN', 'PASSED', 'FAILED'))
|
||||
)
|
||||
);
|
||||
CREATE UNIQUE INDEX "ActivationCheck_reviewId_code_key" ON "ActivationCheck"("reviewId", "code");
|
||||
CREATE TABLE "ActivationCheckChange" (
|
||||
"id" TEXT PRIMARY KEY, "checkId" TEXT NOT NULL REFERENCES "ActivationCheck"("id") ON DELETE CASCADE ON UPDATE CASCADE,
|
||||
"actorId" TEXT NOT NULL REFERENCES "User"("id") ON DELETE RESTRICT ON UPDATE CASCADE,
|
||||
"fromState" "ActivationState" NOT NULL, "toState" "ActivationState" NOT NULL, "note" TEXT,
|
||||
"occurredAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
CREATE INDEX "ActivationCheckChange_checkId_occurredAt_idx" ON "ActivationCheckChange"("checkId", "occurredAt");
|
||||
@@ -0,0 +1,7 @@
|
||||
-- A new missing record is not evidence of collection. Historical rows/snapshots remain intact.
|
||||
INSERT INTO "KybChecklistItem" ("id", "merchantId", "documentCode", "state", "updatedAt")
|
||||
SELECT gen_random_uuid()::text, "id", 'AUTHORIZED_REPRESENTATIVE', 'MISSING', CURRENT_TIMESTAMP
|
||||
FROM "Merchant" WHERE "status" NOT IN ('LIVE', 'REJECTED')
|
||||
ON CONFLICT ("merchantId", "documentCode") DO NOTHING;
|
||||
-- Invalidate any editor opened against the old policy; preserve company/stage timestamps.
|
||||
UPDATE "Merchant" SET "version" = "version" + 1 WHERE "status" NOT IN ('LIVE', 'REJECTED');
|
||||
@@ -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())
|
||||
|
||||
@@ -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}`,
|
||||
|
||||
@@ -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 {
|
||||
|
||||
Reference in New Issue
Block a user