commit 3aa47d825fe8273d9d14e750b99e85a9d3a61e37 Author: Oleksandr Prokhorenko Date: Thu Sep 24 16:43:22 2026 +0300 Build MerchantFlow onboarding CRM foundation diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..1d696f5 --- /dev/null +++ b/.env.example @@ -0,0 +1,4 @@ +DATABASE_URL=postgresql://merchantflow:merchantflow_local@localhost:55440/merchantflow +API_PORT=3001 +WEB_PORT=5173 +APP_ORIGIN=http://localhost:5173 diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..699074e --- /dev/null +++ b/.gitignore @@ -0,0 +1,12 @@ +node_modules/ +dist/ +.turbo/ +.env +.env.* +!.env.example +packages/database/src/generated/ +playwright-report/ +test-results/ +coverage/ +*.tsbuildinfo +.DS_Store diff --git a/.npmrc b/.npmrc new file mode 100644 index 0000000..16d6d69 --- /dev/null +++ b/.npmrc @@ -0,0 +1,2 @@ +save-exact=true +strict-peer-dependencies=true diff --git a/.nvmrc b/.nvmrc new file mode 100644 index 0000000..e222811 --- /dev/null +++ b/.nvmrc @@ -0,0 +1 @@ +22.19.0 diff --git a/.prettierignore b/.prettierignore new file mode 100644 index 0000000..7611016 --- /dev/null +++ b/.prettierignore @@ -0,0 +1,8 @@ +node_modules +dist +.turbo +pnpm-lock.yaml +packages/database/src/generated +playwright-report +test-results +*.sql diff --git a/.prettierrc.json b/.prettierrc.json new file mode 100644 index 0000000..4926aa8 --- /dev/null +++ b/.prettierrc.json @@ -0,0 +1 @@ +{ "singleQuote": true, "trailingComma": "all", "printWidth": 100 } diff --git a/README.md b/README.md new file mode 100644 index 0000000..548e4c3 --- /dev/null +++ b/README.md @@ -0,0 +1,107 @@ +# MerchantFlow + +A local Merchant Onboarding CRM for a fictional crypto-payment provider. This milestone provides real login, database-backed browsing, role-scoped views, and a responsive English/Russian UI. Editing and workflow actions are intentionally deferred. + +## Start locally + +Prerequisites: Node **22.19+ on the 22.x line**, pnpm **10.32.1**, and Docker Desktop with its engine running. `.nvmrc` pins the verified Node version. + +```sh +nvm use +corepack enable +corepack prepare pnpm@10.32.1 --activate +cp .env.example .env +pnpm install --frozen-lockfile +pnpm db:setup +pnpm dev +``` + +Open **http://localhost:5173**. The API runs at http://localhost:3001/api; Vite forwards `/api` to it without rewriting the path. Local `localhost` and `127.0.0.1` browser URLs are both accepted. Docker runs only PostgreSQL; the two applications run on the host. + +Development PostgreSQL uses **55440**, to avoid existing local databases. The isolated test service uses **55441**. Both bind to loopback only. If a port is occupied, update the matching Compose mapping and database URL (the test URL lives in `scripts/test-database.mjs`). Frontend/API ports and the trusted browser origin can be changed in `.env`. + +`pnpm db:setup` starts PostgreSQL, applies the checked-in migration, generates/builds database code, and seeds the fixtures. Seeding is repeatable: existing fixture IDs, passwords, records and history are preserved. `pnpm db:down` stops the project services but preserves development data. + +## Demo accounts + +All four accounts use **`MerchantFlow123!`**. The login page has credential-fill buttons; sign-in still goes through the API. + +| Email | Role | Visibility | +| ------------------------------ | ----------------------------- | ------------------------------------------------- | +| `head@merchantflow.test` | Head of Sales | All 18 merchants | +| `compliance@merchantflow.test` | Compliance Officer | 4 merchants currently in KYB or Compliance Review | +| `manager1@merchantflow.test` | Account Manager · Alex Morgan | 9 assigned merchants | +| `manager2@merchantflow.test` | Account Manager · Maria Chen | 9 assigned merchants | + +Only Compliance can open the Review Queue. Scope restrictions apply to every list, detail, task, history event and aggregate; knowing a hidden merchant ID does not grant access. The API returns 404 for hidden merchant details and 403 for forbidden queue access. + +## Workspace structure + +```text +apps/web React + Vite + React Router +apps/api NestJS REST API +packages/ui shadcn/Base UI components, tokens and reusable states +packages/contracts Zod schemas, DTOs, canonical role/status codes +packages/database Prisma schema, generated client, migrations and seed +docs Product brief and implementation checklist +tests Playwright journeys +``` + +The browser depends on UI and contracts only. Database exports have a Node-only condition, and Vite fails the build if Prisma, database code or PostgreSQL drivers enter its module graph. Contracts never import Prisma types. An integration test checks that Prisma enums and contract codes agree. + +The shared UI follows [shadcn's monorepo conventions](https://ui.shadcn.com/docs/monorepo): matching `base-nova` configuration, neutral tokens, `rsc: false`, shared CSS, and package subpath exports. Components were installed using the pinned shadcn 4.21.0 CLI; imports use the shared `@merchantflow/ui/lib/utils` utility. Forms use React Hook Form and shared Zod schemas. + +API, database and contracts compile to ESM. Turbo builds dependencies before dependent apps. `pnpm dev` first compiles the API, then starts dependency watchers, the API compiler/process watcher, and Vite. Run `pnpm db:generate` after a Prisma schema edit. Add migrations with Prisma during development; `db:migrate` only applies checked-in migrations. + +## Routes and API + +Public routes are `/` and `/login`. CRM routes are `/app`, `/app/merchants`, `/app/merchants/:id`, `/app/pipeline`, `/app/tasks` and `/app/review-queue`. Browser history URLs support direct navigation and refresh through Vite. + +| Method | Endpoint | Purpose | +| ------ | --------------------------------------- | ----------------------------------------------------- | +| GET | `/api/health` | Database-aware health; 503 if unavailable | +| POST | `/api/auth/login` | Email/password login | +| POST | `/api/auth/logout` | Revoke session and clear cookie | +| GET | `/api/auth/me` | Current public user | +| GET | `/api/dashboard` | Scoped counts, distribution, activity, priority tasks | +| GET | `/api/merchants?search=&status=&page=1` | Search, canonical status filter, 8 records per page | +| GET | `/api/merchants/:id` | Overview, checklist, notes, tasks, history | +| GET | `/api/pipeline` | Scoped merchants grouped in the UI | +| GET | `/api/tasks?filter=ALL` | ALL / OPEN / OVERDUE / UPCOMING / DONE | +| GET | `/api/review-queue` | Compliance-only, oldest review first | + +Passwords are salted with scrypt. A random session token lives in an HttpOnly, SameSite=Lax cookie; only its SHA-256 digest is stored in PostgreSQL. Sessions expire after eight hours. Login/logout validate browser origins; local failed logins have a bounded rate limit. The UI clears private query caches on logout, login and API session rejection. + +## Data and localization + +The successful path is **New Lead → Contacted → Qualified → KYB → Compliance Review → Integration → Testing → Live**. **Rejected** is a separate terminal outcome. Luma Labs demonstrates a historical return from Compliance Review to KYB for corrections. + +The seed creates 18 merchants, 36 tasks, document checklists, notes and chronological history. Dates are relative to the first seed, then preserved. There are no fabricated trend percentages or payment metrics. The dashboard counts visible merchants, current review records, open overdue tasks, and non-initial status changes during the past 30 days. Its activity feed uses persisted events; counts naturally change as fixtures age. + +English is the default; EN/RU selection persists in local storage, including across sign-out. Dates and numbers use `Intl` and the viewer's local timezone. Status, role, industry and document labels are translated from canonical codes. Names, task titles and user notes remain verbatim. Checklists and tasks are read-only; reminders are derived from stored dates and refresh inside the app, without background notification infrastructure. + +## Verification + +```sh +pnpm build +pnpm lint +pnpm typecheck +pnpm test +pnpm test:integration +pnpm exec playwright install chromium +pnpm test:e2e +pnpm format:check +``` + +Unit tests cover contracts, translated resources, return URLs, scope rules and password verification. Integration tests use an isolated `merchantflow_test` database on a separate Compose service with temporary storage; they never truncate the development database. Browser tests start dedicated web/API instances on **5174/3002**, then test EN/RU at **390px/1440px**, permissions, navigation, filtering, direct refresh, focus restoration, reduced motion, and loading/error/empty states. Reports and screenshots are written to ignored `playwright-report/` and `test-results/` directories. Run integration and browser commands sequentially. + +Health smoke check while `pnpm dev` is running: + +```sh +curl --fail http://localhost:3001/api/health +curl --fail http://localhost:5173/api/health +``` + +Both should return `{"status":"ok","database":"connected"}`. If startup fails, check Docker, port availability and `.env`; do not point the tests at development data. + +The [product brief](docs/product-brief.md) and [implementation checklist](docs/implementation-checklist.md) record the accepted scope and verification results. Merchant editing, stage/review actions and task management are later milestones. Uploads, merchant self-service, payments, external KYB/reminders and deployment remain out of scope. diff --git a/apps/api/package.json b/apps/api/package.json new file mode 100644 index 0000000..c396bf2 --- /dev/null +++ b/apps/api/package.json @@ -0,0 +1,28 @@ +{ + "name": "@merchantflow/api", + "private": true, + "version": "0.0.0", + "type": "module", + "scripts": { + "dev": "node ../../scripts/dev-api.mjs", + "build": "tsc", + "typecheck": "tsc --noEmit", + "test": "node --test test/unit.test.mjs" + }, + "dependencies": { + "@merchantflow/contracts": "workspace:*", + "@merchantflow/database": "workspace:*", + "@nestjs/common": "11.2.6", + "@nestjs/core": "11.2.6", + "@nestjs/platform-express": "11.2.6", + "cookie-parser": "1.4.7", + "dotenv": "17.4.2", + "reflect-metadata": "0.2.2", + "rxjs": "7.8.2", + "zod": "4.6.5" + }, + "devDependencies": { + "@types/cookie-parser": "1.4.10", + "@types/express": "5.0.6" + } +} diff --git a/apps/api/src/access.ts b/apps/api/src/access.ts new file mode 100644 index 0000000..96b1efa --- /dev/null +++ b/apps/api/src/access.ts @@ -0,0 +1,14 @@ +import type { User } from '@merchantflow/contracts'; +import type { Prisma } from '@merchantflow/database'; +export function merchantScope(user: User): Prisma.MerchantWhereInput { + switch (user.role) { + case 'HEAD_OF_SALES': + return {}; + case 'COMPLIANCE_OFFICER': + return { status: { in: ['KYB', 'COMPLIANCE_REVIEW'] } }; + case 'ACCOUNT_MANAGER': + return { ownerId: user.id }; + default: + return { id: '__no_access__' }; + } +} diff --git a/apps/api/src/app.ts b/apps/api/src/app.ts new file mode 100644 index 0000000..14ed140 --- /dev/null +++ b/apps/api/src/app.ts @@ -0,0 +1,60 @@ +import 'reflect-metadata'; +import { + Module, + Controller, + Get, + Inject, + Injectable, + type OnApplicationShutdown, +} from '@nestjs/common'; +import { NestFactory } from '@nestjs/core'; +import cookieParser from 'cookie-parser'; +import { createDatabase, PrismaClient } from '@merchantflow/database'; +import { AuthController, AuthService, SessionGuard } from './auth.js'; +import { CrmController } from './crm.js'; +import { DATABASE, ApiError, ErrorFilter } from './shared.js'; +import { env } from './env.js'; +@Controller('health') +class HealthController { + constructor(@Inject(DATABASE) private readonly db: PrismaClient) {} + @Get() async health() { + try { + await this.db.$queryRaw`SELECT 1`; + return { status: 'ok', database: 'connected' }; + } catch { + throw new ApiError('DATABASE_UNAVAILABLE', 503); + } + } +} +@Injectable() +class DatabaseLifecycle implements OnApplicationShutdown { + constructor(@Inject(DATABASE) private readonly db: PrismaClient) {} + async onApplicationShutdown() { + await this.db.$disconnect(); + } +} +@Module({ + controllers: [HealthController, AuthController, CrmController], + providers: [ + { provide: DATABASE, useFactory: () => createDatabase(env.DATABASE_URL) }, + DatabaseLifecycle, + AuthService, + SessionGuard, + ], +}) +class AppModule {} +export async function createApp() { + const app = await NestFactory.create(AppModule, { logger: ['error', 'warn', 'log'] }); + app.setGlobalPrefix('api'); + app.use(cookieParser()); + app.use( + (_req: unknown, res: { setHeader: (key: string, value: string) => void }, next: () => void) => { + res.setHeader('Cache-Control', 'no-store'); + res.setHeader('X-Content-Type-Options', 'nosniff'); + next(); + }, + ); + app.useGlobalFilters(new ErrorFilter()); + app.enableShutdownHooks(); + return app; +} diff --git a/apps/api/src/auth.ts b/apps/api/src/auth.ts new file mode 100644 index 0000000..4a83339 --- /dev/null +++ b/apps/api/src/auth.ts @@ -0,0 +1,117 @@ +import { + Injectable, + Inject, + Controller, + Post, + Get, + Body, + Req, + Res, + UseGuards, + type CanActivate, + type ExecutionContext, +} from '@nestjs/common'; +import { createHash, randomBytes } from 'node:crypto'; +import type { Request, Response } from 'express'; +import { PrismaClient, hashPassword, verifyPassword } from '@merchantflow/database'; +import { loginSchema } from '@merchantflow/contracts'; +import { DATABASE, ApiError, type AuthRequest } from './shared.js'; +import { env } from './env.js'; +export const publicUser = { id: true, name: true, email: true, role: true } as const; +const sessionId = (token: string) => createHash('sha256').update(token).digest('hex'); +const cookieName = 'mf_session'; +const cookieOptions = { + httpOnly: true, + sameSite: 'lax' as const, + secure: env.NODE_ENV === 'production', + path: '/api', +}; +const dummyHash = hashPassword('invalid-account-placeholder'); +@Injectable() +export class AuthService { + private attempts = new Map(); + constructor(@Inject(DATABASE) private readonly db: PrismaClient) {} + async current(token: unknown) { + if (typeof token !== 'string' || !/^[a-f0-9]{64}$/.test(token)) + throw new ApiError('UNAUTHORIZED', 401); + const session = await this.db.session.findUnique({ + where: { id: sessionId(token) }, + include: { user: { select: publicUser } }, + }); + if (!session || session.expiresAt.getTime() <= Date.now()) + throw new ApiError('UNAUTHORIZED', 401); + return session.user; + } + async login(body: unknown, request: Request, response: Response) { + this.checkOrigin(request); + const input = loginSchema.parse(body); + const key = request.ip ?? 'local'; + const now = Date.now(); + for (const [ip, value] of this.attempts) if (value.until <= now) this.attempts.delete(ip); + const attempt = this.attempts.get(key) ?? { count: 0, until: now + 300000 }; + if (attempt.count >= 20) throw new ApiError('TOO_MANY_REQUESTS', 429); + attempt.count++; + this.attempts.set(key, attempt); + const user = await this.db.user.findUnique({ where: { email: input.email } }); + const valid = verifyPassword(input.password, user?.passwordHash ?? dummyHash); + if (!user || !valid) throw new ApiError('INVALID_CREDENTIALS', 401); + this.attempts.delete(key); + await this.revoke(request.cookies?.[cookieName]); + await this.db.session.deleteMany({ where: { expiresAt: { lt: new Date() } } }); + const token = randomBytes(32).toString('hex'); + await this.db.session.create({ + data: { id: sessionId(token), userId: user.id, expiresAt: new Date(now + 8 * 3600000) }, + }); + response.cookie(cookieName, token, { ...cookieOptions, maxAge: 8 * 3600000 }); + return { id: user.id, name: user.name, email: user.email, role: user.role }; + } + async revoke(token: unknown) { + if (typeof token === 'string') + await this.db.session.deleteMany({ where: { id: sessionId(token) } }); + } + checkOrigin(req: Request) { + const allowed = new Set([env.APP_ORIGIN]); + const origin = new URL(env.APP_ORIGIN); + if (env.NODE_ENV !== 'production' && ['localhost', '127.0.0.1'].includes(origin.hostname)) { + origin.hostname = origin.hostname === 'localhost' ? '127.0.0.1' : 'localhost'; + allowed.add(origin.origin); + } + if ( + (req.headers.origin && !allowed.has(req.headers.origin)) || + req.headers['sec-fetch-site'] === 'cross-site' + ) + throw new ApiError('FORBIDDEN', 403); + } + async logout(request: Request, response: Response) { + this.checkOrigin(request); + await this.revoke(request.cookies?.[cookieName]); + response.clearCookie(cookieName, cookieOptions); + } +} +@Injectable() +export class SessionGuard implements CanActivate { + constructor(private readonly auth: AuthService) {} + async canActivate(context: ExecutionContext) { + const req = context.switchToHttp().getRequest(); + req.user = await this.auth.current(req.cookies?.[cookieName]); + return true; + } +} +@Controller('auth') +export class AuthController { + constructor(private readonly auth: AuthService) {} + @Post('login') login( + @Body() body: unknown, + @Req() req: Request, + @Res({ passthrough: true }) res: Response, + ) { + return this.auth.login(body, req, res); + } + @Post('logout') async logout(@Req() req: Request, @Res({ passthrough: true }) res: Response) { + await this.auth.logout(req, res); + return { ok: true }; + } + @UseGuards(SessionGuard) @Get('me') me(@Req() req: AuthRequest) { + return req.user; + } +} diff --git a/apps/api/src/crm.ts b/apps/api/src/crm.ts new file mode 100644 index 0000000..db009e4 --- /dev/null +++ b/apps/api/src/crm.ts @@ -0,0 +1,175 @@ +import { Controller, Get, Inject, Param, Query, Req, UseGuards } from '@nestjs/common'; +import { PrismaClient, type Prisma } from '@merchantflow/database'; +import { statuses, merchantQuerySchema, taskQuerySchema } from '@merchantflow/contracts'; +import { SessionGuard } from './auth.js'; +import { DATABASE, ApiError, type AuthRequest } from './shared.js'; +import { merchantScope } from './access.js'; +const merchantSelect = { + id: true, + name: true, + website: true, + industry: true, + country: true, + contactName: true, + contactEmail: true, + status: true, + createdAt: true, + stageEnteredAt: true, + owner: { select: { id: true, name: true } }, +} as const; +const eventSelect = { + id: true, + fromStatus: true, + toStatus: true, + occurredAt: true, + note: true, + merchant: { select: { id: true, name: true } }, + actor: { select: { name: true } }, +} as const; +const taskSelect = { + id: true, + title: true, + status: true, + dueAt: true, + remindAt: true, + completedAt: true, + merchant: { select: { id: true, name: true } }, + assignee: { select: { name: true } }, +} as const; +@UseGuards(SessionGuard) +@Controller() +export class CrmController { + constructor(@Inject(DATABASE) private readonly db: PrismaClient) {} + @Get('merchants') async merchants(@Req() req: AuthRequest, @Query() query: unknown) { + const { page, search, status } = merchantQuerySchema.parse(query); + const where: Prisma.MerchantWhereInput = { + AND: [ + merchantScope(req.user), + ...(status ? [{ status }] : []), + ...(search + ? [ + { + OR: [ + { name: { contains: search, mode: 'insensitive' as const } }, + { contactEmail: { contains: search, mode: 'insensitive' as const } }, + ], + }, + ] + : []), + ], + }; + const [items, total] = await this.db.$transaction([ + this.db.merchant.findMany({ + where, + select: merchantSelect, + orderBy: [{ createdAt: 'desc' }, { id: 'asc' }], + take: 8, + skip: (page - 1) * 8, + }), + this.db.merchant.count({ where }), + ]); + return { items, total, page, pageSize: 8 }; + } + @Get('merchants/:id') async detail(@Req() req: AuthRequest, @Param('id') id: string) { + const merchant = await this.db.merchant.findFirst({ + where: { AND: [merchantScope(req.user), { id }] }, + select: { + ...merchantSelect, + checklist: { + select: { id: true, documentCode: true, state: true, note: true }, + orderBy: { documentCode: 'asc' }, + }, + notes: { + select: { id: true, text: true, createdAt: true, author: { select: { name: true } } }, + orderBy: { createdAt: 'desc' }, + }, + events: { select: eventSelect, orderBy: { occurredAt: 'desc' } }, + tasks: { select: taskSelect, orderBy: { dueAt: 'asc' } }, + }, + }); + if (!merchant) throw new ApiError('NOT_FOUND', 404); + return merchant; + } + @Get('pipeline') pipeline(@Req() req: AuthRequest) { + return this.db.merchant.findMany({ + where: merchantScope(req.user), + select: merchantSelect, + orderBy: { stageEnteredAt: 'asc' }, + }); + } + @Get('tasks') tasks(@Req() req: AuthRequest, @Query() query: unknown) { + const { filter } = taskQuerySchema.parse(query); + const where: Prisma.TaskWhereInput = { merchant: merchantScope(req.user) }; + if (filter === 'DONE') where.status = 'DONE'; + if (['OPEN', 'OVERDUE', 'UPCOMING'].includes(filter)) where.status = 'OPEN'; + if (filter === 'OVERDUE') where.dueAt = { lt: new Date() }; + if (filter === 'UPCOMING') where.dueAt = { gte: new Date() }; + return this.db.task.findMany({ + where, + select: taskSelect, + orderBy: [{ status: 'asc' }, { dueAt: 'asc' }], + }); + } + @Get('review-queue') reviewQueue(@Req() req: AuthRequest) { + if (req.user.role !== 'COMPLIANCE_OFFICER') throw new ApiError('FORBIDDEN', 403); + return this.db.merchant.findMany({ + where: { AND: [merchantScope(req.user), { status: 'COMPLIANCE_REVIEW' }] }, + select: merchantSelect, + orderBy: [{ stageEnteredAt: 'asc' }, { id: 'asc' }], + }); + } + @Get('dashboard') async dashboard(@Req() req: AuthRequest) { + const scope = merchantScope(req.user); + const distributionQuery = this.db.merchant.groupBy({ + by: ['status'], + orderBy: { status: 'asc' }, + where: scope, + _count: { _all: true }, + }); + const [ + merchantCount, + reviewCount, + overdueTasks, + transitionsLast30Days, + distribution, + recentEvents, + upcomingTasks, + ] = await this.db.$transaction([ + this.db.merchant.count({ where: scope }), + this.db.merchant.count({ where: { AND: [scope, { status: 'COMPLIANCE_REVIEW' }] } }), + this.db.task.count({ where: { merchant: scope, status: 'OPEN', dueAt: { lt: new Date() } } }), + this.db.statusEvent.count({ + where: { + merchant: scope, + fromStatus: { not: null }, + occurredAt: { gte: new Date(Date.now() - 30 * 86400000) }, + }, + }), + distributionQuery, + this.db.statusEvent.findMany({ + where: { merchant: scope }, + select: eventSelect, + orderBy: [{ occurredAt: 'desc' }, { id: 'asc' }], + take: 6, + }), + this.db.task.findMany({ + where: { merchant: scope, status: 'OPEN' }, + select: taskSelect, + orderBy: { dueAt: 'asc' }, + take: 4, + }), + ]); + return { + merchantCount, + reviewCount, + overdueTasks, + transitionsLast30Days, + distribution: statuses.map((status) => ({ + status, + count: distribution.find((d) => d.status === status)?._count._all ?? 0, + })), + recentEvents, + upcomingTasks, + }; + } +} diff --git a/apps/api/src/env.ts b/apps/api/src/env.ts new file mode 100644 index 0000000..92ac7e3 --- /dev/null +++ b/apps/api/src/env.ts @@ -0,0 +1,13 @@ +import { config } from 'dotenv'; +import { z } from 'zod'; +config({ path: new URL('../../../.env', import.meta.url).pathname, quiet: true }); +export const env = z + .object({ + DATABASE_URL: z + .url() + .default('postgresql://merchantflow:merchantflow_local@localhost:55440/merchantflow'), + API_PORT: z.coerce.number().default(3001), + APP_ORIGIN: z.url().default('http://localhost:5173'), + NODE_ENV: z.string().default('development'), + }) + .parse(process.env); diff --git a/apps/api/src/main.ts b/apps/api/src/main.ts new file mode 100644 index 0000000..03b6e48 --- /dev/null +++ b/apps/api/src/main.ts @@ -0,0 +1,5 @@ +import { createApp } from './app.js'; +import { env } from './env.js'; +const app = await createApp(); +await app.listen(env.API_PORT, '127.0.0.1'); +console.log(`MerchantFlow API: http://localhost:${env.API_PORT}/api/health`); diff --git a/apps/api/src/shared.ts b/apps/api/src/shared.ts new file mode 100644 index 0000000..b269ee9 --- /dev/null +++ b/apps/api/src/shared.ts @@ -0,0 +1,42 @@ +import { Catch, HttpException, type ExceptionFilter, type ArgumentsHost } from '@nestjs/common'; +import type { Request, Response } from 'express'; +import type { User } from '@merchantflow/contracts'; +import { ZodError } from 'zod'; +export const DATABASE = Symbol('DATABASE'); +export interface AuthRequest extends Request { + user: User; +} +export class ApiError extends HttpException { + constructor(code: string, status: number) { + super({ code }, status); + } +} +@Catch() +export class ErrorFilter implements ExceptionFilter { + catch(error: unknown, host: ArgumentsHost) { + const response = host.switchToHttp().getResponse(); + if (error instanceof ZodError) { + response.status(400).json({ + code: 'VALIDATION_ERROR', + issues: error.issues.map((i) => ({ + path: i.path.join('.'), + code: i.message.startsWith('validation.') ? i.message : 'validation.invalid', + })), + }); + return; + } + if (error instanceof ApiError) { + response.status(error.getStatus()).json(error.getResponse()); + return; + } + if (error instanceof HttpException) { + const status = error.getStatus(); + response.status(status).json({ + code: status === 404 ? 'NOT_FOUND' : status === 400 ? 'VALIDATION_ERROR' : 'INTERNAL_ERROR', + }); + return; + } + console.error('API request failed', error instanceof Error ? error.message : 'Unknown error'); + response.status(500).json({ code: 'INTERNAL_ERROR' }); + } +} diff --git a/apps/api/test/integration.test.mjs b/apps/api/test/integration.test.mjs new file mode 100644 index 0000000..cfb47a1 --- /dev/null +++ b/apps/api/test/integration.test.mjs @@ -0,0 +1,232 @@ +import { before, after, test } from 'node:test'; +import assert from 'node:assert/strict'; +import { createHash } from 'node:crypto'; +import { spawnSync } from 'node:child_process'; +import { createDatabase } from '@merchantflow/database'; +import { roles, statuses, documentCodes } from '@merchantflow/contracts'; +import { + Role, + MerchantStatus, + DocumentCode, +} from '../../../packages/database/dist/generated/prisma/enums.js'; +if (!process.env.DATABASE_URL?.endsWith('/merchantflow_test')) + throw new Error('Integration tests require the isolated merchantflow_test database'); +const db = createDatabase(process.env.DATABASE_URL); +let app, base; +const cookies = {}; +async function request(path, cookie, options = {}) { + const response = await fetch(`${base}${path}`, { + ...options, + headers: { + ...(cookie ? { cookie } : {}), + ...(options.body ? { 'content-type': 'application/json' } : {}), + ...options.headers, + }, + }); + return { status: response.status, body: await response.json(), response }; +} +async function login(account, password = 'MerchantFlow123!') { + return request('/auth/login', null, { + method: 'POST', + body: JSON.stringify({ email: `${account}@merchantflow.test`, password }), + }); +} +before(async () => { + const { createApp } = await import('../dist/app.js'); + app = await createApp(); + await app.listen(0, '127.0.0.1'); + base = (await app.getUrl()) + '/api'; + for (const account of ['head', 'compliance', 'manager1', 'manager2']) { + const r = await login(account); + assert.equal(r.status, 201); + cookies[account] = r.response.headers.get('set-cookie').split(';')[0]; + } +}); +after(async () => { + await app?.close(); + await db.$disconnect(); +}); +test('Prisma and browser contracts agree on canonical codes', () => { + assert.deepEqual(Object.values(Role), [...roles]); + assert.deepEqual(Object.values(MerchantStatus), [...statuses]); + assert.deepEqual(Object.values(DocumentCode), [...documentCodes]); +}); +test('health checks the database and every CRM endpoint requires a session', async () => { + assert.deepEqual((await request('/health')).body, { status: 'ok', database: 'connected' }); + for (const path of [ + '/auth/me', + '/dashboard', + '/merchants', + '/merchants/merchant-01', + '/pipeline', + '/tasks', + '/review-queue', + ]) + assert.equal((await request(path)).status, 401, path); +}); +test('login validates, sets protected cookies, and rejects incorrect credentials and cross-origin writes', async () => { + assert.equal((await login('head', 'incorrect')).status, 401); + const invalid = await request('/auth/login', null, { + method: 'POST', + body: '{"email":"wrong","password":""}', + }); + assert.equal(invalid.status, 400); + assert.equal(invalid.body.code, 'VALIDATION_ERROR'); + const r = await login('head'); + const cookie = r.response.headers.get('set-cookie'); + assert.match(cookie, /HttpOnly/i); + assert.match(cookie, /SameSite=Lax/i); + assert.match(cookie, /Path=\/api/i); + assert.equal( + ( + await request('/auth/logout', cookies.head, { + method: 'POST', + headers: { origin: 'https://untrusted.example' }, + }) + ).status, + 403, + ); +}); +for (const [account, total] of [ + ['head', 18], + ['manager1', 9], + ['manager2', 9], + ['compliance', 4], +]) + test(`${account}: all reads, details, history, tasks and metrics respect the scope`, async () => { + const cookie = cookies[account]; + const expected = (await db.merchant.findMany()).filter((m) => + account === 'head' || account === 'compliance' + ? account === 'head' || ['KYB', 'COMPLIANCE_REVIEW'].includes(m.status) + : m.ownerId === `user-${account}`, + ); + assert.equal(expected.length, total); + const ids = expected.map((m) => m.id); + const list = await request('/merchants', cookie); + assert.equal(list.status, 200); + assert.equal(list.body.total, total); + assert.ok(list.body.items.every((m) => ids.includes(m.id))); + assert.equal(list.body.items.length, Math.min(total, 8)); + if (total > 8) { + const second = await request('/merchants?page=2', cookie); + assert.ok(second.body.items.length > 0); + assert.ok( + second.body.items.every((m) => !list.body.items.some((first) => first.id === m.id)), + ); + } + const pipeline = (await request('/pipeline', cookie)).body; + assert.deepEqual(pipeline.map((m) => m.id).sort(), [...ids].sort()); + const tasks = (await request('/tasks', cookie)).body; + assert.equal(tasks.length, total * 2); + assert.ok(tasks.every((t) => ids.includes(t.merchant.id))); + for (const m of expected) { + const detail = (await request(`/merchants/${m.id}`, cookie)).body; + assert.equal(detail.id, m.id); + assert.equal(detail.checklist.length, 4); + assert.ok(detail.events.every((e) => e.merchant.id === m.id)); + assert.ok(detail.tasks.every((t) => t.merchant.id === m.id)); + assert.ok(!JSON.stringify(detail).includes('passwordHash')); + } + const dashboard = (await request('/dashboard', cookie)).body; + assert.equal(dashboard.merchantCount, total); + assert.equal( + dashboard.reviewCount, + expected.filter((m) => m.status === 'COMPLIANCE_REVIEW').length, + ); + assert.equal( + dashboard.overdueTasks, + await db.task.count({ + where: { merchantId: { in: ids }, status: 'OPEN', dueAt: { lt: new Date() } }, + }), + ); + assert.equal( + dashboard.transitionsLast30Days, + await db.statusEvent.count({ + where: { + merchantId: { in: ids }, + fromStatus: { not: null }, + occurredAt: { gte: new Date(Date.now() - 30 * 86400000) }, + }, + }), + ); + assert.equal( + dashboard.distribution.reduce((sum, x) => sum + x.count, 0), + total, + ); + assert.ok(dashboard.recentEvents.every((e) => ids.includes(e.merchant.id))); + assert.ok(dashboard.upcomingTasks.every((t) => ids.includes(t.merchant.id))); + const hidden = (await db.merchant.findMany()).find((m) => !ids.includes(m.id)); + if (hidden) { + assert.equal((await request(`/merchants/${hidden.id}`, cookie)).status, 404); + assert.equal( + (await request(`/merchants?search=${encodeURIComponent(hidden.name)}`, cookie)).body.total, + 0, + ); + } + assert.equal( + (await request('/review-queue', cookie)).status, + account === 'compliance' ? 200 : 403, + ); + }); +test('filters are validated and review queue is oldest first', async () => { + const cookie = cookies.head; + for (const query of ['page=-1', 'status=Live', 'page=1.5']) + assert.equal((await request(`/merchants?${query}`, cookie)).status, 400); + assert.equal((await request('/tasks?filter=invalid', cookie)).status, 400); + const live = (await request('/merchants?status=LIVE', cookie)).body; + assert.equal(live.total, 2); + const done = (await request('/tasks?filter=DONE', cookie)).body; + assert.ok(done.every((t) => t.status === 'DONE')); + const overdue = (await request('/tasks?filter=OVERDUE', cookie)).body; + assert.ok(overdue.every((t) => t.status === 'OPEN' && new Date(t.dueAt) < new Date())); + const queue = (await request('/review-queue', cookies.compliance)).body; + assert.equal(queue.length, 2); + assert.ok(queue.every((m) => m.status === 'COMPLIANCE_REVIEW')); + assert.ok(new Date(queue[0].stageEnteredAt) <= new Date(queue[1].stageEnteredAt)); +}); +test('seed is repeatable without modifying records; history includes correction and terminal outcomes', async () => { + const snapshot = await db.merchant.findMany({ + orderBy: { id: 'asc' }, + include: { events: { orderBy: { id: 'asc' } } }, + }); + const result = spawnSync('pnpm', ['--filter', '@merchantflow/database', 'seed'], { + env: process.env, + encoding: 'utf8', + }); + assert.equal(result.status, 0, result.stderr); + assert.equal(await db.user.count(), 4); + assert.equal(await db.merchant.count(), 18); + assert.deepEqual( + await db.merchant.findMany({ + orderBy: { id: 'asc' }, + include: { events: { orderBy: { id: 'asc' } } }, + }), + snapshot, + ); + assert.ok( + snapshot.some((m) => + m.events.some((e) => e.fromStatus === 'COMPLIANCE_REVIEW' && e.toStatus === 'KYB'), + ), + ); + assert.ok(!snapshot.some((m) => m.events.some((e) => e.fromStatus === 'LIVE'))); +}); +test('expired, logged-out and replaced sessions cannot be reused', async () => { + const r = await login('manager1'); + const cookie = r.response.headers.get('set-cookie').split(';')[0]; + const token = cookie.split('=')[1]; + await db.session.update({ + where: { id: createHash('sha256').update(token).digest('hex') }, + data: { expiresAt: new Date(0) }, + }); + assert.equal((await request('/auth/me', cookie)).status, 401); + const fresh = await login('manager1'); + const freshCookie = fresh.response.headers.get('set-cookie').split(';')[0]; + assert.equal((await request('/auth/logout', freshCookie, { method: 'POST' })).status, 201); + assert.equal((await request('/pipeline', freshCookie)).status, 401); + const replacement = await request('/auth/login', cookies.manager2, { + method: 'POST', + body: JSON.stringify({ email: 'head@merchantflow.test', password: 'MerchantFlow123!' }), + }); + assert.equal(replacement.status, 201); + assert.equal((await request('/auth/me', cookies.manager2)).status, 401); +}); diff --git a/apps/api/test/unit.test.mjs b/apps/api/test/unit.test.mjs new file mode 100644 index 0000000..e7c4838 --- /dev/null +++ b/apps/api/test/unit.test.mjs @@ -0,0 +1,21 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { merchantScope } from '../dist/access.js'; +import { hashPassword, verifyPassword } from '@merchantflow/database'; +test('passwords use distinct salts and reject incorrect values', () => { + const hash = hashPassword('example-password'); + assert.notEqual(hash, hashPassword('example-password')); + assert.equal(verifyPassword('example-password', hash), true); + assert.equal(verifyPassword('wrong', hash), false); + assert.equal(verifyPassword('wrong', 'broken'), false); +}); +test('every role receives its exact merchant scope', () => { + assert.deepEqual(merchantScope({ role: 'HEAD_OF_SALES' }), {}); + assert.deepEqual(merchantScope({ role: 'ACCOUNT_MANAGER', id: 'manager-1' }), { + ownerId: 'manager-1', + }); + assert.deepEqual(merchantScope({ role: 'COMPLIANCE_OFFICER' }), { + status: { in: ['KYB', 'COMPLIANCE_REVIEW'] }, + }); + assert.deepEqual(merchantScope({ role: 'unexpected' }), { id: '__no_access__' }); +}); diff --git a/apps/api/tsconfig.json b/apps/api/tsconfig.json new file mode 100644 index 0000000..4f40047 --- /dev/null +++ b/apps/api/tsconfig.json @@ -0,0 +1,13 @@ +{ + "extends": "../../tsconfig.base.json", + "compilerOptions": { + "module": "NodeNext", + "moduleResolution": "NodeNext", + "rootDir": "src", + "outDir": "dist", + "experimentalDecorators": true, + "emitDecoratorMetadata": true, + "sourceMap": true + }, + "include": ["src"] +} diff --git a/apps/web/components.json b/apps/web/components.json new file mode 100644 index 0000000..0b50a2d --- /dev/null +++ b/apps/web/components.json @@ -0,0 +1,20 @@ +{ + "$schema": "https://ui.shadcn.com/schema.json", + "style": "base-nova", + "rsc": false, + "tsx": true, + "tailwind": { + "config": "", + "css": "../../packages/ui/src/styles/globals.css", + "baseColor": "neutral", + "cssVariables": true + }, + "iconLibrary": "lucide", + "aliases": { + "components": "@/components", + "hooks": "@/hooks", + "lib": "@/lib", + "utils": "@merchantflow/ui/lib/utils", + "ui": "@merchantflow/ui/components" + } +} diff --git a/apps/web/index.html b/apps/web/index.html new file mode 100644 index 0000000..ca08d60 --- /dev/null +++ b/apps/web/index.html @@ -0,0 +1,18 @@ + + + + + + + + + MerchantFlow — Merchant onboarding, in flow + + +
+ + + diff --git a/apps/web/package.json b/apps/web/package.json new file mode 100644 index 0000000..5aa857e --- /dev/null +++ b/apps/web/package.json @@ -0,0 +1,34 @@ +{ + "name": "@merchantflow/web", + "private": true, + "version": "0.0.0", + "type": "module", + "scripts": { + "dev": "vite --host 127.0.0.1", + "build": "tsc --noEmit && vite build", + "typecheck": "tsc --noEmit", + "test": "vitest run" + }, + "dependencies": { + "@merchantflow/contracts": "workspace:*", + "@merchantflow/ui": "workspace:*", + "@hookform/resolvers": "5.9.1", + "@tanstack/react-query": "5.103.2", + "i18next": "25.10.10", + "lucide-react": "1.48.0", + "react": "19.3.0", + "react-dom": "19.3.0", + "react-hook-form": "7.88.0", + "react-i18next": "16.6.6", + "react-router": "7.18.4", + "zod": "4.6.5" + }, + "devDependencies": { + "@tailwindcss/vite": "4.3.3", + "@types/react": "19.3.0", + "@types/react-dom": "19.3.0", + "@vitejs/plugin-react": "4.7.0", + "tailwindcss": "4.3.3", + "vite": "7.3.6" + } +} diff --git a/apps/web/public/favicon.svg b/apps/web/public/favicon.svg new file mode 100644 index 0000000..0bdbfe3 --- /dev/null +++ b/apps/web/public/favicon.svg @@ -0,0 +1 @@ + diff --git a/apps/web/src/components/shared.tsx b/apps/web/src/components/shared.tsx new file mode 100644 index 0000000..c2a4755 --- /dev/null +++ b/apps/web/src/components/shared.tsx @@ -0,0 +1,356 @@ +import { useEffect, type ReactNode } from 'react'; +import { Link } from 'react-router'; +import { useTranslation } from 'react-i18next'; +import type { UseQueryResult } from '@tanstack/react-query'; +import { + ArrowDownRight, + ArrowUpRight, + Bell, + Check, + Circle, + Clock3, + MoveUpRight, +} from 'lucide-react'; +import type { Status, Merchant, Task, StageEvent } from '@merchantflow/contracts'; +import { Badge } from '@merchantflow/ui/components/badge'; +import { Button, buttonVariants } from '@merchantflow/ui/components/button'; +import { LoadingState, EmptyState, ErrorState } from '@merchantflow/ui/components/states'; +import { cn } from '@merchantflow/ui/lib/utils'; +import { ApiError } from '../lib/api'; +import { useFormat } from '../lib/format'; +export function Brand({ compact = false }: { compact?: boolean }) { + return ( + + + {!compact && ( + + merchantflow. + + )} + + ); +} +export function LanguageSwitch() { + const { t, i18n } = useTranslation(); + return ( +
+ {['en', 'ru'].map((l) => ( + + ))} +
+ ); +} +export function LinkButton({ + to, + children, + variant = 'default', + className, +}: { + to: string; + children: ReactNode; + variant?: 'default' | 'outline' | 'ghost'; + className?: string; +}) { + return ( + + {children} + + ); +} +export function PageHeader({ + title, + description, + eyebrow, + action, +}: { + title: string; + description: string; + eyebrow?: string; + action?: ReactNode; +}) { + useEffect(() => { + document.title = `${title} · MerchantFlow`; + }, [title]); + return ( +
+
+ {eyebrow &&

{eyebrow}

} +

{title}

+

+ {description} +

+
+ {action &&
{action}
} +
+ ); +} +export function SectionHeader({ + title, + description, + action, +}: { + title: string; + description?: string; + action?: ReactNode; +}) { + return ( +
+
+

{title}

+ {description && ( +

{description}

+ )} +
+ {action} +
+ ); +} +export const statusStyles: Record = { + NEW_LEAD: 'bg-slate-100 text-slate-700', + CONTACTED: 'bg-blue-50 text-blue-800', + QUALIFIED: 'bg-indigo-50 text-indigo-800', + KYB: 'bg-amber-50 text-amber-800', + COMPLIANCE_REVIEW: 'bg-orange-50 text-orange-800', + INTEGRATION: 'bg-violet-50 text-violet-800', + TESTING: 'bg-teal-50 text-teal-800', + LIVE: 'bg-[#edf5da] text-[#46641d]', + REJECTED: 'bg-rose-50 text-rose-800', +}; +export const stageColors: Record = { + NEW_LEAD: '#aebbb0', + CONTACTED: '#8ba5ce', + QUALIFIED: '#9e9bc9', + KYB: '#ddbd78', + COMPLIANCE_REVIEW: '#dba879', + INTEGRATION: '#b49acf', + TESTING: '#8ebcb0', + LIVE: '#a6c65e', + REJECTED: '#cf969e', +}; +export function StatusBadge({ status }: { status: Status }) { + const { t } = useTranslation(); + return ( + + + ); +} +export function Avatar({ name, small = false }: { name: string; small?: boolean }) { + const sum = [...name].reduce((a, c) => a + c.charCodeAt(0), 0); + return ( + + ); +} +export function QueryBoundary({ + query, + children, +}: { + query: UseQueryResult; + children: (data: T) => ReactNode; +}) { + const { t } = useTranslation(); + if (query.isPending) return ; + if (query.isError) + return ( + void query.refetch()} + /> + ); + return <>{children(query.data)}; +} +export function MerchantCard({ merchant }: { merchant: Merchant }) { + const { t } = useTranslation(); + const f = useFormat(); + return ( + +
+ +
+

{merchant.name}

+

+ {t(`industry.${merchant.industry}`)} +

+
+
+
+ {merchant.owner.name.split(' ')[0]} + + +
+ + ); +} +export function TaskRow({ task, compact = false }: { task: Task; compact?: boolean }) { + const { t } = useTranslation(); + const f = useFormat(); + const done = task.status === 'DONE'; + const overdue = !done && new Date(task.dueAt).getTime() < Date.now(); + return ( +
+
+ {done ? ( + + ) : ( +
+
+

+ {task.title} +

+
+ + {task.merchant.name} + + + + {done ? t('tasks.completed') : t('tasks.due', { date: f.shortDate(task.dueAt) })} + {overdue && ` · ${t('tasks.OVERDUE')}`} + +
+ {!compact && ( +
+ {t('tasks.assigned', { name: task.assignee.name })} + {!done && task.remindAt && ( + + + )} +
+ )} +
+
+ ); +} +export function ActivityFeed({ + events, + detail = false, +}: { + events: StageEvent[]; + detail?: boolean; +}) { + const { t } = useTranslation(); + const f = useFormat(); + if (!events.length) return ; + return ( +
+ {events.map((event, i) => ( +
+ {i < events.length - 1 && ( + + ))} +
+ ); +} +export { Button, EmptyState }; diff --git a/apps/web/src/components/shell.tsx b/apps/web/src/components/shell.tsx new file mode 100644 index 0000000..1f587ea --- /dev/null +++ b/apps/web/src/components/shell.tsx @@ -0,0 +1,215 @@ +import { useState, useEffect } from 'react'; +import { NavLink, Navigate, Outlet, useLocation, useNavigate } from 'react-router'; +import { useQuery, useMutation } from '@tanstack/react-query'; +import { useTranslation } from 'react-i18next'; +import { + LayoutDashboard, + Building2, + Columns3, + ListTodo, + ShieldCheck, + LogOut, + Menu, + ChevronRight, + ArrowUpRight, +} from 'lucide-react'; +import { z } from 'zod'; +import { canSeeReviewQueue, type User } from '@merchantflow/contracts'; +import { + Sheet, + SheetContent, + SheetTitle, + SheetDescription, +} from '@merchantflow/ui/components/sheet'; +import { cn } from '@merchantflow/ui/lib/utils'; +import { Brand, LanguageSwitch, Button, QueryBoundary, Avatar } from './shared'; +import { api, queryClient, sessionOptions, ApiError } from '../lib/api'; +import { useFormat } from '../lib/format'; +const navigation = [ + { key: 'dashboard', to: '/app', Icon: LayoutDashboard }, + { key: 'merchants', to: '/app/merchants', Icon: Building2 }, + { key: 'pipeline', to: '/app/pipeline', Icon: Columns3 }, + { key: 'tasks', to: '/app/tasks', Icon: ListTodo }, + { key: 'review', to: '/app/review-queue', Icon: ShieldCheck }, +]; +function Sidebar({ user, onNavigate }: { user: User; onNavigate?: () => void }) { + const { t } = useTranslation(); + const navigate = useNavigate(); + const logout = useMutation({ + mutationFn: () => api('/auth/logout', z.object({ ok: z.boolean() }), { method: 'POST' }), + onSuccess: async () => { + await queryClient.cancelQueries(); + queryClient.clear(); + queryClient.setQueryData(['session'], null); + navigate('/login', { replace: true }); + }, + }); + return ( +
+
+ +
+
+
+
+
+

{t('common.team')}

+

MerchantFlow CRM

+
+
+

{t('common.workspace')}

+ +
+
+
+
+

{t('common.brandTag')}

+
+ {logout.isError && ( +

+ {t(`errors.${logout.error instanceof ApiError ? logout.error.code : 'NETWORK'}`)} +

+ )} +
+ +
+

{user.name}

+

+ {t(`roles.${user.role}`)} +

+
+ +
+
+
+ ); +} +function AuthenticatedShell({ user }: { user: User }) { + const [open, setOpen] = useState(false); + const location = useLocation(); + const { t } = useTranslation(); + const f = useFormat(); + const active = + navigation.find((n) => n.to !== '/app' && location.pathname.startsWith(n.to)) ?? navigation[0]!; + useEffect(() => { + window.scrollTo(0, 0); + }, [location.pathname]); + return ( +
+ + {t('common.skip')} + + + + + {t('common.workspace')} + {t('common.team')} + setOpen(false)} /> + + +
+
+
+ + + {t('common.workspace')} + +
+
+ + {f.date(new Date())} + + +
+
+
+ +
+
+ + MerchantFlow / {t('common.local')} + + + {t( + `dashboard.${user.role === 'HEAD_OF_SALES' ? 'scopeHead' : user.role === 'COMPLIANCE_OFFICER' ? 'scopeCompliance' : 'scopeManager'}`, + )} + +
+
+
+ ); +} +export function ProtectedShell() { + const query = useQuery(sessionOptions); + const location = useLocation(); + return ( + + {(user) => + user ? ( + + ) : ( + + ) + } + + ); +} diff --git a/apps/web/src/i18n.ts b/apps/web/src/i18n.ts new file mode 100644 index 0000000..10296dd --- /dev/null +++ b/apps/web/src/i18n.ts @@ -0,0 +1,25 @@ +import i18n from 'i18next'; +import { initReactI18next } from 'react-i18next'; +import { en, ru } from './locales'; +let saved: string | null = null; +try { + saved = localStorage.getItem('merchantflow.language'); +} catch { + /* Storage can be unavailable in private contexts. */ +} +void i18n.use(initReactI18next).init({ + resources: { en: { translation: en }, ru: { translation: ru } }, + lng: saved === 'ru' ? 'ru' : 'en', + fallbackLng: 'en', + interpolation: { escapeValue: false }, +}); +document.documentElement.lang = i18n.language; +i18n.on('languageChanged', (language) => { + document.documentElement.lang = language; + try { + localStorage.setItem('merchantflow.language', language); + } catch { + /* Keep the current session usable without storage. */ + } +}); +export default i18n; diff --git a/apps/web/src/lib/api.ts b/apps/web/src/lib/api.ts new file mode 100644 index 0000000..f0f8683 --- /dev/null +++ b/apps/web/src/lib/api.ts @@ -0,0 +1,73 @@ +import { QueryClient } from '@tanstack/react-query'; +import { z } from 'zod'; +import { userSchema } from '@merchantflow/contracts'; +export class ApiError extends Error { + constructor( + public code: string, + public status = 0, + ) { + super(code); + } +} +export const queryClient = new QueryClient({ + defaultOptions: { + queries: { + staleTime: 30000, + retry: (count, error) => + !(error instanceof ApiError && [401, 403, 404].includes(error.status)) && count < 1, + refetchOnWindowFocus: true, + }, + }, +}); +export async function api( + path: string, + schema: z.ZodType, + options: RequestInit = {}, +): Promise { + let response: Response; + try { + response = await fetch(`/api${path}`, { + credentials: 'same-origin', + ...options, + headers: { + ...(options.body ? { 'Content-Type': 'application/json' } : {}), + ...options.headers, + }, + }); + } catch (error) { + if (error instanceof Error && error.name === 'AbortError') throw error; + throw new ApiError('NETWORK'); + } + if (!response.ok) { + const body = await response.json().catch(() => ({})); + if (response.status === 401 && !path.startsWith('/auth/')) { + await queryClient.cancelQueries(); + queryClient.clear(); + queryClient.setQueryData(['session'], null); + } + throw new ApiError( + typeof body.code === 'string' ? body.code : 'INTERNAL_ERROR', + response.status, + ); + } + const result = schema.safeParse(await response.json()); + if (!result.success) throw new ApiError('RESPONSE'); + return result.data; +} +export const sessionOptions = { + queryKey: ['session'], + queryFn: async ({ signal }: { signal: AbortSignal }) => { + try { + return await api('/auth/me', userSchema, { signal }); + } catch (error) { + if (error instanceof ApiError && error.status === 401) return null; + throw error; + } + }, + retry: false, +}; +export function safeReturnTo(value: unknown) { + return typeof value === 'string' && /^\/app(?:[/?#]|$)/.test(value) && !value.includes('\\') + ? value + : '/app'; +} diff --git a/apps/web/src/lib/format.ts b/apps/web/src/lib/format.ts new file mode 100644 index 0000000..a60dd2a --- /dev/null +++ b/apps/web/src/lib/format.ts @@ -0,0 +1,22 @@ +import { useTranslation } from 'react-i18next'; +export function useFormat() { + const { i18n } = useTranslation(); + const locale = i18n.language === 'ru' ? 'ru-RU' : 'en-GB'; + return { + date: (value: string | Date) => + new Intl.DateTimeFormat(locale, { day: 'numeric', month: 'short', year: 'numeric' }).format( + new Date(value), + ), + shortDate: (value: string | Date) => + new Intl.DateTimeFormat(locale, { day: 'numeric', month: 'short' }).format(new Date(value)), + number: (value: number) => new Intl.NumberFormat(locale).format(value), + country: (code: string) => new Intl.DisplayNames([locale], { type: 'region' }).of(code), + relative: (value: string) => { + const hours = Math.round((new Date(value).getTime() - Date.now()) / 3600000); + return new Intl.RelativeTimeFormat(locale, { numeric: 'auto' }).format( + Math.abs(hours) >= 24 ? Math.round(hours / 24) : hours, + Math.abs(hours) >= 24 ? 'day' : 'hour', + ); + }, + }; +} diff --git a/apps/web/src/locales.test.ts b/apps/web/src/locales.test.ts new file mode 100644 index 0000000..594a495 --- /dev/null +++ b/apps/web/src/locales.test.ts @@ -0,0 +1,24 @@ +import { expect, it } from 'vitest'; +import { en, ru } from './locales'; +import { safeReturnTo } from './lib/api'; +function keys(value: object, prefix = ''): string[] { + return Object.entries(value) + .flatMap(([key, child]) => + typeof child === 'object' ? keys(child, `${prefix}${key}.`) : [`${prefix}${key}`], + ) + .filter((key) => !/_(few|many)$/.test(key)) + .sort(); +} +it('has matching EN/RU keys and interpolation variables', () => { + expect(keys(en)).toEqual(keys(ru)); + for (const key of keys(en)) { + const get = (obj: object) => + key.split('.').reduce((v, k) => (v as Record)[k], obj) as string; + expect(get(en).match(/{{\w+}}/g)).toEqual(get(ru).match(/{{\w+}}/g)); + } +}); +it('only accepts internal CRM return paths', () => { + expect(safeReturnTo('/app/merchants/merchant-01?x=1')).toBe('/app/merchants/merchant-01?x=1'); + for (const unsafe of ['https://example.com', '//example.com', '/application', '/app\\evil', null]) + expect(safeReturnTo(unsafe)).toBe('/app'); +}); diff --git a/apps/web/src/locales.ts b/apps/web/src/locales.ts new file mode 100644 index 0000000..b36721b --- /dev/null +++ b/apps/web/src/locales.ts @@ -0,0 +1,474 @@ +export const en = { + common: { + workspace: 'Workspace', + team: 'Merchant workspace', + close: 'Close', + back: 'Back', + retry: 'Try again', + loading: 'Loading your workspace…', + errorTitle: 'Something interrupted the flow', + emptyTitle: 'Nothing here just yet', + emptyText: 'Records will appear here when they match this view.', + noResults: 'No merchants found', + noResultsText: 'Try a different name or clear your filters.', + clear: 'Clear filters', + viewAll: 'View all', + viewMerchant: 'View merchant', + previous: 'Previous', + next: 'Next', + page: 'Page {{page}} of {{total}}', + showing: '{{from}}–{{to}} of {{total}} merchants', + all: 'All', + language: 'Language', + logout: 'Sign out', + openMenu: 'Open navigation', + skip: 'Skip to content', + notFound: 'This page is off the map', + notFoundText: 'The page may have moved, or you may not have access to it.', + goHome: 'Back to workspace', + local: 'Team workspace', + readOnly: 'Workspace overview', + noAccess: 'This view is for Compliance', + noAccessText: 'Your merchant portfolio is available from the workspace.', + date: 'Date', + status: 'Status', + owner: 'Account manager', + merchant: 'Merchant', + created: 'Created', + currentStage: 'Current stage', + daysInStage: '{{count}} days in stage', + daysInStage_one: '{{count}} day in stage', + number: '{{value}}', + brandTag: 'Every stage. One workspace.', + }, + nav: { + dashboard: 'Dashboard', + merchants: 'Merchants', + pipeline: 'Pipeline', + tasks: 'Tasks', + review: 'Review queue', + }, + roles: { + HEAD_OF_SALES: 'Head of Sales', + COMPLIANCE_OFFICER: 'Compliance Officer', + ACCOUNT_MANAGER: 'Account Manager', + }, + statuses: { + NEW_LEAD: 'New Lead', + CONTACTED: 'Contacted', + QUALIFIED: 'Qualified', + KYB: 'KYB', + COMPLIANCE_REVIEW: 'Compliance Review', + INTEGRATION: 'Integration', + TESTING: 'Testing', + LIVE: 'Live', + REJECTED: 'Rejected', + }, + industry: { + ECOMMERCE: 'E-commerce', + SOFTWARE: 'Software', + TRAVEL: 'Travel', + SERVICES: 'Services', + }, + landing: { + eyebrow: 'MERCHANT ONBOARDING, IN FLOW', + title: 'Great partnerships\nstart with a clear path.', + description: + 'From the first conversation to going live. Give sales, compliance, and account teams one calm place to move merchants forward.', + cta: 'Enter your workspace', + signIn: 'Sign in', + why: 'Less chasing. More moving forward.', + whyText: 'The context you need, exactly where you need it.', + feature1: 'See the whole journey', + feature1Text: 'A shared pipeline from new lead to live, with every handoff in view.', + feature2: 'Make reviews clearer', + feature2Text: 'Keep document checklists, notes, and merchant history together.', + feature3: 'Keep the next step close', + feature3Text: 'Stay connected to your merchants with tasks and in-app reminders.', + visualTitle: 'One shared journey', + visualSub: 'Built around your team', + visualNote: 'Context travels with every merchant.', + footer: 'A fictional crypto-payment provider. A thoughtfully connected workspace.', + }, + auth: { + eyebrow: 'WELCOME BACK', + title: 'Get back into flow.', + description: 'Sign in to your MerchantFlow workspace.', + email: 'Email address', + password: 'Password', + showPassword: 'Show password', + hidePassword: 'Hide password', + submit: 'Sign in to workspace', + submitting: 'Signing in…', + demoTitle: 'Explore the demo', + demoText: 'Choose an account to fill in its credentials, then sign in.', + demoPassword: 'Demo password', + back: 'Back to MerchantFlow', + sideTitle: 'Good handoffs make\ngreat partnerships.', + sideText: 'Your merchants, their story, and the next step. All in one place.', + expired: 'Your session ended. Sign in to continue.', + }, + validation: { + email: 'Enter a valid email address.', + password: 'Enter your password.', + passwordMax: 'Use 128 characters or fewer.', + invalid: 'Please check this value.', + }, + errors: { + UNAUTHORIZED: 'Sign in to continue.', + INVALID_CREDENTIALS: 'The email or password is incorrect.', + FORBIDDEN: 'You do not have access to this view.', + NOT_FOUND: 'This merchant was not found or is outside your portfolio.', + VALIDATION_ERROR: 'Please check the information and try again.', + INTERNAL_ERROR: 'We could not load this information. Please try again.', + DATABASE_UNAVAILABLE: 'The workspace database is unavailable. Please try again.', + TOO_MANY_REQUESTS: 'Too many sign-in attempts. Try again in five minutes.', + NETWORK: 'We could not reach the workspace. Check your connection and try again.', + RESPONSE: 'We received an unexpected response. Please try again.', + }, + dashboard: { + eyebrow: 'YOUR WORKSPACE, IN SYNC', + title: 'Overview', + description: 'A clear view of your merchant relationships.', + welcome: 'Welcome back, {{name}}', + view: 'View merchants', + merchants: 'Total merchants', + merchantsHint: 'In your visible portfolio', + reviews: 'Awaiting review', + reviewsHint: 'Ready for Compliance', + overdue: 'Overdue tasks', + overdueHint: 'A little attention needed', + changes: 'Stage changes', + changesHint: 'Over the last 30 days', + pipeline: 'Pipeline at a glance', + pipelineText: 'Every relationship has a next chapter.', + openPipeline: 'Open pipeline', + activity: 'Recent activity', + activityText: 'The latest moves across your portfolio.', + priorities: 'On your radar', + prioritiesText: 'Upcoming steps and timely follow-ups.', + moved: 'Moved to', + added: 'Added as', + emptyActivity: 'No activity to show yet', + scopeHead: 'Your entire merchant portfolio', + scopeManager: 'Your assigned merchants', + scopeCompliance: 'Merchants in KYB and Compliance Review', + }, + merchants: { + title: 'Merchants', + description: 'The people and businesses behind every partnership.', + search: 'Search merchants or contact email…', + filter: 'Filter by stage', + allStages: 'All stages', + business: 'Business', + location: 'Location', + portfolio: 'YOUR MERCHANT PORTFOLIO', + contact: 'Primary contact', + website: 'Website', + industry: 'Industry', + overview: 'Merchant overview', + details: 'The essentials, all together.', + checklist: 'KYB checklist', + checklistText: 'Document readiness for the next review.', + notes: 'Team notes', + notesText: 'Context from the people closest to the relationship.', + history: 'Journey history', + historyText: 'Every step, including the steps back.', + tasks: 'Related tasks', + tasksText: 'Follow-ups connected to this merchant.', + back: 'Back to merchants', + since: 'In this stage since {{date}}', + noNotes: 'No notes yet', + noTasks: 'No related tasks yet', + }, + documents: { + INCORPORATION: 'Certificate of incorporation', + OWNERSHIP: 'Ownership structure', + UBO_IDENTIFICATION: 'Beneficial owner identification', + BUSINESS_ACTIVITY: 'Business activity description', + }, + checklist: { MISSING: 'Missing', RECEIVED: 'Received', NEEDS_CORRECTION: 'Needs correction' }, + pipeline: { + title: 'Pipeline', + description: 'From a first hello to a lasting partnership.', + journey: 'THE PATH TO LIVE', + rejectedTitle: 'Closed · Rejected', + rejectedText: 'An alternate outcome, separate from the path to Live.', + stageSelect: 'Choose a pipeline stage', + empty: 'No merchants in this stage', + count: '{{count}} merchants', + count_one: '{{count}} merchant', + stageCount: '{{number}} of 8 stages', + }, + tasks: { + title: 'Tasks', + description: 'A little structure for the next right step.', + ALL: 'All tasks', + OPEN: 'Open', + OVERDUE: 'Overdue', + UPCOMING: 'Upcoming', + DONE: 'Completed', + due: 'Due {{date}}', + completed: 'Completed', + reminder: 'Reminder', + reminderDue: 'Reminder due', + assigned: 'Assigned to {{name}}', + empty: 'You’re all caught up here', + emptyText: 'No tasks match this filter.', + filter: 'Filter tasks', + taskTitle: 'Task', + dueDate: 'Due date', + }, + review: { + title: 'Review queue', + description: 'Clear context for confident decisions.', + eyebrow: 'COMPLIANCE WORKSPACE', + count: '{{count}} merchants awaiting review', + count_one: '{{count}} merchant awaiting review', + order: 'Oldest first', + empty: 'The queue is clear', + emptyText: 'Merchants appear here when they reach Compliance Review.', + entered: 'Entered review', + view: 'View checklist', + }, +}; +export const ru = { + common: { + workspace: 'Рабочее пространство', + team: 'Работа с мерчантами', + close: 'Закрыть', + back: 'Назад', + retry: 'Повторить', + loading: 'Загружаем рабочее пространство…', + errorTitle: 'Не удалось загрузить данные', + emptyTitle: 'Здесь пока ничего нет', + emptyText: 'Здесь появятся записи, соответствующие этому разделу.', + noResults: 'Мерчанты не найдены', + noResultsText: 'Попробуйте другое название или сбросьте фильтры.', + clear: 'Сбросить фильтры', + viewAll: 'Посмотреть все', + viewMerchant: 'Открыть мерчанта', + previous: 'Назад', + next: 'Далее', + page: 'Страница {{page}} из {{total}}', + showing: '{{from}}–{{to}} из {{total}} мерчантов', + all: 'Все', + language: 'Язык', + logout: 'Выйти', + openMenu: 'Открыть навигацию', + skip: 'Перейти к содержимому', + notFound: 'Такой страницы нет', + notFoundText: 'Возможно, страница перемещена или у вас нет доступа к ней.', + goHome: 'В рабочее пространство', + local: 'Пространство команды', + readOnly: 'Обзор рабочего пространства', + noAccess: 'Раздел для комплаенса', + noAccessText: 'Ваш портфель мерчантов доступен в рабочем пространстве.', + date: 'Дата', + status: 'Статус', + owner: 'Аккаунт-менеджер', + merchant: 'Мерчант', + created: 'Создан', + currentStage: 'Текущий этап', + daysInStage: '{{count}} дней на этапе', + daysInStage_one: '{{count}} день на этапе', + daysInStage_few: '{{count}} дня на этапе', + daysInStage_many: '{{count}} дней на этапе', + number: '{{value}}', + brandTag: 'Все этапы. Одно пространство.', + }, + nav: { + dashboard: 'Обзор', + merchants: 'Мерчанты', + pipeline: 'Воронка', + tasks: 'Задачи', + review: 'Очередь проверок', + }, + roles: { + HEAD_OF_SALES: 'Руководитель продаж', + COMPLIANCE_OFFICER: 'Специалист по комплаенсу', + ACCOUNT_MANAGER: 'Аккаунт-менеджер', + }, + statuses: { + NEW_LEAD: 'Новый лид', + CONTACTED: 'Контакт установлен', + QUALIFIED: 'Квалифицирован', + KYB: 'KYB', + COMPLIANCE_REVIEW: 'Комплаенс-проверка', + INTEGRATION: 'Интеграция', + TESTING: 'Тестирование', + LIVE: 'Запущен', + REJECTED: 'Отклонён', + }, + industry: { + ECOMMERCE: 'Электронная торговля', + SOFTWARE: 'Программное обеспечение', + TRAVEL: 'Туризм', + SERVICES: 'Услуги', + }, + landing: { + eyebrow: 'ПОДКЛЮЧЕНИЕ МЕРЧАНТОВ БЕЗ СУЕТЫ', + title: 'Хорошие партнёрства\nначинаются с ясного пути.', + description: + 'От первого разговора до запуска. Единое пространство, где продажи, комплаенс и аккаунт-менеджеры помогают мерчантам двигаться вперёд.', + cta: 'В рабочее пространство', + signIn: 'Войти', + why: 'Меньше поисков. Больше движения.', + whyText: 'Нужный контекст — в нужном месте.', + feature1: 'Весь путь перед глазами', + feature1Text: 'Общая воронка от нового лида до запуска с понятной передачей между командами.', + feature2: 'Прозрачные проверки', + feature2Text: 'Чек-листы документов, заметки и история мерчанта в одном месте.', + feature3: 'Следующий шаг рядом', + feature3Text: 'Задачи и напоминания внутри приложения помогают не терять связь с мерчантами.', + visualTitle: 'Один общий путь', + visualSub: 'Вокруг вашей команды', + visualNote: 'Контекст остаётся с мерчантом на каждом этапе.', + footer: 'Вымышленный криптоплатёжный провайдер. Продуманное рабочее пространство.', + }, + auth: { + eyebrow: 'С ВОЗВРАЩЕНИЕМ', + title: 'Продолжим в одном ритме.', + description: 'Войдите в рабочее пространство MerchantFlow.', + email: 'Электронная почта', + password: 'Пароль', + showPassword: 'Показать пароль', + hidePassword: 'Скрыть пароль', + submit: 'Войти в рабочее пространство', + submitting: 'Входим…', + demoTitle: 'Попробуйте демо', + demoText: 'Выберите аккаунт, чтобы заполнить данные, затем войдите.', + demoPassword: 'Демо-пароль', + back: 'На главную MerchantFlow', + sideTitle: 'Хорошая передача дел —\nоснова партнёрства.', + sideText: 'Ваши мерчанты, их история и следующий шаг. Всё в одном месте.', + expired: 'Сессия завершена. Войдите снова.', + }, + validation: { + email: 'Введите корректный адрес почты.', + password: 'Введите пароль.', + passwordMax: 'Не более 128 символов.', + invalid: 'Проверьте это значение.', + }, + errors: { + UNAUTHORIZED: 'Войдите, чтобы продолжить.', + INVALID_CREDENTIALS: 'Неверная почта или пароль.', + FORBIDDEN: 'У вас нет доступа к этому разделу.', + NOT_FOUND: 'Мерчант не найден или находится вне вашего портфеля.', + VALIDATION_ERROR: 'Проверьте данные и попробуйте снова.', + INTERNAL_ERROR: 'Не удалось загрузить данные. Попробуйте ещё раз.', + DATABASE_UNAVAILABLE: 'База данных недоступна. Попробуйте ещё раз.', + TOO_MANY_REQUESTS: 'Слишком много попыток входа. Попробуйте через пять минут.', + NETWORK: 'Не удалось подключиться. Проверьте соединение и попробуйте снова.', + RESPONSE: 'Получен неожиданный ответ. Попробуйте ещё раз.', + }, + dashboard: { + eyebrow: 'КОМАНДА В ОДНОМ РИТМЕ', + title: 'Обзор', + description: 'Всё важное о ваших отношениях с мерчантами.', + welcome: 'С возвращением, {{name}}', + view: 'К мерчантам', + merchants: 'Всего мерчантов', + merchantsHint: 'В доступном вам портфеле', + reviews: 'Ожидают проверки', + reviewsHint: 'Готовы к комплаенсу', + overdue: 'Просроченные задачи', + overdueHint: 'Требуют вашего внимания', + changes: 'Смены этапов', + changesHint: 'За последние 30 дней', + pipeline: 'Воронка с первого взгляда', + pipelineText: 'У каждого партнёрства есть следующий этап.', + openPipeline: 'Открыть воронку', + activity: 'Последние события', + activityText: 'Что изменилось в вашем портфеле.', + priorities: 'В поле внимания', + prioritiesText: 'Следующие шаги и своевременная обратная связь.', + moved: 'Переход на этап', + added: 'Добавлен на этап', + emptyActivity: 'Событий пока нет', + scopeHead: 'Весь портфель мерчантов', + scopeManager: 'Закреплённые за вами мерчанты', + scopeCompliance: 'Мерчанты на KYB и комплаенс-проверке', + }, + merchants: { + title: 'Мерчанты', + description: 'Люди и компании за каждым партнёрством.', + search: 'Название мерчанта или почта…', + filter: 'Фильтр по этапу', + allStages: 'Все этапы', + business: 'Компания', + location: 'Страна', + portfolio: 'ВАШ ПОРТФЕЛЬ МЕРЧАНТОВ', + contact: 'Основной контакт', + website: 'Сайт', + industry: 'Отрасль', + overview: 'О мерчанте', + details: 'Главное — в одном месте.', + checklist: 'Чек-лист KYB', + checklistText: 'Готовность документов к следующей проверке.', + notes: 'Заметки команды', + notesText: 'Контекст от тех, кто работает с мерчантом.', + history: 'История этапов', + historyText: 'Каждый шаг, включая возвраты.', + tasks: 'Связанные задачи', + tasksText: 'Дальнейшие действия по этому мерчанту.', + back: 'К списку мерчантов', + since: 'На этом этапе с {{date}}', + noNotes: 'Заметок пока нет', + noTasks: 'Связанных задач пока нет', + }, + documents: { + INCORPORATION: 'Свидетельство о регистрации', + OWNERSHIP: 'Структура собственности', + UBO_IDENTIFICATION: 'Идентификация бенефициаров', + BUSINESS_ACTIVITY: 'Описание деятельности', + }, + checklist: { MISSING: 'Отсутствует', RECEIVED: 'Получен', NEEDS_CORRECTION: 'Нужны исправления' }, + pipeline: { + title: 'Воронка', + description: 'От первого знакомства до долгого партнёрства.', + journey: 'ПУТЬ К ЗАПУСКУ', + rejectedTitle: 'Закрыто · Отклонён', + rejectedText: 'Альтернативный исход вне успешного пути к запуску.', + stageSelect: 'Выбрать этап воронки', + empty: 'На этом этапе нет мерчантов', + count: '{{count}} мерчантов', + count_one: '{{count}} мерчант', + count_few: '{{count}} мерчанта', + count_many: '{{count}} мерчантов', + stageCount: '{{number}} из 8 этапов', + }, + tasks: { + title: 'Задачи', + description: 'Немного порядка для следующего верного шага.', + ALL: 'Все задачи', + OPEN: 'Открытые', + OVERDUE: 'Просроченные', + UPCOMING: 'Предстоящие', + DONE: 'Выполненные', + due: 'Срок: {{date}}', + completed: 'Выполнено', + reminder: 'Напоминание', + reminderDue: 'Пора напомнить', + assigned: 'Ответственный: {{name}}', + empty: 'Здесь всё в порядке', + emptyText: 'Нет задач по выбранному фильтру.', + filter: 'Фильтр задач', + taskTitle: 'Задача', + dueDate: 'Срок', + }, + review: { + title: 'Очередь проверок', + description: 'Полный контекст для уверенных решений.', + eyebrow: 'ПРОСТРАНСТВО КОМПЛАЕНСА', + count: '{{count}} мерчантов ожидают проверки', + count_one: '{{count}} мерчант ожидает проверки', + count_few: '{{count}} мерчанта ожидают проверки', + count_many: '{{count}} мерчантов ожидают проверки', + order: 'Сначала самые ранние', + empty: 'Очередь пуста', + emptyText: 'Мерчанты появятся здесь на этапе комплаенс-проверки.', + entered: 'Начало проверки', + view: 'Открыть чек-лист', + }, +}; diff --git a/apps/web/src/main.tsx b/apps/web/src/main.tsx new file mode 100644 index 0000000..360deee --- /dev/null +++ b/apps/web/src/main.tsx @@ -0,0 +1,46 @@ +import React from 'react'; +import ReactDOM from 'react-dom/client'; +import { BrowserRouter, Routes, Route } from 'react-router'; +import { QueryClientProvider } from '@tanstack/react-query'; +import '@merchantflow/ui/globals.css'; +import './i18n'; +import { queryClient } from './lib/api'; +import { ProtectedShell } from './components/shell'; +import { Landing, Login } from './pages/public'; +import { + Dashboard, + Merchants, + MerchantDetail, + Pipeline, + Tasks, + ReviewQueue, + NotFound, +} from './pages/crm'; +document.addEventListener('keydown', () => { + document.documentElement.dataset.input = 'keyboard'; +}); +document.addEventListener('pointerdown', () => { + document.documentElement.dataset.input = 'pointer'; +}); +ReactDOM.createRoot(document.getElementById('root')!).render( + + + + + } /> + } /> + }> + } /> + } /> + } /> + } /> + } /> + } /> + } /> + + } /> + + + + , +); diff --git a/apps/web/src/pages/crm.tsx b/apps/web/src/pages/crm.tsx new file mode 100644 index 0000000..41096d7 --- /dev/null +++ b/apps/web/src/pages/crm.tsx @@ -0,0 +1,837 @@ +import { useEffect, useState } from 'react'; +import { Link, useOutletContext, useParams, useSearchParams } from 'react-router'; +import { keepPreviousData, useQuery } from '@tanstack/react-query'; +import { useTranslation } from 'react-i18next'; +import { + ArrowRight, + ArrowUpRight, + ArrowLeft, + Building2, + ShieldCheck, + Clock3, + Activity, + Search, + ChevronLeft, + ChevronRight, + Check, + FileText, + Globe2, + Mail, + ExternalLink, + SlidersHorizontal, + LoaderCircle, +} from 'lucide-react'; +import { + dashboardSchema, + merchantListSchema, + merchantDetailSchema, + pipelineSchema, + taskListSchema, + statuses, + successfulStages, + statusSchema, + taskFilters, + canSeeReviewQueue, + type Status, + type User, + type TaskFilter, + type Merchant, +} from '@merchantflow/contracts'; +import { Input } from '@merchantflow/ui/components/input'; +import { NativeSelect } from '@merchantflow/ui/components/native-select'; +import { + Table, + TableHeader, + TableBody, + TableRow, + TableHead, + TableCell, +} from '@merchantflow/ui/components/table'; +import { Badge } from '@merchantflow/ui/components/badge'; +import { cn } from '@merchantflow/ui/lib/utils'; +import { api } from '../lib/api'; +import { useFormat } from '../lib/format'; +import { + PageHeader, + SectionHeader, + QueryBoundary, + LinkButton, + Button, + StatusBadge, + Avatar, + ActivityFeed, + TaskRow, + MerchantCard, + EmptyState, + stageColors, +} from '../components/shared'; +export function Dashboard() { + const { t } = useTranslation(); + const f = useFormat(); + const user = useOutletContext(); + const query = useQuery({ + queryKey: ['dashboard'], + queryFn: ({ signal }) => api('/dashboard', dashboardSchema, { signal }), + }); + return ( + <> + + {t('dashboard.view')} + + + } + /> + + {(data) => ( +
+
+ {[ + { key: 'merchants', value: data.merchantCount, Icon: Building2 }, + { key: 'reviews', value: data.reviewCount, Icon: ShieldCheck }, + { key: 'overdue', value: data.overdueTasks, Icon: Clock3 }, + { key: 'changes', value: data.transitionsLast30Days, Icon: Activity }, + ].map(({ key, value, Icon }, i) => ( +
+
+

+ {t(`dashboard.${key}`)} +

+
+
+
+

+ {f.number(value)} +

+

+ {t(`dashboard.${key}Hint`)} +

+
+ ))} +
+
+ + {t('dashboard.openPipeline')} + + + } + /> +
+ +
+
+
+ + +
+
+ + {t('common.viewAll')} + + + } + /> +
+ {data.upcomingTasks.length ? ( + data.upcomingTasks.map((task) => ) + ) : ( + + )} +
+
+
+
+
+
+ )} +
+ + ); +} +function useDebounced(value: string) { + const [debounced, setDebounced] = useState(value); + useEffect(() => { + const timer = setTimeout(() => setDebounced(value), 200); + return () => clearTimeout(timer); + }, [value]); + return debounced; +} +function MerchantTable({ merchants }: { merchants: Merchant[] }) { + const { t } = useTranslation(); + const f = useFormat(); + return ( + <> +
+ + + + {t('common.merchant')} + {t('common.status')} + {t('merchants.location')} + {t('common.owner')} + {t('common.created')} + + + + {merchants.map((m) => ( + + + + +
+

{m.name}

+

+ {t(`industry.${m.industry}`)} +

+
+ +
+ + + + + {f.country(m.country)} + + {m.owner.name} + + {f.shortDate(m.createdAt)} + +
+ ))} +
+
+
+
+ {merchants.map((m) => ( + +
+ +
+

{m.name}

+

+ {t(`industry.${m.industry}`)} · {f.country(m.country)} +

+
+ +
+
+ + {m.owner.name} +
+ + ))} +
+ + ); +} +export function Merchants() { + const { t } = useTranslation(); + const f = useFormat(); + const [params, setParams] = useSearchParams(); + const search = params.get('search') ?? ''; + const debounced = useDebounced(search); + const parsedStatus = statusSchema.safeParse(params.get('status')); + const status = parsedStatus.success ? parsedStatus.data : ''; + const page = Math.max(1, Math.min(10000, Number(params.get('page')) || 1)); + const update = (key: string, value: string) => { + const next = new URLSearchParams(params); + if (value) next.set(key, value); + else next.delete(key); + if (key !== 'page') next.delete('page'); + setParams(next, { replace: true }); + }; + const query = useQuery({ + queryKey: ['merchants', debounced, status, page], + queryFn: ({ signal }) => + api( + `/merchants?${new URLSearchParams({ search: debounced, ...(status ? { status } : {}), page: String(page) })}`, + merchantListSchema, + { signal }, + ), + placeholderData: keepPreviousData, + }); + return ( + <> + +
+
+
+
+
+
+
+ + {(data) => + data.items.length ? ( + <> + +
+

+ {t('common.showing', { + from: f.number((page - 1) * data.pageSize + 1), + to: f.number(Math.min(page * data.pageSize, data.total)), + total: f.number(data.total), + })} +

+ +
+ + ) : ( + setParams({})}> + {t('common.clear')} + + } + /> + ) + } +
+
+ + ); +} +export function MerchantDetail() { + const { id } = useParams(); + const { t } = useTranslation(); + const f = useFormat(); + const query = useQuery({ + queryKey: ['merchant', id], + queryFn: ({ signal }) => + api(`/merchants/${encodeURIComponent(id ?? '')}`, merchantDetailSchema, { signal }), + }); + return ( + <> + + + {t('merchants.back')} + + + {(m) => ( + <> +
+ +
+

{m.name}

+

+ {t(`industry.${m.industry}`)} · {f.country(m.country)} +

+
+
+ +

+ {t('merchants.since', { date: f.date(m.stageEnteredAt) })} +

+
+
+
+
+
+ +
+ {[ + { label: t('common.owner'), value: m.owner.name }, + { label: t('merchants.contact'), value: m.contactName }, + { + label: t('merchants.website'), + value: ( + + + {new URL(m.website).hostname} + + + ), + }, + { + label: t('auth.email'), + value: ( + + + {m.contactEmail} + + ), + }, + ].map((item, i) => ( +
+
{item.label}
+
{item.value}
+
+ ))} +
+
+
+ +
+ {m.checklist.map((doc) => ( +
+
+ {doc.state === 'RECEIVED' ? ( + + ) : ( + + )} +
+
+
+

{t(`documents.${doc.documentCode}`)}

+ + {t(`checklist.${doc.state}`)} + +
+ {doc.note && ( +

+ {doc.note} +

+ )} +
+
+ ))} +
+
+
+ +
+ {m.notes.length ? ( + m.notes.map((note) => ( +
+

{note.text}

+

+ {note.author.name} · {f.date(note.createdAt)} +

+
+ )) + ) : ( + + )} +
+
+
+
+
+ + +
+
+ +
+ {m.tasks.length ? ( + m.tasks.map((task) => ) + ) : ( + + )} +
+
+
+
+ + )} +
+ + ); +} +export function Pipeline() { + const { t } = useTranslation(); + const f = useFormat(); + const [stage, setStage] = useState('NEW_LEAD'); + const query = useQuery({ + queryKey: ['pipeline'], + queryFn: ({ signal }) => api('/pipeline', pipelineSchema, { signal }), + }); + return ( + <> + + + {(merchants) => ( + <> + setStage(e.target.value as Status)} + > + {successfulStages.map((s) => ( + + ))} + +
+ {successfulStages.map((s, i) => { + const items = merchants.filter((m) => m.status === s); + return ( +
+
+

+ + {t(`statuses.${s}`)} +

+ + {f.number(items.length)} + +
+
+ {items.map((m) => ( + + ))} + {!items.length && ( +

+ {t('pipeline.empty')} +

+ )} +
+

+ {t('pipeline.stageCount', { number: f.number(i + 1) })} +

+
+ ); + })} +
+
+

{t('pipeline.rejectedTitle')}

+

+ {t('pipeline.rejectedText')} +

+
+ {merchants + .filter((m) => m.status === 'REJECTED') + .map((m) => ( + + ))} + {!merchants.some((m) => m.status === 'REJECTED') && ( +

{t('pipeline.empty')}

+ )} +
+
+ + )} +
+ + ); +} +export function Tasks() { + const { t } = useTranslation(); + const [params, setParams] = useSearchParams(); + const raw = params.get('filter'); + const filter: TaskFilter = taskFilters.includes(raw as TaskFilter) ? (raw as TaskFilter) : 'ALL'; + const query = useQuery({ + queryKey: ['tasks', filter], + queryFn: ({ signal }) => api(`/tasks?filter=${filter}`, taskListSchema, { signal }), + refetchInterval: 60000, + }); + return ( + <> + +
+
+ {taskFilters.map((s) => ( + + ))} +
+ + {(tasks) => + tasks.length ? ( +
+ {tasks.map((task) => ( + + ))} +
+ ) : ( + + ) + } +
+
+ + ); +} +export function ReviewQueue() { + const user = useOutletContext(); + const { t } = useTranslation(); + const f = useFormat(); + const allowed = canSeeReviewQueue(user.role); + const query = useQuery({ + queryKey: ['review-queue'], + queryFn: ({ signal }) => api('/review-queue', pipelineSchema, { signal }), + enabled: allowed, + }); + if (!allowed) return ; + return ( + <> + + + {(merchants) => ( +
+
+

+ {t('review.count', { count: merchants.length })} +

+ + + {t('review.order')} + +
+ {merchants.length ? ( + merchants.map((m) => ( +
+
+ +
+ + {m.name} + +

+ {m.owner.name} · {t(`industry.${m.industry}`)} +

+
+
+
+
+

+ {t('review.entered')} +

+

{f.date(m.stageEnteredAt)}

+
+ + {t('review.view')} + + +
+
+ )) + ) : ( + + )} +
+ )} +
+ + ); +} +export function NotFound({ forbidden = false }: { forbidden?: boolean }) { + const { t } = useTranslation(); + return ( +
+ + {t('common.goHome')} + + + } + /> +
+ ); +} diff --git a/apps/web/src/pages/public.tsx b/apps/web/src/pages/public.tsx new file mode 100644 index 0000000..dcfedbd --- /dev/null +++ b/apps/web/src/pages/public.tsx @@ -0,0 +1,281 @@ +import { useState } from 'react'; +import { Link, useNavigate, useSearchParams } from 'react-router'; +import { useTranslation } from 'react-i18next'; +import { useMutation } from '@tanstack/react-query'; +import { useForm } from 'react-hook-form'; +import { zodResolver } from '@hookform/resolvers/zod'; +import { + ArrowRight, + ArrowLeft, + Columns3, + ShieldCheck, + ListTodo, + Check, + Eye, + EyeOff, + LoaderCircle, +} from 'lucide-react'; +import { loginSchema, userSchema, type LoginInput } from '@merchantflow/contracts'; +import { Input } from '@merchantflow/ui/components/input'; +import { FormField } from '@merchantflow/ui/components/form-field'; +import { Brand, LanguageSwitch, LinkButton, Button, StatusBadge } from '../components/shared'; +import { api, ApiError, queryClient, safeReturnTo } from '../lib/api'; +function JourneyIllustration() { + const { t } = useTranslation(); + return ( +
+
+
+

{t('landing.visualTitle')}

+

{t('landing.visualSub')}

+
+
+
+
+
+ {(['QUALIFIED', 'COMPLIANCE_REVIEW', 'LIVE'] as const).map((status, i) => ( +
+
+ {i === 0 ? ( + + ) : i === 1 ? ( + + ) : ( + + )} +
+
+

+ 0{i + 1} +

+ +
+
+ ))} +
+

+ + {t('landing.visualNote')} +

+
+ ); +} +export function Landing() { + const { t } = useTranslation(); + return ( +
+
+ +
+ + + {t('landing.signIn')} + + +
+
+
+
+
+

{t('landing.eyebrow')}

+

+ {t('landing.title')} +

+

+ {t('landing.description')} +

+ + {t('landing.cta')} + + +

{t('common.brandTag')}

+
+ +
+
+
+

{t('landing.why')}

+

{t('landing.whyText')}

+
+ {[Columns3, ShieldCheck, ListTodo].map((Icon, i) => ( +
+
+
+

{t(`landing.feature${i + 1}`)}

+

+ {t(`landing.feature${i + 1}Text`)} +

+
+ ))} +
+
+
+
+
+ © {new Date().getFullYear()} MerchantFlow + {t('landing.footer')} +
+
+ ); +} +export function Login() { + const { t } = useTranslation(); + const [show, setShow] = useState(false); + const [params] = useSearchParams(); + const navigate = useNavigate(); + const form = useForm({ + resolver: zodResolver(loginSchema), + defaultValues: { email: '', password: '' }, + }); + const mutation = useMutation({ + mutationFn: (input: LoginInput) => + api('/auth/login', userSchema, { method: 'POST', body: JSON.stringify(input) }), + onSuccess: async (user) => { + await queryClient.cancelQueries(); + queryClient.clear(); + queryClient.setQueryData(['session'], user); + navigate(safeReturnTo(params.get('next')), { replace: true }); + }, + }); + const demos = [ + { email: 'head', role: 'HEAD_OF_SALES' }, + { email: 'compliance', role: 'COMPLIANCE_OFFICER' }, + { email: 'manager1', role: 'ACCOUNT_MANAGER', name: 'Alex' }, + { email: 'manager2', role: 'ACCOUNT_MANAGER', name: 'Maria' }, + ]; + return ( +
+
+
+ + +
+
+ + + {t('auth.back')} + +

{t('auth.eyebrow')}

+

{t('auth.title')}

+

+ {t('auth.description')} +

+
mutation.mutate(input))} + className="space-y-5" + > + + + + +
+ + +
+
+ {mutation.isError && ( +

+ {t( + `errors.${mutation.error instanceof ApiError ? mutation.error.code : 'INTERNAL_ERROR'}`, + )} +

+ )} + +
+
+

{t('auth.demoTitle')}

+

+ {t('auth.demoText')} +

+
+ {demos.map((d) => ( + + ))} +
+

+ {t('auth.demoPassword')}: MerchantFlow123! +

+
+
+
+ +
+ ); +} diff --git a/apps/web/tsconfig.json b/apps/web/tsconfig.json new file mode 100644 index 0000000..03950f1 --- /dev/null +++ b/apps/web/tsconfig.json @@ -0,0 +1,14 @@ +{ + "extends": "../../tsconfig.base.json", + "compilerOptions": { + "module": "ESNext", + "moduleResolution": "Bundler", + "jsx": "react-jsx", + "lib": ["ES2022", "DOM", "DOM.Iterable"], + "noEmit": true, + "baseUrl": ".", + "paths": { "@/*": ["./src/*"] }, + "types": ["vite/client"] + }, + "include": ["src", "vite.config.ts"] +} diff --git a/apps/web/vite.config.ts b/apps/web/vite.config.ts new file mode 100644 index 0000000..e0ea1b5 --- /dev/null +++ b/apps/web/vite.config.ts @@ -0,0 +1,44 @@ +import { defineConfig, loadEnv } from 'vite'; +import react from '@vitejs/plugin-react'; +import tailwindcss from '@tailwindcss/vite'; +import { fileURLToPath } from 'node:url'; +export default defineConfig(({ mode }) => { + const env = { ...loadEnv(mode, '../..', ''), ...process.env }; + return { + plugins: [ + react(), + tailwindcss(), + { + name: 'server-boundary', + generateBundle() { + for (const id of this.getModuleIds()) + if ( + id.includes('@prisma') || + id.includes('/packages/database/') || + /\/node_modules\/(pg|pg-pool)\//.test(id) + ) + this.error(`Server dependency in browser bundle: ${id}`); + }, + }, + ], + resolve: { alias: { '@': fileURLToPath(new URL('./src', import.meta.url)) } }, + build: { + rollupOptions: { + output: { + manualChunks(id) { + if (/\/node_modules\/(react|react-dom|scheduler)\//.test(id)) return 'react-vendor'; + if (/\/node_modules\/(zod|react-hook-form|@hookform)\//.test(id)) return 'forms'; + if (id.includes('/@base-ui/') || id.includes('/@floating-ui/')) return 'primitives'; + }, + }, + }, + }, + server: { + port: Number(env.WEB_PORT ?? 5173), + strictPort: true, + proxy: { + '/api': { target: `http://127.0.0.1:${env.API_PORT ?? 3001}`, changeOrigin: false }, + }, + }, + }; +}); diff --git a/compose.yaml b/compose.yaml new file mode 100644 index 0000000..f29c4f2 --- /dev/null +++ b/compose.yaml @@ -0,0 +1,30 @@ +services: + db: + image: postgres:17.6-alpine + environment: + POSTGRES_USER: merchantflow + POSTGRES_PASSWORD: merchantflow_local + POSTGRES_DB: merchantflow + ports: ['127.0.0.1:55440:5432'] + volumes: ['merchantflow_data:/var/lib/postgresql/data'] + healthcheck: + test: ['CMD-SHELL', 'pg_isready -U merchantflow -d merchantflow'] + interval: 2s + timeout: 5s + retries: 20 + db-test: + image: postgres:17.6-alpine + profiles: ['test'] + environment: + POSTGRES_USER: merchantflow + POSTGRES_PASSWORD: merchantflow_local + POSTGRES_DB: merchantflow_test + ports: ['127.0.0.1:55441:5432'] + tmpfs: ['/var/lib/postgresql/data'] + healthcheck: + test: ['CMD-SHELL', 'pg_isready -U merchantflow -d merchantflow_test'] + interval: 2s + timeout: 5s + retries: 20 +volumes: + merchantflow_data: diff --git a/docs/implementation-checklist.md b/docs/implementation-checklist.md new file mode 100644 index 0000000..74332c6 --- /dev/null +++ b/docs/implementation-checklist.md @@ -0,0 +1,50 @@ +# Implementation checklist + +## Foundation + +- [x] pnpm/Turbo workspace, pinned packages and lockfile +- [x] Shared UI, browser-safe contracts, server-only database package +- [x] PostgreSQL Compose, migrations, repeatable four-account/eighteen-merchant seed +- [x] Cookie sessions and server-enforced role scopes +- [x] Scoped dashboard, merchants/detail, pipeline, tasks, review queue +- [x] Responsive public landing, login, CRM shell, reusable states and controls +- [x] Persistent EN/RU UI, validation, statuses and formatting +- [x] Setup documentation and environment examples + +## Verification (record actual outcomes) + +- [x] Frozen install, build, lint, typecheck, unit tests +- [x] Isolated PostgreSQL integration tests: auth, expiry, access, metrics, seed repeatability +- [x] Direct and proxied database-aware health endpoint +- [x] Browser checks at 390px/1440px, EN/RU, all roles and navigation +- [x] Keyboard, reduced motion, loading/error/empty states and overflow +- [x] Browser bundle excludes Prisma/database dependencies + +### Results · 24 September 2026 + +| Check | Actual outcome | +| -------------------------------- | ------------------------------------------------------------------------------------------------------------------------------ | +| `pnpm install --frozen-lockfile` | Passed; lockfile matches all six workspace manifests | +| `pnpm build` | All five packages built; Vite's server-dependency boundary passed | +| `pnpm lint` / `pnpm typecheck` | Passed | +| `pnpm test` | 8 passed: 4 contracts, 2 localization/return URL, 2 API units | +| `pnpm test:integration` | 10 passed against isolated PostgreSQL on port 55441 | +| `pnpm test:e2e` | 7 passed; EN/RU at 390px and 1440px, account switching and all role restrictions | +| Frontend/backend start | Vite 5173 and NestJS 3001 started through the root development command | +| Health directly / through proxy | Both returned `{"status":"ok","database":"connected"}` | +| Visual inspection | Inspected desktop/mobile screenshots, Russian layout, merchant detail and landing page; no page overflow in browser assertions | +| Accessibility interactions | Login errors associated with fields, keyboard skip link, mobile sheet Escape/focus restoration, reduced motion checked | +| `pnpm format:check` | Passed | + +Browser reports and screenshots are generated in ignored `playwright-report/` and `test-results/`. Test databases and server ports are separate from development. PostgreSQL uses 55440/55441 because 5432 and 55432 were already occupied. The Vite build emits non-fatal annotation warnings from Zod 4.6.5; emitted assets and all runtime checks pass. + +The dedicated browser runner was verified to release ports 5174/3002 after the suite. The development app remains on 5173/3001. Sign-in was also smoke-tested through both `localhost` and `127.0.0.1` origins. `.env` and generated Prisma sources are ignored by Git. + +## Deferred intentionally + +- [ ] Merchant editing and assignment +- [ ] Pipeline actions, rejection and return-to-KYB mutations +- [ ] KYB checklist editing and review decisions +- [ ] Task/reminder management + +Never in this prototype: merchant portal, payments, uploads, external KYB, external reminders, deployment. diff --git a/docs/product-brief.md b/docs/product-brief.md new file mode 100644 index 0000000..5259030 --- /dev/null +++ b/docs/product-brief.md @@ -0,0 +1,25 @@ +# MerchantFlow product brief + +A local test-assignment prototype for a fictional crypto-payment provider. The first milestone is a usable, read-only CRM foundation with real authentication, persisted sample records, responsive navigation, and EN/RU localization. + +## People and access + +Four seeded accounts: one Head of Sales, one Compliance Officer, two Account Managers. The Head sees all merchants. Compliance sees only merchants currently in KYB or Compliance Review. Managers see only their assigned merchants. These scopes apply to details, lists, metrics, history, tasks, and search. The Review Queue is exclusive to Compliance, including direct API requests. + +## Onboarding + +New Lead → Contacted → Qualified → KYB → Compliance Review → Integration → Testing → Live. + +Rejected is an alternate terminal outcome, never a step after Live. Compliance may return a review to KYB for corrections. KYB uses document checklists and notes without uploads. Names and notes remain exactly as entered. Status and role codes remain canonical; labels are translated. + +## Foundation journeys + +Public landing → login → role-scoped dashboard → merchant search/filter → merchant detail, checklist, notes, history, tasks. Separate Pipeline and Tasks pages and a Compliance-only Review Queue. Records are read-only in this milestone. Tasks and reminders are displayed inside the app. Dashboard values come from database records and historical events. + +## Defaults and boundaries + +English is the default. Persist EN/RU selection in browser storage. Dates use the selected locale and the viewer's local time zone. Light neutral UI, restrained lime accents, visible focus, touch-sized controls, reduced-motion support. No merchant self-service, real payment processing, external KYB integration, uploads, external notifications, or deployment. + +## Later milestones + +Merchant create/edit and owner assignment; permission-aware pipeline transitions with atomic history; Compliance approve/reject/return-to-KYB with correction notes; checklist editing; task/reminder create/edit/complete. These require explicit workflow permission and validation rules before implementation. diff --git a/eslint.config.mjs b/eslint.config.mjs new file mode 100644 index 0000000..e60877f --- /dev/null +++ b/eslint.config.mjs @@ -0,0 +1,29 @@ +import tseslint from 'typescript-eslint'; +import hooks from 'eslint-plugin-react-hooks'; +export default tseslint.config( + { + ignores: [ + '**/dist/**', + '**/node_modules/**', + '**/generated/**', + '**/.turbo/**', + 'playwright-report/**', + 'test-results/**', + ], + }, + ...tseslint.configs.recommended, + { + files: ['**/*.{ts,tsx}'], + rules: { + '@typescript-eslint/no-unused-vars': [ + 'error', + { argsIgnorePattern: '^_', varsIgnorePattern: '^_' }, + ], + }, + }, + { + files: ['**/*.tsx'], + plugins: { 'react-hooks': hooks }, + rules: { 'react-hooks/rules-of-hooks': 'error', 'react-hooks/exhaustive-deps': 'warn' }, + }, +); diff --git a/package.json b/package.json new file mode 100644 index 0000000..d1e9a36 --- /dev/null +++ b/package.json @@ -0,0 +1,46 @@ +{ + "name": "merchantflow", + "private": true, + "type": "module", + "packageManager": "pnpm@10.32.1", + "engines": { + "node": ">=22.19.0 <23" + }, + "scripts": { + "dev": "turbo run build --filter=@merchantflow/api && turbo run dev", + "build": "turbo run build", + "lint": "eslint .", + "typecheck": "turbo run typecheck", + "test": "turbo run test", + "db:up": "docker compose up -d --wait db", + "db:down": "docker compose down", + "db:generate": "pnpm --filter @merchantflow/database generate", + "db:migrate": "pnpm --filter @merchantflow/database migrate", + "db:seed": "turbo run build --filter=@merchantflow/database && pnpm --filter @merchantflow/database seed", + "db:setup": "pnpm db:up && pnpm db:migrate && pnpm db:seed", + "test:integration": "node scripts/test-database.mjs integration", + "test:e2e": "node scripts/test-database.mjs browser", + "format": "prettier --write .", + "format:check": "prettier --check ." + }, + "devDependencies": { + "@playwright/test": "1.63.0", + "@types/node": "22.20.4", + "eslint": "9.39.5", + "eslint-plugin-react-hooks": "7.1.1", + "eslint-plugin-react-refresh": "0.5.7", + "prettier": "3.6.2", + "turbo": "2.11.3", + "typescript": "5.9.3", + "typescript-eslint": "8.70.1", + "vitest": "3.2.7" + }, + "pnpm": { + "onlyBuiltDependencies": [ + "@nestjs/core", + "@prisma/engines", + "prisma", + "esbuild" + ] + } +} diff --git a/packages/contracts/package.json b/packages/contracts/package.json new file mode 100644 index 0000000..9023c87 --- /dev/null +++ b/packages/contracts/package.json @@ -0,0 +1,21 @@ +{ + "name": "@merchantflow/contracts", + "version": "0.0.0", + "private": true, + "type": "module", + "exports": { + ".": { + "types": "./dist/index.d.ts", + "import": "./dist/index.js" + } + }, + "scripts": { + "build": "tsc", + "typecheck": "tsc --noEmit", + "test": "vitest run", + "dev": "tsc --watch --preserveWatchOutput" + }, + "dependencies": { + "zod": "4.6.5" + } +} diff --git a/packages/contracts/src/index.test.ts b/packages/contracts/src/index.test.ts new file mode 100644 index 0000000..c355149 --- /dev/null +++ b/packages/contracts/src/index.test.ts @@ -0,0 +1,31 @@ +import { describe, it, expect } from 'vitest'; +import { + loginSchema, + merchantQuerySchema, + successfulStages, + statuses, + canSeeReviewQueue, +} from './index.js'; +describe('browser-safe contracts', () => { + it('keeps rejection outside the successful sequence', () => { + expect(successfulStages.at(-1)).toBe('LIVE'); + expect(successfulStages).not.toContain('REJECTED'); + expect(statuses).toHaveLength(9); + }); + it('validates and normalizes login without changing the password', () => { + expect( + loginSchema.parse({ email: 'Head@MerchantFlow.test', password: ' keep spaces ' }), + ).toEqual({ email: 'head@merchantflow.test', password: ' keep spaces ' }); + expect(loginSchema.safeParse({ email: 'invalid', password: '' }).success).toBe(false); + }); + it('rejects malformed filters and pages', () => { + expect(merchantQuerySchema.safeParse({ status: 'Live' }).success).toBe(false); + expect(merchantQuerySchema.safeParse({ page: '-1' }).success).toBe(false); + expect(merchantQuerySchema.parse({}).page).toBe(1); + }); + it('keeps review queue exclusive to Compliance', () => { + expect(canSeeReviewQueue('HEAD_OF_SALES')).toBe(false); + expect(canSeeReviewQueue('ACCOUNT_MANAGER')).toBe(false); + expect(canSeeReviewQueue('COMPLIANCE_OFFICER')).toBe(true); + }); +}); diff --git a/packages/contracts/src/index.ts b/packages/contracts/src/index.ts new file mode 100644 index 0000000..f98f7c8 --- /dev/null +++ b/packages/contracts/src/index.ts @@ -0,0 +1,140 @@ +import { z } from 'zod'; + +export const roles = ['HEAD_OF_SALES', 'COMPLIANCE_OFFICER', 'ACCOUNT_MANAGER'] as const; +export const successfulStages = [ + 'NEW_LEAD', + 'CONTACTED', + 'QUALIFIED', + 'KYB', + 'COMPLIANCE_REVIEW', + 'INTEGRATION', + 'TESTING', + 'LIVE', +] as const; +export const statuses = [...successfulStages, 'REJECTED'] as const; +export const roleSchema = z.enum(roles); +export const statusSchema = z.enum(statuses); +export type Role = z.infer; +export type Status = z.infer; +export const loginSchema = z.object({ + email: z + .email({ error: 'validation.email' }) + .max(254, 'validation.email') + .transform((v) => v.toLowerCase()), + password: z.string().min(1, 'validation.password').max(128, 'validation.passwordMax'), +}); +export type LoginInput = z.input; +export const merchantQuerySchema = z.object({ + search: z.string().trim().max(100).default(''), + status: statusSchema.optional(), + page: z.coerce.number().int().min(1).max(10000).default(1), +}); +export const taskFilters = ['ALL', 'OPEN', 'OVERDUE', 'UPCOMING', 'DONE'] as const; +export const taskQuerySchema = z.object({ filter: z.enum(taskFilters).default('ALL') }); +export type TaskFilter = (typeof taskFilters)[number]; +export const errorCodes = [ + 'UNAUTHORIZED', + 'INVALID_CREDENTIALS', + 'FORBIDDEN', + 'NOT_FOUND', + 'VALIDATION_ERROR', + 'INTERNAL_ERROR', + 'DATABASE_UNAVAILABLE', + 'TOO_MANY_REQUESTS', +] as const; +export const apiErrorSchema = z.object({ + code: z.enum(errorCodes), + issues: z.array(z.object({ path: z.string(), code: z.string() })).optional(), +}); +export const userSchema = z.object({ + id: z.string(), + name: z.string(), + email: z.string(), + role: roleSchema, +}); +export type User = z.infer; +const date = z.iso.datetime(); +export const merchantSchema = z.object({ + id: z.string(), + name: z.string(), + website: z.string(), + industry: z.string(), + country: z.string(), + contactName: z.string(), + contactEmail: z.string(), + status: statusSchema, + createdAt: date, + stageEnteredAt: date, + owner: userSchema.pick({ id: true, name: true }), +}); +export type Merchant = z.infer; +export const merchantListSchema = z.object({ + items: z.array(merchantSchema), + total: z.number(), + page: z.number(), + pageSize: z.number(), +}); +export const eventSchema = z.object({ + id: z.string(), + fromStatus: statusSchema.nullable(), + toStatus: statusSchema, + occurredAt: date, + note: z.string().nullable(), + merchant: z.object({ id: z.string(), name: z.string() }), + actor: z.object({ name: z.string() }), +}); +export type StageEvent = z.infer; +export const taskSchema = z.object({ + id: z.string(), + title: z.string(), + status: z.enum(['OPEN', 'DONE']), + dueAt: date, + remindAt: date.nullable(), + completedAt: date.nullable(), + merchant: z.object({ id: z.string(), name: z.string() }), + assignee: z.object({ name: z.string() }), +}); +export type Task = z.infer; +export const taskListSchema = z.array(taskSchema); +export const documentCodes = [ + 'INCORPORATION', + 'OWNERSHIP', + 'UBO_IDENTIFICATION', + 'BUSINESS_ACTIVITY', +] as const; +export const merchantDetailSchema = merchantSchema.extend({ + checklist: z.array( + z.object({ + id: z.string(), + documentCode: z.enum(documentCodes), + state: z.enum(['MISSING', 'RECEIVED', 'NEEDS_CORRECTION']), + note: z.string().nullable(), + }), + ), + notes: z.array( + z.object({ + id: z.string(), + text: z.string(), + createdAt: date, + author: z.object({ name: z.string() }), + }), + ), + events: z.array(eventSchema), + tasks: taskListSchema, +}); +export const dashboardSchema = z.object({ + merchantCount: z.number(), + reviewCount: z.number(), + overdueTasks: z.number(), + transitionsLast30Days: z.number(), + distribution: z.array(z.object({ status: statusSchema, count: z.number() })), + recentEvents: z.array(eventSchema), + upcomingTasks: taskListSchema, +}); +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 function canSeeReviewQueue(role: Role) { + return role === 'COMPLIANCE_OFFICER'; +} diff --git a/packages/contracts/tsconfig.json b/packages/contracts/tsconfig.json new file mode 100644 index 0000000..a05e8d1 --- /dev/null +++ b/packages/contracts/tsconfig.json @@ -0,0 +1,12 @@ +{ + "extends": "../../tsconfig.base.json", + "compilerOptions": { + "module": "NodeNext", + "moduleResolution": "NodeNext", + "rootDir": "src", + "outDir": "dist", + "declaration": true + }, + "include": ["src"], + "exclude": ["src/**/*.test.ts"] +} diff --git a/packages/database/package.json b/packages/database/package.json new file mode 100644 index 0000000..517ccf9 --- /dev/null +++ b/packages/database/package.json @@ -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" + } +} diff --git a/packages/database/prisma.config.ts b/packages/database/prisma.config.ts new file mode 100644 index 0000000..1ee27f9 --- /dev/null +++ b/packages/database/prisma.config.ts @@ -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', + }, +}); diff --git a/packages/database/prisma/migrations/202609240001_foundation/migration.sql b/packages/database/prisma/migrations/202609240001_foundation/migration.sql new file mode 100644 index 0000000..d74a080 --- /dev/null +++ b/packages/database/prisma/migrations/202609240001_foundation/migration.sql @@ -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; diff --git a/packages/database/prisma/migrations/migration_lock.toml b/packages/database/prisma/migrations/migration_lock.toml new file mode 100644 index 0000000..2fe25d8 --- /dev/null +++ b/packages/database/prisma/migrations/migration_lock.toml @@ -0,0 +1 @@ +provider = "postgresql" diff --git a/packages/database/prisma/schema.prisma b/packages/database/prisma/schema.prisma new file mode 100644 index 0000000..7008ed9 --- /dev/null +++ b/packages/database/prisma/schema.prisma @@ -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]) +} diff --git a/packages/database/src/index.ts b/packages/database/src/index.ts new file mode 100644 index 0000000..9cc1797 --- /dev/null +++ b/packages/database/src/index.ts @@ -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 }), + }); +} diff --git a/packages/database/src/password.ts b/packages/database/src/password.ts new file mode 100644 index 0000000..b3a0e02 --- /dev/null +++ b/packages/database/src/password.ts @@ -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); +} diff --git a/packages/database/src/seed.ts b/packages/database/src/seed.ts new file mode 100644 index 0000000..9530a3c --- /dev/null +++ b/packages/database/src/seed.ts @@ -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: 'head@merchantflow.test', + name: 'Elena Carter', + role: 'HEAD_OF_SALES' as const, + }, + { + id: 'user-compliance', + email: 'compliance@merchantflow.test', + name: 'Pavel Sokolov', + role: 'COMPLIANCE_OFFICER' as const, + }, + { + id: 'user-manager1', + email: 'manager1@merchantflow.test', + name: 'Alex Morgan', + role: 'ACCOUNT_MANAGER' as const, + }, + { + id: 'user-manager2', + email: 'manager2@merchantflow.test', + 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(); +} diff --git a/packages/database/tsconfig.json b/packages/database/tsconfig.json new file mode 100644 index 0000000..3bbc36f --- /dev/null +++ b/packages/database/tsconfig.json @@ -0,0 +1,11 @@ +{ + "extends": "../../tsconfig.base.json", + "compilerOptions": { + "module": "NodeNext", + "moduleResolution": "NodeNext", + "rootDir": "src", + "outDir": "dist", + "declaration": true + }, + "include": ["src"] +} diff --git a/packages/ui/components.json b/packages/ui/components.json new file mode 100644 index 0000000..42a587d --- /dev/null +++ b/packages/ui/components.json @@ -0,0 +1,20 @@ +{ + "$schema": "https://ui.shadcn.com/schema.json", + "style": "base-nova", + "rsc": false, + "tsx": true, + "tailwind": { + "config": "", + "css": "src/styles/globals.css", + "baseColor": "neutral", + "cssVariables": true + }, + "iconLibrary": "lucide", + "aliases": { + "components": "@merchantflow/ui/components", + "hooks": "@merchantflow/ui/hooks", + "lib": "@merchantflow/ui/lib", + "utils": "@merchantflow/ui/lib/utils", + "ui": "@merchantflow/ui/components" + } +} diff --git a/packages/ui/package.json b/packages/ui/package.json new file mode 100644 index 0000000..2c58346 --- /dev/null +++ b/packages/ui/package.json @@ -0,0 +1,35 @@ +{ + "name": "@merchantflow/ui", + "version": "0.0.0", + "private": true, + "type": "module", + "exports": { + "./globals.css": "./src/styles/globals.css", + "./components/*": "./src/components/*.tsx", + "./lib/*": "./src/lib/*.ts", + "./hooks/*": "./src/hooks/*.ts" + }, + "scripts": { + "build": "tsc --noEmit", + "typecheck": "tsc --noEmit" + }, + "dependencies": { + "@base-ui/react": "1.8.0", + "class-variance-authority": "0.7.1", + "clsx": "2.1.1", + "lucide-react": "1.48.0", + "tailwind-merge": "3.7.0", + "tw-animate-css": "1.4.0" + }, + "peerDependencies": { + "react": "^19.0.0", + "react-dom": "^19.0.0" + }, + "devDependencies": { + "@types/react": "19.3.0", + "@types/react-dom": "19.3.0", + "react": "19.3.0", + "react-dom": "19.3.0", + "tailwindcss": "4.3.3" + } +} diff --git a/packages/ui/src/components/badge.tsx b/packages/ui/src/components/badge.tsx new file mode 100644 index 0000000..40305c0 --- /dev/null +++ b/packages/ui/src/components/badge.tsx @@ -0,0 +1,48 @@ +import { mergeProps } from '@base-ui/react/merge-props'; +import { useRender } from '@base-ui/react/use-render'; +import { cva, type VariantProps } from 'class-variance-authority'; +import { cn } from '@merchantflow/ui/lib/utils'; + +const badgeVariants = cva( + 'group/badge inline-flex h-5 w-fit shrink-0 items-center justify-center gap-1 overflow-hidden rounded-4xl border border-transparent px-2 py-0.5 text-xs font-medium whitespace-nowrap transition-[color,background-color,box-shadow,transform] focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 has-data-[icon=inline-end]:pr-1.5 has-data-[icon=inline-start]:pl-1.5 aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 [&>svg]:pointer-events-none [&>svg]:size-3!', + { + variants: { + variant: { + default: 'bg-primary text-primary-foreground [a]:hover:bg-primary/80', + secondary: 'bg-secondary text-secondary-foreground [a]:hover:bg-secondary/80', + destructive: + 'bg-destructive/10 text-destructive focus-visible:ring-destructive/20 dark:bg-destructive/20 dark:focus-visible:ring-destructive/40 [a]:hover:bg-destructive/20', + outline: 'border-border text-foreground [a]:hover:bg-muted [a]:hover:text-muted-foreground', + ghost: 'hover:bg-muted hover:text-muted-foreground dark:hover:bg-muted/50', + link: 'text-primary underline-offset-4 hover:underline', + }, + }, + defaultVariants: { + variant: 'default', + }, + }, +); + +function Badge({ + className, + variant = 'default', + render, + ...props +}: useRender.ComponentProps<'span'> & VariantProps) { + return useRender({ + defaultTagName: 'span', + props: mergeProps<'span'>( + { + className: cn(badgeVariants({ variant }), className), + }, + props, + ), + render, + state: { + slot: 'badge', + variant, + }, + }); +} + +export { Badge, badgeVariants }; diff --git a/packages/ui/src/components/button.tsx b/packages/ui/src/components/button.tsx new file mode 100644 index 0000000..0991f7a --- /dev/null +++ b/packages/ui/src/components/button.tsx @@ -0,0 +1,57 @@ +import { Button as ButtonPrimitive } from '@base-ui/react/button'; +import { cva, type VariantProps } from 'class-variance-authority'; +import { cn } from '@merchantflow/ui/lib/utils'; + +const buttonVariants = cva( + "pressable group/button inline-flex shrink-0 items-center justify-center rounded-lg border border-transparent bg-clip-padding text-sm font-medium whitespace-nowrap transition-[color,background-color,box-shadow,transform] outline-none select-none focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 disabled:pointer-events-none disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4", + { + variants: { + variant: { + default: 'bg-primary text-primary-foreground hover:bg-primary/80', + outline: + 'border-border bg-background hover:bg-muted hover:text-foreground aria-expanded:bg-muted aria-expanded:text-foreground dark:border-input dark:bg-input/30 dark:hover:bg-input/50', + secondary: + 'bg-secondary text-secondary-foreground hover:bg-[color-mix(in_oklch,var(--secondary),var(--foreground)_5%)] aria-expanded:bg-secondary aria-expanded:text-secondary-foreground', + ghost: + 'hover:bg-muted hover:text-foreground aria-expanded:bg-muted aria-expanded:text-foreground dark:hover:bg-muted/50', + destructive: + 'bg-destructive/10 text-destructive hover:bg-destructive/20 focus-visible:border-destructive/40 focus-visible:ring-destructive/20 dark:bg-destructive/20 dark:hover:bg-destructive/30 dark:focus-visible:ring-destructive/40', + link: 'text-foreground underline-offset-4 hover:underline', + }, + size: { + default: + 'h-11 gap-2 px-4 has-data-[icon=inline-end]:pr-2 has-data-[icon=inline-start]:pl-2', + xs: "h-11 gap-1 rounded-[min(var(--radius-md),10px)] px-2 text-xs in-data-[slot=button-group]:rounded-lg has-data-[icon=inline-end]:pr-1.5 has-data-[icon=inline-start]:pl-1.5 [&_svg:not([class*='size-'])]:size-3", + sm: "h-11 gap-1 rounded-[min(var(--radius-md),12px)] px-2.5 text-[0.8rem] in-data-[slot=button-group]:rounded-lg has-data-[icon=inline-end]:pr-1.5 has-data-[icon=inline-start]:pl-1.5 [&_svg:not([class*='size-'])]:size-3.5", + lg: 'h-12 gap-2 px-5 has-data-[icon=inline-end]:pr-2 has-data-[icon=inline-start]:pl-2', + icon: 'size-11', + 'icon-xs': + "size-11 rounded-[min(var(--radius-md),10px)] in-data-[slot=button-group]:rounded-lg [&_svg:not([class*='size-'])]:size-3", + 'icon-sm': + 'size-11 rounded-[min(var(--radius-md),12px)] in-data-[slot=button-group]:rounded-lg', + 'icon-lg': 'size-12', + }, + }, + defaultVariants: { + variant: 'default', + size: 'default', + }, + }, +); + +function Button({ + className, + variant = 'default', + size = 'default', + ...props +}: ButtonPrimitive.Props & VariantProps) { + return ( + + ); +} + +export { Button, buttonVariants }; diff --git a/packages/ui/src/components/card.tsx b/packages/ui/src/components/card.tsx new file mode 100644 index 0000000..a6183f7 --- /dev/null +++ b/packages/ui/src/components/card.tsx @@ -0,0 +1,87 @@ +import * as React from 'react'; +import { cn } from '@merchantflow/ui/lib/utils'; + +function Card({ + className, + size = 'default', + ...props +}: React.ComponentProps<'div'> & { size?: 'default' | 'sm' }) { + return ( +
img:first-child]:pt-0 data-[size=sm]:[--card-spacing:--spacing(3)] data-[size=sm]:has-data-[slot=card-footer]:pb-0 *:[img:first-child]:rounded-t-xl *:[img:last-child]:rounded-b-xl', + className, + )} + {...props} + /> + ); +} + +function CardHeader({ className, ...props }: React.ComponentProps<'div'>) { + return ( +
+ ); +} + +function CardTitle({ className, ...props }: React.ComponentProps<'div'>) { + return ( +
+ ); +} + +function CardDescription({ className, ...props }: React.ComponentProps<'div'>) { + return ( +
+ ); +} + +function CardAction({ className, ...props }: React.ComponentProps<'div'>) { + return ( +
+ ); +} + +function CardContent({ className, ...props }: React.ComponentProps<'div'>) { + return ( +
+ ); +} + +function CardFooter({ className, ...props }: React.ComponentProps<'div'>) { + return ( +
+ ); +} + +export { Card, CardHeader, CardFooter, CardTitle, CardAction, CardDescription, CardContent }; diff --git a/packages/ui/src/components/checkbox.tsx b/packages/ui/src/components/checkbox.tsx new file mode 100644 index 0000000..cb28f41 --- /dev/null +++ b/packages/ui/src/components/checkbox.tsx @@ -0,0 +1,25 @@ +import { Checkbox as CheckboxPrimitive } from '@base-ui/react/checkbox'; +import { cn } from '@merchantflow/ui/lib/utils'; +import { CheckIcon } from 'lucide-react'; + +function Checkbox({ className, ...props }: CheckboxPrimitive.Root.Props) { + return ( + + + + + + ); +} + +export { Checkbox }; diff --git a/packages/ui/src/components/form-field.tsx b/packages/ui/src/components/form-field.tsx new file mode 100644 index 0000000..d97d61f --- /dev/null +++ b/packages/ui/src/components/form-field.tsx @@ -0,0 +1,25 @@ +export function FormField({ + id, + label, + error, + children, +}: { + id: string; + label: string; + error?: string; + children: React.ReactNode; +}) { + return ( +
+ + {children} + {error && ( + + )} +
+ ); +} diff --git a/packages/ui/src/components/input.tsx b/packages/ui/src/components/input.tsx new file mode 100644 index 0000000..da0b390 --- /dev/null +++ b/packages/ui/src/components/input.tsx @@ -0,0 +1,19 @@ +import * as React from 'react'; +import { Input as InputPrimitive } from '@base-ui/react/input'; +import { cn } from '@merchantflow/ui/lib/utils'; + +function Input({ className, type, ...props }: React.ComponentProps<'input'>) { + return ( + + ); +} + +export { Input }; diff --git a/packages/ui/src/components/native-select.tsx b/packages/ui/src/components/native-select.tsx new file mode 100644 index 0000000..e99b9d5 --- /dev/null +++ b/packages/ui/src/components/native-select.tsx @@ -0,0 +1,54 @@ +import * as React from 'react'; +import { cn } from '@merchantflow/ui/lib/utils'; +import { ChevronDownIcon } from 'lucide-react'; + +type NativeSelectProps = Omit, 'size'> & { + size?: 'sm' | 'default'; +}; + +function NativeSelect({ className, size = 'default', ...props }: NativeSelectProps) { + return ( +
+