import { MerchantControls, ChecklistControl, ReviewHistory, InteractionHistory, MerchantTasks, RecentInteractions, } from '../components/merchant-workflow'; 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(); const query = useQuery({ queryKey: ['dashboard'], queryFn: ({ signal }) => api('/dashboard', dashboardSchema, { signal }), }); return ( <> {t('dashboard.view')} } /> {(data) => (
{[ { 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) => (

{t(`dashboard.${key}`)}

{f.number(value)}

{t(`dashboard.${key}Hint`)}

))}
{t('dashboard.openPipeline')} } />
{t('common.viewAll')} } />
{data.upcomingTasks.length ? ( data.upcomingTasks.map((task) => ) ) : ( )}
)}
); } 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 ( <>
{t('common.merchant')} {t('common.status')} {t('merchants.location')} {t('common.owner')} {t('common.created')} {merchants.map((m) => (

{m.name}

{t(`industry.${m.industry}`)}

{f.country(m.country)} {m.owner?.name ?? t('workflow.unassigned')} {f.shortDate(m.createdAt)}
))}
{merchants.map((m) => (

{m.name}

{t(`industry.${m.industry}`)} · {f.country(m.country)}

{m.owner?.name ?? t('workflow.unassigned')}
))}
); } 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 ( <>
{(data) => data.items.length ? ( <>

{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), })}

) : ( setParams({})}> {t('common.clear')} } /> ) }
); } 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 ( <> {t('merchants.back')} {(m) => ( <>

{m.name}

{t(`industry.${m.industry}`)} · {f.country(m.country)}

{t('merchants.since', { date: f.date(m.stageEnteredAt) })}

{[ { 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: ( {new URL(m.website).hostname} ), }, { label: t('auth.email'), value: ( {m.contactEmail} ), }, ].map((item, i) => (
{item.label}
{item.value}
))}
{m.checklist.map((doc) => (
{doc.state === 'RECEIVED' ? ( ) : ( )}

{t(`documents.${doc.documentCode}`)}

{t(`checklist.${doc.state}`)}
{doc.note && (

{doc.note}

)}
))}
{m.notes.length ? ( m.notes.map((note) => (

{note.text}

{note.author.name} · {f.date(note.createdAt)}

)) ) : ( )}
)}
); } export function Pipeline() { const { t } = useTranslation(); const f = useFormat(); const [stage, setStage] = useState('NEW_LEAD'); const query = useQuery({ queryKey: ['pipeline'], queryFn: ({ signal }) => api('/pipeline', pipelineSchema, { signal }), }); return ( <> {(merchants) => ( <> setStage(e.target.value as Status)} > {successfulStages.map((s) => ( ))}
{successfulStages.map((s, i) => { const items = merchants.filter((m) => m.status === s); return (

{t(`statuses.${s}`)}

{f.number(items.length)}
{items.map((m) => ( ))} {!items.length && (

{t('pipeline.empty')}

)}

{t('pipeline.stageCount', { number: f.number(i + 1) })}

); })}

{t('pipeline.rejectedTitle')}

{t('pipeline.rejectedText')}

{merchants .filter((m) => m.status === 'REJECTED') .map((m) => ( ))} {!merchants.some((m) => m.status === 'REJECTED') && (

{t('pipeline.empty')}

)}
)}
); } 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 ( <>
{taskFilters.map((s) => ( ))}
{(tasks) => tasks.length ? (
{tasks.map((task) => ( ))}
) : ( ) }
); } export function ReviewQueue() { const user = useOutletContext(); 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 ; return ( <> {(merchants) => (

{t('review.count', { count: merchants.length })}

{t('review.order')}
{merchants.length ? ( merchants.map((m) => (
{m.name}

{m.owner?.name ?? t('workflow.unassigned')} · {t(`industry.${m.industry}`)}

{t('review.entered')}

{f.date(m.stageEnteredAt)}

{t('review.view')}
)) ) : ( )}
)}
); } export function NotFound({ forbidden = false }: { forbidden?: boolean }) { const { t } = useTranslation(); return (
{t('common.goHome')} } />
); }