Implemented KYB, compliance decisions, integration, and testing
This commit is contained in:
@@ -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);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -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<typeof historyEntrySchema>;
|
||||
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),
|
||||
|
||||
@@ -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