Built merchant management, activity history, and the pipeline

This commit is contained in:
Oleksandr Prokhorenko
2026-09-24 20:50:15 +03:00
parent 5de240fda3
commit 382f6e8841
43 changed files with 4679 additions and 812 deletions
+69 -15
View File
@@ -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": "[email protected]",
"website": "https://example.test",
"country": "GB",
"industry": "SOFTWARE",
"estimatedMonthlyVolumeUsd": "25000.50",
"companyFax": ""
}
```
The shared schema trims names, lowercases email, validates country/industry codes and HTTP(S) websites, and accepts scheme-less websites by adding HTTPS. USD amounts remain decimal strings, from zero to `999999999999.99`, with at most two fractional digits; decimal commas are accepted without thousands separators. Email providers are not blocked or externally verified. Unexpected business fields are rejected.
A successful request returns **202 `{ "ok": true }`** and atomically creates an unassigned `NEW_LEAD`, source `LANDING_PAGE`, 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 `[email protected]` and `[email protected]`, and the original Maria demo identity becomes Sam Taylor. Existing password hashes remain unchanged; the documented password applies to newly created and unchanged demo accounts.
## Daily sales workspace
Head can add merchants from the directory and optionally assign a manager. Managers create merchants assigned to themselves. Company name, contact name and email are required; website, country, industry and volume can be supplied later. Compliance has no creation access. New leads begin at `NEW_LEAD` with 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.
+6 -9
View File
@@ -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,
};
}
+9 -1
View File
@@ -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 {}
+126 -57
View File
@@ -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);
+139
View File
@@ -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<string, unknown> {
return value && typeof value === 'object' && !Array.isArray(value)
? (value as Record<string, unknown>)
: {};
}
export async function merchantHistory(
m: Sources,
db: Prisma.TransactionClient,
): Promise<HistoryEntry[]> {
const ownerIds = new Set<string>();
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),
);
}
+169
View File
@@ -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<string> };
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<string, Bucket>();
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<string, { hash: string; promise: Promise<typeof accepted> }>();
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);
}
}
+6 -2
View File
@@ -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()
+122
View File
@@ -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;
}
+106 -60
View File
@@ -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(
+21 -1
View File
@@ -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);
+282
View File
@@ -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);
});
+473
View File
@@ -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: '[email protected]',
...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()`;
}
});
+17
View File
@@ -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('[email protected]', String(i)), 0);
assert.equal(limiter.reserveEmail('[email protected]', '0'), 0);
assert.equal(limiter.reserveEmail('[email protected]', 'new'), 900);
limiter.releaseEmail('[email protected]', '0');
assert.equal(limiter.reserveEmail('[email protected]', '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('[email protected]', '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' }), {
+285
View File
@@ -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: '[email protected]', 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<string, string>());
const busy = useRef(false);
const successRef = useRef<HTMLDivElement>(null);
const [retryAt, setRetryAt] = useState(0);
const [now, setNow] = useState(Date.now);
const form = useForm<PublicLeadInput, unknown, PublicLead>({
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 (
<div ref={successRef} tabIndex={-1} className="lead-success" role="status">
<span className="lead-success-icon">
<Check size={28} aria-hidden="true" />
</span>
<h3>{t('landing.successTitle')}</h3>
<p>{t('landing.successText')}</p>
</div>
);
return (
<form
noValidate
aria-label={t('landing.formHeading')}
aria-busy={mutation.isPending}
onSubmit={form.handleSubmit(async (input) => {
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;
}
})}
>
<div className="lead-form-heading">
<h3>{t('landing.formHeading')}</h3>
<p>{t('landing.required')}</p>
</div>
<fieldset disabled={mutation.isPending} className="lead-fields">
{inputs.map((field) => (
<FormField
key={field.name}
id={`lead-${field.name}`}
label={t(`landing.${field.name}`)}
error={errorText(field.name)}
>
<Input
{...form.register(field.name)}
{...accessibility(field.name)}
type={field.type}
autoComplete={field.autoComplete}
placeholder={field.placeholder}
maxLength={
field.name === 'website' ? 2048 : field.name === 'contactEmail' ? 254 : 200
}
autoCapitalize={
field.name === 'contactEmail' || field.name === 'website' ? 'none' : 'words'
}
inputMode={field.name === 'website' ? 'url' : undefined}
/>
</FormField>
))}
<FormField id="lead-country" label={t('landing.country')} error={errorText('country')}>
<NativeSelect
{...form.register('country')}
{...accessibility('country')}
autoComplete="country"
className="w-full"
>
<option value="" disabled>
{t('landing.countryPlaceholder')}
</option>
{countries.map(({ code, name }) => (
<option key={code} value={code}>
{name}
</option>
))}
</NativeSelect>
</FormField>
<FormField id="lead-industry" label={t('landing.industry')} error={errorText('industry')}>
<NativeSelect
{...form.register('industry')}
{...accessibility('industry')}
className="w-full"
>
<option value="" disabled>
{t('landing.industryPlaceholder')}
</option>
{industries.map((industry) => (
<option key={industry} value={industry}>
{t(`industry.${industry}`)}
</option>
))}
</NativeSelect>
</FormField>
<div className="lead-volume">
<FormField
id="lead-estimatedMonthlyVolumeUsd"
label={t('landing.estimatedMonthlyVolumeUsd')}
error={errorText('estimatedMonthlyVolumeUsd')}
>
<Input
{...form.register('estimatedMonthlyVolumeUsd')}
{...accessibility('estimatedMonthlyVolumeUsd')}
inputMode="decimal"
placeholder="25000"
maxLength={15}
/>
</FormField>
<p id="lead-volume-hint">{t('landing.volumeHint')}</p>
</div>
<div className="lead-honeypot" aria-hidden="true">
<input type="text" {...form.register('companyFax')} tabIndex={-1} autoComplete="off" />
</div>
</fieldset>
{mutation.isError && (
<div className="lead-feedback">
{error instanceof ApiError && error.status === 429 ? (
<>
<p role="alert">{t('landing.rateNotice')}</p>
<p role="status" aria-live={remaining ? 'off' : 'polite'}>
{feedback}
</p>
</>
) : (
<p role="alert">{feedback}</p>
)}
</div>
)}
<Button
className="landing-cta lead-submit"
type="submit"
disabled={mutation.isPending || remaining > 0}
>
{mutation.isPending ? <LoaderCircle className="animate-spin" aria-hidden="true" /> : null}
{t(mutation.isPending ? 'landing.pending' : 'landing.submit')}
{!mutation.isPending && <ArrowUpRight aria-hidden="true" />}
</Button>
<p className="lead-form-note" role={mutation.isPending ? 'status' : undefined}>
{t(mutation.isPending ? 'landing.pending' : 'landing.formNote')}
</p>
</form>
);
}
+123 -234
View File
@@ -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<string, string>;
schema: z.ZodType;
build: (values: Record<string, string>) => 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<Record<string, string>>({ defaultValues: initial });
const [errors, setErrors] = useState<Record<string, string>>({});
return (
<Sheet
open
onOpenChange={(open) => {
if (!open && !pending) close();
}}
>
<SheetContent
closeLabel={t('common.close')}
className="w-full! overflow-y-auto p-5 sm:max-w-xl! sm:p-8"
>
<SheetTitle className="pr-10 text-xl">{title}</SheetTitle>
<SheetDescription>{description ?? t('merchants.details')}</SheetDescription>
<form
noValidate
className="space-y-5"
onSubmit={form.handleSubmit((values) => {
const result = schema.safeParse(build(values));
if (!result.success) {
const messages: Record<string, string> = {};
for (const issue of result.error.issues)
messages[String(issue.path[0] ?? 'form')] = t('validation.invalid');
setErrors(messages);
return;
}
setErrors({});
submit(result.data);
})}
>
<fieldset disabled={pending} className="space-y-5">
{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 (
<FormField
key={field.name}
id={fieldId}
label={field.label ?? t(`workflow.${field.name}`)}
error={errors[field.name]}
>
{field.options ? (
<NativeSelect {...props}>
{field.options.map((option) => (
<option key={option.value} value={option.value}>
{option.label}
</option>
))}
</NativeSelect>
) : field.type === 'textarea' ? (
<textarea
{...props}
rows={4}
className="min-h-28 w-full resize-y rounded-lg border bg-background px-3 py-2 text-sm"
/>
) : (
<Input {...props} type={field.type ?? 'text'} />
)}
</FormField>
);
})}
{Object.keys(errors).some((key) => !fields.some((field) => field.name === key)) && (
<p role="alert" className="text-sm text-destructive">
{t('errors.VALIDATION_ERROR')}
</p>
)}
<div className="flex flex-wrap gap-3 border-t pt-5">
<Button type="submit">{t(pending ? 'workflow.saving' : 'workflow.save')}</Button>
<Button type="button" variant="outline" onClick={close}>
{t('workflow.cancel')}
</Button>
</div>
</fieldset>
</form>
</SheetContent>
</Sheet>
);
}
function useAction(merchant: MerchantDetail, close?: () => void) {
const { t } = useTranslation();
const mutation = useMutation({
mutationFn: ({
path,
body,
method = 'PATCH',
}: {
path: string;
body: unknown;
method?: string;
}) =>
api(`/merchants/${merchant.id}${path}`, mutationResultSchema, {
method,
body: JSON.stringify(body),
}),
onSuccess: async () => {
close?.();
await queryClient.invalidateQueries({
predicate: (query) => query.queryKey[0] !== 'session',
});
},
onError: async () => {
close?.();
await queryClient.invalidateQueries({ queryKey: ['merchant', merchant.id] });
},
});
return {
...mutation,
feedback: mutation.isError ? (
<p role="alert" className="rounded-lg bg-rose-50 p-3 text-sm text-destructive">
{t(`errors.${mutation.error instanceof ApiError ? mutation.error.code : 'INTERNAL_ERROR'}`)}
</p>
) : mutation.isSuccess ? (
<p role="status" className="text-xs text-muted-foreground">
{t('workflow.saved')}
</p>
) : null,
};
}
const identityFields = [
'name',
'legalName',
@@ -220,7 +54,10 @@ export function MerchantControls({ merchant: m }: { merchant: MerchantDetail })
type: name === 'contactEmail' ? 'email' : name === 'website' ? 'url' : 'text',
options:
name === 'industry'
? industries.map((value) => ({ value, label: t(`industry.${value}`) }))
? [
{ value: '', label: '—' },
...industries.map((value) => ({ value, label: t(`industry.${value}`) })),
]
: name === 'source'
? [
{ value: '', label: '—' },
@@ -257,21 +94,8 @@ export function MerchantControls({ merchant: m }: { merchant: MerchantDetail })
{t('workflow.assign')}
</Button>
)}
{m.capabilities.nextStage && (
<Button
disabled={action.isPending}
onClick={() =>
action.mutate({
path: '/transitions',
method: 'POST',
body: { version: m.version, toStatus: m.capabilities.nextStage },
})
}
>
{t('workflow.advance', { stage: t(`statuses.${m.capabilities.nextStage}`) })}
</Button>
)}
</div>
<StageActions merchant={m} />
{managers.isError && (
<p role="alert" className="text-sm text-destructive">
{t('errors.NETWORK')}{' '}
@@ -299,8 +123,17 @@ export function MerchantControls({ merchant: m }: { merchant: MerchantDetail })
)
.map(([key, value]) => [
key,
['registrationNumber', 'address', 'contactPhone', 'contactTitle'].includes(key) &&
!value
[
'registrationNumber',
'address',
'contactPhone',
'contactTitle',
'website',
'country',
'industry',
'estimatedMonthlyVolumeUsd',
'source',
].includes(key) && !value
? null
: value,
]),
@@ -309,6 +142,7 @@ export function MerchantControls({ merchant: m }: { merchant: MerchantDetail })
submit={(body) => action.mutate({ path: '', body })}
close={() => setMode(null)}
pending={action.isPending}
feedback={action.feedback}
/>
)}
{mode === 'assign' && (
@@ -327,6 +161,7 @@ export function MerchantControls({ merchant: m }: { merchant: MerchantDetail })
submit={(body) => action.mutate({ path: '/assignment', body })}
close={() => setMode(null)}
pending={action.isPending}
feedback={action.feedback}
/>
)}
</div>
@@ -394,6 +229,7 @@ export function ChecklistControl({
submit={(body) => action.mutate({ path: `/checklist/${item.id}`, body })}
close={() => setOpen(false)}
pending={action.isPending}
feedback={action.feedback}
/>
)}
</div>
@@ -490,21 +326,24 @@ export function ReviewHistory({ merchant: m }: { merchant: MerchantDetail }) {
}
close={() => setOpen(false)}
pending={action.isPending}
feedback={action.feedback}
/>
)}
</section>
);
}
function useActivityText() {
export function useActivityText() {
const { t } = useTranslation();
return (activity: MerchantDetail['activities'][number]) => {
return (activity: Pick<MerchantDetail['activities'][number], 'kind' | 'text'>) => {
if (activity.kind !== 'AUDIT') return activity.text;
const labels: Record<string, string> = {
'Merchant details updated': 'detailsUpdated',
'Merchant created': 'staffCreated',
'Manager assignment updated': 'assignmentUpdated',
'Activity edited': 'activityEdited',
'Task updated': 'taskUpdated',
'Task created': 'taskCreated',
'Lead received from landing page': 'leadCreated',
};
if (labels[activity.text]) return t(`workflow.${labels[activity.text]}`);
const stages = activity.text.split(' → ');
@@ -526,11 +365,12 @@ export function InteractionHistory({ merchant: m }: { merchant: MerchantDetail }
const action = useAction(m, () => setEdit(null));
const existing = m.activities.find((activity) => activity.id === edit);
const describe = useActivityText();
const audit = m.activities.filter((activity) => activity.kind === 'AUDIT');
return (
<section className="surface">
<SectionHeader
title={t('workflow.activities')}
title={t('workspace.history')}
description={t('workspace.historyHint')}
action={
<Button
variant="outline"
@@ -545,48 +385,95 @@ export function InteractionHistory({ merchant: m }: { merchant: MerchantDetail }
/>
<div className="space-y-4 p-5 sm:p-6">
{action.feedback}
{m.activities
.filter((activity) => activity.kind !== 'AUDIT')
.map((activity) => (
<article key={activity.id} className="rounded-lg bg-background p-4">
<p className="mb-2 text-xs text-muted-foreground">
{t(`workflow.${activity.kind}`)} · {activity.actor.name} ·{' '}
{f.date(activity.occurredAt)}
</p>
<p className="whitespace-pre-wrap break-words text-sm leading-relaxed">
{activity.text}
</p>
{m.capabilities.activityKinds.some((kind) => kind === activity.kind) && (
<Button
className="mt-2"
variant="ghost"
onClick={() => {
action.reset();
setEdit(activity.id);
}}
>
{t('workflow.editActivity')}
</Button>
)}
</article>
))}
{!!audit.length && (
<details className="border-t pt-2">
<summary className="min-h-11 cursor-pointer py-3 text-sm font-medium">
{t('workflow.auditHistory', { count: audit.length })}
</summary>
<ol className="divide-y">
{audit.map((activity) => (
<li key={activity.id} className="py-3">
<p className="text-sm">{describe(activity)}</p>
<p className="mt-1 text-xs text-muted-foreground">
{activity.actor.name} · {f.date(activity.occurredAt)}
</p>
</li>
))}
</ol>
</details>
{!m.history.length && (
<p className="text-sm text-muted-foreground">{t('workspace.noHistory')}</p>
)}
<ol className="divide-y">
{m.history.map((entry) => {
const editable =
entry.kind === 'INTERACTION' &&
entry.activityId &&
m.capabilities.activityKinds.some((kind) => kind === entry.activityKind);
return (
<li key={entry.id} className="py-4 first:pt-0">
<div className="mb-2 flex flex-wrap items-center gap-x-2 gap-y-1 text-xs text-muted-foreground">
<span>
{entry.kind === 'INTERACTION'
? t(`workflow.${entry.activityKind}`)
: entry.kind === 'REVIEW'
? t('workflow.reviews')
: t('workflow.AUDIT')}
</span>
<span aria-hidden="true">·</span>
<span>{entry.actor?.name ?? t('workflow.system')}</span>
<span aria-hidden="true">·</span>
<time dateTime={entry.occurredAt}>{f.dateTime(entry.occurredAt)}</time>
</div>
{entry.kind === 'INTERACTION' && (
<>
<p className="whitespace-pre-wrap break-words text-sm leading-relaxed">
{entry.text}
</p>
{entry.updatedAt !== entry.occurredAt && (
<p className="mt-1 text-xs text-muted-foreground">
{t('workspace.edited', { date: f.dateTime(entry.updatedAt) })}
</p>
)}
{editable && (
<Button
className="mt-2"
variant="ghost"
onClick={() => {
action.reset();
setEdit(entry.activityId);
}}
>
{t('workflow.editActivity')}
</Button>
)}
</>
)}
{entry.kind === 'STAGE' && (
<>
<p className="text-sm font-medium">
{entry.fromStatus
? t('workspace.stageChange', {
from: t(`statuses.${entry.fromStatus}`),
to: t(`statuses.${entry.toStatus}`),
})
: t('workspace.created', { stage: t(`statuses.${entry.toStatus}`) })}
</p>
{entry.reason && (
<p className="mt-2 whitespace-pre-wrap break-words text-sm">{entry.reason}</p>
)}
</>
)}
{entry.kind === 'OWNERSHIP' && (
<p className="text-sm">
{t('workspace.ownership', {
previous: entry.previousOwner?.name ?? t('workflow.unassigned'),
owner: entry.owner?.name ?? t('workflow.unassigned'),
})}
</p>
)}
{entry.kind === 'REVIEW' && (
<>
<p className="text-sm font-medium">
{t('workflow.cycle', { cycle: entry.cycle })} ·{' '}
{t(`workflow.${entry.decision}`)}
</p>
{entry.reason && (
<p className="mt-2 whitespace-pre-wrap break-words text-sm">{entry.reason}</p>
)}
</>
)}
{entry.kind === 'AUDIT' && (
<p className="text-sm">{describe({ kind: 'AUDIT', text: entry.text })}</p>
)}
</li>
);
})}
</ol>
</div>
{edit && (
<Editor
@@ -616,6 +503,7 @@ export function InteractionHistory({ merchant: m }: { merchant: MerchantDetail }
}
close={() => setEdit(null)}
pending={action.isPending}
feedback={action.feedback}
/>
)}
</section>
@@ -720,6 +608,7 @@ export function MerchantTasks({ merchant: m }: { merchant: MerchantDetail }) {
}
close={() => setEdit(null)}
pending={action.isPending}
feedback={action.feedback}
/>
)}
</section>
@@ -740,7 +629,7 @@ export function RecentInteractions({ activities }: { activities: MerchantDetail[
{activity.merchant.name}
</Link>
<p className="mt-1 text-xs text-muted-foreground">
{t(`workflow.${activity.kind}`)} · {activity.actor.name} ·{' '}
{t(`workflow.${activity.kind}`)} · {activity.actor?.name ?? t('workflow.system')} ·{' '}
{f.relative(activity.occurredAt)}
</p>
<p className="mt-2 whitespace-pre-wrap break-words text-sm leading-relaxed">
+244
View File
@@ -0,0 +1,244 @@
import { useEffect, useState } from 'react';
import { useMutation, useQuery } from '@tanstack/react-query';
import { useNavigate } from 'react-router';
import { useTranslation } from 'react-i18next';
import { Plus, ArrowRight } from 'lucide-react';
import {
countryCodes,
industries,
sources,
managerListSchema,
merchantCreateSchema,
merchantCreatedSchema,
transitionSchema,
type Capabilities,
type Merchant,
type User,
} from '@merchantflow/contracts';
import { api, ApiError, queryClient } from '../lib/api';
import { useFormat } from '../lib/format';
import { Button, LinkButton } from './shared';
import { Editor, useAction, type Field } from './workflow-form';
export function StageAge({ since }: { since: string }) {
const { t, i18n } = useTranslation();
const [now, setNow] = useState(() => Date.now());
useEffect(() => {
const timer = setInterval(() => setNow(Date.now()), 60000);
return () => clearInterval(timer);
}, []);
const hours = Math.max(0, Math.floor((now - new Date(since).getTime()) / 3600000));
const duration =
hours < 1
? t('workspace.lessThanHour')
: new Intl.NumberFormat(i18n.language, {
style: 'unit',
unit: hours >= 24 ? 'day' : 'hour',
unitDisplay: 'short',
}).format(hours >= 24 ? Math.floor(hours / 24) : hours);
return (
<span title={new Date(since).toLocaleString(i18n.language)}>
{t('workspace.timeInStage', { duration })}
</span>
);
}
export function CreateMerchant({ user }: { user: User }) {
const { t } = useTranslation();
const f = useFormat();
const navigate = useNavigate();
const [open, setOpen] = useState(false);
const managers = useQuery({
queryKey: ['assignable-managers'],
queryFn: ({ signal }) => api('/users/assignable-managers', managerListSchema, { signal }),
enabled: open && user.role === 'HEAD_OF_SALES',
});
const action = useMutation({
mutationFn: (body: unknown) =>
api('/merchants', merchantCreatedSchema, { method: 'POST', body: JSON.stringify(body) }),
onSuccess: async (merchant) => {
await queryClient.invalidateQueries({
predicate: (query) => query.queryKey[0] !== 'session',
});
setOpen(false);
navigate(`/app/merchants/${merchant.id}`);
},
});
const optional = [{ value: '', label: t('workspace.notProvided') }];
const fields: Field[] = [
{ name: 'name' },
{ name: 'contactName' },
{ name: 'contactEmail', type: 'email' },
{ name: 'website' },
{
name: 'country',
options: [
...optional,
...countryCodes
.map((value) => ({ value, label: f.country(value) ?? value }))
.sort((a, b) => a.label.localeCompare(b.label)),
],
},
{
name: 'industry',
options: [
...optional,
...industries.map((value) => ({ value, label: t(`industry.${value}`) })),
],
},
{ name: 'estimatedMonthlyVolumeUsd' },
{
name: 'source',
options: [...optional, ...sources.map((value) => ({ value, label: t(`workflow.${value}`) }))],
},
...(user.role === 'HEAD_OF_SALES'
? [
{
name: 'ownerId',
options: [
{ value: '', label: t('workflow.unassigned') },
...(managers.data ?? []).map((manager) => ({
value: manager.id,
label: manager.name,
})),
],
},
]
: []),
];
return (
<>
<Button
onClick={() => {
action.reset();
setOpen(true);
}}
>
<Plus className="size-4" />
{t('workspace.create')}
</Button>
{open && (
<Editor
title={t('workspace.create')}
description={t('workspace.createHint')}
fields={fields}
initial={Object.fromEntries(fields.map((field) => [field.name, '']))}
schema={merchantCreateSchema}
build={(values) =>
Object.fromEntries(Object.entries(values).map(([key, value]) => [key, value || null]))
}
submit={(body) => action.mutate(body)}
close={() => setOpen(false)}
pending={action.isPending}
feedback={
<>
{managers.isError && (
<p role="alert" className="text-sm text-destructive">
{t('errors.NETWORK')}{' '}
<Button variant="ghost" onClick={() => void managers.refetch()}>
{t('common.retry')}
</Button>
</p>
)}
{action.isError && (
<p role="alert" className="text-sm text-destructive">
{t(
`errors.${action.error instanceof ApiError ? action.error.code : 'INTERNAL_ERROR'}`,
)}
</p>
)}
</>
}
/>
)}
</>
);
}
type ActionMerchant = Pick<Merchant, 'id' | 'version' | 'status'> & { capabilities: Capabilities };
export function StageActions({
merchant: m,
compact = false,
}: {
merchant: ActionMerchant;
compact?: boolean;
}) {
const { t } = useTranslation();
const [reject, setReject] = useState(false);
const action = useAction(m, () => setReject(false));
const business = ['KYB', 'INTEGRATION', 'TESTING'].includes(m.status);
return (
<div className="space-y-3">
{!m.capabilities.actions.length && (
<p className="text-xs text-muted-foreground">{t('workspace.terminal')}</p>
)}
<div className={compact ? 'space-y-3' : 'flex flex-wrap items-start gap-3'}>
{m.capabilities.actions.map((item) => (
<div key={item.kind} className={compact ? 'w-full' : 'max-w-lg'}>
{item.kind === 'REVIEW' && item.enabled ? (
<LinkButton to={`/app/merchants/${m.id}?tab=onboarding`} variant="outline">
{t('workspace.openOnboarding')}
<ArrowRight className="size-4" />
</LinkButton>
) : (
<Button
className={compact ? 'w-full text-xs' : undefined}
variant={item.kind === 'REJECT' ? 'outline' : 'default'}
disabled={!item.enabled || action.isPending}
onClick={() => {
action.reset();
if (item.kind === 'REJECT') setReject(true);
else
action.mutate({
path: '/transitions',
method: 'POST',
body: { version: m.version, toStatus: item.toStatus },
});
}}
>
{item.kind === 'REJECT'
? t('workspace.reject')
: item.kind === 'REVIEW'
? t('workflow.decide')
: t('workflow.advance', { stage: t(`statuses.${item.toStatus}`) })}
</Button>
)}
{!!item.blockingReasons.length && (
<ul className="mt-2 space-y-1 text-xs leading-relaxed text-muted-foreground">
{item.blockingReasons.map((reason) => (
<li key={reason.code}>
{t(`workspace.blockers.${reason.code}`)}
{reason.fields?.length
? ` ${reason.fields.map((field) => t(`workflow.${field}`)).join(', ')}.`
: ''}
</li>
))}
</ul>
)}
</div>
))}
</div>
{!reject && action.feedback}
{reject && (
<Editor
title={t('workspace.reject')}
description={t(business ? 'workspace.businessReasonHint' : 'workspace.rejectHint')}
fields={[
{
name: 'reason',
label: t(business ? 'workspace.businessReason' : 'workspace.rejectionReason'),
type: 'textarea',
},
]}
initial={{ reason: '' }}
schema={transitionSchema}
build={(values) => ({ version: m.version, toStatus: 'REJECTED', reason: values.reason })}
submit={(body) => action.mutate({ path: '/transitions', method: 'POST', body })}
close={() => setReject(false)}
pending={action.isPending}
feedback={action.feedback}
/>
)}
</div>
);
}
+7 -4
View File
@@ -215,17 +215,20 @@ export function QueryBoundary<T>({
);
return <>{children(query.data)}</>;
}
export function MerchantCard({ merchant }: { merchant: Merchant }) {
export function MerchantCard({ merchant, className }: { merchant: Merchant; className?: string }) {
const { t } = useTranslation();
const f = useFormat();
return (
<Link to={`/app/merchants/${merchant.id}`} className="surface hover-surface block p-4">
<Link
to={`/app/merchants/${merchant.id}`}
className={cn('surface hover-surface block p-4', className)}
>
<div className="flex items-center gap-3">
<Avatar name={merchant.name} small />
<div className="min-w-0">
<h3 className="truncate text-sm font-semibold">{merchant.name}</h3>
<p className="mt-0.5 text-xs text-muted-foreground">
{t(`industry.${merchant.industry}`)}
{merchant.industry ? t(`industry.${merchant.industry}`) : '—'}
</p>
</div>
<MoveUpRight
@@ -335,7 +338,7 @@ export function ActivityFeed({
{t(event.fromStatus ? 'dashboard.moved' : 'dashboard.added')}{' '}
<span className="font-medium text-foreground">{t(`statuses.${event.toStatus}`)}</span>
<span className="mx-1.5">·</span>
{event.actor.name}
{event.actor?.name ?? t('workflow.system')}
</p>
{event.note && (
<p className="mt-2 rounded-lg bg-muted p-3 text-xs leading-relaxed">{event.note}</p>
+182
View File
@@ -0,0 +1,182 @@
import { useId, useState, type ReactNode } from 'react';
import { useForm } from 'react-hook-form';
import { useMutation } from '@tanstack/react-query';
import { useTranslation } from 'react-i18next';
import { z } from 'zod';
import { mutationResultSchema, type MerchantDetail } 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 { Button } from './shared';
export 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<string, string>;
schema: z.ZodType;
build: (values: Record<string, string>) => unknown;
submit: (body: unknown) => void;
close: () => void;
pending: boolean;
feedback?: ReactNode;
};
export function Editor({
title,
description,
fields,
initial,
schema,
build,
submit,
close,
pending,
feedback,
}: EditorProps) {
const { t } = useTranslation();
const id = useId();
const form = useForm<Record<string, string>>({ defaultValues: initial });
const [errors, setErrors] = useState<Record<string, string>>({});
return (
<Sheet
open
onOpenChange={(open) => {
if (!open && !pending) close();
}}
>
<SheetContent
closeLabel={t('common.close')}
className="w-full! overflow-y-auto p-5 sm:max-w-xl! sm:p-8"
>
<SheetTitle className="pr-10 text-xl">{title}</SheetTitle>
<SheetDescription>{description ?? t('merchants.details')}</SheetDescription>
<form
noValidate
className="space-y-5"
onSubmit={form.handleSubmit((values) => {
const result = schema.safeParse(build(values));
if (!result.success) {
const messages: Record<string, string> = {};
for (const issue of result.error.issues)
messages[String(issue.path[0] ?? 'form')] = t(
issue.message.startsWith('validation.') ? issue.message : 'validation.invalid',
);
setErrors(messages);
const first = fields.find((field) => messages[field.name]);
if (first) form.setFocus(first.name);
return;
}
setErrors({});
submit(result.data);
})}
>
{feedback}
<fieldset disabled={pending} className="space-y-5">
{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 (
<FormField
key={field.name}
id={fieldId}
label={field.label ?? t(`workflow.${field.name}`)}
error={errors[field.name]}
>
{field.options ? (
<NativeSelect {...props}>
{field.options.map((option) => (
<option key={option.value} value={option.value}>
{option.label}
</option>
))}
</NativeSelect>
) : field.type === 'textarea' ? (
<textarea
{...props}
rows={4}
className="min-h-28 w-full resize-y rounded-lg border bg-background px-3 py-2 text-sm"
/>
) : (
<Input {...props} type={field.type ?? 'text'} />
)}
</FormField>
);
})}
{Object.keys(errors).some((key) => !fields.some((field) => field.name === key)) && (
<p role="alert" className="text-sm text-destructive">
{t('errors.VALIDATION_ERROR')}
</p>
)}
<div className="flex flex-wrap gap-3 border-t pt-5">
<Button type="submit">{t(pending ? 'workflow.saving' : 'workflow.save')}</Button>
<Button type="button" variant="outline" onClick={close}>
{t('workflow.cancel')}
</Button>
</div>
</fieldset>
</form>
</SheetContent>
</Sheet>
);
}
export function useAction(merchant: Pick<MerchantDetail, 'id'>, close?: () => void) {
const { t } = useTranslation();
const mutation = useMutation({
mutationFn: ({
path,
body,
method = 'PATCH',
}: {
path: string;
body: unknown;
method?: string;
}) =>
api(`/merchants/${merchant.id}${path}`, mutationResultSchema, {
method,
body: JSON.stringify(body),
}),
onSuccess: async () => {
close?.();
await queryClient.invalidateQueries({
predicate: (query) => query.queryKey[0] !== 'session',
});
},
onError: async () => {
await queryClient.invalidateQueries({
predicate: (query) => query.queryKey[0] !== 'session',
});
},
});
return {
...mutation,
feedback: mutation.isError ? (
<p role="alert" className="rounded-lg bg-rose-50 p-3 text-sm text-destructive">
{t(`errors.${mutation.error instanceof ApiError ? mutation.error.code : 'INTERNAL_ERROR'}`)}
</p>
) : mutation.isSuccess ? (
<p role="status" className="text-xs text-muted-foreground">
{t('workflow.saved')}
</p>
) : null,
};
}
+139
View File
@@ -0,0 +1,139 @@
export const landingEn = {
eyebrow: 'CRYPTO PAYMENTS · MERCHANT ONBOARDING',
title: 'Your next payment chapter',
titleAccent: 'starts here.',
description:
'Explore crypto payments for your business. We’ll help you understand the requirements and map a clear path from first conversation to integration.',
cta: 'Let’s talk payments',
signIn: 'Staff login',
explore: 'How it works',
heroNote: 'A conversation first. A clear next step.',
journeyLabel: 'A path built around your business',
journeyStart: 'Your business',
journeyEnd: 'Ready to integrate',
why: 'A clear path. People at every step.',
feature1: 'Start with your business',
feature1Text:
'Tell us how you operate and what you need from crypto payments. We’ll work through the next steps together.',
feature2: 'Know what’s needed',
feature2Text:
'Get a clear view of company verification and the documents required for a compliance review.',
feature3: 'Connect with a plan',
feature3Text:
'After approval, move through integration and testing with an onboarding team coordinating the handoffs.',
processLabel: 'FROM HELLO TO NEXT STEPS',
processTitle: 'Let’s make the path clear.',
step1: 'Tell us about your business',
step1Text: 'Share a few details. We’ll discuss your payment needs and onboarding requirements.',
step2: 'Prepare for verification',
step2Text: 'Gather your company documents for KYB and compliance review.',
step3: 'Integrate and test',
step3Text: 'Following approval, plan your integration and test before going live.',
formLabel: 'START A CONVERSATION',
formTitle: 'Your business.\nYour next move.',
formDescription:
'Tell us a little about your company and what you have in mind for crypto payments.',
formNote: 'We’ll use these details to follow up on your enquiry.',
formHeading: 'Request a consultation',
required: 'All fields are required.',
name: 'Company name',
contactName: 'Contact name',
contactEmail: 'Work email',
website: 'Company website',
country: 'Company country',
industry: 'Industry',
estimatedMonthlyVolumeUsd: 'Estimated monthly volume (USD)',
countryPlaceholder: 'Select a country',
industryPlaceholder: 'Select an industry',
volumeHint: 'An estimate is fine. Enter 0 if you’re just getting started.',
submit: 'Request a consultation',
pending: 'Sending your request…',
validationError: 'Please check the highlighted fields.',
networkError: 'We couldn’t confirm your request. Your details are still here. Try again safely.',
serverError: 'We couldn’t complete your request. Please try again. Your details are still here.',
rateLimit:
'Please wait {{seconds}} seconds before trying again. Your details are saved on this page.',
rateReady: 'You can try again now. Your details are still here.',
rateNotice: 'Too many requests. Please wait before trying again.',
conflict:
'This request key was already used for different details. Reload the page to start a new request.',
successTitle: 'Thanks. Let’s take the next step.',
successText:
'Your request has been received. Our team will follow up using the email you provided.',
footer: 'A fictional crypto-payment provider. Built for a clearer start.',
metaTitle: 'MerchantFlow — Your path to crypto payments',
metaDescription:
'Start a conversation about merchant crypto payments. Explore business verification, onboarding, and integration with MerchantFlow.',
visualTitle: 'One shared journey',
visualSub: 'Built around your team',
visualNote: 'Context travels with every merchant.',
};
export const landingRu: Record<keyof typeof landingEn, string> = {
eyebrow: 'КРИПТОПЛАТЕЖИ · ПОДКЛЮЧЕНИЕ БИЗНЕСА',
title: 'Новый этап ваших платежей',
titleAccent: 'начинается здесь.',
description:
'Рассмотрите криптоплатежи для своего бизнеса. Поможем разобраться в требованиях и наметить путь от первого разговора до интеграции.',
cta: 'Обсудим платежи',
signIn: 'Вход для команды',
explore: 'Как это работает',
heroNote: 'Начнём с разговора. Определим следующий шаг.',
journeyLabel: 'Путь с учётом вашего бизнеса',
journeyStart: 'Ваш бизнес',
journeyEnd: 'К интеграции',
why: 'Понятный путь. Поддержка на каждом этапе.',
feature1: 'Начнём с вашего бизнеса',
feature1Text:
'Расскажите, как работает ваша компания и что вам нужно от криптоплатежей. Вместе определим дальнейшие шаги.',
feature2: 'Разберёмся в требованиях',
feature2Text:
'Узнайте, как проходит проверка компании и какие документы потребуются для комплаенс-проверки.',
feature3: 'Спланируем подключение',
feature3Text:
'После одобрения переходите к интеграции и тестированию. Команда подключения поможет согласовать этапы.',
processLabel: 'ОТ ЗНАКОМСТВА К СЛЕДУЮЩИМ ШАГАМ',
processTitle: 'Сделаем путь понятным.',
step1: 'Расскажите о компании',
step1Text: 'Поделитесь основными данными. Обсудим ваши задачи и требования к подключению.',
step2: 'Подготовьтесь к проверке',
step2Text: 'Соберите документы компании для KYB и комплаенс-проверки.',
step3: 'Интеграция и тестирование',
step3Text: 'После одобрения спланируйте интеграцию и проверьте её перед запуском.',
formLabel: 'НАЧНЁМ С РАЗГОВОРА',
formTitle: 'Ваш бизнес.\nВаш следующий шаг.',
formDescription:
'Расскажите немного о компании и о том, как вы планируете использовать криптоплатежи.',
formNote: 'Используем эти данные, чтобы связаться с вами по заявке.',
formHeading: 'Заявка на консультацию',
required: 'Все поля обязательны.',
name: 'Название компании',
contactName: 'Контактное лицо',
contactEmail: 'Рабочая почта',
website: 'Сайт компании',
country: 'Страна компании',
industry: 'Отрасль',
estimatedMonthlyVolumeUsd: 'Ожидаемый объём в месяц (USD)',
countryPlaceholder: 'Выберите страну',
industryPlaceholder: 'Выберите отрасль',
volumeHint: 'Достаточно оценки. Укажите 0, если только начинаете.',
submit: 'Запросить консультацию',
pending: 'Отправляем заявку…',
validationError: 'Проверьте выделенные поля.',
networkError:
'Не удалось подтвердить отправку. Данные остались в форме. Можно безопасно повторить попытку.',
serverError: 'Не удалось отправить заявку. Попробуйте ещё раз. Данные остались в форме.',
rateLimit: 'Повторите попытку через {{seconds}} сек. Данные сохранены на этой странице.',
rateReady: 'Теперь можно попробовать снова. Данные остались в форме.',
rateNotice: 'Слишком много запросов. Подождите перед следующей попыткой.',
conflict:
'Ключ заявки уже использован с другими данными. Обновите страницу, чтобы начать новую заявку.',
successTitle: 'Спасибо. Сделаем следующий шаг.',
successText: 'Ваша заявка получена. Команда свяжется с вами по указанной почте.',
footer: 'Вымышленный криптоплатёжный провайдер. Понятное начало сотрудничества.',
metaTitle: 'MerchantFlow — Ваш путь к криптоплатежам',
metaDescription:
'Обсудите криптоплатежи для бизнеса. Узнайте о проверке компании, подключении и интеграции с MerchantFlow.',
visualTitle: 'Один общий путь',
visualSub: 'Вокруг вашей команды',
visualNote: 'Контекст остаётся с мерчантом на каждом этапе.',
};
+14
View File
@@ -5,6 +5,8 @@ export class ApiError extends Error {
constructor(
public code: string,
public status = 0,
public issues: { path: string; code: string }[] = [],
public retryAfter = 0,
) {
super(code);
}
@@ -48,6 +50,18 @@ export async function api<T>(
throw new ApiError(
typeof body.code === 'string' ? body.code : 'INTERNAL_ERROR',
response.status,
Array.isArray(body.issues)
? body.issues.filter(
(issue: unknown): issue is { path: string; code: string } =>
typeof issue === 'object' &&
issue !== null &&
'path' in issue &&
typeof issue.path === 'string' &&
'code' in issue &&
typeof issue.code === 'string',
)
: [],
Math.max(0, Number(response.headers.get('Retry-After')) || 0),
);
}
const result = schema.safeParse(await response.json());
+29
View File
@@ -0,0 +1,29 @@
import { expect, it } from 'vitest';
import { directoryParams } from './directory-params';
it('canonicalizes invalid/default query values while retaining search typing and all valid filters', () => {
const input = new URLSearchParams(
'page=2&search=Acme+&status=KYB&country=GB&industry=SOFTWARE&ownerId=unassigned&unrelated=1',
);
const normalized = directoryParams(input, 'HEAD_OF_SALES');
expect(normalized.toString()).toBe(
'search=Acme+&status=KYB&country=GB&industry=SOFTWARE&ownerId=unassigned&page=2',
);
expect(directoryParams(normalized, 'HEAD_OF_SALES').toString()).toBe(normalized.toString());
expect(
directoryParams(
new URLSearchParams('page=1.5&status=bad&country=ZZ&industry=bad'),
'HEAD_OF_SALES',
).toString(),
).toBe('');
expect(directoryParams(new URLSearchParams('page=1'), 'HEAD_OF_SALES').toString()).toBe('');
});
it('removes owner controls from manager URLs without dropping the rest of their search', () => {
const result = directoryParams(
new URLSearchParams('search=hello&ownerId=user-manager2&country=GB&page=3'),
'ACCOUNT_MANAGER',
);
expect(result.get('ownerId')).toBeNull();
expect(result.get('country')).toBe('GB');
expect(result.get('page')).toBe('3');
expect(result.get('search')).toBe('hello');
});
+17
View File
@@ -0,0 +1,17 @@
import { merchantQuerySchema, type Role } from '@merchantflow/contracts';
export function directoryParams(input: URLSearchParams, role: Role) {
const result = new URLSearchParams();
const search = input.get('search')?.slice(0, 100);
// Preserve typing whitespace; the server normalizes the search term.
if (search) result.set('search', search);
for (const key of ['status', 'country', 'industry', 'ownerId', 'page'] as const) {
if (key === 'ownerId' && role === 'ACCOUNT_MANAGER') continue;
const raw = input.get(key);
if (!raw) continue;
const value = merchantQuerySchema.shape[key].safeParse(raw);
if (value.success && value.data !== undefined && !(key === 'page' && value.data === 1))
result.set(key, String(value.data));
}
return result;
}
+6 -1
View File
@@ -18,7 +18,12 @@ export function useFormat() {
currency: 'USD',
maximumFractionDigits: 2,
}).format(Number(value)),
country: (code: string) => new Intl.DisplayNames([locale], { type: 'region' }).of(code),
country: (code: string | null) =>
code ? new Intl.DisplayNames([locale], { type: 'region' }).of(code) : '—',
dateTime: (value: string) =>
new Intl.DateTimeFormat(locale, { dateStyle: 'medium', timeStyle: 'short' }).format(
new Date(value),
),
relative: (value: string) => {
const hours = Math.round((new Date(value).getTime() - Date.now()) / 3600000);
return new Intl.RelativeTimeFormat(locale, { numeric: 'auto' }).format(
+26 -40
View File
@@ -1,6 +1,9 @@
import { salesEn, salesRu } from './sales-locales';
import { workflowEn, workflowRu } from './workflow-locales';
import { landingEn, landingRu } from './landing-locales';
export const en = {
workflow: workflowEn,
workspace: salesEn,
common: {
workspace: 'Workspace',
team: 'Merchant workspace',
@@ -71,27 +74,9 @@ export const en = {
SOFTWARE: 'Software',
TRAVEL: 'Travel',
SERVICES: 'Services',
OTHER: 'Other',
},
landing: {
eyebrow: 'MERCHANT ONBOARDING, IN FLOW',
title: 'Great partnerships\nstart with a clear path.',
description:
'From the first conversation to going live. Give sales, compliance, and account teams one calm place to move merchants forward.',
cta: 'Enter your workspace',
signIn: 'Sign in',
why: 'Less chasing. More moving forward.',
whyText: 'The context you need, exactly where you need it.',
feature1: 'See the whole journey',
feature1Text: 'A shared pipeline from new lead to live, with every handoff in view.',
feature2: 'Make reviews clearer',
feature2Text: 'Keep document checklists, notes, and merchant history together.',
feature3: 'Keep the next step close',
feature3Text: 'Stay connected to your merchants with tasks and in-app reminders.',
visualTitle: 'One shared journey',
visualSub: 'Built around your team',
visualNote: 'Context travels with every merchant.',
footer: 'A fictional crypto-payment provider. A thoughtfully connected workspace.',
},
landing: landingEn,
auth: {
eyebrow: 'WELCOME BACK',
title: 'Get back into flow.',
@@ -115,8 +100,17 @@ export const en = {
password: 'Enter your password.',
passwordMax: 'Use 128 characters or fewer.',
invalid: 'Please check this value.',
required: 'Please complete this field.',
nameMax: 'Use 200 characters or fewer.',
website: 'Enter a website such as example.com or https://example.com.',
country: 'Select the country where your company is based.',
industry: 'Select your industry, or choose Other.',
volume:
'Enter a USD amount from 0 to 999999999999.99, with up to two decimal places and no thousands separators.',
submissionKey: 'Reload the page and try again.',
},
errors: {
IDEMPOTENCY_CONFLICT: 'This request key was already used for different details.',
CONFLICT: 'This record changed. Review the latest information and try again.',
WORKFLOW_INVALID:
'This action requires a valid stage, complete documents and approval where applicable.',
@@ -240,6 +234,7 @@ export const en = {
};
export const ru = {
workflow: workflowRu,
workspace: salesRu,
common: {
workspace: 'Рабочее пространство',
team: 'Работа с мерчантами',
@@ -312,27 +307,9 @@ export const ru = {
SOFTWARE: 'Программное обеспечение',
TRAVEL: 'Туризм',
SERVICES: 'Услуги',
OTHER: 'Другое',
},
landing: {
eyebrow: 'ПОДКЛЮЧЕНИЕ МЕРЧАНТОВ БЕЗ СУЕТЫ',
title: 'Хорошие партнёрства\nначинаются с ясного пути.',
description:
'От первого разговора до запуска. Единое пространство, где продажи, комплаенс и аккаунт-менеджеры помогают мерчантам двигаться вперёд.',
cta: 'В рабочее пространство',
signIn: 'Войти',
why: 'Меньше поисков. Больше движения.',
whyText: 'Нужный контекст — в нужном месте.',
feature1: 'Весь путь перед глазами',
feature1Text: 'Общая воронка от нового лида до запуска с понятной передачей между командами.',
feature2: 'Прозрачные проверки',
feature2Text: 'Чек-листы документов, заметки и история мерчанта в одном месте.',
feature3: 'Следующий шаг рядом',
feature3Text: 'Задачи и напоминания внутри приложения помогают не терять связь с мерчантами.',
visualTitle: 'Один общий путь',
visualSub: 'Вокруг вашей команды',
visualNote: 'Контекст остаётся с мерчантом на каждом этапе.',
footer: 'Вымышленный криптоплатёжный провайдер. Продуманное рабочее пространство.',
},
landing: landingRu,
auth: {
eyebrow: 'С ВОЗВРАЩЕНИЕМ',
title: 'Продолжим в одном ритме.',
@@ -356,8 +333,17 @@ export const ru = {
password: 'Введите пароль.',
passwordMax: 'Не более 128 символов.',
invalid: 'Проверьте это значение.',
required: 'Заполните это поле.',
nameMax: 'Не более 200 символов.',
website: 'Введите адрес сайта, например example.com или https://example.com.',
country: 'Выберите страну, в которой находится ваша компания.',
industry: 'Выберите отрасль или вариант «Другое».',
volume:
'Введите сумму в USD от 0 до 999999999999,99: до двух знаков после запятой, без разделителей тысяч.',
submissionKey: 'Обновите страницу и попробуйте снова.',
},
errors: {
IDEMPOTENCY_CONFLICT: 'Ключ заявки уже использован с другими данными.',
CONFLICT: 'Запись изменилась. Проверьте актуальные данные и повторите действие.',
WORKFLOW_INVALID: 'Проверьте этап, готовность документов и наличие одобрения.',
REVIEW_LOCKED: 'Эти данные защищены от изменений во время и после проверки.',
+2 -1
View File
@@ -6,7 +6,8 @@ import '@merchantflow/ui/globals.css';
import './i18n';
import { queryClient } from './lib/api';
import { ProtectedShell } from './components/shell';
import { Landing, Login } from './pages/public';
import { Login } from './pages/public';
import { Landing } from './pages/landing';
import {
Dashboard,
Merchants,
+425 -274
View File
@@ -7,7 +7,7 @@ import {
RecentInteractions,
} from '../components/merchant-workflow';
import { useEffect, useState } from 'react';
import { Link, useOutletContext, useParams, useSearchParams } from 'react-router';
import { Link, useLocation, useOutletContext, useParams, useSearchParams } from 'react-router';
import { keepPreviousData, useQuery } from '@tanstack/react-query';
import { useTranslation } from 'react-i18next';
import {
@@ -26,7 +26,6 @@ import {
Globe2,
Mail,
ExternalLink,
SlidersHorizontal,
LoaderCircle,
} from 'lucide-react';
import {
@@ -34,13 +33,13 @@ import {
merchantListSchema,
merchantDetailSchema,
pipelineSchema,
pipelineBoardSchema,
merchantFiltersSchema,
taskListSchema,
statuses,
successfulStages,
statusSchema,
taskFilters,
canSeeReviewQueue,
type Status,
type User,
type TaskFilter,
type Merchant,
@@ -57,7 +56,9 @@ import {
} from '@merchantflow/ui/components/table';
import { Badge } from '@merchantflow/ui/components/badge';
import { cn } from '@merchantflow/ui/lib/utils';
import { api } from '../lib/api';
import { api, safeReturnTo } from '../lib/api';
import { directoryParams } from '../lib/directory-params';
import { CreateMerchant, StageActions, StageAge } from '../components/sales-workspace';
import { useFormat } from '../lib/format';
import {
PageHeader,
@@ -67,7 +68,6 @@ import {
Button,
StatusBadge,
Avatar,
ActivityFeed,
TaskRow,
MerchantCard,
EmptyState,
@@ -227,6 +227,7 @@ function useDebounced(value: string) {
function MerchantTable({ merchants }: { merchants: Merchant[] }) {
const { t } = useTranslation();
const f = useFormat();
const location = useLocation();
return (
<>
<div className="hidden md:block">
@@ -234,6 +235,7 @@ function MerchantTable({ merchants }: { merchants: Merchant[] }) {
<TableHeader>
<TableRow className="bg-[#fafbf9] hover:bg-[#fafbf9]">
<TableHead className="pl-6">{t('common.merchant')}</TableHead>
<TableHead>{t('merchants.contact')}</TableHead>
<TableHead>{t('common.status')}</TableHead>
<TableHead>{t('merchants.location')}</TableHead>
<TableHead>{t('common.owner')}</TableHead>
@@ -246,17 +248,22 @@ function MerchantTable({ merchants }: { merchants: Merchant[] }) {
<TableCell className="pl-6">
<Link
to={`/app/merchants/${m.id}`}
state={{ returnTo: `${location.pathname}${location.search}` }}
className="flex min-h-14 items-center gap-3 py-2"
>
<Avatar name={m.name} small />
<div>
<p className="text-[13px] font-semibold">{m.name}</p>
<p className="mt-1 text-[11px] text-muted-foreground">
{t(`industry.${m.industry}`)}
{m.industry ? t(`industry.${m.industry}`) : '—'}
</p>
</div>
</Link>
</TableCell>
<TableCell className="max-w-52 text-xs">
<p className="truncate">{m.contactName}</p>
<p className="mt-1 truncate text-muted-foreground">{m.contactEmail}</p>
</TableCell>
<TableCell>
<StatusBadge status={m.status} />
</TableCell>
@@ -276,17 +283,25 @@ function MerchantTable({ merchants }: { merchants: Merchant[] }) {
</div>
<div className="divide-y md:hidden">
{merchants.map((m) => (
<Link key={m.id} to={`/app/merchants/${m.id}`} className="hover-surface block p-4">
<Link
key={m.id}
to={`/app/merchants/${m.id}`}
state={{ returnTo: `${location.pathname}${location.search}` }}
className="hover-surface block p-4"
>
<div className="flex items-center gap-3">
<Avatar name={m.name} />
<div className="min-w-0">
<h2 className="truncate text-sm font-semibold">{m.name}</h2>
<p className="mt-1 text-xs text-muted-foreground">
{t(`industry.${m.industry}`)} · {f.country(m.country)}
{m.industry ? t(`industry.${m.industry}`) : '—'} · {f.country(m.country)}
</p>
</div>
<ChevronRight className="ml-auto size-4 shrink-0 text-muted-foreground" />
</div>
<p className="mt-3 truncate text-xs text-muted-foreground">
{m.contactName} · {m.contactEmail}
</p>
<div className="mt-4 flex flex-wrap items-center justify-between gap-2">
<StatusBadge status={m.status} />
<span className="text-xs text-muted-foreground">
@@ -302,38 +317,59 @@ function MerchantTable({ merchants }: { merchants: Merchant[] }) {
export function Merchants() {
const { t } = useTranslation();
const f = useFormat();
const user = useOutletContext<User>();
const [params, setParams] = useSearchParams();
const search = params.get('search') ?? '';
const normalized = directoryParams(params, user.role);
const canonical = normalized.toString();
const search = normalized.get('search') ?? '';
const debounced = useDebounced(search);
const parsedStatus = statusSchema.safeParse(params.get('status'));
const status = parsedStatus.success ? parsedStatus.data : '';
const page = Math.max(1, Math.min(10000, Number(params.get('page')) || 1));
const status = normalized.get('status') ?? '';
const page = Number(normalized.get('page') ?? 1);
const requestParams = new URLSearchParams(canonical);
if (debounced) requestParams.set('search', debounced);
else requestParams.delete('search');
const requestQuery = requestParams.toString();
const update = (key: string, value: string) => {
const next = new URLSearchParams(params);
const next = new URLSearchParams(canonical);
if (value) next.set(key, value);
else next.delete(key);
if (key !== 'page') next.delete('page');
setParams(next, { replace: true });
setParams(next, { replace: key === 'search' });
};
const filters = useQuery({
queryKey: ['merchant-filters'],
queryFn: ({ signal }) => api('/merchants/filters', merchantFiltersSchema, { signal }),
});
const query = useQuery({
queryKey: ['merchants', debounced, status, page],
queryFn: ({ signal }) =>
api(
`/merchants?${new URLSearchParams({ search: debounced, ...(status ? { status } : {}), page: String(page) })}`,
merchantListSchema,
{ signal },
),
queryKey: ['merchants', requestQuery],
queryFn: ({ signal }) => api(`/merchants?${requestQuery}`, merchantListSchema, { signal }),
placeholderData: keepPreviousData,
});
useEffect(() => {
if (params.toString() !== canonical)
setParams(new URLSearchParams(canonical), { replace: true });
else if (
query.data &&
!query.isPlaceholderData &&
debounced === search &&
query.data.page !== page
) {
const next = new URLSearchParams(canonical);
if (query.data.page === 1) next.delete('page');
else next.set('page', String(query.data.page));
setParams(next, { replace: true });
}
}, [canonical, params, setParams, query.data, query.isPlaceholderData, debounced, search, page]);
return (
<>
<PageHeader
title={t('merchants.title')}
description={t('merchants.description')}
eyebrow={t('merchants.portfolio')}
action={filters.data?.canCreate && <CreateMerchant user={user} />}
/>
<section className="surface overflow-hidden">
<div className="flex flex-col gap-3 border-b p-4 sm:flex-row sm:items-center sm:justify-between sm:px-6">
<div className="space-y-3 border-b p-4 sm:px-6">
<div className="relative w-full sm:max-w-sm">
<Search
className="pointer-events-none absolute left-3 top-3.5 size-4 text-muted-foreground"
@@ -354,11 +390,11 @@ export function Merchants() {
/>
)}
</div>
<div className="flex items-center gap-2">
<SlidersHorizontal
className="size-4 shrink-0 text-muted-foreground"
aria-hidden="true"
/>
<div
role="group"
aria-label={t('workspace.filters')}
className="grid gap-2 sm:grid-cols-2 xl:grid-cols-4"
>
<NativeSelect
aria-label={t('merchants.filter')}
value={status}
@@ -372,65 +408,139 @@ export function Merchants() {
</option>
))}
</NativeSelect>
<NativeSelect
className="w-full bg-white"
aria-label={t('workspace.allCountries')}
value={normalized.get('country') ?? ''}
onChange={(event) => update('country', event.target.value)}
>
<option value="">{t('workspace.allCountries')}</option>
{[
...new Set([
...(filters.data?.countries ?? []),
...(normalized.get('country') ? [normalized.get('country')!] : []),
]),
].map((country) => (
<option key={country} value={country}>
{f.country(country)}
</option>
))}
</NativeSelect>
<NativeSelect
className="w-full bg-white"
aria-label={t('workspace.allIndustries')}
value={normalized.get('industry') ?? ''}
onChange={(event) => update('industry', event.target.value)}
>
<option value="">{t('workspace.allIndustries')}</option>
{[
...new Set([
...(filters.data?.industries ?? []),
...(normalized.get('industry') ? [normalized.get('industry')!] : []),
]),
].map((industry) => (
<option key={industry} value={industry}>
{t(`industry.${industry}`)}
</option>
))}
</NativeSelect>
{filters.data?.canFilterOwner && (
<NativeSelect
className="w-full bg-white"
aria-label={t('workspace.allOwners')}
value={normalized.get('ownerId') ?? ''}
onChange={(event) => update('ownerId', event.target.value)}
>
<option value="">{t('workspace.allOwners')}</option>
<option value="unassigned">{t('workflow.unassigned')}</option>
{filters.data.owners.map((owner) => (
<option key={owner.id} value={owner.id}>
{owner.name}
</option>
))}
{normalized.get('ownerId') &&
normalized.get('ownerId') !== 'unassigned' &&
!filters.data.owners.some((owner) => owner.id === normalized.get('ownerId')) && (
<option value={normalized.get('ownerId')!}>{t('workspace.notProvided')}</option>
)}
</NativeSelect>
)}
</div>
</div>
<QueryBoundary query={query}>
{(data) =>
data.items.length ? (
<>
<MerchantTable merchants={data.items} />
<div className="flex flex-col items-center justify-between gap-3 border-t px-5 py-4 sm:flex-row sm:px-6">
<p className="text-xs text-muted-foreground">
{t('common.showing', {
from: f.number((page - 1) * data.pageSize + 1),
to: f.number(Math.min(page * data.pageSize, data.total)),
total: f.number(data.total),
})}
</p>
<nav
aria-label={t('common.page', {
page: f.number(page),
total: f.number(Math.ceil(data.total / data.pageSize)),
})}
className="flex items-center gap-2"
>
<Button
variant="outline"
size="icon"
aria-label={t('common.previous')}
disabled={page <= 1 || query.isPlaceholderData}
onClick={() => update('page', String(page - 1))}
{filters.isError && (
<div role="alert" className="px-5 py-3 text-sm">
{t('common.errorTitle')}{' '}
<Button variant="ghost" onClick={() => void filters.refetch()}>
{t('common.retry')}
</Button>
</div>
)}
{!!canonical && !!query.data?.items.length && (
<div className="border-b px-4 py-2">
<Button variant="ghost" onClick={() => setParams({})}>
{t('common.clear')}
</Button>
</div>
)}
<div aria-busy={query.isFetching}>
<QueryBoundary query={query}>
{(data) =>
data.items.length ? (
<>
<MerchantTable merchants={data.items} />
<div className="flex flex-col items-center justify-between gap-3 border-t px-5 py-4 sm:flex-row sm:px-6">
<p className="text-xs text-muted-foreground">
{t('common.showing', {
from: f.number((page - 1) * data.pageSize + 1),
to: f.number(Math.min(page * data.pageSize, data.total)),
total: f.number(data.total),
})}
</p>
<nav
aria-label={t('common.page', {
page: f.number(page),
total: f.number(Math.ceil(data.total / data.pageSize)),
})}
className="flex items-center gap-2"
>
<ChevronLeft className="size-4" />
<Button
variant="outline"
size="icon"
aria-label={t('common.previous')}
disabled={page <= 1 || query.isPlaceholderData}
onClick={() => update('page', String(page - 1))}
>
<ChevronLeft className="size-4" />
</Button>
<span className="px-2 text-xs">
{f.number(page)} / {f.number(Math.ceil(data.total / data.pageSize))}
</span>
<Button
variant="outline"
size="icon"
aria-label={t('common.next')}
disabled={page * data.pageSize >= data.total || query.isPlaceholderData}
onClick={() => update('page', String(page + 1))}
>
<ChevronRight className="size-4" />
</Button>
</nav>
</div>
</>
) : (
<EmptyState
title={t('common.noResults')}
description={t('common.noResultsText')}
action={
<Button variant="outline" onClick={() => setParams({})}>
{t('common.clear')}
</Button>
<span className="px-2 text-xs">
{f.number(page)} / {f.number(Math.ceil(data.total / data.pageSize))}
</span>
<Button
variant="outline"
size="icon"
aria-label={t('common.next')}
disabled={page * data.pageSize >= data.total || query.isPlaceholderData}
onClick={() => update('page', String(page + 1))}
>
<ChevronRight className="size-4" />
</Button>
</nav>
</div>
</>
) : (
<EmptyState
title={t('common.noResults')}
description={t('common.noResultsText')}
action={
<Button variant="outline" onClick={() => setParams({})}>
{t('common.clear')}
</Button>
}
/>
)
}
</QueryBoundary>
}
/>
)
}
</QueryBoundary>
</div>
</section>
</>
);
@@ -439,15 +549,32 @@ export function MerchantDetail() {
const { id } = useParams();
const { t } = useTranslation();
const f = useFormat();
const location = useLocation();
const [params, setParams] = useSearchParams();
const tabs = ['overview', 'activity', 'onboarding', 'tasks'] as const;
const requested =
location.hash === '#checklist'
? 'onboarding'
: location.hash === '#tasks'
? 'tasks'
: params.get('tab');
const tab = tabs.find((value) => value === requested) ?? 'overview';
const query = useQuery({
queryKey: ['merchant', id],
queryFn: ({ signal }) =>
api(`/merchants/${encodeURIComponent(id ?? '')}`, merchantDetailSchema, { signal }),
});
const back = safeReturnTo(location.state?.returnTo ?? '/app/merchants');
const selectTab = (value: string) => {
const next = new URLSearchParams(params);
if (value === 'overview') next.delete('tab');
else next.set('tab', value);
setParams(next, { state: location.state });
};
return (
<>
<Link
to="/app/merchants"
to={back}
className="mb-5 inline-flex min-h-11 items-center gap-2 text-xs text-muted-foreground"
>
<ArrowLeft className="size-3.5" />
@@ -456,168 +583,196 @@ export function MerchantDetail() {
<QueryBoundary query={query}>
{(m) => (
<>
<div className="mb-7 flex flex-wrap items-center gap-4">
<div className="mb-6 flex flex-wrap items-center gap-4">
<Avatar name={m.name} />
<div className="min-w-0">
<h1 className="page-title">{m.name}</h1>
<div className="min-w-0 flex-1">
<h1 className="page-title break-words">{m.name}</h1>
<p className="mt-1 text-xs text-muted-foreground">
{t(`industry.${m.industry}`)} · {f.country(m.country)}
{m.industry ? t(`industry.${m.industry}`) : '—'} · {f.country(m.country)} ·{' '}
{m.owner?.name ?? t('workflow.unassigned')}
</p>
</div>
<div className="ml-auto">
<div className="flex w-full flex-wrap items-center gap-x-3 gap-y-1 pl-[60px] sm:block sm:w-auto sm:pl-0">
<StatusBadge status={m.status} />
<p className="mt-2 text-[11px] text-muted-foreground">
{t('merchants.since', { date: f.date(m.stageEnteredAt) })}
<p className="text-xs text-muted-foreground sm:mt-2">
<StageAge since={m.stageEnteredAt} />
</p>
</div>
</div>
<MerchantControls merchant={m} />
<div className="grid gap-6 xl:grid-cols-[1.15fr_1fr]">
<div className="min-w-0 space-y-6">
<section className="surface">
<SectionHeader
title={t('merchants.overview')}
description={t('merchants.details')}
/>
<dl className="grid grid-cols-1 gap-5 p-5 sm:grid-cols-2 sm:p-6">
{[
{
label: t('common.owner'),
value: m.owner?.name ?? t('workflow.unassigned'),
},
{ label: t('merchants.contact'), value: m.contactName },
...(
[
'legalName',
'registrationNumber',
'address',
'contactPhone',
'contactTitle',
] as const
).map((key) => ({ label: t(`workflow.${key}`), value: m[key] ?? '—' })),
{
label: t('workflow.estimatedMonthlyVolumeUsd'),
value: f.usd(m.estimatedMonthlyVolumeUsd),
},
{
label: t('workflow.source'),
value: m.source ? t(`workflow.${m.source}`) : '—',
},
{
label: t('merchants.website'),
value: (
<a
href={m.website}
target="_blank"
rel="noreferrer"
className="inline-flex min-h-11 items-center gap-1.5 break-all hover:underline"
>
<Globe2 className="size-3.5 shrink-0" />
{new URL(m.website).hostname}
<ExternalLink className="size-3 shrink-0" />
</a>
),
},
{
label: t('auth.email'),
value: (
<a
href={`mailto:${m.contactEmail}`}
className="inline-flex min-h-11 items-center gap-1.5 break-all hover:underline"
>
<Mail className="size-3.5 shrink-0" />
{m.contactEmail}
</a>
),
},
].map((item, i) => (
<div key={i} className="min-w-0">
<dt className="text-xs text-muted-foreground">{item.label}</dt>
<dd className="mt-2 text-sm font-medium">{item.value}</dd>
</div>
))}
</dl>
</section>
<ReviewHistory merchant={m} />
<section id="checklist" className="surface">
<SectionHeader
title={t('merchants.checklist')}
description={t('merchants.checklistText')}
/>
<div className="mt-4">
{m.checklist.map((doc) => (
<div key={doc.id} className="flex gap-3 border-t px-5 py-4 sm:px-6">
<div
className={cn(
'mt-1 flex size-7 shrink-0 items-center justify-center rounded-lg',
doc.state === 'RECEIVED'
? 'bg-accent text-[#46641d]'
: 'bg-muted text-muted-foreground',
)}
>
{doc.state === 'RECEIVED' ? (
<Check className="size-4" />
) : (
<FileText className="size-4" />
)}
</div>
<div className="min-w-0 flex-1">
<div className="flex flex-wrap items-center justify-between gap-2">
<p className="text-sm">{t(`documents.${doc.documentCode}`)}</p>
<Badge
variant="outline"
className={cn(
'text-[10px]',
doc.state === 'NEEDS_CORRECTION' &&
'border-amber-200 bg-amber-50 text-amber-800',
)}
<div
role="tablist"
aria-label={t('workspace.sections')}
className="mb-6 flex overflow-x-auto border-b"
>
{tabs.map((value, index) => (
<button
key={value}
id={`tab-${value}`}
type="button"
role="tab"
aria-selected={tab === value}
aria-controls={`panel-${value}`}
tabIndex={tab === value ? 0 : -1}
className={cn(
'min-h-12 shrink-0 border-b-2 px-4 text-sm font-medium',
tab === value
? 'border-[#719344] text-foreground'
: 'border-transparent text-muted-foreground',
)}
onClick={() => selectTab(value)}
onKeyDown={(event) => {
const next =
event.key === 'ArrowRight'
? (index + 1) % tabs.length
: event.key === 'ArrowLeft'
? (index + tabs.length - 1) % tabs.length
: event.key === 'Home'
? 0
: event.key === 'End'
? tabs.length - 1
: -1;
if (next < 0) return;
event.preventDefault();
selectTab(tabs[next]!);
document.getElementById(`tab-${tabs[next]}`)?.focus();
}}
>
{t(`workspace.${value}`)}
</button>
))}
</div>
<div
role="tabpanel"
id={`panel-${tab}`}
aria-labelledby={`tab-${tab}`}
tabIndex={0}
className="min-w-0 space-y-6"
>
{tab === 'overview' && (
<>
<section className="surface">
<SectionHeader
title={t('merchants.overview')}
description={t('merchants.details')}
/>
<dl className="grid grid-cols-1 gap-5 p-5 sm:grid-cols-2 sm:p-6">
{[
{
label: t('common.owner'),
value: m.owner?.name ?? t('workflow.unassigned'),
},
{ label: t('merchants.contact'), value: m.contactName },
...(
[
'legalName',
'registrationNumber',
'address',
'contactPhone',
'contactTitle',
] as const
).map((key) => ({ label: t(`workflow.${key}`), value: m[key] ?? '—' })),
{
label: t('workflow.estimatedMonthlyVolumeUsd'),
value: f.usd(m.estimatedMonthlyVolumeUsd),
},
{
label: t('workflow.source'),
value: m.source ? t(`workflow.${m.source}`) : '—',
},
{
label: t('merchants.website'),
value: m.website ? (
<a
href={m.website}
target="_blank"
rel="noreferrer"
className="inline-flex min-h-11 items-center gap-1.5 break-all hover:underline"
>
{t(`checklist.${doc.state}`)}
</Badge>
</div>
<ChecklistControl merchant={m} item={doc} />
{doc.note && (
<p className="mt-2 text-xs leading-relaxed text-muted-foreground">
{doc.note}
</p>
)}
<Globe2 className="size-3.5 shrink-0" />
{new URL(m.website).hostname}
<ExternalLink className="size-3 shrink-0" />
</a>
) : (
'—'
),
},
{
label: t('auth.email'),
value: (
<a
href={`mailto:${m.contactEmail}`}
className="inline-flex min-h-11 items-center gap-1.5 break-all hover:underline"
>
<Mail className="size-3.5 shrink-0" />
{m.contactEmail}
</a>
),
},
].map((item, i) => (
<div key={i} className="min-w-0">
<dt className="text-xs text-muted-foreground">{item.label}</dt>
<dd className="mt-2 text-sm font-medium">{item.value}</dd>
</div>
</div>
))}
</div>
</section>
<section className="surface">
<SectionHeader
title={t('merchants.notes')}
description={t('merchants.notesText')}
/>
<div className="space-y-4 p-5 sm:p-6">
{m.notes.length ? (
m.notes.map((note) => (
<article key={note.id} className="rounded-lg bg-background p-4">
<p className="whitespace-pre-wrap text-sm leading-7">{note.text}</p>
<p className="mt-3 text-[11px] text-muted-foreground">
{note.author.name} · {f.date(note.createdAt)}
</p>
</article>
))
) : (
<EmptyState title={t('merchants.noNotes')} />
)}
</div>
</section>
</div>
<div className="min-w-0 space-y-6">
<section className="surface">
<SectionHeader
title={t('merchants.history')}
description={t('merchants.historyText')}
/>
<ActivityFeed events={m.events} detail />
</section>
<MerchantTasks merchant={m} />
<InteractionHistory merchant={m} />
</div>
))}
</dl>
</section>
</>
)}
{tab === 'activity' && <InteractionHistory merchant={m} />}
{tab === 'onboarding' && (
<>
<ReviewHistory merchant={m} />
<section id="checklist" className="surface">
<SectionHeader
title={t('merchants.checklist')}
description={t('merchants.checklistText')}
/>
<div className="mt-4">
{m.checklist.map((doc) => (
<div key={doc.id} className="flex gap-3 border-t px-5 py-4 sm:px-6">
<div
className={cn(
'mt-1 flex size-7 shrink-0 items-center justify-center rounded-lg',
doc.state === 'RECEIVED'
? 'bg-accent text-[#46641d]'
: 'bg-muted text-muted-foreground',
)}
>
{doc.state === 'RECEIVED' ? (
<Check className="size-4" />
) : (
<FileText className="size-4" />
)}
</div>
<div className="min-w-0 flex-1">
<div className="flex flex-wrap items-center justify-between gap-2">
<p className="text-sm">{t(`documents.${doc.documentCode}`)}</p>
<Badge
variant="outline"
className={cn(
'text-[10px]',
doc.state === 'NEEDS_CORRECTION' &&
'border-amber-200 bg-amber-50 text-amber-800',
)}
>
{t(`checklist.${doc.state}`)}
</Badge>
</div>
<ChecklistControl merchant={m} item={doc} />
{doc.note && (
<p className="mt-2 text-xs leading-relaxed text-muted-foreground">
{doc.note}
</p>
)}
</div>
</div>
))}
</div>
</section>
</>
)}
{tab === 'tasks' && <MerchantTasks merchant={m} />}
</div>
</>
)}
@@ -628,10 +783,11 @@ export function MerchantDetail() {
export function Pipeline() {
const { t } = useTranslation();
const f = useFormat();
const [stage, setStage] = useState<Status>('NEW_LEAD');
const [params, setParams] = useSearchParams();
const stage = statusSchema.safeParse(params.get('stage')).data ?? 'NEW_LEAD';
const query = useQuery({
queryKey: ['pipeline'],
queryFn: ({ signal }) => api('/pipeline', pipelineSchema, { signal }),
queryFn: ({ signal }) => api('/pipeline', pipelineBoardSchema, { signal }),
});
return (
<>
@@ -647,70 +803,64 @@ export function Pipeline() {
className="mb-5 w-full md:hidden"
aria-label={t('pipeline.stageSelect')}
value={stage}
onChange={(e) => setStage(e.target.value as Status)}
onChange={(event) => setParams({ stage: event.target.value })}
>
{successfulStages.map((s) => (
<option value={s} key={s}>
{t(`statuses.${s}`)} ({f.number(merchants.filter((m) => m.status === s).length)})
{statuses.map((value) => (
<option key={value} value={value}>
{t(`statuses.${value}`)} (
{f.number(merchants.filter((merchant) => merchant.status === value).length)})
</option>
))}
</NativeSelect>
<div className="grid gap-4 md:grid-cols-2 xl:grid-cols-4">
{successfulStages.map((s, i) => {
const items = merchants.filter((m) => m.status === s);
<div
className="flex gap-4 overflow-x-auto pb-4"
aria-label={t('pipeline.title')}
tabIndex={0}
>
{statuses.map((value) => {
const items = merchants.filter((merchant) => merchant.status === value);
return (
<section
key={s}
key={value}
aria-label={t(`statuses.${value}`)}
className={cn(
'min-w-0 rounded-xl border bg-[#f0f3ee] p-3',
s !== stage && 'hidden md:block',
'w-full min-w-0 shrink-0 rounded-xl border bg-[#f0f3ee] p-3 md:w-72',
stage !== value && 'hidden md:block',
)}
>
<div className="mb-4 flex min-h-10 items-center justify-between gap-2 px-1">
<h2 className="flex items-center gap-2 text-xs font-semibold">
<span
className="size-2 shrink-0 rounded-full"
style={{ backgroundColor: stageColors[s] }}
className="size-2 rounded-full"
style={{ backgroundColor: stageColors[value] }}
/>
{t(`statuses.${s}`)}
{t(`statuses.${value}`)}
</h2>
<span className="rounded-md border bg-white px-2 py-1 text-[10px] tabular-nums">
<span className="rounded-md border bg-white px-2 py-1 text-xs tabular-nums">
{f.number(items.length)}
</span>
</div>
<div className="space-y-3">
{items.map((m) => (
<MerchantCard key={m.id} merchant={m} />
{items.map((merchant) => (
<article key={merchant.id} className="surface overflow-hidden">
<MerchantCard merchant={merchant} className="rounded-none border-0" />
{merchant.capabilities.actions.length > 0 && (
<div className="border-t p-3">
<StageActions merchant={merchant} compact />
</div>
)}
</article>
))}
{!items.length && (
<p className="flex min-h-36 items-center justify-center rounded-lg border border-dashed px-4 text-center text-xs leading-relaxed text-muted-foreground">
<p className="flex min-h-36 items-center justify-center rounded-lg border border-dashed p-4 text-center text-xs text-muted-foreground">
{t('pipeline.empty')}
</p>
)}
</div>
<p className="mt-4 px-1 text-[10px] text-muted-foreground">
{t('pipeline.stageCount', { number: f.number(i + 1) })}
</p>
</section>
);
})}
</div>
<section className="mt-7 rounded-xl border border-dashed p-5">
<h2 className="text-sm font-semibold">{t('pipeline.rejectedTitle')}</h2>
<p className="mb-4 mt-1 text-xs leading-relaxed text-muted-foreground">
{t('pipeline.rejectedText')}
</p>
<div className="grid gap-3 md:grid-cols-2 xl:grid-cols-4">
{merchants
.filter((m) => m.status === 'REJECTED')
.map((m) => (
<MerchantCard merchant={m} key={m.id} />
))}
{!merchants.some((m) => m.status === 'REJECTED') && (
<p className="text-xs text-muted-foreground">{t('pipeline.empty')}</p>
)}
</div>
</section>
</>
)}
</QueryBoundary>
@@ -811,7 +961,8 @@ export function ReviewQueue() {
{m.name}
</Link>
<p className="mt-1 text-xs text-muted-foreground">
{m.owner?.name ?? t('workflow.unassigned')} · {t(`industry.${m.industry}`)}
{m.owner?.name ?? t('workflow.unassigned')} ·{' '}
{m.industry ? t(`industry.${m.industry}`) : '—'}
</p>
</div>
</div>
+528
View File
@@ -0,0 +1,528 @@
.landing-page {
--primary: #d6f36b;
--primary-foreground: #20251b;
--foreground: #20251b;
--muted-foreground: #596153;
color: var(--foreground);
background: #fafbf7;
}
.landing-wrap {
width: min(100% - 40px, 1184px);
margin-inline: auto;
}
.landing-header {
display: flex;
flex-wrap: wrap;
align-items: center;
justify-content: space-between;
gap: 6px 20px;
padding-block: 20px;
border-bottom: 1px solid #dfe3d8;
}
.landing-header-actions {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 12px;
}
.landing-staff,
.landing-text-link {
min-height: 44px;
display: inline-flex;
align-items: center;
gap: 8px;
font-size: 13px;
font-weight: 600;
border-radius: 4px;
}
.landing-skip {
position: absolute;
top: 8px;
left: 20px;
padding: 12px;
background: white;
transform: translateY(-150%);
z-index: 10;
}
.landing-skip:focus {
transform: none;
}
.landing-hero {
padding-block: 48px 52px;
}
.landing-eyebrow {
display: flex;
align-items: center;
gap: 10px;
font-size: 10px;
line-height: 1.6;
font-weight: 600;
letter-spacing: 0.095em;
}
.landing-eyebrow > span {
width: 7px;
height: 7px;
border-radius: 50%;
background: #748d29;
flex-shrink: 0;
}
.landing-hero h1 {
margin-top: 25px;
max-width: 1070px;
font-size: clamp(44px, 6.7vw, 92px);
font-weight: 650;
letter-spacing: -0.062em;
line-height: 1.04;
text-wrap: balance;
}
.landing-hero h1 > span {
color: #61752d;
}
.landing-hero-bottom {
display: grid;
gap: 32px;
margin-top: 28px;
}
.landing-description {
max-width: 565px;
font-size: 16px;
line-height: 1.75;
color: var(--muted-foreground);
}
.landing-hero-actions {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 8px 24px;
margin-top: 26px;
}
.landing-cta {
display: inline-flex;
justify-content: center;
align-items: center;
gap: 22px;
min-height: 52px;
height: auto;
padding: 14px 22px;
border-radius: 100px;
background: var(--primary);
color: var(--primary-foreground);
font-size: 15px;
font-weight: 600;
white-space: normal;
line-height: 1.4;
text-align: center;
}
.landing-cta svg {
flex-shrink: 0;
}
.landing-hero-note {
margin-top: 15px;
font-size: 11px;
color: var(--muted-foreground);
}
.landing-path {
display: none;
}
.landing-benefits {
padding-bottom: 52px;
}
.landing-benefits h2 {
max-width: 740px;
margin-bottom: 24px;
font-size: 27px;
font-weight: 550;
letter-spacing: -0.035em;
line-height: 1.2;
text-wrap: balance;
}
.landing-benefit-grid {
display: grid;
gap: 12px;
}
.landing-benefit {
min-width: 0;
padding: 24px;
border: 1px solid #e0e5d8;
border-radius: 16px;
background: #f0f3e9;
}
.landing-benefit:nth-child(2) {
background: #f6f7f1;
}
.landing-benefit:nth-child(3) {
background: #eaf0df;
}
.landing-card-top {
display: flex;
justify-content: space-between;
align-items: center;
color: #465635;
margin-bottom: 28px;
}
.landing-card-top > span {
font-size: 11px;
color: #68735b;
}
.landing-benefit h3 {
font-size: 18px;
font-weight: 600;
letter-spacing: -0.025em;
}
.landing-benefit p {
margin-top: 12px;
color: var(--muted-foreground);
font-size: 14px;
line-height: 1.75;
}
.landing-process {
display: grid;
gap: 26px;
border-top: 1px solid #dfe3d8;
padding-block: 42px 52px;
scroll-margin-top: 24px;
}
.landing-process h2 {
margin-top: 14px;
max-width: 400px;
font-size: 34px;
font-weight: 550;
letter-spacing: -0.045em;
line-height: 1.13;
}
.landing-process ol {
list-style: none;
margin: 0;
padding: 0;
}
.landing-process li {
display: flex;
align-items: flex-start;
gap: 15px;
padding-block: 22px;
border-bottom: 1px solid #dfe3d8;
}
.landing-process li:first-child {
padding-top: 0;
}
.landing-process li:last-child {
border: 0;
padding-bottom: 0;
}
.landing-step-number {
display: grid;
flex-shrink: 0;
place-items: center;
width: 34px;
height: 34px;
border: 1px solid #c9d3b6;
border-radius: 50%;
font-size: 11px;
}
.landing-process h3 {
font-size: 16px;
font-weight: 600;
line-height: 1.4;
}
.landing-process li p {
margin-top: 8px;
font-size: 14px;
line-height: 1.7;
color: var(--muted-foreground);
}
.landing-process li > svg {
display: none;
flex-shrink: 0;
margin-left: auto;
}
.landing-consultation {
background: #e9eddf;
padding-block: 42px;
scroll-margin-top: 16px;
}
.landing-consultation-grid {
display: grid;
gap: 28px;
}
.landing-form-intro h2 {
margin-top: 16px;
font-size: 38px;
letter-spacing: -0.045em;
font-weight: 550;
line-height: 1.12;
white-space: pre-line;
}
.landing-form-intro > p:not(.landing-eyebrow) {
max-width: 350px;
margin-top: 20px;
color: var(--muted-foreground);
font-size: 15px;
line-height: 1.75;
}
.landing-form-arrow {
display: none;
}
.lead-panel {
background: #fff;
border: 1px solid #dce2d2;
border-radius: 18px;
padding: 24px 20px;
min-width: 0;
}
.lead-form-heading {
margin-bottom: 26px;
}
.lead-form-heading h3 {
font-size: 20px;
font-weight: 600;
letter-spacing: -0.025em;
}
.lead-form-heading p {
color: var(--muted-foreground);
font-size: 12px;
margin-top: 7px;
}
.lead-fields {
display: grid;
min-width: 0;
gap: 20px;
border: 0;
padding: 0;
margin: 0;
}
.lead-fields > * {
min-width: 0;
}
.lead-fields input,
.lead-fields select {
background: #fcfdf9;
min-height: 48px;
}
.lead-volume > p {
margin-top: 8px;
color: var(--muted-foreground);
font-size: 12px;
line-height: 1.6;
}
.lead-honeypot {
position: absolute;
width: 1px;
height: 1px;
padding: 0;
margin: -1px;
overflow: hidden;
clip-path: inset(50%);
white-space: nowrap;
pointer-events: none;
}
.lead-submit {
width: 100%;
margin-top: 26px;
}
.lead-form-note {
font-size: 11px;
line-height: 1.7;
color: var(--muted-foreground);
margin-top: 14px;
text-align: center;
}
.lead-feedback {
margin-top: 20px;
padding: 12px;
border: 1px solid #ebc3b8;
background: #fff8f5;
border-radius: 8px;
font-size: 13px;
line-height: 1.7;
color: #8b372e;
}
.lead-success {
min-height: 300px;
display: flex;
flex-direction: column;
align-items: flex-start;
justify-content: center;
padding: 10px;
border-radius: 8px;
}
.lead-success-icon {
display: grid;
place-items: center;
width: 60px;
height: 60px;
background: #e6f5b2;
border-radius: 50%;
margin-bottom: 28px;
}
.lead-success h3 {
font-size: 28px;
font-weight: 600;
letter-spacing: -0.04em;
line-height: 1.2;
}
.lead-success p {
margin-top: 16px;
color: var(--muted-foreground);
line-height: 1.8;
font-size: 15px;
}
.landing-footer {
display: flex;
flex-wrap: wrap;
gap: 18px 30px;
align-items: center;
padding-block: 28px;
}
.landing-footer > p,
.landing-footer > span {
font-size: 11px;
line-height: 1.7;
color: var(--muted-foreground);
}
@media (hover: hover) and (pointer: fine) {
.landing-cta:hover {
background: #cbe95e;
}
.landing-text-link:hover,
.landing-staff:hover {
text-decoration: underline;
text-underline-offset: 5px;
}
}
@media (min-width: 640px) {
.landing-wrap {
width: min(100% - 64px, 1184px);
}
.landing-header-actions {
gap: 24px;
}
.landing-hero {
padding-block: 64px 72px;
}
.landing-hero h1 {
margin-top: 28px;
}
.landing-benefit-grid {
grid-template-columns: repeat(3, minmax(0, 1fr));
gap: 16px;
}
.landing-benefit {
padding: 26px;
}
.landing-benefits h2 {
font-size: 34px;
}
.lead-fields {
grid-template-columns: repeat(2, minmax(0, 1fr));
}
.lead-volume {
grid-column: 1 / -1;
}
.lead-panel {
padding: 32px;
}
.landing-process li > svg {
display: block;
}
}
@media (min-width: 1024px) {
.landing-header {
padding-block: 24px;
}
.landing-hero {
padding-block: 64px 80px;
}
.landing-hero-bottom {
grid-template-columns: 1.2fr 1fr;
align-items: center;
gap: 80px;
margin-top: 35px;
}
.landing-path {
display: block;
padding: 25px 0 0;
}
.landing-path-line {
display: flex;
justify-content: space-between;
align-items: center;
position: relative;
height: 48px;
}
.landing-path-line::before {
content: '';
position: absolute;
height: 1px;
background: #aab892;
left: 0;
right: 15px;
}
.landing-path-line span {
z-index: 1;
width: 15px;
height: 15px;
border: 1px solid #839561;
border-radius: 50%;
background: #fafbf7;
}
.landing-path-line span:first-child {
width: 45px;
height: 45px;
border: 13px solid #d6f36b;
background: #20251b;
}
.landing-path-line svg {
z-index: 1;
background: #fafbf7;
}
.landing-path-labels {
display: flex;
justify-content: space-between;
margin-top: 12px;
font-size: 11px;
font-weight: 500;
}
.landing-path > p {
font-size: 10px;
color: var(--muted-foreground);
margin-top: 24px;
}
.landing-benefits {
padding-bottom: 64px;
}
.landing-card-top {
margin-bottom: 36px;
}
.landing-process {
grid-template-columns: 0.85fr 1.15fr;
gap: 80px;
padding-block: 56px 64px;
}
.landing-process h2 {
font-size: 45px;
}
.landing-consultation {
padding-block: 64px;
}
.landing-consultation-grid {
grid-template-columns: 0.8fr 1.2fr;
gap: 72px;
}
.landing-form-intro {
padding-top: 20px;
}
.landing-form-intro h2 {
font-size: 51px;
}
.landing-form-arrow {
display: block;
margin-top: 35px;
color: #627344;
}
.landing-footer > p {
max-width: 340px;
}
.landing-footer > span {
margin-left: auto;
}
}
+146
View File
@@ -0,0 +1,146 @@
import { useEffect } from 'react';
import { Link } from 'react-router';
import { useTranslation } from 'react-i18next';
import { ArrowDown, ArrowUpRight, ArrowRight, Route, Files, Waypoints } from 'lucide-react';
import { Brand, LanguageSwitch } from '../components/shared';
import { LeadForm } from '../components/lead-form';
import './landing.css';
export function Landing() {
const { t } = useTranslation();
useEffect(() => {
document.title = t('landing.metaTitle');
const meta = document.querySelector('meta[name="description"]');
const previous = meta?.getAttribute('content');
meta?.setAttribute('content', t('landing.metaDescription'));
return () => {
if (previous) meta?.setAttribute('content', previous);
};
}, [t]);
const consultation = (event: React.MouseEvent<HTMLAnchorElement>) => {
event.preventDefault();
document.getElementById('consultation')?.scrollIntoView({ block: 'start' });
document.getElementById('lead-name')?.focus({ preventScroll: true });
};
return (
<div className="landing-page">
<a className="landing-skip" href="#main">
{t('common.skip')}
</a>
<header className="landing-header landing-wrap">
<Brand />
<div className="landing-header-actions">
<LanguageSwitch />
<Link to="/login" className="landing-staff">
{t('landing.signIn')}
<ArrowUpRight size={16} aria-hidden="true" />
</Link>
</div>
</header>
<main id="main">
<section className="landing-hero landing-wrap" aria-labelledby="hero-title">
<p className="landing-eyebrow">
<span aria-hidden="true" />
{t('landing.eyebrow')}
</p>
<h1 id="hero-title">
{t('landing.title')} <span>{t('landing.titleAccent')}</span>
</h1>
<div className="landing-hero-bottom">
<div>
<p className="landing-description">{t('landing.description')}</p>
<div className="landing-hero-actions">
<a href="#consultation" onClick={consultation} className="landing-cta pressable">
{t('landing.cta')}
<ArrowUpRight size={22} aria-hidden="true" />
</a>
<a href="#process" className="landing-text-link">
{t('landing.explore')}
<ArrowDown size={16} aria-hidden="true" />
</a>
</div>
<p className="landing-hero-note">{t('landing.heroNote')}</p>
</div>
<div className="landing-path" aria-hidden="true">
<div className="landing-path-line">
<span />
<span />
<span />
<ArrowUpRight size={30} />
</div>
<div className="landing-path-labels">
<span>{t('landing.journeyStart')}</span>
<span>{t('landing.journeyEnd')}</span>
</div>
<p>{t('landing.journeyLabel')}</p>
</div>
</div>
</section>
<section className="landing-benefits landing-wrap" aria-labelledby="benefits-title">
<h2 id="benefits-title">{t('landing.why')}</h2>
<div className="landing-benefit-grid">
{[Route, Files, Waypoints].map((Icon, index) => (
<article key={index} className="landing-benefit">
<div className="landing-card-top">
<Icon size={23} strokeWidth={1.5} aria-hidden="true" />
<span>0{index + 1}</span>
</div>
<h3>{t(`landing.feature${index + 1}`)}</h3>
<p>{t(`landing.feature${index + 1}Text`)}</p>
</article>
))}
</div>
</section>
<section
className="landing-process landing-wrap"
id="process"
aria-labelledby="process-title"
>
<div>
<p className="landing-eyebrow">{t('landing.processLabel')}</p>
<h2 id="process-title">{t('landing.processTitle')}</h2>
</div>
<ol>
{[1, 2, 3].map((step) => (
<li key={step}>
<span className="landing-step-number">0{step}</span>
<div>
<h3>{t(`landing.step${step}`)}</h3>
<p>{t(`landing.step${step}Text`)}</p>
</div>
<ArrowRight size={18} aria-hidden="true" />
</li>
))}
</ol>
</section>
<section
className="landing-consultation"
id="consultation"
aria-labelledby="consultation-title"
>
<div className="landing-wrap landing-consultation-grid">
<div className="landing-form-intro">
<p className="landing-eyebrow">{t('landing.formLabel')}</p>
<h2 id="consultation-title">{t('landing.formTitle')}</h2>
<p>{t('landing.formDescription')}</p>
<ArrowUpRight
className="landing-form-arrow"
size={100}
strokeWidth={1}
aria-hidden="true"
/>
</div>
<div className="lead-panel">
<LeadForm />
</div>
</div>
</section>
</main>
<footer className="landing-footer landing-wrap">
<Brand />
<p>{t('landing.footer')}</p>
<span>© {new Date().getFullYear()} MerchantFlow</span>
</footer>
</div>
);
}
+2 -71
View File
@@ -4,21 +4,11 @@ import { useTranslation } from 'react-i18next';
import { useMutation } from '@tanstack/react-query';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import {
ArrowRight,
ArrowLeft,
Columns3,
ShieldCheck,
ListTodo,
Check,
Eye,
EyeOff,
LoaderCircle,
} from 'lucide-react';
import { ArrowRight, ArrowLeft, ShieldCheck, Check, Eye, EyeOff, LoaderCircle } from 'lucide-react';
import { loginSchema, userSchema, type LoginInput } from '@merchantflow/contracts';
import { Input } from '@merchantflow/ui/components/input';
import { FormField } from '@merchantflow/ui/components/form-field';
import { Brand, LanguageSwitch, LinkButton, Button, StatusBadge } from '../components/shared';
import { Brand, LanguageSwitch, Button, StatusBadge } from '../components/shared';
import { api, ApiError, queryClient, safeReturnTo } from '../lib/api';
function JourneyIllustration() {
const { t } = useTranslation();
@@ -66,65 +56,6 @@ function JourneyIllustration() {
</div>
);
}
export function Landing() {
const { t } = useTranslation();
return (
<div className="min-h-dvh bg-[#fbfcf9]">
<header className="mx-auto flex max-w-6xl flex-wrap items-center justify-between gap-3 px-5 py-5 sm:px-8">
<Brand />
<div className="flex items-center gap-3">
<LanguageSwitch />
<LinkButton to="/login" variant="ghost" className="hidden sm:inline-flex">
{t('landing.signIn')}
<ArrowRight className="size-4" />
</LinkButton>
</div>
</header>
<main>
<section className="mx-auto grid max-w-6xl gap-12 px-5 pb-20 pt-12 sm:px-8 lg:grid-cols-[1.12fr_1fr] lg:items-center lg:gap-14 lg:pb-28 lg:pt-24">
<div>
<p className="section-label mb-6 text-[#577035]">{t('landing.eyebrow')}</p>
<h1 className="whitespace-pre-line text-[40px] font-medium leading-[1.12] tracking-[-.045em] sm:text-5xl lg:text-[58px]">
{t('landing.title')}
</h1>
<p className="mt-6 max-w-lg text-base leading-[1.8] text-muted-foreground">
{t('landing.description')}
</p>
<LinkButton to="/login" className="mt-8 min-h-12 px-5">
{t('landing.cta')}
<ArrowRight className="ml-2 size-4" />
</LinkButton>
<p className="mt-5 text-xs text-muted-foreground">{t('common.brandTag')}</p>
</div>
<JourneyIllustration />
</section>
<section className="border-y bg-white">
<div className="mx-auto max-w-6xl px-5 py-16 sm:px-8">
<h2 className="text-2xl font-medium tracking-tight">{t('landing.why')}</h2>
<p className="mt-2 text-sm text-muted-foreground">{t('landing.whyText')}</p>
<div className="mt-10 grid gap-9 md:grid-cols-3">
{[Columns3, ShieldCheck, ListTodo].map((Icon, i) => (
<div key={i}>
<div className="mb-5 flex size-11 items-center justify-center rounded-xl bg-[#f0f4e9]">
<Icon className="size-5 text-[#577035]" aria-hidden="true" />
</div>
<h3 className="text-base font-semibold">{t(`landing.feature${i + 1}`)}</h3>
<p className="mt-3 max-w-xs text-sm leading-7 text-muted-foreground">
{t(`landing.feature${i + 1}Text`)}
</p>
</div>
))}
</div>
</div>
</section>
</main>
<footer className="mx-auto flex max-w-6xl flex-wrap items-center justify-between gap-4 px-5 py-7 text-xs text-muted-foreground sm:px-8">
<span>© {new Date().getFullYear()} MerchantFlow</span>
<span>{t('landing.footer')}</span>
</footer>
</div>
);
}
export function Login() {
const { t } = useTranslation();
const [show, setShow] = useState(false);
+89
View File
@@ -0,0 +1,89 @@
export const salesEn = {
create: 'Add merchant',
createHint:
'Company name, primary contact and email are required. Add the remaining details before qualification.',
notProvided: 'Not provided yet',
allCountries: 'All countries',
allIndustries: 'All industries',
allOwners: 'All managers',
filters: 'Directory filters',
overview: 'Overview',
activity: 'Activity',
onboarding: 'Onboarding',
tasks: 'Tasks',
sections: 'Merchant sections',
history: 'Merchant history',
historyHint: 'Interactions, ownership, stages and compliance decisions, newest first.',
noHistory: 'No activity yet. Log a note, call or email to start the history.',
ownership: 'Manager changed: {{previous}} → {{owner}}',
stageChange: '{{from}} → {{to}}',
created: 'Created as {{stage}}',
reject: 'Reject merchant',
rejectionReason: 'Rejection reason',
businessReason: 'Business reason',
rejectHint:
'Explain why this merchant should be closed. Rejected merchants cannot progress further.',
businessReasonHint:
'Record the business reason for closing this merchant. This does not change an existing compliance decision.',
terminal: 'This is a final stage. No further transitions are available.',
openOnboarding: 'Open onboarding',
timeInStage: '{{duration}} in stage',
lessThanHour: 'Less than 1 hour',
edited: 'Edited {{date}}',
blockers: {
ASSIGNMENT_REQUIRED: 'Assign a manager before progressing.',
CONTACT_REQUIRED: 'Log a call or email before moving to Contacted.',
QUALIFICATION_INCOMPLETE: 'Complete the following fields:',
DOCUMENTS_REQUIRED: 'Receive all four KYB documents before submitting for review.',
REVIEW_PENDING: 'A single pending review is required; check the onboarding section.',
APPROVAL_REQUIRED: 'Matching compliance approval and document evidence are required.',
COMPLIANCE_ONLY: 'Only Compliance can decide the outcome of this review.',
SALES_ONLY: 'Only the Head or assigned manager can advance commercial stages.',
},
};
export const salesRu = {
create: 'Добавить мерчанта',
createHint:
'Название компании, основной контакт и email обязательны. Остальные данные нужны до квалификации.',
notProvided: 'Пока не указано',
allCountries: 'Все страны',
allIndustries: 'Все отрасли',
allOwners: 'Все менеджеры',
filters: 'Фильтры каталога',
overview: 'Обзор',
activity: 'Активность',
onboarding: 'Онбординг',
tasks: 'Задачи',
sections: 'Разделы мерчанта',
history: 'История мерчанта',
historyHint: 'Взаимодействия, менеджеры, этапы и комплаенс-решения: сначала новые.',
noHistory: 'Пока нет событий. Добавьте заметку, звонок или письмо.',
ownership: 'Менеджер изменён: {{previous}} → {{owner}}',
stageChange: '{{from}} → {{to}}',
created: 'Создан на этапе «{{stage}}»',
reject: 'Отклонить мерчанта',
rejectionReason: 'Причина отклонения',
businessReason: 'Бизнес-причина',
rejectHint: 'Укажите причину закрытия мерчанта. После отклонения переходы недоступны.',
businessReasonHint:
'Укажите бизнес-причину закрытия. Это не изменяет существующее комплаенс-решение.',
terminal: 'Это финальный этап. Дальнейшие переходы недоступны.',
openOnboarding: 'Открыть онбординг',
timeInStage: '{{duration}} на этапе',
lessThanHour: 'Менее 1 часа',
edited: 'Изменено: {{date}}',
blockers: {
ASSIGNMENT_REQUIRED: 'Назначьте менеджера для перехода дальше.',
CONTACT_REQUIRED: 'Запишите звонок или письмо перед переходом к контакту.',
QUALIFICATION_INCOMPLETE: 'Заполните следующие поля:',
DOCUMENTS_REQUIRED: 'Получите все четыре документа KYB перед отправкой на проверку.',
REVIEW_PENDING: 'Нужна одна активная проверка. Откройте раздел онбординга.',
APPROVAL_REQUIRED: 'Нужны актуальное одобрение комплаенса и история документов.',
COMPLIANCE_ONLY: 'Только комплаенс может принять решение по проверке.',
SALES_ONLY: 'Коммерческие этапы меняет руководитель или назначенный менеджер.',
},
} satisfies {
[K in keyof typeof salesEn]: (typeof salesEn)[K] extends string
? string
: Record<keyof (typeof salesEn)[K], string>;
};
+8
View File
@@ -5,6 +5,10 @@ export const workflowEn = {
activityEdited: 'Interaction edited',
taskUpdated: 'Task updated',
taskCreated: 'Task created',
leadCreated: 'Lead received from landing page',
staffCreated: 'Merchant created',
system: 'System',
LANDING_PAGE: 'Landing page',
checklistUpdated: 'Checklist updated: {{document}}',
reviewDecided: 'Compliance review: {{decision}}',
unassigned: 'Unassigned',
@@ -83,6 +87,10 @@ export const workflowRu: Record<keyof typeof workflowEn, string> = {
activityEdited: 'Взаимодействие изменено',
taskUpdated: 'Задача обновлена',
taskCreated: 'Задача создана',
leadCreated: 'Заявка получена с сайта',
staffCreated: 'Мерчант создан',
system: 'Система',
LANDING_PAGE: 'Сайт',
checklistUpdated: 'Документ обновлён: {{document}}',
reviewDecided: 'Комплаенс-проверка: {{decision}}',
unassigned: 'Не назначен',
+31 -2
View File
@@ -39,10 +39,39 @@ A pre-upgrade development backup was saved locally at `/tmp/merchantflow-before-
Development smoke checks passed through both `localhost:5173` and `127.0.0.1:5173`: healthy database, successful login for all four accounts, 45 merchants for Head/Compliance, 20 for each manager, and 401 when reusing every revoked session. The API health check also passed directly on port 3001.
Visual inspection covered the completed approval-to-Live detail screen and the mobile Russian editor. Audit records are collapsed in merchant detail, with translated system labels; the complete history remains available.
Visual inspection covered the completed approval-to-Live detail screen and the mobile Russian editor. The later daily-sales milestone brings these records together in the Activity tab, with translated system labels and complete history.
Existing dependency warnings are non-fatal: Zod/Rollup annotation placement and the Prisma PostgreSQL adapter's pg concurrent-query deprecation. All checks above passed despite these warnings.
## Public landing and lead intake · 24 September 2026
- [x] Original MerchantFlow consultation page with bold typography, lime accents, three benefits, onboarding steps, inline form and mobile staff login
- [x] All seven required fields, localized countries, Other industry, shared validation and complete EN/RU feedback
- [x] Public lead endpoint with trusted-Origin checks, bounded IP/email throttles and Retry-After
- [x] Atomic unassigned New Lead creation, LANDING_PAGE source, four missing KYB items and system-attributed creation history
- [x] Database-backed idempotency across concurrent requests and API restarts; changed-payload conflicts
- [x] Keyboard/accessibility-excluded honeypot with indistinguishable acceptance and no database writes
- [x] Preserved form values, stable retry keys, pending/success/validation/network/server/rate-limit states and accessible announcements
Verification: build, lint, typecheck and 13 unit tests passed. All 24 integration tests passed, including public creation, permission checks, parallel retries across two API instances, restart replay, honeypot rejection, throttling and injected transaction rollback. The six public API tests were rerun successfully after the final quota-reservation adjustment.
All 14 browser tests passed. Consultation coverage exercises EN/RU at 375px and 1440px, every submission state, keyboard focus, hidden honeypot, locale/value preservation, real persistence and a committed request with a deliberately lost response. Existing CRM journeys continue to pass at 390px and 1440px. Screenshots were visually inspected in both languages and sizes. Test-created leads are cleaned up only in the disposable test database; the reference website received no submissions.
The additive migration was applied to development. Before/after checksums confirmed all 45 existing merchants, 135 activities and 206 stage events remained unchanged. Prisma reports no schema difference, and the running web/API database health check passes. No development reseed or reset was performed.
## Boundaries
No staff registration, merchant creation/deletion UI, merchant portal, uploads, payment processing, external KYB service, external reminders or deployment. Login rate-limit buckets are intentionally in-process for this single-process local prototype. Seed dates are anchored once and naturally age; reruns do not refresh deadlines or rewrite existing edits.
No staff registration, merchant deletion UI, merchant portal, uploads, payment processing, external KYB service, external reminders or deployment. Login rate-limit buckets are intentionally in-process for this single-process local prototype. Seed dates are anchored once and naturally age; reruns do not refresh deadlines or rewrite existing edits.
## Daily sales workspace
- [x] Staff lead creation with required company/contact/email, Head assignment and server-enforced Manager self-assignment
- [x] Additive nullable-field migration with safe incomplete-lead rendering
- [x] Scoped combined directory filters, URL persistence, pagination recovery and responsive contact information
- [x] Shared workflow policy, Call/Email evidence, qualification completeness and explicit rejection permissions
- [x] Typed actions/blockers on detail and pipeline; strict general edits and atomic version-checked mutations
- [x] Unified chronological history with ownership identities, rejection reasons and preserved attribution
- [x] URL-addressable detail tabs and single-stage mobile pipeline with explicit card actions
- [x] Retained form values on failure, accessible controls and bilingual feedback
Verification: all 32 integration tests passed against the isolated PostgreSQL service, including role/stage rejection cases, filters, creation, races and injected transaction rollback. All 19 browser tests passed, covering EN/RU at mobile and desktop sizes, real API creation/filtering/history, pipeline progression and rejection, ownership isolation, stale-editor preservation and the existing compliance journeys. Build, lint, typecheck, 17 unit tests, formatting and whitespace checks passed. The additive sales migration was applied to development without a reset or reseed.
+13 -5
View File
@@ -4,7 +4,7 @@ A local merchant-onboarding CRM for a fictional crypto-payment provider, with pe
## People and access
Four seeded staff accounts: Head of Sales, Compliance Officer, Alex Morgan and Sam Taylor. Head sees the portfolio and team activity, assigns/reassigns managers and manages commercial onboarding. Managers see and edit only assigned merchants and related commercial activities/tasks; they cannot change ownership. Compliance sees merchant context and KYB across the portfolio, records reviews and KYB notes, and manages personal compliance tasks. Compliance cannot edit commercial details, change ownership or activate merchants. Sales cannot issue or override compliance decisions. The Review Queue is Compliance-only.
Four seeded staff accounts: Head of Sales, Compliance Officer, Alex Morgan and Sam Taylor. Head sees the portfolio and team activity, creates merchants, assigns/reassigns managers and manages commercial onboarding. Managers may create merchants assigned to themselves; Compliance cannot create merchants. Managers see and edit only assigned merchants and related commercial activities/tasks; they cannot change ownership. Compliance sees merchant context and KYB across the portfolio, records reviews and KYB notes, and manages personal compliance tasks. Compliance cannot edit commercial details, change ownership or activate merchants. Sales cannot issue or override compliance decisions. The Review Queue is Compliance-only.
NestJS authorization and database predicates apply to all reads, searches, counts, detail children, dashboards and mutations. A hidden resource returns 404; a forbidden action on a visible resource returns 403. The UI reflects server capabilities.
@@ -12,15 +12,23 @@ NestJS authorization and database predicates apply to all reads, searches, count
New Lead → Contacted → Qualified → KYB → Compliance Review → Integration → Testing → Live. Rejected is an alternate terminal outcome; neither Live nor Rejected has outgoing stage actions. The same merchant ID persists throughout.
Assignment is required before leaving New Lead. Sales collects the four KYB documents. All must have received-history evidence before submission creates a pending review. Reviewed company/KYB fields freeze during review. Compliance approval advances to Integration; rejection requires a reason; corrections require a reason and item-specific notes and return the merchant to KYB. Resubmission creates another review cycle. Decisions are immutable.
Assignment is required before leaving New Lead and before entering KYB. Contacted requires a persisted call or email; a note or meeting does not qualify. Qualified requires company name, website, primary contact name/email, country, industry and estimated monthly volume (zero is valid). Head or the assigned Manager may reject New Lead, Contacted or Qualified with a reason. Only Head may close KYB, Integration or Testing for a recorded business reason; this preserves any compliance decision. Only Compliance can decide rejection during Compliance Review. Sales collects the four KYB documents. All must have received-history evidence before submission creates a pending review. Reviewed company/KYB fields freeze during review. Compliance approval advances to Integration; rejection requires a reason; corrections require a reason and item-specific notes and return the merchant to KYB. Resubmission creates another review cycle. Decisions are immutable.
Reviewed company identity, website, country, industry and KYB items remain locked after approval. Contact details, volume estimates, source and authorized ownership can change. Head or the assigned manager may advance Integration → Testing → Live only with matching approval/checklist evidence. Reassignment transfers open commercial tasks, preserving completed attribution and personal Compliance tasks.
## Journeys and records
Landing → email/password login → role-scoped dashboard → merchant search/filter → detail, editing, assignment, checklist, reviews, interactions, history and tasks. Pipeline, Tasks and Compliance Review Queue provide dedicated views. Tasks can be created, edited and completed from merchant details; reminders stay in the app.
Landing → email/password login → role-scoped dashboard → merchant search/filter → detail, editing, assignment, checklist, reviews, interactions, history and tasks. The directory searches company, contact, email and website and combines stage, country, industry and authorized owner filters with eight-record pagination. Search/filter/page state is stored in the URL. Head and Compliance may filter by manager or Unassigned; Managers remain scoped to their own merchants. Desktop uses tables and pipeline columns; mobile uses directory cards and exactly one selected pipeline stage. Detail has URL-addressable Overview, Activity, Onboarding and Tasks tabs; Activity merges notes, interactions, ownership, stage events and compliance outcomes into one newest-first history. Explicit stage controls display server-derived blocking reasons. Pipeline, Tasks and Compliance Review Queue provide dedicated views. Tasks can be created, edited and completed from merchant details; reminders stay in the app.
Merchants include company and primary-contact details, website, country, industry, decimal USD volume estimates, source, nullable manager, stage, timestamps and a concurrency version. Related models retain activities, stage events, checklist changes, review snapshots and task attribution. Mutations and audit history commit atomically and reject stale versions.
Staff creation requires company name, primary-contact name and email; website, country, industry and volume may be completed later. Merchants include company and primary-contact details, website, country, industry, decimal USD volume estimates, source, nullable manager, stage, timestamps and a concurrency version. Related models retain activities, stage events, checklist changes, review snapshots and task attribution. Mutations and audit history commit atomically and reject stale versions.
## Public lead intake
The public landing page introduces merchant crypto-payment onboarding in EN/RU with an inline consultation form. Company name, contact name, work email, website, country, industry and estimated monthly USD volume are required. Industries include Other; zero is a valid volume estimate. The staff-login link remains available on mobile.
`POST /api/public/leads` requires a trusted Origin and a UUID `Idempotency-Key`. Accepted submissions atomically create an unassigned New Lead with source `LANDING_PAGE`, four missing KYB items, an initial stage event and a system-attributed creation activity. Database uniqueness prevents duplicate records on retries, including concurrent requests and API restarts. A changed payload under the same key returns a conflict. Filled honeypots receive the same generic acceptance without creating records.
The endpoint validates on the server and uses bounded process-local IP/email limits. The form preserves inputs after errors, translates field feedback, announces submission states and respects Retry-After. Lead details remain in component memory; only language is stored in the browser. No external notifications are sent.
## Authentication and demo data
@@ -34,4 +42,4 @@ Seeding uses stable IDs, a stored date anchor and a version marker. It preserves
English is the default; EN/RU selection persists in browser storage. Dates use the selected locale and viewer's time zone. Names and notes remain verbatim; canonical status/role labels are translated. Retain the light neutral UI, lime accents, visible focus, touch-sized controls and reduced-motion support.
No merchant creation/deletion UI, staff registration, merchant self-service, real payments, external KYB integration, uploads, external notifications or deployment.
No merchant deletion UI, staff registration, merchant self-service, real payments, external KYB integration, uploads, external notifications or deployment.
+10
View File
@@ -0,0 +1,10 @@
// ISO 3166-1 alpha-2 codes. Display names come from the selected locale's Intl data.
export const countryCodes = (
'AD AE AF AG AI AL AM AO AQ AR AS AT AU AW AX AZ BA BB BD BE BF BG BH BI BJ BL BM BN BO BQ BR BS BT BV BW BY BZ ' +
'CA CC CD CF CG CH CI CK CL CM CN CO CR CU CV CW CX CY CZ DE DJ DK DM DO DZ EC EE EG EH ER ES ET FI FJ FK FM FO FR ' +
'GA GB GD GE GF GG GH GI GL GM GN GP GQ GR GS GT GU GW GY HK HM HN HR HT HU ID IE IL IM IN IO IQ IR IS IT JE JM JO JP ' +
'KE KG KH KI KM KN KP KR KW KY KZ LA LB LC LI LK LR LS LT LU LV LY MA MC MD ME MF MG MH MK ML MM MN MO MP MQ MR MS MT MU MV MW MX MY MZ ' +
'NA NC NE NF NG NI NL NO NP NR NU NZ OM PA PE PF PG PH PK PL PM PN PR PS PT PW PY QA RE RO RS RU RW ' +
'SA SB SC SD SE SG SH SI SJ SK SL SM SN SO SR SS ST SV SX SY SZ TC TD TF TG TH TJ TK TL TM TN TO TR TT TV TW TZ ' +
'UA UG UM US UY UZ VA VC VE VG VI VN VU WF WS YE YT ZA ZM ZW'
).split(' ');
+110
View File
@@ -5,6 +5,9 @@ import {
successfulStages,
statuses,
canSeeReviewQueue,
publicLeadSchema,
publicLeadKeySchema,
countryCodes,
} from './index.js';
describe('browser-safe contracts', () => {
it('keeps rejection outside the successful sequence', () => {
@@ -29,3 +32,110 @@ describe('browser-safe contracts', () => {
expect(canSeeReviewQueue('COMPLIANCE_OFFICER')).toBe(true);
});
});
const lead = {
name: ' Example Company ',
contactName: ' Alex ',
contactEmail: ' [email protected] ',
website: 'example.com',
country: 'gb',
industry: 'OTHER',
estimatedMonthlyVolumeUsd: '25000,5',
};
describe('public lead contracts', () => {
it('normalizes a lead without floating-point amounts', () => {
expect(publicLeadSchema.parse(lead)).toEqual({
name: 'Example Company',
contactName: 'Alex',
contactEmail: '[email protected]',
website: 'https://example.com/',
country: 'GB',
industry: 'OTHER',
estimatedMonthlyVolumeUsd: '25000.50',
companyFax: '',
});
expect(countryCodes).toHaveLength(249);
expect(new Set(countryCodes).size).toBe(249);
});
it('requires every business field and rejects privilege injection', () => {
for (const field of Object.keys(lead)) {
expect(publicLeadSchema.safeParse({ ...lead, [field]: '' }).success, field).toBe(false);
expect(publicLeadSchema.safeParse({ ...lead, [field]: undefined }).success, field).toBe(
false,
);
}
for (const field of ['ownerId', 'status', 'source', 'actorId', 'publicSubmissionKey'])
expect(publicLeadSchema.safeParse({ ...lead, [field]: 'injected' }).success).toBe(false);
});
it('validates websites, countries, names and addresses with translation keys', () => {
for (const website of [
'invalid website',
'https://',
'javascript:alert(1)',
'ftp://example.com',
'https://user:[email protected]',
'x'.repeat(2050),
])
expect(publicLeadSchema.safeParse({ ...lead, website }).success, website).toBe(false);
for (const input of [
{ country: 'ZZ' },
{ industry: 'UNSUPPORTED' },
{ name: ' '.repeat(20) },
{ contactName: 'x'.repeat(201) },
{ contactEmail: 'not an email' },
]) {
const result = publicLeadSchema.safeParse({ ...lead, ...input });
expect(result.success).toBe(false);
if (!result.success)
expect(result.error.issues.every((issue) => issue.message.startsWith('validation.'))).toBe(
true,
);
}
expect(publicLeadKeySchema.safeParse({ idempotencyKey: 'arbitrary' }).success).toBe(false);
});
it('keeps exact decimal limits and supports a zero estimate', () => {
for (const value of ['0', '0.00', '999999999999.99', '1,25'])
expect(
publicLeadSchema.safeParse({ ...lead, estimatedMonthlyVolumeUsd: value }).success,
).toBe(true);
for (const value of ['-1', '1e3', '1.001', '1000000000000', '25,000', 'NaN', 'Infinity', '01'])
expect(
publicLeadSchema.safeParse({ ...lead, estimatedMonthlyVolumeUsd: value }).success,
value,
).toBe(false);
});
});
describe('daily sales contracts', () => {
it('allows incomplete staff leads while enforcing core contact fields and strict ownership boundaries', async () => {
const { merchantCreateSchema, merchantEditSchema } = await import('./index.js');
const basic = { name: 'Acme', contactName: 'Jo', contactEmail: '[email protected]' };
expect(merchantCreateSchema.safeParse(basic).success).toBe(true);
expect(
merchantCreateSchema.parse({ ...basic, estimatedMonthlyVolumeUsd: '0' })
.estimatedMonthlyVolumeUsd,
).toBe('0.00');
for (const field of ['name', 'contactName', 'contactEmail'])
expect(merchantCreateSchema.safeParse({ ...basic, [field]: '' }).success).toBe(false);
for (const field of ['status', 'actorId', 'publicSubmissionKey', 'version'])
expect(merchantCreateSchema.safeParse({ ...basic, [field]: 'injected' }).success).toBe(false);
expect(merchantEditSchema.safeParse({ version: 1, status: 'LIVE' }).success).toBe(false);
expect(merchantEditSchema.safeParse({ version: 1, ownerId: 'manager' }).success).toBe(false);
});
it('requires a nonblank rejection reason and validates directory filters', async () => {
const { transitionSchema } = await import('./index.js');
for (const reason of ['', ' ', undefined])
expect(transitionSchema.safeParse({ version: 1, toStatus: 'REJECTED', reason }).success).toBe(
false,
);
expect(
transitionSchema.parse({ version: 1, toStatus: 'REJECTED', reason: ' Closed ' }).reason,
).toBe('Closed');
for (const query of [{ country: 'ZZ' }, { industry: 'bad' }, { ownerId: '' }, { page: 1.5 }])
expect(merchantQuerySchema.safeParse(query).success).toBe(false);
expect(
merchantQuerySchema.parse({ country: 'GB', industry: 'OTHER', ownerId: 'unassigned' })
.ownerId,
).toBe('unassigned');
});
});
+181 -21
View File
@@ -1,4 +1,6 @@
import { z } from 'zod';
import { countryCodes } from './countries.js';
export { countryCodes } from './countries.js';
export const roles = ['HEAD_OF_SALES', 'COMPLIANCE_OFFICER', 'ACCOUNT_MANAGER'] as const;
export const successfulStages = [
@@ -27,6 +29,12 @@ export type LoginInput = z.input<typeof loginSchema>;
export const merchantQuerySchema = z.object({
search: z.string().trim().max(100).default(''),
status: statusSchema.optional(),
country: z
.string()
.refine((value) => countryCodes.includes(value))
.optional(),
industry: z.enum(['ECOMMERCE', 'SOFTWARE', 'TRAVEL', 'SERVICES', 'OTHER']).optional(),
ownerId: z.string().min(1).max(200).optional(),
page: z.coerce.number().int().min(1).max(10000).default(1),
});
export const taskFilters = ['ALL', 'OPEN', 'OVERDUE', 'UPCOMING', 'DONE'] as const;
@@ -44,10 +52,14 @@ export const errorCodes = [
'CONFLICT',
'WORKFLOW_INVALID',
'REVIEW_LOCKED',
'IDEMPOTENCY_CONFLICT',
] as const;
export const apiErrorSchema = z.object({
code: z.enum(errorCodes),
issues: z.array(z.object({ path: z.string(), code: z.string() })).optional(),
blockingReasons: z
.array(z.object({ code: z.string(), fields: z.array(z.string()).optional() }))
.optional(),
});
export const userSchema = z.object({
id: z.string(),
@@ -60,9 +72,9 @@ const date = z.iso.datetime();
export const merchantSchema = z.object({
id: z.string(),
name: z.string(),
website: z.string(),
industry: z.string(),
country: z.string(),
website: z.string().nullable(),
industry: z.string().nullable(),
country: z.string().nullable(),
contactName: z.string(),
contactEmail: z.string(),
legalName: z.string().nullable(),
@@ -93,7 +105,7 @@ export const eventSchema = z.object({
occurredAt: date,
note: z.string().nullable(),
merchant: z.object({ id: z.string(), name: z.string() }),
actor: z.object({ name: z.string() }),
actor: z.object({ name: z.string() }).nullable(),
});
export type StageEvent = z.infer<typeof eventSchema>;
export const taskSchema = z.object({
@@ -126,7 +138,7 @@ export const activitySchema = z.object({
text: z.string(),
occurredAt: date,
updatedAt: date,
actor: z.object({ id: z.string(), name: z.string() }),
actor: z.object({ id: z.string(), name: z.string() }).nullable(),
merchant: z.object({ id: z.string(), name: z.string() }),
});
export const reviewSchema = z.object({
@@ -139,6 +151,28 @@ export const reviewSchema = z.object({
submittedBy: z.object({ name: z.string() }),
reviewer: z.object({ name: z.string() }).nullable(),
});
export const blockingReasonSchema = z.object({
code: z.enum([
'ASSIGNMENT_REQUIRED',
'CONTACT_REQUIRED',
'QUALIFICATION_INCOMPLETE',
'DOCUMENTS_REQUIRED',
'REVIEW_PENDING',
'APPROVAL_REQUIRED',
'COMPLIANCE_ONLY',
'SALES_ONLY',
]),
fields: z.array(z.string()).optional(),
});
export const workflowActionSchema = z.object({
kind: z.enum(['ADVANCE', 'REJECT', 'REVIEW']),
toStatus: statusSchema.nullable(),
enabled: z.boolean(),
reasonRequired: z.boolean(),
blockingReasons: z.array(blockingReasonSchema),
});
export type WorkflowAction = z.infer<typeof workflowActionSchema>;
export type BlockingReason = z.infer<typeof blockingReasonSchema>;
export const capabilitiesSchema = z.object({
editCommercial: z.boolean(),
editIdentity: z.boolean(),
@@ -148,7 +182,42 @@ export const capabilitiesSchema = z.object({
activityKinds: z.array(z.enum(activityKinds)),
manageTaskKind: z.enum(['COMMERCIAL', 'COMPLIANCE']),
nextStage: statusSchema.nullable(),
actions: z.array(workflowActionSchema),
});
export type Capabilities = z.infer<typeof capabilitiesSchema>;
const historyBase = z.object({
id: z.string(),
occurredAt: date,
actor: z.object({ name: z.string() }).nullable(),
});
export const historyEntrySchema = z.discriminatedUnion('kind', [
historyBase.extend({
kind: z.literal('INTERACTION'),
activityId: z.string().nullable(),
activityKind: z.enum(activityKinds),
text: z.string(),
updatedAt: date,
}),
historyBase.extend({
kind: z.literal('STAGE'),
fromStatus: statusSchema.nullable(),
toStatus: statusSchema,
reason: z.string().nullable(),
}),
historyBase.extend({
kind: z.literal('OWNERSHIP'),
previousOwner: z.object({ id: z.string(), name: z.string() }).nullable(),
owner: z.object({ id: z.string(), name: z.string() }).nullable(),
}),
historyBase.extend({
kind: z.literal('REVIEW'),
decision: z.enum(['APPROVED', 'CORRECTIONS', 'REJECTED']),
cycle: z.number(),
reason: z.string().nullable(),
}),
historyBase.extend({ kind: z.literal('AUDIT'), text: z.string() }),
]);
export type HistoryEntry = z.infer<typeof historyEntrySchema>;
export const merchantDetailSchema = merchantSchema.extend({
checklist: z.array(
z.object({
@@ -181,6 +250,7 @@ export const merchantDetailSchema = merchantSchema.extend({
activities: z.array(activitySchema),
reviews: z.array(reviewSchema),
capabilities: capabilitiesSchema,
history: z.array(historyEntrySchema),
});
export type MerchantDetail = z.infer<typeof merchantDetailSchema>;
export const dashboardSchema = z.object({
@@ -194,10 +264,98 @@ export const dashboardSchema = z.object({
recentActivities: z.array(activitySchema),
});
export const pipelineSchema = z.array(merchantSchema);
export const pipelineBoardSchema = z.array(
merchantSchema.extend({ capabilities: capabilitiesSchema }),
);
export const merchantFiltersSchema = z.object({
countries: z.array(z.string()),
industries: z.array(z.string()),
owners: z.array(z.object({ id: z.string(), name: z.string() })),
canCreate: z.boolean(),
canFilterOwner: z.boolean(),
});
export const healthSchema = z.object({ status: z.literal('ok'), database: z.literal('connected') });
export const sources = ['INBOUND', 'OUTBOUND', 'REFERRAL', 'PARTNER', 'EVENT'] as const;
export const industries = ['ECOMMERCE', 'SOFTWARE', 'TRAVEL', 'SERVICES'] as const;
export const sources = [
'INBOUND',
'OUTBOUND',
'REFERRAL',
'PARTNER',
'EVENT',
'LANDING_PAGE',
] as const;
export const industries = ['ECOMMERCE', 'SOFTWARE', 'TRAVEL', 'SERVICES', 'OTHER'] as const;
const leadName = z
.string({ error: 'validation.required' })
.trim()
.min(1, 'validation.required')
.max(200, 'validation.nameMax');
const leadWebsite = z
.string({ error: 'validation.website' })
.trim()
.min(1, 'validation.required')
.max(2048, 'validation.website')
.transform((value) => (/^[a-z][a-z\d+.-]*:/i.test(value) ? value : `https://${value}`))
.pipe(z.url({ error: 'validation.website' }).max(2048, 'validation.website'))
.refine((value) => {
try {
const url = new URL(value);
return ['http:', 'https:'].includes(url.protocol) && !url.username && !url.password;
} catch {
return false;
}
}, 'validation.website')
.transform((value) => new URL(value).href);
export const publicLeadSchema = z
.object({
name: leadName,
contactName: leadName,
contactEmail: z
.string({ error: 'validation.email' })
.trim()
.pipe(z.email({ error: 'validation.email' }).max(254, 'validation.email'))
.transform((value) => value.toLowerCase()),
website: leadWebsite,
country: z
.string({ error: 'validation.country' })
.trim()
.toUpperCase()
.refine((value) => countryCodes.includes(value), 'validation.country'),
industry: z
.string({ error: 'validation.industry' })
.pipe(z.enum(industries, { error: 'validation.industry' })),
estimatedMonthlyVolumeUsd: z
.string({ error: 'validation.volume' })
.trim()
.transform((value) => value.replace(',', '.'))
.pipe(z.string().regex(/^(?:0|[1-9]\d{0,11})(?:\.\d{1,2})?$/, 'validation.volume'))
.transform((value) => {
const [whole, fraction = ''] = value.split('.');
return `${whole}.${fraction.padEnd(2, '0')}`;
}),
companyFax: z.string().max(512).default(''),
})
.strict();
export type PublicLeadInput = z.input<typeof publicLeadSchema>;
export type PublicLead = z.output<typeof publicLeadSchema>;
export const merchantCreateSchema = publicLeadSchema
.omit({ companyFax: true })
.extend({
website: leadWebsite.nullable().optional(),
country: publicLeadSchema.shape.country.nullable().optional(),
industry: publicLeadSchema.shape.industry.nullable().optional(),
estimatedMonthlyVolumeUsd: publicLeadSchema.shape.estimatedMonthlyVolumeUsd
.nullable()
.optional(),
ownerId: z.string().min(1).max(200).nullable().optional(),
source: z.enum(sources).nullable().optional(),
})
.strict();
export const merchantCreatedSchema = z.object({ id: z.string(), version: z.number().int() });
export const publicLeadAcceptedSchema = z.object({ ok: z.literal(true) });
export const publicLeadKeySchema = z.object({
idempotencyKey: z.uuid({ error: 'validation.submissionKey' }),
});
const text = z
.string()
.min(1)
@@ -211,28 +369,30 @@ export const merchantEditSchema = versionSchema
legalName: text.optional(),
registrationNumber: optionalText.optional(),
address: optionalText.optional(),
website: z
.url()
.refine((v) => /^https?:\/\//.test(v))
.optional(),
country: z
.string()
.regex(/^[A-Z]{2}$/)
.optional(),
industry: z.enum(industries).optional(),
website: leadWebsite.nullable().optional(),
country: publicLeadSchema.shape.country.nullable().optional(),
industry: z.enum(industries).nullable().optional(),
contactName: text.optional(),
contactEmail: z.email().max(254).optional(),
contactPhone: optionalText.optional(),
contactTitle: optionalText.optional(),
estimatedMonthlyVolumeUsd: z
.string()
.regex(/^(?:0|[1-9]\d{0,11})(?:\.\d{1,2})?$/)
estimatedMonthlyVolumeUsd: publicLeadSchema.shape.estimatedMonthlyVolumeUsd
.nullable()
.optional(),
source: z.enum(sources).optional(),
source: z.enum(sources).nullable().optional(),
})
.strict();
export const assignmentSchema = versionSchema.extend({ ownerId: text }).strict();
export const transitionSchema = versionSchema.extend({ toStatus: statusSchema }).strict();
export const transitionSchema = versionSchema
.extend({
toStatus: statusSchema,
reason: z.string().trim().max(2000).optional(),
})
.strict()
.superRefine((value, ctx) => {
if (value.toStatus === 'REJECTED' && !value.reason)
ctx.addIssue({ code: 'custom', path: ['reason'], message: 'validation.required' });
});
export const checklistEditSchema = versionSchema
.extend({
state: z.enum(['MISSING', 'RECEIVED']),
@@ -0,0 +1,5 @@
ALTER TABLE "Merchant" ADD COLUMN "publicSubmissionKey" TEXT,
ADD COLUMN "publicSubmissionHash" TEXT;
CREATE UNIQUE INDEX "Merchant_publicSubmissionKey_key" ON "Merchant"("publicSubmissionKey");
ALTER TABLE "Activity" ALTER COLUMN "actorId" DROP NOT NULL;
ALTER TABLE "StatusEvent" ALTER COLUMN "actorId" DROP NOT NULL;
@@ -0,0 +1,3 @@
ALTER TABLE "Merchant" ALTER COLUMN "website" DROP NOT NULL;
ALTER TABLE "Merchant" ALTER COLUMN "country" DROP NOT NULL;
ALTER TABLE "Merchant" ALTER COLUMN "industry" DROP NOT NULL;
+9 -7
View File
@@ -86,9 +86,9 @@ model Session {
model Merchant {
id String @id @default(uuid())
name String
website String
industry String
country String
website String?
industry String?
country String?
contactName String
contactEmail String
legalName String?
@@ -98,6 +98,8 @@ model Merchant {
contactTitle String?
estimatedMonthlyVolumeUsd Decimal? @db.Decimal(18, 2)
source String?
publicSubmissionKey String? @unique
publicSubmissionHash String?
status MerchantStatus @default(NEW_LEAD)
ownerId String?
createdAt DateTime @default(now())
@@ -118,13 +120,13 @@ model Merchant {
model StatusEvent {
id String @id @default(uuid())
merchantId String
actorId String
actorId String?
fromStatus MerchantStatus?
toStatus MerchantStatus
occurredAt DateTime @default(now())
note String?
merchant Merchant @relation(fields: [merchantId], references: [id], onDelete: Cascade)
actor User @relation(fields: [actorId], references: [id])
actor User? @relation(fields: [actorId], references: [id], onDelete: Restrict)
@@index([merchantId, occurredAt])
@@index([occurredAt])
}
@@ -173,14 +175,14 @@ model Task {
model Activity {
id String @id @default(uuid())
merchantId String
actorId String
actorId String?
kind ActivityKind
text String
occurredAt DateTime @default(now())
updatedAt DateTime @default(now()) @updatedAt
metadata Json?
merchant Merchant @relation(fields: [merchantId], references: [id], onDelete: Cascade)
actor User @relation(fields: [actorId], references: [id])
actor User? @relation(fields: [actorId], references: [id], onDelete: Restrict)
@@index([merchantId, occurredAt])
@@index([occurredAt])
}
+8 -1
View File
@@ -21,5 +21,12 @@ run('docker', ['compose', '--profile', 'test', 'up', '-d', '--wait', 'db-test'])
run('pnpm', ['exec', 'turbo', 'run', 'build']);
run('pnpm', ['--filter', '@merchantflow/database', 'migrate']);
run('pnpm', ['--filter', '@merchantflow/database', 'seed']);
if (mode === 'integration') run('node', ['--test', 'apps/api/test/integration.test.mjs']);
if (mode === 'integration')
run('node', [
'--test',
'--test-concurrency=1',
'apps/api/test/integration.test.mjs',
'apps/api/test/public-leads.test.mjs',
'apps/api/test/sales-workspace.test.mjs',
]);
else run('pnpm', ['exec', 'playwright', 'test']);
+239
View File
@@ -0,0 +1,239 @@
import { test, expect, type Page } from '@playwright/test';
import { createDatabase } from '../packages/database/dist/index.js';
if (!process.env.DATABASE_URL?.endsWith('/merchantflow_test'))
throw new Error('Landing tests require the isolated test database');
const db = createDatabase(process.env.DATABASE_URL);
const submissionKeys = new Set<string>();
test.beforeEach(({ page }) => {
page.on('request', (request) => {
if (request.url().endsWith('/api/public/leads')) {
const key = request.headers()['idempotency-key'];
if (key) submissionKeys.add(key);
}
});
});
test.afterEach(async () => {
await db.merchant.deleteMany({ where: { publicSubmissionKey: { in: [...submissionKeys] } } });
submissionKeys.clear();
});
test.afterAll(() => db.$disconnect());
const fields = [
'name',
'contactName',
'contactEmail',
'website',
'country',
'industry',
'estimatedMonthlyVolumeUsd',
] as const;
async function fill(page: Page) {
const email = `browser-${crypto.randomUUID()}@example.test`;
await page.locator('#lead-name').fill('MerchantFlow browser fixture');
await page.locator('#lead-contactName').fill('Test Contact');
await page.locator('#lead-contactEmail').fill(email);
await page.locator('#lead-website').fill('example.test');
await page.locator('#lead-country').selectOption('GB');
await page.locator('#lead-industry').selectOption('OTHER');
await page.locator('#lead-estimatedMonthlyVolumeUsd').fill('12500,50');
return email;
}
async function noOverflow(page: Page) {
expect(await page.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth)).toBe(
true,
);
}
for (const language of ['en', 'ru'])
for (const width of [375, 1440]) {
test.describe(`landing ${language} ${width}px`, () => {
test.use({ viewport: { width, height: 1000 } });
test('accessible consultation, bilingual errors, retained values and real persistence', async ({
page,
}, info) => {
const runtimeErrors: string[] = [];
page.on('pageerror', (error) => runtimeErrors.push(error.message));
await page.addInitScript(
(lang) => localStorage.setItem('merchantflow.language', lang),
language,
);
await page.goto('/');
await expect(page.locator('html')).toHaveAttribute('lang', language);
await expect(
page.getByRole('link', { name: /Staff login|Вход для команды/ }),
).toBeVisible();
await expect(page.getByRole('heading', { level: 1 })).toBeVisible();
await noOverflow(page);
await page.screenshot({ path: info.outputPath('landing.png'), fullPage: true });
await page.getByRole('link', { name: /Let’s talk payments|Обсудим платежи/ }).click();
await expect(page.locator('#lead-name')).toBeFocused();
const submit = page.locator('button[type="submit"]');
await submit.click();
for (const name of fields)
await expect(page.locator(`#lead-${name}`)).toHaveAttribute('aria-invalid', 'true');
await expect(page.locator('#lead-name')).toBeFocused();
await expect(page.locator('#lead-name-error')).toHaveText(
language === 'en' ? 'Please complete this field.' : 'Заполните это поле.',
);
await noOverflow(page);
await page.screenshot({ path: info.outputPath('validation.png'), fullPage: true });
const email = await fill(page);
await page
.getByRole('button', { name: language === 'en' ? 'Русский' : 'English', exact: true })
.click();
await expect(page.locator('#lead-name')).toHaveValue('MerchantFlow browser fixture');
await expect(page.locator('#lead-estimatedMonthlyVolumeUsd')).toHaveValue('12500,50');
await expect(page.locator('#lead-country')).toHaveValue('GB');
await page
.getByRole('button', { name: language === 'en' ? 'English' : 'Русский', exact: true })
.click();
const trap = page.locator('input[name="companyFax"]');
await expect(trap).toHaveAttribute('tabindex', '-1');
await expect(trap.locator('..')).toHaveAttribute('aria-hidden', 'true');
await page.locator('#lead-estimatedMonthlyVolumeUsd').focus();
await page.keyboard.press('Tab');
await expect(submit).toBeFocused();
expect(await page.locator('form').ariaSnapshot()).not.toContain('companyFax');
await page.route('**/api/public/leads', (route) => route.abort('failed'));
await submit.click();
await expect(page.locator('.lead-feedback')).toContainText(
language === 'en' ? 'couldn’t confirm' : 'Не удалось подтвердить',
);
await expect(page.locator('#lead-contactEmail')).toHaveValue(email);
await page.unroute('**/api/public/leads');
await page.route('**/api/public/leads', (route) =>
route.fulfill({
status: 400,
json: {
code: 'VALIDATION_ERROR',
issues: [{ path: 'contactEmail', code: 'validation.email' }],
},
}),
);
await submit.click();
await expect(page.locator('#lead-contactEmail-error')).toHaveText(
language === 'en' ? 'Enter a valid email address.' : 'Введите корректный адрес почты.',
);
await expect(page.locator('#lead-contactEmail')).toBeFocused();
await page.unroute('**/api/public/leads');
await page.route('**/api/public/leads', (route) =>
route.fulfill({
status: 429,
headers: { 'Retry-After': '1' },
json: { code: 'TOO_MANY_REQUESTS' },
}),
);
await submit.click();
await expect(submit).toBeDisabled();
await expect(page.locator('.lead-feedback')).toContainText(
language === 'en' ? 'wait' : 'через',
);
await expect(submit).toBeEnabled();
await expect(page.locator('#lead-estimatedMonthlyVolumeUsd')).toHaveValue('12500,50');
await page.unroute('**/api/public/leads');
await page.route('**/api/public/leads', (route) =>
route.fulfill({ status: 503, json: { code: 'DATABASE_UNAVAILABLE' } }),
);
await submit.click();
await expect(page.locator('.lead-feedback')).toContainText(
language === 'en' ? 'couldn’t complete' : 'Не удалось отправить',
);
await page.unroute('**/api/public/leads');
let release = () => {};
const held = new Promise<void>((resolve) => {
release = resolve;
});
await page.route('**/api/public/leads', async (route) => {
await held;
await route.continue();
});
await submit.click();
await expect(submit).toBeDisabled();
await expect(page.locator('form')).toHaveAttribute('aria-busy', 'true');
release();
await expect(page.locator('.lead-success')).toBeVisible();
await expect(page.locator('.lead-success')).toBeFocused();
await noOverflow(page);
await page.screenshot({ path: info.outputPath('success.png'), fullPage: true });
expect(submissionKeys.size).toBe(1);
const merchants = await db.merchant.findMany({
where: { contactEmail: email },
include: { activities: true, events: true, checklist: true },
});
expect(merchants).toHaveLength(1);
expect(merchants[0]?.source).toBe('LANDING_PAGE');
expect(merchants[0]?.ownerId).toBeNull();
expect(merchants[0]?.activities).toHaveLength(1);
expect(merchants[0]?.events).toHaveLength(1);
expect(merchants[0]?.checklist).toHaveLength(4);
expect(runtimeErrors).toEqual([]);
});
});
}
test('lost response retry reuses its key and system history renders in the CRM', async ({
page,
}) => {
await page.goto('/');
const email = await fill(page);
await page.route('**/api/public/leads', async (route) => {
const response = await route.fetch();
expect(response.status()).toBe(202);
await route.abort('failed');
});
await page.locator('button[type="submit"]').click();
await expect(page.locator('.lead-feedback')).toBeVisible();
expect(await db.merchant.count({ where: { contactEmail: email } })).toBe(1);
await page.unroute('**/api/public/leads');
await page.locator('button[type="submit"]').click();
await expect(page.locator('.lead-success')).toBeVisible();
expect(submissionKeys.size).toBe(1);
const records = await db.merchant.findMany({
where: { contactEmail: email },
include: { activities: true },
});
expect(records).toHaveLength(1);
expect(records[0]?.activities).toHaveLength(1);
await page.getByRole('link', { name: 'Staff login' }).click();
await page.getByLabel('Email address').fill('[email protected]');
await page.getByLabel('Password', { exact: true }).fill('MerchantFlow123!');
await page.getByRole('button', { name: 'Sign in to workspace', exact: true }).click();
await expect(page).toHaveURL(/\/app$/);
await page.goto(`/app/merchants/${records[0]?.id}`);
await expect(page.locator('h1')).toHaveText('MerchantFlow browser fixture');
await expect(page.getByText('Landing page', { exact: true })).toBeVisible();
await page.getByRole('tab', { name: 'Activity', exact: true }).click();
await expect(page.getByText('Lead received from landing page', { exact: true })).toBeVisible();
await page.getByRole('button', { name: 'Русский', exact: true }).click();
await expect(page.getByText('Заявка получена с сайта', { exact: true })).toBeVisible();
await page.getByRole('tab', { name: 'Обзор', exact: true }).click();
await expect(page.getByRole('definition').filter({ hasText: /^Сайт$/ })).toBeVisible();
});
test('changing the normalized payload creates a new key; reduced motion and locale persist', async ({
page,
}) => {
await page.goto('/');
await fill(page);
await page.route('**/api/public/leads', (route) => route.abort('failed'));
await page.locator('button[type="submit"]').click();
await expect(page.locator('.lead-feedback')).toBeVisible();
await page.locator('#lead-name').fill('An edited request');
await page.locator('button[type="submit"]').click();
await expect(page.locator('.lead-feedback')).toBeVisible();
await expect.poll(() => submissionKeys.size).toBe(2);
await page.emulateMedia({ reducedMotion: 'reduce' });
expect(
await page
.locator('.lead-submit')
.evaluate((el) => parseFloat(getComputedStyle(el).transitionDuration)),
).toBeLessThan(0.01);
await page.getByRole('button', { name: 'Русский', exact: true }).click();
await page.reload();
await expect(page.locator('html')).toHaveAttribute('lang', 'ru');
await expect(page.locator('#lead-name')).toHaveValue('');
});
+239
View File
@@ -0,0 +1,239 @@
import { test, expect, type Page } from '@playwright/test';
import { createDatabase } from '../packages/database/dist/index.js';
if (!process.env.DATABASE_URL?.endsWith('/merchantflow_test'))
throw new Error('Daily sales browser tests require the isolated database');
const db = createDatabase(process.env.DATABASE_URL);
const names = new Set<string>();
test.afterEach(async () => {
await db.merchant.deleteMany({ where: { name: { in: [...names] } } });
names.clear();
});
test.afterAll(() => db.$disconnect());
async function login(page: Page, account = 'head') {
await page.goto('/login');
await page.getByLabel(/Email address|Электронная почта/).fill(`${account}@merchantflow.test`);
await page.getByLabel(/^Password$|^Пароль$/).fill('MerchantFlow123!');
await page
.getByRole('button', { name: /^Sign in to workspace$|^Войти в рабочее пространство$/ })
.click();
await expect(page).toHaveURL(/\/app$/);
}
async function save(page: Page) {
await page
.getByRole('dialog')
.getByRole('button', { name: /^(Save changes|Сохранить изменения)$/ })
.click();
await expect(page.getByRole('dialog')).not.toBeVisible();
}
async function create(page: Page, name: string) {
names.add(name);
await page.goto('/app/merchants');
await page.getByRole('button', { name: /^(Add merchant|Добавить мерчанта)$/ }).click();
const dialog = page.getByRole('dialog');
await dialog.getByLabel(/^(Company name|Название компании)$/).fill(name);
await dialog.getByLabel(/^(Primary contact|Основной контакт)$/).fill(`Contact ${name}`);
await dialog.getByLabel(/^(Contact email|Email контакта)$/).fill('[email protected]');
await save(page);
await expect(page.locator('h1')).toHaveText(name);
return new URL(page.url()).pathname.split('/').at(-1)!;
}
async function noOverflow(page: Page) {
expect(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth)).toBe(true);
}
for (const language of ['en', 'ru'])
for (const width of [390, 1440]) {
test.describe(`daily sales ${language} ${width}`, () => {
test.use({ viewport: { width, height: 1000 } });
test('creation, filters, history, pipeline actions and rejection use persistent API data', async ({
page,
}, info) => {
const errors: string[] = [];
page.on('pageerror', (error) => errors.push(error.message));
await page.addInitScript(
(locale) => localStorage.setItem('merchantflow.language', locale),
language,
);
await login(page);
const name = `Daily workspace ${language} ${width}`;
const id = await create(page, name);
await expect(
page.getByText(/Assign a manager before progressing|Назначьте менеджера для перехода/),
).toBeVisible();
await expect(
page.getByText(/Log a call or email before|Запишите звонок или письмо/),
).toBeVisible();
await page.getByRole('button', { name: /^(Assign manager|Назначить менеджера)$/ }).click();
await page
.getByRole('dialog')
.getByLabel(/^(Account manager|Аккаунт-менеджер)$/)
.selectOption('user-manager1');
await save(page);
await page.getByRole('tab', { name: /^(Activity|Активность)$/ }).click();
await page
.getByRole('button', { name: /^(Log interaction|Добавить взаимодействие)$/ })
.click();
await page
.getByRole('dialog')
.getByLabel(/^(Interaction type|Тип взаимодействия)$/)
.selectOption('CALL');
await page
.getByRole('dialog')
.getByLabel(/^(Details|Подробности)$/)
.fill('A real discovery call recorded through the API.');
await save(page);
await expect(
page.getByText('A real discovery call recorded through the API.', { exact: true }),
).toBeVisible();
await expect(
page.getByText(
/Manager changed: Unassigned → Alex Morgan|Менеджер изменён: Не назначен → Alex Morgan/,
),
).toBeVisible();
await page.reload();
await expect(page.getByRole('tab', { name: /^(Activity|Активность)$/ })).toHaveAttribute(
'aria-selected',
'true',
);
const activityTab = page.getByRole('tab', { name: /^(Activity|Активность)$/ });
await activityTab.focus();
await activityTab.press('End');
await expect(page.getByRole('tab', { name: /^(Tasks|Задачи)$/ })).toHaveAttribute(
'aria-selected',
'true',
);
await page.getByRole('tab', { name: /^(Tasks|Задачи)$/ }).press('Home');
await expect(page.getByRole('tab', { name: /^(Overview|Обзор)$/ })).toHaveAttribute(
'aria-selected',
'true',
);
await page.getByRole('tab', { name: /^(Overview|Обзор)$/ }).press('ArrowRight');
await expect(activityTab).toBeFocused();
await page.getByRole('button', { name: /^(Edit merchant|Изменить мерчанта)$/ }).click();
const dialog = page.getByRole('dialog');
await dialog.getByLabel(/^(Website|Сайт)$/).fill('https://daily.example.test');
await dialog.getByLabel(/^(Country code|Код страны)$/).fill('GB');
await dialog.getByLabel(/^(Industry|Отрасль)$/).selectOption('OTHER');
await dialog
.getByLabel(/^(Estimated monthly processing \(USD\)|Месячный объём обработки \(USD\))$/)
.fill('0');
await save(page);
await page.goto('/app/merchants');
await page
.getByRole('textbox', { name: /Search merchants|Название мерчанта/ })
.fill(`Contact ${name}`);
await page
.getByRole('combobox', { name: /^(All countries|Все страны)$/ })
.selectOption('GB');
await page
.getByRole('combobox', { name: /^(All industries|Все отрасли)$/ })
.selectOption('OTHER');
await page
.getByRole('combobox', { name: /^(All managers|Все менеджеры)$/ })
.selectOption('user-manager1');
await expect(page).toHaveURL(/country=GB.*industry=OTHER.*ownerId=user-manager1/);
await expect(page.getByRole('link', { name: new RegExp(name) }).first()).toBeVisible();
await noOverflow(page);
await page.screenshot({ path: info.outputPath('daily-directory.png'), fullPage: true });
const directory = page.url();
await page
.getByRole('link', { name: new RegExp(name) })
.first()
.click();
await page.getByRole('tab', { name: /^(Activity|Активность)$/ }).click();
await page.getByRole('link', { name: /Back to merchants|К списку мерчантов/ }).click();
await expect(page).toHaveURL(directory);
await page.reload();
await expect(
page.getByRole('textbox', { name: /Search merchants|Название мерчанта/ }),
).toHaveValue(`Contact ${name}`);
await page.goto(`${directory}&page=9999`);
await expect(page).not.toHaveURL(/page=/);
await page.goto('/app/pipeline?stage=NEW_LEAD');
const card = page
.locator('article')
.filter({ has: page.getByRole('link', { name: new RegExp(name) }) });
await card.getByRole('button', { name: /Move to Contacted|Перевести: Контакт/ }).click();
await expect
.poll(async () => (await (await page.request.get(`/api/merchants/${id}`)).json()).status)
.toBe('CONTACTED');
if (width === 390) await page.getByRole('combobox').selectOption('CONTACTED');
const contactedCard = page
.getByRole('region', {
name: language === 'en' ? 'Contacted' : 'Контакт установлен',
exact: true,
})
.locator('article')
.filter({ has: page.getByRole('link', { name: new RegExp(name) }) });
await expect(contactedCard).toBeVisible();
await contactedCard.getByRole('link', { name: new RegExp(name) }).click();
await expect(page).toHaveURL(new RegExp(`/app/merchants/${id}$`));
await expect(page.locator('h1')).toHaveText(name);
await page
.getByRole('button', { name: /Move to Qualified|Перевести: Квалифицирован/ })
.click();
await expect
.poll(async () => (await (await page.request.get(`/api/merchants/${id}`)).json()).status)
.toBe('QUALIFIED');
await page.getByRole('button', { name: /^(Reject merchant|Отклонить мерчанта)$/ }).click();
await page
.getByRole('dialog')
.getByRole('button', { name: /Save changes|Сохранить изменения/ })
.click();
await expect(
page.getByRole('dialog').getByLabel(/Rejection reason|Причина отклонения/),
).toHaveAttribute('aria-invalid', 'true');
await page
.getByRole('dialog')
.getByLabel(/Rejection reason|Причина отклонения/)
.fill('Commercial terms were declined.');
await save(page);
await expect(page.getByText(/This is a final stage|Это финальный этап/)).toBeVisible();
await page.getByRole('tab', { name: /^(Activity|Активность)$/ }).click();
await expect(
page.getByText('Commercial terms were declined.', { exact: true }),
).toBeVisible();
await page.screenshot({ path: info.outputPath('daily-history.png'), fullPage: true });
await page.goto('/app/pipeline?stage=REJECTED');
await expect(card).toBeVisible();
if (width === 390)
expect(await page.locator('section[aria-label]:visible').count()).toBe(1);
await noOverflow(page);
await page.screenshot({ path: info.outputPath('daily-pipeline.png'), fullPage: true });
expect(errors).toEqual([]);
});
});
}
test('manager creation assigns self and stale edits keep unsaved form values', async ({ page }) => {
await login(page, 'alex');
const id = await create(page, 'Daily workspace manager');
const merchant = await (await page.request.get(`/api/merchants/${id}`)).json();
expect(merchant.owner.id).toBe('user-manager1');
await expect(page.getByRole('button', { name: 'Assign manager', exact: true })).toHaveCount(0);
await page.getByRole('button', { name: 'Edit merchant', exact: true }).click();
await page.getByRole('dialog').getByLabel('Contact title', { exact: true }).fill('Unsaved title');
const concurrent = await page.request.post(`/api/merchants/${id}/activities`, {
headers: { origin: 'http://127.0.0.1:5174' },
data: { version: merchant.version, kind: 'NOTE', text: 'Concurrent update' },
});
expect(concurrent.ok()).toBe(true);
await page.getByRole('dialog').getByRole('button', { name: 'Save changes', exact: true }).click();
await expect(page.getByRole('dialog').getByRole('alert')).toBeVisible();
await expect(page.getByRole('dialog').getByLabel('Contact title', { exact: true })).toHaveValue(
'Unsaved title',
);
await save(page);
await expect(page.getByText('Unsaved title', { exact: true })).toBeVisible();
await page.goto('/app/merchants?ownerId=user-manager2');
await expect(page).not.toHaveURL(/ownerId/);
await expect(page.getByRole('combobox', { name: 'All managers' })).toHaveCount(0);
await page.getByRole('button', { name: 'Sign out', exact: true }).click();
await login(page, 'sam');
expect((await page.request.get(`/api/merchants/${id}`)).status()).toBe(404);
await page.getByRole('button', { name: 'Sign out', exact: true }).click();
await login(page, 'compliance');
await page.goto('/app/merchants');
await expect(page.getByRole('button', { name: 'Add merchant', exact: true })).toHaveCount(0);
});
+14 -6
View File
@@ -64,6 +64,7 @@ for (const language of ['en', 'ru'])
.first()
.click();
await expect(page.locator('h1')).toHaveText('Luma Labs');
await page.getByRole('tab', { name: /^(Onboarding|Онбординг)$/ }).click();
await expect(
page.getByText(/Please clarify the beneficial ownership/).first(),
).toBeVisible();
@@ -82,7 +83,9 @@ for (const language of ['en', 'ru'])
await page.keyboard.press('Escape');
await expect(page.getByRole('dialog')).not.toBeVisible();
await page.goto('/app/merchants');
await page.getByRole('combobox').selectOption('LIVE');
await page
.getByRole('combobox', { name: /Filter by stage|Фильтр по этапу/ })
.selectOption('LIVE');
await expect(page.getByRole('link', { name: /Sunday Market/ }).first()).toBeVisible();
await page.getByRole('textbox').fill('no-such-merchant');
await expect(page.getByText(/No merchants found|Мерчанты не найдены/)).toBeVisible();
@@ -92,9 +95,8 @@ for (const language of ['en', 'ru'])
await expect(page.locator('h1')).toHaveText(language === 'en' ? 'Pipeline' : 'Воронка');
if (width === 390) await page.getByRole('combobox').selectOption('KYB');
await expect(page.getByRole('link', { name: /Luma Labs/ })).toBeVisible();
await expect(
page.getByRole('heading', { name: /Closed · Rejected|Закрыто · Отклонён/ }),
).toBeVisible();
if (width === 390) await page.getByRole('combobox').selectOption('REJECTED');
await expect(page.getByRole('heading', { name: /^(Rejected|Отклонён)$/ })).toBeVisible();
await noOverflow(page);
await page.screenshot({ path: info.outputPath('pipeline.png'), fullPage: true });
await page.goto('/app/tasks');
@@ -178,7 +180,7 @@ test('loading, retryable errors, empty states, session expiry and reduced motion
).toBeVisible();
await page.unroute('**/api/pipeline');
await page.getByRole('button', { name: 'Try again' }).click();
await expect(page.getByRole('heading', { name: 'Closed · Rejected' })).toBeVisible();
await expect(page.getByRole('heading', { name: 'Rejected', exact: true })).toBeVisible();
await page.route('**/api/tasks?**', (route) => route.fulfill({ json: [] }));
await page.goto('/app/tasks');
await expect(page.getByText('You’re all caught up here')).toBeVisible();
@@ -237,6 +239,7 @@ test('Head assignment, manager editing, Compliance decisions and manager activat
.fill('246000.75');
await save();
await expect(page.getByText('Director of Partnerships', { exact: true })).toBeVisible();
await page.getByRole('tab', { name: 'Activity', exact: true }).click();
await page.getByRole('button', { name: 'Log interaction', exact: true }).click();
await page.getByRole('dialog').getByLabel('Interaction type').selectOption('CALL');
await page
@@ -247,6 +250,7 @@ test('Head assignment, manager editing, Compliance decisions and manager activat
await expect(
page.getByText('Confirmed the launch requirements in a discovery call.', { exact: true }),
).toBeVisible();
await page.getByRole('tab', { name: 'Tasks', exact: true }).click();
await page.getByRole('button', { name: 'Add task', exact: true }).click();
await page
.getByRole('dialog')
@@ -259,6 +263,7 @@ test('Head assignment, manager editing, Compliance decisions and manager activat
await advance('Contacted');
await advance('Qualified');
await advance('KYB');
await page.getByRole('tab', { name: 'Onboarding', exact: true }).click();
for (let i = 0; i < 4; i++) {
await page.getByRole('button', { name: 'Update document', exact: true }).nth(i).click();
await page
@@ -268,8 +273,9 @@ test('Head assignment, manager editing, Compliance decisions and manager activat
await save();
}
await advance('Compliance Review');
await expect(page.getByRole('button', { name: 'Record decision', exact: true })).toHaveCount(0);
await expect(page.getByRole('button', { name: 'Record decision', exact: true })).toBeDisabled();
await switchAccount('compliance');
await page.getByRole('tab', { name: 'Onboarding', exact: true }).click();
await page.getByRole('button', { name: 'Record decision', exact: true }).click();
await page
.getByRole('dialog')
@@ -285,6 +291,7 @@ test('Head assignment, manager editing, Compliance decisions and manager activat
.fill('Please sign and date the declaration.');
await save();
await switchAccount('alex');
await page.getByRole('tab', { name: 'Onboarding', exact: true }).click();
const ownership = page
.locator('#checklist > div > div')
.filter({ hasText: 'Ownership structure' });
@@ -300,6 +307,7 @@ test('Head assignment, manager editing, Compliance decisions and manager activat
await save();
await advance('Compliance Review');
await switchAccount('compliance');
await page.getByRole('tab', { name: 'Onboarding', exact: true }).click();
await page.getByRole('button', { name: 'Record decision', exact: true }).click();
await page
.getByRole('dialog')