Build MerchantFlow onboarding CRM foundation

This commit is contained in:
Oleksandr Prokhorenko
2026-09-24 16:43:22 +03:00
commit 3aa47d825f
78 changed files with 10739 additions and 0 deletions
+31
View File
@@ -0,0 +1,31 @@
{
"name": "@merchantflow/database",
"version": "0.0.0",
"private": true,
"type": "module",
"exports": {
".": {
"types": "./dist/index.d.ts",
"node": "./dist/index.js"
}
},
"scripts": {
"generate": "prisma generate",
"build": "tsc",
"typecheck": "tsc --noEmit",
"migrate": "prisma migrate deploy",
"seed": "node dist/seed.js",
"dev": "tsc --watch --preserveWatchOutput"
},
"dependencies": {
"@merchantflow/contracts": "workspace:*",
"@prisma/adapter-pg": "7.10.0",
"@prisma/client": "7.10.0",
"dotenv": "17.4.2",
"pg": "8.23.0"
},
"devDependencies": {
"@types/pg": "8.23.1",
"prisma": "7.10.0"
}
}
+12
View File
@@ -0,0 +1,12 @@
import { config } from 'dotenv';
import { defineConfig } from 'prisma/config';
config({ path: new URL('../../.env', import.meta.url).pathname, quiet: true });
export default defineConfig({
schema: 'prisma/schema.prisma',
migrations: { path: 'prisma/migrations' },
datasource: {
url:
process.env.DATABASE_URL ??
'postgresql://merchantflow:merchantflow_local@localhost:55440/merchantflow',
},
});
@@ -0,0 +1,157 @@
-- CreateSchema
CREATE SCHEMA IF NOT EXISTS "public";
-- CreateEnum
CREATE TYPE "Role" AS ENUM ('HEAD_OF_SALES', 'COMPLIANCE_OFFICER', 'ACCOUNT_MANAGER');
-- CreateEnum
CREATE TYPE "MerchantStatus" AS ENUM ('NEW_LEAD', 'CONTACTED', 'QUALIFIED', 'KYB', 'COMPLIANCE_REVIEW', 'INTEGRATION', 'TESTING', 'LIVE', 'REJECTED');
-- CreateEnum
CREATE TYPE "ChecklistState" AS ENUM ('MISSING', 'RECEIVED', 'NEEDS_CORRECTION');
-- CreateEnum
CREATE TYPE "DocumentCode" AS ENUM ('INCORPORATION', 'OWNERSHIP', 'UBO_IDENTIFICATION', 'BUSINESS_ACTIVITY');
-- CreateEnum
CREATE TYPE "TaskStatus" AS ENUM ('OPEN', 'DONE');
-- CreateTable
CREATE TABLE "User" (
"id" TEXT NOT NULL,
"email" TEXT NOT NULL,
"name" TEXT NOT NULL,
"passwordHash" TEXT NOT NULL,
"role" "Role" NOT NULL,
CONSTRAINT "User_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "Session" (
"id" TEXT NOT NULL,
"userId" TEXT NOT NULL,
"expiresAt" TIMESTAMP(3) NOT NULL,
CONSTRAINT "Session_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "Merchant" (
"id" TEXT NOT NULL,
"name" TEXT NOT NULL,
"website" TEXT NOT NULL,
"industry" TEXT NOT NULL,
"country" TEXT NOT NULL,
"contactName" TEXT NOT NULL,
"contactEmail" TEXT NOT NULL,
"status" "MerchantStatus" NOT NULL DEFAULT 'NEW_LEAD',
"ownerId" TEXT NOT NULL,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"stageEnteredAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "Merchant_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "StatusEvent" (
"id" TEXT NOT NULL,
"merchantId" TEXT NOT NULL,
"actorId" TEXT NOT NULL,
"fromStatus" "MerchantStatus",
"toStatus" "MerchantStatus" NOT NULL,
"occurredAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"note" TEXT,
CONSTRAINT "StatusEvent_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "KybChecklistItem" (
"id" TEXT NOT NULL,
"merchantId" TEXT NOT NULL,
"documentCode" "DocumentCode" NOT NULL,
"state" "ChecklistState" NOT NULL DEFAULT 'MISSING',
"note" TEXT,
CONSTRAINT "KybChecklistItem_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "MerchantNote" (
"id" TEXT NOT NULL,
"merchantId" TEXT NOT NULL,
"authorId" TEXT NOT NULL,
"text" TEXT NOT NULL,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "MerchantNote_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "Task" (
"id" TEXT NOT NULL,
"merchantId" TEXT NOT NULL,
"assigneeId" TEXT NOT NULL,
"title" TEXT NOT NULL,
"status" "TaskStatus" NOT NULL DEFAULT 'OPEN',
"dueAt" TIMESTAMP(3) NOT NULL,
"remindAt" TIMESTAMP(3),
"completedAt" TIMESTAMP(3),
CONSTRAINT "Task_pkey" PRIMARY KEY ("id")
);
-- CreateIndex
CREATE UNIQUE INDEX "User_email_key" ON "User"("email");
-- CreateIndex
CREATE INDEX "Session_expiresAt_idx" ON "Session"("expiresAt");
-- CreateIndex
CREATE INDEX "Merchant_ownerId_status_idx" ON "Merchant"("ownerId", "status");
-- CreateIndex
CREATE INDEX "Merchant_status_stageEnteredAt_idx" ON "Merchant"("status", "stageEnteredAt");
-- CreateIndex
CREATE INDEX "StatusEvent_merchantId_occurredAt_idx" ON "StatusEvent"("merchantId", "occurredAt");
-- CreateIndex
CREATE INDEX "StatusEvent_occurredAt_idx" ON "StatusEvent"("occurredAt");
-- CreateIndex
CREATE UNIQUE INDEX "KybChecklistItem_merchantId_documentCode_key" ON "KybChecklistItem"("merchantId", "documentCode");
-- CreateIndex
CREATE INDEX "MerchantNote_merchantId_createdAt_idx" ON "MerchantNote"("merchantId", "createdAt");
-- CreateIndex
CREATE INDEX "Task_merchantId_status_dueAt_idx" ON "Task"("merchantId", "status", "dueAt");
-- AddForeignKey
ALTER TABLE "Session" ADD CONSTRAINT "Session_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "Merchant" ADD CONSTRAINT "Merchant_ownerId_fkey" FOREIGN KEY ("ownerId") REFERENCES "User"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "StatusEvent" ADD CONSTRAINT "StatusEvent_merchantId_fkey" FOREIGN KEY ("merchantId") REFERENCES "Merchant"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "StatusEvent" ADD CONSTRAINT "StatusEvent_actorId_fkey" FOREIGN KEY ("actorId") REFERENCES "User"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "KybChecklistItem" ADD CONSTRAINT "KybChecklistItem_merchantId_fkey" FOREIGN KEY ("merchantId") REFERENCES "Merchant"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "MerchantNote" ADD CONSTRAINT "MerchantNote_merchantId_fkey" FOREIGN KEY ("merchantId") REFERENCES "Merchant"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "MerchantNote" ADD CONSTRAINT "MerchantNote_authorId_fkey" FOREIGN KEY ("authorId") REFERENCES "User"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "Task" ADD CONSTRAINT "Task_merchantId_fkey" FOREIGN KEY ("merchantId") REFERENCES "Merchant"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "Task" ADD CONSTRAINT "Task_assigneeId_fkey" FOREIGN KEY ("assigneeId") REFERENCES "User"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
@@ -0,0 +1 @@
provider = "postgresql"
+123
View File
@@ -0,0 +1,123 @@
generator client {
provider = "prisma-client"
output = "../src/generated/prisma"
moduleFormat = "esm"
}
datasource db {
provider = "postgresql"
}
enum Role {
HEAD_OF_SALES
COMPLIANCE_OFFICER
ACCOUNT_MANAGER
}
enum MerchantStatus {
NEW_LEAD
CONTACTED
QUALIFIED
KYB
COMPLIANCE_REVIEW
INTEGRATION
TESTING
LIVE
REJECTED
}
enum ChecklistState {
MISSING
RECEIVED
NEEDS_CORRECTION
}
enum DocumentCode {
INCORPORATION
OWNERSHIP
UBO_IDENTIFICATION
BUSINESS_ACTIVITY
}
enum TaskStatus {
OPEN
DONE
}
model User {
id String @id @default(uuid())
email String @unique
name String
passwordHash String
role Role
sessions Session[]
merchants Merchant[]
events StatusEvent[]
notes MerchantNote[]
tasks Task[]
}
model Session {
id String @id
userId String
expiresAt DateTime
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
@@index([expiresAt])
}
model Merchant {
id String @id @default(uuid())
name String
website String
industry String
country String
contactName String
contactEmail String
status MerchantStatus @default(NEW_LEAD)
ownerId String
createdAt DateTime @default(now())
stageEnteredAt DateTime @default(now())
owner User @relation(fields: [ownerId], references: [id])
events StatusEvent[]
checklist KybChecklistItem[]
notes MerchantNote[]
tasks Task[]
@@index([ownerId, status])
@@index([status, stageEnteredAt])
}
model StatusEvent {
id String @id @default(uuid())
merchantId String
actorId String
fromStatus MerchantStatus?
toStatus MerchantStatus
occurredAt DateTime @default(now())
note String?
merchant Merchant @relation(fields: [merchantId], references: [id], onDelete: Cascade)
actor User @relation(fields: [actorId], references: [id])
@@index([merchantId, occurredAt])
@@index([occurredAt])
}
model KybChecklistItem {
id String @id @default(uuid())
merchantId String
documentCode DocumentCode
state ChecklistState @default(MISSING)
note String?
merchant Merchant @relation(fields: [merchantId], references: [id], onDelete: Cascade)
@@unique([merchantId, documentCode])
}
model MerchantNote {
id String @id @default(uuid())
merchantId String
authorId String
text String
createdAt DateTime @default(now())
merchant Merchant @relation(fields: [merchantId], references: [id], onDelete: Cascade)
author User @relation(fields: [authorId], references: [id])
@@index([merchantId, createdAt])
}
model Task {
id String @id @default(uuid())
merchantId String
assigneeId String
title String
status TaskStatus @default(OPEN)
dueAt DateTime
remindAt DateTime?
completedAt DateTime?
merchant Merchant @relation(fields: [merchantId], references: [id], onDelete: Cascade)
assignee User @relation(fields: [assigneeId], references: [id])
@@index([merchantId, status, dueAt])
}
+10
View File
@@ -0,0 +1,10 @@
import { PrismaClient } from './generated/prisma/client.js';
import { PrismaPg } from '@prisma/adapter-pg';
export { PrismaClient };
export { hashPassword, verifyPassword } from './password.js';
export type { Prisma } from './generated/prisma/client.js';
export function createDatabase(url: string) {
return new PrismaClient({
adapter: new PrismaPg({ connectionString: url, connectionTimeoutMillis: 3000 }),
});
}
+12
View File
@@ -0,0 +1,12 @@
import { scryptSync, randomBytes, timingSafeEqual } from 'node:crypto';
export function hashPassword(password: string) {
const salt = randomBytes(16).toString('hex');
return `${salt}:${scryptSync(password, salt, 64).toString('hex')}`;
}
export function verifyPassword(password: string, stored: string) {
const [salt, hash] = stored.split(':');
if (!salt || !hash) return false;
const expected = Buffer.from(hash, 'hex');
const actual = scryptSync(password, salt, 64);
return expected.length === actual.length && timingSafeEqual(actual, expected);
}
+173
View File
@@ -0,0 +1,173 @@
import { config } from 'dotenv';
import { statuses, successfulStages, documentCodes, type Status } from '@merchantflow/contracts';
import { createDatabase } from './index.js';
import { hashPassword } from './password.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 names = [
'Orbit Goods',
'Northstar Studio',
'Forma Market',
'Sora Travel',
'Atlas Commerce',
'Mellow Living',
'Luma Labs',
'Nomad Supply',
'Aster Digital',
'Fieldwork',
'Contour Studio',
'Evergreen Shop',
'Nova Collective',
'Plain Goods',
'Sunday Market',
'Kinfolk Supply',
'Peak Ventures',
'Amber Exchange',
];
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.'
: 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)
? '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,
},
],
},
},
});
}
console.log('Seed ready: 4 accounts, 18 merchants. Password: MerchantFlow123!');
} finally {
await db.$disconnect();
}
+11
View File
@@ -0,0 +1,11 @@
{
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"module": "NodeNext",
"moduleResolution": "NodeNext",
"rootDir": "src",
"outDir": "dist",
"declaration": true
},
"include": ["src"]
}