Added tasks, reminders, and role-specific dashboards
This commit is contained in:
@@ -0,0 +1,342 @@
|
||||
import { useOutletContext, Link } from 'react-router';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { dashboardSchema, type User } from '@merchantflow/contracts';
|
||||
import { z } from 'zod';
|
||||
import { api } from '../lib/api';
|
||||
import { useFormat } from '../lib/format';
|
||||
import { useLiveRefresh } from '../lib/live-refresh';
|
||||
import {
|
||||
EmptyState,
|
||||
LinkButton,
|
||||
PageHeader,
|
||||
QueryBoundary,
|
||||
SectionHeader,
|
||||
stageColors,
|
||||
} from './shared';
|
||||
import { ActionableTask } from './tasks';
|
||||
import { StageAge } from './sales-workspace';
|
||||
import { RecentInteractions } from './merchant-workflow';
|
||||
type Data = z.infer<typeof dashboardSchema>;
|
||||
function Metric({
|
||||
title,
|
||||
value,
|
||||
hint,
|
||||
to,
|
||||
}: {
|
||||
title: string;
|
||||
value: string | number;
|
||||
hint?: string;
|
||||
to: string;
|
||||
}) {
|
||||
return (
|
||||
<Link to={to} className="surface hover-surface block p-5">
|
||||
<h2 className="text-xs font-medium text-muted-foreground">{title}</h2>
|
||||
<p className="my-4 text-3xl font-semibold tracking-tight tabular-nums">{value}</p>
|
||||
{hint && <p className="text-xs leading-relaxed text-muted-foreground">{hint}</p>}
|
||||
</Link>
|
||||
);
|
||||
}
|
||||
function BusinessMetrics({ data }: { data: Data }) {
|
||||
const { t } = useTranslation();
|
||||
const f = useFormat();
|
||||
return (
|
||||
<div className="grid gap-4 sm:grid-cols-2">
|
||||
<Metric
|
||||
title={t('operations.activation')}
|
||||
value={
|
||||
data.activation.rate === null
|
||||
? '—'
|
||||
: `${f.number(Number((100 * data.activation.rate).toFixed(1)))}%`
|
||||
}
|
||||
hint={
|
||||
data.activation.denominator
|
||||
? t('operations.activationHint', {
|
||||
live: data.activation.numerator,
|
||||
total: data.activation.denominator,
|
||||
})
|
||||
: t('operations.noMerchants')
|
||||
}
|
||||
to="/app/merchants?status=LIVE"
|
||||
/>
|
||||
<Metric
|
||||
title={t('operations.duration')}
|
||||
value={
|
||||
data.onboardingDuration.averageDays === null
|
||||
? '—'
|
||||
: t('operations.days', {
|
||||
value: f.number(Number(data.onboardingDuration.averageDays.toFixed(1))),
|
||||
})
|
||||
}
|
||||
hint={
|
||||
data.onboardingDuration.sampleCount
|
||||
? t('operations.durationHint', { count: data.onboardingDuration.sampleCount })
|
||||
: t('operations.noLive')
|
||||
}
|
||||
to="/app/merchants?cohort=REACHED_LIVE"
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
function Priorities({ data, compliance = false }: { data: Data; compliance?: boolean }) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<section className="surface">
|
||||
<SectionHeader
|
||||
title={t(compliance ? 'operations.reviewTasks' : 'operations.next')}
|
||||
description={t('operations.nextHint')}
|
||||
action={
|
||||
<LinkButton to="/app/tasks?filter=OPEN" variant="ghost">
|
||||
{t('common.viewAll')}
|
||||
</LinkButton>
|
||||
}
|
||||
/>
|
||||
{data.upcomingTasks.length ? (
|
||||
data.upcomingTasks.map((task) => <ActionableTask key={task.id} task={task} />)
|
||||
) : (
|
||||
<EmptyState title={t('operations.noTasks')} />
|
||||
)}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
function SalesDashboard({ data, user }: { data: Data; user: User }) {
|
||||
const { t } = useTranslation();
|
||||
const f = useFormat();
|
||||
const manager = user.role === 'ACCOUNT_MANAGER';
|
||||
const createdQuery = new URLSearchParams({ createdFrom: data.periodStart, createdTo: data.asOf });
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="grid gap-4 sm:grid-cols-2 xl:grid-cols-4">
|
||||
<Metric
|
||||
title={t('operations.total')}
|
||||
value={f.number(data.merchantCount)}
|
||||
to="/app/merchants"
|
||||
/>
|
||||
<Metric
|
||||
title={t('operations.newLeads')}
|
||||
value={f.number(data.newLeads)}
|
||||
hint={t('operations.newHint')}
|
||||
to={`/app/merchants?${createdQuery}`}
|
||||
/>
|
||||
<Metric
|
||||
title={t('operations.active')}
|
||||
value={f.number(data.activeOnboarding)}
|
||||
hint={t('operations.activeHint')}
|
||||
to="/app/merchants?cohort=ACTIVE_ONBOARDING"
|
||||
/>
|
||||
<Metric
|
||||
title={t('operations.live')}
|
||||
value={f.number(data.liveMerchants)}
|
||||
to="/app/merchants?status=LIVE"
|
||||
/>
|
||||
</div>
|
||||
<div className="grid gap-4 sm:grid-cols-2">
|
||||
<Metric
|
||||
title={t('operations.overdue')}
|
||||
value={f.number(data.overdueTasks)}
|
||||
hint={t('operations.overdueHint')}
|
||||
to="/app/tasks?filter=OVERDUE"
|
||||
/>
|
||||
{!manager && (
|
||||
<Metric
|
||||
title={t('operations.unassigned')}
|
||||
value={f.number(data.unassignedLeads)}
|
||||
to="/app/merchants?status=NEW_LEAD&ownerId=unassigned"
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
{manager && <Priorities data={data} />}
|
||||
<BusinessMetrics data={data} />
|
||||
<section className="surface">
|
||||
<SectionHeader
|
||||
title={t('dashboard.pipeline')}
|
||||
description={t('dashboard.pipelineText')}
|
||||
action={
|
||||
<LinkButton to="/app/pipeline" variant="ghost">
|
||||
{t('dashboard.openPipeline')}
|
||||
</LinkButton>
|
||||
}
|
||||
/>
|
||||
{data.merchantCount ? (
|
||||
<div className="px-5 pb-5">
|
||||
<div className="mb-5 flex h-3 gap-1 overflow-hidden rounded-full" aria-hidden="true">
|
||||
{data.distribution
|
||||
.filter((d) => d.count)
|
||||
.map((d) => (
|
||||
<div
|
||||
key={d.status}
|
||||
style={{ flex: d.count, backgroundColor: stageColors[d.status] }}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
<div className="grid grid-cols-2 gap-3 sm:grid-cols-3 xl:grid-cols-9">
|
||||
{data.distribution.map((d) => (
|
||||
<Link
|
||||
className="min-h-11 rounded-md p-1"
|
||||
key={d.status}
|
||||
to={`/app/merchants?status=${d.status}`}
|
||||
>
|
||||
<span className="text-xs text-muted-foreground">{t(`statuses.${d.status}`)}</span>
|
||||
<span className="mt-2 block text-lg font-semibold tabular-nums">
|
||||
{f.number(d.count)}
|
||||
</span>
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<EmptyState title={t('operations.noMerchants')} />
|
||||
)}
|
||||
</section>
|
||||
<section className="surface">
|
||||
<SectionHeader title={t(manager ? 'operations.ownWorkload' : 'operations.workload')} />
|
||||
<div className="grid gap-4 px-5 pb-5 sm:grid-cols-2">
|
||||
{data.workload.map((row) => {
|
||||
const owner = manager ? '' : `ownerId=${row.id}`;
|
||||
return (
|
||||
<article key={row.id} className="rounded-lg border p-4">
|
||||
<h3 className="mb-3 text-sm font-semibold">{row.name}</h3>
|
||||
<dl className="space-y-3 text-sm">
|
||||
{[
|
||||
['assigned', row.merchants, `/app/merchants?${owner}`],
|
||||
[
|
||||
'active',
|
||||
row.activeOnboarding,
|
||||
`/app/merchants?cohort=ACTIVE_ONBOARDING${owner ? '&' + owner : ''}`,
|
||||
],
|
||||
['openTasks', row.openTasks, `/app/tasks?filter=OPEN&assigneeId=${row.id}`],
|
||||
['overdue', row.overdueTasks, `/app/tasks?filter=OVERDUE&assigneeId=${row.id}`],
|
||||
].map(([label, value, to]) => (
|
||||
<div key={label} className="flex justify-between gap-3">
|
||||
<dt>{t(`operations.${label}`)}</dt>
|
||||
<dd>
|
||||
<Link className="font-semibold underline tabular-nums" to={String(to)}>
|
||||
{f.number(Number(value))}
|
||||
</Link>
|
||||
</dd>
|
||||
</div>
|
||||
))}
|
||||
</dl>
|
||||
</article>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</section>
|
||||
{!manager && <Priorities data={data} />}
|
||||
<section className="surface">
|
||||
<SectionHeader title={t('dashboard.activity')} description={t('dashboard.activityText')} />
|
||||
{data.recentActivities.length ? (
|
||||
<RecentInteractions activities={data.recentActivities} />
|
||||
) : (
|
||||
<EmptyState title={t('operations.noActivity')} />
|
||||
)}
|
||||
</section>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
function ComplianceDashboard({ data }: { data: Data }) {
|
||||
const { t } = useTranslation();
|
||||
const f = useFormat();
|
||||
const history = `/app/review-queue?${new URLSearchParams({ view: 'DECISIONS', decidedFrom: data.periodStart, decidedTo: data.asOf })}`;
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="grid gap-4 sm:grid-cols-3">
|
||||
<Metric
|
||||
title={t('operations.pending')}
|
||||
value={f.number(data.reviewCount)}
|
||||
to="/app/review-queue"
|
||||
/>
|
||||
<Metric
|
||||
title={t('operations.decisions')}
|
||||
value={f.number(data.decisionsLast30Days)}
|
||||
hint={t('operations.decisionsHint')}
|
||||
to={history}
|
||||
/>
|
||||
<Metric
|
||||
title={t('operations.overdue')}
|
||||
value={f.number(data.overdueTasks)}
|
||||
hint={t('operations.personal')}
|
||||
to="/app/tasks?filter=OVERDUE"
|
||||
/>
|
||||
</div>
|
||||
<section className="surface">
|
||||
<SectionHeader
|
||||
title={t('operations.oldest')}
|
||||
action={
|
||||
<LinkButton to="/app/review-queue" variant="ghost">
|
||||
{t('common.viewAll')}
|
||||
</LinkButton>
|
||||
}
|
||||
/>
|
||||
{data.oldestReviews.length ? (
|
||||
<div className="divide-y px-5 pb-3">
|
||||
{data.oldestReviews.map((review) => (
|
||||
<Link
|
||||
className="flex min-h-16 flex-wrap items-center justify-between gap-3 py-4"
|
||||
key={review.id}
|
||||
to={`/app/merchants/${review.merchant.id}?tab=onboarding#review-${review.id}`}
|
||||
>
|
||||
<span className="text-sm font-semibold">{review.merchant.name}</span>
|
||||
<span className="text-xs text-muted-foreground">
|
||||
<StageAge since={review.submittedAt} waiting /> · {f.dateTime(review.submittedAt)}
|
||||
</span>
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<EmptyState title={t('operations.noReviews')} />
|
||||
)}
|
||||
</section>
|
||||
<div className="grid gap-4 sm:grid-cols-3">
|
||||
{data.decisions.map((d) => (
|
||||
<Metric
|
||||
key={d.decision}
|
||||
title={t(`workflow.${d.decision}`)}
|
||||
value={f.number(d.count)}
|
||||
to={`${history}&decision=${d.decision}`}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
<Priorities data={data} compliance />
|
||||
<BusinessMetrics data={data} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
export function Dashboard() {
|
||||
const { t } = useTranslation();
|
||||
const user = useOutletContext<User>();
|
||||
const query = useQuery({
|
||||
queryKey: ['dashboard'],
|
||||
queryFn: ({ signal }) => api('/dashboard', dashboardSchema, { signal }),
|
||||
});
|
||||
useLiveRefresh(query.refetch);
|
||||
const role =
|
||||
user.role === 'HEAD_OF_SALES'
|
||||
? 'head'
|
||||
: user.role === 'ACCOUNT_MANAGER'
|
||||
? 'manager'
|
||||
: 'compliance';
|
||||
return (
|
||||
<>
|
||||
<PageHeader
|
||||
title={t(`operations.${role}Title`)}
|
||||
description={t(`operations.${role}Description`)}
|
||||
eyebrow={t('dashboard.eyebrow')}
|
||||
action={
|
||||
<LinkButton to={role === 'compliance' ? '/app/review-queue' : '/app/merchants'}>
|
||||
{t(role === 'compliance' ? 'review.title' : 'dashboard.view')}
|
||||
</LinkButton>
|
||||
}
|
||||
/>
|
||||
<QueryBoundary query={query}>
|
||||
{(data) =>
|
||||
role === 'compliance' ? (
|
||||
<ComplianceDashboard data={data} />
|
||||
) : (
|
||||
<SalesDashboard data={data} user={user} />
|
||||
)
|
||||
}
|
||||
</QueryBoundary>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -12,15 +12,13 @@ import {
|
||||
isRequiredDocument,
|
||||
sources,
|
||||
statuses,
|
||||
taskInputSchema,
|
||||
type MerchantDetail,
|
||||
type Task,
|
||||
} from '@merchantflow/contracts';
|
||||
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';
|
||||
import { Button, SectionHeader } from './shared';
|
||||
|
||||
const identityFields = [
|
||||
'name',
|
||||
@@ -431,111 +429,7 @@ export function InteractionHistory({ merchant: m }: { merchant: MerchantDetail }
|
||||
</section>
|
||||
);
|
||||
}
|
||||
const localDate = (value: string) => {
|
||||
const date = new Date(value);
|
||||
return new Date(date.getTime() - date.getTimezoneOffset() * 60000).toISOString().slice(0, 16);
|
||||
};
|
||||
const isoDate = (value: string) => {
|
||||
const date = new Date(value);
|
||||
return Number.isFinite(date.getTime()) ? date.toISOString() : '';
|
||||
};
|
||||
export function MerchantTasks({ merchant: m }: { merchant: MerchantDetail }) {
|
||||
const { t } = useTranslation();
|
||||
const [edit, setEdit] = useState<string | null>(null);
|
||||
const action = useAction(m, () => setEdit(null));
|
||||
const existing = m.tasks.find((task) => task.id === edit);
|
||||
const complete = (task: Task) =>
|
||||
action.mutate({
|
||||
path: `/tasks/${task.id}`,
|
||||
body: {
|
||||
version: m.version,
|
||||
title: task.title,
|
||||
dueAt: task.dueAt,
|
||||
remindAt: task.remindAt,
|
||||
status: 'DONE',
|
||||
},
|
||||
});
|
||||
return (
|
||||
<section className="surface" id="tasks">
|
||||
<SectionHeader
|
||||
title={t('merchants.tasks')}
|
||||
description={t('workflow.taskOwnership')}
|
||||
action={
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => {
|
||||
action.reset();
|
||||
setEdit('new');
|
||||
}}
|
||||
>
|
||||
{t('workflow.addTask')}
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
<div className="p-5">{action.feedback}</div>
|
||||
{m.tasks.map((task) => (
|
||||
<div key={task.id} className="border-t">
|
||||
<TaskRow task={task} />
|
||||
{task.kind === m.capabilities.manageTaskKind && (
|
||||
<div className="flex flex-wrap gap-2 px-5 pb-4">
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => {
|
||||
action.reset();
|
||||
setEdit(task.id);
|
||||
}}
|
||||
>
|
||||
{t('workflow.editTask')}
|
||||
</Button>
|
||||
{task.status === 'OPEN' && (
|
||||
<Button variant="ghost" disabled={action.isPending} onClick={() => complete(task)}>
|
||||
{t('workflow.complete')}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
{edit && (
|
||||
<Editor
|
||||
title={t(existing ? 'workflow.editTask' : 'workflow.addTask')}
|
||||
fields={[
|
||||
{ name: 'title' },
|
||||
{ name: 'dueAt', type: 'datetime-local' },
|
||||
{ name: 'remindAt', type: 'datetime-local' },
|
||||
{
|
||||
name: 'status',
|
||||
options: ['OPEN', 'DONE'].map((value) => ({ value, label: t(`tasks.${value}`) })),
|
||||
},
|
||||
]}
|
||||
initial={{
|
||||
title: existing?.title ?? '',
|
||||
dueAt: localDate(existing?.dueAt ?? new Date(Date.now() + 86400000).toISOString()),
|
||||
remindAt: existing?.remindAt ? localDate(existing.remindAt) : '',
|
||||
status: existing?.status ?? 'OPEN',
|
||||
}}
|
||||
schema={taskInputSchema}
|
||||
build={(values) => ({
|
||||
...values,
|
||||
version: m.version,
|
||||
dueAt: isoDate(values.dueAt!),
|
||||
remindAt: values.remindAt ? isoDate(values.remindAt) : null,
|
||||
})}
|
||||
submit={(body) =>
|
||||
action.mutate({
|
||||
path: `/tasks${existing ? `/${existing.id}` : ''}`,
|
||||
method: existing ? 'PATCH' : 'POST',
|
||||
body,
|
||||
})
|
||||
}
|
||||
close={() => setEdit(null)}
|
||||
pending={action.isPending}
|
||||
feedback={action.feedback}
|
||||
/>
|
||||
)}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
export { MerchantTasks } from './tasks';
|
||||
export function RecentInteractions({ activities }: { activities: MerchantDetail['activities'] }) {
|
||||
const { t } = useTranslation();
|
||||
const f = useFormat();
|
||||
|
||||
@@ -0,0 +1,97 @@
|
||||
import { useState } from 'react';
|
||||
import { useMutation, useQuery } from '@tanstack/react-query';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Bell } from 'lucide-react';
|
||||
import { mutationResultSchema, taskListSchema, type Task } from '@merchantflow/contracts';
|
||||
import {
|
||||
Sheet,
|
||||
SheetContent,
|
||||
SheetTitle,
|
||||
SheetDescription,
|
||||
} from '@merchantflow/ui/components/sheet';
|
||||
import { api, queryClient } from '../lib/api';
|
||||
import { useLiveRefresh } from '../lib/live-refresh';
|
||||
import { Button, EmptyState, QueryBoundary, TaskRow } from './shared';
|
||||
export function ReminderInbox() {
|
||||
const { t } = useTranslation();
|
||||
const [open, setOpen] = useState(false);
|
||||
const query = useQuery({
|
||||
queryKey: ['reminders'],
|
||||
queryFn: ({ signal }) => api('/reminders', taskListSchema, { signal }),
|
||||
staleTime: 0,
|
||||
refetchOnMount: 'always',
|
||||
refetchOnWindowFocus: 'always',
|
||||
refetchOnReconnect: 'always',
|
||||
});
|
||||
useLiveRefresh(query.refetch);
|
||||
const dismissal = useMutation({
|
||||
mutationFn: (task: Task) =>
|
||||
api(`/tasks/${task.id}/reminder-dismissal`, mutationResultSchema, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ reminderRevision: task.reminderRevision }),
|
||||
}),
|
||||
onSettled: () => queryClient.invalidateQueries({ queryKey: ['reminders'] }),
|
||||
});
|
||||
const count = query.data?.length;
|
||||
return (
|
||||
<>
|
||||
<Button
|
||||
variant="ghost"
|
||||
className="relative"
|
||||
aria-label={
|
||||
query.isError || count === undefined
|
||||
? t('operations.reminders')
|
||||
: t('operations.remindersCount', { count })
|
||||
}
|
||||
onClick={() => {
|
||||
setOpen(true);
|
||||
void query.refetch();
|
||||
}}
|
||||
>
|
||||
<Bell className="size-5" aria-hidden="true" />
|
||||
<span aria-live="polite" className="tabular-nums">
|
||||
{query.isError ? '!' : count ? count : ''}
|
||||
</span>
|
||||
</Button>
|
||||
<Sheet open={open} onOpenChange={setOpen}>
|
||||
<SheetContent
|
||||
closeLabel={t('common.close')}
|
||||
className="w-full! overflow-y-auto p-5 sm:max-w-lg!"
|
||||
>
|
||||
<SheetTitle>{t('operations.reminders')}</SheetTitle>
|
||||
<SheetDescription>{t('operations.inboxDescription')}</SheetDescription>
|
||||
{dismissal.isError && (
|
||||
<p role="alert" className="text-sm text-destructive">
|
||||
{t('operations.remindersError')}
|
||||
</p>
|
||||
)}
|
||||
<QueryBoundary query={query}>
|
||||
{(tasks) =>
|
||||
tasks.length ? (
|
||||
<div>
|
||||
{tasks.map((task) => (
|
||||
<div className="border-b pb-3" key={task.id}>
|
||||
<TaskRow task={task} onNavigate={() => setOpen(false)} />
|
||||
<Button
|
||||
variant="outline"
|
||||
disabled={dismissal.isPending}
|
||||
onClick={() => dismissal.mutate(task)}
|
||||
>
|
||||
{t('operations.dismiss')}
|
||||
</Button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<EmptyState
|
||||
title={t('operations.noReminders')}
|
||||
description={t('operations.noRemindersHint')}
|
||||
/>
|
||||
)
|
||||
}
|
||||
</QueryBoundary>
|
||||
</SheetContent>
|
||||
</Sheet>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -248,7 +248,15 @@ export function MerchantCard({ merchant, className }: { merchant: Merchant; clas
|
||||
</Link>
|
||||
);
|
||||
}
|
||||
export function TaskRow({ task, compact = false }: { task: Task; compact?: boolean }) {
|
||||
export function TaskRow({
|
||||
task,
|
||||
compact = false,
|
||||
onNavigate,
|
||||
}: {
|
||||
task: Task;
|
||||
compact?: boolean;
|
||||
onNavigate?: () => void;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const f = useFormat();
|
||||
const done = task.status === 'DONE';
|
||||
@@ -272,14 +280,20 @@ export function TaskRow({ task, compact = false }: { task: Task; compact?: boole
|
||||
{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">
|
||||
<Link
|
||||
to={`/app/merchants/${task.merchant.id}?tab=tasks#task-${task.id}`}
|
||||
onClick={onNavigate}
|
||||
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) })}
|
||||
{done
|
||||
? `${t('tasks.completed')} · ${f.dateTime(task.completedAt ?? task.dueAt)}`
|
||||
: t('tasks.due', { date: f.dateTime(task.dueAt) })}
|
||||
{overdue && ` · ${t('tasks.OVERDUE')}`}
|
||||
</span>
|
||||
</div>
|
||||
@@ -290,8 +304,8 @@ export function TaskRow({ task, compact = false }: { task: Task; compact?: boole
|
||||
<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)}`}
|
||||
? `${t('tasks.reminderDue')} · ${f.dateTime(task.remindAt)}`
|
||||
: `${t('tasks.reminder')}: ${f.dateTime(task.remindAt)}`}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { ReminderInbox } from './reminders';
|
||||
import { useState, useEffect } from 'react';
|
||||
import { NavLink, Navigate, Outlet, useLocation, useNavigate } from 'react-router';
|
||||
import { useQuery, useMutation } from '@tanstack/react-query';
|
||||
@@ -171,6 +172,7 @@ function AuthenticatedShell({ user }: { user: User }) {
|
||||
<span className="hidden text-xs text-muted-foreground xl:block">
|
||||
{f.date(new Date())}
|
||||
</span>
|
||||
<ReminderInbox />
|
||||
<LanguageSwitch />
|
||||
</div>
|
||||
</header>
|
||||
|
||||
@@ -0,0 +1,361 @@
|
||||
import { useState } from 'react';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { useOutletContext, useSearchParams } from 'react-router';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import {
|
||||
merchantDetailSchema,
|
||||
merchantListSchema,
|
||||
taskInputSchema,
|
||||
taskListSchema,
|
||||
taskFilters,
|
||||
type MerchantDetail,
|
||||
type Task,
|
||||
type User,
|
||||
type TaskFilter,
|
||||
} from '@merchantflow/contracts';
|
||||
import { Input } from '@merchantflow/ui/components/input';
|
||||
import {
|
||||
Sheet,
|
||||
SheetContent,
|
||||
SheetTitle,
|
||||
SheetDescription,
|
||||
} from '@merchantflow/ui/components/sheet';
|
||||
import { api, ApiError } from '../lib/api';
|
||||
import { useLiveRefresh, viewerTimeZone } from '../lib/live-refresh';
|
||||
import { Button, EmptyState, PageHeader, QueryBoundary, SectionHeader, TaskRow } from './shared';
|
||||
import { Editor, useAction } from './workflow-form';
|
||||
const localDate = (value: string) => {
|
||||
const date = new Date(value);
|
||||
return new Date(date.getTime() - date.getTimezoneOffset() * 60000).toISOString().slice(0, 16);
|
||||
};
|
||||
const isoDate = (value: string) => {
|
||||
const date = new Date(value);
|
||||
return Number.isFinite(date.getTime()) ? date.toISOString() : '';
|
||||
};
|
||||
function TaskEditor({
|
||||
merchant,
|
||||
task,
|
||||
close,
|
||||
assignee,
|
||||
}: {
|
||||
merchant: { id: string; version: number };
|
||||
task?: Task;
|
||||
close: () => void;
|
||||
assignee: string;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const [version, setVersion] = useState(merchant.version);
|
||||
const [refreshed, setRefreshed] = useState(false);
|
||||
const [refreshError, setRefreshError] = useState(false);
|
||||
const action = useAction(merchant, close);
|
||||
const feedback = (
|
||||
<>
|
||||
{action.feedback}
|
||||
{refreshed && (
|
||||
<p role="status" className="text-sm">
|
||||
{t('operations.versionLoaded')}
|
||||
</p>
|
||||
)}
|
||||
{refreshError && <p role="alert">{t('common.errorTitle')}</p>}
|
||||
{action.error instanceof ApiError && action.error.status === 409 && (
|
||||
<Button
|
||||
variant="outline"
|
||||
type="button"
|
||||
onClick={async () => {
|
||||
try {
|
||||
const latest = await api(`/merchants/${merchant.id}`, merchantDetailSchema);
|
||||
setVersion(latest.version);
|
||||
setRefreshed(true);
|
||||
setRefreshError(false);
|
||||
action.reset();
|
||||
} catch {
|
||||
setRefreshError(true);
|
||||
}
|
||||
}}
|
||||
>
|
||||
{t('operations.reloadVersion')}
|
||||
</Button>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
return (
|
||||
<Editor
|
||||
title={t(task ? 'workflow.editTask' : 'workflow.addTask')}
|
||||
description={`${t('operations.assignee', { name: assignee })} · ${t('operations.timeZone', { zone: viewerTimeZone() })}`}
|
||||
fields={[
|
||||
{ name: 'title' },
|
||||
{ name: 'dueAt', type: 'datetime-local' },
|
||||
{ name: 'remindAt', type: 'datetime-local' },
|
||||
{
|
||||
name: 'status',
|
||||
options: ['OPEN', 'DONE'].map((value) => ({ value, label: t(`tasks.${value}`) })),
|
||||
},
|
||||
]}
|
||||
initial={{
|
||||
title: task?.title ?? '',
|
||||
dueAt: localDate(task?.dueAt ?? new Date(Date.now() + 86400000).toISOString()),
|
||||
remindAt: task?.remindAt ? localDate(task.remindAt) : '',
|
||||
status: task?.status ?? 'OPEN',
|
||||
}}
|
||||
schema={taskInputSchema}
|
||||
build={(values) => ({
|
||||
...values,
|
||||
version,
|
||||
dueAt: task && values.dueAt === localDate(task.dueAt) ? task.dueAt : isoDate(values.dueAt!),
|
||||
remindAt:
|
||||
task?.remindAt && values.remindAt === localDate(task.remindAt)
|
||||
? task.remindAt
|
||||
: values.remindAt
|
||||
? isoDate(values.remindAt)
|
||||
: null,
|
||||
})}
|
||||
submit={(body) =>
|
||||
action.mutate({
|
||||
path: `/tasks${task ? `/${task.id}` : ''}`,
|
||||
method: task ? 'PATCH' : 'POST',
|
||||
body,
|
||||
})
|
||||
}
|
||||
close={close}
|
||||
pending={action.isPending}
|
||||
feedback={feedback}
|
||||
/>
|
||||
);
|
||||
}
|
||||
export function ActionableTask({ task }: { task: Task }) {
|
||||
const { t } = useTranslation();
|
||||
const [editing, setEditing] = useState<Task | null>(null);
|
||||
const action = useAction(task.merchant);
|
||||
const changeStatus = (status: 'OPEN' | 'DONE') =>
|
||||
action.mutate({
|
||||
path: `/tasks/${task.id}`,
|
||||
body: {
|
||||
version: task.merchant.version,
|
||||
title: task.title,
|
||||
dueAt: task.dueAt,
|
||||
remindAt: task.remindAt,
|
||||
status,
|
||||
},
|
||||
});
|
||||
return (
|
||||
<div id={`task-${task.id}`} className="border-t first:border-0 scroll-mt-5">
|
||||
<TaskRow task={task} />
|
||||
<div className="flex flex-wrap items-center gap-2 px-5 pb-4">
|
||||
{task.capabilities.edit && (
|
||||
<Button variant="outline" onClick={() => setEditing(task)}>
|
||||
{t('workflow.editTask')}
|
||||
</Button>
|
||||
)}
|
||||
{task.capabilities.complete && (
|
||||
<Button variant="ghost" disabled={action.isPending} onClick={() => changeStatus('DONE')}>
|
||||
{t('workflow.complete')}
|
||||
</Button>
|
||||
)}
|
||||
{task.capabilities.reopen && (
|
||||
<Button variant="ghost" disabled={action.isPending} onClick={() => changeStatus('OPEN')}>
|
||||
{t('operations.reopen')}
|
||||
</Button>
|
||||
)}
|
||||
{action.feedback}
|
||||
</div>
|
||||
{editing && (
|
||||
<TaskEditor
|
||||
merchant={editing.merchant}
|
||||
task={editing}
|
||||
assignee={editing.assignee.name}
|
||||
close={() => setEditing(null)}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
function TaskComposer({ merchant, close }: { merchant?: MerchantDetail; close: () => void }) {
|
||||
const { t } = useTranslation();
|
||||
const user = useOutletContext<User>();
|
||||
const [search, setSearch] = useState('');
|
||||
const [page, setPage] = useState(1);
|
||||
const [selected, setSelected] = useState<string | null>(null);
|
||||
const directory = useQuery({
|
||||
queryKey: ['merchants', 'task-picker', search, page],
|
||||
queryFn: ({ signal }) =>
|
||||
api(`/merchants?${new URLSearchParams({ search, page: String(page) })}`, merchantListSchema, {
|
||||
signal,
|
||||
}),
|
||||
enabled: !merchant && !selected,
|
||||
});
|
||||
const detail = useQuery({
|
||||
queryKey: ['merchant', selected],
|
||||
queryFn: ({ signal }) => api(`/merchants/${selected}`, merchantDetailSchema, { signal }),
|
||||
enabled: !!selected,
|
||||
});
|
||||
const current = merchant ?? detail.data;
|
||||
if (current)
|
||||
return (
|
||||
<TaskEditor
|
||||
merchant={current}
|
||||
assignee={
|
||||
user.role === 'COMPLIANCE_OFFICER' ? user.name : (current.owner?.name ?? user.name)
|
||||
}
|
||||
close={close}
|
||||
/>
|
||||
);
|
||||
return (
|
||||
<Sheet
|
||||
open
|
||||
onOpenChange={(open) => {
|
||||
if (!open) close();
|
||||
}}
|
||||
>
|
||||
<SheetContent closeLabel={t('common.close')} className="overflow-y-auto p-6">
|
||||
<SheetTitle>{t('operations.chooseMerchant')}</SheetTitle>
|
||||
<SheetDescription>{t('operations.ownerRule')}</SheetDescription>
|
||||
{selected ? (
|
||||
<QueryBoundary query={detail}>{() => null}</QueryBoundary>
|
||||
) : (
|
||||
<>
|
||||
<Input
|
||||
aria-label={t('operations.searchMerchant')}
|
||||
value={search}
|
||||
onChange={(e) => {
|
||||
setSearch(e.target.value);
|
||||
setPage(1);
|
||||
}}
|
||||
/>
|
||||
<QueryBoundary query={directory}>
|
||||
{(data) => (
|
||||
<div className="space-y-2">
|
||||
{data.items.map((m) => (
|
||||
<Button
|
||||
key={m.id}
|
||||
variant="outline"
|
||||
className="h-auto w-full justify-start whitespace-normal py-3 text-left"
|
||||
onClick={() => setSelected(m.id)}
|
||||
>
|
||||
{m.name}
|
||||
</Button>
|
||||
))}
|
||||
{!data.items.length && <EmptyState title={t('common.noResults')} />}
|
||||
<div className="flex justify-between gap-2">
|
||||
<Button
|
||||
variant="ghost"
|
||||
disabled={data.page <= 1}
|
||||
onClick={() => setPage((p) => p - 1)}
|
||||
>
|
||||
{t('common.previous')}
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
disabled={data.page * data.pageSize >= data.total}
|
||||
onClick={() => setPage((p) => p + 1)}
|
||||
>
|
||||
{t('common.next')}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</QueryBoundary>
|
||||
</>
|
||||
)}
|
||||
</SheetContent>
|
||||
</Sheet>
|
||||
);
|
||||
}
|
||||
export function MerchantTasks({ merchant }: { merchant: MerchantDetail }) {
|
||||
const { t } = useTranslation();
|
||||
const [creating, setCreating] = useState(false);
|
||||
return (
|
||||
<section id="tasks" className="surface">
|
||||
<SectionHeader
|
||||
title={t('merchants.tasks')}
|
||||
description={t('operations.ownerRule')}
|
||||
action={
|
||||
<Button variant="outline" onClick={() => setCreating(true)}>
|
||||
{t('workflow.addTask')}
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
{merchant.tasks.length ? (
|
||||
merchant.tasks.map((task) => <ActionableTask key={task.id} task={task} />)
|
||||
) : (
|
||||
<EmptyState title={t('operations.noTasks')} />
|
||||
)}
|
||||
{creating && <TaskComposer merchant={merchant} close={() => setCreating(false)} />}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
export function Tasks() {
|
||||
const { t } = useTranslation();
|
||||
const [params, setParams] = useSearchParams();
|
||||
const [creating, setCreating] = useState(false);
|
||||
const raw = params.get('filter');
|
||||
const filter: TaskFilter = taskFilters.includes(raw as TaskFilter)
|
||||
? (raw as TaskFilter)
|
||||
: 'TODAY';
|
||||
const queryParams = new URLSearchParams({ filter, timeZone: viewerTimeZone() });
|
||||
for (const key of ['merchantId', 'assigneeId'])
|
||||
if (params.get(key)) queryParams.set(key, params.get(key)!);
|
||||
const serialized = queryParams.toString();
|
||||
const query = useQuery({
|
||||
queryKey: ['tasks', serialized],
|
||||
queryFn: ({ signal }) => api(`/tasks?${serialized}`, taskListSchema, { signal }),
|
||||
});
|
||||
useLiveRefresh(query.refetch);
|
||||
const hint = {
|
||||
TODAY: 'todayHint',
|
||||
UPCOMING: 'upcomingHint',
|
||||
OVERDUE: 'overdueHint',
|
||||
DONE: 'completedHint',
|
||||
ALL: 'ownerRule',
|
||||
OPEN: 'ownerRule',
|
||||
}[filter];
|
||||
return (
|
||||
<>
|
||||
<PageHeader
|
||||
title={t('tasks.title')}
|
||||
description={`${t(`operations.${hint}`)} ${t('operations.timeZone', { zone: viewerTimeZone() })}`}
|
||||
action={<Button onClick={() => setCreating(true)}>{t('workflow.addTask')}</Button>}
|
||||
/>
|
||||
<section className="surface overflow-hidden">
|
||||
<div
|
||||
role="group"
|
||||
aria-label={t('tasks.filter')}
|
||||
className="flex flex-wrap gap-1 border-b p-3"
|
||||
>
|
||||
{taskFilters.map((value) => (
|
||||
<Button
|
||||
key={value}
|
||||
variant="ghost"
|
||||
aria-pressed={filter === value}
|
||||
className={filter === value ? 'bg-secondary' : ''}
|
||||
onClick={() => {
|
||||
const next = new URLSearchParams(params);
|
||||
next.set('filter', value);
|
||||
setParams(next);
|
||||
}}
|
||||
>
|
||||
{t(`tasks.${value}`)}
|
||||
</Button>
|
||||
))}
|
||||
{(params.has('merchantId') || params.has('assigneeId')) && (
|
||||
<Button variant="outline" onClick={() => setParams({ filter })}>
|
||||
{t('common.clear')}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
<QueryBoundary query={query}>
|
||||
{(tasks) =>
|
||||
tasks.length ? (
|
||||
tasks.map((task) => <ActionableTask task={task} key={task.id} />)
|
||||
) : (
|
||||
<EmptyState
|
||||
title={t('operations.noTasks')}
|
||||
description={t('operations.noTasksHint')}
|
||||
/>
|
||||
)
|
||||
}
|
||||
</QueryBoundary>
|
||||
</section>
|
||||
{creating && <TaskComposer close={() => setCreating(false)} />}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -5,7 +5,16 @@ export function directoryParams(input: URLSearchParams, role: Role) {
|
||||
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) {
|
||||
for (const key of [
|
||||
'status',
|
||||
'country',
|
||||
'industry',
|
||||
'ownerId',
|
||||
'page',
|
||||
'createdFrom',
|
||||
'createdTo',
|
||||
'cohort',
|
||||
] as const) {
|
||||
if (key === 'ownerId' && role === 'ACCOUNT_MANAGER') continue;
|
||||
const raw = input.get(key);
|
||||
if (!raw) continue;
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
import { useEffect } from 'react';
|
||||
export function useLiveRefresh(refetch: () => unknown) {
|
||||
useEffect(() => {
|
||||
const refresh = () => {
|
||||
if (document.visibilityState === 'visible') void refetch();
|
||||
};
|
||||
window.addEventListener('focus', refresh);
|
||||
window.addEventListener('online', refresh);
|
||||
document.addEventListener('visibilitychange', refresh);
|
||||
const timer = window.setInterval(refresh, 30000);
|
||||
return () => {
|
||||
window.clearInterval(timer);
|
||||
window.removeEventListener('focus', refresh);
|
||||
window.removeEventListener('online', refresh);
|
||||
document.removeEventListener('visibilitychange', refresh);
|
||||
};
|
||||
}, [refetch]);
|
||||
}
|
||||
export const viewerTimeZone = () => Intl.DateTimeFormat().resolvedOptions().timeZone;
|
||||
@@ -3,9 +3,17 @@ export function reviewParams(input: URLSearchParams) {
|
||||
const result = new URLSearchParams();
|
||||
const search = input.get('search')?.slice(0, 100);
|
||||
if (search) result.set('search', search);
|
||||
for (const key of ['ownerId', 'waiting'] as const) {
|
||||
for (const key of [
|
||||
'ownerId',
|
||||
'waiting',
|
||||
'view',
|
||||
'decision',
|
||||
'decidedFrom',
|
||||
'decidedTo',
|
||||
] as const) {
|
||||
const parsed = reviewQueueQuerySchema.shape[key].safeParse(input.get(key) ?? undefined);
|
||||
if (parsed.success && parsed.data && parsed.data !== 'ALL') result.set(key, parsed.data);
|
||||
if (parsed.success && parsed.data && parsed.data !== 'ALL' && parsed.data !== 'PENDING')
|
||||
result.set(key, parsed.data);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
import { operationsEn, operationsRu } from './task-dashboard-locales';
|
||||
import { onboardingEn, onboardingRu } from './onboarding-locales';
|
||||
import { salesEn, salesRu } from './sales-locales';
|
||||
import { workflowEn, workflowRu } from './workflow-locales';
|
||||
import { landingEn, landingRu } from './landing-locales';
|
||||
export const en = {
|
||||
operations: operationsEn,
|
||||
onboarding: onboardingEn,
|
||||
workflow: workflowEn,
|
||||
workspace: salesEn,
|
||||
@@ -204,6 +206,7 @@ export const en = {
|
||||
stageCount: '{{number}} of 8 stages',
|
||||
},
|
||||
tasks: {
|
||||
TODAY: 'Today',
|
||||
title: 'Tasks',
|
||||
description: 'A little structure for the next right step.',
|
||||
ALL: 'All tasks',
|
||||
@@ -236,6 +239,7 @@ export const en = {
|
||||
},
|
||||
};
|
||||
export const ru = {
|
||||
operations: operationsRu,
|
||||
onboarding: onboardingRu,
|
||||
workflow: workflowRu,
|
||||
workspace: salesRu,
|
||||
@@ -440,6 +444,7 @@ export const ru = {
|
||||
stageCount: '{{number}} из 8 этапов',
|
||||
},
|
||||
tasks: {
|
||||
TODAY: 'Сегодня',
|
||||
title: 'Задачи',
|
||||
description: 'Немного порядка для следующего верного шага.',
|
||||
ALL: 'Все задачи',
|
||||
|
||||
+70
-213
@@ -6,7 +6,6 @@ import {
|
||||
ReviewHistory,
|
||||
InteractionHistory,
|
||||
MerchantTasks,
|
||||
RecentInteractions,
|
||||
} from '../components/merchant-workflow';
|
||||
import { useEffect, useState } from 'react';
|
||||
import { Link, useLocation, useOutletContext, useParams, useSearchParams } from 'react-router';
|
||||
@@ -14,12 +13,8 @@ import { keepPreviousData, useQuery } from '@tanstack/react-query';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import {
|
||||
ArrowRight,
|
||||
ArrowUpRight,
|
||||
ArrowLeft,
|
||||
Building2,
|
||||
ShieldCheck,
|
||||
Clock3,
|
||||
Activity,
|
||||
Search,
|
||||
ChevronLeft,
|
||||
ChevronRight,
|
||||
@@ -31,19 +26,15 @@ import {
|
||||
LoaderCircle,
|
||||
} from 'lucide-react';
|
||||
import {
|
||||
dashboardSchema,
|
||||
merchantListSchema,
|
||||
merchantDetailSchema,
|
||||
reviewQueueSchema,
|
||||
pipelineBoardSchema,
|
||||
merchantFiltersSchema,
|
||||
taskListSchema,
|
||||
statuses,
|
||||
statusSchema,
|
||||
taskFilters,
|
||||
canSeeReviewQueue,
|
||||
type User,
|
||||
type TaskFilter,
|
||||
type Merchant,
|
||||
} from '@merchantflow/contracts';
|
||||
import { Input } from '@merchantflow/ui/components/input';
|
||||
@@ -70,154 +61,11 @@ import {
|
||||
Button,
|
||||
StatusBadge,
|
||||
Avatar,
|
||||
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')}
|
||||
/>
|
||||
<RecentInteractions activities={data.recentActivities} />
|
||||
</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>
|
||||
</>
|
||||
);
|
||||
}
|
||||
export { Dashboard } from '../components/dashboard';
|
||||
function useDebounced(value: string) {
|
||||
const [debounced, setDebounced] = useState(value);
|
||||
useEffect(() => {
|
||||
@@ -469,6 +317,23 @@ export function Merchants() {
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
{(normalized.has('cohort') ||
|
||||
normalized.has('createdFrom') ||
|
||||
normalized.has('createdTo')) && (
|
||||
<div className="border-b px-5 py-3 text-sm text-muted-foreground">
|
||||
{normalized.get('cohort') && <p>{t(`operations.${normalized.get('cohort')}`)}</p>}
|
||||
{(normalized.has('createdFrom') || normalized.has('createdTo')) && (
|
||||
<p>
|
||||
{t('operations.createdWindow', {
|
||||
from: normalized.get('createdFrom')
|
||||
? f.dateTime(normalized.get('createdFrom')!)
|
||||
: '—',
|
||||
to: normalized.get('createdTo') ? f.dateTime(normalized.get('createdTo')!) : '—',
|
||||
})}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
{filters.isError && (
|
||||
<div role="alert" className="px-5 py-3 text-sm">
|
||||
{t('common.errorTitle')}{' '}
|
||||
@@ -880,54 +745,7 @@ export function Pipeline() {
|
||||
</>
|
||||
);
|
||||
}
|
||||
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 { Tasks } from '../components/tasks';
|
||||
export function ReviewQueue() {
|
||||
const user = useOutletContext<User>();
|
||||
const { t } = useTranslation();
|
||||
@@ -935,6 +753,7 @@ export function ReviewQueue() {
|
||||
const [params, setParams] = useSearchParams();
|
||||
const filters = reviewParams(params);
|
||||
const serialized = filters.toString();
|
||||
const decided = filters.get('view') === 'DECISIONS';
|
||||
const allowed = canSeeReviewQueue(user.role);
|
||||
const query = useQuery({
|
||||
queryKey: ['review-queue', serialized],
|
||||
@@ -951,10 +770,38 @@ export function ReviewQueue() {
|
||||
return (
|
||||
<>
|
||||
<PageHeader
|
||||
title={t('review.title')}
|
||||
title={t(decided ? 'operations.decisionHistory' : 'review.title')}
|
||||
description={t('review.description')}
|
||||
eyebrow={t('review.eyebrow')}
|
||||
/>
|
||||
<div
|
||||
className="mb-4 flex flex-wrap gap-2"
|
||||
role="group"
|
||||
aria-label={t('operations.decisionHistory')}
|
||||
>
|
||||
<Button
|
||||
variant={decided ? 'ghost' : 'outline'}
|
||||
aria-pressed={!decided}
|
||||
onClick={() => setParams({})}
|
||||
>
|
||||
{t('operations.pending')}
|
||||
</Button>
|
||||
<Button
|
||||
variant={decided ? 'outline' : 'ghost'}
|
||||
aria-pressed={decided}
|
||||
onClick={() => setParams({ view: 'DECISIONS' })}
|
||||
>
|
||||
{t('operations.decisionHistory')}
|
||||
</Button>
|
||||
</div>
|
||||
{decided && (filters.has('decidedFrom') || filters.has('decidedTo')) && (
|
||||
<p className="mb-4 text-sm text-muted-foreground">
|
||||
{t('operations.decisionWindow', {
|
||||
from: filters.get('decidedFrom') ? f.dateTime(filters.get('decidedFrom')!) : '—',
|
||||
to: filters.get('decidedTo') ? f.dateTime(filters.get('decidedTo')!) : '—',
|
||||
})}
|
||||
</p>
|
||||
)}
|
||||
<section aria-label={t('onboarding.queueFilters')} className="mb-5 grid gap-3 sm:grid-cols-3">
|
||||
<label className="space-y-2 text-xs text-muted-foreground">
|
||||
<span>{t('onboarding.search')}</span>
|
||||
@@ -981,17 +828,23 @@ export function ReviewQueue() {
|
||||
</NativeSelect>
|
||||
</label>
|
||||
<label className="space-y-2 text-xs text-muted-foreground">
|
||||
<span>{t('onboarding.waitingTime')}</span>
|
||||
<span>{t(decided ? 'workflow.decision' : 'onboarding.waitingTime')}</span>
|
||||
<NativeSelect
|
||||
className="w-full"
|
||||
value={filters.get('waiting') ?? 'ALL'}
|
||||
onChange={(event) => update('waiting', event.target.value)}
|
||||
value={filters.get(decided ? 'decision' : 'waiting') ?? 'ALL'}
|
||||
onChange={(event) => update(decided ? 'decision' : 'waiting', event.target.value)}
|
||||
>
|
||||
{['ALL', '24', '72'].map((value) => (
|
||||
<option key={value} value={value}>
|
||||
{t(`onboarding.waiting.${value}`)}
|
||||
</option>
|
||||
))}
|
||||
{(decided ? ['ALL', 'APPROVED', 'CORRECTIONS', 'REJECTED'] : ['ALL', '24', '72']).map(
|
||||
(value) => (
|
||||
<option key={value} value={value}>
|
||||
{t(
|
||||
decided && value !== 'ALL'
|
||||
? `workflow.${value}`
|
||||
: `onboarding.waiting.${value}`,
|
||||
)}
|
||||
</option>
|
||||
),
|
||||
)}
|
||||
</NativeSelect>
|
||||
</label>
|
||||
</section>
|
||||
@@ -1009,7 +862,7 @@ export function ReviewQueue() {
|
||||
</div>
|
||||
<span className="inline-flex items-center gap-2 text-xs text-muted-foreground">
|
||||
<Clock3 className="size-4" />
|
||||
{t('review.order')}
|
||||
{t(decided ? 'operations.decisionHistory' : 'review.order')}
|
||||
</span>
|
||||
{serialized && (
|
||||
<Button variant="ghost" onClick={() => setParams({})}>
|
||||
@@ -1042,10 +895,14 @@ export function ReviewQueue() {
|
||||
<div className="flex flex-wrap items-center justify-between gap-4">
|
||||
<div>
|
||||
<p className="text-sm">
|
||||
<StageAge since={review.submittedAt} waiting />
|
||||
{decided ? (
|
||||
t(`workflow.${review.decision}`)
|
||||
) : (
|
||||
<StageAge since={review.submittedAt} waiting />
|
||||
)}
|
||||
</p>
|
||||
<p className="mt-1 text-xs text-muted-foreground">
|
||||
{f.dateTime(review.submittedAt)}
|
||||
{f.dateTime(review.decidedAt ?? review.submittedAt)}
|
||||
</p>
|
||||
</div>
|
||||
<LinkButton
|
||||
|
||||
@@ -0,0 +1,135 @@
|
||||
export const operationsEn = {
|
||||
headTitle: 'Portfolio overview',
|
||||
managerTitle: 'My merchant workspace',
|
||||
complianceTitle: 'Review workspace',
|
||||
headDescription: 'Portfolio health, team workload, and the next actions that need attention.',
|
||||
managerDescription: 'Your assigned merchants, overdue follow-ups, and next actions.',
|
||||
complianceDescription: 'Waiting reviews, recent decisions, and your personal review tasks.',
|
||||
total: 'Total merchants',
|
||||
newLeads: 'New leads · 30 days',
|
||||
active: 'Active onboarding',
|
||||
live: 'Live merchants',
|
||||
newHint: 'Created in the last 30 days, including merchants that have advanced.',
|
||||
activeHint: 'KYB, Compliance Review, Integration, and Testing.',
|
||||
unassigned: 'Unassigned leads',
|
||||
activation: 'Activation rate',
|
||||
activationHint: '{{live}} Live / {{total}} visible merchants, including Rejected.',
|
||||
duration: 'Average onboarding duration',
|
||||
durationHint: 'Creation to first Live transition · {{count}} merchants.',
|
||||
days: '{{value}} days',
|
||||
noMerchants: 'No merchants yet',
|
||||
noLive: 'No recorded Live transitions yet',
|
||||
workload: 'Manager workload',
|
||||
ownWorkload: 'My workload',
|
||||
assigned: 'Assigned merchants',
|
||||
openTasks: 'Open tasks',
|
||||
next: 'Next actions',
|
||||
nextHint: 'Open tasks ordered by due time, with overdue follow-ups first.',
|
||||
overdue: 'Overdue tasks',
|
||||
noTasks: 'No tasks in this view',
|
||||
noTasksHint: 'Create a task or choose another view.',
|
||||
pending: 'Pending reviews',
|
||||
oldest: 'Oldest waiting reviews',
|
||||
decisions: 'Decisions · 30 days',
|
||||
decisionsHint: 'Review cycles decided in the last 30 days, including corrections.',
|
||||
decisionHistory: 'Decision history',
|
||||
noReviews: 'No reviews waiting',
|
||||
reviewTasks: 'My review tasks',
|
||||
allTasks: 'All tasks',
|
||||
today: 'Today',
|
||||
reopen: 'Reopen task',
|
||||
merchant: 'Merchant',
|
||||
chooseMerchant: 'Choose a merchant',
|
||||
searchMerchant: 'Search merchants',
|
||||
assignee: 'Assignee: {{name}}',
|
||||
ownerRule: 'Sales tasks follow the merchant owner. Review tasks belong to you.',
|
||||
timeZone: 'Times shown in {{zone}}',
|
||||
reloadVersion: 'Load current version',
|
||||
versionLoaded: 'Current version loaded. Review your changes before saving.',
|
||||
reminders: 'Reminders',
|
||||
remindersCount: 'Reminders ({{count}})',
|
||||
dismiss: 'Dismiss reminder',
|
||||
inboxDescription: 'Scheduled reminders for your open tasks. Dismissals are saved across visits.',
|
||||
noReminders: 'You’re all caught up',
|
||||
noRemindersHint: 'Reminders appear here when their scheduled time arrives.',
|
||||
remindersError: 'Reminders could not be refreshed. Try again.',
|
||||
upcomingHint: 'Open tasks due tomorrow or later.',
|
||||
todayHint: 'Open tasks due today in your time zone, including overdue tasks.',
|
||||
overdueHint: 'Open tasks whose due time has passed.',
|
||||
completedHint: 'Completed tasks, with their recorded assignee and completion time.',
|
||||
cohort: 'Dashboard filter',
|
||||
createdWindow: 'Created: {{from}} – {{to}}',
|
||||
ACTIVE_ONBOARDING: 'Active onboarding',
|
||||
REACHED_LIVE: 'Recorded Live transition',
|
||||
decisionWindow: 'Decided: {{from}} – {{to}}',
|
||||
noActivity: 'No activity yet',
|
||||
personal: 'Your personal review tasks',
|
||||
};
|
||||
export const operationsRu: typeof operationsEn = {
|
||||
headTitle: 'Обзор портфеля',
|
||||
managerTitle: 'Мои мерчанты',
|
||||
complianceTitle: 'Проверки комплаенса',
|
||||
headDescription: 'Состояние портфеля, загрузка команды и ближайшие действия.',
|
||||
managerDescription: 'Закреплённые мерчанты, просроченные задачи и ближайшие действия.',
|
||||
complianceDescription: 'Ожидающие проверки, недавние решения и ваши личные задачи.',
|
||||
total: 'Всего мерчантов',
|
||||
newLeads: 'Новые лиды · 30 дней',
|
||||
active: 'Активный онбординг',
|
||||
live: 'Мерчанты Live',
|
||||
newHint: 'Созданы за последние 30 дней, включая перешедших на следующие этапы.',
|
||||
activeHint: 'KYB, проверка комплаенса, интеграция и тестирование.',
|
||||
unassigned: 'Лиды без менеджера',
|
||||
activation: 'Доля активации',
|
||||
activationHint: '{{live}} Live / {{total}} доступных мерчантов, включая отклонённых.',
|
||||
duration: 'Среднее время онбординга',
|
||||
durationHint: 'От создания до первого перехода в Live · {{count}} мерчантов.',
|
||||
days: '{{value}} дн.',
|
||||
noMerchants: 'Пока нет мерчантов',
|
||||
noLive: 'Переходов в Live пока нет',
|
||||
workload: 'Загрузка менеджеров',
|
||||
ownWorkload: 'Моя загрузка',
|
||||
assigned: 'Закреплённые мерчанты',
|
||||
openTasks: 'Открытые задачи',
|
||||
next: 'Следующие действия',
|
||||
nextHint: 'Открытые задачи по сроку выполнения, сначала просроченные.',
|
||||
overdue: 'Просроченные задачи',
|
||||
noTasks: 'В этом разделе нет задач',
|
||||
noTasksHint: 'Создайте задачу или выберите другой раздел.',
|
||||
pending: 'Ожидающие проверки',
|
||||
oldest: 'Дольше всего ожидают',
|
||||
decisions: 'Решения · 30 дней',
|
||||
decisionsHint: 'Циклы проверки с решением за последние 30 дней, включая исправления.',
|
||||
decisionHistory: 'История решений',
|
||||
noReviews: 'Нет ожидающих проверок',
|
||||
reviewTasks: 'Мои задачи по проверкам',
|
||||
allTasks: 'Все задачи',
|
||||
today: 'Сегодня',
|
||||
reopen: 'Открыть задачу снова',
|
||||
merchant: 'Мерчант',
|
||||
chooseMerchant: 'Выберите мерчанта',
|
||||
searchMerchant: 'Поиск мерчантов',
|
||||
assignee: 'Исполнитель: {{name}}',
|
||||
ownerRule: 'Задачи продаж следуют за менеджером мерчанта. Задачи по проверкам принадлежат вам.',
|
||||
timeZone: 'Время указано для {{zone}}',
|
||||
reloadVersion: 'Загрузить текущую версию',
|
||||
versionLoaded: 'Текущая версия загружена. Проверьте изменения перед сохранением.',
|
||||
reminders: 'Напоминания',
|
||||
remindersCount: 'Напоминания ({{count}})',
|
||||
dismiss: 'Скрыть напоминание',
|
||||
inboxDescription:
|
||||
'Запланированные напоминания об открытых задачах. Скрытые напоминания сохраняются между посещениями.',
|
||||
noReminders: 'Всё под контролем',
|
||||
noRemindersHint: 'Напоминания появятся здесь в запланированное время.',
|
||||
remindersError: 'Не удалось обновить напоминания. Попробуйте снова.',
|
||||
upcomingHint: 'Открытые задачи со сроком завтра или позже.',
|
||||
todayHint: 'Открытые задачи на сегодня по вашему часовому поясу, включая просроченные.',
|
||||
overdueHint: 'Открытые задачи, срок которых уже прошёл.',
|
||||
completedHint: 'Завершённые задачи с сохранённым исполнителем и временем завершения.',
|
||||
cohort: 'Фильтр обзора',
|
||||
createdWindow: 'Созданы: {{from}} – {{to}}',
|
||||
ACTIVE_ONBOARDING: 'Активный онбординг',
|
||||
REACHED_LIVE: 'Зафиксирован переход в Live',
|
||||
decisionWindow: 'Решения: {{from}} – {{to}}',
|
||||
noActivity: 'Пока нет активности',
|
||||
personal: 'Ваши личные задачи по проверкам',
|
||||
};
|
||||
Reference in New Issue
Block a user