diff --git a/README.md b/README.md index ef76fb2..7cd6f1e 100644 --- a/README.md +++ b/README.md @@ -57,21 +57,53 @@ API, database and contracts compile to ESM. Turbo builds dependencies before dep 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 | -| ------ | --------------------------------------- | ----------------------------------------------------- | -| 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=&page=1` | Search, canonical status filter, 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` | ALL / OPEN / OVERDUE / UPCOMING / DONE | -| GET | `/api/review-queue` | Compliance-only, oldest review first | +| 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` | 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. 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`: + +```json +{ + "name": "Example Company", + "contactName": "Example Contact", + "contactEmail": "contact@example.test", + "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`, 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 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. @@ -93,7 +125,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. Each runner recreates only the disposable `db-test` service to isolate workflow mutations; development data and the `db` service are never reset. +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: @@ -110,7 +142,7 @@ 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. 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. 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. 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. @@ -127,10 +159,32 @@ All mutation bodies carry the merchant's current integer `version`. Transactions | 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. +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 `alex@merchantflow.test` and `sam@merchantflow.test`, 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 four missing KYB items 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. + +| 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. diff --git a/apps/api/src/access.ts b/apps/api/src/access.ts index 1b8b3b2..d277e8f 100644 --- a/apps/api/src/access.ts +++ b/apps/api/src/access.ts @@ -1,6 +1,7 @@ import type { User } from '@merchantflow/contracts'; import type { Prisma } from '@merchantflow/database'; -import { successfulStages, type Status } from '@merchantflow/contracts'; +import type { Capabilities } from '@merchantflow/contracts'; +import { workflowActions, type Evidence } from './workflow-policy.js'; import { ApiError } from './shared.js'; export function merchantScope(user: User): Prisma.MerchantWhereInput { switch (user.role) { @@ -24,17 +25,14 @@ 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 }[] }, -) { +export function capabilities(user: User, merchant: Evidence): Capabilities { 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); + const actions = workflowActions(user, merchant); return { editCommercial: sales, editIdentity: sales && !locked, @@ -46,9 +44,8 @@ export function capabilities( ? (['KYB_NOTE'] as const) : (['NOTE', 'CALL', 'EMAIL', 'MEETING'] as const), manageTaskKind: user.role === 'COMPLIANCE_OFFICER' ? 'COMPLIANCE' : 'COMMERCIAL', + actions, nextStage: - sales && merchant.ownerId && index >= 0 && merchant.status !== 'COMPLIANCE_REVIEW' - ? (successfulStages[index + 1] ?? null) - : null, + actions.find((action) => action.kind === 'ADVANCE' && action.enabled)?.toStatus ?? null, }; } diff --git a/apps/api/src/app.ts b/apps/api/src/app.ts index 78468b9..489b449 100644 --- a/apps/api/src/app.ts +++ b/apps/api/src/app.ts @@ -15,6 +15,7 @@ import { CrmController } from './crm.js'; import { WorkflowController } from './workflow.js'; import { DATABASE, ApiError, ErrorFilter } from './shared.js'; import { env } from './env.js'; +import { PublicLeadController, PublicLeadService } from './public-leads.js'; @Controller('health') class HealthController { constructor(@Inject(DATABASE) private readonly db: PrismaClient) {} @@ -35,12 +36,19 @@ class DatabaseLifecycle implements OnApplicationShutdown { } } @Module({ - controllers: [HealthController, AuthController, CrmController, WorkflowController], + controllers: [ + HealthController, + AuthController, + CrmController, + WorkflowController, + PublicLeadController, + ], providers: [ { provide: DATABASE, useFactory: () => createDatabase(env.DATABASE_URL) }, DatabaseLifecycle, AuthService, SessionGuard, + PublicLeadService, ], }) class AppModule {} diff --git a/apps/api/src/crm.ts b/apps/api/src/crm.ts index 25776b9..6a22a8f 100644 --- a/apps/api/src/crm.ts +++ b/apps/api/src/crm.ts @@ -4,6 +4,8 @@ import { statuses, merchantQuerySchema, taskQuerySchema } from '@merchantflow/co import { SessionGuard } from './auth.js'; import { DATABASE, ApiError, type AuthRequest } from './shared.js'; import { capabilities, merchantScope, taskScope } from './access.js'; +import { evidenceInclude } from './workflow-policy.js'; +import { merchantHistory } from './history.js'; const merchantSelect = { id: true, name: true, @@ -73,11 +75,22 @@ export class CrmController { }); } @Get('merchants') async merchants(@Req() req: AuthRequest, @Query() query: unknown) { - const { page, search, status } = merchantQuerySchema.parse(query); + const { + page: requestedPage, + search, + status, + country, + industry, + ownerId, + } = merchantQuerySchema.parse(query); + if (ownerId && req.user.role === 'ACCOUNT_MANAGER') throw new ApiError('FORBIDDEN', 403); const where: Prisma.MerchantWhereInput = { AND: [ merchantScope(req.user), ...(status ? [{ status }] : []), + ...(country ? [{ country }] : []), + ...(industry ? [{ industry }] : []), + ...(ownerId ? [{ ownerId: ownerId === 'unassigned' ? null : ownerId }] : []), ...(search ? [ { @@ -93,74 +106,130 @@ export class CrmController { : []), ], }; - const [items, total] = await this.db.$transaction([ - this.db.merchant.findMany({ - where, - select: merchantSelect, - orderBy: [{ createdAt: 'desc' }, { id: 'asc' }], - take: 8, - skip: (page - 1) * 8, - }), - this.db.merchant.count({ where }), - ]); - return { items, total, page, pageSize: 8 }; + return this.db.$transaction( + async (tx) => { + const total = await tx.merchant.count({ where }); + const page = Math.min(requestedPage, Math.max(1, Math.ceil(total / 8))); + const items = await tx.merchant.findMany({ + where, + select: merchantSelect, + orderBy: [{ createdAt: 'desc' }, { id: 'asc' }], + take: 8, + skip: (page - 1) * 8, + }); + return { items, total, page, pageSize: 8 }; + }, + { isolationLevel: 'RepeatableRead' }, + ); + } + @Get('merchants/filters') async filters(@Req() req: AuthRequest) { + const rows = await this.db.merchant.findMany({ + where: merchantScope(req.user), + select: { country: true, industry: true, owner: { select: { id: true, name: true } } }, + }); + const canFilterOwner = req.user.role !== 'ACCOUNT_MANAGER'; + return { + countries: [...new Set(rows.flatMap((m) => (m.country ? [m.country] : [])))].sort(), + industries: [...new Set(rows.flatMap((m) => (m.industry ? [m.industry] : [])))].sort(), + owners: canFilterOwner + ? [ + ...new Map( + rows.flatMap((m) => (m.owner ? [[m.owner.id, m.owner] as const] : [])), + ).values(), + ].sort((a, b) => a.name.localeCompare(b.name)) + : [], + canCreate: req.user.role !== 'COMPLIANCE_OFFICER', + canFilterOwner, + }; } @Get('merchants/:id') async detail(@Req() req: AuthRequest, @Param('id') id: string) { - const merchant = await this.db.merchant.findFirst({ - where: { AND: [merchantScope(req.user), { id }] }, - select: { - ...merchantSelect, - checklist: { + return this.db.$transaction( + async (tx) => { + const merchant = await tx.merchant.findFirst({ + where: { AND: [merchantScope(req.user), { id }] }, select: { - id: true, - documentCode: true, - state: true, - note: true, - changes: { + ...merchantSelect, + checklist: { select: { id: true, - fromState: true, - toState: true, + documentCode: true, + state: true, note: true, - occurredAt: true, - actor: { select: { name: 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' }, + }, + notes: { + select: { id: true, text: true, createdAt: true, author: { select: { name: true } } }, + orderBy: { createdAt: 'desc' }, + }, + events: { select: eventSelect, orderBy: { occurredAt: 'desc' } }, + tasks: { where: taskScope(req.user), select: taskSelect, orderBy: { dueAt: 'asc' } }, + activities: { + select: { ...activitySelect, metadata: true }, 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' }, + }, }, - orderBy: { documentCode: 'asc' }, - }, - notes: { - select: { id: true, text: true, createdAt: true, author: { select: { name: true } } }, - orderBy: { createdAt: 'desc' }, - }, - events: { select: eventSelect, orderBy: { occurredAt: 'desc' } }, - 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); + const evidence = await tx.merchant.findFirstOrThrow({ + where: { AND: [merchantScope(req.user), { id }] }, + include: evidenceInclude, + }); + const history = await merchantHistory(merchant, tx); + return { + ...merchant, + activities: merchant.activities.map(({ metadata: _metadata, ...activity }) => activity), + capabilities: capabilities(req.user, evidence), + history, + }; }, - }); - if (!merchant) throw new ApiError('NOT_FOUND', 404); - return { ...merchant, capabilities: capabilities(req.user, merchant) }; + { isolationLevel: 'RepeatableRead' }, + ); } - @Get('pipeline') pipeline(@Req() req: AuthRequest) { - return this.db.merchant.findMany({ - where: merchantScope(req.user), - select: merchantSelect, - orderBy: { stageEnteredAt: 'asc' }, - }); + @Get('pipeline') async pipeline(@Req() req: AuthRequest) { + return this.db.$transaction( + async (tx) => { + const merchants = await tx.merchant.findMany({ + where: merchantScope(req.user), + select: merchantSelect, + orderBy: [{ stageEnteredAt: 'asc' }, { id: 'asc' }], + }); + const evidence = await tx.merchant.findMany({ + where: merchantScope(req.user), + include: evidenceInclude, + }); + const byId = new Map(evidence.map((merchant) => [merchant.id, merchant])); + return merchants.map((merchant) => ({ + ...merchant, + capabilities: capabilities(req.user, byId.get(merchant.id)!), + })); + }, + { isolationLevel: 'RepeatableRead' }, + ); } @Get('tasks') tasks(@Req() req: AuthRequest, @Query() query: unknown) { const { filter } = taskQuerySchema.parse(query); diff --git a/apps/api/src/history.ts b/apps/api/src/history.ts new file mode 100644 index 0000000..d8a5497 --- /dev/null +++ b/apps/api/src/history.ts @@ -0,0 +1,139 @@ +import type { HistoryEntry, Status } from '@merchantflow/contracts'; +import type { Prisma } from '@merchantflow/database'; + +type Actor = { name: string } | null; +type Sources = { + notes: { id: string; text: string; createdAt: Date; author: { name: string } }[]; + events: { + id: string; + fromStatus: Status | null; + toStatus: Status; + occurredAt: Date; + note: string | null; + actor: Actor; + }[]; + activities: { + id: string; + kind: 'NOTE' | 'CALL' | 'EMAIL' | 'MEETING' | 'KYB_NOTE' | 'AUDIT'; + text: string; + occurredAt: Date; + updatedAt: Date; + actor: Actor; + metadata: unknown; + }[]; + reviews: { + id: string; + cycle: number; + decision: 'PENDING' | 'APPROVED' | 'REJECTED' | 'CORRECTIONS'; + decidedAt: Date | null; + reason: string | null; + reviewer: Actor; + }[]; +}; +function record(value: unknown): Record { + return value && typeof value === 'object' && !Array.isArray(value) + ? (value as Record) + : {}; +} +export async function merchantHistory( + m: Sources, + db: Prisma.TransactionClient, +): Promise { + const ownerIds = new Set(); + for (const activity of m.activities) { + const meta = record(activity.metadata); + if (activity.text === 'Manager assignment updated') + for (const key of ['previousOwnerId', 'ownerId']) + if (typeof meta[key] === 'string') ownerIds.add(meta[key]); + } + const users = ownerIds.size + ? await db.user.findMany({ + where: { id: { in: [...ownerIds] } }, + select: { id: true, name: true }, + }) + : []; + const owner = (snapshot: unknown, id: unknown) => { + const value = record(snapshot); + if (typeof value.id === 'string' && typeof value.name === 'string') + return { id: value.id, name: value.name }; + return users.find((user) => user.id === id) ?? null; + }; + const history: HistoryEntry[] = [ + ...m.notes.map( + (note): HistoryEntry => ({ + id: `note:${note.id}`, + kind: 'INTERACTION', + occurredAt: note.createdAt.toISOString(), + updatedAt: note.createdAt.toISOString(), + actor: note.author, + activityId: null, + activityKind: 'NOTE', + text: note.text, + }), + ), + ...m.events.map( + (event): HistoryEntry => ({ + id: `stage:${event.id}`, + kind: 'STAGE', + occurredAt: event.occurredAt.toISOString(), + actor: event.actor, + fromStatus: event.fromStatus, + toStatus: event.toStatus, + reason: event.note, + }), + ), + ]; + for (const review of m.reviews) { + if (!review.decidedAt || review.decision === 'PENDING') continue; + history.push({ + id: `review:${review.id}`, + kind: 'REVIEW', + occurredAt: review.decidedAt.toISOString(), + actor: review.reviewer, + cycle: review.cycle, + decision: review.decision, + reason: review.reason, + }); + } + for (const activity of m.activities) { + const base = { + id: `activity:${activity.id}`, + occurredAt: activity.occurredAt.toISOString(), + actor: activity.actor, + }; + const meta = record(activity.metadata); + if (activity.kind !== 'AUDIT') { + history.push({ + ...base, + kind: 'INTERACTION', + activityId: activity.id, + activityKind: activity.kind, + text: activity.text, + updatedAt: activity.updatedAt.toISOString(), + }); + } else if (activity.text === 'Manager assignment updated') { + history.push({ + ...base, + kind: 'OWNERSHIP', + previousOwner: owner(meta.previousOwner, meta.previousOwnerId), + owner: owner(meta.owner, meta.ownerId), + }); + } else if ( + !meta.toStatus && + !meta.reviewId && + !( + activity.text === 'Merchant created' && + m.events.some( + (event) => + event.fromStatus === null && + event.occurredAt.getTime() === activity.occurredAt.getTime(), + ) + ) + ) { + history.push({ ...base, kind: 'AUDIT', text: activity.text }); + } + } + return history.sort( + (a, b) => b.occurredAt.localeCompare(a.occurredAt) || a.id.localeCompare(b.id), + ); +} diff --git a/apps/api/src/public-leads.ts b/apps/api/src/public-leads.ts new file mode 100644 index 0000000..0a9b396 --- /dev/null +++ b/apps/api/src/public-leads.ts @@ -0,0 +1,169 @@ +import { Body, Controller, HttpCode, Inject, Injectable, Post, Req, Res } from '@nestjs/common'; +import { createHash } from 'node:crypto'; +import type { Request, Response } from 'express'; +import { z } from 'zod'; +import { PrismaClient } from '@merchantflow/database'; +import { + documentCodes, + publicLeadKeySchema, + publicLeadSchema, + type PublicLead, +} from '@merchantflow/contracts'; +import { AuthService } from './auth.js'; +import { ApiError, DATABASE } from './shared.js'; + +const accepted = { ok: true } as const; +const envelope = z.object({ companyFax: z.string().max(512).default('') }).passthrough(); +const windowMs = 15 * 60 * 1000; +type Bucket = { until: number; count: number; keys: Set }; +class LeadLimitError extends ApiError { + constructor(readonly retryAfter: number) { + super('TOO_MANY_REQUESTS', 429); + } +} + +// Intentionally process-local, matching this application's single-process deployment. +export class LeadRateLimiter { + private buckets = new Map(); + constructor( + private now = Date.now, + private capacity = 10000, + ) {} + private take(key: string, limit: number, submissionKey?: string) { + const now = this.now(); + for (const [id, bucket] of this.buckets) if (bucket.until <= now) this.buckets.delete(id); + let bucket = this.buckets.get(key); + if (!bucket && this.buckets.size >= this.capacity) { + const earliest = Math.min(...[...this.buckets.values()].map((item) => item.until)); + return Math.max(1, Math.ceil((earliest - now) / 1000)); + } + bucket ??= { until: now + windowMs, count: 0, keys: new Set() }; + if (submissionKey && bucket.keys.has(submissionKey)) return 0; + if (bucket.count >= limit) return Math.max(1, Math.ceil((bucket.until - now) / 1000)); + bucket.count++; + if (submissionKey) bucket.keys.add(submissionKey); + this.buckets.set(key, bucket); + return 0; + } + attemptIp(ip: string) { + return this.take(`ip:${ip}`, 10); + } + reserveEmail(email: string, key: string) { + return this.take(`email:${email}`, 3, key); + } + releaseEmail(email: string, key: string) { + const bucket = this.buckets.get(`email:${email}`); + if (bucket?.keys.delete(key)) bucket.count--; + } +} + +@Injectable() +export class PublicLeadService { + private limits = new LeadRateLimiter(); + private inFlight = new Map }>(); + constructor( + @Inject(DATABASE) private db: PrismaClient, + private auth: AuthService, + ) {} + + async submit(body: unknown, req: Request, res: Response) { + this.auth.checkOrigin(req); + // Honeypots count toward IP pressure but never disclose rejection to the submitter. + const retryAfter = this.limits.attemptIp(req.ip ?? 'local'); + const { companyFax } = envelope.parse(body); + const { idempotencyKey } = publicLeadKeySchema.parse({ + idempotencyKey: req.get('Idempotency-Key'), + }); + if (companyFax.length > 0) return accepted; + if (retryAfter) { + res.setHeader('Retry-After', retryAfter); + throw new LeadLimitError(retryAfter); + } + const input = publicLeadSchema.parse(body); + // Schema output fixes property order; locale and honeypot are not business data. + const { companyFax: _trap, ...business } = input; + const hash = createHash('sha256').update(JSON.stringify(business)).digest('hex'); + const pending = this.inFlight.get(idempotencyKey); + if (pending && pending.hash !== hash) throw new ApiError('IDEMPOTENCY_CONFLICT', 409); + const operation = pending ?? { hash, promise: this.persist(idempotencyKey, hash, input) }; + if (!pending) this.inFlight.set(idempotencyKey, operation); + try { + return await operation.promise; + } catch (error) { + if (error instanceof LeadLimitError) res.setHeader('Retry-After', error.retryAfter); + throw error; + } finally { + if (this.inFlight.get(idempotencyKey) === operation) this.inFlight.delete(idempotencyKey); + } + } + + private async replay(key: string, hash: string) { + const existing = await this.db.merchant.findUnique({ + where: { publicSubmissionKey: key }, + select: { publicSubmissionHash: true }, + }); + if (!existing) return false; + if (existing.publicSubmissionHash !== hash) throw new ApiError('IDEMPOTENCY_CONFLICT', 409); + return true; + } + + private async persist(key: string, hash: string, input: PublicLead) { + if (await this.replay(key, hash)) return accepted; + const retryAfter = this.limits.reserveEmail(input.contactEmail, key); + if (retryAfter) throw new LeadLimitError(retryAfter); + try { + const { companyFax: _trap, ...business } = input; + const now = new Date(); + await this.db.$transaction(async (tx) => { + await tx.merchant.create({ + data: { + ...business, + status: 'NEW_LEAD', + source: 'LANDING_PAGE', + ownerId: null, + version: 0, + publicSubmissionKey: key, + publicSubmissionHash: hash, + createdAt: now, + stageEnteredAt: now, + checklist: { + create: documentCodes.map((documentCode) => ({ documentCode, state: 'MISSING' })), + }, + events: { create: { fromStatus: null, toStatus: 'NEW_LEAD', occurredAt: now } }, + activities: { + create: { + kind: 'AUDIT', + text: 'Lead received from landing page', + occurredAt: now, + metadata: { source: 'LANDING_PAGE' }, + }, + }, + }, + }); + }); + return accepted; + } catch (error) { + this.limits.releaseEmail(input.contactEmail, key); + // Another process may have won the unique-key race. The failed transaction is over. + if ( + typeof error === 'object' && + error !== null && + 'code' in error && + error.code === 'P2002' + ) { + if (await this.replay(key, hash)) return accepted; + } + throw error; + } + } +} + +@Controller('public/leads') +export class PublicLeadController { + constructor(private leads: PublicLeadService) {} + @Post() + @HttpCode(202) + create(@Body() body: unknown, @Req() req: Request, @Res({ passthrough: true }) res: Response) { + return this.leads.submit(body, req, res); + } +} diff --git a/apps/api/src/shared.ts b/apps/api/src/shared.ts index b269ee9..c2861c7 100644 --- a/apps/api/src/shared.ts +++ b/apps/api/src/shared.ts @@ -7,8 +7,12 @@ export interface AuthRequest extends Request { user: User; } export class ApiError extends HttpException { - constructor(code: string, status: number) { - super({ code }, status); + constructor( + code: string, + status: number, + details?: { blockingReasons: import('@merchantflow/contracts').BlockingReason[] }, + ) { + super({ code, ...details }, status); } } @Catch() diff --git a/apps/api/src/workflow-policy.ts b/apps/api/src/workflow-policy.ts new file mode 100644 index 0000000..e51f8b9 --- /dev/null +++ b/apps/api/src/workflow-policy.ts @@ -0,0 +1,122 @@ +import { + checklistComplete, + reviewSnapshot, + snapshotsEqual, + type Prisma, +} from '@merchantflow/database'; +import { + countryCodes, + industries, + successfulStages, + type BlockingReason, + type User, + type WorkflowAction, +} from '@merchantflow/contracts'; + +export const evidenceInclude = { + checklist: { + include: { changes: { orderBy: [{ occurredAt: 'asc' as const }, { id: 'asc' as const }] } }, + }, + reviews: { + include: { reviewer: { select: { role: true } } }, + orderBy: { cycle: 'desc' as const }, + }, + activities: { select: { kind: true } }, +} satisfies Prisma.MerchantInclude; +export type Evidence = Prisma.MerchantGetPayload<{ include: typeof evidenceInclude }>; + +export 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', + ) + ); +} +export 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)) + ); +} +export function qualificationFields(merchant: Evidence) { + const fields: string[] = []; + for (const field of ['name', 'website', 'contactName', 'contactEmail'] as const) + if (!merchant[field]?.trim()) fields.push(field); + if (!merchant.country || !countryCodes.includes(merchant.country)) fields.push('country'); + if (!merchant.industry || !industries.some((value) => value === merchant.industry)) + fields.push('industry'); + if (merchant.estimatedMonthlyVolumeUsd === null) fields.push('estimatedMonthlyVolumeUsd'); + return fields; +} +export function workflowActions(user: User, merchant: Evidence): WorkflowAction[] { + if (['LIVE', 'REJECTED'].includes(merchant.status)) return []; + const sales = + user.role === 'HEAD_OF_SALES' || + (user.role === 'ACCOUNT_MANAGER' && merchant.ownerId === user.id); + if (merchant.status === 'COMPLIANCE_REVIEW') { + const blockers: BlockingReason[] = + user.role === 'COMPLIANCE_OFFICER' ? [] : [{ code: 'COMPLIANCE_ONLY' }]; + if (!merchant.reviews.some((review) => review.decision === 'PENDING')) + blockers.push({ code: 'REVIEW_PENDING' }); + return [ + { + kind: 'REVIEW', + toStatus: null, + enabled: !blockers.length, + reasonRequired: false, + blockingReasons: blockers, + }, + ]; + } + const toStatus = + successfulStages[successfulStages.findIndex((stage) => stage === merchant.status) + 1]!; + const blockingReasons: BlockingReason[] = []; + if (!sales) blockingReasons.push({ code: 'SALES_ONLY' }); + if (!merchant.ownerId) blockingReasons.push({ code: 'ASSIGNMENT_REQUIRED' }); + if ( + toStatus === 'CONTACTED' && + !merchant.activities.some((a) => a.kind === 'CALL' || a.kind === 'EMAIL') + ) + blockingReasons.push({ code: 'CONTACT_REQUIRED' }); + if (toStatus === 'QUALIFIED') { + const fields = qualificationFields(merchant); + if (fields.length) blockingReasons.push({ code: 'QUALIFICATION_INCOMPLETE', fields }); + } + if (toStatus === 'COMPLIANCE_REVIEW') { + if (!receivedHistory(merchant, new Date())) + blockingReasons.push({ code: 'DOCUMENTS_REQUIRED' }); + if (merchant.reviews.some((r) => r.decision === 'PENDING')) + blockingReasons.push({ code: 'REVIEW_PENDING' }); + } + if (['TESTING', 'LIVE'].includes(toStatus) && !validApproval(merchant)) + blockingReasons.push({ code: 'APPROVAL_REQUIRED' }); + const actions: WorkflowAction[] = [ + { + kind: 'ADVANCE', + toStatus, + enabled: !blockingReasons.length, + reasonRequired: false, + blockingReasons, + }, + ]; + if ( + sales && + (['NEW_LEAD', 'CONTACTED', 'QUALIFIED'].includes(merchant.status) || + user.role === 'HEAD_OF_SALES') + ) + actions.push({ + kind: 'REJECT', + toStatus: 'REJECTED', + enabled: true, + reasonRequired: true, + blockingReasons: [], + }); + return actions; +} diff --git a/apps/api/src/workflow.ts b/apps/api/src/workflow.ts index 2fe12d7..36b0e77 100644 --- a/apps/api/src/workflow.ts +++ b/apps/api/src/workflow.ts @@ -2,7 +2,6 @@ import { Body, Controller, Inject, Param, Patch, Post, Req, UseGuards } from '@n import { PrismaClient, type Prisma, - checklistComplete, reviewSnapshot, reviewedFields, snapshotsEqual, @@ -15,40 +14,19 @@ import { reviewDecisionSchema, taskInputSchema, transitionSchema, - successfulStages, + merchantCreateSchema, + documentCodes, } 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)) - ); -} +import { + evidenceInclude, + receivedHistory, + workflowActions, + type Evidence, +} from './workflow-policy.js'; @UseGuards(SessionGuard) @Controller('merchants') @@ -63,8 +41,8 @@ export class WorkflowController { ) { 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); + if (!(await tx.merchant.findFirst({ where: scope, select: { id: true } }))) + 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({ @@ -76,6 +54,10 @@ export class WorkflowController { throw new ApiError('NOT_FOUND', 404); throw new ApiError('CONFLICT', 409); } + const merchant = await tx.merchant.findFirstOrThrow({ + where: scope, + include: evidenceInclude, + }); await action(tx, merchant); }); return { ok: true }; @@ -86,9 +68,10 @@ export class WorkflowController { merchantId: string, text: string, metadata?: Prisma.InputJsonValue, + occurredAt = new Date(), ) { await tx.activity.create({ - data: { merchantId, actorId: req.user.id, kind: 'AUDIT', text, metadata }, + data: { merchantId, actorId: req.user.id, kind: 'AUDIT', text, metadata, occurredAt }, }); } private async stage( @@ -103,7 +86,7 @@ export class WorkflowController { where: { AND: [merchantScope(req.user), { id: merchant.id }] }, data: { status: toStatus, stageEnteredAt: occurredAt }, }); - await tx.statusEvent.create({ + const event = await tx.statusEvent.create({ data: { merchantId: merchant.id, actorId: req.user.id, @@ -113,10 +96,69 @@ export class WorkflowController { note, }, }); - await this.audit(tx, req, merchant.id, `${merchant.status} → ${toStatus}`, { - fromStatus: merchant.status, - toStatus, - note: note ?? null, + await this.audit( + tx, + req, + merchant.id, + `${merchant.status} → ${toStatus}`, + { + fromStatus: merchant.status, + toStatus, + note: note ?? null, + eventId: event.id, + }, + occurredAt, + ); + } + + @Post() async create(@Req() req: AuthRequest, @Body() body: unknown) { + requireSales(req.user); + const { ownerId: requestedOwner, ...data } = merchantCreateSchema.parse(body); + if ( + req.user.role === 'ACCOUNT_MANAGER' && + requestedOwner !== undefined && + requestedOwner !== req.user.id + ) + throw new ApiError('FORBIDDEN', 403); + const ownerId = req.user.role === 'ACCOUNT_MANAGER' ? req.user.id : (requestedOwner ?? null); + return this.db.$transaction(async (tx) => { + if ( + ownerId && + !(await tx.user.findFirst({ + where: { id: ownerId, role: 'ACCOUNT_MANAGER' }, + select: { id: true }, + })) + ) + throw new ApiError('VALIDATION_ERROR', 400); + const now = new Date(); + return tx.merchant.create({ + data: { + ...data, + ownerId, + status: 'NEW_LEAD', + createdAt: now, + stageEnteredAt: now, + checklist: { create: documentCodes.map((documentCode) => ({ documentCode })) }, + events: { + create: { + fromStatus: null, + toStatus: 'NEW_LEAD', + actorId: req.user.id, + occurredAt: now, + }, + }, + activities: { + create: { + kind: 'AUDIT', + text: 'Merchant created', + actorId: req.user.id, + occurredAt: now, + metadata: { ownerId }, + }, + }, + }, + select: { id: true, version: true }, + }); }); } @Patch(':id') edit(@Req() req: AuthRequest, @Param('id') id: string, @Body() body: unknown) { @@ -141,13 +183,18 @@ export class WorkflowController { 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); + const owner = await tx.user.findFirst({ + where: { id: ownerId, role: 'ACCOUNT_MANAGER' }, + select: { id: true, name: true }, + }); + if (!owner) throw new ApiError('VALIDATION_ERROR', 400); + if (merchant.ownerId === ownerId) return; + const previousOwner = merchant.ownerId + ? await tx.user.findUnique({ + where: { id: merchant.ownerId }, + select: { id: true, name: true }, + }) + : null; await tx.merchant.updateMany({ where: { id }, data: { ownerId } }); await tx.task.updateMany({ where: { merchantId: id, kind: 'COMMERCIAL', status: 'OPEN' }, @@ -156,6 +203,8 @@ export class WorkflowController { await this.audit(tx, req, id, 'Manager assignment updated', { previousOwnerId: merchant.ownerId, ownerId, + previousOwner, + owner, }); }); } @@ -164,24 +213,23 @@ export class WorkflowController { @Param('id') id: string, @Body() body: unknown, ) { - const { version, toStatus } = transitionSchema.parse(body); + const { version, toStatus, reason } = transitionSchema.parse(body); return this.mutate(req, id, version, async (tx, merchant) => { requireSales(req.user); - const index = successfulStages.findIndex((stage) => stage === merchant.status); + const action = workflowActions(req.user, merchant).find( + (candidate) => candidate.toStatus === toStatus && candidate.kind !== 'REVIEW', + ); if ( - !merchant.ownerId || - index < 0 || - successfulStages[index + 1] !== toStatus || - merchant.status === 'COMPLIANCE_REVIEW' + merchant.status === 'COMPLIANCE_REVIEW' || + (toStatus === 'REJECTED' && !action && !['LIVE', 'REJECTED'].includes(merchant.status)) ) - throw new ApiError('WORKFLOW_INVALID', 409); + throw new ApiError('FORBIDDEN', 403); + if (!action || !action.enabled) + throw new ApiError('WORKFLOW_INVALID', 409, { + blockingReasons: action?.blockingReasons ?? [], + }); 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, @@ -192,9 +240,7 @@ export class WorkflowController { }, }); } - if (['TESTING', 'LIVE'].includes(toStatus) && !validApproval(merchant)) - throw new ApiError('WORKFLOW_INVALID', 409); - await this.stage(tx, req, merchant, toStatus); + await this.stage(tx, req, merchant, toStatus, reason); }); } @Patch(':id/checklist/:itemId') checklist( diff --git a/apps/api/test/integration.test.mjs b/apps/api/test/integration.test.mjs index e3cad3e..fa3b377 100644 --- a/apps/api/test/integration.test.mjs +++ b/apps/api/test/integration.test.mjs @@ -262,6 +262,7 @@ async function fixture(id, status = 'NEW_LEAD', ownerId = 'user-manager1') { data: { id, name: 'Workflow Test', + estimatedMonthlyVolumeUsd: '10000', legalName: 'Workflow Test Ltd', website: 'https://workflow.example', industry: 'SOFTWARE', @@ -438,11 +439,30 @@ test('corrections, resubmission, approval and activation preserve one merchant a mutate( `/merchants/${id}/transitions`, cookie, - { version: (await detail()).version, toStatus }, + { + version: (await detail()).version, + toStatus, + ...(toStatus === 'REJECTED' ? { reason: 'Attempted terminal transition' } : {}), + }, 'POST', ); try { assert.equal((await move('LIVE')).status, 409); + assert.equal( + ( + await mutate( + `/merchants/${id}/activities`, + sales, + { + version: (await detail()).version, + kind: 'CALL', + text: 'Confirmed contact before progression', + }, + 'POST', + ) + ).status, + 201, + ); for (const stage of ['CONTACTED', 'QUALIFIED', 'KYB']) assert.equal((await move(stage)).status, 201); assert.equal((await move('COMPLIANCE_REVIEW')).status, 409); diff --git a/apps/api/test/public-leads.test.mjs b/apps/api/test/public-leads.test.mjs new file mode 100644 index 0000000..4d2fcfb --- /dev/null +++ b/apps/api/test/public-leads.test.mjs @@ -0,0 +1,282 @@ +import { beforeEach, afterEach, after, test } from 'node:test'; +import assert from 'node:assert/strict'; +import { randomUUID } from 'node:crypto'; +import { createDatabase } from '@merchantflow/database'; +import { merchantDetailSchema, dashboardSchema } from '@merchantflow/contracts'; +import { createApp } from '../dist/app.js'; + +if (!process.env.DATABASE_URL?.endsWith('/merchantflow_test')) + throw new Error('Only the isolated test database is allowed'); +const db = createDatabase(process.env.DATABASE_URL); +const keys = new Set(); +let app, base; +const origin = process.env.APP_ORIGIN; +const input = () => ({ + name: 'Public lead integration', + contactName: 'Test Contact', + contactEmail: `lead-${randomUUID()}@example.test`, + website: 'example.test', + country: 'GB', + industry: 'OTHER', + estimatedMonthlyVolumeUsd: '1234,50', + companyFax: '', +}); +function key() { + const value = randomUUID(); + keys.add(value); + return value; +} +async function start() { + app = await createApp(); + await app.listen(0, '127.0.0.1'); + base = `${await app.getUrl()}/api`; +} +async function request(path, body, headers = {}, method = 'POST', url = base) { + const response = await fetch(`${url}${path}`, { + method, + headers: { + origin, + ...(body !== undefined ? { 'content-type': 'application/json' } : {}), + ...headers, + }, + ...(body !== undefined ? { body: JSON.stringify(body) } : {}), + }); + return { status: response.status, body: await response.json(), headers: response.headers }; +} +const submit = (data, id, headers = {}, url = base) => + request('/public/leads', data, { 'Idempotency-Key': id, ...headers }, 'POST', url); +async function cookie(account) { + const result = await request('/auth/login', { + email: `${account}@merchantflow.test`, + password: 'MerchantFlow123!', + }); + assert.equal(result.status, 201); + return result.headers.get('set-cookie').split(';')[0]; +} +beforeEach(start); +afterEach(async () => { + await app?.close(); + await db.merchant.deleteMany({ where: { publicSubmissionKey: { in: [...keys] } } }); + keys.clear(); +}); +after(() => db.$disconnect()); + +test('public submission persists complete onboarding context and respects CRM permissions', async () => { + const id = key(), + data = input(); + const result = await submit(data, id); + assert.equal(result.status, 202); + assert.deepEqual(result.body, { ok: true }); + const merchant = await db.merchant.findUnique({ + where: { publicSubmissionKey: id }, + include: { activities: true, events: true, checklist: { include: { changes: true } } }, + }); + assert.equal(merchant.status, 'NEW_LEAD'); + assert.equal(merchant.ownerId, null); + assert.equal(merchant.source, 'LANDING_PAGE'); + assert.equal(merchant.version, 0); + assert.equal(merchant.name, data.name); + assert.equal(merchant.contactName, data.contactName); + assert.equal(merchant.contactEmail, data.contactEmail); + assert.equal(merchant.country, 'GB'); + assert.equal(merchant.industry, 'OTHER'); + assert.equal(merchant.website, 'https://example.test/'); + assert.equal(merchant.estimatedMonthlyVolumeUsd.toFixed(2), '1234.50'); + assert.equal(merchant.checklist.length, 4); + assert.ok( + merchant.checklist.every((item) => item.state === 'MISSING' && item.changes.length === 0), + ); + assert.equal(merchant.activities.length, 1); + assert.equal(merchant.activities[0].actorId, null); + assert.equal(merchant.activities[0].kind, 'AUDIT'); + assert.equal(merchant.events.length, 1); + assert.equal(merchant.events[0].actorId, null); + assert.equal(merchant.events[0].fromStatus, null); + assert.equal(merchant.events[0].toStatus, 'NEW_LEAD'); + const head = await cookie('head'), + compliance = await cookie('compliance'), + alex = await cookie('alex'), + sam = await cookie('sam'); + for (const staff of [head, compliance]) { + const detail = await request(`/merchants/${merchant.id}`, undefined, { cookie: staff }, 'GET'); + assert.equal(detail.status, 200); + assert.equal(merchantDetailSchema.safeParse(detail.body).success, true); + assert.equal(detail.body.activities[0].actor, null); + assert.ok(!JSON.stringify(detail.body).includes('publicSubmission')); + const dashboard = await request('/dashboard', undefined, { cookie: staff }, 'GET'); + assert.equal(dashboardSchema.safeParse(dashboard.body).success, true); + } + for (const staff of [alex, sam]) { + assert.equal( + (await request(`/merchants/${merchant.id}`, undefined, { cookie: staff }, 'GET')).status, + 404, + ); + const list = await request( + `/merchants?search=${encodeURIComponent(data.contactEmail)}`, + undefined, + { cookie: staff }, + 'GET', + ); + assert.equal(list.body.total, 0); + } + assert.equal( + ( + await request( + `/merchants/${merchant.id}/transitions`, + { version: 0, toStatus: 'CONTACTED' }, + { cookie: head }, + ) + ).status, + 409, + ); + assert.equal( + ( + await request( + `/merchants/${merchant.id}/assignment`, + { version: 0, ownerId: 'user-manager1' }, + { cookie: head }, + 'PATCH', + ) + ).status, + 200, + ); + assert.equal( + ( + await request( + `/merchants/${merchant.id}/activities`, + { version: 1, kind: 'EMAIL', text: 'Responded to the public enquiry' }, + { cookie: alex }, + ) + ).status, + 201, + ); + assert.equal( + ( + await request( + `/merchants/${merchant.id}/transitions`, + { version: 2, toStatus: 'CONTACTED' }, + { cookie: alex }, + ) + ).status, + 201, + ); + assert.equal( + ( + await request( + `/merchants/${merchant.id}/activities/${merchant.activities[0].id}`, + { version: 3, kind: 'NOTE', text: 'attempt to edit audit' }, + { cookie: head }, + 'PATCH', + ) + ).status, + 403, + ); +}); + +test('sequential, concurrent and post-restart retries create exactly one lead', async () => { + const id = key(), + data = input(); + const other = await createApp(); + await other.listen(0, '127.0.0.1'); + try { + const results = await Promise.all([ + submit(data, id), + submit(data, id), + submit(data, id, {}, `${await other.getUrl()}/api`), + ]); + assert.ok(results.every((result) => result.status === 202)); + assert.equal((await submit({ ...data, estimatedMonthlyVolumeUsd: '1234.50' }, id)).status, 202); + } finally { + await other.close(); + } + await app.close(); + await start(); + assert.equal((await submit(data, id)).status, 202); + assert.equal((await submit({ ...data, name: 'Changed payload' }, id)).status, 409); + const matches = await db.merchant.findMany({ + where: { publicSubmissionKey: id }, + include: { activities: true, events: true }, + }); + assert.equal(matches.length, 1); + assert.equal(matches[0].activities.length, 1); + assert.equal(matches[0].events.length, 1); +}); + +test('honeypots always accept valid envelopes without creating any related records', async () => { + const before = [ + await db.merchant.count(), + await db.activity.count(), + await db.statusEvent.count(), + await db.kybChecklistItem.count(), + ]; + for (let i = 0; i < 12; i++) { + const result = await submit( + i % 2 ? { ...input(), companyFax: 'spam' } : { companyFax: ' ', contactEmail: 'invalid' }, + key(), + ); + assert.equal(result.status, 202); + assert.deepEqual(result.body, { ok: true }); + } + assert.deepEqual( + [ + await db.merchant.count(), + await db.activity.count(), + await db.statusEvent.count(), + await db.kybChecklistItem.count(), + ], + before, + ); +}); + +test('origin, key and body checks reject invalid submissions without persisting', async () => { + const id = key(); + for (const headers of [ + { origin: 'https://untrusted.example' }, + { origin: '' }, + { 'sec-fetch-site': 'cross-site' }, + ]) + assert.equal((await submit(input(), id, headers)).status, 403); + assert.equal((await submit(input(), 'invalid')).status, 400); + assert.equal((await request('/public/leads', input())).status, 400); + for (const data of [ + { ...input(), country: 'ZZ' }, + { ...input(), ownerId: 'user-head' }, + { ...input(), estimatedMonthlyVolumeUsd: '-1' }, + { ...input(), companyFax: 42 }, + ]) + assert.equal((await submit(data, id)).status, 400); + assert.equal(await db.merchant.count({ where: { publicSubmissionKey: id } }), 0); +}); + +test('email quotas allow successful replays and IP quotas include invalid attempts', async () => { + const data = input(), + first = key(); + assert.equal((await submit(data, first)).status, 202); + for (let i = 0; i < 2; i++) assert.equal((await submit(data, key())).status, 202); + assert.equal((await submit(data, first)).status, 202); + const result = await submit(data, key()); + assert.equal(result.status, 429); + assert.ok(Number(result.headers.get('retry-after')) > 0); + await app.close(); + await start(); + for (let i = 0; i < 10; i++) assert.equal((await submit({}, key())).status, 400); + const limited = await submit(input(), key(), { 'x-forwarded-for': '1.2.3.4' }); + assert.equal(limited.status, 429); + assert.ok(Number(limited.headers.get('retry-after')) > 0); +}); + +test('a failed creation activity rolls back the lead and its children; retry remains safe', async () => { + const id = key(), + data = { ...input(), name: 'Force rollback integration' }; + await db.$executeRaw`CREATE FUNCTION fail_public_lead_activity() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN IF EXISTS (SELECT 1 FROM "Merchant" WHERE id = NEW."merchantId" AND name = 'Force rollback integration') THEN RAISE EXCEPTION 'Injected test failure'; END IF; RETURN NEW; END $$`; + await db.$executeRaw`CREATE TRIGGER fail_public_lead_activity BEFORE INSERT ON "Activity" FOR EACH ROW EXECUTE FUNCTION fail_public_lead_activity()`; + try { + assert.equal((await submit(data, id)).status, 500); + assert.equal(await db.merchant.count({ where: { publicSubmissionKey: id } }), 0); + } finally { + await db.$executeRaw`DROP TRIGGER fail_public_lead_activity ON "Activity"`; + await db.$executeRaw`DROP FUNCTION fail_public_lead_activity()`; + } + assert.equal((await submit(data, id)).status, 202); + assert.equal(await db.merchant.count({ where: { publicSubmissionKey: id } }), 1); +}); diff --git a/apps/api/test/sales-workspace.test.mjs b/apps/api/test/sales-workspace.test.mjs new file mode 100644 index 0000000..348f5e5 --- /dev/null +++ b/apps/api/test/sales-workspace.test.mjs @@ -0,0 +1,473 @@ +import { before, after, afterEach, test } from 'node:test'; +import assert from 'node:assert/strict'; +import { randomUUID } from 'node:crypto'; +import { createDatabase } from '@merchantflow/database'; +import { + merchantDetailSchema, + pipelineBoardSchema, + merchantFiltersSchema, + statuses, +} from '@merchantflow/contracts'; +import { createApp } from '../dist/app.js'; + +if (!process.env.DATABASE_URL?.endsWith('/merchantflow_test')) + throw new Error('Only the isolated test database is allowed'); +const db = createDatabase(process.env.DATABASE_URL); +const created = new Set(); +const cookies = {}; +let app, base; +async function request( + path, + actor = 'head', + body, + method = body === undefined ? 'GET' : 'POST', + headers = {}, +) { + const response = await fetch(`${base}${path}`, { + method, + headers: { + origin: process.env.APP_ORIGIN, + ...(cookies[actor] ? { cookie: cookies[actor] } : {}), + ...(body === undefined ? {} : { 'content-type': 'application/json' }), + ...headers, + }, + ...(body === undefined ? {} : { body: JSON.stringify(body) }), + }); + return { status: response.status, body: await response.json(), headers: response.headers }; +} +before(async () => { + app = await createApp(); + await app.listen(0, '127.0.0.1'); + base = `${await app.getUrl()}/api`; + for (const account of ['head', 'alex', 'sam', 'compliance']) { + const result = await request('/auth/login', null, { + email: `${account}@merchantflow.test`, + password: 'MerchantFlow123!', + }); + assert.equal(result.status, 201); + cookies[account] = result.headers.get('set-cookie').split(';')[0]; + } +}); +afterEach(async () => { + await db.merchant.deleteMany({ where: { id: { in: [...created] } } }); + created.clear(); +}); +after(async () => { + await app?.close(); + await db.$disconnect(); +}); +const input = (extra = {}) => ({ + name: `Sales ${randomUUID()}`, + contactName: 'Unique Contact', + contactEmail: 'unique@sales.test', + ...extra, +}); +async function create(actor = 'head', extra = {}) { + const result = await request('/merchants', actor, input(extra)); + assert.equal(result.status, 201, JSON.stringify(result.body)); + created.add(result.body.id); + return result.body.id; +} +async function detail(id, actor = 'head') { + const result = await request(`/merchants/${id}`, actor); + assert.equal(result.status, 200); + return merchantDetailSchema.parse(result.body); +} +async function change(id, path, body, actor = 'head', method = 'PATCH') { + const m = await detail(id); + return request(`/merchants/${id}${path}`, actor, { version: m.version, ...body }, method); +} +const move = (id, toStatus, actor = 'head', reason) => + change( + id, + '/transitions', + { toStatus, ...(reason === undefined ? {} : { reason }) }, + actor, + 'POST', + ); +const log = (id, kind = 'CALL', text = 'Contacted the primary contact') => + change(id, '/activities', { kind, text }, 'head', 'POST'); + +test('staff creation is atomic, minimally required, role-bound and strict', async () => { + const unassigned = await create(); + let m = await detail(unassigned); + assert.equal(m.status, 'NEW_LEAD'); + assert.equal(m.owner, null); + assert.equal(m.website, null); + assert.equal(m.country, null); + assert.equal(m.industry, null); + assert.equal(m.checklist.length, 4); + assert.ok(m.checklist.every((item) => item.state === 'MISSING')); + assert.equal(m.events.length, 1); + assert.equal(m.activities.length, 1); + assert.equal(m.activities[0].actor.name, 'Elena Carter'); + assert.equal(m.history.length, 1); // Initial stage and creation audit represent one event. + assert.equal(m.version, 0); + assert.ok(!JSON.stringify(m).includes('publicSubmission')); + const assigned = await create('head', { + ownerId: 'user-manager2', + website: 'example.test', + country: 'gb', + industry: 'SOFTWARE', + estimatedMonthlyVolumeUsd: '0', + }); + m = await detail(assigned); + assert.equal(m.owner.id, 'user-manager2'); + assert.equal(m.country, 'GB'); + assert.equal(m.estimatedMonthlyVolumeUsd, '0'); + const self = await create('alex'); + assert.equal((await detail(self)).owner.id, 'user-manager1'); + for (const ownerId of ['user-manager2', null]) + assert.equal((await request('/merchants', 'alex', input({ ownerId }))).status, 403); + assert.equal((await request('/merchants', 'compliance', input())).status, 403); + assert.equal((await request('/merchants', null, input())).status, 401); + assert.equal( + (await request('/merchants', 'head', input(), 'POST', { origin: 'https://untrusted.test' })) + .status, + 403, + ); + assert.equal((await request('/merchants', 'head', input({ ownerId: 'user-head' }))).status, 400); + for (const field of ['status', 'actorId', 'reviewerId', 'publicSubmissionKey', 'version']) + assert.equal( + (await request('/merchants', 'head', input({ [field]: 'injected' }))).status, + 400, + field, + ); + for (const field of ['name', 'contactName', 'contactEmail']) + assert.equal((await request('/merchants', 'head', input({ [field]: '' }))).status, 400, field); + assert.equal((await request(`/merchants/${self}`, 'sam')).status, 404); + assert.equal((await request(`/merchants/${assigned}`, 'alex')).status, 404); +}); + +test('search, combined filters, pagination and metadata apply ownership scope before counts', async () => { + const prefix = `Directory-${randomUUID()}`; + const ids = []; + for (let index = 0; index < 10; index++) + ids.push( + await create('alex', { + name: `${prefix} ${index}`, + contactName: `${prefix} Contact`, + contactEmail: `${prefix.toLowerCase()}@example.test`, + country: 'GB', + industry: 'SOFTWARE', + website: 'search.example.test', + }), + ); + const hidden = await create('sam', { + name: `${prefix} Hidden`, + country: 'JP', + industry: 'TRAVEL', + }); + const unassigned = await create('head', { name: `${prefix} Unassigned` }); + await change(ids[0], '', { legalName: `${prefix} Legal` }); + for (const search of [ + `${prefix} 1`, + `${prefix} Contact`, + `${prefix.toLowerCase()}@example.test`, + `${prefix} Legal`, + ]) { + const result = await request(`/merchants?search=${encodeURIComponent(search)}`, 'alex'); + assert.equal(result.status, 200); + assert.ok(result.body.total > 0); + assert.ok(result.body.items.every((m) => m.owner.id === 'user-manager1')); + } + const query = `search=${prefix}&country=GB&industry=SOFTWARE&status=NEW_LEAD`; + const page1 = (await request(`/merchants?${query}`, 'alex')).body; + const page2 = (await request(`/merchants?${query}&page=2`, 'alex')).body; + assert.equal(page1.total, 10); + assert.equal(page1.items.length, 8); + assert.equal(page2.items.length, 2); + assert.equal(new Set([...page1.items, ...page2.items].map((m) => m.id)).size, 10); + assert.equal((await request(`/merchants?${query}&page=10000`, 'alex')).body.page, 2); + assert.equal((await request(`/merchants?${query}&ownerId=user-manager2`, 'alex')).status, 403); + assert.equal( + (await request(`/merchants?search=${prefix}&ownerId=user-manager2`, 'head')).body.items[0].id, + hidden, + ); + assert.equal( + (await request(`/merchants?search=${prefix}&ownerId=unassigned`, 'compliance')).body.items[0] + .id, + unassigned, + ); + assert.equal((await request(`/merchants?search=${prefix}&country=JP`, 'alex')).body.total, 0); + for (const invalid of ['country=ZZ', 'industry=INVALID', 'status=Live', 'page=1.5', 'page=-1']) + assert.equal((await request(`/merchants?${invalid}`)).status, 400); + const ownFilters = merchantFiltersSchema.parse( + (await request('/merchants/filters', 'alex')).body, + ); + assert.equal(ownFilters.canFilterOwner, false); + assert.deepEqual(ownFilters.owners, []); + assert.equal(ownFilters.canCreate, true); + const expectedCountries = [ + ...new Set( + ( + await db.merchant.findMany({ where: { ownerId: 'user-manager1', country: { not: null } } }) + ).map((m) => m.country), + ), + ].sort(); + assert.deepEqual(ownFilters.countries, expectedCountries); + const complianceFilters = merchantFiltersSchema.parse( + (await request('/merchants/filters', 'compliance')).body, + ); + assert.equal(complianceFilters.canFilterOwner, true); + assert.equal(complianceFilters.canCreate, false); + assert.equal((await request('/users/assignable-managers', 'compliance')).status, 403); +}); + +test('commercial gates expose the same blockers as mutations and accept a zero volume', async () => { + const id = await create(); + const action = async () => + (await detail(id)).capabilities.actions.find((a) => a.kind === 'ADVANCE'); + assert.deepEqual( + (await action()).blockingReasons.map((b) => b.code), + ['ASSIGNMENT_REQUIRED', 'CONTACT_REQUIRED'], + ); + let result = await move(id, 'CONTACTED'); + assert.equal(result.status, 409); + assert.deepEqual(result.body.blockingReasons, (await action()).blockingReasons); + assert.equal((await detail(id)).version, 0); + await change(id, '/assignment', { ownerId: 'user-manager1' }); + await log(id, 'MEETING'); + assert.equal((await move(id, 'CONTACTED', 'alex')).status, 409); + await log(id, 'EMAIL'); + assert.equal((await action()).enabled, true); + assert.equal((await move(id, 'CONTACTED', 'alex')).status, 201); + assert.equal((await move(id, 'QUALIFIED', 'alex')).status, 409); + assert.deepEqual( + (await action()).blockingReasons[0].fields.sort(), + ['website', 'country', 'industry', 'estimatedMonthlyVolumeUsd'].sort(), + ); + await change( + id, + '', + { website: 'sales.test', country: 'GB', industry: 'OTHER', estimatedMonthlyVolumeUsd: '0' }, + 'alex', + ); + assert.equal((await move(id, 'QUALIFIED', 'alex')).status, 201); + assert.equal((await move(id, 'KYB', 'alex')).status, 201); + result = await move(id, 'COMPLIANCE_REVIEW', 'alex'); + assert.equal(result.status, 409); + assert.equal(result.body.blockingReasons[0].code, 'DOCUMENTS_REQUIRED'); + const m = await detail(id); + assert.equal(m.events.filter((event) => event.toStatus === 'CONTACTED').length, 1); + assert.equal( + m.history.filter((entry) => entry.kind === 'STAGE' && entry.toStatus === 'CONTACTED').length, + 1, + ); + for (const payload of [ + { status: 'LIVE' }, + { ownerId: 'user-manager2' }, + { actorId: 'user-head' }, + ]) + assert.equal((await change(id, '', payload, 'alex')).status, 400); + assert.equal((await move(id, 'LIVE', 'alex')).status, 409); + assert.equal((await move(id, 'TESTING', 'compliance')).status, 403); + const pipe = pipelineBoardSchema.parse((await request('/pipeline', 'alex')).body); + assert.deepEqual( + pipe.find((row) => row.id === id).capabilities, + (await detail(id, 'alex')).capabilities, + ); +}); + +test('every rejection role and stage rule is enforced, with terminal outcomes and preserved compliance records', async () => { + for (const stage of statuses) { + for (const actor of ['head', 'alex', 'compliance']) { + const id = await create('alex'); + await db.merchant.update({ where: { id }, data: { status: stage } }); + const allowed = + (['NEW_LEAD', 'CONTACTED', 'QUALIFIED'].includes(stage) && actor !== 'compliance') || + (['KYB', 'INTEGRATION', 'TESTING'].includes(stage) && actor === 'head'); + assert.equal( + (await move(id, 'REJECTED', actor, ' Business no longer proceeding ')).status, + allowed + ? 201 + : actor === 'compliance' || + stage === 'COMPLIANCE_REVIEW' || + !['LIVE', 'REJECTED'].includes(stage) + ? 403 + : 409, + `${stage}/${actor}`, + ); + const m = await detail(id); + assert.equal(m.status, allowed ? 'REJECTED' : stage); + if (allowed) { + assert.equal(m.events[0].note, 'Business no longer proceeding'); + assert.equal(m.capabilities.actions.length, 0); + assert.equal((await move(id, 'NEW_LEAD', actor)).status, 409); + } + } + } + const id = await create('alex'); + for (const reason of [undefined, '', ' ']) + assert.equal((await move(id, 'REJECTED', 'alex', reason)).status, 400); + assert.equal((await detail(id)).version, 0); + // Head closure of an approved merchant must retain the original immutable decision. + const approved = await db.merchant.findFirst({ + where: { status: 'INTEGRATION' }, + include: { reviews: true }, + }); + const clone = await create('alex'); + await db.merchant.update({ where: { id: clone }, data: { status: 'INTEGRATION' } }); + const review = await db.complianceReview.create({ + data: { + merchantId: clone, + cycle: 1, + decision: 'APPROVED', + submittedById: 'user-head', + reviewerId: 'user-compliance', + decidedAt: new Date(), + snapshot: approved.reviews[0].snapshot, + }, + }); + assert.equal((await move(clone, 'REJECTED', 'head', 'Commercial terms declined')).status, 201); + assert.deepEqual(await db.complianceReview.findUnique({ where: { id: review.id } }), review); +}); + +test('qualification and assignment gates cannot be bypassed; approved integration evidence is still required', async () => { + for (const stage of ['QUALIFIED', 'INTEGRATION', 'TESTING']) { + const id = await create('head', stage === 'QUALIFIED' ? {} : { ownerId: 'user-manager1' }); + await db.merchant.update({ where: { id }, data: { status: stage } }); + const target = stage === 'QUALIFIED' ? 'KYB' : stage === 'INTEGRATION' ? 'TESTING' : 'LIVE'; + const result = await move(id, target); + assert.equal(result.status, 409); + assert.equal( + result.body.blockingReasons[0].code, + stage === 'QUALIFIED' ? 'ASSIGNMENT_REQUIRED' : 'APPROVAL_REQUIRED', + ); + } +}); + +test('ownership handoff retains attribution and persists typed chronological history', async () => { + const id = await create('alex'); + await log(id, 'NOTE', 'Durable note'); + await log(id, 'CALL', 'Durable call'); + const open = await db.task.create({ + data: { + merchantId: id, + title: 'Transfer me', + assigneeId: 'user-manager1', + creatorId: 'user-head', + dueAt: new Date(), + }, + }); + const done = await db.task.create({ + data: { + merchantId: id, + title: 'Keep attribution', + status: 'DONE', + assigneeId: 'user-manager1', + creatorId: 'user-manager1', + completedById: 'user-head', + completedAt: new Date(), + dueAt: new Date(), + }, + }); + const comp = await db.task.create({ + data: { + merchantId: id, + title: 'Personal review', + kind: 'COMPLIANCE', + assigneeId: 'user-compliance', + creatorId: 'user-compliance', + dueAt: new Date(), + }, + }); + const original = await detail(id); + assert.equal((await change(id, '/assignment', { ownerId: 'user-manager2' })).status, 200); + assert.equal((await db.task.findUnique({ where: { id: open.id } })).assigneeId, 'user-manager2'); + assert.deepEqual(await db.task.findUnique({ where: { id: done.id } }), done); + assert.deepEqual(await db.task.findUnique({ where: { id: comp.id } }), comp); + assert.equal((await request(`/merchants/${id}`, 'alex')).status, 404); + assert.equal( + ( + await request(`/merchants/${id}/activities`, 'alex', { + version: original.version, + kind: 'NOTE', + text: 'Former owner', + }) + ).status, + 404, + ); + const m = await detail(id, 'sam'); + const ownership = m.history.find((entry) => entry.kind === 'OWNERSHIP'); + assert.equal(ownership.previousOwner.id, 'user-manager1'); + assert.equal(ownership.owner.id, 'user-manager2'); + assert.equal(ownership.actor.name, 'Elena Carter'); + assert.deepEqual( + m.history.map((entry) => entry.occurredAt), + [...m.history.map((entry) => entry.occurredAt)].sort().reverse(), + ); + for (const activity of original.activities) + assert.deepEqual(m.activities.find((entry) => entry.id === activity.id).actor, activity.actor); + assert.ok(!JSON.stringify(m).includes('previousOwnerId')); + assert.ok( + m.history.some((entry) => entry.kind === 'INTERACTION' && entry.text === 'Durable call'), + ); + assert.deepEqual((await detail(id, 'sam')).history, m.history); +}); + +test('conflicting transitions, ownership and activity writes commit at most once', async () => { + const id = await create('alex'); + await log(id); + let m = await detail(id); + const results = await Promise.all([ + request(`/merchants/${id}/transitions`, 'alex', { version: m.version, toStatus: 'CONTACTED' }), + request( + `/merchants/${id}/assignment`, + 'head', + { version: m.version, ownerId: 'user-manager2' }, + 'PATCH', + ), + request(`/merchants/${id}/activities`, 'alex', { + version: m.version, + kind: 'EMAIL', + text: 'Concurrent outreach', + }), + ]); + assert.equal(results.filter((r) => r.status < 300).length, 1); + assert.ok(results.filter((r) => r.status >= 300).every((r) => [404, 409].includes(r.status))); + assert.equal((await detail(id)).version, m.version + 1); + assert.equal( + ( + await request(`/merchants/${id}/transitions`, 'head', { + version: m.version, + toStatus: 'REJECTED', + reason: 'Stale closure', + }) + ).status, + 409, + ); + m = await detail(id); + const rejection = await Promise.all( + [1, 2].map(() => + request(`/merchants/${id}/transitions`, 'head', { + version: m.version, + toStatus: 'REJECTED', + reason: 'Closure', + }), + ), + ); + assert.deepEqual(rejection.map((r) => r.status).sort(), [201, 409]); + assert.equal( + (await detail(id)).events.filter((event) => event.toStatus === 'REJECTED').length, + 1, + ); +}); + +test('failed audit writes roll back merchant creation and stage changes completely', async () => { + const id = await create('alex'); + await log(id); + const original = await detail(id); + await db.$executeRaw`CREATE FUNCTION fail_sales_audit() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN IF NEW.text = 'NEW_LEAD → CONTACTED' OR NEW.text = 'Merchant created' THEN RAISE EXCEPTION 'Injected sales failure'; END IF; RETURN NEW; END $$`; + await db.$executeRaw`CREATE TRIGGER sales_audit_failure BEFORE INSERT ON "Activity" FOR EACH ROW EXECUTE FUNCTION fail_sales_audit()`; + try { + assert.equal((await move(id, 'CONTACTED', 'alex')).status, 500); + assert.deepEqual(await detail(id), original); + const name = `Rollback-${randomUUID()}`; + assert.equal((await request('/merchants', 'head', input({ name }))).status, 500); + assert.equal(await db.merchant.count({ where: { name } }), 0); + } finally { + await db.$executeRaw`DROP TRIGGER sales_audit_failure ON "Activity"`; + await db.$executeRaw`DROP FUNCTION fail_sales_audit()`; + } +}); diff --git a/apps/api/test/unit.test.mjs b/apps/api/test/unit.test.mjs index 5b96c08..d4dec7e 100644 --- a/apps/api/test/unit.test.mjs +++ b/apps/api/test/unit.test.mjs @@ -2,6 +2,7 @@ import test from 'node:test'; import assert from 'node:assert/strict'; import { merchantScope } from '../dist/access.js'; import { hashPassword, verifyPassword } from '@merchantflow/database'; +import { LeadRateLimiter } from '../dist/public-leads.js'; test('passwords use distinct salts and reject incorrect values', () => { const hash = hashPassword('example-password'); assert.notEqual(hash, hashPassword('example-password')); @@ -9,6 +10,22 @@ test('passwords use distinct salts and reject incorrect values', () => { assert.equal(verifyPassword('wrong', hash), false); assert.equal(verifyPassword('wrong', 'broken'), false); }); +test('public lead limits expire, bound storage and reserve each submission once', () => { + let now = 0; + const limiter = new LeadRateLimiter(() => now, 3); + for (let i = 0; i < 10; i++) assert.equal(limiter.attemptIp('127.0.0.1'), 0); + assert.equal(limiter.attemptIp('127.0.0.1'), 900); + for (let i = 0; i < 3; i++) assert.equal(limiter.reserveEmail('lead@example.test', String(i)), 0); + assert.equal(limiter.reserveEmail('lead@example.test', '0'), 0); + assert.equal(limiter.reserveEmail('lead@example.test', 'new'), 900); + limiter.releaseEmail('lead@example.test', '0'); + assert.equal(limiter.reserveEmail('lead@example.test', 'new'), 0); + assert.equal(limiter.attemptIp('another'), 0); + assert.equal(limiter.attemptIp('map-full'), 900); + now = 900001; + assert.equal(limiter.attemptIp('map-full'), 0); + assert.equal(limiter.reserveEmail('lead@example.test', 'another'), 0); +}); test('every role receives its exact merchant scope', () => { assert.deepEqual(merchantScope({ role: 'HEAD_OF_SALES' }), {}); assert.deepEqual(merchantScope({ role: 'ACCOUNT_MANAGER', id: 'manager-1' }), { diff --git a/apps/web/src/components/lead-form.tsx b/apps/web/src/components/lead-form.tsx new file mode 100644 index 0000000..37f2de3 --- /dev/null +++ b/apps/web/src/components/lead-form.tsx @@ -0,0 +1,285 @@ +import { useEffect, useMemo, useRef, useState } from 'react'; +import { useTranslation } from 'react-i18next'; +import { useMutation } from '@tanstack/react-query'; +import { useForm } from 'react-hook-form'; +import { zodResolver } from '@hookform/resolvers/zod'; +import { ArrowUpRight, Check, LoaderCircle } from 'lucide-react'; +import { + countryCodes, + industries, + publicLeadSchema, + publicLeadAcceptedSchema, + type PublicLead, + type PublicLeadInput, +} from '@merchantflow/contracts'; +import { Input } from '@merchantflow/ui/components/input'; +import { NativeSelect } from '@merchantflow/ui/components/native-select'; +import { FormField } from '@merchantflow/ui/components/form-field'; +import { Button } from '@merchantflow/ui/components/button'; +import { api, ApiError } from '../lib/api'; + +const fields = [ + 'name', + 'contactName', + 'contactEmail', + 'website', + 'country', + 'industry', + 'estimatedMonthlyVolumeUsd', +] as const; +type LeadField = (typeof fields)[number]; +const inputs = [ + { name: 'name', autoComplete: 'organization', placeholder: 'Acme', type: 'text' }, + { name: 'contactName', autoComplete: 'name', placeholder: '', type: 'text' }, + { name: 'contactEmail', autoComplete: 'email', placeholder: 'you@company.com', type: 'email' }, + { name: 'website', autoComplete: 'url', placeholder: 'example.com', type: 'text' }, +] as const; + +export function LeadForm() { + const { t, i18n } = useTranslation(); + const keys = useRef(new Map()); + const busy = useRef(false); + const successRef = useRef(null); + const [retryAt, setRetryAt] = useState(0); + const [now, setNow] = useState(Date.now); + const form = useForm({ + resolver: zodResolver(publicLeadSchema), + defaultValues: { + name: '', + contactName: '', + contactEmail: '', + website: '', + country: '', + industry: '', + estimatedMonthlyVolumeUsd: '', + companyFax: '', + }, + }); + const countries = useMemo(() => { + const display = new Intl.DisplayNames([i18n.language], { type: 'region' }); + const collator = new Intl.Collator(i18n.language); + return countryCodes + .map((code) => ({ code, name: display.of(code) ?? code })) + .sort((a, b) => collator.compare(a.name, b.name)); + }, [i18n.language]); + const remaining = Math.max(0, Math.ceil((retryAt - now) / 1000)); + useEffect(() => { + if (!retryAt) return; + const timer = window.setInterval(() => { + const time = Date.now(); + setNow(time); + if (time >= retryAt) window.clearInterval(timer); + }, 1000); + return () => window.clearInterval(timer); + }, [retryAt]); + const mutation = useMutation({ + retry: false, + mutationFn: (input: PublicLead) => { + const { companyFax: _trap, ...business } = input; + const payload = JSON.stringify(business); + const key = keys.current.get(payload) ?? crypto.randomUUID(); + keys.current.set(payload, key); + return api('/public/leads', publicLeadAcceptedSchema, { + method: 'POST', + headers: { 'Idempotency-Key': key }, + body: JSON.stringify(input), + signal: AbortSignal.timeout(20000), + }); + }, + onError: (error) => { + if (!(error instanceof ApiError)) return; + for (const issue of error.issues) { + if (fields.includes(issue.path as LeadField)) { + form.setError(issue.path as LeadField, { type: 'server', message: issue.code }); + } + } + if (error.status === 429) { + const time = Date.now(); + setNow(time); + setRetryAt(time + (error.retryAfter || 60) * 1000); + } + }, + }); + useEffect(() => { + if (mutation.isSuccess) successRef.current?.focus(); + if (mutation.isError && mutation.error instanceof ApiError) { + const field = fields.find( + (name) => + mutation.error instanceof ApiError && + mutation.error.issues.some((issue) => issue.path === name), + ); + if (field) form.setFocus(field); + } + }, [mutation.isSuccess, mutation.isError, mutation.error, form]); + + function accessibility(name: LeadField) { + const invalid = !!form.formState.errors[name]; + return { + id: `lead-${name}`, + required: true, + 'aria-invalid': invalid, + 'aria-describedby': + [ + invalid ? `lead-${name}-error` : '', + name === 'estimatedMonthlyVolumeUsd' ? 'lead-volume-hint' : '', + ] + .filter(Boolean) + .join(' ') || undefined, + }; + } + function errorText(name: LeadField) { + const error = form.formState.errors[name]; + return error + ? t(error.message ?? 'validation.invalid', { defaultValue: t('validation.invalid') }) + : undefined; + } + const error = mutation.error; + const feedback = + error instanceof ApiError && error.status === 429 + ? t(remaining ? 'landing.rateLimit' : 'landing.rateReady', { seconds: remaining }) + : error instanceof ApiError && error.code === 'VALIDATION_ERROR' + ? t('landing.validationError') + : error instanceof ApiError && error.code === 'IDEMPOTENCY_CONFLICT' + ? t('landing.conflict') + : error instanceof ApiError && error.status > 0 + ? t('landing.serverError') + : t('landing.networkError'); + + if (mutation.isSuccess) + return ( +
+ + +

{t('landing.successTitle')}

+

{t('landing.successText')}

+
+ ); + return ( +
{ + if (busy.current || remaining) return; + busy.current = true; + setRetryAt(0); + try { + await mutation.mutateAsync(input); + } catch { + /* Inline feedback retains the form. */ + } finally { + busy.current = false; + } + })} + > +
+

{t('landing.formHeading')}

+

{t('landing.required')}

+
+
+ {inputs.map((field) => ( + + + + ))} + + + + {countries.map(({ code, name }) => ( + + ))} + + + + + + {industries.map((industry) => ( + + ))} + + +
+ + + +

{t('landing.volumeHint')}

+
+ +
+ {mutation.isError && ( +
+ {error instanceof ApiError && error.status === 429 ? ( + <> +

{t('landing.rateNotice')}

+

+ {feedback} +

+ + ) : ( +

{feedback}

+ )} +
+ )} + +

+ {t(mutation.isPending ? 'landing.pending' : 'landing.formNote')} +

+
+ ); +} diff --git a/apps/web/src/components/merchant-workflow.tsx b/apps/web/src/components/merchant-workflow.tsx index e180d2b..35ec5d3 100644 --- a/apps/web/src/components/merchant-workflow.tsx +++ b/apps/web/src/components/merchant-workflow.tsx @@ -1,9 +1,7 @@ -import { useId, useState } from 'react'; -import { useForm } from 'react-hook-form'; -import { useMutation, useQuery } from '@tanstack/react-query'; +import { useState } from 'react'; +import { useQuery } from '@tanstack/react-query'; import { Link } from 'react-router'; import { useTranslation } from 'react-i18next'; -import { z } from 'zod'; import { activityInputSchema, assignmentSchema, @@ -11,7 +9,6 @@ import { industries, managerListSchema, merchantEditSchema, - mutationResultSchema, reviewDecisionSchema, sources, statuses, @@ -19,175 +16,12 @@ import { 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 { api } from '../lib/api'; +import { Editor, useAction, type Field } from './workflow-form'; +import { StageActions } from './sales-workspace'; 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; - schema: z.ZodType; - build: (values: Record) => 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>({ defaultValues: initial }); - const [errors, setErrors] = useState>({}); - return ( - { - if (!open && !pending) close(); - }} - > - - {title} - {description ?? t('merchants.details')} -
{ - const result = schema.safeParse(build(values)); - if (!result.success) { - const messages: Record = {}; - for (const issue of result.error.issues) - messages[String(issue.path[0] ?? 'form')] = t('validation.invalid'); - setErrors(messages); - return; - } - setErrors({}); - submit(result.data); - })} - > -
- {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 ( - - {field.options ? ( - - {field.options.map((option) => ( - - ))} - - ) : field.type === 'textarea' ? ( -