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
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
@@ -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`.
`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
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 18 merchants |
| `[email protected]` | Compliance Officer | 4 merchants currently in KYB or Compliance Review |
| `manager1@merchantflow.test` | Account Manager · Alex Morgan | 9 assigned merchants |
| `manager2@merchantflow.test` | Account Manager · Maria Chen | 9 assigned merchants |
| Email | Role | Visibility |
| ------------------------------ | ----------------------------- | ------------------------------------------- |
| `[email protected]` | Head of Sales | All 45 merchants |
| `[email protected]` | Compliance Officer | All 45 merchants; personal compliance tasks |
| `alex@merchantflow.test` | Account Manager · Alex Morgan | 20 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
@@ -47,7 +47,7 @@ docs Product brief and implementation checklist
tests Playwright journeys
```
The browser depends on UI and contracts only. Database exports have a Node-only condition, and Vite fails the build if Prisma, database code or PostgreSQL drivers enter its module graph. Contracts never import Prisma types. An integration test checks that Prisma enums and contract codes agree.
The 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.
@@ -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/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
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
@@ -93,7 +93,7 @@ pnpm test:e2e
pnpm format:check
```
Unit tests cover contracts, translated resources, return URLs, scope rules and password verification. Integration tests use an isolated `merchantflow_test` database on a separate Compose service with temporary storage; they never truncate the development database. Browser tests start dedicated web/API instances on **5174/3002**, then test EN/RU at **390px/1440px**, permissions, navigation, filtering, direct refresh, focus restoration, reduced motion, and loading/error/empty states. Reports and screenshots are written to ignored `playwright-report/` and `test-results/` directories. Run integration and browser commands sequentially.
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:
@@ -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.
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.