Implemented KYB, compliance decisions, integration, and testing

This commit is contained in:
Oleksandr Prokhorenko
2026-09-24 21:31:42 +03:00
parent 382f6e8841
commit 1f8721e742
36 changed files with 2279 additions and 233 deletions
+19 -4
View File
@@ -94,7 +94,7 @@ The landing page at `/` is mobile-first and available in English and Russian, wi
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`, four missing KYB items, 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 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.
@@ -142,9 +142,9 @@ The [product brief](docs/product-brief.md) and [implementation checklist](docs/i
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. 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, 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.
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.
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.
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.
@@ -169,7 +169,7 @@ The old manager account IDs are retained while the original addresses become `al
## 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 four missing KYB items and an attributed creation history. The API rejects caller-supplied stage, audit identity and public-submission fields.
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 retain eight-record pages and clamp excessive page numbers to the last available page. Search, filters and pagination survive URL sharing, reload and browser navigation.
@@ -188,3 +188,18 @@ Merchant detail uses `?tab=overview|activity|onboarding|tasks`; existing `#check
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.