Implemented the database, authentication, access rules, and seed data
This commit is contained in:
@@ -41,6 +41,9 @@ export const errorCodes = [
|
||||
'INTERNAL_ERROR',
|
||||
'DATABASE_UNAVAILABLE',
|
||||
'TOO_MANY_REQUESTS',
|
||||
'CONFLICT',
|
||||
'WORKFLOW_INVALID',
|
||||
'REVIEW_LOCKED',
|
||||
] as const;
|
||||
export const apiErrorSchema = z.object({
|
||||
code: z.enum(errorCodes),
|
||||
@@ -62,10 +65,19 @@ export const merchantSchema = z.object({
|
||||
country: z.string(),
|
||||
contactName: z.string(),
|
||||
contactEmail: z.string(),
|
||||
legalName: z.string().nullable(),
|
||||
registrationNumber: z.string().nullable(),
|
||||
address: z.string().nullable(),
|
||||
contactPhone: z.string().nullable(),
|
||||
contactTitle: z.string().nullable(),
|
||||
estimatedMonthlyVolumeUsd: z.string().nullable(),
|
||||
source: z.string().nullable(),
|
||||
version: z.number().int(),
|
||||
updatedAt: date,
|
||||
status: statusSchema,
|
||||
createdAt: date,
|
||||
stageEnteredAt: date,
|
||||
owner: userSchema.pick({ id: true, name: true }),
|
||||
owner: userSchema.pick({ id: true, name: true }).nullable(),
|
||||
});
|
||||
export type Merchant = z.infer<typeof merchantSchema>;
|
||||
export const merchantListSchema = z.object({
|
||||
@@ -88,11 +100,16 @@ export const taskSchema = z.object({
|
||||
id: z.string(),
|
||||
title: z.string(),
|
||||
status: z.enum(['OPEN', 'DONE']),
|
||||
kind: z.enum(['COMMERCIAL', 'COMPLIANCE']),
|
||||
createdAt: date,
|
||||
updatedAt: date,
|
||||
dueAt: date,
|
||||
remindAt: date.nullable(),
|
||||
completedAt: date.nullable(),
|
||||
merchant: z.object({ id: z.string(), name: z.string() }),
|
||||
assignee: z.object({ name: z.string() }),
|
||||
assignee: z.object({ id: z.string(), name: z.string() }),
|
||||
creator: z.object({ name: z.string() }).nullable(),
|
||||
completedBy: z.object({ name: z.string() }).nullable(),
|
||||
});
|
||||
export type Task = z.infer<typeof taskSchema>;
|
||||
export const taskListSchema = z.array(taskSchema);
|
||||
@@ -102,6 +119,36 @@ export const documentCodes = [
|
||||
'UBO_IDENTIFICATION',
|
||||
'BUSINESS_ACTIVITY',
|
||||
] as const;
|
||||
export const activityKinds = ['NOTE', 'CALL', 'EMAIL', 'MEETING', 'KYB_NOTE'] as const;
|
||||
export const activitySchema = z.object({
|
||||
id: z.string(),
|
||||
kind: z.enum([...activityKinds, 'AUDIT']),
|
||||
text: z.string(),
|
||||
occurredAt: date,
|
||||
updatedAt: date,
|
||||
actor: z.object({ id: z.string(), name: z.string() }),
|
||||
merchant: z.object({ id: z.string(), name: z.string() }),
|
||||
});
|
||||
export const reviewSchema = z.object({
|
||||
id: z.string(),
|
||||
cycle: z.number(),
|
||||
decision: z.enum(['PENDING', 'APPROVED', 'CORRECTIONS', 'REJECTED']),
|
||||
reason: z.string().nullable(),
|
||||
submittedAt: date,
|
||||
decidedAt: date.nullable(),
|
||||
submittedBy: z.object({ name: z.string() }),
|
||||
reviewer: z.object({ name: z.string() }).nullable(),
|
||||
});
|
||||
export const capabilitiesSchema = z.object({
|
||||
editCommercial: z.boolean(),
|
||||
editIdentity: z.boolean(),
|
||||
assign: z.boolean(),
|
||||
collectChecklist: z.boolean(),
|
||||
review: z.boolean(),
|
||||
activityKinds: z.array(z.enum(activityKinds)),
|
||||
manageTaskKind: z.enum(['COMMERCIAL', 'COMPLIANCE']),
|
||||
nextStage: statusSchema.nullable(),
|
||||
});
|
||||
export const merchantDetailSchema = merchantSchema.extend({
|
||||
checklist: z.array(
|
||||
z.object({
|
||||
@@ -109,6 +156,16 @@ export const merchantDetailSchema = merchantSchema.extend({
|
||||
documentCode: z.enum(documentCodes),
|
||||
state: z.enum(['MISSING', 'RECEIVED', 'NEEDS_CORRECTION']),
|
||||
note: z.string().nullable(),
|
||||
changes: z.array(
|
||||
z.object({
|
||||
id: z.string(),
|
||||
fromState: z.enum(['MISSING', 'RECEIVED', 'NEEDS_CORRECTION']).nullable(),
|
||||
toState: z.enum(['MISSING', 'RECEIVED', 'NEEDS_CORRECTION']),
|
||||
note: z.string().nullable(),
|
||||
occurredAt: date,
|
||||
actor: z.object({ name: z.string() }),
|
||||
}),
|
||||
),
|
||||
}),
|
||||
),
|
||||
notes: z.array(
|
||||
@@ -121,7 +178,11 @@ export const merchantDetailSchema = merchantSchema.extend({
|
||||
),
|
||||
events: z.array(eventSchema),
|
||||
tasks: taskListSchema,
|
||||
activities: z.array(activitySchema),
|
||||
reviews: z.array(reviewSchema),
|
||||
capabilities: capabilitiesSchema,
|
||||
});
|
||||
export type MerchantDetail = z.infer<typeof merchantDetailSchema>;
|
||||
export const dashboardSchema = z.object({
|
||||
merchantCount: z.number(),
|
||||
reviewCount: z.number(),
|
||||
@@ -130,11 +191,113 @@ export const dashboardSchema = z.object({
|
||||
distribution: z.array(z.object({ status: statusSchema, count: z.number() })),
|
||||
recentEvents: z.array(eventSchema),
|
||||
upcomingTasks: taskListSchema,
|
||||
recentActivities: z.array(activitySchema),
|
||||
});
|
||||
export const pipelineSchema = z.array(merchantSchema);
|
||||
export const healthSchema = z.object({ status: z.literal('ok'), database: z.literal('connected') });
|
||||
|
||||
// Navigation metadata only; write permissions are intentionally deferred.
|
||||
export const sources = ['INBOUND', 'OUTBOUND', 'REFERRAL', 'PARTNER', 'EVENT'] as const;
|
||||
export const industries = ['ECOMMERCE', 'SOFTWARE', 'TRAVEL', 'SERVICES'] as const;
|
||||
const text = z
|
||||
.string()
|
||||
.min(1)
|
||||
.max(200)
|
||||
.refine((value) => !!value.trim());
|
||||
const optionalText = z.string().max(500).nullable();
|
||||
export const versionSchema = z.object({ version: z.number().int().nonnegative() });
|
||||
export const merchantEditSchema = versionSchema
|
||||
.extend({
|
||||
name: text.optional(),
|
||||
legalName: text.optional(),
|
||||
registrationNumber: optionalText.optional(),
|
||||
address: optionalText.optional(),
|
||||
website: z
|
||||
.url()
|
||||
.refine((v) => /^https?:\/\//.test(v))
|
||||
.optional(),
|
||||
country: z
|
||||
.string()
|
||||
.regex(/^[A-Z]{2}$/)
|
||||
.optional(),
|
||||
industry: z.enum(industries).optional(),
|
||||
contactName: text.optional(),
|
||||
contactEmail: z.email().max(254).optional(),
|
||||
contactPhone: optionalText.optional(),
|
||||
contactTitle: optionalText.optional(),
|
||||
estimatedMonthlyVolumeUsd: z
|
||||
.string()
|
||||
.regex(/^(?:0|[1-9]\d{0,11})(?:\.\d{1,2})?$/)
|
||||
.optional(),
|
||||
source: z.enum(sources).optional(),
|
||||
})
|
||||
.strict();
|
||||
export const assignmentSchema = versionSchema.extend({ ownerId: text }).strict();
|
||||
export const transitionSchema = versionSchema.extend({ toStatus: statusSchema }).strict();
|
||||
export const checklistEditSchema = versionSchema
|
||||
.extend({
|
||||
state: z.enum(['MISSING', 'RECEIVED']),
|
||||
note: z.string().max(2000).nullable(),
|
||||
})
|
||||
.strict();
|
||||
export const reviewDecisionSchema = versionSchema
|
||||
.extend({
|
||||
decision: z.enum(['APPROVED', 'REJECTED', 'CORRECTIONS']),
|
||||
reason: z.string().max(2000).default(''),
|
||||
corrections: z
|
||||
.array(
|
||||
z
|
||||
.object({
|
||||
itemId: text,
|
||||
note: z
|
||||
.string()
|
||||
.min(1)
|
||||
.max(2000)
|
||||
.refine((value) => !!value.trim()),
|
||||
})
|
||||
.strict(),
|
||||
)
|
||||
.default([]),
|
||||
})
|
||||
.strict()
|
||||
.superRefine((v, ctx) => {
|
||||
if (v.decision !== 'APPROVED' && !v.reason.trim())
|
||||
ctx.addIssue({ code: 'custom', path: ['reason'], message: 'validation.required' });
|
||||
if (v.decision === 'CORRECTIONS' && !v.corrections.length)
|
||||
ctx.addIssue({ code: 'custom', path: ['corrections'], message: 'validation.required' });
|
||||
if (v.decision !== 'CORRECTIONS' && v.corrections.length)
|
||||
ctx.addIssue({ code: 'custom', path: ['corrections'], message: 'validation.invalid' });
|
||||
if (new Set(v.corrections.map((c) => c.itemId)).size !== v.corrections.length)
|
||||
ctx.addIssue({ code: 'custom', path: ['corrections'], message: 'validation.invalid' });
|
||||
});
|
||||
export const activityInputSchema = versionSchema
|
||||
.extend({
|
||||
kind: z.enum(activityKinds),
|
||||
text: z
|
||||
.string()
|
||||
.min(1)
|
||||
.max(5000)
|
||||
.refine((v) => !!v.trim()),
|
||||
})
|
||||
.strict();
|
||||
export const taskInputSchema = versionSchema
|
||||
.extend({
|
||||
title: z
|
||||
.string()
|
||||
.min(1)
|
||||
.max(200)
|
||||
.refine((v) => !!v.trim()),
|
||||
dueAt: date,
|
||||
remindAt: date.nullable(),
|
||||
status: z.enum(['OPEN', 'DONE']),
|
||||
})
|
||||
.strict()
|
||||
.refine((v) => !v.remindAt || v.remindAt <= v.dueAt, {
|
||||
message: 'validation.invalid',
|
||||
path: ['remindAt'],
|
||||
});
|
||||
export const managerListSchema = z.array(userSchema.pick({ id: true, name: true, email: true }));
|
||||
export const mutationResultSchema = z.object({ ok: z.literal(true) });
|
||||
|
||||
export function canSeeReviewQueue(role: Role) {
|
||||
return role === 'COMPLIANCE_OFFICER';
|
||||
}
|
||||
|
||||
@@ -0,0 +1,159 @@
|
||||
-- CreateEnum
|
||||
CREATE TYPE "TaskKind" AS ENUM ('COMMERCIAL', 'COMPLIANCE');
|
||||
|
||||
-- CreateEnum
|
||||
CREATE TYPE "ActivityKind" AS ENUM ('NOTE', 'CALL', 'EMAIL', 'MEETING', 'KYB_NOTE', 'AUDIT');
|
||||
|
||||
-- CreateEnum
|
||||
CREATE TYPE "ReviewDecision" AS ENUM ('PENDING', 'APPROVED', 'CORRECTIONS', 'REJECTED');
|
||||
|
||||
-- DropForeignKey
|
||||
ALTER TABLE "Merchant" DROP CONSTRAINT "Merchant_ownerId_fkey";
|
||||
|
||||
-- AlterTable
|
||||
ALTER TABLE "User" ADD COLUMN "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
ADD COLUMN "updatedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP;
|
||||
|
||||
-- AlterTable
|
||||
ALTER TABLE "Session" ADD COLUMN "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP;
|
||||
|
||||
-- AlterTable
|
||||
ALTER TABLE "Merchant" ADD COLUMN "address" TEXT,
|
||||
ADD COLUMN "contactPhone" TEXT,
|
||||
ADD COLUMN "contactTitle" TEXT,
|
||||
ADD COLUMN "estimatedMonthlyVolumeUsd" DECIMAL(18,2),
|
||||
ADD COLUMN "legalName" TEXT,
|
||||
ADD COLUMN "registrationNumber" TEXT,
|
||||
ADD COLUMN "source" TEXT,
|
||||
ADD COLUMN "updatedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
ADD COLUMN "version" INTEGER NOT NULL DEFAULT 0,
|
||||
ALTER COLUMN "ownerId" DROP NOT NULL;
|
||||
|
||||
-- AlterTable
|
||||
ALTER TABLE "KybChecklistItem" ADD COLUMN "updatedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP;
|
||||
|
||||
-- AlterTable
|
||||
ALTER TABLE "Task" ADD COLUMN "completedById" TEXT,
|
||||
ADD COLUMN "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
ADD COLUMN "creatorId" TEXT,
|
||||
ADD COLUMN "kind" "TaskKind" NOT NULL DEFAULT 'COMMERCIAL',
|
||||
ADD COLUMN "updatedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP;
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "Activity" (
|
||||
"id" TEXT NOT NULL,
|
||||
"merchantId" TEXT NOT NULL,
|
||||
"actorId" TEXT NOT NULL,
|
||||
"kind" "ActivityKind" NOT NULL,
|
||||
"text" TEXT NOT NULL,
|
||||
"occurredAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"metadata" JSONB,
|
||||
|
||||
CONSTRAINT "Activity_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "ChecklistChange" (
|
||||
"id" TEXT NOT NULL,
|
||||
"itemId" TEXT NOT NULL,
|
||||
"actorId" TEXT NOT NULL,
|
||||
"fromState" "ChecklistState",
|
||||
"toState" "ChecklistState" NOT NULL,
|
||||
"note" TEXT,
|
||||
"occurredAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "ChecklistChange_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "ComplianceReview" (
|
||||
"id" TEXT NOT NULL,
|
||||
"merchantId" TEXT NOT NULL,
|
||||
"cycle" INTEGER NOT NULL,
|
||||
"submittedById" TEXT NOT NULL,
|
||||
"reviewerId" TEXT,
|
||||
"decision" "ReviewDecision" NOT NULL DEFAULT 'PENDING',
|
||||
"reason" TEXT,
|
||||
"submittedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"decidedAt" TIMESTAMP(3),
|
||||
"snapshot" JSONB NOT NULL,
|
||||
|
||||
CONSTRAINT "ComplianceReview_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "DemoSeedState" (
|
||||
"id" TEXT NOT NULL,
|
||||
"anchorAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "DemoSeedState_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "DemoSeedRecord" (
|
||||
"merchantId" TEXT NOT NULL,
|
||||
"version" INTEGER NOT NULL,
|
||||
"appliedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "DemoSeedRecord_pkey" PRIMARY KEY ("merchantId")
|
||||
);
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "Activity_merchantId_occurredAt_idx" ON "Activity"("merchantId", "occurredAt");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "Activity_occurredAt_idx" ON "Activity"("occurredAt");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "ChecklistChange_itemId_occurredAt_idx" ON "ChecklistChange"("itemId", "occurredAt");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "ComplianceReview_decision_submittedAt_idx" ON "ComplianceReview"("decision", "submittedAt");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "ComplianceReview_merchantId_cycle_key" ON "ComplianceReview"("merchantId", "cycle");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "Task_assigneeId_kind_status_dueAt_idx" ON "Task"("assigneeId", "kind", "status", "dueAt");
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "Merchant" ADD CONSTRAINT "Merchant_ownerId_fkey" FOREIGN KEY ("ownerId") REFERENCES "User"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "Task" ADD CONSTRAINT "Task_creatorId_fkey" FOREIGN KEY ("creatorId") REFERENCES "User"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "Task" ADD CONSTRAINT "Task_completedById_fkey" FOREIGN KEY ("completedById") REFERENCES "User"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "Activity" ADD CONSTRAINT "Activity_merchantId_fkey" FOREIGN KEY ("merchantId") REFERENCES "Merchant"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "Activity" ADD CONSTRAINT "Activity_actorId_fkey" FOREIGN KEY ("actorId") REFERENCES "User"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "ChecklistChange" ADD CONSTRAINT "ChecklistChange_itemId_fkey" FOREIGN KEY ("itemId") REFERENCES "KybChecklistItem"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "ChecklistChange" ADD CONSTRAINT "ChecklistChange_actorId_fkey" FOREIGN KEY ("actorId") REFERENCES "User"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "ComplianceReview" ADD CONSTRAINT "ComplianceReview_merchantId_fkey" FOREIGN KEY ("merchantId") REFERENCES "Merchant"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "ComplianceReview" ADD CONSTRAINT "ComplianceReview_submittedById_fkey" FOREIGN KEY ("submittedById") REFERENCES "User"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "ComplianceReview" ADD CONSTRAINT "ComplianceReview_reviewerId_fkey" FOREIGN KEY ("reviewerId") REFERENCES "User"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "DemoSeedRecord" ADD CONSTRAINT "DemoSeedRecord_merchantId_fkey" FOREIGN KEY ("merchantId") REFERENCES "Merchant"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
-- Only one open review may exist for a merchant, including concurrent submissions.
|
||||
CREATE UNIQUE INDEX "ComplianceReview_one_pending" ON "ComplianceReview" ("merchantId") WHERE "decision" = 'PENDING';
|
||||
ALTER TABLE "Merchant" ADD CONSTRAINT "Merchant_volume_nonnegative" CHECK ("estimatedMonthlyVolumeUsd" >= 0);
|
||||
ALTER TABLE "ComplianceReview" ADD CONSTRAINT "ComplianceReview_decision_evidence" CHECK (
|
||||
("decision" = 'PENDING' AND "reviewerId" IS NULL AND "decidedAt" IS NULL) OR
|
||||
("decision" <> 'PENDING' AND "reviewerId" IS NOT NULL AND "decidedAt" IS NOT NULL AND "decidedAt" >= "submittedAt"
|
||||
AND ("decision" = 'APPROVED' OR ("reason" IS NOT NULL AND length(trim("reason")) > 0)))
|
||||
);
|
||||
@@ -37,6 +37,24 @@ enum TaskStatus {
|
||||
OPEN
|
||||
DONE
|
||||
}
|
||||
enum TaskKind {
|
||||
COMMERCIAL
|
||||
COMPLIANCE
|
||||
}
|
||||
enum ActivityKind {
|
||||
NOTE
|
||||
CALL
|
||||
EMAIL
|
||||
MEETING
|
||||
KYB_NOTE
|
||||
AUDIT
|
||||
}
|
||||
enum ReviewDecision {
|
||||
PENDING
|
||||
APPROVED
|
||||
CORRECTIONS
|
||||
REJECTED
|
||||
}
|
||||
model User {
|
||||
id String @id @default(uuid())
|
||||
email String @unique
|
||||
@@ -47,12 +65,21 @@ model User {
|
||||
merchants Merchant[]
|
||||
events StatusEvent[]
|
||||
notes MerchantNote[]
|
||||
tasks Task[]
|
||||
tasks Task[] @relation("TaskAssignee")
|
||||
createdTasks Task[] @relation("TaskCreator")
|
||||
completedTasks Task[] @relation("TaskCompleter")
|
||||
activities Activity[]
|
||||
checklistChanges ChecklistChange[]
|
||||
submittedReviews ComplianceReview[] @relation("ReviewSubmitter")
|
||||
decidedReviews ComplianceReview[] @relation("ReviewReviewer")
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @default(now()) @updatedAt
|
||||
}
|
||||
model Session {
|
||||
id String @id
|
||||
userId String
|
||||
expiresAt DateTime
|
||||
createdAt DateTime @default(now())
|
||||
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
|
||||
@@index([expiresAt])
|
||||
}
|
||||
@@ -64,15 +91,27 @@ model Merchant {
|
||||
country String
|
||||
contactName String
|
||||
contactEmail String
|
||||
legalName String?
|
||||
registrationNumber String?
|
||||
address String?
|
||||
contactPhone String?
|
||||
contactTitle String?
|
||||
estimatedMonthlyVolumeUsd Decimal? @db.Decimal(18, 2)
|
||||
source String?
|
||||
status MerchantStatus @default(NEW_LEAD)
|
||||
ownerId String
|
||||
ownerId String?
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @default(now()) @updatedAt
|
||||
version Int @default(0)
|
||||
stageEnteredAt DateTime @default(now())
|
||||
owner User @relation(fields: [ownerId], references: [id])
|
||||
owner User? @relation(fields: [ownerId], references: [id])
|
||||
events StatusEvent[]
|
||||
checklist KybChecklistItem[]
|
||||
notes MerchantNote[]
|
||||
tasks Task[]
|
||||
activities Activity[]
|
||||
reviews ComplianceReview[]
|
||||
seedRecord DemoSeedRecord?
|
||||
@@index([ownerId, status])
|
||||
@@index([status, stageEnteredAt])
|
||||
}
|
||||
@@ -95,6 +134,8 @@ model KybChecklistItem {
|
||||
documentCode DocumentCode
|
||||
state ChecklistState @default(MISSING)
|
||||
note String?
|
||||
updatedAt DateTime @default(now()) @updatedAt
|
||||
changes ChecklistChange[]
|
||||
merchant Merchant @relation(fields: [merchantId], references: [id], onDelete: Cascade)
|
||||
@@unique([merchantId, documentCode])
|
||||
}
|
||||
@@ -114,10 +155,71 @@ model Task {
|
||||
assigneeId String
|
||||
title String
|
||||
status TaskStatus @default(OPEN)
|
||||
kind TaskKind @default(COMMERCIAL)
|
||||
creatorId String?
|
||||
completedById String?
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @default(now()) @updatedAt
|
||||
dueAt DateTime
|
||||
remindAt DateTime?
|
||||
completedAt DateTime?
|
||||
merchant Merchant @relation(fields: [merchantId], references: [id], onDelete: Cascade)
|
||||
assignee User @relation(fields: [assigneeId], references: [id])
|
||||
assignee User @relation("TaskAssignee", fields: [assigneeId], references: [id])
|
||||
creator User? @relation("TaskCreator", fields: [creatorId], references: [id])
|
||||
completedBy User? @relation("TaskCompleter", fields: [completedById], references: [id])
|
||||
@@index([merchantId, status, dueAt])
|
||||
@@index([assigneeId, kind, status, dueAt])
|
||||
}
|
||||
model Activity {
|
||||
id String @id @default(uuid())
|
||||
merchantId String
|
||||
actorId String
|
||||
kind ActivityKind
|
||||
text String
|
||||
occurredAt DateTime @default(now())
|
||||
updatedAt DateTime @default(now()) @updatedAt
|
||||
metadata Json?
|
||||
merchant Merchant @relation(fields: [merchantId], references: [id], onDelete: Cascade)
|
||||
actor User @relation(fields: [actorId], references: [id])
|
||||
@@index([merchantId, occurredAt])
|
||||
@@index([occurredAt])
|
||||
}
|
||||
model ChecklistChange {
|
||||
id String @id @default(uuid())
|
||||
itemId String
|
||||
actorId String
|
||||
fromState ChecklistState?
|
||||
toState ChecklistState
|
||||
note String?
|
||||
occurredAt DateTime @default(now())
|
||||
item KybChecklistItem @relation(fields: [itemId], references: [id], onDelete: Cascade)
|
||||
actor User @relation(fields: [actorId], references: [id])
|
||||
@@index([itemId, occurredAt])
|
||||
}
|
||||
model ComplianceReview {
|
||||
id String @id @default(uuid())
|
||||
merchantId String
|
||||
cycle Int
|
||||
submittedById String
|
||||
reviewerId String?
|
||||
decision ReviewDecision @default(PENDING)
|
||||
reason String?
|
||||
submittedAt DateTime @default(now())
|
||||
decidedAt DateTime?
|
||||
snapshot Json
|
||||
merchant Merchant @relation(fields: [merchantId], references: [id], onDelete: Cascade)
|
||||
submittedBy User @relation("ReviewSubmitter", fields: [submittedById], references: [id])
|
||||
reviewer User? @relation("ReviewReviewer", fields: [reviewerId], references: [id])
|
||||
@@unique([merchantId, cycle])
|
||||
@@index([decision, submittedAt])
|
||||
}
|
||||
model DemoSeedState {
|
||||
id String @id
|
||||
anchorAt DateTime @default(now())
|
||||
}
|
||||
model DemoSeedRecord {
|
||||
merchantId String @id
|
||||
version Int
|
||||
appliedAt DateTime @default(now())
|
||||
merchant Merchant @relation(fields: [merchantId], references: [id], onDelete: Cascade)
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ import { PrismaClient } from './generated/prisma/client.js';
|
||||
import { PrismaPg } from '@prisma/adapter-pg';
|
||||
export { PrismaClient };
|
||||
export { hashPassword, verifyPassword } from './password.js';
|
||||
export { reviewSnapshot, checklistComplete, snapshotsEqual, reviewedFields } from './workflow.js';
|
||||
export type { Prisma } from './generated/prisma/client.js';
|
||||
export function createDatabase(url: string) {
|
||||
return new PrismaClient({
|
||||
|
||||
+575
-135
@@ -1,38 +1,14 @@
|
||||
import { config } from 'dotenv';
|
||||
import { statuses, successfulStages, documentCodes, type Status } from '@merchantflow/contracts';
|
||||
import { createDatabase } from './index.js';
|
||||
import { documentCodes, sources, successfulStages, type Status } from '@merchantflow/contracts';
|
||||
import { createDatabase, type Prisma } from './index.js';
|
||||
import { hashPassword } from './password.js';
|
||||
import { reviewSnapshot } from './workflow.js';
|
||||
config({ path: new URL('../../../.env', import.meta.url).pathname, quiet: true });
|
||||
const db = createDatabase(
|
||||
process.env.DATABASE_URL ??
|
||||
'postgresql://merchantflow:merchantflow_local@localhost:55440/merchantflow',
|
||||
);
|
||||
const users = [
|
||||
{
|
||||
id: 'user-head',
|
||||
email: '[email protected]',
|
||||
name: 'Elena Carter',
|
||||
role: 'HEAD_OF_SALES' as const,
|
||||
},
|
||||
{
|
||||
id: 'user-compliance',
|
||||
email: '[email protected]',
|
||||
name: 'Pavel Sokolov',
|
||||
role: 'COMPLIANCE_OFFICER' as const,
|
||||
},
|
||||
{
|
||||
id: 'user-manager1',
|
||||
email: '[email protected]',
|
||||
name: 'Alex Morgan',
|
||||
role: 'ACCOUNT_MANAGER' as const,
|
||||
},
|
||||
{
|
||||
id: 'user-manager2',
|
||||
email: '[email protected]',
|
||||
name: 'Maria Chen',
|
||||
role: 'ACCOUNT_MANAGER' as const,
|
||||
},
|
||||
];
|
||||
const day = 86400000;
|
||||
const names = [
|
||||
'Orbit Goods',
|
||||
'Northstar Studio',
|
||||
@@ -52,122 +28,586 @@ const names = [
|
||||
'Kinfolk Supply',
|
||||
'Peak Ventures',
|
||||
'Amber Exchange',
|
||||
'Willow Ceramics',
|
||||
'Cobalt Software',
|
||||
'Meadow Retreats',
|
||||
'Cedar Workshop',
|
||||
'Tide Cart',
|
||||
'Juniper Tools',
|
||||
'Alpine Desk',
|
||||
'Maple Routes',
|
||||
'Vela Systems',
|
||||
'Pebble Goods',
|
||||
'Clover Services',
|
||||
'Finch Travel',
|
||||
'Birch Trading',
|
||||
'Harbor Learning',
|
||||
'Coral Works',
|
||||
'Spruce Studio',
|
||||
'Mosaic Rentals',
|
||||
'Copper Cloud',
|
||||
'Elm Outfitters',
|
||||
'Hearth Home',
|
||||
'Quartz Analytics',
|
||||
'Dune Apparel',
|
||||
'Marble Market',
|
||||
'Saffron Supply',
|
||||
'Fern Booking',
|
||||
'Canvas Metrics',
|
||||
'Drift Ventures',
|
||||
];
|
||||
const extraStages: Status[] = [
|
||||
...Array<Status>(5).fill('NEW_LEAD'),
|
||||
...Array<Status>(3).fill('CONTACTED'),
|
||||
...Array<Status>(3).fill('QUALIFIED'),
|
||||
...Array<Status>(4).fill('KYB'),
|
||||
...Array<Status>(4).fill('COMPLIANCE_REVIEW'),
|
||||
...Array<Status>(2).fill('INTEGRATION'),
|
||||
...Array<Status>(2).fill('TESTING'),
|
||||
...Array<Status>(3).fill('LIVE'),
|
||||
'REJECTED',
|
||||
];
|
||||
const allStages: Status[] = [...successfulStages, 'REJECTED'];
|
||||
const industries = ['ECOMMERCE', 'SOFTWARE', 'TRAVEL', 'SERVICES'];
|
||||
const countries = ['GB', 'DE', 'NL', 'EE', 'FR', 'CA'];
|
||||
const now = Date.now();
|
||||
const day = 86400000;
|
||||
try {
|
||||
for (const u of users)
|
||||
await db.user.upsert({
|
||||
where: { id: u.id },
|
||||
create: { ...u, passwordHash: hashPassword('MerchantFlow123!') },
|
||||
update: {},
|
||||
});
|
||||
for (let index = 0; index < names.length; index++) {
|
||||
const id = `merchant-${String(index + 1).padStart(2, '0')}`;
|
||||
// A second seed never rewrites the user's existing records, dates or history.
|
||||
if (await db.merchant.findUnique({ where: { id } })) continue;
|
||||
const status = statuses[Math.floor(index / 2)]!;
|
||||
const ownerId = index % 2 === 0 ? 'user-manager1' : 'user-manager2';
|
||||
const name = names[index]!;
|
||||
let journey: Status[] =
|
||||
status === 'REJECTED'
|
||||
? [...successfulStages.slice(0, 5), 'REJECTED']
|
||||
: successfulStages.slice(0, successfulStages.indexOf(status) + 1);
|
||||
if (status === 'KYB' && index % 2 === 0) journey = [...successfulStages.slice(0, 5), 'KYB'];
|
||||
const stageEnteredAt = new Date(now - ((index % 4) + 1) * day);
|
||||
const createdAt = new Date(stageEnteredAt.getTime() - (journey.length - 1) * 3 * day);
|
||||
const domain = name.toLowerCase().replaceAll(' ', '') + '.example';
|
||||
await db.merchant.create({
|
||||
data: {
|
||||
id,
|
||||
name,
|
||||
website: `https://${domain}`,
|
||||
industry: industries[index % 4]!,
|
||||
country: countries[index % 6]!,
|
||||
contactName: index % 2 ? 'Jamie Wilson' : 'Sam Taylor',
|
||||
contactEmail: `hello@${domain}`,
|
||||
status,
|
||||
ownerId,
|
||||
createdAt,
|
||||
stageEnteredAt,
|
||||
events: {
|
||||
create: journey.map((toStatus, i) => ({
|
||||
id: `${id}-event-${i}`,
|
||||
fromStatus: journey[i - 1] ?? null,
|
||||
toStatus,
|
||||
actorId:
|
||||
toStatus === 'COMPLIANCE_REVIEW' || (i > 0 && toStatus === 'KYB')
|
||||
? 'user-compliance'
|
||||
: ownerId,
|
||||
occurredAt: new Date(createdAt.getTime() + i * 3 * day),
|
||||
note:
|
||||
journey[i - 1] === 'COMPLIANCE_REVIEW' && toStatus === 'KYB'
|
||||
? 'Please clarify the beneficial ownership structure before resubmitting.'
|
||||
const contacts = [
|
||||
'Riley Bennett',
|
||||
'Jordan Ellis',
|
||||
'Casey Laurent',
|
||||
'Morgan Reed',
|
||||
'Taylor Brooks',
|
||||
'Avery Santos',
|
||||
'Robin Bell',
|
||||
'Drew Collins',
|
||||
];
|
||||
const users = [
|
||||
{
|
||||
id: 'user-head',
|
||||
email: '[email protected]',
|
||||
name: 'Elena Carter',
|
||||
role: 'HEAD_OF_SALES' as const,
|
||||
},
|
||||
{
|
||||
id: 'user-compliance',
|
||||
email: '[email protected]',
|
||||
name: 'Pavel Sokolov',
|
||||
role: 'COMPLIANCE_OFFICER' as const,
|
||||
},
|
||||
{
|
||||
id: 'user-manager1',
|
||||
email: '[email protected]',
|
||||
name: 'Alex Morgan',
|
||||
role: 'ACCOUNT_MANAGER' as const,
|
||||
},
|
||||
{
|
||||
id: 'user-manager2',
|
||||
email: 'sam@merchantflow.test',
|
||||
name: 'Sam Taylor',
|
||||
role: 'ACCOUNT_MANAGER' as const,
|
||||
},
|
||||
];
|
||||
function journeyFor(status: Status, corrections: boolean): Status[] {
|
||||
const journey: Status[] =
|
||||
status === 'REJECTED'
|
||||
? [...successfulStages.slice(0, 5), 'REJECTED']
|
||||
: successfulStages.slice(0, successfulStages.indexOf(status) + 1);
|
||||
if (corrections) journey.splice(4, 0, 'COMPLIANCE_REVIEW', 'KYB');
|
||||
return journey;
|
||||
}
|
||||
const correctionReason = 'Please clarify the beneficial ownership structure before resubmitting.';
|
||||
const legacyNote = (index: number) =>
|
||||
index % 2
|
||||
? 'Команда заинтересована в подключении. Следующий контакт — после проверки документов.'
|
||||
: 'Initial discovery complete. The team is interested in a straightforward checkout integration.';
|
||||
const include = {
|
||||
checklist: true,
|
||||
events: { orderBy: { occurredAt: 'asc' as const } },
|
||||
notes: true,
|
||||
tasks: true,
|
||||
} as const;
|
||||
type SeedMerchant = Prisma.MerchantGetPayload<{ include: typeof include }>;
|
||||
// Only exact legacy fixtures receive inferred demo evidence. A changed fixture is preserved.
|
||||
function matchesLegacy(m: SeedMerchant, index: number) {
|
||||
if (index >= 18) return false;
|
||||
const status = allStages[Math.floor(index / 2)]!;
|
||||
// The original Luma fixture returned to KYB once (without a duplicate KYB event).
|
||||
const journey: Status[] =
|
||||
index === 6 ? [...successfulStages.slice(0, 5), 'KYB'] : journeyFor(status, false);
|
||||
const domain = names[index]!.toLowerCase().replaceAll(' ', '') + '.example';
|
||||
if (
|
||||
m.name !== names[index] ||
|
||||
m.status !== status ||
|
||||
m.ownerId !== `user-manager${(index % 2) + 1}` ||
|
||||
m.website !== `https://${domain}` ||
|
||||
m.industry !== industries[index % 4] ||
|
||||
m.country !== countries[index % 6] ||
|
||||
m.contactName !== (index % 2 ? 'Jamie Wilson' : 'Sam Taylor') ||
|
||||
m.contactEmail !== `hello@${domain}` ||
|
||||
m.events.length !== journey.length ||
|
||||
m.checklist.length !== 4 ||
|
||||
m.notes.length !== 1 ||
|
||||
m.tasks.length !== 2 ||
|
||||
m.createdAt.getTime() !== m.stageEnteredAt.getTime() - (journey.length - 1) * 3 * day
|
||||
)
|
||||
return false;
|
||||
if (
|
||||
!m.events.every(
|
||||
(event, i) =>
|
||||
event.id === `${m.id}-event-${i}` &&
|
||||
event.toStatus === journey[i] &&
|
||||
event.fromStatus === (journey[i - 1] ?? null) &&
|
||||
event.occurredAt.getTime() === m.createdAt.getTime() + i * 3 * day &&
|
||||
event.actorId ===
|
||||
(event.toStatus === 'COMPLIANCE_REVIEW' || (i > 0 && event.toStatus === 'KYB')
|
||||
? 'user-compliance'
|
||||
: m.ownerId) &&
|
||||
event.note ===
|
||||
(event.fromStatus === 'COMPLIANCE_REVIEW' && event.toStatus === 'KYB'
|
||||
? correctionReason
|
||||
: null),
|
||||
)
|
||||
)
|
||||
return false;
|
||||
if (
|
||||
!m.checklist.every((item) => {
|
||||
const j = documentCodes.indexOf(item.documentCode);
|
||||
return (
|
||||
item.id === `${m.id}-doc-${j}` &&
|
||||
item.state ===
|
||||
(status === 'KYB'
|
||||
? j === 2
|
||||
? 'NEEDS_CORRECTION'
|
||||
: j === 3
|
||||
? 'MISSING'
|
||||
: 'RECEIVED'
|
||||
: ['NEW_LEAD', 'CONTACTED', 'QUALIFIED'].includes(status)
|
||||
? 'MISSING'
|
||||
: 'RECEIVED') &&
|
||||
item.note ===
|
||||
(status === 'KYB' && j === 2 ? 'Ownership declaration needs an updated signature.' : null)
|
||||
);
|
||||
})
|
||||
)
|
||||
return false;
|
||||
const note = m.notes[0]!;
|
||||
if (
|
||||
note.text !== legacyNote(index) ||
|
||||
note.authorId !== m.ownerId ||
|
||||
note.createdAt.getTime() !== m.stageEnteredAt.getTime() + 3600000
|
||||
)
|
||||
return false;
|
||||
const open = m.tasks.find((task) => task.id === `${m.id}-task-1`);
|
||||
const done = m.tasks.find((task) => task.id === `${m.id}-task-2`);
|
||||
const anchor = m.stageEnteredAt.getTime() + ((index % 4) + 1) * day;
|
||||
return (
|
||||
open?.status === 'OPEN' &&
|
||||
open.assigneeId === m.ownerId &&
|
||||
open.completedAt === null &&
|
||||
open.title ===
|
||||
(status === 'KYB'
|
||||
? 'Follow up on ownership documentation'
|
||||
: status === 'COMPLIANCE_REVIEW'
|
||||
? 'Review the merchant document checklist'
|
||||
: 'Schedule the next merchant check-in') &&
|
||||
open.dueAt.getTime() === anchor + ((index % 5) - 2) * day &&
|
||||
open.remindAt?.getTime() === anchor + ((index % 5) - 3) * day &&
|
||||
done?.status === 'DONE' &&
|
||||
done.assigneeId === m.ownerId &&
|
||||
done.title === 'Confirm the primary contact details' &&
|
||||
done.dueAt.getTime() === m.stageEnteredAt.getTime() &&
|
||||
done.completedAt?.getTime() === m.stageEnteredAt.getTime()
|
||||
);
|
||||
}
|
||||
function companyFields(index: number) {
|
||||
return {
|
||||
legalName: `${names[index]} ${index % 2 ? 'Limited' : 'Ltd'}`,
|
||||
registrationNumber: `MF-${countries[index % 6]}-${81000 + index}`,
|
||||
address: `${12 + index} Example Lane`,
|
||||
contactPhone: `+44 20 7946 ${String(index).padStart(4, '0')}`,
|
||||
contactTitle: index % 2 ? 'Operations Director' : 'Founder',
|
||||
estimatedMonthlyVolumeUsd: String([25000, 80000, 145000, 310000, 680000, 1250000][index % 6]),
|
||||
source: sources[index % sources.length]!,
|
||||
};
|
||||
}
|
||||
async function createMerchant(tx: Prisma.TransactionClient, index: number, anchor: number) {
|
||||
const id = `merchant-${String(index + 1).padStart(2, '0')}`;
|
||||
const status = index < 18 ? allStages[Math.floor(index / 2)]! : extraStages[index - 18]!;
|
||||
const ownerId =
|
||||
index >= 18 && index < 23
|
||||
? null
|
||||
: index < 18
|
||||
? `user-manager${(index % 2) + 1}`
|
||||
: `user-manager${((index - 23) % 2) + 1}`;
|
||||
const actorId = ownerId ?? 'user-head';
|
||||
const correction =
|
||||
index === 6 ||
|
||||
(index >= 18 && ['KYB', 'COMPLIANCE_REVIEW', 'LIVE'].includes(status) && index % 3 === 0);
|
||||
const journey =
|
||||
status === 'KYB' && correction
|
||||
? ([...successfulStages.slice(0, 5), 'KYB'] as Status[])
|
||||
: journeyFor(status, correction);
|
||||
const age =
|
||||
status === 'NEW_LEAD'
|
||||
? (index % 7) + 1
|
||||
: status === 'CONTACTED'
|
||||
? 15 + (index % 8)
|
||||
: status === 'QUALIFIED'
|
||||
? 28 + (index % 9)
|
||||
: status === 'LIVE'
|
||||
? index === 41
|
||||
? 90
|
||||
: 76 + (index % 10)
|
||||
: 40 + (index % 25);
|
||||
const stageEnteredAt = new Date(anchor - ((index % 5) + 1) * day);
|
||||
const createdAt = journey.length === 1 ? stageEnteredAt : new Date(anchor - age * day);
|
||||
const step =
|
||||
journey.length === 1
|
||||
? 0
|
||||
: (stageEnteredAt.getTime() - createdAt.getTime()) / (journey.length - 1);
|
||||
const domain = names[index]!.toLowerCase().replaceAll(' ', '') + '.example';
|
||||
await tx.merchant.create({
|
||||
data: {
|
||||
id,
|
||||
name: names[index]!,
|
||||
website: `https://${domain}`,
|
||||
industry: industries[index % 4]!,
|
||||
country: countries[index % 6]!,
|
||||
contactName: contacts[index % contacts.length]!,
|
||||
contactEmail: `hello@${domain}`,
|
||||
...companyFields(index),
|
||||
status,
|
||||
ownerId,
|
||||
createdAt,
|
||||
stageEnteredAt,
|
||||
updatedAt: stageEnteredAt,
|
||||
events: {
|
||||
create: journey.map((toStatus, i) => ({
|
||||
id: `${id}-event-${i}`,
|
||||
fromStatus: journey[i - 1] ?? null,
|
||||
toStatus,
|
||||
actorId: journey[i - 1] === 'COMPLIANCE_REVIEW' ? 'user-compliance' : actorId,
|
||||
occurredAt: new Date(createdAt.getTime() + Math.round(i * step)),
|
||||
note:
|
||||
journey[i - 1] === 'COMPLIANCE_REVIEW' && toStatus === 'KYB'
|
||||
? correctionReason
|
||||
: toStatus === 'REJECTED'
|
||||
? 'Unable to verify the declared beneficial owner against the submitted ownership register.'
|
||||
: null,
|
||||
})),
|
||||
},
|
||||
checklist: {
|
||||
create: documentCodes.map((documentCode, j) => ({
|
||||
id: `${id}-doc-${j}`,
|
||||
documentCode,
|
||||
state:
|
||||
status === 'KYB'
|
||||
? j === 2
|
||||
? 'NEEDS_CORRECTION'
|
||||
: j === 3
|
||||
? 'MISSING'
|
||||
: 'RECEIVED'
|
||||
: ['NEW_LEAD', 'CONTACTED', 'QUALIFIED'].includes(status)
|
||||
})),
|
||||
},
|
||||
checklist: {
|
||||
create: documentCodes.map((documentCode, j) => ({
|
||||
id: `${id}-doc-${j}`,
|
||||
documentCode,
|
||||
state:
|
||||
status === 'KYB'
|
||||
? j === 2 && correction
|
||||
? 'NEEDS_CORRECTION'
|
||||
: j >= 2
|
||||
? 'MISSING'
|
||||
: 'RECEIVED',
|
||||
note:
|
||||
status === 'KYB' && j === 2
|
||||
? 'Ownership declaration needs an updated signature.'
|
||||
: null,
|
||||
})),
|
||||
},
|
||||
notes: {
|
||||
create: {
|
||||
id: `${id}-note`,
|
||||
authorId: ownerId,
|
||||
text:
|
||||
index % 2
|
||||
? 'Команда заинтересована в подключении. Следующий контакт — после проверки документов.'
|
||||
: 'Initial discovery complete. The team is interested in a straightforward checkout integration.',
|
||||
createdAt: new Date(stageEnteredAt.getTime() + 3600000),
|
||||
},
|
||||
},
|
||||
tasks: {
|
||||
create: [
|
||||
{
|
||||
id: `${id}-task-1`,
|
||||
assigneeId: ownerId,
|
||||
title:
|
||||
status === 'KYB'
|
||||
? 'Follow up on ownership documentation'
|
||||
: status === 'COMPLIANCE_REVIEW'
|
||||
? 'Review the merchant document checklist'
|
||||
: 'Schedule the next merchant check-in',
|
||||
status: 'OPEN',
|
||||
dueAt: new Date(now + ((index % 5) - 2) * day),
|
||||
remindAt: new Date(now + ((index % 5) - 3) * day),
|
||||
},
|
||||
{
|
||||
id: `${id}-task-2`,
|
||||
assigneeId: ownerId,
|
||||
title: 'Confirm the primary contact details',
|
||||
status: 'DONE',
|
||||
dueAt: stageEnteredAt,
|
||||
completedAt: stageEnteredAt,
|
||||
},
|
||||
],
|
||||
: 'RECEIVED'
|
||||
: ['NEW_LEAD', 'CONTACTED', 'QUALIFIED'].includes(status)
|
||||
? 'MISSING'
|
||||
: 'RECEIVED',
|
||||
note:
|
||||
status === 'KYB' && j === 2 && correction
|
||||
? 'Ownership declaration needs an updated signature.'
|
||||
: null,
|
||||
updatedAt: stageEnteredAt,
|
||||
})),
|
||||
},
|
||||
notes: {
|
||||
create: {
|
||||
id: `${id}-note`,
|
||||
authorId: actorId,
|
||||
text:
|
||||
index < 18
|
||||
? legacyNote(index)
|
||||
: `Discussed ${index % 2 ? 'hosted checkout' : 'API integration'} with ${contacts[index % contacts.length]}. Expected rollout in ${(index % 3) + 2} weeks after approval.`,
|
||||
createdAt: new Date(stageEnteredAt.getTime() + 3600000),
|
||||
},
|
||||
},
|
||||
tasks: {
|
||||
create: [
|
||||
{
|
||||
id: `${id}-task-1`,
|
||||
assigneeId: actorId,
|
||||
creatorId: actorId,
|
||||
title:
|
||||
status === 'KYB'
|
||||
? 'Follow up on ownership documentation'
|
||||
: status === 'LIVE'
|
||||
? 'Review the first-week integration feedback'
|
||||
: status === 'REJECTED'
|
||||
? 'Send the closure summary to the primary contact'
|
||||
: 'Schedule the next merchant check-in',
|
||||
status: 'OPEN',
|
||||
dueAt: new Date(anchor + ((index % 7) - 3) * day),
|
||||
remindAt: new Date(anchor + ((index % 7) - 4) * day),
|
||||
createdAt: stageEnteredAt,
|
||||
updatedAt: stageEnteredAt,
|
||||
},
|
||||
{
|
||||
id: `${id}-task-2`,
|
||||
assigneeId: actorId,
|
||||
creatorId: actorId,
|
||||
title: 'Confirm the primary contact details',
|
||||
status: 'DONE',
|
||||
dueAt: stageEnteredAt,
|
||||
completedAt: stageEnteredAt,
|
||||
completedById: actorId,
|
||||
createdAt,
|
||||
updatedAt: stageEnteredAt,
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
async function enrich(
|
||||
tx: Prisma.TransactionClient,
|
||||
m: SeedMerchant,
|
||||
index: number,
|
||||
anchor: number,
|
||||
) {
|
||||
const actorId = m.ownerId ?? 'user-head';
|
||||
const allReceived = m.checklist.map((item) => ({ ...item, state: 'RECEIVED', note: null }));
|
||||
for (const item of m.checklist)
|
||||
await tx.checklistChange.create({
|
||||
data: {
|
||||
id: `${item.id}-initial`,
|
||||
itemId: item.id,
|
||||
actorId,
|
||||
fromState: null,
|
||||
toState: 'MISSING',
|
||||
occurredAt: m.createdAt,
|
||||
},
|
||||
});
|
||||
let cycle = 0;
|
||||
let states: Record<string, 'MISSING' | 'RECEIVED' | 'NEEDS_CORRECTION'> = Object.fromEntries(
|
||||
m.checklist.map((item) => [item.id, 'MISSING']),
|
||||
);
|
||||
for (let e = 0; e < m.events.length; e++) {
|
||||
const event = m.events[e]!;
|
||||
if (event.toStatus !== 'COMPLIANCE_REVIEW') continue;
|
||||
cycle++;
|
||||
for (const item of m.checklist)
|
||||
await tx.checklistChange.create({
|
||||
data: {
|
||||
id: `${item.id}-received-${cycle}`,
|
||||
itemId: item.id,
|
||||
actorId,
|
||||
fromState: states[item.id],
|
||||
toState: 'RECEIVED',
|
||||
occurredAt: new Date(event.occurredAt.getTime() - 3600000),
|
||||
},
|
||||
});
|
||||
states = Object.fromEntries(m.checklist.map((item) => [item.id, 'RECEIVED']));
|
||||
const next = m.events[e + 1];
|
||||
const decision = !next
|
||||
? 'PENDING'
|
||||
: next.toStatus === 'KYB'
|
||||
? 'CORRECTIONS'
|
||||
: next.toStatus === 'REJECTED'
|
||||
? 'REJECTED'
|
||||
: 'APPROVED';
|
||||
const decidedAt = next ? new Date(next.occurredAt.getTime() - 1) : null;
|
||||
await tx.complianceReview.create({
|
||||
data: {
|
||||
id: `${m.id}-review-${cycle}`,
|
||||
merchantId: m.id,
|
||||
cycle,
|
||||
submittedById: actorId,
|
||||
reviewerId: next ? 'user-compliance' : null,
|
||||
decision,
|
||||
submittedAt: event.occurredAt,
|
||||
decidedAt,
|
||||
reason:
|
||||
decision === 'CORRECTIONS'
|
||||
? correctionReason
|
||||
: decision === 'REJECTED'
|
||||
? (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.'
|
||||
: null,
|
||||
snapshot: reviewSnapshot({ ...m, checklist: allReceived }),
|
||||
},
|
||||
});
|
||||
if (decision === 'CORRECTIONS')
|
||||
for (const item of m.checklist.filter((item) =>
|
||||
['UBO_IDENTIFICATION', 'BUSINESS_ACTIVITY'].includes(item.documentCode),
|
||||
)) {
|
||||
const state = item.documentCode === 'UBO_IDENTIFICATION' ? 'NEEDS_CORRECTION' : 'MISSING';
|
||||
await tx.checklistChange.create({
|
||||
data: {
|
||||
id: `${item.id}-correction-${cycle}`,
|
||||
itemId: item.id,
|
||||
actorId: 'user-compliance',
|
||||
fromState: 'RECEIVED',
|
||||
toState: state,
|
||||
note:
|
||||
item.documentCode === 'UBO_IDENTIFICATION'
|
||||
? 'Ownership declaration needs an updated signature.'
|
||||
: 'Please provide a current description of the business activity.',
|
||||
occurredAt: decidedAt!,
|
||||
},
|
||||
});
|
||||
states[item.id] = state;
|
||||
}
|
||||
}
|
||||
console.log('Seed ready: 4 accounts, 18 merchants. Password: MerchantFlow123!');
|
||||
for (const item of m.checklist)
|
||||
if (states[item.id] !== item.state)
|
||||
await tx.checklistChange.create({
|
||||
data: {
|
||||
id: `${item.id}-current`,
|
||||
itemId: item.id,
|
||||
actorId,
|
||||
fromState: states[item.id],
|
||||
toState: item.state,
|
||||
note: item.note,
|
||||
occurredAt: new Date(m.stageEnteredAt.getTime() + 1000),
|
||||
},
|
||||
});
|
||||
await tx.activity.createMany({
|
||||
data: [
|
||||
{
|
||||
id: `${m.id}-activity-1`,
|
||||
merchantId: m.id,
|
||||
actorId,
|
||||
kind: 'NOTE',
|
||||
text: `Lead received through ${m.source?.toLowerCase() ?? 'referral'}. Primary contact: ${m.contactName}.`,
|
||||
occurredAt: m.createdAt,
|
||||
updatedAt: m.createdAt,
|
||||
},
|
||||
{
|
||||
id: `${m.id}-activity-2`,
|
||||
merchantId: m.id,
|
||||
actorId,
|
||||
kind: index % 2 ? 'EMAIL' : 'CALL',
|
||||
text:
|
||||
m.status === 'NEW_LEAD'
|
||||
? 'Prepared the introductory outreach and confirmed the company website.'
|
||||
: `Discussed expected monthly processing of USD ${m.estimatedMonthlyVolumeUsd} and ${index % 2 ? 'settlement reporting' : 'checkout requirements'}.`,
|
||||
occurredAt: new Date(m.createdAt.getTime() + 3600000),
|
||||
updatedAt: new Date(m.createdAt.getTime() + 3600000),
|
||||
},
|
||||
{
|
||||
id: `${m.id}-activity-3`,
|
||||
merchantId: m.id,
|
||||
actorId: cycle ? 'user-compliance' : actorId,
|
||||
kind: cycle ? 'KYB_NOTE' : 'NOTE',
|
||||
text: cycle
|
||||
? 'Review evidence and document changes are recorded in the KYB history.'
|
||||
: 'Next follow-up is tracked in the merchant task list.',
|
||||
occurredAt: m.stageEnteredAt,
|
||||
updatedAt: m.stageEnteredAt,
|
||||
},
|
||||
],
|
||||
});
|
||||
if (cycle)
|
||||
await tx.task.create({
|
||||
data: {
|
||||
id: `${m.id}-compliance-task`,
|
||||
merchantId: m.id,
|
||||
kind: 'COMPLIANCE',
|
||||
assigneeId: 'user-compliance',
|
||||
creatorId: 'user-compliance',
|
||||
title:
|
||||
m.status === 'KYB'
|
||||
? 'Check corrected beneficial ownership evidence'
|
||||
: m.status === 'COMPLIANCE_REVIEW'
|
||||
? 'Complete the KYB assessment'
|
||||
: 'Record the compliance decision rationale',
|
||||
status: ['KYB', 'COMPLIANCE_REVIEW'].includes(m.status) ? 'OPEN' : 'DONE',
|
||||
dueAt: new Date(anchor + ((index % 5) - 2) * day),
|
||||
remindAt: new Date(anchor + ((index % 5) - 3) * day),
|
||||
createdAt: m.events.find((e) => e.toStatus === 'COMPLIANCE_REVIEW')!.occurredAt,
|
||||
completedAt: ['KYB', 'COMPLIANCE_REVIEW'].includes(m.status) ? null : m.stageEnteredAt,
|
||||
completedById: ['KYB', 'COMPLIANCE_REVIEW'].includes(m.status) ? null : 'user-compliance',
|
||||
updatedAt: m.stageEnteredAt,
|
||||
},
|
||||
});
|
||||
await tx.demoSeedRecord.create({ data: { merchantId: m.id, version: 2 } });
|
||||
}
|
||||
try {
|
||||
await db.$transaction(
|
||||
async (tx) => {
|
||||
await tx.$executeRaw`SELECT pg_advisory_xact_lock(72465102)`;
|
||||
const seed = await tx.demoSeedState.upsert({
|
||||
where: { id: 'merchantflow-v2' },
|
||||
update: {},
|
||||
create: { id: 'merchantflow-v2' },
|
||||
});
|
||||
for (const user of users)
|
||||
await tx.user.upsert({
|
||||
where: { id: user.id },
|
||||
update: {},
|
||||
create: { ...user, passwordHash: hashPassword('MerchantFlow123!') },
|
||||
});
|
||||
for (const [id, oldEmail, email, oldName, name] of [
|
||||
[
|
||||
'user-manager1',
|
||||
'[email protected]',
|
||||
'[email protected]',
|
||||
'Alex Morgan',
|
||||
'Alex Morgan',
|
||||
],
|
||||
[
|
||||
'user-manager2',
|
||||
'[email protected]',
|
||||
'[email protected]',
|
||||
'Maria Chen',
|
||||
'Sam Taylor',
|
||||
],
|
||||
]) {
|
||||
await tx.user.updateMany({ where: { id, email: oldEmail }, data: { email } });
|
||||
if (oldName !== name)
|
||||
await tx.user.updateMany({ where: { id, name: oldName }, data: { name } });
|
||||
}
|
||||
for (let index = 0; index < names.length; index++) {
|
||||
const id = `merchant-${String(index + 1).padStart(2, '0')}`;
|
||||
if (await tx.demoSeedRecord.findUnique({ where: { merchantId: id } })) continue;
|
||||
let merchant = await tx.merchant.findUnique({ where: { id }, include });
|
||||
if (merchant) {
|
||||
if (!matchesLegacy(merchant, index)) {
|
||||
console.warn(
|
||||
`Preserved edited or unrecognized legacy fixture ${id}; no approval/history inferred.`,
|
||||
);
|
||||
continue;
|
||||
}
|
||||
const fields = companyFields(index);
|
||||
await tx.merchant.update({
|
||||
where: { id },
|
||||
data: {
|
||||
...Object.fromEntries(
|
||||
Object.entries(fields).filter(
|
||||
([key]) => merchant![key as keyof typeof fields] === null,
|
||||
),
|
||||
),
|
||||
updatedAt: merchant.updatedAt,
|
||||
},
|
||||
});
|
||||
for (const task of merchant.tasks)
|
||||
await tx.task.update({
|
||||
where: { id: task.id },
|
||||
data: {
|
||||
creatorId: task.assigneeId,
|
||||
completedById: task.status === 'DONE' ? task.assigneeId : null,
|
||||
createdAt: merchant.createdAt,
|
||||
updatedAt: task.completedAt ?? merchant.stageEnteredAt,
|
||||
},
|
||||
});
|
||||
} else await createMerchant(tx, index, seed.anchorAt.getTime());
|
||||
merchant = await tx.merchant.findUniqueOrThrow({ where: { id }, include });
|
||||
await enrich(tx, merchant, index, seed.anchorAt.getTime());
|
||||
}
|
||||
},
|
||||
{ timeout: 60000 },
|
||||
);
|
||||
console.log(
|
||||
'Seed ready: 4 demo accounts, 45 fixture IDs. Password for newly created accounts: MerchantFlow123! Existing edits and passwords preserved.',
|
||||
);
|
||||
} finally {
|
||||
await db.$disconnect();
|
||||
}
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
import { documentCodes } from '@merchantflow/contracts';
|
||||
|
||||
export const reviewedFields = [
|
||||
'name',
|
||||
'legalName',
|
||||
'registrationNumber',
|
||||
'address',
|
||||
'website',
|
||||
'country',
|
||||
'industry',
|
||||
] as const;
|
||||
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) {
|
||||
return {
|
||||
company: Object.fromEntries(reviewedFields.map((key) => [key, merchant[key]])),
|
||||
checklist: [...merchant.checklist]
|
||||
.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'),
|
||||
)
|
||||
);
|
||||
}
|
||||
export function snapshotsEqual(a: unknown, b: unknown): boolean {
|
||||
const canonical = (value: unknown): string => {
|
||||
if (Array.isArray(value)) return `[${value.map(canonical).join(',')}]`;
|
||||
if (value && typeof value === 'object')
|
||||
return `{${Object.entries(value)
|
||||
.sort(([a], [b]) => a.localeCompare(b))
|
||||
.map(([key, item]) => `${JSON.stringify(key)}:${canonical(item)}`)
|
||||
.join(',')}}`;
|
||||
return JSON.stringify(value);
|
||||
};
|
||||
return canonical(a) === canonical(b);
|
||||
}
|
||||
Reference in New Issue
Block a user