Implemented the database, authentication, access rules, and seed data
This commit is contained in:
@@ -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