2026-09-24 22:41:06 +03:00
2026-09-24 22:41:06 +03:00
2026-09-24 22:41:06 +03:00
2026-09-24 22:41:06 +03:00

MerchantFlow

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

Prerequisites: Node 22.19+ on the 22.x line, pnpm 10.32.1, and Docker Desktop with its engine running. .nvmrc pins the verified Node version.

nvm use
corepack enable
corepack prepare [email protected] --activate
cp .env.example .env
pnpm install --frozen-lockfile
pnpm db:setup
pnpm dev

Open http://localhost:5173. The API runs at http://localhost:3001/api; Vite forwards /api to it without rewriting the path. Local localhost and 127.0.0.1 browser URLs are both accepted. Docker runs only PostgreSQL; the two applications run on the host.

Development PostgreSQL uses 55440, to avoid existing local databases. The isolated test service uses 55441. Both bind to loopback only. If a port is occupied, update the matching Compose mapping and database URL (the test URL lives in scripts/test-database.mjs). Frontend/API ports and the trusted browser origin can be changed in .env.

pnpm db:setup starts PostgreSQL, applies the checked-in migration, generates/builds database code, and seeds the fixtures. Seeding is repeatable: existing fixture IDs, passwords, 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

All four accounts use MerchantFlow123!. The login page has credential-fill buttons; sign-in still goes through the API.

Email Role Visibility
[email protected] Head of Sales All 45 merchants
[email protected] Compliance Officer All 45 merchants; personal compliance tasks
[email protected] Account Manager · Alex Morgan 20 assigned merchants
[email protected] Account Manager · Sam Taylor 20 assigned merchants

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

apps/web              React + Vite + React Router
apps/api              NestJS REST API
packages/ui           shadcn/Base UI components, tokens and reusable states
packages/contracts    Zod schemas, DTOs, canonical role/status codes
packages/database     Prisma schema, generated client, migrations and seed
docs                  Product brief and implementation checklist
tests                 Playwright journeys

The browser depends on UI and contracts only. Database exports have a Node-only condition, and Vite fails the build if Prisma, database code or PostgreSQL drivers enter its module graph. Contracts never import Prisma types. An integration test checks that Prisma enums and contract codes agree. 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: matching base-nova configuration, neutral tokens, rsc: false, shared CSS, and package subpath exports. Components were installed using the pinned shadcn 4.21.0 CLI; imports use the shared @merchantflow/ui/lib/utils utility. Forms use React Hook Form and shared Zod schemas.

API, database and contracts compile to ESM. Turbo builds dependencies before dependent apps. pnpm dev first compiles the API, then starts dependency watchers, the API compiler/process watcher, and Vite. Run pnpm db:generate after a Prisma schema edit. Add migrations with Prisma during development; db:migrate only applies checked-in migrations.

Routes and API

Public routes are / and /login. CRM routes are /app, /app/merchants, /app/merchants/:id, /app/pipeline, /app/tasks and /app/review-queue. Browser history URLs support direct navigation and refresh through Vite.

Method Endpoint Purpose
POST /api/public/leads Public consultation intake with idempotent persistence
GET /api/health Database-aware health; 503 if unavailable
POST /api/auth/login Email/password login
POST /api/auth/logout Revoke session and clear cookie
GET /api/auth/me Current public user
GET /api/dashboard Scoped counts, distribution, activity, priority tasks
GET /api/merchants?search=&status=&country=&industry=&ownerId=&page=1 Scoped combined filters; 8 records per page
GET /api/merchants/:id Overview, checklist, notes, tasks, history
GET /api/pipeline Scoped merchants grouped in the UI
GET /api/tasks?filter=ALL TODAY / UPCOMING / OVERDUE / DONE; ALL / OPEN retained
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. 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.

Public consultation form

The landing page at / is mobile-first and available in English and Russian, with a consultation CTA and a separate staff-login link. All seven business fields are required. Countries use ISO codes and localized display names; industries include OTHER. No reference-site assets, customer logos, certifications or performance claims are used.

POST /api/public/leads accepts this JSON shape with a UUID Idempotency-Key header and the configured trusted Origin:

{
  "name": "Example Company",
  "contactName": "Example Contact",
  "contactEmail": "[email protected]",
  "website": "https://example.test",
  "country": "GB",
  "industry": "SOFTWARE",
  "estimatedMonthlyVolumeUsd": "25000.50",
  "companyFax": ""
}

The shared schema trims names, lowercases email, validates country/industry codes and HTTP(S) websites, and accepts scheme-less websites by adding HTTPS. USD amounts remain decimal strings, from zero to 999999999999.99, with at most two fractional digits; decimal commas are accepted without thousands separators. Email providers are not blocked or externally verified. Unexpected business fields are rejected.

A successful request returns 202 { "ok": true } and atomically creates an unassigned NEW_LEAD, source LANDING_PAGE, three missing KYB checklist records, an initial stage event and an immutable creation activity. Public creation has a null actor, displayed as System/Система; staff actions retain their authenticated actor. Existing role scopes and assignment requirements apply immediately.

A unique database submission key and normalized payload hash protect retries across concurrency and restarts. Reusing the key with the same payload returns the same response; a changed payload returns 409 IDEMPOTENCY_CONFLICT. Keys and hashes are not exposed by CRM responses. The frontend reuses its key for unchanged retries, including uncertain network failures; changing normalized business details selects another key. Form values and keys stay in component memory, so navigating away or reloading starts a fresh form.

The hidden companyFax trap is excluded from keyboard and accessibility navigation. After trusted-Origin and envelope/key checks, a populated trap returns the same 202 response, even if business fields are invalid or the IP quota is exhausted. It writes no database records. Genuine invalid requests return 400 VALIDATION_ERROR with translated field issue codes.

The public endpoint has independent, process-local limits: 10 attempts per IP and three new submissions per normalized email per 15 minutes, with a 10,000-bucket cap and Retry-After on 429 responses. Replays do not spend the email creation allowance, failed transactions release their reservation, and forwarded IP headers are not trusted. As with login limits, these settings target the local single-process application. Pending, success, validation, network/server-error and rate-limit states preserve legitimate inputs after errors. No external email or notifications are sent.

Apply checked-in additive migrations with pnpm db:migrate when upgrading an existing workspace. No reseed or development database reset is needed. Integration tests cover atomic persistence, role scoping, concurrent/restarted retries, honeypots and throttling. Browser tests exercise both languages at 375px/1440px, including a committed request whose response is lost; test-created leads are removed only from the disposable test database.

Data and localization

The successful path is New Lead → Contacted → Qualified → KYB → Compliance Review → Integration → Testing → Live. Rejected is a separate terminal outcome. Luma Labs demonstrates a historical return from Compliance Review to KYB for corrections.

The seed creates 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. Role-specific dashboards derive portfolio, workload and review metrics from scoped database records. 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. Checklist collection, review decisions, interaction logging and task management are available from merchant details. Reminders and their dismissals persist in PostgreSQL and refresh in the app while visible and on focus or reconnection.

Verification

pnpm build
pnpm lint
pnpm typecheck
pnpm test
pnpm test:integration
pnpm exec playwright install chromium
pnpm test:e2e
pnpm format:check

Unit tests cover contracts, translated resources, return URLs, scope rules and password verification. Integration tests use an isolated merchantflow_test database on a separate Compose service with temporary storage; they never truncate the development database. Browser tests start dedicated web/API instances on 5174/3002, then test the consultation form in EN/RU at 375px/1440px, and CRM journeys 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:

curl --fail http://localhost:3001/api/health
curl --fail http://localhost:5173/api/health

Both should return {"status":"ok","database":"connected"}. If startup fails, check Docker, port availability and .env; do not point the tests at development data.

The product brief and implementation checklist 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. Personal Compliance tasks are private; Head and managers see commercial tasks only. Query predicates enforce these scopes on lists, search, totals, dashboard, detail children, and mutation targets.

Only adjacent commercial stage advances are accepted, plus the explicit legacy return-to-KYB action described below. A manager must be assigned before leaving New Lead. Contacted requires a logged call or email. Qualified requires company name, website, contact name/email, country, industry and an estimated volume; zero is valid. In KYB, Head or the assigned Manager records Missing/Received status and collection notes for company registration, ownership structure and authorized-representative identification. These are checklist records, with no uploads. Submission requires all three required checklist records to have received-history evidence and creates one pending review. Company/KYB fields freeze while that review is pending. Compliance can approve with Low/Medium/High risk and a required rationale (atomically advancing to Integration), reject with a reason, or request item-specific corrections stored with the review, separately from collection notes (returning to KYB). Resubmission creates a new review cycle. Decisions and system history cannot be edited.

Current-policy approval 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 the latest valid approval and the stage’s demo checks are complete. Integration requires API connection and webhook setup marked Complete; Testing requires test payment and reconciliation marked Passed. Checks retain their own notes and change history and are bound to that review cycle. Updates are allowed only in the corresponding stage; no real payments or external services are called. 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 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.

Daily sales workspace

Head can add merchants from the directory and optionally assign a manager. Managers create merchants assigned to themselves. Company name, contact name and email are required; website, country, industry and volume can be supplied later. Compliance has no creation access. New leads begin at NEW_LEAD with three missing KYB checklist records and an attributed creation history. The API rejects caller-supplied stage, audit identity and public-submission fields.

Directory search matches company/legal name, contact name, email and website. status, ISO country, canonical industry, and ownerId combine with search. Head and Compliance may use ownerId=unassigned or a manager ID. Manager owner filters return 403. All records, totals and filter options use the same authorization scope. Results support 10, 20 or 30 records per page (pageSize, default 10) and clamp excessive page numbers to the last available page. Changing the page size returns to page one. Search, filters and pagination survive URL sharing, reload and browser navigation.

Method Endpoint Purpose
POST /api/merchants Create a staff lead; returns { id, version }
GET /api/merchants/filters Scoped country/industry/owner options and create/filter permissions
POST /api/merchants/:id/transitions { version, toStatus, reason? }; rejection requires a nonblank reason

Detail and pipeline responses include capabilities.actions: kind, optional target stage, enabled state, reason requirement and structured blockingReasons. One backend policy drives both display and execution. Workflow errors return those blockers; the UI translates their codes and field names. General editing still cannot change stage or ownership. A conditional version claim locks the parent, then current evidence is read before committing stage, timestamp and audit changes atomically. Stale conflicts refresh the current view without automatically resubmitting an action; editor values are retained.

Head and assigned Managers can reject New Lead, Contacted and Qualified. Only Head may reject KYB, Integration or Testing for a business reason. This closure never alters an existing compliance decision. During Compliance Review, only the dedicated Compliance decision endpoint can reject. Live and Rejected have no outgoing transitions.

Merchant detail uses ?tab=overview|activity|onboarding|tasks; existing #checklist and #tasks links remain supported. history is a typed chronological projection, newest first, combining legacy notes, interactions, stage events, ownership changes and compliance outcomes without duplicate stage/review audit rows. Ownership history records both owners; task handoff preserves completed attribution and personal Compliance tasks. Raw audit metadata and public submission keys remain private.

The desktop pipeline has horizontally scrollable stage columns, including Rejected. Mobile displays only the selected ?stage= with counts and merchant cards. Explicit progression and rejection actions are available on cards and detail pages. API-provided explanations appear next to blocked controls. EN/RU labels, keyboard tabs, focus handling, touch targets and reduced-motion support are retained.

Migration 202609240004_sales_workspace only makes website, country and industry nullable. Apply with pnpm db:migrate; no reseed or database reset is required. Public consultation validation remains fully required and unchanged.

Gated onboarding API and upgrades

Current review policy version 2 requires exactly three active KYB records. documentCodes retains legacy codes for historical reads; requiredDocumentCodes defines the current creation/submission requirements. The latest approved cycle must have a Compliance reviewer, valid timestamps, risk, rationale, received-history evidence and matching company/checklist snapshot. Any pending cycle invalidates activation.

Method Route Contract
GET /api/review-queue?search=…&ownerId=…&waiting=ALL|24|72 Compliance only; {items, pendingCount, filteredCount, owners}. Each item contains review ID, cycle, policy version, submitted timestamp and merchant. Oldest submitted first. ownerId=unassigned is supported.
POST /api/merchants/:id/reviews/:reviewId/decision {version, decision, reason, riskLevel?, corrections?}. Approval requires risk and rationale; corrections require {itemId,note} entries; rejection requires a reason. Only the latest pending cycle is decidable.
PATCH /api/merchants/:id/activation-checks/:code {version, reviewId, state, note}. Codes: API_CONNECTION, WEBHOOK_SETUP, TEST_PAYMENT, RECONCILIATION. Integration states: INCOMPLETE/COMPLETE; testing states: NOT_RUN/PASSED/FAILED.
POST /api/merchants/:id/reopen-kyb {version}. Head or assigned Manager may return legacy Integration/Testing records without a pending review to KYB.

Merchant detail includes review snapshots, risk and immutable correction notes, activation check history, and server-derived handoff/edit capabilities. Review links use ?tab=onboarding#review-<id> and remain valid after decisions.

Apply the two new additive migrations with pnpm db:migrate; do not reset or reseed development data. Old review cycles retain policy version 1 and their original evidence. Legacy beneficial-owner ID and business-activity items become read-only historical requirements. Unfinished merchants receive a new Missing representative-identification record; terminal records remain untouched. Old pending reviews require corrections/resubmission or rejection. Old approvals cannot authorize further activation: use Return to KYB for re-review. Existing decisions, notes, timestamps and passwords are preserved, and no risk or demo results are inferred for existing fixtures. Fresh fixtures include current-policy approval/check evidence; seed reruns preserve existing records.

Tasks, reminders, and operational dashboards

Apply migration 202609240007_tasks_dashboards with pnpm db:migrate; no reset or reseed is required. It adds reminder dismissal, a revision number and an assignee/status/reminder index without changing existing task values.

Tasks and merchant details share creation, editing, completion and reopening controls. The merchant selector uses the scoped directory. Mutation payloads retain the existing {version,title,dueAt,remindAt,status} contract; assignee and task kind are server-derived. Responses include merchant version and task action capabilities. An open editor retains its starting version; a conflict preserves inputs and offers an explicit current-version refresh before resubmission.

Sales tasks follow the merchant owner; unassigned lead tasks belong to the Head. Reassignment atomically transfers open commercial tasks and resets their reminder dismissal. Completed attribution and Compliance tasks stay intact. A new manager may reopen an inherited completed task; its previous completion is audited before it is assigned to the current manager. Personal Compliance tasks never appear in Sales task lists or dashboards.

Endpoint Behavior
GET /api/tasks?filter=TODAY&timeZone=Europe/Kyiv Open tasks due during the viewer’s local day, including overdue tasks due today. UPCOMING begins tomorrow, OVERDUE is due before now, and DONE is completed. ALL and OPEN remain supported. Optional merchantId and authorized assigneeId filters combine with role scope.
GET /api/reminders Only the caller’s visible, open, undismissed tasks with remindAt <= now; includes reminderRevision.
POST /api/tasks/:id/reminder-dismissal {reminderRevision}; persists dismissal, is idempotent for that revision, and rejects stale revisions with 409.
GET /api/merchants Adds UTC createdFrom/createdTo inclusive bounds and cohort=ACTIVE_ONBOARDING|REACHED_LIVE to the existing combined filters.
GET /api/review-queue?view=DECISIONS Compliance-only decided review history, newest decision first, with optional decision, decidedFrom, and decidedTo. Default view remains pending reviews.

The inbox polls every 30 seconds while visible and refreshes immediately on mount, focus, visibility restoration and reconnection. Completion suppresses reminders; reopening preserves dismissal. A change to reminder time or assignee starts a fresh revision. Title-only edits preserve exact stored reminder timestamps. UTC instants are stored and transported; the UI shows local dates/times and uses DST-aware local-day boundaries. No browser storage, external notifications or scheduler is required for reminders.

Head dashboards show total merchants, created leads during the last 30 days, active onboarding (KYB through Testing), Live merchants, all-stage distribution, manager workload, overdue sales tasks and unassigned New Leads. Workload shows assigned merchants, active onboarding, open sales tasks and overdue sales tasks, including managers with zero work. Managers get their assigned scope and own workload, with next actions first. Compliance gets pending reviews, oldest waiting cycles, 30-day decision counts by outcome and personal review tasks.

Activation rate is currently Live / all visible merchants, including Rejected. Average onboarding duration is creation to earliest recorded Live transition, once per visible merchant with such an event. Neither uses current-stage entry time as a substitute. The UI shows denominators/sample counts and honest empty states. Totals and charts come from a repeatable-read database snapshot with one captured time; their drilldowns reuse the same predicates. Thirty-day drilldowns preserve the snapshot’s UTC period bounds in the URL. Live operational lists refresh as records and time change.

S
Description
No description provided
Readme
362 KiB
Languages
TypeScript 77.9%
JavaScript 19%
CSS 2.1%
Shell 0.6%
Dockerfile 0.3%
Other 0.1%