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
+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: 'Не назначен',