Build MerchantFlow onboarding CRM foundation

This commit is contained in:
Oleksandr Prokhorenko
2026-09-24 16:43:22 +03:00
commit 3aa47d825f
78 changed files with 10739 additions and 0 deletions
+20
View File
@@ -0,0 +1,20 @@
{
"$schema": "https://ui.shadcn.com/schema.json",
"style": "base-nova",
"rsc": false,
"tsx": true,
"tailwind": {
"config": "",
"css": "../../packages/ui/src/styles/globals.css",
"baseColor": "neutral",
"cssVariables": true
},
"iconLibrary": "lucide",
"aliases": {
"components": "@/components",
"hooks": "@/hooks",
"lib": "@/lib",
"utils": "@merchantflow/ui/lib/utils",
"ui": "@merchantflow/ui/components"
}
}
+18
View File
@@ -0,0 +1,18 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="theme-color" content="#f7f8fa" />
<meta
name="description"
content="MerchantFlow brings your merchant onboarding, compliance, and relationships into one clear workspace."
/>
<title>MerchantFlow — Merchant onboarding, in flow</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>
+34
View File
@@ -0,0 +1,34 @@
{
"name": "@merchantflow/web",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "vite --host 127.0.0.1",
"build": "tsc --noEmit && vite build",
"typecheck": "tsc --noEmit",
"test": "vitest run"
},
"dependencies": {
"@merchantflow/contracts": "workspace:*",
"@merchantflow/ui": "workspace:*",
"@hookform/resolvers": "5.9.1",
"@tanstack/react-query": "5.103.2",
"i18next": "25.10.10",
"lucide-react": "1.48.0",
"react": "19.3.0",
"react-dom": "19.3.0",
"react-hook-form": "7.88.0",
"react-i18next": "16.6.6",
"react-router": "7.18.4",
"zod": "4.6.5"
},
"devDependencies": {
"@tailwindcss/vite": "4.3.3",
"@types/react": "19.3.0",
"@types/react-dom": "19.3.0",
"@vitejs/plugin-react": "4.7.0",
"tailwindcss": "4.3.3",
"vite": "7.3.6"
}
}
+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 40 40"><rect width="40" height="40" rx="12" fill="#d1ef7c"/><path d="M10 27V13l10 8 10-8v14M20 21v8" fill="none" stroke="#28321b" stroke-width="3.2" stroke-linecap="round" stroke-linejoin="round"/></svg>

After

Width:  |  Height:  |  Size: 257 B

+356
View File
@@ -0,0 +1,356 @@
import { useEffect, type ReactNode } from 'react';
import { Link } from 'react-router';
import { useTranslation } from 'react-i18next';
import type { UseQueryResult } from '@tanstack/react-query';
import {
ArrowDownRight,
ArrowUpRight,
Bell,
Check,
Circle,
Clock3,
MoveUpRight,
} from 'lucide-react';
import type { Status, Merchant, Task, StageEvent } from '@merchantflow/contracts';
import { Badge } from '@merchantflow/ui/components/badge';
import { Button, buttonVariants } from '@merchantflow/ui/components/button';
import { LoadingState, EmptyState, ErrorState } from '@merchantflow/ui/components/states';
import { cn } from '@merchantflow/ui/lib/utils';
import { ApiError } from '../lib/api';
import { useFormat } from '../lib/format';
export function Brand({ compact = false }: { compact?: boolean }) {
return (
<Link
to="/"
aria-label="MerchantFlow"
className="inline-flex min-h-11 items-center gap-2.5 rounded-md"
>
<svg className="size-9 shrink-0" aria-hidden="true" viewBox="0 0 40 40">
<rect width="40" height="40" rx="12" fill="#d1ef7c" />
<path
d="M10 27V13l10 8 10-8v14M20 21v8"
fill="none"
stroke="#28321b"
strokeWidth="3.2"
strokeLinecap="round"
strokeLinejoin="round"
/>
</svg>
{!compact && (
<span className="text-xl font-semibold tracking-[-.05em]">
merchantflow<span className="text-[#6a8a34]">.</span>
</span>
)}
</Link>
);
}
export function LanguageSwitch() {
const { t, i18n } = useTranslation();
return (
<div
role="group"
aria-label={t('common.language')}
className="inline-flex shrink-0 rounded-lg border bg-card p-0.5"
>
{['en', 'ru'].map((l) => (
<button
key={l}
type="button"
aria-label={l === 'en' ? 'English' : 'Русский'}
aria-pressed={i18n.language === l}
onClick={() => void i18n.changeLanguage(l)}
className={cn(
'min-h-11 min-w-11 rounded-md px-2 text-xs font-semibold',
i18n.language === l ? 'bg-secondary text-foreground' : 'text-muted-foreground',
)}
>
{l.toUpperCase()}
</button>
))}
</div>
);
}
export function LinkButton({
to,
children,
variant = 'default',
className,
}: {
to: string;
children: ReactNode;
variant?: 'default' | 'outline' | 'ghost';
className?: string;
}) {
return (
<Link to={to} className={cn(buttonVariants({ variant }), className)}>
{children}
</Link>
);
}
export function PageHeader({
title,
description,
eyebrow,
action,
}: {
title: string;
description: string;
eyebrow?: string;
action?: ReactNode;
}) {
useEffect(() => {
document.title = `${title} · MerchantFlow`;
}, [title]);
return (
<div className="mb-7 flex flex-col gap-5 sm:flex-row sm:items-end sm:justify-between">
<div>
{eyebrow && <p className="section-label mb-2.5">{eyebrow}</p>}
<h1 className="page-title">{title}</h1>
<p className="mt-2 max-w-2xl text-sm leading-relaxed text-muted-foreground">
{description}
</p>
</div>
{action && <div className="shrink-0">{action}</div>}
</div>
);
}
export function SectionHeader({
title,
description,
action,
}: {
title: string;
description?: string;
action?: ReactNode;
}) {
return (
<div className="flex flex-wrap items-start justify-between gap-3 px-5 pt-5 sm:px-6">
<div>
<h2 className="text-base font-semibold tracking-tight">{title}</h2>
{description && (
<p className="mt-1 text-xs leading-relaxed text-muted-foreground">{description}</p>
)}
</div>
{action}
</div>
);
}
export const statusStyles: Record<Status, string> = {
NEW_LEAD: 'bg-slate-100 text-slate-700',
CONTACTED: 'bg-blue-50 text-blue-800',
QUALIFIED: 'bg-indigo-50 text-indigo-800',
KYB: 'bg-amber-50 text-amber-800',
COMPLIANCE_REVIEW: 'bg-orange-50 text-orange-800',
INTEGRATION: 'bg-violet-50 text-violet-800',
TESTING: 'bg-teal-50 text-teal-800',
LIVE: 'bg-[#edf5da] text-[#46641d]',
REJECTED: 'bg-rose-50 text-rose-800',
};
export const stageColors: Record<Status, string> = {
NEW_LEAD: '#aebbb0',
CONTACTED: '#8ba5ce',
QUALIFIED: '#9e9bc9',
KYB: '#ddbd78',
COMPLIANCE_REVIEW: '#dba879',
INTEGRATION: '#b49acf',
TESTING: '#8ebcb0',
LIVE: '#a6c65e',
REJECTED: '#cf969e',
};
export function StatusBadge({ status }: { status: Status }) {
const { t } = useTranslation();
return (
<Badge
className={cn('gap-1.5 border-0 px-2 py-1 text-[11px] font-medium', statusStyles[status])}
>
<span className="size-1.5 shrink-0 rounded-full bg-current" aria-hidden="true" />
{t(`statuses.${status}`)}
</Badge>
);
}
export function Avatar({ name, small = false }: { name: string; small?: boolean }) {
const sum = [...name].reduce((a, c) => a + c.charCodeAt(0), 0);
return (
<div
aria-hidden="true"
className={cn(
'flex shrink-0 items-center justify-center rounded-xl border border-black/5 font-semibold',
small ? 'size-9 text-xs' : 'size-11 text-sm',
[
'bg-[#ecf0e4] text-[#56693d]',
'bg-[#e9edf5] text-[#596a88]',
'bg-[#f3ebe4] text-[#8a6b52]',
'bg-[#ede9f2] text-[#78678b]',
][sum % 4],
)}
>
{name
.split(' ')
.map((n) => n[0])
.slice(0, 2)
.join('')}
</div>
);
}
export function QueryBoundary<T>({
query,
children,
}: {
query: UseQueryResult<T, Error>;
children: (data: T) => ReactNode;
}) {
const { t } = useTranslation();
if (query.isPending) return <LoadingState label={t('common.loading')} />;
if (query.isError)
return (
<ErrorState
title={t('common.errorTitle')}
description={t(
`errors.${query.error instanceof ApiError ? query.error.code : 'INTERNAL_ERROR'}`,
{ defaultValue: t('errors.INTERNAL_ERROR') },
)}
retryLabel={t('common.retry')}
onRetry={() => void query.refetch()}
/>
);
return <>{children(query.data)}</>;
}
export function MerchantCard({ merchant }: { merchant: Merchant }) {
const { t } = useTranslation();
const f = useFormat();
return (
<Link to={`/app/merchants/${merchant.id}`} className="surface hover-surface block p-4">
<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}`)}
</p>
</div>
<MoveUpRight
aria-hidden="true"
className="ml-auto size-3.5 shrink-0 text-muted-foreground"
/>
</div>
<div className="mt-5 flex items-center justify-between gap-2 text-xs text-muted-foreground">
<span>{merchant.owner.name.split(' ')[0]}</span>
<span className="flex items-center gap-1">
<Clock3 className="size-3" aria-hidden="true" />
{f.relative(merchant.stageEnteredAt)}
</span>
</div>
</Link>
);
}
export function TaskRow({ task, compact = false }: { task: Task; compact?: boolean }) {
const { t } = useTranslation();
const f = useFormat();
const done = task.status === 'DONE';
const overdue = !done && new Date(task.dueAt).getTime() < Date.now();
return (
<div className={cn('flex gap-3 border-b px-5 py-4 last:border-0 sm:px-6', compact && 'py-4')}>
<div
className={cn(
'mt-0.5 flex size-6 shrink-0 items-center justify-center rounded-full border',
done ? 'border-[#ccdfab] bg-accent text-[#46641d]' : 'text-muted-foreground',
)}
>
{done ? (
<Check className="size-3.5" aria-label={t('tasks.completed')} />
) : (
<Circle className="size-2" aria-hidden="true" />
)}
</div>
<div className="min-w-0 flex-1">
<p className={cn('text-sm leading-relaxed', done && 'text-muted-foreground')}>
{task.title}
</p>
<div className="mt-1 flex flex-wrap items-center gap-x-2 gap-y-1 text-xs">
<Link to={`/app/merchants/${task.merchant.id}`} className="font-medium hover:underline">
{task.merchant.name}
</Link>
<span className="text-muted-foreground" aria-hidden="true">
·
</span>
<span className={overdue ? 'text-amber-800' : 'text-muted-foreground'}>
{done ? t('tasks.completed') : t('tasks.due', { date: f.shortDate(task.dueAt) })}
{overdue && ` · ${t('tasks.OVERDUE')}`}
</span>
</div>
{!compact && (
<div className="mt-2 flex flex-wrap gap-x-4 gap-y-1 text-xs text-muted-foreground">
<span>{t('tasks.assigned', { name: task.assignee.name })}</span>
{!done && task.remindAt && (
<span className="inline-flex items-center gap-1">
<Bell className="size-3" aria-hidden="true" />
{new Date(task.remindAt).getTime() <= Date.now()
? t('tasks.reminderDue')
: `${t('tasks.reminder')}: ${f.date(task.remindAt)}`}
</span>
)}
</div>
)}
</div>
</div>
);
}
export function ActivityFeed({
events,
detail = false,
}: {
events: StageEvent[];
detail?: boolean;
}) {
const { t } = useTranslation();
const f = useFormat();
if (!events.length) return <EmptyState title={t('dashboard.emptyActivity')} />;
return (
<div className="px-5 py-2 sm:px-6">
{events.map((event, i) => (
<div key={event.id} className="relative flex gap-3 py-4">
{i < events.length - 1 && (
<div
className="absolute top-11 bottom-[-16px] left-[15px] w-px bg-border"
aria-hidden="true"
/>
)}
<div className="z-10 flex size-8 shrink-0 items-center justify-center rounded-full border bg-card">
{event.fromStatus === 'COMPLIANCE_REVIEW' && event.toStatus === 'KYB' ? (
<ArrowDownRight className="size-3.5 text-amber-700" aria-hidden="true" />
) : (
<ArrowUpRight className="size-3.5 text-muted-foreground" aria-hidden="true" />
)}
</div>
<div className="min-w-0 flex-1">
{!detail && (
<Link
to={`/app/merchants/${event.merchant.id}`}
className="text-sm font-medium hover:underline"
>
{event.merchant.name}
</Link>
)}
<p className="mt-0.5 text-xs leading-relaxed text-muted-foreground">
{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}
</p>
{event.note && (
<p className="mt-2 rounded-lg bg-muted p-3 text-xs leading-relaxed">{event.note}</p>
)}
<time
dateTime={event.occurredAt}
title={f.date(event.occurredAt)}
className="mt-1 block text-[11px] text-muted-foreground"
>
{f.relative(event.occurredAt)}
</time>
</div>
</div>
))}
</div>
);
}
export { Button, EmptyState };
+215
View File
@@ -0,0 +1,215 @@
import { useState, useEffect } from 'react';
import { NavLink, Navigate, Outlet, useLocation, useNavigate } from 'react-router';
import { useQuery, useMutation } from '@tanstack/react-query';
import { useTranslation } from 'react-i18next';
import {
LayoutDashboard,
Building2,
Columns3,
ListTodo,
ShieldCheck,
LogOut,
Menu,
ChevronRight,
ArrowUpRight,
} from 'lucide-react';
import { z } from 'zod';
import { canSeeReviewQueue, type User } from '@merchantflow/contracts';
import {
Sheet,
SheetContent,
SheetTitle,
SheetDescription,
} from '@merchantflow/ui/components/sheet';
import { cn } from '@merchantflow/ui/lib/utils';
import { Brand, LanguageSwitch, Button, QueryBoundary, Avatar } from './shared';
import { api, queryClient, sessionOptions, ApiError } from '../lib/api';
import { useFormat } from '../lib/format';
const navigation = [
{ key: 'dashboard', to: '/app', Icon: LayoutDashboard },
{ key: 'merchants', to: '/app/merchants', Icon: Building2 },
{ key: 'pipeline', to: '/app/pipeline', Icon: Columns3 },
{ key: 'tasks', to: '/app/tasks', Icon: ListTodo },
{ key: 'review', to: '/app/review-queue', Icon: ShieldCheck },
];
function Sidebar({ user, onNavigate }: { user: User; onNavigate?: () => void }) {
const { t } = useTranslation();
const navigate = useNavigate();
const logout = useMutation({
mutationFn: () => api('/auth/logout', z.object({ ok: z.boolean() }), { method: 'POST' }),
onSuccess: async () => {
await queryClient.cancelQueries();
queryClient.clear();
queryClient.setQueryData(['session'], null);
navigate('/login', { replace: true });
},
});
return (
<div className="flex h-full flex-col px-4 pb-4 pt-5">
<div className="mb-8 px-2">
<Brand />
</div>
<div className="mb-7 flex items-center gap-2.5 rounded-lg border bg-background px-3 py-3">
<div className="flex size-8 shrink-0 items-center justify-center rounded-lg bg-white">
<Building2 className="size-4" aria-hidden="true" />
</div>
<div className="min-w-0">
<p className="text-xs font-semibold">{t('common.team')}</p>
<p className="mt-0.5 text-[10px] text-muted-foreground">MerchantFlow CRM</p>
</div>
</div>
<p className="section-label mb-2 px-3">{t('common.workspace')}</p>
<nav aria-label={t('common.workspace')} className="space-y-1">
{navigation
.filter((n) => n.key !== 'review' || canSeeReviewQueue(user.role))
.map(({ key, to, Icon }) => (
<NavLink
key={key}
to={to}
end={key === 'dashboard'}
onClick={onNavigate}
className={({ isActive }) =>
cn(
'flex min-h-11 items-center gap-3 rounded-lg px-3 py-2.5 text-[13px] font-medium',
isActive ? 'bg-[#edf4e2] text-[#384e22]' : 'text-muted-foreground hover:bg-muted',
)
}
>
<Icon className="size-[18px] shrink-0" aria-hidden="true" />
{t(`nav.${key}`)}
</NavLink>
))}
</nav>
<div className="mt-auto pt-10">
<div className="mb-5 rounded-xl bg-[#f3f6ed] p-4">
<div className="mb-4 flex size-8 items-center justify-center rounded-full bg-primary">
<ArrowUpRight className="size-4" aria-hidden="true" />
</div>
<p className="text-xs font-medium leading-relaxed">{t('common.brandTag')}</p>
</div>
{logout.isError && (
<p role="alert" className="mb-3 text-xs text-destructive">
{t(`errors.${logout.error instanceof ApiError ? logout.error.code : 'NETWORK'}`)}
</p>
)}
<div className="flex items-center gap-2.5 border-t pt-4">
<Avatar name={user.name} small />
<div className="min-w-0 flex-1">
<p className="truncate text-xs font-semibold">{user.name}</p>
<p className="mt-1 text-[10px] leading-snug text-muted-foreground">
{t(`roles.${user.role}`)}
</p>
</div>
<Button
variant="ghost"
size="icon"
aria-label={t('common.logout')}
disabled={logout.isPending}
onClick={() => logout.mutate()}
>
<LogOut className="size-4" />
</Button>
</div>
</div>
</div>
);
}
function AuthenticatedShell({ user }: { user: User }) {
const [open, setOpen] = useState(false);
const location = useLocation();
const { t } = useTranslation();
const f = useFormat();
const active =
navigation.find((n) => n.to !== '/app' && location.pathname.startsWith(n.to)) ?? navigation[0]!;
useEffect(() => {
window.scrollTo(0, 0);
}, [location.pathname]);
return (
<div className="min-h-dvh">
<a
href="#main"
className="fixed left-4 top-2 z-[100] -translate-y-24 rounded-lg bg-primary px-4 py-3 focus:translate-y-0"
>
{t('common.skip')}
</a>
<aside className="fixed inset-y-0 left-0 z-30 hidden w-[236px] border-r bg-card lg:block">
<Sidebar user={user} />
</aside>
<Sheet open={open} onOpenChange={setOpen}>
<SheetContent
side="left"
closeLabel={t('common.close')}
className="w-[min(320px,90vw)]! gap-0"
>
<SheetTitle className="sr-only">{t('common.workspace')}</SheetTitle>
<SheetDescription className="sr-only">{t('common.team')}</SheetDescription>
<Sidebar user={user} onNavigate={() => setOpen(false)} />
</SheetContent>
</Sheet>
<div className="min-w-0 lg:pl-[236px]">
<header className="flex h-[76px] items-center justify-between gap-3 border-b bg-card px-4 sm:px-8">
<div className="flex min-w-0 items-center gap-2">
<Button
variant="ghost"
size="icon"
className="lg:hidden"
aria-label={t('common.openMenu')}
onClick={() => setOpen(true)}
>
<Menu className="size-5" />
</Button>
<span className="hidden text-xs text-muted-foreground sm:inline">
{t('common.workspace')}
</span>
<ChevronRight
className="hidden size-3 text-muted-foreground sm:block"
aria-hidden="true"
/>
<span className="truncate text-xs font-medium">{t(`nav.${active.key}`)}</span>
</div>
<div className="flex shrink-0 items-center gap-5">
<span className="hidden text-xs text-muted-foreground xl:block">
{f.date(new Date())}
</span>
<LanguageSwitch />
</div>
</header>
<main
id="main"
tabIndex={-1}
className="mx-auto max-w-[1600px] px-4 py-7 outline-none sm:px-8 sm:py-9"
>
<Outlet context={user} />
</main>
<footer className="mx-auto flex max-w-[1600px] flex-wrap items-center justify-between gap-2 px-4 pb-6 pt-3 text-[10px] text-muted-foreground sm:px-8">
<span>
MerchantFlow <span className="mx-1">/</span> {t('common.local')}
</span>
<span>
{t(
`dashboard.${user.role === 'HEAD_OF_SALES' ? 'scopeHead' : user.role === 'COMPLIANCE_OFFICER' ? 'scopeCompliance' : 'scopeManager'}`,
)}
</span>
</footer>
</div>
</div>
);
}
export function ProtectedShell() {
const query = useQuery(sessionOptions);
const location = useLocation();
return (
<QueryBoundary query={query}>
{(user) =>
user ? (
<AuthenticatedShell user={user} />
) : (
<Navigate
to={`/login?next=${encodeURIComponent(location.pathname + location.search)}`}
replace
/>
)
}
</QueryBoundary>
);
}
+25
View File
@@ -0,0 +1,25 @@
import i18n from 'i18next';
import { initReactI18next } from 'react-i18next';
import { en, ru } from './locales';
let saved: string | null = null;
try {
saved = localStorage.getItem('merchantflow.language');
} catch {
/* Storage can be unavailable in private contexts. */
}
void i18n.use(initReactI18next).init({
resources: { en: { translation: en }, ru: { translation: ru } },
lng: saved === 'ru' ? 'ru' : 'en',
fallbackLng: 'en',
interpolation: { escapeValue: false },
});
document.documentElement.lang = i18n.language;
i18n.on('languageChanged', (language) => {
document.documentElement.lang = language;
try {
localStorage.setItem('merchantflow.language', language);
} catch {
/* Keep the current session usable without storage. */
}
});
export default i18n;
+73
View File
@@ -0,0 +1,73 @@
import { QueryClient } from '@tanstack/react-query';
import { z } from 'zod';
import { userSchema } from '@merchantflow/contracts';
export class ApiError extends Error {
constructor(
public code: string,
public status = 0,
) {
super(code);
}
}
export const queryClient = new QueryClient({
defaultOptions: {
queries: {
staleTime: 30000,
retry: (count, error) =>
!(error instanceof ApiError && [401, 403, 404].includes(error.status)) && count < 1,
refetchOnWindowFocus: true,
},
},
});
export async function api<T>(
path: string,
schema: z.ZodType<T>,
options: RequestInit = {},
): Promise<T> {
let response: Response;
try {
response = await fetch(`/api${path}`, {
credentials: 'same-origin',
...options,
headers: {
...(options.body ? { 'Content-Type': 'application/json' } : {}),
...options.headers,
},
});
} catch (error) {
if (error instanceof Error && error.name === 'AbortError') throw error;
throw new ApiError('NETWORK');
}
if (!response.ok) {
const body = await response.json().catch(() => ({}));
if (response.status === 401 && !path.startsWith('/auth/')) {
await queryClient.cancelQueries();
queryClient.clear();
queryClient.setQueryData(['session'], null);
}
throw new ApiError(
typeof body.code === 'string' ? body.code : 'INTERNAL_ERROR',
response.status,
);
}
const result = schema.safeParse(await response.json());
if (!result.success) throw new ApiError('RESPONSE');
return result.data;
}
export const sessionOptions = {
queryKey: ['session'],
queryFn: async ({ signal }: { signal: AbortSignal }) => {
try {
return await api('/auth/me', userSchema, { signal });
} catch (error) {
if (error instanceof ApiError && error.status === 401) return null;
throw error;
}
},
retry: false,
};
export function safeReturnTo(value: unknown) {
return typeof value === 'string' && /^\/app(?:[/?#]|$)/.test(value) && !value.includes('\\')
? value
: '/app';
}
+22
View File
@@ -0,0 +1,22 @@
import { useTranslation } from 'react-i18next';
export function useFormat() {
const { i18n } = useTranslation();
const locale = i18n.language === 'ru' ? 'ru-RU' : 'en-GB';
return {
date: (value: string | Date) =>
new Intl.DateTimeFormat(locale, { day: 'numeric', month: 'short', year: 'numeric' }).format(
new Date(value),
),
shortDate: (value: string | Date) =>
new Intl.DateTimeFormat(locale, { day: 'numeric', month: 'short' }).format(new Date(value)),
number: (value: number) => new Intl.NumberFormat(locale).format(value),
country: (code: string) => new Intl.DisplayNames([locale], { type: 'region' }).of(code),
relative: (value: string) => {
const hours = Math.round((new Date(value).getTime() - Date.now()) / 3600000);
return new Intl.RelativeTimeFormat(locale, { numeric: 'auto' }).format(
Math.abs(hours) >= 24 ? Math.round(hours / 24) : hours,
Math.abs(hours) >= 24 ? 'day' : 'hour',
);
},
};
}
+24
View File
@@ -0,0 +1,24 @@
import { expect, it } from 'vitest';
import { en, ru } from './locales';
import { safeReturnTo } from './lib/api';
function keys(value: object, prefix = ''): string[] {
return Object.entries(value)
.flatMap(([key, child]) =>
typeof child === 'object' ? keys(child, `${prefix}${key}.`) : [`${prefix}${key}`],
)
.filter((key) => !/_(few|many)$/.test(key))
.sort();
}
it('has matching EN/RU keys and interpolation variables', () => {
expect(keys(en)).toEqual(keys(ru));
for (const key of keys(en)) {
const get = (obj: object) =>
key.split('.').reduce<unknown>((v, k) => (v as Record<string, unknown>)[k], obj) as string;
expect(get(en).match(/{{\w+}}/g)).toEqual(get(ru).match(/{{\w+}}/g));
}
});
it('only accepts internal CRM return paths', () => {
expect(safeReturnTo('/app/merchants/merchant-01?x=1')).toBe('/app/merchants/merchant-01?x=1');
for (const unsafe of ['https://example.com', '//example.com', '/application', '/app\\evil', null])
expect(safeReturnTo(unsafe)).toBe('/app');
});
+474
View File
@@ -0,0 +1,474 @@
export const en = {
common: {
workspace: 'Workspace',
team: 'Merchant workspace',
close: 'Close',
back: 'Back',
retry: 'Try again',
loading: 'Loading your workspace…',
errorTitle: 'Something interrupted the flow',
emptyTitle: 'Nothing here just yet',
emptyText: 'Records will appear here when they match this view.',
noResults: 'No merchants found',
noResultsText: 'Try a different name or clear your filters.',
clear: 'Clear filters',
viewAll: 'View all',
viewMerchant: 'View merchant',
previous: 'Previous',
next: 'Next',
page: 'Page {{page}} of {{total}}',
showing: '{{from}}–{{to}} of {{total}} merchants',
all: 'All',
language: 'Language',
logout: 'Sign out',
openMenu: 'Open navigation',
skip: 'Skip to content',
notFound: 'This page is off the map',
notFoundText: 'The page may have moved, or you may not have access to it.',
goHome: 'Back to workspace',
local: 'Team workspace',
readOnly: 'Workspace overview',
noAccess: 'This view is for Compliance',
noAccessText: 'Your merchant portfolio is available from the workspace.',
date: 'Date',
status: 'Status',
owner: 'Account manager',
merchant: 'Merchant',
created: 'Created',
currentStage: 'Current stage',
daysInStage: '{{count}} days in stage',
daysInStage_one: '{{count}} day in stage',
number: '{{value}}',
brandTag: 'Every stage. One workspace.',
},
nav: {
dashboard: 'Dashboard',
merchants: 'Merchants',
pipeline: 'Pipeline',
tasks: 'Tasks',
review: 'Review queue',
},
roles: {
HEAD_OF_SALES: 'Head of Sales',
COMPLIANCE_OFFICER: 'Compliance Officer',
ACCOUNT_MANAGER: 'Account Manager',
},
statuses: {
NEW_LEAD: 'New Lead',
CONTACTED: 'Contacted',
QUALIFIED: 'Qualified',
KYB: 'KYB',
COMPLIANCE_REVIEW: 'Compliance Review',
INTEGRATION: 'Integration',
TESTING: 'Testing',
LIVE: 'Live',
REJECTED: 'Rejected',
},
industry: {
ECOMMERCE: 'E-commerce',
SOFTWARE: 'Software',
TRAVEL: 'Travel',
SERVICES: 'Services',
},
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.',
},
auth: {
eyebrow: 'WELCOME BACK',
title: 'Get back into flow.',
description: 'Sign in to your MerchantFlow workspace.',
email: 'Email address',
password: 'Password',
showPassword: 'Show password',
hidePassword: 'Hide password',
submit: 'Sign in to workspace',
submitting: 'Signing in…',
demoTitle: 'Explore the demo',
demoText: 'Choose an account to fill in its credentials, then sign in.',
demoPassword: 'Demo password',
back: 'Back to MerchantFlow',
sideTitle: 'Good handoffs make\ngreat partnerships.',
sideText: 'Your merchants, their story, and the next step. All in one place.',
expired: 'Your session ended. Sign in to continue.',
},
validation: {
email: 'Enter a valid email address.',
password: 'Enter your password.',
passwordMax: 'Use 128 characters or fewer.',
invalid: 'Please check this value.',
},
errors: {
UNAUTHORIZED: 'Sign in to continue.',
INVALID_CREDENTIALS: 'The email or password is incorrect.',
FORBIDDEN: 'You do not have access to this view.',
NOT_FOUND: 'This merchant was not found or is outside your portfolio.',
VALIDATION_ERROR: 'Please check the information and try again.',
INTERNAL_ERROR: 'We could not load this information. Please try again.',
DATABASE_UNAVAILABLE: 'The workspace database is unavailable. Please try again.',
TOO_MANY_REQUESTS: 'Too many sign-in attempts. Try again in five minutes.',
NETWORK: 'We could not reach the workspace. Check your connection and try again.',
RESPONSE: 'We received an unexpected response. Please try again.',
},
dashboard: {
eyebrow: 'YOUR WORKSPACE, IN SYNC',
title: 'Overview',
description: 'A clear view of your merchant relationships.',
welcome: 'Welcome back, {{name}}',
view: 'View merchants',
merchants: 'Total merchants',
merchantsHint: 'In your visible portfolio',
reviews: 'Awaiting review',
reviewsHint: 'Ready for Compliance',
overdue: 'Overdue tasks',
overdueHint: 'A little attention needed',
changes: 'Stage changes',
changesHint: 'Over the last 30 days',
pipeline: 'Pipeline at a glance',
pipelineText: 'Every relationship has a next chapter.',
openPipeline: 'Open pipeline',
activity: 'Recent activity',
activityText: 'The latest moves across your portfolio.',
priorities: 'On your radar',
prioritiesText: 'Upcoming steps and timely follow-ups.',
moved: 'Moved to',
added: 'Added as',
emptyActivity: 'No activity to show yet',
scopeHead: 'Your entire merchant portfolio',
scopeManager: 'Your assigned merchants',
scopeCompliance: 'Merchants in KYB and Compliance Review',
},
merchants: {
title: 'Merchants',
description: 'The people and businesses behind every partnership.',
search: 'Search merchants or contact email…',
filter: 'Filter by stage',
allStages: 'All stages',
business: 'Business',
location: 'Location',
portfolio: 'YOUR MERCHANT PORTFOLIO',
contact: 'Primary contact',
website: 'Website',
industry: 'Industry',
overview: 'Merchant overview',
details: 'The essentials, all together.',
checklist: 'KYB checklist',
checklistText: 'Document readiness for the next review.',
notes: 'Team notes',
notesText: 'Context from the people closest to the relationship.',
history: 'Journey history',
historyText: 'Every step, including the steps back.',
tasks: 'Related tasks',
tasksText: 'Follow-ups connected to this merchant.',
back: 'Back to merchants',
since: 'In this stage since {{date}}',
noNotes: 'No notes yet',
noTasks: 'No related tasks yet',
},
documents: {
INCORPORATION: 'Certificate of incorporation',
OWNERSHIP: 'Ownership structure',
UBO_IDENTIFICATION: 'Beneficial owner identification',
BUSINESS_ACTIVITY: 'Business activity description',
},
checklist: { MISSING: 'Missing', RECEIVED: 'Received', NEEDS_CORRECTION: 'Needs correction' },
pipeline: {
title: 'Pipeline',
description: 'From a first hello to a lasting partnership.',
journey: 'THE PATH TO LIVE',
rejectedTitle: 'Closed · Rejected',
rejectedText: 'An alternate outcome, separate from the path to Live.',
stageSelect: 'Choose a pipeline stage',
empty: 'No merchants in this stage',
count: '{{count}} merchants',
count_one: '{{count}} merchant',
stageCount: '{{number}} of 8 stages',
},
tasks: {
title: 'Tasks',
description: 'A little structure for the next right step.',
ALL: 'All tasks',
OPEN: 'Open',
OVERDUE: 'Overdue',
UPCOMING: 'Upcoming',
DONE: 'Completed',
due: 'Due {{date}}',
completed: 'Completed',
reminder: 'Reminder',
reminderDue: 'Reminder due',
assigned: 'Assigned to {{name}}',
empty: 'You’re all caught up here',
emptyText: 'No tasks match this filter.',
filter: 'Filter tasks',
taskTitle: 'Task',
dueDate: 'Due date',
},
review: {
title: 'Review queue',
description: 'Clear context for confident decisions.',
eyebrow: 'COMPLIANCE WORKSPACE',
count: '{{count}} merchants awaiting review',
count_one: '{{count}} merchant awaiting review',
order: 'Oldest first',
empty: 'The queue is clear',
emptyText: 'Merchants appear here when they reach Compliance Review.',
entered: 'Entered review',
view: 'View checklist',
},
};
export const ru = {
common: {
workspace: 'Рабочее пространство',
team: 'Работа с мерчантами',
close: 'Закрыть',
back: 'Назад',
retry: 'Повторить',
loading: 'Загружаем рабочее пространство…',
errorTitle: 'Не удалось загрузить данные',
emptyTitle: 'Здесь пока ничего нет',
emptyText: 'Здесь появятся записи, соответствующие этому разделу.',
noResults: 'Мерчанты не найдены',
noResultsText: 'Попробуйте другое название или сбросьте фильтры.',
clear: 'Сбросить фильтры',
viewAll: 'Посмотреть все',
viewMerchant: 'Открыть мерчанта',
previous: 'Назад',
next: 'Далее',
page: 'Страница {{page}} из {{total}}',
showing: '{{from}}–{{to}} из {{total}} мерчантов',
all: 'Все',
language: 'Язык',
logout: 'Выйти',
openMenu: 'Открыть навигацию',
skip: 'Перейти к содержимому',
notFound: 'Такой страницы нет',
notFoundText: 'Возможно, страница перемещена или у вас нет доступа к ней.',
goHome: 'В рабочее пространство',
local: 'Пространство команды',
readOnly: 'Обзор рабочего пространства',
noAccess: 'Раздел для комплаенса',
noAccessText: 'Ваш портфель мерчантов доступен в рабочем пространстве.',
date: 'Дата',
status: 'Статус',
owner: 'Аккаунт-менеджер',
merchant: 'Мерчант',
created: 'Создан',
currentStage: 'Текущий этап',
daysInStage: '{{count}} дней на этапе',
daysInStage_one: '{{count}} день на этапе',
daysInStage_few: '{{count}} дня на этапе',
daysInStage_many: '{{count}} дней на этапе',
number: '{{value}}',
brandTag: 'Все этапы. Одно пространство.',
},
nav: {
dashboard: 'Обзор',
merchants: 'Мерчанты',
pipeline: 'Воронка',
tasks: 'Задачи',
review: 'Очередь проверок',
},
roles: {
HEAD_OF_SALES: 'Руководитель продаж',
COMPLIANCE_OFFICER: 'Специалист по комплаенсу',
ACCOUNT_MANAGER: 'Аккаунт-менеджер',
},
statuses: {
NEW_LEAD: 'Новый лид',
CONTACTED: 'Контакт установлен',
QUALIFIED: 'Квалифицирован',
KYB: 'KYB',
COMPLIANCE_REVIEW: 'Комплаенс-проверка',
INTEGRATION: 'Интеграция',
TESTING: 'Тестирование',
LIVE: 'Запущен',
REJECTED: 'Отклонён',
},
industry: {
ECOMMERCE: 'Электронная торговля',
SOFTWARE: 'Программное обеспечение',
TRAVEL: 'Туризм',
SERVICES: 'Услуги',
},
landing: {
eyebrow: 'ПОДКЛЮЧЕНИЕ МЕРЧАНТОВ БЕЗ СУЕТЫ',
title: 'Хорошие партнёрства\nначинаются с ясного пути.',
description:
'От первого разговора до запуска. Единое пространство, где продажи, комплаенс и аккаунт-менеджеры помогают мерчантам двигаться вперёд.',
cta: 'В рабочее пространство',
signIn: 'Войти',
why: 'Меньше поисков. Больше движения.',
whyText: 'Нужный контекст — в нужном месте.',
feature1: 'Весь путь перед глазами',
feature1Text: 'Общая воронка от нового лида до запуска с понятной передачей между командами.',
feature2: 'Прозрачные проверки',
feature2Text: 'Чек-листы документов, заметки и история мерчанта в одном месте.',
feature3: 'Следующий шаг рядом',
feature3Text: 'Задачи и напоминания внутри приложения помогают не терять связь с мерчантами.',
visualTitle: 'Один общий путь',
visualSub: 'Вокруг вашей команды',
visualNote: 'Контекст остаётся с мерчантом на каждом этапе.',
footer: 'Вымышленный криптоплатёжный провайдер. Продуманное рабочее пространство.',
},
auth: {
eyebrow: 'С ВОЗВРАЩЕНИЕМ',
title: 'Продолжим в одном ритме.',
description: 'Войдите в рабочее пространство MerchantFlow.',
email: 'Электронная почта',
password: 'Пароль',
showPassword: 'Показать пароль',
hidePassword: 'Скрыть пароль',
submit: 'Войти в рабочее пространство',
submitting: 'Входим…',
demoTitle: 'Попробуйте демо',
demoText: 'Выберите аккаунт, чтобы заполнить данные, затем войдите.',
demoPassword: 'Демо-пароль',
back: 'На главную MerchantFlow',
sideTitle: 'Хорошая передача дел —\nоснова партнёрства.',
sideText: 'Ваши мерчанты, их история и следующий шаг. Всё в одном месте.',
expired: 'Сессия завершена. Войдите снова.',
},
validation: {
email: 'Введите корректный адрес почты.',
password: 'Введите пароль.',
passwordMax: 'Не более 128 символов.',
invalid: 'Проверьте это значение.',
},
errors: {
UNAUTHORIZED: 'Войдите, чтобы продолжить.',
INVALID_CREDENTIALS: 'Неверная почта или пароль.',
FORBIDDEN: 'У вас нет доступа к этому разделу.',
NOT_FOUND: 'Мерчант не найден или находится вне вашего портфеля.',
VALIDATION_ERROR: 'Проверьте данные и попробуйте снова.',
INTERNAL_ERROR: 'Не удалось загрузить данные. Попробуйте ещё раз.',
DATABASE_UNAVAILABLE: 'База данных недоступна. Попробуйте ещё раз.',
TOO_MANY_REQUESTS: 'Слишком много попыток входа. Попробуйте через пять минут.',
NETWORK: 'Не удалось подключиться. Проверьте соединение и попробуйте снова.',
RESPONSE: 'Получен неожиданный ответ. Попробуйте ещё раз.',
},
dashboard: {
eyebrow: 'КОМАНДА В ОДНОМ РИТМЕ',
title: 'Обзор',
description: 'Всё важное о ваших отношениях с мерчантами.',
welcome: 'С возвращением, {{name}}',
view: 'К мерчантам',
merchants: 'Всего мерчантов',
merchantsHint: 'В доступном вам портфеле',
reviews: 'Ожидают проверки',
reviewsHint: 'Готовы к комплаенсу',
overdue: 'Просроченные задачи',
overdueHint: 'Требуют вашего внимания',
changes: 'Смены этапов',
changesHint: 'За последние 30 дней',
pipeline: 'Воронка с первого взгляда',
pipelineText: 'У каждого партнёрства есть следующий этап.',
openPipeline: 'Открыть воронку',
activity: 'Последние события',
activityText: 'Что изменилось в вашем портфеле.',
priorities: 'В поле внимания',
prioritiesText: 'Следующие шаги и своевременная обратная связь.',
moved: 'Переход на этап',
added: 'Добавлен на этап',
emptyActivity: 'Событий пока нет',
scopeHead: 'Весь портфель мерчантов',
scopeManager: 'Закреплённые за вами мерчанты',
scopeCompliance: 'Мерчанты на KYB и комплаенс-проверке',
},
merchants: {
title: 'Мерчанты',
description: 'Люди и компании за каждым партнёрством.',
search: 'Название мерчанта или почта…',
filter: 'Фильтр по этапу',
allStages: 'Все этапы',
business: 'Компания',
location: 'Страна',
portfolio: 'ВАШ ПОРТФЕЛЬ МЕРЧАНТОВ',
contact: 'Основной контакт',
website: 'Сайт',
industry: 'Отрасль',
overview: 'О мерчанте',
details: 'Главное — в одном месте.',
checklist: 'Чек-лист KYB',
checklistText: 'Готовность документов к следующей проверке.',
notes: 'Заметки команды',
notesText: 'Контекст от тех, кто работает с мерчантом.',
history: 'История этапов',
historyText: 'Каждый шаг, включая возвраты.',
tasks: 'Связанные задачи',
tasksText: 'Дальнейшие действия по этому мерчанту.',
back: 'К списку мерчантов',
since: 'На этом этапе с {{date}}',
noNotes: 'Заметок пока нет',
noTasks: 'Связанных задач пока нет',
},
documents: {
INCORPORATION: 'Свидетельство о регистрации',
OWNERSHIP: 'Структура собственности',
UBO_IDENTIFICATION: 'Идентификация бенефициаров',
BUSINESS_ACTIVITY: 'Описание деятельности',
},
checklist: { MISSING: 'Отсутствует', RECEIVED: 'Получен', NEEDS_CORRECTION: 'Нужны исправления' },
pipeline: {
title: 'Воронка',
description: 'От первого знакомства до долгого партнёрства.',
journey: 'ПУТЬ К ЗАПУСКУ',
rejectedTitle: 'Закрыто · Отклонён',
rejectedText: 'Альтернативный исход вне успешного пути к запуску.',
stageSelect: 'Выбрать этап воронки',
empty: 'На этом этапе нет мерчантов',
count: '{{count}} мерчантов',
count_one: '{{count}} мерчант',
count_few: '{{count}} мерчанта',
count_many: '{{count}} мерчантов',
stageCount: '{{number}} из 8 этапов',
},
tasks: {
title: 'Задачи',
description: 'Немного порядка для следующего верного шага.',
ALL: 'Все задачи',
OPEN: 'Открытые',
OVERDUE: 'Просроченные',
UPCOMING: 'Предстоящие',
DONE: 'Выполненные',
due: 'Срок: {{date}}',
completed: 'Выполнено',
reminder: 'Напоминание',
reminderDue: 'Пора напомнить',
assigned: 'Ответственный: {{name}}',
empty: 'Здесь всё в порядке',
emptyText: 'Нет задач по выбранному фильтру.',
filter: 'Фильтр задач',
taskTitle: 'Задача',
dueDate: 'Срок',
},
review: {
title: 'Очередь проверок',
description: 'Полный контекст для уверенных решений.',
eyebrow: 'ПРОСТРАНСТВО КОМПЛАЕНСА',
count: '{{count}} мерчантов ожидают проверки',
count_one: '{{count}} мерчант ожидает проверки',
count_few: '{{count}} мерчанта ожидают проверки',
count_many: '{{count}} мерчантов ожидают проверки',
order: 'Сначала самые ранние',
empty: 'Очередь пуста',
emptyText: 'Мерчанты появятся здесь на этапе комплаенс-проверки.',
entered: 'Начало проверки',
view: 'Открыть чек-лист',
},
};
+46
View File
@@ -0,0 +1,46 @@
import React from 'react';
import ReactDOM from 'react-dom/client';
import { BrowserRouter, Routes, Route } from 'react-router';
import { QueryClientProvider } from '@tanstack/react-query';
import '@merchantflow/ui/globals.css';
import './i18n';
import { queryClient } from './lib/api';
import { ProtectedShell } from './components/shell';
import { Landing, Login } from './pages/public';
import {
Dashboard,
Merchants,
MerchantDetail,
Pipeline,
Tasks,
ReviewQueue,
NotFound,
} from './pages/crm';
document.addEventListener('keydown', () => {
document.documentElement.dataset.input = 'keyboard';
});
document.addEventListener('pointerdown', () => {
document.documentElement.dataset.input = 'pointer';
});
ReactDOM.createRoot(document.getElementById('root')!).render(
<React.StrictMode>
<QueryClientProvider client={queryClient}>
<BrowserRouter>
<Routes>
<Route path="/" element={<Landing />} />
<Route path="/login" element={<Login />} />
<Route path="/app" element={<ProtectedShell />}>
<Route index element={<Dashboard />} />
<Route path="merchants" element={<Merchants />} />
<Route path="merchants/:id" element={<MerchantDetail />} />
<Route path="pipeline" element={<Pipeline />} />
<Route path="tasks" element={<Tasks />} />
<Route path="review-queue" element={<ReviewQueue />} />
<Route path="*" element={<NotFound />} />
</Route>
<Route path="*" element={<NotFound />} />
</Routes>
</BrowserRouter>
</QueryClientProvider>
</React.StrictMode>,
);
+837
View File
@@ -0,0 +1,837 @@
import { useEffect, useState } from 'react';
import { Link, useOutletContext, useParams, useSearchParams } from 'react-router';
import { keepPreviousData, useQuery } from '@tanstack/react-query';
import { useTranslation } from 'react-i18next';
import {
ArrowRight,
ArrowUpRight,
ArrowLeft,
Building2,
ShieldCheck,
Clock3,
Activity,
Search,
ChevronLeft,
ChevronRight,
Check,
FileText,
Globe2,
Mail,
ExternalLink,
SlidersHorizontal,
LoaderCircle,
} from 'lucide-react';
import {
dashboardSchema,
merchantListSchema,
merchantDetailSchema,
pipelineSchema,
taskListSchema,
statuses,
successfulStages,
statusSchema,
taskFilters,
canSeeReviewQueue,
type Status,
type User,
type TaskFilter,
type Merchant,
} from '@merchantflow/contracts';
import { Input } from '@merchantflow/ui/components/input';
import { NativeSelect } from '@merchantflow/ui/components/native-select';
import {
Table,
TableHeader,
TableBody,
TableRow,
TableHead,
TableCell,
} 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 { useFormat } from '../lib/format';
import {
PageHeader,
SectionHeader,
QueryBoundary,
LinkButton,
Button,
StatusBadge,
Avatar,
ActivityFeed,
TaskRow,
MerchantCard,
EmptyState,
stageColors,
} from '../components/shared';
export function Dashboard() {
const { t } = useTranslation();
const f = useFormat();
const user = useOutletContext<User>();
const query = useQuery({
queryKey: ['dashboard'],
queryFn: ({ signal }) => api('/dashboard', dashboardSchema, { signal }),
});
return (
<>
<PageHeader
title={t('dashboard.title')}
description={t('dashboard.description')}
eyebrow={t('dashboard.eyebrow')}
action={
<LinkButton to="/app/merchants">
{t('dashboard.view')}
<ArrowUpRight className="size-4" />
</LinkButton>
}
/>
<QueryBoundary query={query}>
{(data) => (
<div className="space-y-6">
<div className="grid grid-cols-1 gap-3 min-[360px]:grid-cols-2 xl:grid-cols-4">
{[
{ key: 'merchants', value: data.merchantCount, Icon: Building2 },
{ key: 'reviews', value: data.reviewCount, Icon: ShieldCheck },
{ key: 'overdue', value: data.overdueTasks, Icon: Clock3 },
{ key: 'changes', value: data.transitionsLast30Days, Icon: Activity },
].map(({ key, value, Icon }, i) => (
<section key={key} className="surface p-5">
<div className="flex items-center justify-between gap-2">
<h2 className="text-xs font-medium text-muted-foreground">
{t(`dashboard.${key}`)}
</h2>
<div
className={cn(
'flex size-8 shrink-0 items-center justify-center rounded-lg',
i === 0 ? 'bg-[#edf4de] text-[#526a2e]' : 'bg-muted text-muted-foreground',
)}
>
<Icon className="size-4" aria-hidden="true" />
</div>
</div>
<p className="mb-2 mt-4 text-[32px] font-semibold leading-none tracking-tight tabular-nums">
{f.number(value)}
</p>
<p className="mt-3 text-[11px] text-muted-foreground">
{t(`dashboard.${key}Hint`)}
</p>
</section>
))}
</div>
<section className="surface">
<SectionHeader
title={t('dashboard.pipeline')}
description={t('dashboard.pipelineText')}
action={
<LinkButton to="/app/pipeline" variant="ghost" className="text-xs">
{t('dashboard.openPipeline')}
<ArrowRight className="size-3.5" />
</LinkButton>
}
/>
<div className="px-5 pb-6 pt-6 sm:px-6">
<div
className="mb-5 flex h-3 gap-1 overflow-hidden rounded-full"
aria-hidden="true"
>
{data.distribution
.filter((s) => s.status !== 'REJECTED' && s.count > 0)
.map((s) => (
<div
key={s.status}
style={{ flex: s.count, backgroundColor: stageColors[s.status] }}
/>
))}
</div>
<div className="grid grid-cols-2 gap-x-4 gap-y-4 sm:grid-cols-4 xl:grid-cols-8">
{data.distribution
.filter((s) => s.status !== 'REJECTED')
.map((s) => (
<Link
to={`/app/merchants?status=${s.status}`}
key={s.status}
className="flex min-h-11 flex-col justify-center gap-2 rounded-md"
>
<span className="flex items-start gap-1.5 text-[10px] leading-tight text-muted-foreground">
<span
style={{ backgroundColor: stageColors[s.status] }}
className="mt-0.5 size-1.5 shrink-0 rounded-full"
/>
{t(`statuses.${s.status}`)}
</span>
<span className="pl-3 text-lg font-semibold tabular-nums">
{f.number(s.count)}
</span>
</Link>
))}
</div>
</div>
</section>
<div className="grid gap-6 xl:grid-cols-[1.12fr_1fr]">
<section className="surface">
<SectionHeader
title={t('dashboard.activity')}
description={t('dashboard.activityText')}
/>
<ActivityFeed events={data.recentEvents} />
</section>
<section className="surface self-start">
<SectionHeader
title={t('dashboard.priorities')}
description={t('dashboard.prioritiesText')}
action={
<LinkButton to="/app/tasks" variant="ghost" className="text-xs">
{t('common.viewAll')}
<ArrowRight className="size-3.5" />
</LinkButton>
}
/>
<div className="mt-4">
{data.upcomingTasks.length ? (
data.upcomingTasks.map((task) => <TaskRow key={task.id} task={task} compact />)
) : (
<EmptyState title={t('tasks.empty')} />
)}
</div>
<div className="m-5 flex items-center gap-2 rounded-lg bg-[#f6f8f1] p-3 text-[11px] text-muted-foreground">
<ShieldCheck className="size-4 shrink-0 text-[#617d37]" aria-hidden="true" />
{t(
`dashboard.${user.role === 'HEAD_OF_SALES' ? 'scopeHead' : user.role === 'COMPLIANCE_OFFICER' ? 'scopeCompliance' : 'scopeManager'}`,
)}
</div>
</section>
</div>
</div>
)}
</QueryBoundary>
</>
);
}
function useDebounced(value: string) {
const [debounced, setDebounced] = useState(value);
useEffect(() => {
const timer = setTimeout(() => setDebounced(value), 200);
return () => clearTimeout(timer);
}, [value]);
return debounced;
}
function MerchantTable({ merchants }: { merchants: Merchant[] }) {
const { t } = useTranslation();
const f = useFormat();
return (
<>
<div className="hidden md:block">
<Table>
<TableHeader>
<TableRow className="bg-[#fafbf9] hover:bg-[#fafbf9]">
<TableHead className="pl-6">{t('common.merchant')}</TableHead>
<TableHead>{t('common.status')}</TableHead>
<TableHead>{t('merchants.location')}</TableHead>
<TableHead>{t('common.owner')}</TableHead>
<TableHead className="pr-6 text-right">{t('common.created')}</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{merchants.map((m) => (
<TableRow key={m.id} className="hover-surface">
<TableCell className="pl-6">
<Link
to={`/app/merchants/${m.id}`}
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}`)}
</p>
</div>
</Link>
</TableCell>
<TableCell>
<StatusBadge status={m.status} />
</TableCell>
<TableCell className="text-xs text-muted-foreground">
{f.country(m.country)}
</TableCell>
<TableCell className="text-xs">{m.owner.name}</TableCell>
<TableCell className="pr-6 text-right text-xs text-muted-foreground">
{f.shortDate(m.createdAt)}
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</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">
<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)}
</p>
</div>
<ChevronRight className="ml-auto size-4 shrink-0 text-muted-foreground" />
</div>
<div className="mt-4 flex flex-wrap items-center justify-between gap-2">
<StatusBadge status={m.status} />
<span className="text-xs text-muted-foreground">{m.owner.name}</span>
</div>
</Link>
))}
</div>
</>
);
}
export function Merchants() {
const { t } = useTranslation();
const f = useFormat();
const [params, setParams] = useSearchParams();
const search = params.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 update = (key: string, value: string) => {
const next = new URLSearchParams(params);
if (value) next.set(key, value);
else next.delete(key);
if (key !== 'page') next.delete('page');
setParams(next, { replace: true });
};
const query = useQuery({
queryKey: ['merchants', debounced, status, page],
queryFn: ({ signal }) =>
api(
`/merchants?${new URLSearchParams({ search: debounced, ...(status ? { status } : {}), page: String(page) })}`,
merchantListSchema,
{ signal },
),
placeholderData: keepPreviousData,
});
return (
<>
<PageHeader
title={t('merchants.title')}
description={t('merchants.description')}
eyebrow={t('merchants.portfolio')}
/>
<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="relative w-full sm:max-w-sm">
<Search
className="pointer-events-none absolute left-3 top-3.5 size-4 text-muted-foreground"
aria-hidden="true"
/>
<Input
aria-label={t('merchants.search')}
value={search}
onChange={(e) => update('search', e.target.value)}
maxLength={100}
placeholder={t('merchants.search')}
className="bg-white pl-10"
/>
{query.isFetching && (
<LoaderCircle
aria-label={t('common.loading')}
className="absolute right-3 top-3.5 size-4 animate-spin text-muted-foreground"
/>
)}
</div>
<div className="flex items-center gap-2">
<SlidersHorizontal
className="size-4 shrink-0 text-muted-foreground"
aria-hidden="true"
/>
<NativeSelect
aria-label={t('merchants.filter')}
value={status}
onChange={(e) => update('status', e.target.value)}
className="w-full bg-white sm:min-w-[190px]"
>
<option value="">{t('merchants.allStages')}</option>
{statuses.map((s) => (
<option key={s} value={s}>
{t(`statuses.${s}`)}
</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))}
>
<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>
}
/>
)
}
</QueryBoundary>
</section>
</>
);
}
export function MerchantDetail() {
const { id } = useParams();
const { t } = useTranslation();
const f = useFormat();
const query = useQuery({
queryKey: ['merchant', id],
queryFn: ({ signal }) =>
api(`/merchants/${encodeURIComponent(id ?? '')}`, merchantDetailSchema, { signal }),
});
return (
<>
<Link
to="/app/merchants"
className="mb-5 inline-flex min-h-11 items-center gap-2 text-xs text-muted-foreground"
>
<ArrowLeft className="size-3.5" />
{t('merchants.back')}
</Link>
<QueryBoundary query={query}>
{(m) => (
<>
<div className="mb-7 flex flex-wrap items-center gap-4">
<Avatar name={m.name} />
<div className="min-w-0">
<h1 className="page-title">{m.name}</h1>
<p className="mt-1 text-xs text-muted-foreground">
{t(`industry.${m.industry}`)} · {f.country(m.country)}
</p>
</div>
<div className="ml-auto">
<StatusBadge status={m.status} />
<p className="mt-2 text-[11px] text-muted-foreground">
{t('merchants.since', { date: f.date(m.stageEnteredAt) })}
</p>
</div>
</div>
<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 },
{ label: t('merchants.contact'), value: m.contactName },
{
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>
<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>
{doc.note && (
<p className="mt-2 text-xs leading-relaxed text-muted-foreground">
{doc.note}
</p>
)}
</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>
<section className="surface">
<SectionHeader
title={t('merchants.tasks')}
description={t('merchants.tasksText')}
/>
<div className="mt-4">
{m.tasks.length ? (
m.tasks.map((task) => <TaskRow key={task.id} task={task} />)
) : (
<EmptyState title={t('merchants.noTasks')} />
)}
</div>
</section>
</div>
</div>
</>
)}
</QueryBoundary>
</>
);
}
export function Pipeline() {
const { t } = useTranslation();
const f = useFormat();
const [stage, setStage] = useState<Status>('NEW_LEAD');
const query = useQuery({
queryKey: ['pipeline'],
queryFn: ({ signal }) => api('/pipeline', pipelineSchema, { signal }),
});
return (
<>
<PageHeader
title={t('pipeline.title')}
description={t('pipeline.description')}
eyebrow={t('pipeline.journey')}
/>
<QueryBoundary query={query}>
{(merchants) => (
<>
<NativeSelect
className="mb-5 w-full md:hidden"
aria-label={t('pipeline.stageSelect')}
value={stage}
onChange={(e) => setStage(e.target.value as Status)}
>
{successfulStages.map((s) => (
<option value={s} key={s}>
{t(`statuses.${s}`)} ({f.number(merchants.filter((m) => m.status === s).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);
return (
<section
key={s}
className={cn(
'min-w-0 rounded-xl border bg-[#f0f3ee] p-3',
s !== stage && '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] }}
/>
{t(`statuses.${s}`)}
</h2>
<span className="rounded-md border bg-white px-2 py-1 text-[10px] tabular-nums">
{f.number(items.length)}
</span>
</div>
<div className="space-y-3">
{items.map((m) => (
<MerchantCard key={m.id} merchant={m} />
))}
{!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">
{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>
</>
);
}
export function Tasks() {
const { t } = useTranslation();
const [params, setParams] = useSearchParams();
const raw = params.get('filter');
const filter: TaskFilter = taskFilters.includes(raw as TaskFilter) ? (raw as TaskFilter) : 'ALL';
const query = useQuery({
queryKey: ['tasks', filter],
queryFn: ({ signal }) => api(`/tasks?filter=${filter}`, taskListSchema, { signal }),
refetchInterval: 60000,
});
return (
<>
<PageHeader title={t('tasks.title')} description={t('tasks.description')} />
<section className="surface overflow-hidden">
<div
className="flex flex-wrap gap-1 border-b p-3"
role="group"
aria-label={t('tasks.filter')}
>
{taskFilters.map((s) => (
<Button
key={s}
variant="ghost"
aria-pressed={filter === s}
onClick={() => setParams(s === 'ALL' ? {} : { filter: s }, { replace: true })}
className={cn('text-xs', filter === s && 'bg-secondary')}
>
{t(`tasks.${s}`)}
</Button>
))}
</div>
<QueryBoundary query={query}>
{(tasks) =>
tasks.length ? (
<div>
{tasks.map((task) => (
<TaskRow key={task.id} task={task} />
))}
</div>
) : (
<EmptyState title={t('tasks.empty')} description={t('tasks.emptyText')} />
)
}
</QueryBoundary>
</section>
</>
);
}
export function ReviewQueue() {
const user = useOutletContext<User>();
const { t } = useTranslation();
const f = useFormat();
const allowed = canSeeReviewQueue(user.role);
const query = useQuery({
queryKey: ['review-queue'],
queryFn: ({ signal }) => api('/review-queue', pipelineSchema, { signal }),
enabled: allowed,
});
if (!allowed) return <NotFound forbidden />;
return (
<>
<PageHeader
title={t('review.title')}
description={t('review.description')}
eyebrow={t('review.eyebrow')}
/>
<QueryBoundary query={query}>
{(merchants) => (
<section className="surface overflow-hidden">
<div className="flex flex-wrap items-center justify-between gap-2 border-b px-5 py-5 sm:px-6">
<h2 className="text-sm font-semibold">
{t('review.count', { count: merchants.length })}
</h2>
<span className="inline-flex items-center gap-1.5 text-xs text-muted-foreground">
<Clock3 className="size-3.5" />
{t('review.order')}
</span>
</div>
{merchants.length ? (
merchants.map((m) => (
<div
key={m.id}
className="flex flex-col gap-5 border-b p-5 last:border-0 sm:flex-row sm:items-center sm:justify-between sm:p-6"
>
<div className="flex items-center gap-3">
<Avatar name={m.name} />
<div>
<Link
to={`/app/merchants/${m.id}`}
className="text-sm font-semibold hover:underline"
>
{m.name}
</Link>
<p className="mt-1 text-xs text-muted-foreground">
{m.owner.name} · {t(`industry.${m.industry}`)}
</p>
</div>
</div>
<div className="flex flex-wrap items-center justify-between gap-4">
<div>
<p className="mb-1 text-[10px] text-muted-foreground">
{t('review.entered')}
</p>
<p className="text-xs">{f.date(m.stageEnteredAt)}</p>
</div>
<LinkButton
to={`/app/merchants/${m.id}#checklist`}
variant="outline"
className="text-xs"
>
{t('review.view')}
<ArrowRight className="size-3.5" />
</LinkButton>
</div>
</div>
))
) : (
<EmptyState title={t('review.empty')} description={t('review.emptyText')} />
)}
</section>
)}
</QueryBoundary>
</>
);
}
export function NotFound({ forbidden = false }: { forbidden?: boolean }) {
const { t } = useTranslation();
return (
<div className="mx-auto max-w-lg py-16">
<EmptyState
title={t(forbidden ? 'common.noAccess' : 'common.notFound')}
description={t(forbidden ? 'common.noAccessText' : 'common.notFoundText')}
action={
<LinkButton to="/app">
{t('common.goHome')}
<ArrowRight className="size-4" />
</LinkButton>
}
/>
</div>
);
}
+281
View File
@@ -0,0 +1,281 @@
import { useState } from 'react';
import { Link, useNavigate, useSearchParams } from 'react-router';
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 { 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 { api, ApiError, queryClient, safeReturnTo } from '../lib/api';
function JourneyIllustration() {
const { t } = useTranslation();
return (
<div className="relative mx-auto w-full max-w-lg rounded-[24px] border border-[#dde5d3] bg-[#f0f4e9] p-6 sm:p-9">
<div className="mb-7 flex items-center justify-between gap-4">
<div>
<p className="text-sm font-semibold">{t('landing.visualTitle')}</p>
<p className="mt-1 text-xs text-muted-foreground">{t('landing.visualSub')}</p>
</div>
<div className="flex size-9 items-center justify-center rounded-full border bg-white">
<ArrowRight className="size-4 -rotate-45" aria-hidden="true" />
</div>
</div>
<div className="relative space-y-4 before:absolute before:inset-y-4 before:left-6 before:w-px before:bg-[#ccd6bd]">
{(['QUALIFIED', 'COMPLIANCE_REVIEW', 'LIVE'] as const).map((status, i) => (
<div
key={status}
className={`relative flex items-center gap-4 rounded-xl border bg-white p-4 shadow-[0_4px_15px_-10px_#56693d40] ${i === 1 ? 'sm:ml-8' : i === 2 ? 'sm:ml-16' : ''}`}
>
<div
className={`flex size-10 shrink-0 items-center justify-center rounded-xl ${i === 2 ? 'bg-primary' : 'bg-muted'}`}
>
{i === 0 ? (
<Check className="size-4" />
) : i === 1 ? (
<ShieldCheck className="size-4" />
) : (
<ArrowRight className="size-4 -rotate-45" />
)}
</div>
<div className="min-w-0">
<p className="mb-1.5 text-[10px] uppercase tracking-wider text-muted-foreground">
0{i + 1}
</p>
<StatusBadge status={status} />
</div>
</div>
))}
</div>
<p className="mt-7 flex items-center gap-2 text-xs text-muted-foreground">
<span className="size-1.5 shrink-0 rounded-full bg-[#718d41]" />
{t('landing.visualNote')}
</p>
</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);
const [params] = useSearchParams();
const navigate = useNavigate();
const form = useForm<LoginInput>({
resolver: zodResolver(loginSchema),
defaultValues: { email: '', password: '' },
});
const mutation = useMutation({
mutationFn: (input: LoginInput) =>
api('/auth/login', userSchema, { method: 'POST', body: JSON.stringify(input) }),
onSuccess: async (user) => {
await queryClient.cancelQueries();
queryClient.clear();
queryClient.setQueryData(['session'], user);
navigate(safeReturnTo(params.get('next')), { replace: true });
},
});
const demos = [
{ email: 'head', role: 'HEAD_OF_SALES' },
{ email: 'compliance', role: 'COMPLIANCE_OFFICER' },
{ email: 'manager1', role: 'ACCOUNT_MANAGER', name: 'Alex' },
{ email: 'manager2', role: 'ACCOUNT_MANAGER', name: 'Maria' },
];
return (
<div className="grid min-h-dvh bg-white lg:grid-cols-2">
<div className="flex flex-col px-5 py-5 sm:px-10">
<header className="flex items-center justify-between gap-3">
<Brand />
<LanguageSwitch />
</header>
<div className="mx-auto my-auto w-full max-w-[400px] py-12">
<Link
to="/"
className="mb-9 inline-flex min-h-11 items-center gap-2 text-xs text-muted-foreground"
>
<ArrowLeft className="size-3.5" />
{t('auth.back')}
</Link>
<p className="section-label mb-3">{t('auth.eyebrow')}</p>
<h1 className="text-3xl font-semibold tracking-tight">{t('auth.title')}</h1>
<p className="mb-8 mt-3 text-sm leading-relaxed text-muted-foreground">
{t('auth.description')}
</p>
<form
noValidate
onSubmit={form.handleSubmit((input) => mutation.mutate(input))}
className="space-y-5"
>
<FormField
id="email"
label={t('auth.email')}
error={
form.formState.errors.email &&
t(form.formState.errors.email.message ?? 'validation.email')
}
>
<Input
id="email"
type="email"
autoComplete="username"
placeholder="[email protected]"
{...form.register('email')}
aria-invalid={!!form.formState.errors.email}
aria-describedby={form.formState.errors.email ? 'email-error' : undefined}
/>
</FormField>
<FormField
id="password"
label={t('auth.password')}
error={
form.formState.errors.password &&
t(form.formState.errors.password.message ?? 'validation.password')
}
>
<div className="relative">
<Input
id="password"
type={show ? 'text' : 'password'}
autoComplete="current-password"
className="pr-12"
{...form.register('password')}
aria-invalid={!!form.formState.errors.password}
aria-describedby={form.formState.errors.password ? 'password-error' : undefined}
/>
<Button
type="button"
variant="ghost"
size="icon"
className="absolute right-0 top-0"
onClick={() => setShow((v) => !v)}
aria-label={t(show ? 'auth.hidePassword' : 'auth.showPassword')}
>
{show ? <EyeOff className="size-4" /> : <Eye className="size-4" />}
</Button>
</div>
</FormField>
{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>
)}
<Button type="submit" disabled={mutation.isPending} className="w-full">
{mutation.isPending ? <LoaderCircle className="size-4 animate-spin" /> : null}
{t(mutation.isPending ? 'auth.submitting' : 'auth.submit')}
{!mutation.isPending && <ArrowRight className="ml-auto size-4" />}
</Button>
</form>
<div className="mt-8 rounded-xl border bg-background p-4">
<h2 className="text-sm font-semibold">{t('auth.demoTitle')}</h2>
<p className="mb-3 mt-1 text-xs leading-relaxed text-muted-foreground">
{t('auth.demoText')}
</p>
<div className="grid grid-cols-2 gap-2">
{demos.map((d) => (
<Button
key={d.email}
variant="outline"
className="h-auto min-h-11 whitespace-normal bg-white px-2 py-2 text-[11px]"
onClick={() => {
form.setValue('email', `${d.email}@merchantflow.test`);
form.setValue('password', 'MerchantFlow123!');
form.clearErrors();
mutation.reset();
}}
>
{d.name ? `${d.name} · ` : ''}
{t(`roles.${d.role}`)}
</Button>
))}
</div>
<p className="mt-3 break-all text-[10px] text-muted-foreground">
{t('auth.demoPassword')}: <code>MerchantFlow123!</code>
</p>
</div>
</div>
</div>
<aside className="hidden flex-col justify-center border-l bg-[#f2f5ec] p-12 lg:flex">
<div className="mx-auto max-w-lg">
<h2 className="mb-4 whitespace-pre-line text-4xl font-medium leading-tight tracking-tight">
{t('auth.sideTitle')}
</h2>
<p className="mb-12 max-w-md text-sm leading-7 text-muted-foreground">
{t('auth.sideText')}
</p>
<JourneyIllustration />
</div>
</aside>
</div>
);
}
+14
View File
@@ -0,0 +1,14 @@
{
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"module": "ESNext",
"moduleResolution": "Bundler",
"jsx": "react-jsx",
"lib": ["ES2022", "DOM", "DOM.Iterable"],
"noEmit": true,
"baseUrl": ".",
"paths": { "@/*": ["./src/*"] },
"types": ["vite/client"]
},
"include": ["src", "vite.config.ts"]
}
+44
View File
@@ -0,0 +1,44 @@
import { defineConfig, loadEnv } from 'vite';
import react from '@vitejs/plugin-react';
import tailwindcss from '@tailwindcss/vite';
import { fileURLToPath } from 'node:url';
export default defineConfig(({ mode }) => {
const env = { ...loadEnv(mode, '../..', ''), ...process.env };
return {
plugins: [
react(),
tailwindcss(),
{
name: 'server-boundary',
generateBundle() {
for (const id of this.getModuleIds())
if (
id.includes('@prisma') ||
id.includes('/packages/database/') ||
/\/node_modules\/(pg|pg-pool)\//.test(id)
)
this.error(`Server dependency in browser bundle: ${id}`);
},
},
],
resolve: { alias: { '@': fileURLToPath(new URL('./src', import.meta.url)) } },
build: {
rollupOptions: {
output: {
manualChunks(id) {
if (/\/node_modules\/(react|react-dom|scheduler)\//.test(id)) return 'react-vendor';
if (/\/node_modules\/(zod|react-hook-form|@hookform)\//.test(id)) return 'forms';
if (id.includes('/@base-ui/') || id.includes('/@floating-ui/')) return 'primitives';
},
},
},
},
server: {
port: Number(env.WEB_PORT ?? 5173),
strictPort: true,
proxy: {
'/api': { target: `http://127.0.0.1:${env.API_PORT ?? 3001}`, changeOrigin: false },
},
},
};
});