Implemented the database, authentication, access rules, and seed data

This commit is contained in:
Oleksandr Prokhorenko
2026-09-24 19:08:55 +03:00
parent 3aa47d825f
commit 5de240fda3
27 changed files with 3793 additions and 277 deletions
+44 -15
View File
@@ -1,6 +1,6 @@
# MerchantFlow # 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. A local Merchant Onboarding CRM for a fictional crypto-payment provider. The workspace provides database-backed login, role-scoped reads and writes, commercial onboarding, Compliance reviews, and a responsive English/Russian UI.
## Start locally ## Start locally
@@ -20,20 +20,20 @@ Open **http://localhost:5173**. The API runs at http://localhost:3001/api; Vite
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`. 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. `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, edits, records and history are preserved. An additive upgrade enriches recognized foundation fixtures once; edited or unrecognized legacy fixtures are reported and left untouched, without inferred approval. `pnpm db:down` stops the project services but preserves development data.
## Demo accounts ## Demo accounts
All four accounts use **`MerchantFlow123!`**. The login page has credential-fill buttons; sign-in still goes through the API. All four accounts use **`MerchantFlow123!`**. The login page has credential-fill buttons; sign-in still goes through the API.
| Email | Role | Visibility | | Email | Role | Visibility |
| ------------------------------ | ----------------------------- | ------------------------------------------------- | | ------------------------------ | ----------------------------- | ------------------------------------------- |
| `[email protected]` | Head of Sales | All 18 merchants | | `[email protected]` | Head of Sales | All 45 merchants |
| `[email protected]` | Compliance Officer | 4 merchants currently in KYB or Compliance Review | | `[email protected]` | Compliance Officer | All 45 merchants; personal compliance tasks |
| `manager1@merchantflow.test` | Account Manager · Alex Morgan | 9 assigned merchants | | `alex@merchantflow.test` | Account Manager · Alex Morgan | 20 assigned merchants |
| `manager2@merchantflow.test` | Account Manager · Maria Chen | 9 assigned merchants | | `sam@merchantflow.test` | Account Manager · Sam Taylor | 20 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. Five New Leads are unassigned. Only the Head can assign or reassign merchants to managers. 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 ## Workspace structure
@@ -47,7 +47,7 @@ docs Product brief and implementation checklist
tests Playwright journeys 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 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. USD estimates use PostgreSQL `DECIMAL(18,2)` and decimal strings in JSON. Owner details may be null for unassigned leads.
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. 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.
@@ -70,15 +70,15 @@ Public routes are `/` and `/login`. CRM routes are `/app`, `/app/merchants`, `/a
| GET | `/api/tasks?filter=ALL` | ALL / OPEN / OVERDUE / UPCOMING / DONE | | GET | `/api/tasks?filter=ALL` | ALL / OPEN / OVERDUE / UPCOMING / DONE |
| GET | `/api/review-queue` | Compliance-only, oldest review first | | 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. 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. Every mutation, including login/logout, requires an exact trusted `Origin` and rejects cross-site Fetch Metadata. Local login limits allow 100 attempts per IP and 20 per normalized email per five minutes, include `Retry-After`, and bound the in-memory bucket map to 10,000 entries. These limits are designed for this single-process local prototype. The UI clears private query caches on logout, login and API session rejection.
## Data and localization ## 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 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. The seed creates 45 merchants, 90 commercial tasks, additional personal compliance tasks, interactions, document checklists and change history, review cycles and chronological stage history spanning 90 days. Fresh fixtures include 7 New Leads, 5 Contacted, 5 Qualified, 6 KYB, 6 Compliance Review, 4 Integration, 4 Testing, 5 Live and 3 Rejected. 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 interactions and immutable audit 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. 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. Checklist collection, review decisions, interaction logging and task management are available from merchant details. Reminders are derived from stored dates and refresh inside the app, without background notification infrastructure.
## Verification ## Verification
@@ -93,7 +93,7 @@ pnpm test:e2e
pnpm format:check 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. 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. Each runner recreates only the disposable `db-test` service to isolate workflow mutations; development data and the `db` service are never reset.
Health smoke check while `pnpm dev` is running: Health smoke check while `pnpm dev` is running:
@@ -104,4 +104,33 @@ 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. 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. The [product brief](docs/product-brief.md) and [implementation checklist](docs/implementation-checklist.md) record the accepted scope and verification results. Merchant editing, ownership handoff, stage/review actions and task management are implemented. Uploads, merchant self-service, payments, external KYB/reminders and deployment remain out of scope.
## Editing and workflow rules
Head of Sales can edit commercial details for the portfolio, assign/reassign Account Managers, collect KYB documents, and manage commercial activities/tasks. Managers can perform commercial actions only for currently assigned merchants and cannot change ownership. Compliance can read merchant context and KYB across every stage, record reviews and KYB notes, and manage only personal compliance tasks. Head and managers can view related compliance tasks but cannot change them. Query predicates enforce these scopes on lists, search, totals, dashboard, detail children, and mutation targets.
Only adjacent commercial stage advances are accepted. A manager must be assigned before leaving New Lead. In KYB, Sales records missing/received documents. Submission requires all four documents to have received-history evidence and creates one pending review. Company/KYB fields freeze while that review is pending. Compliance can approve (atomically advancing to Integration), reject with a reason, or request document-specific corrections (returning to KYB). Resubmission creates a new review cycle. Decisions and system history cannot be edited.
Approval permanently locks the reviewed company identity, website, country, industry and KYB items in this milestone. Contact details, estimated volume, source and authorized assignment remain editable. Either the Head or assigned manager may move Integration → Testing → Live when the current company/checklist matches valid approval evidence. Live and Rejected have no outgoing stage actions. Reassignment transfers open commercial tasks to the new manager; completed task attribution and Compliance ownership remain intact.
All mutation bodies carry the merchant's current integer `version`. Transactions conditionally claim that version and recheck database ownership before writing the merchant or any child records. A stale action returns `409 CONFLICT`; the UI refreshes before another attempt. Hidden resources return 404, forbidden visible actions return 403, and invalid workflow actions return 409. General edits reject unexpected fields such as owner, stage, actor or reviewer.
| Method | Endpoint | Purpose |
| ------------ | ----------------------------------------------- | ------------------------------------------------------------ |
| GET | `/api/users/assignable-managers` | Head-only manager ID/name/email lookup |
| PATCH | `/api/merchants/:id` | Commercial details; reviewed fields lock during/after review |
| PATCH | `/api/merchants/:id/assignment` | Head-only ownership handoff |
| POST | `/api/merchants/:id/transitions` | Adjacent commercial stage action |
| PATCH | `/api/merchants/:id/checklist/:itemId` | Sales collection state and note in KYB |
| POST | `/api/merchants/:id/reviews/:reviewId/decision` | Compliance approval, rejection or corrections |
| POST / PATCH | `/api/merchants/:id/activities[/:activityId]` | Commercial interactions or Compliance KYB notes |
| POST / PATCH | `/api/merchants/:id/tasks[/:taskId]` | Authorized task creation/editing/completion |
No staff registration, merchant creation/deletion UI, file uploads, payments, external notifications, or deployment is included. Authentication credentials never enter localStorage; only the UI language does.
## Seed upgrade behavior
`DemoSeedState` anchors fixture dates and `DemoSeedRecord` tracks enrichment version 2. A PostgreSQL advisory transaction lock serializes concurrent seeds. Existing completed fixtures are skipped entirely, including their children. Recognized legacy merchant fields, notes, stages and timestamps remain intact while missing company fields, interactions, checklist history and review evidence are added once. Legacy matching checks the original merchant, document, note, task and stage-event values before inferring fictional historical approvals. Modified or unrecognized legacy fixtures are reported and preserved; they receive no invented approval. Such records may remain incomplete until explicitly handled through the workflow.
The old manager account IDs are retained while the original addresses become `[email protected]` and `[email protected]`, and the original Maria demo identity becomes Sam Taylor. Existing password hashes remain unchanged; the documented password applies to newly created and unchanged demo accounts.
+41 -1
View File
@@ -1,14 +1,54 @@
import type { User } from '@merchantflow/contracts'; import type { User } from '@merchantflow/contracts';
import type { Prisma } from '@merchantflow/database'; import type { Prisma } from '@merchantflow/database';
import { successfulStages, type Status } from '@merchantflow/contracts';
import { ApiError } from './shared.js';
export function merchantScope(user: User): Prisma.MerchantWhereInput { export function merchantScope(user: User): Prisma.MerchantWhereInput {
switch (user.role) { switch (user.role) {
case 'HEAD_OF_SALES': case 'HEAD_OF_SALES':
return {}; return {};
case 'COMPLIANCE_OFFICER': case 'COMPLIANCE_OFFICER':
return { status: { in: ['KYB', 'COMPLIANCE_REVIEW'] } }; return {};
case 'ACCOUNT_MANAGER': case 'ACCOUNT_MANAGER':
return { ownerId: user.id }; return { ownerId: user.id };
default: default:
return { id: '__no_access__' }; return { id: '__no_access__' };
} }
} }
export function taskScope(user: User): Prisma.TaskWhereInput {
return {
merchant: merchantScope(user),
...(user.role === 'COMPLIANCE_OFFICER' ? { assigneeId: user.id, kind: 'COMPLIANCE' } : {}),
};
}
export function requireSales(user: User) {
if (!['HEAD_OF_SALES', 'ACCOUNT_MANAGER'].includes(user.role))
throw new ApiError('FORBIDDEN', 403);
}
export function capabilities(
user: User,
merchant: { status: Status; ownerId: string | null; reviews: { decision: string }[] },
) {
const sales =
user.role === 'HEAD_OF_SALES' ||
(user.role === 'ACCOUNT_MANAGER' && merchant.ownerId === user.id);
const locked = merchant.reviews.some((review) =>
['PENDING', 'APPROVED'].includes(review.decision),
);
const index = successfulStages.findIndex((stage) => stage === merchant.status);
return {
editCommercial: sales,
editIdentity: sales && !locked,
assign: user.role === 'HEAD_OF_SALES',
collectChecklist: sales && merchant.status === 'KYB' && !locked,
review: user.role === 'COMPLIANCE_OFFICER' && merchant.status === 'COMPLIANCE_REVIEW',
activityKinds:
user.role === 'COMPLIANCE_OFFICER'
? (['KYB_NOTE'] as const)
: (['NOTE', 'CALL', 'EMAIL', 'MEETING'] as const),
manageTaskKind: user.role === 'COMPLIANCE_OFFICER' ? 'COMPLIANCE' : 'COMMERCIAL',
nextStage:
sales && merchant.ownerId && index >= 0 && merchant.status !== 'COMPLIANCE_REVIEW'
? (successfulStages[index + 1] ?? null)
: null,
};
}
+2 -1
View File
@@ -12,6 +12,7 @@ import cookieParser from 'cookie-parser';
import { createDatabase, PrismaClient } from '@merchantflow/database'; import { createDatabase, PrismaClient } from '@merchantflow/database';
import { AuthController, AuthService, SessionGuard } from './auth.js'; import { AuthController, AuthService, SessionGuard } from './auth.js';
import { CrmController } from './crm.js'; import { CrmController } from './crm.js';
import { WorkflowController } from './workflow.js';
import { DATABASE, ApiError, ErrorFilter } from './shared.js'; import { DATABASE, ApiError, ErrorFilter } from './shared.js';
import { env } from './env.js'; import { env } from './env.js';
@Controller('health') @Controller('health')
@@ -34,7 +35,7 @@ class DatabaseLifecycle implements OnApplicationShutdown {
} }
} }
@Module({ @Module({
controllers: [HealthController, AuthController, CrmController], controllers: [HealthController, AuthController, CrmController, WorkflowController],
providers: [ providers: [
{ provide: DATABASE, useFactory: () => createDatabase(env.DATABASE_URL) }, { provide: DATABASE, useFactory: () => createDatabase(env.DATABASE_URL) },
DatabaseLifecycle, DatabaseLifecycle,
+16 -8
View File
@@ -45,17 +45,23 @@ export class AuthService {
async login(body: unknown, request: Request, response: Response) { async login(body: unknown, request: Request, response: Response) {
this.checkOrigin(request); this.checkOrigin(request);
const input = loginSchema.parse(body); const input = loginSchema.parse(body);
const key = request.ip ?? 'local';
const now = Date.now(); const now = Date.now();
for (const [ip, value] of this.attempts) if (value.until <= now) this.attempts.delete(ip); for (const [key, value] of this.attempts) if (value.until <= now) this.attempts.delete(key);
const attempt = this.attempts.get(key) ?? { count: 0, until: now + 300000 }; for (const [key, limit] of [
if (attempt.count >= 20) throw new ApiError('TOO_MANY_REQUESTS', 429); [`ip:${request.ip ?? 'local'}`, 100],
attempt.count++; [`email:${input.email}`, 20],
this.attempts.set(key, attempt); ] as const) {
const attempt = this.attempts.get(key) ?? { count: 0, until: now + 300000 };
if (attempt.count >= limit || (!this.attempts.has(key) && this.attempts.size >= 10000)) {
response.setHeader('Retry-After', Math.max(1, Math.ceil((attempt.until - now) / 1000)));
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 user = await this.db.user.findUnique({ where: { email: input.email } });
const valid = verifyPassword(input.password, user?.passwordHash ?? dummyHash); const valid = verifyPassword(input.password, user?.passwordHash ?? dummyHash);
if (!user || !valid) throw new ApiError('INVALID_CREDENTIALS', 401); if (!user || !valid) throw new ApiError('INVALID_CREDENTIALS', 401);
this.attempts.delete(key);
await this.revoke(request.cookies?.[cookieName]); await this.revoke(request.cookies?.[cookieName]);
await this.db.session.deleteMany({ where: { expiresAt: { lt: new Date() } } }); await this.db.session.deleteMany({ where: { expiresAt: { lt: new Date() } } });
const token = randomBytes(32).toString('hex'); const token = randomBytes(32).toString('hex');
@@ -77,7 +83,8 @@ export class AuthService {
allowed.add(origin.origin); allowed.add(origin.origin);
} }
if ( if (
(req.headers.origin && !allowed.has(req.headers.origin)) || !req.headers.origin ||
!allowed.has(req.headers.origin) ||
req.headers['sec-fetch-site'] === 'cross-site' req.headers['sec-fetch-site'] === 'cross-site'
) )
throw new ApiError('FORBIDDEN', 403); throw new ApiError('FORBIDDEN', 403);
@@ -94,6 +101,7 @@ export class SessionGuard implements CanActivate {
async canActivate(context: ExecutionContext) { async canActivate(context: ExecutionContext) {
const req = context.switchToHttp().getRequest<AuthRequest>(); const req = context.switchToHttp().getRequest<AuthRequest>();
req.user = await this.auth.current(req.cookies?.[cookieName]); req.user = await this.auth.current(req.cookies?.[cookieName]);
if (!['GET', 'HEAD', 'OPTIONS'].includes(req.method)) this.auth.checkOrigin(req);
return true; return true;
} }
} }
+83 -8
View File
@@ -3,7 +3,7 @@ import { PrismaClient, type Prisma } from '@merchantflow/database';
import { statuses, merchantQuerySchema, taskQuerySchema } from '@merchantflow/contracts'; import { statuses, merchantQuerySchema, taskQuerySchema } from '@merchantflow/contracts';
import { SessionGuard } from './auth.js'; import { SessionGuard } from './auth.js';
import { DATABASE, ApiError, type AuthRequest } from './shared.js'; import { DATABASE, ApiError, type AuthRequest } from './shared.js';
import { merchantScope } from './access.js'; import { capabilities, merchantScope, taskScope } from './access.js';
const merchantSelect = { const merchantSelect = {
id: true, id: true,
name: true, name: true,
@@ -12,6 +12,16 @@ const merchantSelect = {
country: true, country: true,
contactName: true, contactName: true,
contactEmail: true, contactEmail: true,
legalName: true,
registrationNumber: true,
address: true,
contactPhone: true,
contactTitle: true,
estimatedMonthlyVolumeUsd: true,
source: true,
version: true,
updatedAt: true,
ownerId: true,
status: true, status: true,
createdAt: true, createdAt: true,
stageEnteredAt: true, stageEnteredAt: true,
@@ -30,16 +40,38 @@ const taskSelect = {
id: true, id: true,
title: true, title: true,
status: true, status: true,
kind: true,
createdAt: true,
updatedAt: true,
dueAt: true, dueAt: true,
remindAt: true, remindAt: true,
completedAt: true, completedAt: true,
merchant: { select: { id: true, name: true } }, merchant: { select: { id: true, name: true } },
assignee: { select: { name: true } }, assignee: { select: { id: true, name: true } },
creator: { select: { name: true } },
completedBy: { select: { name: true } },
} as const;
const activitySelect = {
id: true,
kind: true,
text: true,
occurredAt: true,
updatedAt: true,
actor: { select: { id: true, name: true } },
merchant: { select: { id: true, name: true } },
} as const; } as const;
@UseGuards(SessionGuard) @UseGuards(SessionGuard)
@Controller() @Controller()
export class CrmController { export class CrmController {
constructor(@Inject(DATABASE) private readonly db: PrismaClient) {} constructor(@Inject(DATABASE) private readonly db: PrismaClient) {}
@Get('users/assignable-managers') managers(@Req() req: AuthRequest) {
if (req.user.role !== 'HEAD_OF_SALES') throw new ApiError('FORBIDDEN', 403);
return this.db.user.findMany({
where: { role: 'ACCOUNT_MANAGER' },
select: { id: true, name: true, email: true },
orderBy: { name: 'asc' },
});
}
@Get('merchants') async merchants(@Req() req: AuthRequest, @Query() query: unknown) { @Get('merchants') async merchants(@Req() req: AuthRequest, @Query() query: unknown) {
const { page, search, status } = merchantQuerySchema.parse(query); const { page, search, status } = merchantQuerySchema.parse(query);
const where: Prisma.MerchantWhereInput = { const where: Prisma.MerchantWhereInput = {
@@ -52,6 +84,9 @@ export class CrmController {
OR: [ OR: [
{ name: { contains: search, mode: 'insensitive' as const } }, { name: { contains: search, mode: 'insensitive' as const } },
{ contactEmail: { contains: search, mode: 'insensitive' as const } }, { contactEmail: { contains: search, mode: 'insensitive' as const } },
{ legalName: { contains: search, mode: 'insensitive' as const } },
{ contactName: { contains: search, mode: 'insensitive' as const } },
{ website: { contains: search, mode: 'insensitive' as const } },
], ],
}, },
] ]
@@ -76,7 +111,23 @@ export class CrmController {
select: { select: {
...merchantSelect, ...merchantSelect,
checklist: { checklist: {
select: { id: true, documentCode: true, state: true, note: true }, select: {
id: true,
documentCode: true,
state: true,
note: true,
changes: {
select: {
id: true,
fromState: true,
toState: true,
note: true,
occurredAt: true,
actor: { select: { name: true } },
},
orderBy: [{ occurredAt: 'desc' }, { id: 'asc' }],
},
},
orderBy: { documentCode: 'asc' }, orderBy: { documentCode: 'asc' },
}, },
notes: { notes: {
@@ -84,11 +135,25 @@ export class CrmController {
orderBy: { createdAt: 'desc' }, orderBy: { createdAt: 'desc' },
}, },
events: { select: eventSelect, orderBy: { occurredAt: 'desc' } }, events: { select: eventSelect, orderBy: { occurredAt: 'desc' } },
tasks: { select: taskSelect, orderBy: { dueAt: 'asc' } }, tasks: { where: taskScope(req.user), select: taskSelect, orderBy: { dueAt: 'asc' } },
activities: { select: activitySelect, orderBy: [{ occurredAt: 'desc' }, { id: 'asc' }] },
reviews: {
select: {
id: true,
cycle: true,
decision: true,
reason: true,
submittedAt: true,
decidedAt: true,
submittedBy: { select: { name: true } },
reviewer: { select: { name: true } },
},
orderBy: { cycle: 'desc' },
},
}, },
}); });
if (!merchant) throw new ApiError('NOT_FOUND', 404); if (!merchant) throw new ApiError('NOT_FOUND', 404);
return merchant; return { ...merchant, capabilities: capabilities(req.user, merchant) };
} }
@Get('pipeline') pipeline(@Req() req: AuthRequest) { @Get('pipeline') pipeline(@Req() req: AuthRequest) {
return this.db.merchant.findMany({ return this.db.merchant.findMany({
@@ -99,7 +164,7 @@ export class CrmController {
} }
@Get('tasks') tasks(@Req() req: AuthRequest, @Query() query: unknown) { @Get('tasks') tasks(@Req() req: AuthRequest, @Query() query: unknown) {
const { filter } = taskQuerySchema.parse(query); const { filter } = taskQuerySchema.parse(query);
const where: Prisma.TaskWhereInput = { merchant: merchantScope(req.user) }; const where: Prisma.TaskWhereInput = taskScope(req.user);
if (filter === 'DONE') where.status = 'DONE'; if (filter === 'DONE') where.status = 'DONE';
if (['OPEN', 'OVERDUE', 'UPCOMING'].includes(filter)) where.status = 'OPEN'; if (['OPEN', 'OVERDUE', 'UPCOMING'].includes(filter)) where.status = 'OPEN';
if (filter === 'OVERDUE') where.dueAt = { lt: new Date() }; if (filter === 'OVERDUE') where.dueAt = { lt: new Date() };
@@ -134,10 +199,13 @@ export class CrmController {
distribution, distribution,
recentEvents, recentEvents,
upcomingTasks, upcomingTasks,
recentActivities,
] = await this.db.$transaction([ ] = await this.db.$transaction([
this.db.merchant.count({ where: scope }), this.db.merchant.count({ where: scope }),
this.db.merchant.count({ where: { AND: [scope, { status: 'COMPLIANCE_REVIEW' }] } }), 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.task.count({
where: { ...taskScope(req.user), status: 'OPEN', dueAt: { lt: new Date() } },
}),
this.db.statusEvent.count({ this.db.statusEvent.count({
where: { where: {
merchant: scope, merchant: scope,
@@ -153,11 +221,17 @@ export class CrmController {
take: 6, take: 6,
}), }),
this.db.task.findMany({ this.db.task.findMany({
where: { merchant: scope, status: 'OPEN' }, where: { ...taskScope(req.user), status: 'OPEN' },
select: taskSelect, select: taskSelect,
orderBy: { dueAt: 'asc' }, orderBy: { dueAt: 'asc' },
take: 4, take: 4,
}), }),
this.db.activity.findMany({
where: { merchant: scope },
select: activitySelect,
orderBy: [{ occurredAt: 'desc' }, { id: 'asc' }],
take: 8,
}),
]); ]);
return { return {
merchantCount, merchantCount,
@@ -170,6 +244,7 @@ export class CrmController {
})), })),
recentEvents, recentEvents,
upcomingTasks, upcomingTasks,
recentActivities,
}; };
} }
} }
+386
View File
@@ -0,0 +1,386 @@
import { Body, Controller, Inject, Param, Patch, Post, Req, UseGuards } from '@nestjs/common';
import {
PrismaClient,
type Prisma,
checklistComplete,
reviewSnapshot,
reviewedFields,
snapshotsEqual,
} from '@merchantflow/database';
import {
activityInputSchema,
assignmentSchema,
checklistEditSchema,
merchantEditSchema,
reviewDecisionSchema,
taskInputSchema,
transitionSchema,
successfulStages,
} from '@merchantflow/contracts';
import { SessionGuard } from './auth.js';
import { capabilities, merchantScope, requireSales, taskScope } from './access.js';
import { ApiError, DATABASE, type AuthRequest } from './shared.js';
const evidenceInclude = {
checklist: { include: { changes: { orderBy: { occurredAt: 'asc' as const } } } },
reviews: {
include: { reviewer: { select: { role: true } } },
orderBy: { cycle: 'desc' as const },
},
} as const;
type Evidence = Prisma.MerchantGetPayload<{ include: typeof evidenceInclude }>;
function receivedHistory(merchant: Evidence, at: Date) {
return (
checklistComplete(merchant.checklist) &&
merchant.checklist.every(
(item) =>
item.changes.filter((change) => change.occurredAt <= at).at(-1)?.toState === 'RECEIVED',
)
);
}
function validApproval(merchant: Evidence) {
const review = merchant.reviews[0];
return (
review?.decision === 'APPROVED' &&
review.reviewer?.role === 'COMPLIANCE_OFFICER' &&
review.decidedAt &&
review.decidedAt >= review.submittedAt &&
receivedHistory(merchant, review.submittedAt) &&
snapshotsEqual(review.snapshot, reviewSnapshot(merchant))
);
}
@UseGuards(SessionGuard)
@Controller('merchants')
export class WorkflowController {
constructor(@Inject(DATABASE) private readonly db: PrismaClient) {}
private async mutate(
req: AuthRequest,
id: string,
version: number,
action: (tx: Prisma.TransactionClient, merchant: Evidence) => Promise<void>,
) {
await this.db.$transaction(async (tx) => {
const scope = { AND: [merchantScope(req.user), { id }] };
const merchant = await tx.merchant.findFirst({ where: scope, include: evidenceInclude });
if (!merchant) throw new ApiError('NOT_FOUND', 404);
// This conditional write locks the parent and rechecks ownership/version after any wait.
// Every child mutation and ownership change takes the same lock before writing.
const claimed = await tx.merchant.updateMany({
where: { AND: [scope, { version }] },
data: { version: { increment: 1 } },
});
if (!claimed.count) {
if (!(await tx.merchant.findFirst({ where: scope, select: { id: true } })))
throw new ApiError('NOT_FOUND', 404);
throw new ApiError('CONFLICT', 409);
}
await action(tx, merchant);
});
return { ok: true };
}
private async audit(
tx: Prisma.TransactionClient,
req: AuthRequest,
merchantId: string,
text: string,
metadata?: Prisma.InputJsonValue,
) {
await tx.activity.create({
data: { merchantId, actorId: req.user.id, kind: 'AUDIT', text, metadata },
});
}
private async stage(
tx: Prisma.TransactionClient,
req: AuthRequest,
merchant: Evidence,
toStatus: Evidence['status'],
note?: string,
) {
const occurredAt = new Date();
await tx.merchant.updateMany({
where: { AND: [merchantScope(req.user), { id: merchant.id }] },
data: { status: toStatus, stageEnteredAt: occurredAt },
});
await tx.statusEvent.create({
data: {
merchantId: merchant.id,
actorId: req.user.id,
fromStatus: merchant.status,
toStatus,
occurredAt,
note,
},
});
await this.audit(tx, req, merchant.id, `${merchant.status} → ${toStatus}`, {
fromStatus: merchant.status,
toStatus,
note: note ?? null,
});
}
@Patch(':id') edit(@Req() req: AuthRequest, @Param('id') id: string, @Body() body: unknown) {
const { version, ...data } = merchantEditSchema.parse(body);
return this.mutate(req, id, version, async (tx, merchant) => {
requireSales(req.user);
if (!Object.keys(data).length) throw new ApiError('VALIDATION_ERROR', 400);
if (
!capabilities(req.user, merchant).editIdentity &&
reviewedFields.some((key) => data[key] !== undefined && data[key] !== merchant[key])
)
throw new ApiError('REVIEW_LOCKED', 409);
await tx.merchant.updateMany({ where: { AND: [merchantScope(req.user), { id }] }, data });
await this.audit(tx, req, id, 'Merchant details updated', { fields: Object.keys(data) });
});
}
@Patch(':id/assignment') assign(
@Req() req: AuthRequest,
@Param('id') id: string,
@Body() body: unknown,
) {
const { version, ownerId } = assignmentSchema.parse(body);
return this.mutate(req, id, version, async (tx, merchant) => {
if (req.user.role !== 'HEAD_OF_SALES') throw new ApiError('FORBIDDEN', 403);
if (
!(await tx.user.findFirst({
where: { id: ownerId, role: 'ACCOUNT_MANAGER' },
select: { id: true },
}))
)
throw new ApiError('VALIDATION_ERROR', 400);
await tx.merchant.updateMany({ where: { id }, data: { ownerId } });
await tx.task.updateMany({
where: { merchantId: id, kind: 'COMMERCIAL', status: 'OPEN' },
data: { assigneeId: ownerId },
});
await this.audit(tx, req, id, 'Manager assignment updated', {
previousOwnerId: merchant.ownerId,
ownerId,
});
});
}
@Post(':id/transitions') transition(
@Req() req: AuthRequest,
@Param('id') id: string,
@Body() body: unknown,
) {
const { version, toStatus } = transitionSchema.parse(body);
return this.mutate(req, id, version, async (tx, merchant) => {
requireSales(req.user);
const index = successfulStages.findIndex((stage) => stage === merchant.status);
if (
!merchant.ownerId ||
index < 0 ||
successfulStages[index + 1] !== toStatus ||
merchant.status === 'COMPLIANCE_REVIEW'
)
throw new ApiError('WORKFLOW_INVALID', 409);
if (toStatus === 'COMPLIANCE_REVIEW') {
const submittedAt = new Date();
if (
!receivedHistory(merchant, submittedAt) ||
merchant.reviews.some((r) => r.decision === 'PENDING')
)
throw new ApiError('WORKFLOW_INVALID', 409);
await tx.complianceReview.create({
data: {
merchantId: id,
cycle: (merchant.reviews[0]?.cycle ?? 0) + 1,
submittedById: req.user.id,
submittedAt,
snapshot: reviewSnapshot(merchant),
},
});
}
if (['TESTING', 'LIVE'].includes(toStatus) && !validApproval(merchant))
throw new ApiError('WORKFLOW_INVALID', 409);
await this.stage(tx, req, merchant, toStatus);
});
}
@Patch(':id/checklist/:itemId') checklist(
@Req() req: AuthRequest,
@Param('id') id: string,
@Param('itemId') itemId: string,
@Body() body: unknown,
) {
const { version, state, note } = checklistEditSchema.parse(body);
return this.mutate(req, id, version, async (tx, merchant) => {
const item = merchant.checklist.find((item) => item.id === itemId);
if (!item) throw new ApiError('NOT_FOUND', 404);
requireSales(req.user);
if (!capabilities(req.user, merchant).collectChecklist)
throw new ApiError('REVIEW_LOCKED', 409);
await tx.kybChecklistItem.updateMany({
where: { id: itemId, merchantId: id },
data: { state, note },
});
await tx.checklistChange.create({
data: { itemId, actorId: req.user.id, fromState: item.state, toState: state, note },
});
await this.audit(tx, req, id, `Checklist updated: ${item.documentCode}`, {
itemId,
fromState: item.state,
toState: state,
});
});
}
@Post(':id/reviews/:reviewId/decision') decide(
@Req() req: AuthRequest,
@Param('id') id: string,
@Param('reviewId') reviewId: string,
@Body() body: unknown,
) {
const { version, decision, reason, corrections } = reviewDecisionSchema.parse(body);
return this.mutate(req, id, version, async (tx, merchant) => {
const review = merchant.reviews.find((review) => review.id === reviewId);
if (!review) throw new ApiError('NOT_FOUND', 404);
if (req.user.role !== 'COMPLIANCE_OFFICER') throw new ApiError('FORBIDDEN', 403);
if (merchant.status !== 'COMPLIANCE_REVIEW' || review.decision !== 'PENDING')
throw new ApiError('WORKFLOW_INVALID', 409);
if (!snapshotsEqual(review.snapshot, reviewSnapshot(merchant)))
throw new ApiError('CONFLICT', 409);
if (decision === 'APPROVED' && !receivedHistory(merchant, review.submittedAt))
throw new ApiError('WORKFLOW_INVALID', 409);
for (const correction of corrections) {
const item = merchant.checklist.find((item) => item.id === correction.itemId);
if (!item) throw new ApiError('NOT_FOUND', 404);
await tx.kybChecklistItem.updateMany({
where: { id: item.id, merchantId: id },
data: { state: 'NEEDS_CORRECTION', note: correction.note },
});
await tx.checklistChange.create({
data: {
itemId: item.id,
actorId: req.user.id,
fromState: item.state,
toState: 'NEEDS_CORRECTION',
note: correction.note,
},
});
}
await tx.complianceReview.updateMany({
where: { id: reviewId, merchantId: id, decision: 'PENDING' },
data: { decision, reason: reason || null, reviewerId: req.user.id, decidedAt: new Date() },
});
await this.stage(
tx,
req,
merchant,
decision === 'APPROVED' ? 'INTEGRATION' : decision === 'CORRECTIONS' ? 'KYB' : 'REJECTED',
reason || undefined,
);
await this.audit(tx, req, id, `Compliance review: ${decision}`, {
reviewId,
decision,
reason,
});
});
}
@Post(':id/activities') createActivity(
@Req() req: AuthRequest,
@Param('id') id: string,
@Body() body: unknown,
) {
return this.saveActivity(req, id, undefined, body);
}
@Patch(':id/activities/:activityId') editActivity(
@Req() req: AuthRequest,
@Param('id') id: string,
@Param('activityId') activityId: string,
@Body() body: unknown,
) {
return this.saveActivity(req, id, activityId, body);
}
private saveActivity(
req: AuthRequest,
id: string,
activityId: string | undefined,
body: unknown,
) {
const { version, kind, text } = activityInputSchema.parse(body);
return this.mutate(req, id, version, async (tx, merchant) => {
const allowed: readonly string[] = capabilities(req.user, merchant).activityKinds;
if (!allowed.includes(kind)) throw new ApiError('FORBIDDEN', 403);
if (activityId) {
const activity = await tx.activity.findFirst({
where: { id: activityId, merchantId: id, merchant: merchantScope(req.user) },
});
if (!activity) throw new ApiError('NOT_FOUND', 404);
if (!allowed.includes(activity.kind)) throw new ApiError('FORBIDDEN', 403);
await tx.activity.updateMany({
where: { id: activityId, merchantId: id },
data: { kind, text },
});
await this.audit(tx, req, id, 'Activity edited', {
activityId,
previousText: activity.text,
previousKind: activity.kind,
});
} else {
await tx.activity.create({ data: { merchantId: id, actorId: req.user.id, kind, text } });
}
});
}
@Post(':id/tasks') createTask(
@Req() req: AuthRequest,
@Param('id') id: string,
@Body() body: unknown,
) {
return this.saveTask(req, id, undefined, body);
}
@Patch(':id/tasks/:taskId') editTask(
@Req() req: AuthRequest,
@Param('id') id: string,
@Param('taskId') taskId: string,
@Body() body: unknown,
) {
return this.saveTask(req, id, taskId, body);
}
private saveTask(req: AuthRequest, id: string, taskId: string | undefined, body: unknown) {
const { version, title, dueAt, remindAt, status } = taskInputSchema.parse(body);
return this.mutate(req, id, version, async (tx, merchant) => {
const kind = req.user.role === 'COMPLIANCE_OFFICER' ? 'COMPLIANCE' : 'COMMERCIAL';
const existing = taskId
? await tx.task.findFirst({
where: { AND: [taskScope(req.user), { id: taskId, merchantId: id }] },
})
: null;
if (taskId && !existing) throw new ApiError('NOT_FOUND', 404);
if (existing && existing.kind !== kind) throw new ApiError('FORBIDDEN', 403);
const completion =
status === 'DONE'
? {
completedAt: existing?.status === 'DONE' ? existing.completedAt : new Date(),
completedById: existing?.status === 'DONE' ? existing.completedById : req.user.id,
}
: { completedAt: null, completedById: null };
const data = {
title,
dueAt: new Date(dueAt),
remindAt: remindAt ? new Date(remindAt) : null,
status,
...completion,
};
if (existing)
await tx.task.updateMany({
where: { AND: [taskScope(req.user), { id: existing.id, merchantId: id }] },
data,
});
else
await tx.task.create({
data: {
...data,
kind,
creatorId: req.user.id,
merchantId: id,
assigneeId: kind === 'COMPLIANCE' ? req.user.id : (merchant.ownerId ?? req.user.id),
},
});
await this.audit(tx, req, id, existing ? 'Task updated' : 'Task created', {
taskId: taskId ?? null,
title,
status,
});
});
}
}
+799 -16
View File
@@ -19,6 +19,7 @@ async function request(path, cookie, options = {}) {
...options, ...options,
headers: { headers: {
...(cookie ? { cookie } : {}), ...(cookie ? { cookie } : {}),
origin: process.env.APP_ORIGIN ?? 'http://localhost:5173',
...(options.body ? { 'content-type': 'application/json' } : {}), ...(options.body ? { 'content-type': 'application/json' } : {}),
...options.headers, ...options.headers,
}, },
@@ -36,7 +37,7 @@ before(async () => {
app = await createApp(); app = await createApp();
await app.listen(0, '127.0.0.1'); await app.listen(0, '127.0.0.1');
base = (await app.getUrl()) + '/api'; base = (await app.getUrl()) + '/api';
for (const account of ['head', 'compliance', 'manager1', 'manager2']) { for (const account of ['head', 'compliance', 'alex', 'sam']) {
const r = await login(account); const r = await login(account);
assert.equal(r.status, 201); assert.equal(r.status, 201);
cookies[account] = r.response.headers.get('set-cookie').split(';')[0]; cookies[account] = r.response.headers.get('set-cookie').split(';')[0];
@@ -88,17 +89,17 @@ test('login validates, sets protected cookies, and rejects incorrect credentials
); );
}); });
for (const [account, total] of [ for (const [account, total] of [
['head', 18], ['head', 45],
['manager1', 9], ['alex', 20],
['manager2', 9], ['sam', 20],
['compliance', 4], ['compliance', 45],
]) ])
test(`${account}: all reads, details, history, tasks and metrics respect the scope`, async () => { test(`${account}: all reads, details, history, tasks and metrics respect the scope`, async () => {
const cookie = cookies[account]; const cookie = cookies[account];
const expected = (await db.merchant.findMany()).filter((m) => const expected = (await db.merchant.findMany()).filter((m) =>
account === 'head' || account === 'compliance' account === 'head' || account === 'compliance'
? account === 'head' || ['KYB', 'COMPLIANCE_REVIEW'].includes(m.status) ? true
: m.ownerId === `user-${account}`, : m.ownerId === (account === 'alex' ? 'user-manager1' : 'user-manager2'),
); );
assert.equal(expected.length, total); assert.equal(expected.length, total);
const ids = expected.map((m) => m.id); const ids = expected.map((m) => m.id);
@@ -117,7 +118,17 @@ for (const [account, total] of [
const pipeline = (await request('/pipeline', cookie)).body; const pipeline = (await request('/pipeline', cookie)).body;
assert.deepEqual(pipeline.map((m) => m.id).sort(), [...ids].sort()); assert.deepEqual(pipeline.map((m) => m.id).sort(), [...ids].sort());
const tasks = (await request('/tasks', cookie)).body; const tasks = (await request('/tasks', cookie)).body;
assert.equal(tasks.length, total * 2); assert.equal(
tasks.length,
await db.task.count({
where: {
merchantId: { in: ids },
...(account === 'compliance'
? { kind: 'COMPLIANCE', assigneeId: 'user-compliance' }
: {}),
},
}),
);
assert.ok(tasks.every((t) => ids.includes(t.merchant.id))); assert.ok(tasks.every((t) => ids.includes(t.merchant.id)));
for (const m of expected) { for (const m of expected) {
const detail = (await request(`/merchants/${m.id}`, cookie)).body; const detail = (await request(`/merchants/${m.id}`, cookie)).body;
@@ -136,7 +147,14 @@ for (const [account, total] of [
assert.equal( assert.equal(
dashboard.overdueTasks, dashboard.overdueTasks,
await db.task.count({ await db.task.count({
where: { merchantId: { in: ids }, status: 'OPEN', dueAt: { lt: new Date() } }, where: {
merchantId: { in: ids },
...(account === 'compliance'
? { kind: 'COMPLIANCE', assigneeId: 'user-compliance' }
: {}),
status: 'OPEN',
dueAt: { lt: new Date() },
},
}), }),
); );
assert.equal( assert.equal(
@@ -174,13 +192,13 @@ test('filters are validated and review queue is oldest first', async () => {
assert.equal((await request(`/merchants?${query}`, cookie)).status, 400); assert.equal((await request(`/merchants?${query}`, cookie)).status, 400);
assert.equal((await request('/tasks?filter=invalid', cookie)).status, 400); assert.equal((await request('/tasks?filter=invalid', cookie)).status, 400);
const live = (await request('/merchants?status=LIVE', cookie)).body; const live = (await request('/merchants?status=LIVE', cookie)).body;
assert.equal(live.total, 2); assert.equal(live.total, 5);
const done = (await request('/tasks?filter=DONE', cookie)).body; const done = (await request('/tasks?filter=DONE', cookie)).body;
assert.ok(done.every((t) => t.status === 'DONE')); assert.ok(done.every((t) => t.status === 'DONE'));
const overdue = (await request('/tasks?filter=OVERDUE', cookie)).body; const overdue = (await request('/tasks?filter=OVERDUE', cookie)).body;
assert.ok(overdue.every((t) => t.status === 'OPEN' && new Date(t.dueAt) < new Date())); assert.ok(overdue.every((t) => t.status === 'OPEN' && new Date(t.dueAt) < new Date()));
const queue = (await request('/review-queue', cookies.compliance)).body; const queue = (await request('/review-queue', cookies.compliance)).body;
assert.equal(queue.length, 2); assert.equal(queue.length, 6);
assert.ok(queue.every((m) => m.status === 'COMPLIANCE_REVIEW')); assert.ok(queue.every((m) => m.status === 'COMPLIANCE_REVIEW'));
assert.ok(new Date(queue[0].stageEnteredAt) <= new Date(queue[1].stageEnteredAt)); assert.ok(new Date(queue[0].stageEnteredAt) <= new Date(queue[1].stageEnteredAt));
}); });
@@ -195,7 +213,7 @@ test('seed is repeatable without modifying records; history includes correction
}); });
assert.equal(result.status, 0, result.stderr); assert.equal(result.status, 0, result.stderr);
assert.equal(await db.user.count(), 4); assert.equal(await db.user.count(), 4);
assert.equal(await db.merchant.count(), 18); assert.equal(await db.merchant.count(), 45);
assert.deepEqual( assert.deepEqual(
await db.merchant.findMany({ await db.merchant.findMany({
orderBy: { id: 'asc' }, orderBy: { id: 'asc' },
@@ -211,7 +229,7 @@ test('seed is repeatable without modifying records; history includes correction
assert.ok(!snapshot.some((m) => m.events.some((e) => e.fromStatus === 'LIVE'))); assert.ok(!snapshot.some((m) => m.events.some((e) => e.fromStatus === 'LIVE')));
}); });
test('expired, logged-out and replaced sessions cannot be reused', async () => { test('expired, logged-out and replaced sessions cannot be reused', async () => {
const r = await login('manager1'); const r = await login('alex');
const cookie = r.response.headers.get('set-cookie').split(';')[0]; const cookie = r.response.headers.get('set-cookie').split(';')[0];
const token = cookie.split('=')[1]; const token = cookie.split('=')[1];
await db.session.update({ await db.session.update({
@@ -219,14 +237,779 @@ test('expired, logged-out and replaced sessions cannot be reused', async () => {
data: { expiresAt: new Date(0) }, data: { expiresAt: new Date(0) },
}); });
assert.equal((await request('/auth/me', cookie)).status, 401); assert.equal((await request('/auth/me', cookie)).status, 401);
const fresh = await login('manager1'); const fresh = await login('alex');
const freshCookie = fresh.response.headers.get('set-cookie').split(';')[0]; 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('/auth/logout', freshCookie, { method: 'POST' })).status, 201);
assert.equal((await request('/pipeline', freshCookie)).status, 401); assert.equal((await request('/pipeline', freshCookie)).status, 401);
const replacement = await request('/auth/login', cookies.manager2, { const replacement = await request('/auth/login', cookies.sam, {
method: 'POST', method: 'POST',
body: JSON.stringify({ email: '[email protected]', password: 'MerchantFlow123!' }), body: JSON.stringify({ email: '[email protected]', password: 'MerchantFlow123!' }),
}); });
assert.equal(replacement.status, 201); assert.equal(replacement.status, 201);
assert.equal((await request('/auth/me', cookies.manager2)).status, 401); assert.equal((await request('/auth/me', cookies.sam)).status, 401);
});
async function freshCookie(account) {
const response = await login(account);
assert.equal(response.status, 201);
return response.response.headers.get('set-cookie').split(';')[0];
}
async function mutate(path, cookie, data, method = 'PATCH') {
return request(path, cookie, { method, body: JSON.stringify(data) });
}
async function fixture(id, status = 'NEW_LEAD', ownerId = 'user-manager1') {
return db.merchant.create({
data: {
id,
name: 'Workflow Test',
legalName: 'Workflow Test Ltd',
website: 'https://workflow.example',
industry: 'SOFTWARE',
country: 'GB',
contactName: 'Test Contact',
contactEmail: '[email protected]',
ownerId,
status,
checklist: { create: documentCodes.map((documentCode) => ({ documentCode })) },
},
});
}
test('manager lookup and both directions of direct record/child/mutation attacks are scoped', async () => {
const head = await freshCookie('head');
const comp = await freshCookie('compliance');
const alex = await freshCookie('alex');
const sam = await freshCookie('sam');
const managers = await request('/users/assignable-managers', head);
assert.deepEqual(managers.body.map((u) => u.email).sort(), [
'[email protected]',
'[email protected]',
]);
for (const cookie of [alex, sam, comp])
assert.equal((await request('/users/assignable-managers', cookie)).status, 403);
assert.equal((await request('/users/assignable-managers')).status, 401);
for (const [cookie, hiddenId, ownId] of [
[alex, 'merchant-02', 'merchant-01'],
[sam, 'merchant-01', 'merchant-02'],
]) {
const hidden = await db.merchant.findUniqueOrThrow({
where: { id: hiddenId },
include: { tasks: true, activities: true, checklist: true },
});
const taskBody = {
version: hidden.version,
title: 'Forbidden',
dueAt: new Date().toISOString(),
remindAt: null,
status: 'OPEN',
};
for (const [suffix, body, method] of [
['', { version: hidden.version, contactName: 'Forbidden' }, 'PATCH'],
['/assignment', { version: hidden.version, ownerId: 'user-manager1' }, 'PATCH'],
['/transitions', { version: hidden.version, toStatus: 'CONTACTED' }, 'POST'],
[
`/checklist/${hidden.checklist[0].id}`,
{ version: hidden.version, state: 'RECEIVED', note: null },
'PATCH',
],
['/reviews/unknown/decision', { version: hidden.version, decision: 'APPROVED' }, 'POST'],
['/activities', { version: hidden.version, kind: 'NOTE', text: 'Forbidden' }, 'POST'],
[
`/activities/${hidden.activities[0].id}`,
{ version: hidden.version, kind: 'NOTE', text: 'Forbidden' },
'PATCH',
],
['/tasks', taskBody, 'POST'],
[`/tasks/${hidden.tasks[0].id}`, taskBody, 'PATCH'],
])
assert.equal(
(await mutate(`/merchants/${hiddenId}${suffix}`, cookie, body, method)).status,
404,
suffix,
);
const own = (await request(`/merchants/${ownId}`, cookie)).body;
assert.equal(
(
await mutate(`/merchants/${ownId}/tasks/${hidden.tasks[0].id}`, cookie, {
...taskBody,
version: own.version,
})
).status,
404,
);
assert.equal(
(
await mutate(`/merchants/${ownId}/activities/${hidden.activities[0].id}`, cookie, {
version: own.version,
kind: 'NOTE',
text: 'Forbidden',
})
).status,
404,
);
assert.equal(
(
await mutate(`/merchants/${ownId}/assignment`, cookie, {
version: own.version,
ownerId: 'user-manager2',
})
).status,
403,
);
assert.equal(
(
await mutate(`/merchants/${ownId}`, cookie, {
version: own.version,
ownerId: 'user-manager2',
})
).status,
400,
);
assert.equal((await request(`/merchants/${hiddenId}`, cookie)).status, 404);
assert.equal(
(await request(`/merchants?search=${encodeURIComponent(hidden.name)}`, cookie)).body.total,
0,
);
}
const visible = (await request('/merchants/merchant-15', comp)).body;
assert.equal(visible.status, 'LIVE');
for (const [suffix, body, method] of [
['', { version: visible.version, source: 'PARTNER' }, 'PATCH'],
['/assignment', { version: visible.version, ownerId: 'user-manager2' }, 'PATCH'],
['/transitions', { version: visible.version, toStatus: 'LIVE' }, 'POST'],
['/activities', { version: visible.version, kind: 'CALL', text: 'forbidden' }, 'POST'],
])
assert.equal(
(await mutate(`/merchants/${visible.id}${suffix}`, comp, body, method)).status,
403,
);
});
test('origin checks cover every mutation and no registration endpoint exists', async () => {
const cookie = await freshCookie('head');
const merchant = (await request('/merchants/merchant-01', cookie)).body;
for (const origin of ['', 'null', 'https://untrusted.example']) {
for (const [path, method, body] of [
['/auth/login', 'POST', { email: '[email protected]', password: 'MerchantFlow123!' }],
['/auth/logout', 'POST', undefined],
['/merchants/merchant-01', 'PATCH', { version: merchant.version, contactName: 'Bad origin' }],
['/merchants/merchant-01/tasks', 'POST', { version: merchant.version }],
])
assert.equal(
(
await request(path, cookie, {
method,
headers: { origin },
...(body ? { body: JSON.stringify(body) } : {}),
})
).status,
403,
);
}
assert.equal(
(
await request('/auth/logout', cookie, {
method: 'POST',
headers: { 'sec-fetch-site': 'cross-site' },
})
).status,
403,
);
assert.equal((await request('/auth/register', null, { method: 'POST', body: '{}' })).status, 404);
assert.equal(
(
await mutate('/merchants/merchant-01', null, {
version: merchant.version,
contactName: 'Anonymous',
})
).status,
401,
);
});
test('corrections, resubmission, approval and activation preserve one merchant and immutable evidence', async () => {
const id = 'workflow-cycle';
await fixture(id);
const sales = await freshCookie('alex');
const head = await freshCookie('head');
const comp = await freshCookie('compliance');
const detail = async () => (await request(`/merchants/${id}`, sales)).body;
const move = async (toStatus, cookie = sales) =>
mutate(
`/merchants/${id}/transitions`,
cookie,
{ version: (await detail()).version, toStatus },
'POST',
);
try {
assert.equal((await move('LIVE')).status, 409);
for (const stage of ['CONTACTED', 'QUALIFIED', 'KYB'])
assert.equal((await move(stage)).status, 201);
assert.equal((await move('COMPLIANCE_REVIEW')).status, 409);
let m = await detail();
for (const item of m.checklist) {
assert.equal(
(
await mutate(`/merchants/${id}/checklist/${item.id}`, sales, {
version: (await detail()).version,
state: 'RECEIVED',
note: null,
})
).status,
200,
);
}
assert.equal((await move('COMPLIANCE_REVIEW')).status, 201);
m = await detail();
const first = m.reviews[0];
assert.equal(
(
await mutate(`/merchants/${id}`, head, {
version: m.version,
legalName: 'Changed during review',
})
).status,
409,
);
assert.equal(
(
await mutate(`/merchants/${id}/checklist/${m.checklist[0].id}`, sales, {
version: m.version,
state: 'MISSING',
note: null,
})
).status,
409,
);
for (const cookie of [sales, head])
assert.equal(
(
await mutate(
`/merchants/${id}/reviews/${first.id}/decision`,
cookie,
{ version: m.version, decision: 'APPROVED' },
'POST',
)
).status,
403,
);
assert.equal(
(
await mutate(
`/merchants/${id}/reviews/${first.id}/decision`,
comp,
{ version: m.version, decision: 'REJECTED', reason: ' ' },
'POST',
)
).status,
400,
);
assert.equal(
(
await mutate(
`/merchants/${id}/reviews/${first.id}/decision`,
comp,
{
version: m.version,
decision: 'CORRECTIONS',
reason: 'Updated signature required',
corrections: [{ itemId: m.checklist[0].id, note: 'Please sign the latest version' }],
},
'POST',
)
).status,
201,
);
m = await detail();
assert.equal(m.status, 'KYB');
assert.equal(m.checklist[0].state, 'NEEDS_CORRECTION');
assert.equal((await move('COMPLIANCE_REVIEW')).status, 409);
assert.equal(
(
await mutate(`/merchants/${id}/checklist/${m.checklist[0].id}`, sales, {
version: m.version,
state: 'RECEIVED',
note: 'Signed version received',
})
).status,
200,
);
assert.equal((await move('COMPLIANCE_REVIEW')).status, 201);
m = await detail();
assert.equal(m.reviews.length, 2);
assert.equal(
(
await mutate(
`/merchants/${id}/reviews/${m.reviews[0].id}/decision`,
comp,
{ version: m.version, decision: 'APPROVED', reason: 'All checks passed' },
'POST',
)
).status,
201,
);
m = await detail();
assert.equal(m.status, 'INTEGRATION');
const reviewSnapshot = await db.complianceReview.findUnique({ where: { id: m.reviews[0].id } });
assert.equal(
(
await mutate(`/merchants/${id}`, head, {
version: m.version,
website: 'https://changed.example',
})
).status,
409,
);
assert.equal(
(
await mutate(`/merchants/${id}`, sales, {
version: m.version,
contactPhone: '+44 20 7946 0000',
estimatedMonthlyVolumeUsd: '125000.25',
})
).status,
200,
);
assert.equal((await move('TESTING', comp)).status, 403);
assert.equal((await move('TESTING')).status, 201);
assert.equal((await move('LIVE', head)).status, 201);
assert.equal((await move('REJECTED')).status, 409);
m = await detail();
assert.equal(m.id, id);
assert.equal(m.status, 'LIVE');
assert.equal(m.estimatedMonthlyVolumeUsd, '125000.25');
assert.equal(
(
await mutate(
`/merchants/${id}/reviews/${first.id}/decision`,
comp,
{ version: m.version, decision: 'APPROVED' },
'POST',
)
).status,
409,
);
assert.deepEqual(
await db.complianceReview.findUnique({ where: { id: m.reviews[0].id } }),
reviewSnapshot,
);
assert.equal(m.events.length, 9);
assert.ok(m.activities.some((a) => a.kind === 'AUDIT'));
} finally {
await db.merchant.delete({ where: { id } });
}
});
test('missing approval prevents activation; rejection is terminal; concurrent decisions commit once', async () => {
const sales = await freshCookie('alex');
const comp = await freshCookie('compliance');
await fixture('workflow-evidence', 'TESTING');
await fixture('workflow-reject', 'KYB');
try {
assert.equal(
(
await mutate(
'/merchants/workflow-evidence/transitions',
sales,
{ version: 0, toStatus: 'LIVE' },
'POST',
)
).status,
409,
);
const get = async () => (await request('/merchants/workflow-reject', sales)).body;
for (const item of (await get()).checklist)
await mutate(`/merchants/workflow-reject/checklist/${item.id}`, sales, {
version: (await get()).version,
state: 'RECEIVED',
note: null,
});
await mutate(
'/merchants/workflow-reject/transitions',
sales,
{ version: (await get()).version, toStatus: 'COMPLIANCE_REVIEW' },
'POST',
);
const m = await get();
const decisions = await Promise.all(
[
'Rejected: contradictory ownership evidence',
'Rejected: incomplete business registration',
].map((reason) =>
mutate(
`/merchants/${m.id}/reviews/${m.reviews[0].id}/decision`,
comp,
{ version: m.version, decision: 'REJECTED', reason },
'POST',
),
),
);
assert.deepEqual(decisions.map((r) => r.status).sort(), [201, 409]);
assert.equal((await get()).status, 'REJECTED');
assert.equal(
await db.statusEvent.count({ where: { merchantId: m.id, toStatus: 'REJECTED' } }),
1,
);
assert.equal(
(
await mutate(
`/merchants/${m.id}/transitions`,
sales,
{ version: (await get()).version, toStatus: 'KYB' },
'POST',
)
).status,
409,
);
} finally {
await db.merchant.deleteMany({
where: { id: { in: ['workflow-evidence', 'workflow-reject'] } },
});
}
});
test('reassignment transfers open commercial tasks; concurrent writes and former-owner access fail', async () => {
const id = 'workflow-handoff';
await fixture(id);
const head = await freshCookie('head');
const alex = await freshCookie('alex');
const sam = await freshCookie('sam');
const comp = await freshCookie('compliance');
const get = async (cookie = head) => (await request(`/merchants/${id}`, cookie)).body;
const task = {
title: 'Handoff task',
dueAt: new Date(Date.now() + 86400000).toISOString(),
remindAt: null,
status: 'OPEN',
};
try {
for (const [cookie, status] of [
[alex, 'OPEN'],
[alex, 'DONE'],
[comp, 'OPEN'],
])
assert.equal(
(
await mutate(
`/merchants/${id}/tasks`,
cookie,
{ ...task, status, version: (await get()).version },
'POST',
)
).status,
201,
);
const before = await get();
assert.equal((await get(comp)).tasks.length, 1);
const personal = before.tasks.find((t) => t.kind === 'COMPLIANCE');
assert.equal(
(
await mutate(`/merchants/${id}/tasks/${personal.id}`, head, {
...task,
version: before.version,
})
).status,
403,
);
const commercial = before.tasks.find((t) => t.kind === 'COMMERCIAL');
assert.equal(
(
await mutate(`/merchants/${id}/tasks/${commercial.id}`, comp, {
...task,
version: before.version,
})
).status,
404,
);
const results = await Promise.all([
mutate(`/merchants/${id}/assignment`, head, {
version: before.version,
ownerId: 'user-manager2',
}),
mutate(`/merchants/${id}`, alex, {
version: before.version,
contactTitle: 'Concurrent update',
}),
]);
assert.equal(results.filter((r) => r.status === 200).length, 1);
if (results[0].status !== 200)
assert.equal(
(
await mutate(`/merchants/${id}/assignment`, head, {
version: (await get()).version,
ownerId: 'user-manager2',
})
).status,
200,
);
const after = await get(sam);
assert.equal(after.owner.id, 'user-manager2');
assert.ok(
after.tasks
.filter((t) => t.kind === 'COMMERCIAL' && t.status === 'OPEN')
.every((t) => t.assignee.id === 'user-manager2'),
);
assert.ok(
after.tasks
.filter((t) => t.status === 'DONE')
.every((t) => t.assignee.id === 'user-manager1'),
);
assert.equal(after.tasks.find((t) => t.kind === 'COMPLIANCE').assignee.id, 'user-compliance');
assert.equal((await request(`/merchants/${id}`, alex)).status, 404);
assert.equal(
(
await mutate(`/merchants/${id}`, alex, {
version: after.version,
contactName: 'Former owner',
})
).status,
404,
);
assert.equal(
(
await mutate(`/merchants/${id}`, sam, {
version: before.version,
contactName: 'Stale update',
})
).status,
409,
);
const audit = after.activities.find((a) => a.kind === 'AUDIT');
assert.equal(
(
await mutate(`/merchants/${id}/activities/${audit.id}`, head, {
version: after.version,
kind: 'NOTE',
text: 'Rewrite history',
})
).status,
403,
);
} finally {
await db.merchant.delete({ where: { id } });
}
});
test('seed histories, ownership balance, approval evidence, tasks and edited records survive reseeding', async () => {
const { reviewSnapshot, snapshotsEqual, verifyPassword } = await import('@merchantflow/database');
const merchants = await db.merchant.findMany({
include: {
checklist: { include: { changes: { orderBy: { occurredAt: 'asc' } } } },
reviews: { orderBy: { cycle: 'desc' }, include: { reviewer: true } },
events: { orderBy: { occurredAt: 'asc' } },
},
});
assert.equal(merchants.filter((m) => !m.ownerId && m.status === 'NEW_LEAD').length, 5);
for (const ownerId of ['user-manager1', 'user-manager2'])
assert.equal(merchants.filter((m) => m.ownerId === ownerId).length, 20);
const anchor = (await db.demoSeedState.findUniqueOrThrow({ where: { id: 'merchantflow-v2' } }))
.anchorAt;
assert.ok(merchants.some((m) => anchor.getTime() - m.createdAt.getTime() >= 90 * 86400000));
for (const m of merchants) {
assert.equal(m.events.at(-1).toStatus, m.status);
assert.equal(m.events.at(-1).occurredAt.getTime(), m.stageEnteredAt.getTime());
if (['INTEGRATION', 'TESTING', 'LIVE'].includes(m.status)) {
const review = m.reviews[0];
assert.equal(review.decision, 'APPROVED');
assert.equal(review.reviewer.role, 'COMPLIANCE_OFFICER');
assert.ok(review.decidedAt >= review.submittedAt);
assert.ok(snapshotsEqual(review.snapshot, reviewSnapshot(m)));
assert.ok(
m.checklist.every(
(item) =>
item.changes.filter((change) => change.occurredAt <= review.submittedAt).at(-1)
?.toState === 'RECEIVED',
),
);
}
if (m.status === 'REJECTED') assert.ok(m.reviews[0].reason.trim());
}
for (const user of await db.user.findMany()) {
assert.notEqual(user.passwordHash, 'MerchantFlow123!');
assert.ok(verifyPassword('MerchantFlow123!', user.passwordHash));
}
const merchant = await db.merchant.findUniqueOrThrow({ where: { id: 'merchant-01' } });
const user = await db.user.findUniqueOrThrow({ where: { id: 'user-manager1' } });
const task = await db.task.findFirstOrThrow({ where: { merchantId: merchant.id } });
try {
await db.merchant.update({
where: { id: merchant.id },
data: { name: 'Keep my edited merchant', estimatedMonthlyVolumeUsd: '777.77' },
});
await db.task.update({ where: { id: task.id }, data: { title: 'Keep my edited task' } });
await db.user.update({
where: { id: user.id },
data: { passwordHash: 'intentionally-changed-by-test' },
});
const snapshot = await db.merchant.findUnique({
where: { id: merchant.id },
include: {
tasks: true,
activities: true,
checklist: { include: { changes: true } },
reviews: true,
events: true,
},
});
for (let i = 0; i < 2; i++)
assert.equal(
spawnSync('pnpm', ['--filter', '@merchantflow/database', 'seed'], {
env: process.env,
encoding: 'utf8',
}).status,
0,
);
assert.deepEqual(
await db.merchant.findUnique({
where: { id: merchant.id },
include: {
tasks: true,
activities: true,
checklist: { include: { changes: true } },
reviews: true,
events: true,
},
}),
snapshot,
);
assert.equal(
(await db.user.findUnique({ where: { id: user.id } })).passwordHash,
'intentionally-changed-by-test',
);
assert.equal(await db.merchant.count(), 45);
} finally {
await db.merchant.update({
where: { id: merchant.id },
data: {
name: merchant.name,
estimatedMonthlyVolumeUsd: merchant.estimatedMonthlyVolumeUsd,
updatedAt: merchant.updatedAt,
},
});
await db.task.update({
where: { id: task.id },
data: { title: task.title, updatedAt: task.updatedAt },
});
await db.user.update({
where: { id: user.id },
data: { passwordHash: user.passwordHash, updatedAt: user.updatedAt },
});
}
});
test('login limits are enforced with Retry-After without revealing account existence', async () => {
for (let i = 0; i < 20; i++)
assert.equal((await login('nonexistent-rate-limit', 'wrong')).status, 401);
const limited = await login('nonexistent-rate-limit', 'wrong');
assert.equal(limited.status, 429);
assert.ok(Number(limited.response.headers.get('retry-after')) > 0);
});
test('legacy upgrade preserves edits and identities, enriches matching fixtures only, and repeats safely', async () => {
// This test runs last and can only operate on the guarded disposable database.
await db.merchant.deleteMany();
await db.demoSeedState.deleteMany();
await db.user.update({
where: { id: 'user-manager1' },
data: { email: '[email protected]' },
});
await db.user.update({
where: { id: 'user-manager2' },
data: { email: '[email protected]', name: 'Maria Chen' },
});
const hashes = (await db.user.findMany({ orderBy: { id: 'asc' } })).map(
(user) => user.passwordHash,
);
const old = spawnSync('node', ['tests/fixtures/legacy-demo.mjs'], {
env: process.env,
encoding: 'utf8',
});
assert.equal(old.status, 0, old.stderr);
await db.merchant.update({
where: { id: 'merchant-02' },
data: { name: 'Edited legacy company' },
});
await db.task.update({
where: { id: 'merchant-03-task-1' },
data: { title: 'Edited legacy task' },
});
const include = {
checklist: { include: { changes: true } },
activities: true,
reviews: true,
notes: true,
tasks: true,
events: true,
};
const edited = await db.merchant.findMany({
where: { id: { in: ['merchant-02', 'merchant-03'] } },
include,
orderBy: { id: 'asc' },
});
const oldFields = {
id: true,
name: true,
website: true,
country: true,
industry: true,
contactName: true,
contactEmail: true,
ownerId: true,
status: true,
createdAt: true,
stageEnteredAt: true,
events: { orderBy: { id: 'asc' } },
notes: { orderBy: { id: 'asc' } },
};
const before = await db.merchant.findMany({ select: oldFields, orderBy: { id: 'asc' } });
const upgraded = spawnSync('pnpm', ['--filter', '@merchantflow/database', 'seed'], {
env: process.env,
encoding: 'utf8',
});
assert.equal(upgraded.status, 0, upgraded.stderr);
assert.match(upgraded.stderr, /Preserved edited.*merchant-02/);
assert.match(upgraded.stderr, /Preserved edited.*merchant-03/);
assert.deepEqual(
await db.merchant.findMany({
where: { id: { in: before.map((m) => m.id) } },
select: oldFields,
orderBy: { id: 'asc' },
}),
before,
);
assert.deepEqual(
await db.merchant.findMany({
where: { id: { in: ['merchant-02', 'merchant-03'] } },
include,
orderBy: { id: 'asc' },
}),
edited,
);
assert.equal(await db.merchant.count(), 45);
assert.equal(
(await db.user.findUnique({ where: { id: 'user-manager1' } })).email,
'[email protected]',
);
assert.equal(
(await db.user.findUnique({ where: { id: 'user-manager2' } })).email,
'[email protected]',
);
assert.deepEqual(
(await db.user.findMany({ orderBy: { id: 'asc' } })).map((user) => user.passwordHash),
hashes,
);
for (const m of await db.merchant.findMany({
where: { status: { in: ['INTEGRATION', 'TESTING', 'LIVE'] } },
include: { reviews: true },
}))
assert.ok(m.reviews.some((r) => r.decision === 'APPROVED'));
const snapshot = await db.merchant.findMany({ include, orderBy: { id: 'asc' } });
assert.equal(
spawnSync('pnpm', ['--filter', '@merchantflow/database', 'seed'], {
env: process.env,
encoding: 'utf8',
}).status,
0,
);
assert.deepEqual(await db.merchant.findMany({ include, orderBy: { id: 'asc' } }), snapshot);
}); });
+1 -3
View File
@@ -14,8 +14,6 @@ test('every role receives its exact merchant scope', () => {
assert.deepEqual(merchantScope({ role: 'ACCOUNT_MANAGER', id: 'manager-1' }), { assert.deepEqual(merchantScope({ role: 'ACCOUNT_MANAGER', id: 'manager-1' }), {
ownerId: 'manager-1', ownerId: 'manager-1',
}); });
assert.deepEqual(merchantScope({ role: 'COMPLIANCE_OFFICER' }), { assert.deepEqual(merchantScope({ role: 'COMPLIANCE_OFFICER' }), {});
status: { in: ['KYB', 'COMPLIANCE_REVIEW'] },
});
assert.deepEqual(merchantScope({ role: 'unexpected' }), { id: '__no_access__' }); assert.deepEqual(merchantScope({ role: 'unexpected' }), { id: '__no_access__' });
}); });
@@ -0,0 +1,753 @@
import { useId, useState } from 'react';
import { useForm } from 'react-hook-form';
import { useMutation, useQuery } from '@tanstack/react-query';
import { Link } from 'react-router';
import { useTranslation } from 'react-i18next';
import { z } from 'zod';
import {
activityInputSchema,
assignmentSchema,
checklistEditSchema,
industries,
managerListSchema,
merchantEditSchema,
mutationResultSchema,
reviewDecisionSchema,
sources,
statuses,
taskInputSchema,
type MerchantDetail,
type Task,
} from '@merchantflow/contracts';
import {
Sheet,
SheetContent,
SheetTitle,
SheetDescription,
} from '@merchantflow/ui/components/sheet';
import { Input } from '@merchantflow/ui/components/input';
import { NativeSelect } from '@merchantflow/ui/components/native-select';
import { FormField } from '@merchantflow/ui/components/form-field';
import { api, ApiError, queryClient } from '../lib/api';
import { useFormat } from '../lib/format';
import { Button, SectionHeader, TaskRow } from './shared';
type Field = {
name: string;
label?: string;
type?: string;
options?: { value: string; label: string }[];
disabled?: boolean;
};
type EditorProps = {
title: string;
description?: string;
fields: Field[];
initial: Record<string, string>;
schema: z.ZodType;
build: (values: Record<string, string>) => unknown;
submit: (body: unknown) => void;
close: () => void;
pending: boolean;
};
function Editor({
title,
description,
fields,
initial,
schema,
build,
submit,
close,
pending,
}: EditorProps) {
const { t } = useTranslation();
const id = useId();
const form = useForm<Record<string, string>>({ defaultValues: initial });
const [errors, setErrors] = useState<Record<string, string>>({});
return (
<Sheet
open
onOpenChange={(open) => {
if (!open && !pending) close();
}}
>
<SheetContent
closeLabel={t('common.close')}
className="w-full! overflow-y-auto p-5 sm:max-w-xl! sm:p-8"
>
<SheetTitle className="pr-10 text-xl">{title}</SheetTitle>
<SheetDescription>{description ?? t('merchants.details')}</SheetDescription>
<form
noValidate
className="space-y-5"
onSubmit={form.handleSubmit((values) => {
const result = schema.safeParse(build(values));
if (!result.success) {
const messages: Record<string, string> = {};
for (const issue of result.error.issues)
messages[String(issue.path[0] ?? 'form')] = t('validation.invalid');
setErrors(messages);
return;
}
setErrors({});
submit(result.data);
})}
>
<fieldset disabled={pending} className="space-y-5">
{fields.map((field) => {
const fieldId = `${id}-${field.name}`;
const props = {
id: fieldId,
...form.register(field.name),
disabled: field.disabled,
'aria-invalid': !!errors[field.name],
'aria-describedby': errors[field.name] ? `${fieldId}-error` : undefined,
};
return (
<FormField
key={field.name}
id={fieldId}
label={field.label ?? t(`workflow.${field.name}`)}
error={errors[field.name]}
>
{field.options ? (
<NativeSelect {...props}>
{field.options.map((option) => (
<option key={option.value} value={option.value}>
{option.label}
</option>
))}
</NativeSelect>
) : field.type === 'textarea' ? (
<textarea
{...props}
rows={4}
className="min-h-28 w-full resize-y rounded-lg border bg-background px-3 py-2 text-sm"
/>
) : (
<Input {...props} type={field.type ?? 'text'} />
)}
</FormField>
);
})}
{Object.keys(errors).some((key) => !fields.some((field) => field.name === key)) && (
<p role="alert" className="text-sm text-destructive">
{t('errors.VALIDATION_ERROR')}
</p>
)}
<div className="flex flex-wrap gap-3 border-t pt-5">
<Button type="submit">{t(pending ? 'workflow.saving' : 'workflow.save')}</Button>
<Button type="button" variant="outline" onClick={close}>
{t('workflow.cancel')}
</Button>
</div>
</fieldset>
</form>
</SheetContent>
</Sheet>
);
}
function useAction(merchant: MerchantDetail, close?: () => void) {
const { t } = useTranslation();
const mutation = useMutation({
mutationFn: ({
path,
body,
method = 'PATCH',
}: {
path: string;
body: unknown;
method?: string;
}) =>
api(`/merchants/${merchant.id}${path}`, mutationResultSchema, {
method,
body: JSON.stringify(body),
}),
onSuccess: async () => {
close?.();
await queryClient.invalidateQueries({
predicate: (query) => query.queryKey[0] !== 'session',
});
},
onError: async () => {
close?.();
await queryClient.invalidateQueries({ queryKey: ['merchant', merchant.id] });
},
});
return {
...mutation,
feedback: mutation.isError ? (
<p role="alert" className="rounded-lg bg-rose-50 p-3 text-sm text-destructive">
{t(`errors.${mutation.error instanceof ApiError ? mutation.error.code : 'INTERNAL_ERROR'}`)}
</p>
) : mutation.isSuccess ? (
<p role="status" className="text-xs text-muted-foreground">
{t('workflow.saved')}
</p>
) : null,
};
}
const identityFields = [
'name',
'legalName',
'registrationNumber',
'address',
'website',
'country',
'industry',
];
const commercialFields = [
'contactName',
'contactEmail',
'contactPhone',
'contactTitle',
'estimatedMonthlyVolumeUsd',
'source',
];
export function MerchantControls({ merchant: m }: { merchant: MerchantDetail }) {
const { t } = useTranslation();
const [mode, setMode] = useState<'edit' | 'assign' | null>(null);
const action = useAction(m, () => setMode(null));
const managers = useQuery({
queryKey: ['assignable-managers'],
queryFn: ({ signal }) => api('/users/assignable-managers', managerListSchema, { signal }),
enabled: m.capabilities.assign,
});
const fields: Field[] = [...identityFields, ...commercialFields].map((name) => ({
name,
disabled: identityFields.includes(name) && !m.capabilities.editIdentity,
type: name === 'contactEmail' ? 'email' : name === 'website' ? 'url' : 'text',
options:
name === 'industry'
? industries.map((value) => ({ value, label: t(`industry.${value}`) }))
: name === 'source'
? [
{ value: '', label: '—' },
...sources.map((value) => ({ value, label: t(`workflow.${value}`) })),
]
: undefined,
}));
const initial = Object.fromEntries(
fields.map(({ name }) => [name, String(m[name as keyof MerchantDetail] ?? '')]),
);
return (
<div className="mb-6 space-y-3">
<div className="flex flex-wrap gap-2">
{m.capabilities.editCommercial && (
<Button
variant="outline"
onClick={() => {
action.reset();
setMode('edit');
}}
>
{t('workflow.editMerchant')}
</Button>
)}
{m.capabilities.assign && (
<Button
variant="outline"
disabled={!managers.data}
onClick={() => {
action.reset();
setMode('assign');
}}
>
{t('workflow.assign')}
</Button>
)}
{m.capabilities.nextStage && (
<Button
disabled={action.isPending}
onClick={() =>
action.mutate({
path: '/transitions',
method: 'POST',
body: { version: m.version, toStatus: m.capabilities.nextStage },
})
}
>
{t('workflow.advance', { stage: t(`statuses.${m.capabilities.nextStage}`) })}
</Button>
)}
</div>
{managers.isError && (
<p role="alert" className="text-sm text-destructive">
{t('errors.NETWORK')}{' '}
<Button variant="ghost" onClick={() => void managers.refetch()}>
{t('common.retry')}
</Button>
</p>
)}
{action.feedback}
{mode === 'edit' && (
<Editor
title={t('workflow.editMerchant')}
description={!m.capabilities.editIdentity ? t('workflow.identityLocked') : undefined}
fields={fields}
initial={initial}
schema={merchantEditSchema}
build={(values) => ({
version: m.version,
...Object.fromEntries(
Object.entries(values)
.filter(
([key, value]) =>
value !== initial[key] &&
(!identityFields.includes(key) || m.capabilities.editIdentity),
)
.map(([key, value]) => [
key,
['registrationNumber', 'address', 'contactPhone', 'contactTitle'].includes(key) &&
!value
? null
: value,
]),
),
})}
submit={(body) => action.mutate({ path: '', body })}
close={() => setMode(null)}
pending={action.isPending}
/>
)}
{mode === 'assign' && (
<Editor
title={t('workflow.assign')}
description={t('workflow.taskOwnership')}
fields={[
{
name: 'ownerId',
options: (managers.data ?? []).map((user) => ({ value: user.id, label: user.name })),
},
]}
initial={{ ownerId: m.owner?.id ?? managers.data?.[0]?.id ?? '' }}
schema={assignmentSchema}
build={(values) => ({ ...values, version: m.version })}
submit={(body) => action.mutate({ path: '/assignment', body })}
close={() => setMode(null)}
pending={action.isPending}
/>
)}
</div>
);
}
export function ChecklistControl({
merchant: m,
item,
}: {
merchant: MerchantDetail;
item: MerchantDetail['checklist'][number];
}) {
const { t } = useTranslation();
const f = useFormat();
const [open, setOpen] = useState(false);
const action = useAction(m, () => setOpen(false));
return (
<div className="mt-3 space-y-2">
{m.capabilities.collectChecklist && (
<Button
variant="outline"
onClick={() => {
action.reset();
setOpen(true);
}}
>
{t('workflow.checklistEdit')}
</Button>
)}
{action.feedback}
<details className="text-xs text-muted-foreground">
<summary className="min-h-11 cursor-pointer py-3">{t('workflow.checklistHistory')}</summary>
<ol className="space-y-3 border-l pl-3">
{item.changes.map((change) => (
<li key={change.id}>
<span>
{t(`checklist.${change.toState}`)} · {change.actor.name} ·{' '}
{f.date(change.occurredAt)}
</span>
{change.note && <p className="mt-1 whitespace-pre-wrap">{change.note}</p>}
</li>
))}
</ol>
</details>
{open && (
<Editor
title={t('workflow.checklistEdit')}
description={t(`documents.${item.documentCode}`)}
fields={[
{
name: 'state',
options: ['MISSING', 'RECEIVED'].map((value) => ({
value,
label: t(`checklist.${value}`),
})),
},
{ name: 'note', type: 'textarea' },
]}
initial={{
state: item.state === 'RECEIVED' ? 'RECEIVED' : 'MISSING',
note: item.note ?? '',
}}
schema={checklistEditSchema}
build={(values) => ({ ...values, note: values.note || null, version: m.version })}
submit={(body) => action.mutate({ path: `/checklist/${item.id}`, body })}
close={() => setOpen(false)}
pending={action.isPending}
/>
)}
</div>
);
}
export function ReviewHistory({ merchant: m }: { merchant: MerchantDetail }) {
const { t } = useTranslation();
const f = useFormat();
const [open, setOpen] = useState(false);
const action = useAction(m, () => setOpen(false));
const pending = m.reviews.find((review) => review.decision === 'PENDING');
return (
<section className="surface">
<SectionHeader
title={t('workflow.reviews')}
action={
m.capabilities.review &&
pending && (
<Button
onClick={() => {
action.reset();
setOpen(true);
}}
>
{t('workflow.decide')}
</Button>
)
}
/>
<div className="space-y-4 p-5 sm:p-6">
{action.feedback}
{!m.reviews.length && (
<p className="text-sm text-muted-foreground">{t('review.emptyText')}</p>
)}
{m.reviews.map((review) => (
<article key={review.id} className="rounded-lg border p-4">
<p className="text-sm font-semibold">
{t('workflow.cycle', { cycle: review.cycle })} · {t(`workflow.${review.decision}`)}
</p>
<p className="mt-2 text-xs text-muted-foreground">
{t('workflow.submitted', {
name: review.submittedBy.name,
date: f.date(review.submittedAt),
})}
</p>
{review.reviewer && review.decidedAt && (
<p className="mt-1 text-xs text-muted-foreground">
{t('workflow.reviewed', {
name: review.reviewer.name,
date: f.date(review.decidedAt),
})}
</p>
)}
{review.reason && (
<p className="mt-3 whitespace-pre-wrap text-sm leading-relaxed">{review.reason}</p>
)}
</article>
))}
</div>
{open && pending && (
<Editor
title={t('workflow.decide')}
description={t('workflow.correctionHint')}
fields={[
{
name: 'decision',
options: ['APPROVED', 'CORRECTIONS', 'REJECTED'].map((value) => ({
value,
label: t(`workflow.${value}`),
})),
},
{ name: 'reason', type: 'textarea' },
...m.checklist.map((item) => ({
name: `correction_${item.id}`,
label: t(`documents.${item.documentCode}`),
type: 'textarea',
})),
]}
initial={{ decision: 'APPROVED', reason: '' }}
schema={reviewDecisionSchema}
build={(values) => ({
version: m.version,
decision: values.decision,
reason: values.reason,
corrections:
values.decision === 'CORRECTIONS'
? m.checklist
.filter((item) => values[`correction_${item.id}`]?.trim())
.map((item) => ({ itemId: item.id, note: values[`correction_${item.id}`] }))
: [],
})}
submit={(body) =>
action.mutate({ path: `/reviews/${pending.id}/decision`, method: 'POST', body })
}
close={() => setOpen(false)}
pending={action.isPending}
/>
)}
</section>
);
}
function useActivityText() {
const { t } = useTranslation();
return (activity: MerchantDetail['activities'][number]) => {
if (activity.kind !== 'AUDIT') return activity.text;
const labels: Record<string, string> = {
'Merchant details updated': 'detailsUpdated',
'Manager assignment updated': 'assignmentUpdated',
'Activity edited': 'activityEdited',
'Task updated': 'taskUpdated',
'Task created': 'taskCreated',
};
if (labels[activity.text]) return t(`workflow.${labels[activity.text]}`);
const stages = activity.text.split(' → ');
if (stages.length === 2 && stages.every((stage) => statuses.some((code) => code === stage)))
return stages.map((stage) => t(`statuses.${stage}`)).join(' → ');
if (activity.text.startsWith('Checklist updated: '))
return t('workflow.checklistUpdated', {
document: t(`documents.${activity.text.slice(19)}`),
});
if (activity.text.startsWith('Compliance review: '))
return t('workflow.reviewDecided', { decision: t(`workflow.${activity.text.slice(19)}`) });
return activity.text;
};
}
export function InteractionHistory({ merchant: m }: { merchant: MerchantDetail }) {
const { t } = useTranslation();
const f = useFormat();
const [edit, setEdit] = useState<string | null>(null);
const action = useAction(m, () => setEdit(null));
const existing = m.activities.find((activity) => activity.id === edit);
const describe = useActivityText();
const audit = m.activities.filter((activity) => activity.kind === 'AUDIT');
return (
<section className="surface">
<SectionHeader
title={t('workflow.activities')}
action={
<Button
variant="outline"
onClick={() => {
action.reset();
setEdit('new');
}}
>
{t('workflow.addActivity')}
</Button>
}
/>
<div className="space-y-4 p-5 sm:p-6">
{action.feedback}
{m.activities
.filter((activity) => activity.kind !== 'AUDIT')
.map((activity) => (
<article key={activity.id} className="rounded-lg bg-background p-4">
<p className="mb-2 text-xs text-muted-foreground">
{t(`workflow.${activity.kind}`)} · {activity.actor.name} ·{' '}
{f.date(activity.occurredAt)}
</p>
<p className="whitespace-pre-wrap break-words text-sm leading-relaxed">
{activity.text}
</p>
{m.capabilities.activityKinds.some((kind) => kind === activity.kind) && (
<Button
className="mt-2"
variant="ghost"
onClick={() => {
action.reset();
setEdit(activity.id);
}}
>
{t('workflow.editActivity')}
</Button>
)}
</article>
))}
{!!audit.length && (
<details className="border-t pt-2">
<summary className="min-h-11 cursor-pointer py-3 text-sm font-medium">
{t('workflow.auditHistory', { count: audit.length })}
</summary>
<ol className="divide-y">
{audit.map((activity) => (
<li key={activity.id} className="py-3">
<p className="text-sm">{describe(activity)}</p>
<p className="mt-1 text-xs text-muted-foreground">
{activity.actor.name} · {f.date(activity.occurredAt)}
</p>
</li>
))}
</ol>
</details>
)}
</div>
{edit && (
<Editor
title={t(existing ? 'workflow.editActivity' : 'workflow.addActivity')}
fields={[
{
name: 'kind',
options: m.capabilities.activityKinds.map((value) => ({
value,
label: t(`workflow.${value}`),
})),
},
{ name: 'text', type: 'textarea' },
]}
initial={{
kind: existing?.kind ?? m.capabilities.activityKinds[0]!,
text: existing?.text ?? '',
}}
schema={activityInputSchema}
build={(values) => ({ ...values, version: m.version })}
submit={(body) =>
action.mutate({
path: `/activities${existing ? `/${existing.id}` : ''}`,
method: existing ? 'PATCH' : 'POST',
body,
})
}
close={() => setEdit(null)}
pending={action.isPending}
/>
)}
</section>
);
}
const localDate = (value: string) => {
const date = new Date(value);
return new Date(date.getTime() - date.getTimezoneOffset() * 60000).toISOString().slice(0, 16);
};
const isoDate = (value: string) => {
const date = new Date(value);
return Number.isFinite(date.getTime()) ? date.toISOString() : '';
};
export function MerchantTasks({ merchant: m }: { merchant: MerchantDetail }) {
const { t } = useTranslation();
const [edit, setEdit] = useState<string | null>(null);
const action = useAction(m, () => setEdit(null));
const existing = m.tasks.find((task) => task.id === edit);
const complete = (task: Task) =>
action.mutate({
path: `/tasks/${task.id}`,
body: {
version: m.version,
title: task.title,
dueAt: task.dueAt,
remindAt: task.remindAt,
status: 'DONE',
},
});
return (
<section className="surface" id="tasks">
<SectionHeader
title={t('merchants.tasks')}
description={t('workflow.taskOwnership')}
action={
<Button
variant="outline"
onClick={() => {
action.reset();
setEdit('new');
}}
>
{t('workflow.addTask')}
</Button>
}
/>
<div className="p-5">{action.feedback}</div>
{m.tasks.map((task) => (
<div key={task.id} className="border-t">
<TaskRow task={task} />
{task.kind === m.capabilities.manageTaskKind && (
<div className="flex flex-wrap gap-2 px-5 pb-4">
<Button
variant="outline"
onClick={() => {
action.reset();
setEdit(task.id);
}}
>
{t('workflow.editTask')}
</Button>
{task.status === 'OPEN' && (
<Button variant="ghost" disabled={action.isPending} onClick={() => complete(task)}>
{t('workflow.complete')}
</Button>
)}
</div>
)}
</div>
))}
{edit && (
<Editor
title={t(existing ? 'workflow.editTask' : 'workflow.addTask')}
fields={[
{ name: 'title' },
{ name: 'dueAt', type: 'datetime-local' },
{ name: 'remindAt', type: 'datetime-local' },
{
name: 'status',
options: ['OPEN', 'DONE'].map((value) => ({ value, label: t(`tasks.${value}`) })),
},
]}
initial={{
title: existing?.title ?? '',
dueAt: localDate(existing?.dueAt ?? new Date(Date.now() + 86400000).toISOString()),
remindAt: existing?.remindAt ? localDate(existing.remindAt) : '',
status: existing?.status ?? 'OPEN',
}}
schema={taskInputSchema}
build={(values) => ({
...values,
version: m.version,
dueAt: isoDate(values.dueAt!),
remindAt: values.remindAt ? isoDate(values.remindAt) : null,
})}
submit={(body) =>
action.mutate({
path: `/tasks${existing ? `/${existing.id}` : ''}`,
method: existing ? 'PATCH' : 'POST',
body,
})
}
close={() => setEdit(null)}
pending={action.isPending}
/>
)}
</section>
);
}
export function RecentInteractions({ activities }: { activities: MerchantDetail['activities'] }) {
const { t } = useTranslation();
const f = useFormat();
const describe = useActivityText();
return (
<div className="divide-y px-5 sm:px-6">
{activities.map((activity) => (
<article key={activity.id} className="py-4">
<Link
className="text-sm font-semibold hover:underline"
to={`/app/merchants/${activity.merchant.id}`}
>
{activity.merchant.name}
</Link>
<p className="mt-1 text-xs text-muted-foreground">
{t(`workflow.${activity.kind}`)} · {activity.actor.name} ·{' '}
{f.relative(activity.occurredAt)}
</p>
<p className="mt-2 whitespace-pre-wrap break-words text-sm leading-relaxed">
{describe(activity)}
</p>
</article>
))}
</div>
);
}
+1 -1
View File
@@ -234,7 +234,7 @@ export function MerchantCard({ merchant }: { merchant: Merchant }) {
/> />
</div> </div>
<div className="mt-5 flex items-center justify-between gap-2 text-xs text-muted-foreground"> <div className="mt-5 flex items-center justify-between gap-2 text-xs text-muted-foreground">
<span>{merchant.owner.name.split(' ')[0]}</span> <span>{merchant.owner?.name.split(' ')[0] ?? t('workflow.unassigned')}</span>
<span className="flex items-center gap-1"> <span className="flex items-center gap-1">
<Clock3 className="size-3" aria-hidden="true" /> <Clock3 className="size-3" aria-hidden="true" />
{f.relative(merchant.stageEnteredAt)} {f.relative(merchant.stageEnteredAt)}
+3 -3
View File
@@ -40,9 +40,9 @@ export async function api<T>(
} }
if (!response.ok) { if (!response.ok) {
const body = await response.json().catch(() => ({})); const body = await response.json().catch(() => ({}));
if (response.status === 401 && !path.startsWith('/auth/')) { if (response.status === 401 && path !== '/auth/login') {
await queryClient.cancelQueries(); await queryClient.cancelQueries({ predicate: (query) => query.queryKey[0] !== 'session' });
queryClient.clear(); queryClient.removeQueries({ predicate: (query) => query.queryKey[0] !== 'session' });
queryClient.setQueryData(['session'], null); queryClient.setQueryData(['session'], null);
} }
throw new ApiError( throw new ApiError(
+8
View File
@@ -10,6 +10,14 @@ export function useFormat() {
shortDate: (value: string | Date) => shortDate: (value: string | Date) =>
new Intl.DateTimeFormat(locale, { day: 'numeric', month: 'short' }).format(new Date(value)), new Intl.DateTimeFormat(locale, { day: 'numeric', month: 'short' }).format(new Date(value)),
number: (value: number) => new Intl.NumberFormat(locale).format(value), number: (value: number) => new Intl.NumberFormat(locale).format(value),
usd: (value: string | null) =>
value === null
? '—'
: new Intl.NumberFormat(locale, {
style: 'currency',
currency: 'USD',
maximumFractionDigits: 2,
}).format(Number(value)),
country: (code: string) => new Intl.DisplayNames([locale], { type: 'region' }).of(code), country: (code: string) => new Intl.DisplayNames([locale], { type: 'region' }).of(code),
relative: (value: string) => { relative: (value: string) => {
const hours = Math.round((new Date(value).getTime() - Date.now()) / 3600000); const hours = Math.round((new Date(value).getTime() - Date.now()) / 3600000);
+12 -2
View File
@@ -1,4 +1,6 @@
import { workflowEn, workflowRu } from './workflow-locales';
export const en = { export const en = {
workflow: workflowEn,
common: { common: {
workspace: 'Workspace', workspace: 'Workspace',
team: 'Merchant workspace', team: 'Merchant workspace',
@@ -115,6 +117,10 @@ export const en = {
invalid: 'Please check this value.', invalid: 'Please check this value.',
}, },
errors: { errors: {
CONFLICT: 'This record changed. Review the latest information and try again.',
WORKFLOW_INVALID:
'This action requires a valid stage, complete documents and approval where applicable.',
REVIEW_LOCKED: 'This information is locked during or after review.',
UNAUTHORIZED: 'Sign in to continue.', UNAUTHORIZED: 'Sign in to continue.',
INVALID_CREDENTIALS: 'The email or password is incorrect.', INVALID_CREDENTIALS: 'The email or password is incorrect.',
FORBIDDEN: 'You do not have access to this view.', FORBIDDEN: 'You do not have access to this view.',
@@ -152,7 +158,7 @@ export const en = {
emptyActivity: 'No activity to show yet', emptyActivity: 'No activity to show yet',
scopeHead: 'Your entire merchant portfolio', scopeHead: 'Your entire merchant portfolio',
scopeManager: 'Your assigned merchants', scopeManager: 'Your assigned merchants',
scopeCompliance: 'Merchants in KYB and Compliance Review', scopeCompliance: 'Merchant context across the portfolio · personal compliance tasks',
}, },
merchants: { merchants: {
title: 'Merchants', title: 'Merchants',
@@ -233,6 +239,7 @@ export const en = {
}, },
}; };
export const ru = { export const ru = {
workflow: workflowRu,
common: { common: {
workspace: 'Рабочее пространство', workspace: 'Рабочее пространство',
team: 'Работа с мерчантами', team: 'Работа с мерчантами',
@@ -351,6 +358,9 @@ export const ru = {
invalid: 'Проверьте это значение.', invalid: 'Проверьте это значение.',
}, },
errors: { errors: {
CONFLICT: 'Запись изменилась. Проверьте актуальные данные и повторите действие.',
WORKFLOW_INVALID: 'Проверьте этап, готовность документов и наличие одобрения.',
REVIEW_LOCKED: 'Эти данные защищены от изменений во время и после проверки.',
UNAUTHORIZED: 'Войдите, чтобы продолжить.', UNAUTHORIZED: 'Войдите, чтобы продолжить.',
INVALID_CREDENTIALS: 'Неверная почта или пароль.', INVALID_CREDENTIALS: 'Неверная почта или пароль.',
FORBIDDEN: 'У вас нет доступа к этому разделу.', FORBIDDEN: 'У вас нет доступа к этому разделу.',
@@ -388,7 +398,7 @@ export const ru = {
emptyActivity: 'Событий пока нет', emptyActivity: 'Событий пока нет',
scopeHead: 'Весь портфель мерчантов', scopeHead: 'Весь портфель мерчантов',
scopeManager: 'Закреплённые за вами мерчанты', scopeManager: 'Закреплённые за вами мерчанты',
scopeCompliance: 'Мерчанты на KYB и комплаенс-проверке', scopeCompliance: 'Контекст всех мерчантов · личные комплаенс-задачи',
}, },
merchants: { merchants: {
title: 'Мерчанты', title: 'Мерчанты',
+42 -18
View File
@@ -1,3 +1,11 @@
import {
MerchantControls,
ChecklistControl,
ReviewHistory,
InteractionHistory,
MerchantTasks,
RecentInteractions,
} from '../components/merchant-workflow';
import { useEffect, useState } from 'react'; import { useEffect, useState } from 'react';
import { Link, useOutletContext, useParams, useSearchParams } from 'react-router'; import { Link, useOutletContext, useParams, useSearchParams } from 'react-router';
import { keepPreviousData, useQuery } from '@tanstack/react-query'; import { keepPreviousData, useQuery } from '@tanstack/react-query';
@@ -174,7 +182,7 @@ export function Dashboard() {
title={t('dashboard.activity')} title={t('dashboard.activity')}
description={t('dashboard.activityText')} description={t('dashboard.activityText')}
/> />
<ActivityFeed events={data.recentEvents} /> <RecentInteractions activities={data.recentActivities} />
</section> </section>
<section className="surface self-start"> <section className="surface self-start">
<SectionHeader <SectionHeader
@@ -255,7 +263,9 @@ function MerchantTable({ merchants }: { merchants: Merchant[] }) {
<TableCell className="text-xs text-muted-foreground"> <TableCell className="text-xs text-muted-foreground">
{f.country(m.country)} {f.country(m.country)}
</TableCell> </TableCell>
<TableCell className="text-xs">{m.owner.name}</TableCell> <TableCell className="text-xs">
{m.owner?.name ?? t('workflow.unassigned')}
</TableCell>
<TableCell className="pr-6 text-right text-xs text-muted-foreground"> <TableCell className="pr-6 text-right text-xs text-muted-foreground">
{f.shortDate(m.createdAt)} {f.shortDate(m.createdAt)}
</TableCell> </TableCell>
@@ -279,7 +289,9 @@ function MerchantTable({ merchants }: { merchants: Merchant[] }) {
</div> </div>
<div className="mt-4 flex flex-wrap items-center justify-between gap-2"> <div className="mt-4 flex flex-wrap items-center justify-between gap-2">
<StatusBadge status={m.status} /> <StatusBadge status={m.status} />
<span className="text-xs text-muted-foreground">{m.owner.name}</span> <span className="text-xs text-muted-foreground">
{m.owner?.name ?? t('workflow.unassigned')}
</span>
</div> </div>
</Link> </Link>
))} ))}
@@ -459,6 +471,7 @@ export function MerchantDetail() {
</p> </p>
</div> </div>
</div> </div>
<MerchantControls merchant={m} />
<div className="grid gap-6 xl:grid-cols-[1.15fr_1fr]"> <div className="grid gap-6 xl:grid-cols-[1.15fr_1fr]">
<div className="min-w-0 space-y-6"> <div className="min-w-0 space-y-6">
<section className="surface"> <section className="surface">
@@ -468,8 +481,28 @@ export function MerchantDetail() {
/> />
<dl className="grid grid-cols-1 gap-5 p-5 sm:grid-cols-2 sm:p-6"> <dl className="grid grid-cols-1 gap-5 p-5 sm:grid-cols-2 sm:p-6">
{[ {[
{ label: t('common.owner'), value: m.owner.name }, {
label: t('common.owner'),
value: m.owner?.name ?? t('workflow.unassigned'),
},
{ label: t('merchants.contact'), value: m.contactName }, { label: t('merchants.contact'), value: m.contactName },
...(
[
'legalName',
'registrationNumber',
'address',
'contactPhone',
'contactTitle',
] as const
).map((key) => ({ label: t(`workflow.${key}`), value: m[key] ?? '—' })),
{
label: t('workflow.estimatedMonthlyVolumeUsd'),
value: f.usd(m.estimatedMonthlyVolumeUsd),
},
{
label: t('workflow.source'),
value: m.source ? t(`workflow.${m.source}`) : '—',
},
{ {
label: t('merchants.website'), label: t('merchants.website'),
value: ( value: (
@@ -505,6 +538,7 @@ export function MerchantDetail() {
))} ))}
</dl> </dl>
</section> </section>
<ReviewHistory merchant={m} />
<section id="checklist" className="surface"> <section id="checklist" className="surface">
<SectionHeader <SectionHeader
title={t('merchants.checklist')} title={t('merchants.checklist')}
@@ -541,6 +575,7 @@ export function MerchantDetail() {
{t(`checklist.${doc.state}`)} {t(`checklist.${doc.state}`)}
</Badge> </Badge>
</div> </div>
<ChecklistControl merchant={m} item={doc} />
{doc.note && ( {doc.note && (
<p className="mt-2 text-xs leading-relaxed text-muted-foreground"> <p className="mt-2 text-xs leading-relaxed text-muted-foreground">
{doc.note} {doc.note}
@@ -580,19 +615,8 @@ export function MerchantDetail() {
/> />
<ActivityFeed events={m.events} detail /> <ActivityFeed events={m.events} detail />
</section> </section>
<section className="surface"> <MerchantTasks merchant={m} />
<SectionHeader <InteractionHistory merchant={m} />
title={t('merchants.tasks')}
description={t('merchants.tasksText')}
/>
<div className="mt-4">
{m.tasks.length ? (
m.tasks.map((task) => <TaskRow key={task.id} task={task} />)
) : (
<EmptyState title={t('merchants.noTasks')} />
)}
</div>
</section>
</div> </div>
</div> </div>
</> </>
@@ -787,7 +811,7 @@ export function ReviewQueue() {
{m.name} {m.name}
</Link> </Link>
<p className="mt-1 text-xs text-muted-foreground"> <p className="mt-1 text-xs text-muted-foreground">
{m.owner.name} · {t(`industry.${m.industry}`)} {m.owner?.name ?? t('workflow.unassigned')} · {t(`industry.${m.industry}`)}
</p> </p>
</div> </div>
</div> </div>
+2 -2
View File
@@ -147,8 +147,8 @@ export function Login() {
const demos = [ const demos = [
{ email: 'head', role: 'HEAD_OF_SALES' }, { email: 'head', role: 'HEAD_OF_SALES' },
{ email: 'compliance', role: 'COMPLIANCE_OFFICER' }, { email: 'compliance', role: 'COMPLIANCE_OFFICER' },
{ email: 'manager1', role: 'ACCOUNT_MANAGER', name: 'Alex' }, { email: 'alex', role: 'ACCOUNT_MANAGER', name: 'Alex' },
{ email: 'manager2', role: 'ACCOUNT_MANAGER', name: 'Maria' }, { email: 'sam', role: 'ACCOUNT_MANAGER', name: 'Sam' },
]; ];
return ( return (
<div className="grid min-h-dvh bg-white lg:grid-cols-2"> <div className="grid min-h-dvh bg-white lg:grid-cols-2">
+157
View File
@@ -0,0 +1,157 @@
export const workflowEn = {
auditHistory: 'Audit history ({{count}})',
detailsUpdated: 'Merchant details updated',
assignmentUpdated: 'Manager assignment updated',
activityEdited: 'Interaction edited',
taskUpdated: 'Task updated',
taskCreated: 'Task created',
checklistUpdated: 'Checklist updated: {{document}}',
reviewDecided: 'Compliance review: {{decision}}',
unassigned: 'Unassigned',
edit: 'Edit',
save: 'Save changes',
saving: 'Saving…',
cancel: 'Cancel',
saved: 'Changes saved.',
editMerchant: 'Edit merchant',
assign: 'Assign manager',
ownerId: 'Account manager',
advance: 'Move to {{stage}}',
identityLocked:
'Reviewed company and KYB information is locked. Contact and commercial details can still be updated.',
checklistEdit: 'Update document',
checklistHistory: 'Document history',
state: 'Document status',
note: 'Note',
reviews: 'Compliance reviews',
decide: 'Record decision',
decision: 'Decision',
reason: 'Decision reason',
correctionHint:
'For a correction request, describe the change needed for each affected document.',
APPROVED: 'Approved',
PENDING: 'Pending',
REJECTED: 'Rejected',
CORRECTIONS: 'Corrections requested',
cycle: 'Review {{cycle}}',
submitted: 'Submitted by {{name}} on {{date}}',
reviewed: 'Reviewed by {{name}} on {{date}}',
activities: 'Interactions and audit trail',
addActivity: 'Log interaction',
editActivity: 'Edit interaction',
kind: 'Interaction type',
text: 'Details',
NOTE: 'Note',
CALL: 'Call',
EMAIL: 'Email',
MEETING: 'Meeting',
KYB_NOTE: 'KYB note',
AUDIT: 'System history',
addTask: 'Add task',
editTask: 'Edit task',
complete: 'Complete task',
title: 'Task title',
dueAt: 'Due date and time',
remindAt: 'Reminder date and time',
status: 'Task status',
taskOwnership: 'Commercial tasks follow the assigned manager. Compliance tasks are personal.',
COMMERCIAL: 'Commercial',
COMPLIANCE: 'Compliance',
name: 'Company name',
legalName: 'Legal company name',
registrationNumber: 'Registration number',
address: 'Company address',
website: 'Website',
country: 'Country code',
industry: 'Industry',
contactName: 'Primary contact',
contactEmail: 'Contact email',
contactPhone: 'Contact phone',
contactTitle: 'Contact title',
estimatedMonthlyVolumeUsd: 'Estimated monthly processing (USD)',
source: 'Lead source',
INBOUND: 'Inbound enquiry',
OUTBOUND: 'Outbound outreach',
REFERRAL: 'Referral',
PARTNER: 'Partner',
EVENT: 'Event',
};
export const workflowRu: Record<keyof typeof workflowEn, string> = {
auditHistory: 'Журнал действий ({{count}})',
detailsUpdated: 'Данные мерчанта обновлены',
assignmentUpdated: 'Назначение менеджера изменено',
activityEdited: 'Взаимодействие изменено',
taskUpdated: 'Задача обновлена',
taskCreated: 'Задача создана',
checklistUpdated: 'Документ обновлён: {{document}}',
reviewDecided: 'Комплаенс-проверка: {{decision}}',
unassigned: 'Не назначен',
edit: 'Изменить',
save: 'Сохранить изменения',
saving: 'Сохраняем…',
cancel: 'Отмена',
saved: 'Изменения сохранены.',
editMerchant: 'Изменить мерчанта',
assign: 'Назначить менеджера',
ownerId: 'Аккаунт-менеджер',
advance: 'Перевести: {{stage}}',
identityLocked:
'Проверенные данные компании и KYB защищены от изменений. Контактные и коммерческие данные можно обновлять.',
checklistEdit: 'Обновить документ',
checklistHistory: 'История документа',
state: 'Статус документа',
note: 'Заметка',
reviews: 'Комплаенс-проверки',
decide: 'Записать решение',
decision: 'Решение',
reason: 'Основание решения',
correctionHint:
'Для запроса исправлений укажите необходимые изменения для каждого затронутого документа.',
APPROVED: 'Одобрено',
PENDING: 'Ожидает решения',
REJECTED: 'Отклонено',
CORRECTIONS: 'Запрошены исправления',
cycle: 'Проверка {{cycle}}',
submitted: 'Отправлено: {{name}}, {{date}}',
reviewed: 'Проверено: {{name}}, {{date}}',
activities: 'Взаимодействия и журнал действий',
addActivity: 'Добавить взаимодействие',
editActivity: 'Изменить взаимодействие',
kind: 'Тип взаимодействия',
text: 'Подробности',
NOTE: 'Заметка',
CALL: 'Звонок',
EMAIL: 'Письмо',
MEETING: 'Встреча',
KYB_NOTE: 'Заметка KYB',
AUDIT: 'Системная история',
addTask: 'Добавить задачу',
editTask: 'Изменить задачу',
complete: 'Выполнить задачу',
title: 'Название задачи',
dueAt: 'Дата и время выполнения',
remindAt: 'Дата и время напоминания',
status: 'Статус задачи',
taskOwnership:
'Коммерческие задачи закреплены за менеджером мерчанта. Комплаенс-задачи — личные.',
COMMERCIAL: 'Коммерческая',
COMPLIANCE: 'Комплаенс',
name: 'Название компании',
legalName: 'Юридическое название',
registrationNumber: 'Регистрационный номер',
address: 'Адрес компании',
website: 'Сайт',
country: 'Код страны',
industry: 'Отрасль',
contactName: 'Основной контакт',
contactEmail: 'Email контакта',
contactPhone: 'Телефон контакта',
contactTitle: 'Должность контакта',
estimatedMonthlyVolumeUsd: 'Месячный объём обработки (USD)',
source: 'Источник лида',
INBOUND: 'Входящий запрос',
OUTBOUND: 'Исходящий контакт',
REFERRAL: 'Рекомендация',
PARTNER: 'Партнёр',
EVENT: 'Мероприятие',
};
+37 -39
View File
@@ -1,50 +1,48 @@
# Implementation checklist # Implementation checklist
## Foundation ## Implemented
- [x] pnpm/Turbo workspace, pinned packages and lockfile - [x] Existing pnpm/Turbo, NestJS, React, PostgreSQL and Prisma foundation retained
- [x] Shared UI, browser-safe contracts, server-only database package - [x] Additive migration for merchant company/contact fields, decimal USD estimates, source, nullable manager, timestamps and versions
- [x] PostgreSQL Compose, migrations, repeatable four-account/eighteen-merchant seed - [x] Typed interactions, immutable audit events, checklist change history, review cycles/snapshots and attributed commercial/compliance tasks
- [x] Cookie sessions and server-enforced role scopes - [x] Hashed passwords, opaque database-backed sessions, cookie security, eight-hour expiry, rotation and logout
- [x] Scoped dashboard, merchants/detail, pipeline, tasks, review queue - [x] Trusted-Origin checks on every mutation and bounded IP/email login throttles with Retry-After
- [x] Responsive public landing, login, CRM shell, reusable states and controls - [x] Four demo identities: Head, Compliance, Alex and Sam; original user IDs/password hashes preserved
- [x] Persistent EN/RU UI, validation, statuses and formatting - [x] Query-level scoping for reads, search, totals, detail children, dashboards and writes
- [x] Setup documentation and environment examples - [x] Head-only manager lookup and reassignment with open commercial task handoff
- [x] Adjacent commercial stages, assignment prerequisite, complete KYB submission, immutable review decisions, corrections/resubmission and approval-gated activation
- [x] Reviewed company/KYB fields locked during and after review; Sales cannot override Compliance
- [x] Version-checked transactions serialize merchant and child mutations; stale updates return 409
- [x] Merchant editing, assignment, collection, review, interaction and task UI; server-derived capabilities
- [x] EN/RU controls and validation, nullable-owner rendering, USD formatting, local date/time input and protected routes
- [x] Repeatable 45-merchant seed with 90-day histories, five unassigned leads and balanced 20-merchant manager portfolios
- [x] Recognition-based legacy enrichment; edited/unrecognized legacy fixtures preserved without inferred approvals
- [x] Documentation updated for endpoints, credentials, security, workflow and migration behavior
## Verification (record actual outcomes) ## Verification · 24 September 2026
- [x] Frozen install, build, lint, typecheck, unit tests | Check | Actual outcome |
- [x] Isolated PostgreSQL integration tests: auth, expiry, access, metrics, seed repeatability | ---------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
- [x] Direct and proxied database-aware health endpoint | Build | All workspace packages built; browser bundle excludes database/Prisma dependencies |
- [x] Browser checks at 390px/1440px, EN/RU, all roles and navigation | Lint and typecheck | Passed |
- [x] Keyboard, reduced motion, loading/error/empty states and overflow | Unit tests | 8 passed: contracts, localization, return paths, scopes and password hashing |
- [x] Browser bundle excludes Prisma/database dependencies | Integration tests | 18 passed against disposable PostgreSQL on 55441 |
| Authorization coverage | Both manager-to-manager attack directions, hidden children, forbidden field injection, personal Compliance tasks, Head-only lookup, anonymous and origin denial |
| Workflow coverage | Corrections/resubmission, approval, rejection, approval-required activation, immutable decisions, concurrent decisions and reassignment races |
| Seed coverage | Fresh 45-record fixtures; edited merchant/task/password preservation; legacy account migration; unchanged original records; no inferred approvals for modified legacy fixtures |
| Browser tests | 8 passed: EN/RU at 390px/1440px, editor sheets, all four accounts, assignment, editing, tasks, corrections, approval, activation and reassignment |
| Session/browser coverage | Logout, expiry, account switching, private-cache clearing, no auth tokens in localStorage, protected routes, loading/error/empty states, keyboard and reduced motion |
| Format and whitespace | Prettier check and git diff check passed |
| Development database upgrade | Applied migration and seed; compared all 18 original merchants, stage events, notes, checklist values, original tasks and password hashes: unchanged; 45 merchants after upgrade |
### Results · 24 September 2026 A pre-upgrade development backup was saved locally at `/tmp/merchantflow-before-onboarding-yn40uh40.dump`. Tests recreate only the disposable `db-test` service, never the development `db` service. Integration and browser suites run sequentially. Screenshots/traces are in ignored `test-results/` and `playwright-report/` directories.
| Check | Actual outcome | Development smoke checks passed through both `localhost:5173` and `127.0.0.1:5173`: healthy database, successful login for all four accounts, 45 merchants for Head/Compliance, 20 for each manager, and 401 when reusing every revoked session. The API health check also passed directly on port 3001.
| -------------------------------- | ------------------------------------------------------------------------------------------------------------------------------ |
| `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. Visual inspection covered the completed approval-to-Live detail screen and the mobile Russian editor. Audit records are collapsed in merchant detail, with translated system labels; the complete history remains available.
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. Existing dependency warnings are non-fatal: Zod/Rollup annotation placement and the Prisma PostgreSQL adapter's pg concurrent-query deprecation. All checks above passed despite these warnings.
## Deferred intentionally ## Boundaries
- [ ] Merchant editing and assignment No staff registration, merchant creation/deletion UI, merchant portal, uploads, payment processing, external KYB service, external reminders or deployment. Login rate-limit buckets are intentionally in-process for this single-process local prototype. Seed dates are anchored once and naturally age; reruns do not refresh deadlines or rewrite existing edits.
- [ ] 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.
+22 -10
View File
@@ -1,25 +1,37 @@
# MerchantFlow product brief # 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. A local merchant-onboarding CRM for a fictional crypto-payment provider, with persisted records, real authentication, permission-enforced workflows, responsive navigation and EN/RU localization.
## People and access ## 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. Four seeded staff accounts: Head of Sales, Compliance Officer, Alex Morgan and Sam Taylor. Head sees the portfolio and team activity, assigns/reassigns managers and manages commercial onboarding. Managers see and edit only assigned merchants and related commercial activities/tasks; they cannot change ownership. Compliance sees merchant context and KYB across the portfolio, records reviews and KYB notes, and manages personal compliance tasks. Compliance cannot edit commercial details, change ownership or activate merchants. Sales cannot issue or override compliance decisions. The Review Queue is Compliance-only.
NestJS authorization and database predicates apply to all reads, searches, counts, detail children, dashboards and mutations. A hidden resource returns 404; a forbidden action on a visible resource returns 403. The UI reflects server capabilities.
## Onboarding ## Onboarding
New Lead → Contacted → Qualified → KYB → Compliance Review → Integration → Testing → Live. New Lead → Contacted → Qualified → KYB → Compliance Review → Integration → Testing → Live. Rejected is an alternate terminal outcome; neither Live nor Rejected has outgoing stage actions. The same merchant ID persists throughout.
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. Assignment is required before leaving New Lead. Sales collects the four KYB documents. All must have received-history evidence before submission creates a pending review. Reviewed company/KYB fields freeze during review. Compliance approval advances to Integration; rejection requires a reason; corrections require a reason and item-specific notes and return the merchant to KYB. Resubmission creates another review cycle. Decisions are immutable.
## Foundation journeys Reviewed company identity, website, country, industry and KYB items remain locked after approval. Contact details, volume estimates, source and authorized ownership can change. Head or the assigned manager may advance Integration → Testing → Live only with matching approval/checklist evidence. Reassignment transfers open commercial tasks, preserving completed attribution and personal Compliance tasks.
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. ## Journeys and records
Landing → email/password login → role-scoped dashboard → merchant search/filter → detail, editing, assignment, checklist, reviews, interactions, history and tasks. Pipeline, Tasks and Compliance Review Queue provide dedicated views. Tasks can be created, edited and completed from merchant details; reminders stay in the app.
Merchants include company and primary-contact details, website, country, industry, decimal USD volume estimates, source, nullable manager, stage, timestamps and a concurrency version. Related models retain activities, stage events, checklist changes, review snapshots and task attribution. Mutations and audit history commit atomically and reject stale versions.
## Authentication and demo data
Salted password hashes; opaque eight-hour database-backed sessions in HttpOnly, SameSite cookies; Secure cookies in production; exact trusted-Origin checks for all mutations; bounded IP/email login limits. No authentication tokens in browser storage and no public staff registration.
Demo addresses: head@merchantflow.test, compliance@merchantflow.test, alex@merchantflow.test, sam@merchantflow.test. Initial password: `MerchantFlow123!`. Seed 45 fictional merchants, five unassigned New Leads and 20 per manager, across all stages. Histories span 90 days and include interactions, document corrections, review outcomes and overdue/upcoming/completed tasks. Advanced successful fixtures have valid approval and checklist history. Dashboard values derive from those records.
Seeding uses stable IDs, a stored date anchor and a version marker. It preserves edits and existing passwords. Only recognized unchanged foundation fixtures receive inferred historical enrichment; modified legacy fixtures are reported and preserved.
## Defaults and boundaries ## 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. English is the default; EN/RU selection persists in browser storage. Dates use the selected locale and viewer's time zone. Names and notes remain verbatim; canonical status/role labels are translated. Retain the light neutral UI, lime accents, visible focus, touch-sized controls and reduced-motion support.
## Later milestones No merchant creation/deletion UI, staff registration, merchant self-service, real payments, external KYB integration, uploads, external notifications or deployment.
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.
+166 -3
View File
@@ -41,6 +41,9 @@ export const errorCodes = [
'INTERNAL_ERROR', 'INTERNAL_ERROR',
'DATABASE_UNAVAILABLE', 'DATABASE_UNAVAILABLE',
'TOO_MANY_REQUESTS', 'TOO_MANY_REQUESTS',
'CONFLICT',
'WORKFLOW_INVALID',
'REVIEW_LOCKED',
] as const; ] as const;
export const apiErrorSchema = z.object({ export const apiErrorSchema = z.object({
code: z.enum(errorCodes), code: z.enum(errorCodes),
@@ -62,10 +65,19 @@ export const merchantSchema = z.object({
country: z.string(), country: z.string(),
contactName: z.string(), contactName: z.string(),
contactEmail: z.string(), contactEmail: z.string(),
legalName: z.string().nullable(),
registrationNumber: z.string().nullable(),
address: z.string().nullable(),
contactPhone: z.string().nullable(),
contactTitle: z.string().nullable(),
estimatedMonthlyVolumeUsd: z.string().nullable(),
source: z.string().nullable(),
version: z.number().int(),
updatedAt: date,
status: statusSchema, status: statusSchema,
createdAt: date, createdAt: date,
stageEnteredAt: date, stageEnteredAt: date,
owner: userSchema.pick({ id: true, name: true }), owner: userSchema.pick({ id: true, name: true }).nullable(),
}); });
export type Merchant = z.infer<typeof merchantSchema>; export type Merchant = z.infer<typeof merchantSchema>;
export const merchantListSchema = z.object({ export const merchantListSchema = z.object({
@@ -88,11 +100,16 @@ export const taskSchema = z.object({
id: z.string(), id: z.string(),
title: z.string(), title: z.string(),
status: z.enum(['OPEN', 'DONE']), status: z.enum(['OPEN', 'DONE']),
kind: z.enum(['COMMERCIAL', 'COMPLIANCE']),
createdAt: date,
updatedAt: date,
dueAt: date, dueAt: date,
remindAt: date.nullable(), remindAt: date.nullable(),
completedAt: date.nullable(), completedAt: date.nullable(),
merchant: z.object({ id: z.string(), name: z.string() }), merchant: z.object({ id: z.string(), name: z.string() }),
assignee: z.object({ name: z.string() }), assignee: z.object({ id: z.string(), name: z.string() }),
creator: z.object({ name: z.string() }).nullable(),
completedBy: z.object({ name: z.string() }).nullable(),
}); });
export type Task = z.infer<typeof taskSchema>; export type Task = z.infer<typeof taskSchema>;
export const taskListSchema = z.array(taskSchema); export const taskListSchema = z.array(taskSchema);
@@ -102,6 +119,36 @@ export const documentCodes = [
'UBO_IDENTIFICATION', 'UBO_IDENTIFICATION',
'BUSINESS_ACTIVITY', 'BUSINESS_ACTIVITY',
] as const; ] as const;
export const activityKinds = ['NOTE', 'CALL', 'EMAIL', 'MEETING', 'KYB_NOTE'] as const;
export const activitySchema = z.object({
id: z.string(),
kind: z.enum([...activityKinds, 'AUDIT']),
text: z.string(),
occurredAt: date,
updatedAt: date,
actor: z.object({ id: z.string(), name: z.string() }),
merchant: z.object({ id: z.string(), name: z.string() }),
});
export const reviewSchema = z.object({
id: z.string(),
cycle: z.number(),
decision: z.enum(['PENDING', 'APPROVED', 'CORRECTIONS', 'REJECTED']),
reason: z.string().nullable(),
submittedAt: date,
decidedAt: date.nullable(),
submittedBy: z.object({ name: z.string() }),
reviewer: z.object({ name: z.string() }).nullable(),
});
export const capabilitiesSchema = z.object({
editCommercial: z.boolean(),
editIdentity: z.boolean(),
assign: z.boolean(),
collectChecklist: z.boolean(),
review: z.boolean(),
activityKinds: z.array(z.enum(activityKinds)),
manageTaskKind: z.enum(['COMMERCIAL', 'COMPLIANCE']),
nextStage: statusSchema.nullable(),
});
export const merchantDetailSchema = merchantSchema.extend({ export const merchantDetailSchema = merchantSchema.extend({
checklist: z.array( checklist: z.array(
z.object({ z.object({
@@ -109,6 +156,16 @@ export const merchantDetailSchema = merchantSchema.extend({
documentCode: z.enum(documentCodes), documentCode: z.enum(documentCodes),
state: z.enum(['MISSING', 'RECEIVED', 'NEEDS_CORRECTION']), state: z.enum(['MISSING', 'RECEIVED', 'NEEDS_CORRECTION']),
note: z.string().nullable(), note: z.string().nullable(),
changes: z.array(
z.object({
id: z.string(),
fromState: z.enum(['MISSING', 'RECEIVED', 'NEEDS_CORRECTION']).nullable(),
toState: z.enum(['MISSING', 'RECEIVED', 'NEEDS_CORRECTION']),
note: z.string().nullable(),
occurredAt: date,
actor: z.object({ name: z.string() }),
}),
),
}), }),
), ),
notes: z.array( notes: z.array(
@@ -121,7 +178,11 @@ export const merchantDetailSchema = merchantSchema.extend({
), ),
events: z.array(eventSchema), events: z.array(eventSchema),
tasks: taskListSchema, tasks: taskListSchema,
activities: z.array(activitySchema),
reviews: z.array(reviewSchema),
capabilities: capabilitiesSchema,
}); });
export type MerchantDetail = z.infer<typeof merchantDetailSchema>;
export const dashboardSchema = z.object({ export const dashboardSchema = z.object({
merchantCount: z.number(), merchantCount: z.number(),
reviewCount: z.number(), reviewCount: z.number(),
@@ -130,11 +191,113 @@ export const dashboardSchema = z.object({
distribution: z.array(z.object({ status: statusSchema, count: z.number() })), distribution: z.array(z.object({ status: statusSchema, count: z.number() })),
recentEvents: z.array(eventSchema), recentEvents: z.array(eventSchema),
upcomingTasks: taskListSchema, upcomingTasks: taskListSchema,
recentActivities: z.array(activitySchema),
}); });
export const pipelineSchema = z.array(merchantSchema); export const pipelineSchema = z.array(merchantSchema);
export const healthSchema = z.object({ status: z.literal('ok'), database: z.literal('connected') }); export const healthSchema = z.object({ status: z.literal('ok'), database: z.literal('connected') });
// Navigation metadata only; write permissions are intentionally deferred. export const sources = ['INBOUND', 'OUTBOUND', 'REFERRAL', 'PARTNER', 'EVENT'] as const;
export const industries = ['ECOMMERCE', 'SOFTWARE', 'TRAVEL', 'SERVICES'] as const;
const text = z
.string()
.min(1)
.max(200)
.refine((value) => !!value.trim());
const optionalText = z.string().max(500).nullable();
export const versionSchema = z.object({ version: z.number().int().nonnegative() });
export const merchantEditSchema = versionSchema
.extend({
name: text.optional(),
legalName: text.optional(),
registrationNumber: optionalText.optional(),
address: optionalText.optional(),
website: z
.url()
.refine((v) => /^https?:\/\//.test(v))
.optional(),
country: z
.string()
.regex(/^[A-Z]{2}$/)
.optional(),
industry: z.enum(industries).optional(),
contactName: text.optional(),
contactEmail: z.email().max(254).optional(),
contactPhone: optionalText.optional(),
contactTitle: optionalText.optional(),
estimatedMonthlyVolumeUsd: z
.string()
.regex(/^(?:0|[1-9]\d{0,11})(?:\.\d{1,2})?$/)
.optional(),
source: z.enum(sources).optional(),
})
.strict();
export const assignmentSchema = versionSchema.extend({ ownerId: text }).strict();
export const transitionSchema = versionSchema.extend({ toStatus: statusSchema }).strict();
export const checklistEditSchema = versionSchema
.extend({
state: z.enum(['MISSING', 'RECEIVED']),
note: z.string().max(2000).nullable(),
})
.strict();
export const reviewDecisionSchema = versionSchema
.extend({
decision: z.enum(['APPROVED', 'REJECTED', 'CORRECTIONS']),
reason: z.string().max(2000).default(''),
corrections: z
.array(
z
.object({
itemId: text,
note: z
.string()
.min(1)
.max(2000)
.refine((value) => !!value.trim()),
})
.strict(),
)
.default([]),
})
.strict()
.superRefine((v, ctx) => {
if (v.decision !== 'APPROVED' && !v.reason.trim())
ctx.addIssue({ code: 'custom', path: ['reason'], message: 'validation.required' });
if (v.decision === 'CORRECTIONS' && !v.corrections.length)
ctx.addIssue({ code: 'custom', path: ['corrections'], message: 'validation.required' });
if (v.decision !== 'CORRECTIONS' && v.corrections.length)
ctx.addIssue({ code: 'custom', path: ['corrections'], message: 'validation.invalid' });
if (new Set(v.corrections.map((c) => c.itemId)).size !== v.corrections.length)
ctx.addIssue({ code: 'custom', path: ['corrections'], message: 'validation.invalid' });
});
export const activityInputSchema = versionSchema
.extend({
kind: z.enum(activityKinds),
text: z
.string()
.min(1)
.max(5000)
.refine((v) => !!v.trim()),
})
.strict();
export const taskInputSchema = versionSchema
.extend({
title: z
.string()
.min(1)
.max(200)
.refine((v) => !!v.trim()),
dueAt: date,
remindAt: date.nullable(),
status: z.enum(['OPEN', 'DONE']),
})
.strict()
.refine((v) => !v.remindAt || v.remindAt <= v.dueAt, {
message: 'validation.invalid',
path: ['remindAt'],
});
export const managerListSchema = z.array(userSchema.pick({ id: true, name: true, email: true }));
export const mutationResultSchema = z.object({ ok: z.literal(true) });
export function canSeeReviewQueue(role: Role) { export function canSeeReviewQueue(role: Role) {
return role === 'COMPLIANCE_OFFICER'; return role === 'COMPLIANCE_OFFICER';
} }
@@ -0,0 +1,159 @@
-- CreateEnum
CREATE TYPE "TaskKind" AS ENUM ('COMMERCIAL', 'COMPLIANCE');
-- CreateEnum
CREATE TYPE "ActivityKind" AS ENUM ('NOTE', 'CALL', 'EMAIL', 'MEETING', 'KYB_NOTE', 'AUDIT');
-- CreateEnum
CREATE TYPE "ReviewDecision" AS ENUM ('PENDING', 'APPROVED', 'CORRECTIONS', 'REJECTED');
-- DropForeignKey
ALTER TABLE "Merchant" DROP CONSTRAINT "Merchant_ownerId_fkey";
-- AlterTable
ALTER TABLE "User" ADD COLUMN "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
ADD COLUMN "updatedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP;
-- AlterTable
ALTER TABLE "Session" ADD COLUMN "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP;
-- AlterTable
ALTER TABLE "Merchant" ADD COLUMN "address" TEXT,
ADD COLUMN "contactPhone" TEXT,
ADD COLUMN "contactTitle" TEXT,
ADD COLUMN "estimatedMonthlyVolumeUsd" DECIMAL(18,2),
ADD COLUMN "legalName" TEXT,
ADD COLUMN "registrationNumber" TEXT,
ADD COLUMN "source" TEXT,
ADD COLUMN "updatedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
ADD COLUMN "version" INTEGER NOT NULL DEFAULT 0,
ALTER COLUMN "ownerId" DROP NOT NULL;
-- AlterTable
ALTER TABLE "KybChecklistItem" ADD COLUMN "updatedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP;
-- AlterTable
ALTER TABLE "Task" ADD COLUMN "completedById" TEXT,
ADD COLUMN "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
ADD COLUMN "creatorId" TEXT,
ADD COLUMN "kind" "TaskKind" NOT NULL DEFAULT 'COMMERCIAL',
ADD COLUMN "updatedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP;
-- CreateTable
CREATE TABLE "Activity" (
"id" TEXT NOT NULL,
"merchantId" TEXT NOT NULL,
"actorId" TEXT NOT NULL,
"kind" "ActivityKind" NOT NULL,
"text" TEXT NOT NULL,
"occurredAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"metadata" JSONB,
CONSTRAINT "Activity_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "ChecklistChange" (
"id" TEXT NOT NULL,
"itemId" TEXT NOT NULL,
"actorId" TEXT NOT NULL,
"fromState" "ChecklistState",
"toState" "ChecklistState" NOT NULL,
"note" TEXT,
"occurredAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "ChecklistChange_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "ComplianceReview" (
"id" TEXT NOT NULL,
"merchantId" TEXT NOT NULL,
"cycle" INTEGER NOT NULL,
"submittedById" TEXT NOT NULL,
"reviewerId" TEXT,
"decision" "ReviewDecision" NOT NULL DEFAULT 'PENDING',
"reason" TEXT,
"submittedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"decidedAt" TIMESTAMP(3),
"snapshot" JSONB NOT NULL,
CONSTRAINT "ComplianceReview_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "DemoSeedState" (
"id" TEXT NOT NULL,
"anchorAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "DemoSeedState_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "DemoSeedRecord" (
"merchantId" TEXT NOT NULL,
"version" INTEGER NOT NULL,
"appliedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "DemoSeedRecord_pkey" PRIMARY KEY ("merchantId")
);
-- CreateIndex
CREATE INDEX "Activity_merchantId_occurredAt_idx" ON "Activity"("merchantId", "occurredAt");
-- CreateIndex
CREATE INDEX "Activity_occurredAt_idx" ON "Activity"("occurredAt");
-- CreateIndex
CREATE INDEX "ChecklistChange_itemId_occurredAt_idx" ON "ChecklistChange"("itemId", "occurredAt");
-- CreateIndex
CREATE INDEX "ComplianceReview_decision_submittedAt_idx" ON "ComplianceReview"("decision", "submittedAt");
-- CreateIndex
CREATE UNIQUE INDEX "ComplianceReview_merchantId_cycle_key" ON "ComplianceReview"("merchantId", "cycle");
-- CreateIndex
CREATE INDEX "Task_assigneeId_kind_status_dueAt_idx" ON "Task"("assigneeId", "kind", "status", "dueAt");
-- AddForeignKey
ALTER TABLE "Merchant" ADD CONSTRAINT "Merchant_ownerId_fkey" FOREIGN KEY ("ownerId") REFERENCES "User"("id") ON DELETE SET NULL ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "Task" ADD CONSTRAINT "Task_creatorId_fkey" FOREIGN KEY ("creatorId") REFERENCES "User"("id") ON DELETE SET NULL ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "Task" ADD CONSTRAINT "Task_completedById_fkey" FOREIGN KEY ("completedById") REFERENCES "User"("id") ON DELETE SET NULL ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "Activity" ADD CONSTRAINT "Activity_merchantId_fkey" FOREIGN KEY ("merchantId") REFERENCES "Merchant"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "Activity" ADD CONSTRAINT "Activity_actorId_fkey" FOREIGN KEY ("actorId") REFERENCES "User"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "ChecklistChange" ADD CONSTRAINT "ChecklistChange_itemId_fkey" FOREIGN KEY ("itemId") REFERENCES "KybChecklistItem"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "ChecklistChange" ADD CONSTRAINT "ChecklistChange_actorId_fkey" FOREIGN KEY ("actorId") REFERENCES "User"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "ComplianceReview" ADD CONSTRAINT "ComplianceReview_merchantId_fkey" FOREIGN KEY ("merchantId") REFERENCES "Merchant"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "ComplianceReview" ADD CONSTRAINT "ComplianceReview_submittedById_fkey" FOREIGN KEY ("submittedById") REFERENCES "User"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "ComplianceReview" ADD CONSTRAINT "ComplianceReview_reviewerId_fkey" FOREIGN KEY ("reviewerId") REFERENCES "User"("id") ON DELETE SET NULL ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "DemoSeedRecord" ADD CONSTRAINT "DemoSeedRecord_merchantId_fkey" FOREIGN KEY ("merchantId") REFERENCES "Merchant"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- Only one open review may exist for a merchant, including concurrent submissions.
CREATE UNIQUE INDEX "ComplianceReview_one_pending" ON "ComplianceReview" ("merchantId") WHERE "decision" = 'PENDING';
ALTER TABLE "Merchant" ADD CONSTRAINT "Merchant_volume_nonnegative" CHECK ("estimatedMonthlyVolumeUsd" >= 0);
ALTER TABLE "ComplianceReview" ADD CONSTRAINT "ComplianceReview_decision_evidence" CHECK (
("decision" = 'PENDING' AND "reviewerId" IS NULL AND "decidedAt" IS NULL) OR
("decision" <> 'PENDING' AND "reviewerId" IS NOT NULL AND "decidedAt" IS NOT NULL AND "decidedAt" >= "submittedAt"
AND ("decision" = 'APPROVED' OR ("reason" IS NOT NULL AND length(trim("reason")) > 0)))
);
+106 -4
View File
@@ -37,6 +37,24 @@ enum TaskStatus {
OPEN OPEN
DONE DONE
} }
enum TaskKind {
COMMERCIAL
COMPLIANCE
}
enum ActivityKind {
NOTE
CALL
EMAIL
MEETING
KYB_NOTE
AUDIT
}
enum ReviewDecision {
PENDING
APPROVED
CORRECTIONS
REJECTED
}
model User { model User {
id String @id @default(uuid()) id String @id @default(uuid())
email String @unique email String @unique
@@ -47,12 +65,21 @@ model User {
merchants Merchant[] merchants Merchant[]
events StatusEvent[] events StatusEvent[]
notes MerchantNote[] notes MerchantNote[]
tasks Task[] tasks Task[] @relation("TaskAssignee")
createdTasks Task[] @relation("TaskCreator")
completedTasks Task[] @relation("TaskCompleter")
activities Activity[]
checklistChanges ChecklistChange[]
submittedReviews ComplianceReview[] @relation("ReviewSubmitter")
decidedReviews ComplianceReview[] @relation("ReviewReviewer")
createdAt DateTime @default(now())
updatedAt DateTime @default(now()) @updatedAt
} }
model Session { model Session {
id String @id id String @id
userId String userId String
expiresAt DateTime expiresAt DateTime
createdAt DateTime @default(now())
user User @relation(fields: [userId], references: [id], onDelete: Cascade) user User @relation(fields: [userId], references: [id], onDelete: Cascade)
@@index([expiresAt]) @@index([expiresAt])
} }
@@ -64,15 +91,27 @@ model Merchant {
country String country String
contactName String contactName String
contactEmail String contactEmail String
legalName String?
registrationNumber String?
address String?
contactPhone String?
contactTitle String?
estimatedMonthlyVolumeUsd Decimal? @db.Decimal(18, 2)
source String?
status MerchantStatus @default(NEW_LEAD) status MerchantStatus @default(NEW_LEAD)
ownerId String ownerId String?
createdAt DateTime @default(now()) createdAt DateTime @default(now())
updatedAt DateTime @default(now()) @updatedAt
version Int @default(0)
stageEnteredAt DateTime @default(now()) stageEnteredAt DateTime @default(now())
owner User @relation(fields: [ownerId], references: [id]) owner User? @relation(fields: [ownerId], references: [id])
events StatusEvent[] events StatusEvent[]
checklist KybChecklistItem[] checklist KybChecklistItem[]
notes MerchantNote[] notes MerchantNote[]
tasks Task[] tasks Task[]
activities Activity[]
reviews ComplianceReview[]
seedRecord DemoSeedRecord?
@@index([ownerId, status]) @@index([ownerId, status])
@@index([status, stageEnteredAt]) @@index([status, stageEnteredAt])
} }
@@ -95,6 +134,8 @@ model KybChecklistItem {
documentCode DocumentCode documentCode DocumentCode
state ChecklistState @default(MISSING) state ChecklistState @default(MISSING)
note String? note String?
updatedAt DateTime @default(now()) @updatedAt
changes ChecklistChange[]
merchant Merchant @relation(fields: [merchantId], references: [id], onDelete: Cascade) merchant Merchant @relation(fields: [merchantId], references: [id], onDelete: Cascade)
@@unique([merchantId, documentCode]) @@unique([merchantId, documentCode])
} }
@@ -114,10 +155,71 @@ model Task {
assigneeId String assigneeId String
title String title String
status TaskStatus @default(OPEN) status TaskStatus @default(OPEN)
kind TaskKind @default(COMMERCIAL)
creatorId String?
completedById String?
createdAt DateTime @default(now())
updatedAt DateTime @default(now()) @updatedAt
dueAt DateTime dueAt DateTime
remindAt DateTime? remindAt DateTime?
completedAt DateTime? completedAt DateTime?
merchant Merchant @relation(fields: [merchantId], references: [id], onDelete: Cascade) merchant Merchant @relation(fields: [merchantId], references: [id], onDelete: Cascade)
assignee User @relation(fields: [assigneeId], references: [id]) assignee User @relation("TaskAssignee", fields: [assigneeId], references: [id])
creator User? @relation("TaskCreator", fields: [creatorId], references: [id])
completedBy User? @relation("TaskCompleter", fields: [completedById], references: [id])
@@index([merchantId, status, dueAt]) @@index([merchantId, status, dueAt])
@@index([assigneeId, kind, status, dueAt])
}
model Activity {
id String @id @default(uuid())
merchantId String
actorId String
kind ActivityKind
text String
occurredAt DateTime @default(now())
updatedAt DateTime @default(now()) @updatedAt
metadata Json?
merchant Merchant @relation(fields: [merchantId], references: [id], onDelete: Cascade)
actor User @relation(fields: [actorId], references: [id])
@@index([merchantId, occurredAt])
@@index([occurredAt])
}
model ChecklistChange {
id String @id @default(uuid())
itemId String
actorId String
fromState ChecklistState?
toState ChecklistState
note String?
occurredAt DateTime @default(now())
item KybChecklistItem @relation(fields: [itemId], references: [id], onDelete: Cascade)
actor User @relation(fields: [actorId], references: [id])
@@index([itemId, occurredAt])
}
model ComplianceReview {
id String @id @default(uuid())
merchantId String
cycle Int
submittedById String
reviewerId String?
decision ReviewDecision @default(PENDING)
reason String?
submittedAt DateTime @default(now())
decidedAt DateTime?
snapshot Json
merchant Merchant @relation(fields: [merchantId], references: [id], onDelete: Cascade)
submittedBy User @relation("ReviewSubmitter", fields: [submittedById], references: [id])
reviewer User? @relation("ReviewReviewer", fields: [reviewerId], references: [id])
@@unique([merchantId, cycle])
@@index([decision, submittedAt])
}
model DemoSeedState {
id String @id
anchorAt DateTime @default(now())
}
model DemoSeedRecord {
merchantId String @id
version Int
appliedAt DateTime @default(now())
merchant Merchant @relation(fields: [merchantId], references: [id], onDelete: Cascade)
} }
+1
View File
@@ -2,6 +2,7 @@ import { PrismaClient } from './generated/prisma/client.js';
import { PrismaPg } from '@prisma/adapter-pg'; import { PrismaPg } from '@prisma/adapter-pg';
export { PrismaClient }; export { PrismaClient };
export { hashPassword, verifyPassword } from './password.js'; export { hashPassword, verifyPassword } from './password.js';
export { reviewSnapshot, checklistComplete, snapshotsEqual, reviewedFields } from './workflow.js';
export type { Prisma } from './generated/prisma/client.js'; export type { Prisma } from './generated/prisma/client.js';
export function createDatabase(url: string) { export function createDatabase(url: string) {
return new PrismaClient({ return new PrismaClient({
+575 -135
View File
@@ -1,38 +1,14 @@
import { config } from 'dotenv'; import { config } from 'dotenv';
import { statuses, successfulStages, documentCodes, type Status } from '@merchantflow/contracts'; import { documentCodes, sources, successfulStages, type Status } from '@merchantflow/contracts';
import { createDatabase } from './index.js'; import { createDatabase, type Prisma } from './index.js';
import { hashPassword } from './password.js'; import { hashPassword } from './password.js';
import { reviewSnapshot } from './workflow.js';
config({ path: new URL('../../../.env', import.meta.url).pathname, quiet: true }); config({ path: new URL('../../../.env', import.meta.url).pathname, quiet: true });
const db = createDatabase( const db = createDatabase(
process.env.DATABASE_URL ?? process.env.DATABASE_URL ??
'postgresql://merchantflow:merchantflow_local@localhost:55440/merchantflow', 'postgresql://merchantflow:merchantflow_local@localhost:55440/merchantflow',
); );
const users = [ const day = 86400000;
{
id: 'user-head',
email: '[email protected]',
name: 'Elena Carter',
role: 'HEAD_OF_SALES' as const,
},
{
id: 'user-compliance',
email: '[email protected]',
name: 'Pavel Sokolov',
role: 'COMPLIANCE_OFFICER' as const,
},
{
id: 'user-manager1',
email: '[email protected]',
name: 'Alex Morgan',
role: 'ACCOUNT_MANAGER' as const,
},
{
id: 'user-manager2',
email: '[email protected]',
name: 'Maria Chen',
role: 'ACCOUNT_MANAGER' as const,
},
];
const names = [ const names = [
'Orbit Goods', 'Orbit Goods',
'Northstar Studio', 'Northstar Studio',
@@ -52,122 +28,586 @@ const names = [
'Kinfolk Supply', 'Kinfolk Supply',
'Peak Ventures', 'Peak Ventures',
'Amber Exchange', 'Amber Exchange',
'Willow Ceramics',
'Cobalt Software',
'Meadow Retreats',
'Cedar Workshop',
'Tide Cart',
'Juniper Tools',
'Alpine Desk',
'Maple Routes',
'Vela Systems',
'Pebble Goods',
'Clover Services',
'Finch Travel',
'Birch Trading',
'Harbor Learning',
'Coral Works',
'Spruce Studio',
'Mosaic Rentals',
'Copper Cloud',
'Elm Outfitters',
'Hearth Home',
'Quartz Analytics',
'Dune Apparel',
'Marble Market',
'Saffron Supply',
'Fern Booking',
'Canvas Metrics',
'Drift Ventures',
]; ];
const extraStages: Status[] = [
...Array<Status>(5).fill('NEW_LEAD'),
...Array<Status>(3).fill('CONTACTED'),
...Array<Status>(3).fill('QUALIFIED'),
...Array<Status>(4).fill('KYB'),
...Array<Status>(4).fill('COMPLIANCE_REVIEW'),
...Array<Status>(2).fill('INTEGRATION'),
...Array<Status>(2).fill('TESTING'),
...Array<Status>(3).fill('LIVE'),
'REJECTED',
];
const allStages: Status[] = [...successfulStages, 'REJECTED'];
const industries = ['ECOMMERCE', 'SOFTWARE', 'TRAVEL', 'SERVICES']; const industries = ['ECOMMERCE', 'SOFTWARE', 'TRAVEL', 'SERVICES'];
const countries = ['GB', 'DE', 'NL', 'EE', 'FR', 'CA']; const countries = ['GB', 'DE', 'NL', 'EE', 'FR', 'CA'];
const now = Date.now(); const contacts = [
const day = 86400000; 'Riley Bennett',
try { 'Jordan Ellis',
for (const u of users) 'Casey Laurent',
await db.user.upsert({ 'Morgan Reed',
where: { id: u.id }, 'Taylor Brooks',
create: { ...u, passwordHash: hashPassword('MerchantFlow123!') }, 'Avery Santos',
update: {}, 'Robin Bell',
}); 'Drew Collins',
for (let index = 0; index < names.length; index++) { ];
const id = `merchant-${String(index + 1).padStart(2, '0')}`; const users = [
// A second seed never rewrites the user's existing records, dates or history. {
if (await db.merchant.findUnique({ where: { id } })) continue; id: 'user-head',
const status = statuses[Math.floor(index / 2)]!; email: '[email protected]',
const ownerId = index % 2 === 0 ? 'user-manager1' : 'user-manager2'; name: 'Elena Carter',
const name = names[index]!; role: 'HEAD_OF_SALES' as const,
let journey: Status[] = },
status === 'REJECTED' {
? [...successfulStages.slice(0, 5), 'REJECTED'] id: 'user-compliance',
: successfulStages.slice(0, successfulStages.indexOf(status) + 1); email: '[email protected]',
if (status === 'KYB' && index % 2 === 0) journey = [...successfulStages.slice(0, 5), 'KYB']; name: 'Pavel Sokolov',
const stageEnteredAt = new Date(now - ((index % 4) + 1) * day); role: 'COMPLIANCE_OFFICER' as const,
const createdAt = new Date(stageEnteredAt.getTime() - (journey.length - 1) * 3 * day); },
const domain = name.toLowerCase().replaceAll(' ', '') + '.example'; {
await db.merchant.create({ id: 'user-manager1',
data: { email: '[email protected]',
id, name: 'Alex Morgan',
name, role: 'ACCOUNT_MANAGER' as const,
website: `https://${domain}`, },
industry: industries[index % 4]!, {
country: countries[index % 6]!, id: 'user-manager2',
contactName: index % 2 ? 'Jamie Wilson' : 'Sam Taylor', email: 'sam@merchantflow.test',
contactEmail: `hello@${domain}`, name: 'Sam Taylor',
status, role: 'ACCOUNT_MANAGER' as const,
ownerId, },
createdAt, ];
stageEnteredAt, function journeyFor(status: Status, corrections: boolean): Status[] {
events: { const journey: Status[] =
create: journey.map((toStatus, i) => ({ status === 'REJECTED'
id: `${id}-event-${i}`, ? [...successfulStages.slice(0, 5), 'REJECTED']
fromStatus: journey[i - 1] ?? null, : successfulStages.slice(0, successfulStages.indexOf(status) + 1);
toStatus, if (corrections) journey.splice(4, 0, 'COMPLIANCE_REVIEW', 'KYB');
actorId: return journey;
toStatus === 'COMPLIANCE_REVIEW' || (i > 0 && toStatus === 'KYB') }
? 'user-compliance' const correctionReason = 'Please clarify the beneficial ownership structure before resubmitting.';
: ownerId, const legacyNote = (index: number) =>
occurredAt: new Date(createdAt.getTime() + i * 3 * day), index % 2
note: ? 'Команда заинтересована в подключении. Следующий контакт — после проверки документов.'
journey[i - 1] === 'COMPLIANCE_REVIEW' && toStatus === 'KYB' : 'Initial discovery complete. The team is interested in a straightforward checkout integration.';
? 'Please clarify the beneficial ownership structure before resubmitting.' const include = {
checklist: true,
events: { orderBy: { occurredAt: 'asc' as const } },
notes: true,
tasks: true,
} as const;
type SeedMerchant = Prisma.MerchantGetPayload<{ include: typeof include }>;
// Only exact legacy fixtures receive inferred demo evidence. A changed fixture is preserved.
function matchesLegacy(m: SeedMerchant, index: number) {
if (index >= 18) return false;
const status = allStages[Math.floor(index / 2)]!;
// The original Luma fixture returned to KYB once (without a duplicate KYB event).
const journey: Status[] =
index === 6 ? [...successfulStages.slice(0, 5), 'KYB'] : journeyFor(status, false);
const domain = names[index]!.toLowerCase().replaceAll(' ', '') + '.example';
if (
m.name !== names[index] ||
m.status !== status ||
m.ownerId !== `user-manager${(index % 2) + 1}` ||
m.website !== `https://${domain}` ||
m.industry !== industries[index % 4] ||
m.country !== countries[index % 6] ||
m.contactName !== (index % 2 ? 'Jamie Wilson' : 'Sam Taylor') ||
m.contactEmail !== `hello@${domain}` ||
m.events.length !== journey.length ||
m.checklist.length !== 4 ||
m.notes.length !== 1 ||
m.tasks.length !== 2 ||
m.createdAt.getTime() !== m.stageEnteredAt.getTime() - (journey.length - 1) * 3 * day
)
return false;
if (
!m.events.every(
(event, i) =>
event.id === `${m.id}-event-${i}` &&
event.toStatus === journey[i] &&
event.fromStatus === (journey[i - 1] ?? null) &&
event.occurredAt.getTime() === m.createdAt.getTime() + i * 3 * day &&
event.actorId ===
(event.toStatus === 'COMPLIANCE_REVIEW' || (i > 0 && event.toStatus === 'KYB')
? 'user-compliance'
: m.ownerId) &&
event.note ===
(event.fromStatus === 'COMPLIANCE_REVIEW' && event.toStatus === 'KYB'
? correctionReason
: null),
)
)
return false;
if (
!m.checklist.every((item) => {
const j = documentCodes.indexOf(item.documentCode);
return (
item.id === `${m.id}-doc-${j}` &&
item.state ===
(status === 'KYB'
? j === 2
? 'NEEDS_CORRECTION'
: j === 3
? 'MISSING'
: 'RECEIVED'
: ['NEW_LEAD', 'CONTACTED', 'QUALIFIED'].includes(status)
? 'MISSING'
: 'RECEIVED') &&
item.note ===
(status === 'KYB' && j === 2 ? 'Ownership declaration needs an updated signature.' : null)
);
})
)
return false;
const note = m.notes[0]!;
if (
note.text !== legacyNote(index) ||
note.authorId !== m.ownerId ||
note.createdAt.getTime() !== m.stageEnteredAt.getTime() + 3600000
)
return false;
const open = m.tasks.find((task) => task.id === `${m.id}-task-1`);
const done = m.tasks.find((task) => task.id === `${m.id}-task-2`);
const anchor = m.stageEnteredAt.getTime() + ((index % 4) + 1) * day;
return (
open?.status === 'OPEN' &&
open.assigneeId === m.ownerId &&
open.completedAt === null &&
open.title ===
(status === 'KYB'
? 'Follow up on ownership documentation'
: status === 'COMPLIANCE_REVIEW'
? 'Review the merchant document checklist'
: 'Schedule the next merchant check-in') &&
open.dueAt.getTime() === anchor + ((index % 5) - 2) * day &&
open.remindAt?.getTime() === anchor + ((index % 5) - 3) * day &&
done?.status === 'DONE' &&
done.assigneeId === m.ownerId &&
done.title === 'Confirm the primary contact details' &&
done.dueAt.getTime() === m.stageEnteredAt.getTime() &&
done.completedAt?.getTime() === m.stageEnteredAt.getTime()
);
}
function companyFields(index: number) {
return {
legalName: `${names[index]} ${index % 2 ? 'Limited' : 'Ltd'}`,
registrationNumber: `MF-${countries[index % 6]}-${81000 + index}`,
address: `${12 + index} Example Lane`,
contactPhone: `+44 20 7946 ${String(index).padStart(4, '0')}`,
contactTitle: index % 2 ? 'Operations Director' : 'Founder',
estimatedMonthlyVolumeUsd: String([25000, 80000, 145000, 310000, 680000, 1250000][index % 6]),
source: sources[index % sources.length]!,
};
}
async function createMerchant(tx: Prisma.TransactionClient, index: number, anchor: number) {
const id = `merchant-${String(index + 1).padStart(2, '0')}`;
const status = index < 18 ? allStages[Math.floor(index / 2)]! : extraStages[index - 18]!;
const ownerId =
index >= 18 && index < 23
? null
: index < 18
? `user-manager${(index % 2) + 1}`
: `user-manager${((index - 23) % 2) + 1}`;
const actorId = ownerId ?? 'user-head';
const correction =
index === 6 ||
(index >= 18 && ['KYB', 'COMPLIANCE_REVIEW', 'LIVE'].includes(status) && index % 3 === 0);
const journey =
status === 'KYB' && correction
? ([...successfulStages.slice(0, 5), 'KYB'] as Status[])
: journeyFor(status, correction);
const age =
status === 'NEW_LEAD'
? (index % 7) + 1
: status === 'CONTACTED'
? 15 + (index % 8)
: status === 'QUALIFIED'
? 28 + (index % 9)
: status === 'LIVE'
? index === 41
? 90
: 76 + (index % 10)
: 40 + (index % 25);
const stageEnteredAt = new Date(anchor - ((index % 5) + 1) * day);
const createdAt = journey.length === 1 ? stageEnteredAt : new Date(anchor - age * day);
const step =
journey.length === 1
? 0
: (stageEnteredAt.getTime() - createdAt.getTime()) / (journey.length - 1);
const domain = names[index]!.toLowerCase().replaceAll(' ', '') + '.example';
await tx.merchant.create({
data: {
id,
name: names[index]!,
website: `https://${domain}`,
industry: industries[index % 4]!,
country: countries[index % 6]!,
contactName: contacts[index % contacts.length]!,
contactEmail: `hello@${domain}`,
...companyFields(index),
status,
ownerId,
createdAt,
stageEnteredAt,
updatedAt: stageEnteredAt,
events: {
create: journey.map((toStatus, i) => ({
id: `${id}-event-${i}`,
fromStatus: journey[i - 1] ?? null,
toStatus,
actorId: journey[i - 1] === 'COMPLIANCE_REVIEW' ? 'user-compliance' : actorId,
occurredAt: new Date(createdAt.getTime() + Math.round(i * step)),
note:
journey[i - 1] === 'COMPLIANCE_REVIEW' && toStatus === 'KYB'
? correctionReason
: toStatus === 'REJECTED'
? 'Unable to verify the declared beneficial owner against the submitted ownership register.'
: null, : null,
})), })),
}, },
checklist: { checklist: {
create: documentCodes.map((documentCode, j) => ({ create: documentCodes.map((documentCode, j) => ({
id: `${id}-doc-${j}`, id: `${id}-doc-${j}`,
documentCode, documentCode,
state: state:
status === 'KYB' status === 'KYB'
? j === 2 ? j === 2 && correction
? 'NEEDS_CORRECTION' ? 'NEEDS_CORRECTION'
: j === 3 : j >= 2
? 'MISSING'
: 'RECEIVED'
: ['NEW_LEAD', 'CONTACTED', 'QUALIFIED'].includes(status)
? 'MISSING' ? 'MISSING'
: 'RECEIVED', : 'RECEIVED'
note: : ['NEW_LEAD', 'CONTACTED', 'QUALIFIED'].includes(status)
status === 'KYB' && j === 2 ? 'MISSING'
? 'Ownership declaration needs an updated signature.' : 'RECEIVED',
: null, note:
})), status === 'KYB' && j === 2 && correction
}, ? 'Ownership declaration needs an updated signature.'
notes: { : null,
create: { updatedAt: stageEnteredAt,
id: `${id}-note`, })),
authorId: ownerId, },
text: notes: {
index % 2 create: {
? 'Команда заинтересована в подключении. Следующий контакт — после проверки документов.' id: `${id}-note`,
: 'Initial discovery complete. The team is interested in a straightforward checkout integration.', authorId: actorId,
createdAt: new Date(stageEnteredAt.getTime() + 3600000), text:
}, index < 18
}, ? legacyNote(index)
tasks: { : `Discussed ${index % 2 ? 'hosted checkout' : 'API integration'} with ${contacts[index % contacts.length]}. Expected rollout in ${(index % 3) + 2} weeks after approval.`,
create: [ createdAt: new Date(stageEnteredAt.getTime() + 3600000),
{
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,
},
],
}, },
}, },
tasks: {
create: [
{
id: `${id}-task-1`,
assigneeId: actorId,
creatorId: actorId,
title:
status === 'KYB'
? 'Follow up on ownership documentation'
: status === 'LIVE'
? 'Review the first-week integration feedback'
: status === 'REJECTED'
? 'Send the closure summary to the primary contact'
: 'Schedule the next merchant check-in',
status: 'OPEN',
dueAt: new Date(anchor + ((index % 7) - 3) * day),
remindAt: new Date(anchor + ((index % 7) - 4) * day),
createdAt: stageEnteredAt,
updatedAt: stageEnteredAt,
},
{
id: `${id}-task-2`,
assigneeId: actorId,
creatorId: actorId,
title: 'Confirm the primary contact details',
status: 'DONE',
dueAt: stageEnteredAt,
completedAt: stageEnteredAt,
completedById: actorId,
createdAt,
updatedAt: stageEnteredAt,
},
],
},
},
});
}
async function enrich(
tx: Prisma.TransactionClient,
m: SeedMerchant,
index: number,
anchor: number,
) {
const actorId = m.ownerId ?? 'user-head';
const allReceived = m.checklist.map((item) => ({ ...item, state: 'RECEIVED', note: null }));
for (const item of m.checklist)
await tx.checklistChange.create({
data: {
id: `${item.id}-initial`,
itemId: item.id,
actorId,
fromState: null,
toState: 'MISSING',
occurredAt: m.createdAt,
},
}); });
let cycle = 0;
let states: Record<string, 'MISSING' | 'RECEIVED' | 'NEEDS_CORRECTION'> = Object.fromEntries(
m.checklist.map((item) => [item.id, 'MISSING']),
);
for (let e = 0; e < m.events.length; e++) {
const event = m.events[e]!;
if (event.toStatus !== 'COMPLIANCE_REVIEW') continue;
cycle++;
for (const item of m.checklist)
await tx.checklistChange.create({
data: {
id: `${item.id}-received-${cycle}`,
itemId: item.id,
actorId,
fromState: states[item.id],
toState: 'RECEIVED',
occurredAt: new Date(event.occurredAt.getTime() - 3600000),
},
});
states = Object.fromEntries(m.checklist.map((item) => [item.id, 'RECEIVED']));
const next = m.events[e + 1];
const decision = !next
? 'PENDING'
: next.toStatus === 'KYB'
? 'CORRECTIONS'
: next.toStatus === 'REJECTED'
? 'REJECTED'
: 'APPROVED';
const decidedAt = next ? new Date(next.occurredAt.getTime() - 1) : null;
await tx.complianceReview.create({
data: {
id: `${m.id}-review-${cycle}`,
merchantId: m.id,
cycle,
submittedById: actorId,
reviewerId: next ? 'user-compliance' : null,
decision,
submittedAt: event.occurredAt,
decidedAt,
reason:
decision === 'CORRECTIONS'
? correctionReason
: decision === 'REJECTED'
? (next?.note ??
'Unable to verify the beneficial owner; the submitted register conflicts with the ownership declaration.')
: decision === 'APPROVED'
? 'Company registration, ownership, UBO identification and business activity checks passed.'
: null,
snapshot: reviewSnapshot({ ...m, checklist: allReceived }),
},
});
if (decision === 'CORRECTIONS')
for (const item of m.checklist.filter((item) =>
['UBO_IDENTIFICATION', 'BUSINESS_ACTIVITY'].includes(item.documentCode),
)) {
const state = item.documentCode === 'UBO_IDENTIFICATION' ? 'NEEDS_CORRECTION' : 'MISSING';
await tx.checklistChange.create({
data: {
id: `${item.id}-correction-${cycle}`,
itemId: item.id,
actorId: 'user-compliance',
fromState: 'RECEIVED',
toState: state,
note:
item.documentCode === 'UBO_IDENTIFICATION'
? 'Ownership declaration needs an updated signature.'
: 'Please provide a current description of the business activity.',
occurredAt: decidedAt!,
},
});
states[item.id] = state;
}
} }
console.log('Seed ready: 4 accounts, 18 merchants. Password: MerchantFlow123!'); for (const item of m.checklist)
if (states[item.id] !== item.state)
await tx.checklistChange.create({
data: {
id: `${item.id}-current`,
itemId: item.id,
actorId,
fromState: states[item.id],
toState: item.state,
note: item.note,
occurredAt: new Date(m.stageEnteredAt.getTime() + 1000),
},
});
await tx.activity.createMany({
data: [
{
id: `${m.id}-activity-1`,
merchantId: m.id,
actorId,
kind: 'NOTE',
text: `Lead received through ${m.source?.toLowerCase() ?? 'referral'}. Primary contact: ${m.contactName}.`,
occurredAt: m.createdAt,
updatedAt: m.createdAt,
},
{
id: `${m.id}-activity-2`,
merchantId: m.id,
actorId,
kind: index % 2 ? 'EMAIL' : 'CALL',
text:
m.status === 'NEW_LEAD'
? 'Prepared the introductory outreach and confirmed the company website.'
: `Discussed expected monthly processing of USD ${m.estimatedMonthlyVolumeUsd} and ${index % 2 ? 'settlement reporting' : 'checkout requirements'}.`,
occurredAt: new Date(m.createdAt.getTime() + 3600000),
updatedAt: new Date(m.createdAt.getTime() + 3600000),
},
{
id: `${m.id}-activity-3`,
merchantId: m.id,
actorId: cycle ? 'user-compliance' : actorId,
kind: cycle ? 'KYB_NOTE' : 'NOTE',
text: cycle
? 'Review evidence and document changes are recorded in the KYB history.'
: 'Next follow-up is tracked in the merchant task list.',
occurredAt: m.stageEnteredAt,
updatedAt: m.stageEnteredAt,
},
],
});
if (cycle)
await tx.task.create({
data: {
id: `${m.id}-compliance-task`,
merchantId: m.id,
kind: 'COMPLIANCE',
assigneeId: 'user-compliance',
creatorId: 'user-compliance',
title:
m.status === 'KYB'
? 'Check corrected beneficial ownership evidence'
: m.status === 'COMPLIANCE_REVIEW'
? 'Complete the KYB assessment'
: 'Record the compliance decision rationale',
status: ['KYB', 'COMPLIANCE_REVIEW'].includes(m.status) ? 'OPEN' : 'DONE',
dueAt: new Date(anchor + ((index % 5) - 2) * day),
remindAt: new Date(anchor + ((index % 5) - 3) * day),
createdAt: m.events.find((e) => e.toStatus === 'COMPLIANCE_REVIEW')!.occurredAt,
completedAt: ['KYB', 'COMPLIANCE_REVIEW'].includes(m.status) ? null : m.stageEnteredAt,
completedById: ['KYB', 'COMPLIANCE_REVIEW'].includes(m.status) ? null : 'user-compliance',
updatedAt: m.stageEnteredAt,
},
});
await tx.demoSeedRecord.create({ data: { merchantId: m.id, version: 2 } });
}
try {
await db.$transaction(
async (tx) => {
await tx.$executeRaw`SELECT pg_advisory_xact_lock(72465102)`;
const seed = await tx.demoSeedState.upsert({
where: { id: 'merchantflow-v2' },
update: {},
create: { id: 'merchantflow-v2' },
});
for (const user of users)
await tx.user.upsert({
where: { id: user.id },
update: {},
create: { ...user, passwordHash: hashPassword('MerchantFlow123!') },
});
for (const [id, oldEmail, email, oldName, name] of [
[
'user-manager1',
'[email protected]',
'[email protected]',
'Alex Morgan',
'Alex Morgan',
],
[
'user-manager2',
'[email protected]',
'[email protected]',
'Maria Chen',
'Sam Taylor',
],
]) {
await tx.user.updateMany({ where: { id, email: oldEmail }, data: { email } });
if (oldName !== name)
await tx.user.updateMany({ where: { id, name: oldName }, data: { name } });
}
for (let index = 0; index < names.length; index++) {
const id = `merchant-${String(index + 1).padStart(2, '0')}`;
if (await tx.demoSeedRecord.findUnique({ where: { merchantId: id } })) continue;
let merchant = await tx.merchant.findUnique({ where: { id }, include });
if (merchant) {
if (!matchesLegacy(merchant, index)) {
console.warn(
`Preserved edited or unrecognized legacy fixture ${id}; no approval/history inferred.`,
);
continue;
}
const fields = companyFields(index);
await tx.merchant.update({
where: { id },
data: {
...Object.fromEntries(
Object.entries(fields).filter(
([key]) => merchant![key as keyof typeof fields] === null,
),
),
updatedAt: merchant.updatedAt,
},
});
for (const task of merchant.tasks)
await tx.task.update({
where: { id: task.id },
data: {
creatorId: task.assigneeId,
completedById: task.status === 'DONE' ? task.assigneeId : null,
createdAt: merchant.createdAt,
updatedAt: task.completedAt ?? merchant.stageEnteredAt,
},
});
} else await createMerchant(tx, index, seed.anchorAt.getTime());
merchant = await tx.merchant.findUniqueOrThrow({ where: { id }, include });
await enrich(tx, merchant, index, seed.anchorAt.getTime());
}
},
{ timeout: 60000 },
);
console.log(
'Seed ready: 4 demo accounts, 45 fixture IDs. Password for newly created accounts: MerchantFlow123! Existing edits and passwords preserved.',
);
} finally { } finally {
await db.$disconnect(); await db.$disconnect();
} }
+43
View File
@@ -0,0 +1,43 @@
import { documentCodes } from '@merchantflow/contracts';
export const reviewedFields = [
'name',
'legalName',
'registrationNumber',
'address',
'website',
'country',
'industry',
] as const;
type ReviewedMerchant = Record<(typeof reviewedFields)[number], string | null> & {
checklist: { id: string; documentCode: string; state: string; note: string | null }[];
};
// Stable, minimal evidence: commercial estimates/contact edits do not invalidate approval.
export function reviewSnapshot(merchant: ReviewedMerchant) {
return {
company: Object.fromEntries(reviewedFields.map((key) => [key, merchant[key]])),
checklist: [...merchant.checklist]
.sort((a, b) => a.documentCode.localeCompare(b.documentCode))
.map(({ id, documentCode, state, note }) => ({ id, documentCode, state, note })),
};
}
export function checklistComplete(items: { documentCode: string; state: string }[]) {
return (
items.length === documentCodes.length &&
documentCodes.every((code) =>
items.some((item) => item.documentCode === code && item.state === 'RECEIVED'),
)
);
}
export function snapshotsEqual(a: unknown, b: unknown): boolean {
const canonical = (value: unknown): string => {
if (Array.isArray(value)) return `[${value.map(canonical).join(',')}]`;
if (value && typeof value === 'object')
return `{${Object.entries(value)
.sort(([a], [b]) => a.localeCompare(b))
.map(([key, item]) => `${JSON.stringify(key)}:${canonical(item)}`)
.join(',')}}`;
return JSON.stringify(value);
};
return canonical(a) === canonical(b);
}
+3
View File
@@ -14,6 +14,9 @@ function run(command, args) {
if (result.error) throw result.error; if (result.error) throw result.error;
if (result.status !== 0) process.exit(result.status ?? 1); if (result.status !== 0) process.exit(result.status ?? 1);
} }
// Workflow tests write fixtures. Recreate only the disposable test service; never touch db.
run('docker', ['compose', '--profile', 'test', 'stop', 'db-test']);
run('docker', ['compose', '--profile', 'test', 'rm', '-f', 'db-test']);
run('docker', ['compose', '--profile', 'test', 'up', '-d', '--wait', 'db-test']); run('docker', ['compose', '--profile', 'test', 'up', '-d', '--wait', 'db-test']);
run('pnpm', ['exec', 'turbo', 'run', 'build']); run('pnpm', ['exec', 'turbo', 'run', 'build']);
run('pnpm', ['--filter', '@merchantflow/database', 'migrate']); run('pnpm', ['--filter', '@merchantflow/database', 'migrate']);
+174
View File
@@ -0,0 +1,174 @@
// Frozen foundation fixtures for upgrade compatibility tests.
if (!process.env.DATABASE_URL?.endsWith('/merchantflow_test'))
throw new Error('Legacy fixture requires isolated test database');
import { statuses, successfulStages, documentCodes } from '../../packages/contracts/dist/index.js';
import { createDatabase } from '../../packages/database/dist/index.js';
import { hashPassword } from '../../packages/database/dist/password.js';
const db = createDatabase(
process.env.DATABASE_URL ??
'postgresql://merchantflow:merchantflow_local@localhost:55440/merchantflow',
);
const users = [
{
id: 'user-head',
email: '[email protected]',
name: 'Elena Carter',
role: 'HEAD_OF_SALES',
},
{
id: 'user-compliance',
email: '[email protected]',
name: 'Pavel Sokolov',
role: 'COMPLIANCE_OFFICER',
},
{
id: 'user-manager1',
email: '[email protected]',
name: 'Alex Morgan',
role: 'ACCOUNT_MANAGER',
},
{
id: 'user-manager2',
email: '[email protected]',
name: 'Maria Chen',
role: 'ACCOUNT_MANAGER',
},
];
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 === '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();
}
+157 -8
View File
@@ -64,12 +64,23 @@ for (const language of ['en', 'ru'])
.first() .first()
.click(); .click();
await expect(page.locator('h1')).toHaveText('Luma Labs'); await expect(page.locator('h1')).toHaveText('Luma Labs');
await expect(page.getByText(/Please clarify the beneficial ownership/)).toBeVisible(); await expect(
page.getByText(/Please clarify the beneficial ownership/).first(),
).toBeVisible();
await noOverflow(page); await noOverflow(page);
await page.reload(); await page.reload();
await expect(page.locator('h1')).toHaveText('Luma Labs'); await expect(page.locator('h1')).toHaveText('Luma Labs');
await expect(page.locator('html')).toHaveAttribute('lang', language); await expect(page.locator('html')).toHaveAttribute('lang', language);
await page.screenshot({ path: info.outputPath('merchant.png'), fullPage: true }); await page.screenshot({ path: info.outputPath('merchant.png'), fullPage: true });
const editButton = page.getByRole('button', {
name: /^(Edit merchant|Изменить мерчанта)$/,
});
await editButton.click();
await expect(page.getByRole('dialog')).toBeVisible();
await noOverflow(page);
await page.screenshot({ path: info.outputPath('merchant-editor.png'), fullPage: true });
await page.keyboard.press('Escape');
await expect(page.getByRole('dialog')).not.toBeVisible();
await page.goto('/app/merchants'); await page.goto('/app/merchants');
await page.getByRole('combobox').selectOption('LIVE'); await page.getByRole('combobox').selectOption('LIVE');
await expect(page.getByRole('link', { name: /Sunday Market/ }).first()).toBeVisible(); await expect(page.getByRole('link', { name: /Sunday Market/ }).first()).toBeVisible();
@@ -105,24 +116,23 @@ test('account switching removes old data, manager isolation and Compliance navig
await expect(page.locator('h1')).toHaveText('Northstar Studio'); await expect(page.locator('h1')).toHaveText('Northstar Studio');
await page.getByRole('button', { name: 'Sign out' }).click(); await page.getByRole('button', { name: 'Sign out' }).click();
await expect(page).toHaveURL(/login/); await expect(page).toHaveURL(/login/);
await signIn(page, 'manager1'); await signIn(page, 'alex');
const dashboard = await page.request.get('/api/dashboard'); const dashboard = await page.request.get('/api/dashboard');
expect((await dashboard.json()).merchantCount).toBe(9); expect((await dashboard.json()).merchantCount).toBe(20);
await page.goto('/app/merchants/merchant-02'); await page.goto('/app/merchants/merchant-02');
await expect( await expect(
page.getByText('This merchant was not found or is outside your portfolio.'), page.getByText('This merchant was not found or is outside your portfolio.'),
).toBeVisible(); ).toBeVisible();
await page.getByRole('button', { name: 'Sign out' }).click(); await page.getByRole('button', { name: 'Sign out' }).click();
await signIn(page, 'compliance'); await signIn(page, 'compliance');
expect((await (await page.request.get('/api/dashboard')).json()).merchantCount).toBe(4); expect((await (await page.request.get('/api/dashboard')).json()).merchantCount).toBe(45);
await page.getByRole('link', { name: 'Review queue', exact: true }).click(); await page.getByRole('link', { name: 'Review queue', exact: true }).click();
await expect(page.getByRole('heading', { name: '2 merchants awaiting review' })).toBeVisible(); await expect(page.getByRole('heading', { name: '6 merchants awaiting review' })).toBeVisible();
await page.getByRole('link', { name: 'View checklist' }).first().click(); await page.getByRole('link', { name: 'View checklist' }).first().click();
await expect(page.getByRole('heading', { name: 'KYB checklist' })).toBeVisible(); await expect(page.getByRole('heading', { name: 'KYB checklist' })).toBeVisible();
await page.goto('/app/merchants/merchant-15'); await page.goto('/app/merchants/merchant-15');
await expect( await expect(page.locator('h1')).toHaveText('Sunday Market');
page.getByText('This merchant was not found or is outside your portfolio.'), await expect(page.getByRole('button', { name: 'Edit merchant', exact: true })).toHaveCount(0);
).toBeVisible();
}); });
test('translated validation, persistent language changes and accessible form errors', async ({ test('translated validation, persistent language changes and accessible form errors', async ({
page, page,
@@ -182,3 +192,142 @@ test('loading, retryable errors, empty states, session expiry and reduced motion
await page.goto('/app/merchants'); await page.goto('/app/merchants');
await expect(page).toHaveURL(/\/login\?next=/); await expect(page).toHaveURL(/\/login\?next=/);
}); });
test('Head assignment, manager editing, Compliance decisions and manager activation work through the UI', async ({
page,
}, info) => {
const merchantPath = '/app/merchants/merchant-19';
const save = async () => {
await page.getByRole('button', { name: 'Save changes', exact: true }).click();
await expect(page.getByRole('dialog')).not.toBeVisible();
};
const switchAccount = async (account: string) => {
await page.getByRole('button', { name: 'Sign out', exact: true }).click();
await signIn(page, account);
await page.goto(merchantPath);
await expect(page.locator('h1')).toHaveText('Willow Ceramics');
};
const advance = async (stage: string) => {
await page.getByRole('button', { name: `Move to ${stage}`, exact: true }).click();
await expect(
page.getByRole('status').filter({ hasText: 'Changes saved.' }).first(),
).toBeVisible();
await expect
.poll(
async () => (await (await page.request.get('/api/merchants/merchant-19')).json()).status,
)
.toBe(stage.toUpperCase().replaceAll(' ', '_'));
};
await signIn(page);
await page.goto(merchantPath);
await expect(page.getByText('Unassigned', { exact: true })).toBeVisible();
await page.getByRole('button', { name: 'Assign manager', exact: true }).click();
await page.getByRole('dialog').getByLabel('Account manager').selectOption('user-manager1');
await save();
await switchAccount('alex');
await expect(page.getByRole('button', { name: 'Assign manager', exact: true })).toHaveCount(0);
await page.getByRole('button', { name: 'Edit merchant', exact: true }).click();
await page
.getByRole('dialog')
.getByLabel('Contact title', { exact: true })
.fill('Director of Partnerships');
await page
.getByRole('dialog')
.getByLabel('Estimated monthly processing (USD)', { exact: true })
.fill('246000.75');
await save();
await expect(page.getByText('Director of Partnerships', { exact: true })).toBeVisible();
await page.getByRole('button', { name: 'Log interaction', exact: true }).click();
await page.getByRole('dialog').getByLabel('Interaction type').selectOption('CALL');
await page
.getByRole('dialog')
.getByLabel('Details', { exact: true })
.fill('Confirmed the launch requirements in a discovery call.');
await save();
await expect(
page.getByText('Confirmed the launch requirements in a discovery call.', { exact: true }),
).toBeVisible();
await page.getByRole('button', { name: 'Add task', exact: true }).click();
await page
.getByRole('dialog')
.getByLabel('Task title', { exact: true })
.fill('Send the integration guide');
await save();
const taskRow = page.locator('#tasks > div').filter({ hasText: 'Send the integration guide' });
await taskRow.getByRole('button', { name: 'Complete task', exact: true }).click();
await expect(taskRow.getByText('Completed', { exact: true }).first()).toBeVisible();
await advance('Contacted');
await advance('Qualified');
await advance('KYB');
for (let i = 0; i < 4; i++) {
await page.getByRole('button', { name: 'Update document', exact: true }).nth(i).click();
await page
.getByRole('dialog')
.getByLabel('Document status', { exact: true })
.selectOption('RECEIVED');
await save();
}
await advance('Compliance Review');
await expect(page.getByRole('button', { name: 'Record decision', exact: true })).toHaveCount(0);
await switchAccount('compliance');
await page.getByRole('button', { name: 'Record decision', exact: true }).click();
await page
.getByRole('dialog')
.getByLabel('Decision', { exact: true })
.selectOption('CORRECTIONS');
await page
.getByRole('dialog')
.getByLabel('Decision reason', { exact: true })
.fill('The ownership declaration needs a current signature.');
await page
.getByRole('dialog')
.getByLabel('Ownership structure', { exact: true })
.fill('Please sign and date the declaration.');
await save();
await switchAccount('alex');
const ownership = page
.locator('#checklist > div > div')
.filter({ hasText: 'Ownership structure' });
await ownership.getByRole('button', { name: 'Update document', exact: true }).click();
await page
.getByRole('dialog')
.getByLabel('Document status', { exact: true })
.selectOption('RECEIVED');
await page
.getByRole('dialog')
.getByLabel('Note', { exact: true })
.fill('Updated signature received.');
await save();
await advance('Compliance Review');
await switchAccount('compliance');
await page.getByRole('button', { name: 'Record decision', exact: true }).click();
await page
.getByRole('dialog')
.getByLabel('Decision reason', { exact: true })
.fill('All evidence checked and approved.');
await save();
await expect(page.getByRole('button', { name: 'Edit merchant', exact: true })).toHaveCount(0);
await switchAccount('alex');
await page.getByRole('button', { name: 'Edit merchant', exact: true }).click();
await expect(
page.getByRole('dialog').getByLabel('Legal company name', { exact: true }),
).toBeDisabled();
await page.getByRole('button', { name: 'Cancel', exact: true }).click();
await advance('Testing');
await advance('Live');
await noOverflow(page);
await page.screenshot({ path: info.outputPath('approved-live-merchant.png'), fullPage: true });
await switchAccount('head');
await page.getByRole('button', { name: 'Assign manager', exact: true }).click();
await page.getByRole('dialog').getByLabel('Account manager').selectOption('user-manager2');
await save();
await switchAccount('sam');
await expect(page.getByText('Director of Partnerships', { exact: true })).toBeVisible();
const hidden = await page.request.get('/api/merchants/merchant-01');
expect(hidden.status()).toBe(404);
expect(
await page.evaluate(() =>
Object.keys(localStorage).every((key) => key === 'merchantflow.language'),
),
).toBe(true);
});