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