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
+37 -39
View File
@@ -1,50 +1,48 @@
# Implementation checklist
## Foundation
## Implemented
- [x] pnpm/Turbo workspace, pinned packages and lockfile
- [x] Shared UI, browser-safe contracts, server-only database package
- [x] PostgreSQL Compose, migrations, repeatable four-account/eighteen-merchant seed
- [x] Cookie sessions and server-enforced role scopes
- [x] Scoped dashboard, merchants/detail, pipeline, tasks, review queue
- [x] Responsive public landing, login, CRM shell, reusable states and controls
- [x] Persistent EN/RU UI, validation, statuses and formatting
- [x] Setup documentation and environment examples
- [x] Existing pnpm/Turbo, NestJS, React, PostgreSQL and Prisma foundation retained
- [x] Additive migration for merchant company/contact fields, decimal USD estimates, source, nullable manager, timestamps and versions
- [x] Typed interactions, immutable audit events, checklist change history, review cycles/snapshots and attributed commercial/compliance tasks
- [x] Hashed passwords, opaque database-backed sessions, cookie security, eight-hour expiry, rotation and logout
- [x] Trusted-Origin checks on every mutation and bounded IP/email login throttles with Retry-After
- [x] Four demo identities: Head, Compliance, Alex and Sam; original user IDs/password hashes preserved
- [x] Query-level scoping for reads, search, totals, detail children, dashboards and writes
- [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
- [x] Isolated PostgreSQL integration tests: auth, expiry, access, metrics, seed repeatability
- [x] Direct and proxied database-aware health endpoint
- [x] Browser checks at 390px/1440px, EN/RU, all roles and navigation
- [x] Keyboard, reduced motion, loading/error/empty states and overflow
- [x] Browser bundle excludes Prisma/database dependencies
| Check | Actual outcome |
| ---------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Build | All workspace packages built; browser bundle excludes database/Prisma dependencies |
| Lint and typecheck | Passed |
| Unit tests | 8 passed: contracts, localization, return paths, scopes and password hashing |
| 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 |
| -------------------------------- | ------------------------------------------------------------------------------------------------------------------------------ |
| `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 |
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.
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
- [ ] 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.
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.
+22 -10
View File
@@ -1,25 +1,37 @@
# 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
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
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
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
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.
No merchant creation/deletion UI, staff registration, merchant self-service, real payments, external KYB integration, uploads, external notifications or deployment.