Implemented the database, authentication, access rules, and seed data
This commit is contained in:
@@ -0,0 +1,753 @@
|
||||
import { useId, useState } from 'react';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { useMutation, useQuery } from '@tanstack/react-query';
|
||||
import { Link } from 'react-router';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { z } from 'zod';
|
||||
import {
|
||||
activityInputSchema,
|
||||
assignmentSchema,
|
||||
checklistEditSchema,
|
||||
industries,
|
||||
managerListSchema,
|
||||
merchantEditSchema,
|
||||
mutationResultSchema,
|
||||
reviewDecisionSchema,
|
||||
sources,
|
||||
statuses,
|
||||
taskInputSchema,
|
||||
type MerchantDetail,
|
||||
type Task,
|
||||
} from '@merchantflow/contracts';
|
||||
import {
|
||||
Sheet,
|
||||
SheetContent,
|
||||
SheetTitle,
|
||||
SheetDescription,
|
||||
} from '@merchantflow/ui/components/sheet';
|
||||
import { Input } from '@merchantflow/ui/components/input';
|
||||
import { NativeSelect } from '@merchantflow/ui/components/native-select';
|
||||
import { FormField } from '@merchantflow/ui/components/form-field';
|
||||
import { api, ApiError, queryClient } from '../lib/api';
|
||||
import { useFormat } from '../lib/format';
|
||||
import { Button, SectionHeader, TaskRow } from './shared';
|
||||
|
||||
type Field = {
|
||||
name: string;
|
||||
label?: string;
|
||||
type?: string;
|
||||
options?: { value: string; label: string }[];
|
||||
disabled?: boolean;
|
||||
};
|
||||
type EditorProps = {
|
||||
title: string;
|
||||
description?: string;
|
||||
fields: Field[];
|
||||
initial: Record<string, string>;
|
||||
schema: z.ZodType;
|
||||
build: (values: Record<string, string>) => unknown;
|
||||
submit: (body: unknown) => void;
|
||||
close: () => void;
|
||||
pending: boolean;
|
||||
};
|
||||
function Editor({
|
||||
title,
|
||||
description,
|
||||
fields,
|
||||
initial,
|
||||
schema,
|
||||
build,
|
||||
submit,
|
||||
close,
|
||||
pending,
|
||||
}: EditorProps) {
|
||||
const { t } = useTranslation();
|
||||
const id = useId();
|
||||
const form = useForm<Record<string, string>>({ defaultValues: initial });
|
||||
const [errors, setErrors] = useState<Record<string, string>>({});
|
||||
return (
|
||||
<Sheet
|
||||
open
|
||||
onOpenChange={(open) => {
|
||||
if (!open && !pending) close();
|
||||
}}
|
||||
>
|
||||
<SheetContent
|
||||
closeLabel={t('common.close')}
|
||||
className="w-full! overflow-y-auto p-5 sm:max-w-xl! sm:p-8"
|
||||
>
|
||||
<SheetTitle className="pr-10 text-xl">{title}</SheetTitle>
|
||||
<SheetDescription>{description ?? t('merchants.details')}</SheetDescription>
|
||||
<form
|
||||
noValidate
|
||||
className="space-y-5"
|
||||
onSubmit={form.handleSubmit((values) => {
|
||||
const result = schema.safeParse(build(values));
|
||||
if (!result.success) {
|
||||
const messages: Record<string, string> = {};
|
||||
for (const issue of result.error.issues)
|
||||
messages[String(issue.path[0] ?? 'form')] = t('validation.invalid');
|
||||
setErrors(messages);
|
||||
return;
|
||||
}
|
||||
setErrors({});
|
||||
submit(result.data);
|
||||
})}
|
||||
>
|
||||
<fieldset disabled={pending} className="space-y-5">
|
||||
{fields.map((field) => {
|
||||
const fieldId = `${id}-${field.name}`;
|
||||
const props = {
|
||||
id: fieldId,
|
||||
...form.register(field.name),
|
||||
disabled: field.disabled,
|
||||
'aria-invalid': !!errors[field.name],
|
||||
'aria-describedby': errors[field.name] ? `${fieldId}-error` : undefined,
|
||||
};
|
||||
return (
|
||||
<FormField
|
||||
key={field.name}
|
||||
id={fieldId}
|
||||
label={field.label ?? t(`workflow.${field.name}`)}
|
||||
error={errors[field.name]}
|
||||
>
|
||||
{field.options ? (
|
||||
<NativeSelect {...props}>
|
||||
{field.options.map((option) => (
|
||||
<option key={option.value} value={option.value}>
|
||||
{option.label}
|
||||
</option>
|
||||
))}
|
||||
</NativeSelect>
|
||||
) : field.type === 'textarea' ? (
|
||||
<textarea
|
||||
{...props}
|
||||
rows={4}
|
||||
className="min-h-28 w-full resize-y rounded-lg border bg-background px-3 py-2 text-sm"
|
||||
/>
|
||||
) : (
|
||||
<Input {...props} type={field.type ?? 'text'} />
|
||||
)}
|
||||
</FormField>
|
||||
);
|
||||
})}
|
||||
{Object.keys(errors).some((key) => !fields.some((field) => field.name === key)) && (
|
||||
<p role="alert" className="text-sm text-destructive">
|
||||
{t('errors.VALIDATION_ERROR')}
|
||||
</p>
|
||||
)}
|
||||
<div className="flex flex-wrap gap-3 border-t pt-5">
|
||||
<Button type="submit">{t(pending ? 'workflow.saving' : 'workflow.save')}</Button>
|
||||
<Button type="button" variant="outline" onClick={close}>
|
||||
{t('workflow.cancel')}
|
||||
</Button>
|
||||
</div>
|
||||
</fieldset>
|
||||
</form>
|
||||
</SheetContent>
|
||||
</Sheet>
|
||||
);
|
||||
}
|
||||
function useAction(merchant: MerchantDetail, close?: () => void) {
|
||||
const { t } = useTranslation();
|
||||
const mutation = useMutation({
|
||||
mutationFn: ({
|
||||
path,
|
||||
body,
|
||||
method = 'PATCH',
|
||||
}: {
|
||||
path: string;
|
||||
body: unknown;
|
||||
method?: string;
|
||||
}) =>
|
||||
api(`/merchants/${merchant.id}${path}`, mutationResultSchema, {
|
||||
method,
|
||||
body: JSON.stringify(body),
|
||||
}),
|
||||
onSuccess: async () => {
|
||||
close?.();
|
||||
await queryClient.invalidateQueries({
|
||||
predicate: (query) => query.queryKey[0] !== 'session',
|
||||
});
|
||||
},
|
||||
onError: async () => {
|
||||
close?.();
|
||||
await queryClient.invalidateQueries({ queryKey: ['merchant', merchant.id] });
|
||||
},
|
||||
});
|
||||
return {
|
||||
...mutation,
|
||||
feedback: mutation.isError ? (
|
||||
<p role="alert" className="rounded-lg bg-rose-50 p-3 text-sm text-destructive">
|
||||
{t(`errors.${mutation.error instanceof ApiError ? mutation.error.code : 'INTERNAL_ERROR'}`)}
|
||||
</p>
|
||||
) : mutation.isSuccess ? (
|
||||
<p role="status" className="text-xs text-muted-foreground">
|
||||
{t('workflow.saved')}
|
||||
</p>
|
||||
) : null,
|
||||
};
|
||||
}
|
||||
const identityFields = [
|
||||
'name',
|
||||
'legalName',
|
||||
'registrationNumber',
|
||||
'address',
|
||||
'website',
|
||||
'country',
|
||||
'industry',
|
||||
];
|
||||
const commercialFields = [
|
||||
'contactName',
|
||||
'contactEmail',
|
||||
'contactPhone',
|
||||
'contactTitle',
|
||||
'estimatedMonthlyVolumeUsd',
|
||||
'source',
|
||||
];
|
||||
export function MerchantControls({ merchant: m }: { merchant: MerchantDetail }) {
|
||||
const { t } = useTranslation();
|
||||
const [mode, setMode] = useState<'edit' | 'assign' | null>(null);
|
||||
const action = useAction(m, () => setMode(null));
|
||||
const managers = useQuery({
|
||||
queryKey: ['assignable-managers'],
|
||||
queryFn: ({ signal }) => api('/users/assignable-managers', managerListSchema, { signal }),
|
||||
enabled: m.capabilities.assign,
|
||||
});
|
||||
const fields: Field[] = [...identityFields, ...commercialFields].map((name) => ({
|
||||
name,
|
||||
disabled: identityFields.includes(name) && !m.capabilities.editIdentity,
|
||||
type: name === 'contactEmail' ? 'email' : name === 'website' ? 'url' : 'text',
|
||||
options:
|
||||
name === 'industry'
|
||||
? industries.map((value) => ({ value, label: t(`industry.${value}`) }))
|
||||
: name === 'source'
|
||||
? [
|
||||
{ value: '', label: '—' },
|
||||
...sources.map((value) => ({ value, label: t(`workflow.${value}`) })),
|
||||
]
|
||||
: undefined,
|
||||
}));
|
||||
const initial = Object.fromEntries(
|
||||
fields.map(({ name }) => [name, String(m[name as keyof MerchantDetail] ?? '')]),
|
||||
);
|
||||
return (
|
||||
<div className="mb-6 space-y-3">
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{m.capabilities.editCommercial && (
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => {
|
||||
action.reset();
|
||||
setMode('edit');
|
||||
}}
|
||||
>
|
||||
{t('workflow.editMerchant')}
|
||||
</Button>
|
||||
)}
|
||||
{m.capabilities.assign && (
|
||||
<Button
|
||||
variant="outline"
|
||||
disabled={!managers.data}
|
||||
onClick={() => {
|
||||
action.reset();
|
||||
setMode('assign');
|
||||
}}
|
||||
>
|
||||
{t('workflow.assign')}
|
||||
</Button>
|
||||
)}
|
||||
{m.capabilities.nextStage && (
|
||||
<Button
|
||||
disabled={action.isPending}
|
||||
onClick={() =>
|
||||
action.mutate({
|
||||
path: '/transitions',
|
||||
method: 'POST',
|
||||
body: { version: m.version, toStatus: m.capabilities.nextStage },
|
||||
})
|
||||
}
|
||||
>
|
||||
{t('workflow.advance', { stage: t(`statuses.${m.capabilities.nextStage}`) })}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
{managers.isError && (
|
||||
<p role="alert" className="text-sm text-destructive">
|
||||
{t('errors.NETWORK')}{' '}
|
||||
<Button variant="ghost" onClick={() => void managers.refetch()}>
|
||||
{t('common.retry')}
|
||||
</Button>
|
||||
</p>
|
||||
)}
|
||||
{action.feedback}
|
||||
{mode === 'edit' && (
|
||||
<Editor
|
||||
title={t('workflow.editMerchant')}
|
||||
description={!m.capabilities.editIdentity ? t('workflow.identityLocked') : undefined}
|
||||
fields={fields}
|
||||
initial={initial}
|
||||
schema={merchantEditSchema}
|
||||
build={(values) => ({
|
||||
version: m.version,
|
||||
...Object.fromEntries(
|
||||
Object.entries(values)
|
||||
.filter(
|
||||
([key, value]) =>
|
||||
value !== initial[key] &&
|
||||
(!identityFields.includes(key) || m.capabilities.editIdentity),
|
||||
)
|
||||
.map(([key, value]) => [
|
||||
key,
|
||||
['registrationNumber', 'address', 'contactPhone', 'contactTitle'].includes(key) &&
|
||||
!value
|
||||
? null
|
||||
: value,
|
||||
]),
|
||||
),
|
||||
})}
|
||||
submit={(body) => action.mutate({ path: '', body })}
|
||||
close={() => setMode(null)}
|
||||
pending={action.isPending}
|
||||
/>
|
||||
)}
|
||||
{mode === 'assign' && (
|
||||
<Editor
|
||||
title={t('workflow.assign')}
|
||||
description={t('workflow.taskOwnership')}
|
||||
fields={[
|
||||
{
|
||||
name: 'ownerId',
|
||||
options: (managers.data ?? []).map((user) => ({ value: user.id, label: user.name })),
|
||||
},
|
||||
]}
|
||||
initial={{ ownerId: m.owner?.id ?? managers.data?.[0]?.id ?? '' }}
|
||||
schema={assignmentSchema}
|
||||
build={(values) => ({ ...values, version: m.version })}
|
||||
submit={(body) => action.mutate({ path: '/assignment', body })}
|
||||
close={() => setMode(null)}
|
||||
pending={action.isPending}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
export function ChecklistControl({
|
||||
merchant: m,
|
||||
item,
|
||||
}: {
|
||||
merchant: MerchantDetail;
|
||||
item: MerchantDetail['checklist'][number];
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const f = useFormat();
|
||||
const [open, setOpen] = useState(false);
|
||||
const action = useAction(m, () => setOpen(false));
|
||||
return (
|
||||
<div className="mt-3 space-y-2">
|
||||
{m.capabilities.collectChecklist && (
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => {
|
||||
action.reset();
|
||||
setOpen(true);
|
||||
}}
|
||||
>
|
||||
{t('workflow.checklistEdit')}
|
||||
</Button>
|
||||
)}
|
||||
{action.feedback}
|
||||
<details className="text-xs text-muted-foreground">
|
||||
<summary className="min-h-11 cursor-pointer py-3">{t('workflow.checklistHistory')}</summary>
|
||||
<ol className="space-y-3 border-l pl-3">
|
||||
{item.changes.map((change) => (
|
||||
<li key={change.id}>
|
||||
<span>
|
||||
{t(`checklist.${change.toState}`)} · {change.actor.name} ·{' '}
|
||||
{f.date(change.occurredAt)}
|
||||
</span>
|
||||
{change.note && <p className="mt-1 whitespace-pre-wrap">{change.note}</p>}
|
||||
</li>
|
||||
))}
|
||||
</ol>
|
||||
</details>
|
||||
{open && (
|
||||
<Editor
|
||||
title={t('workflow.checklistEdit')}
|
||||
description={t(`documents.${item.documentCode}`)}
|
||||
fields={[
|
||||
{
|
||||
name: 'state',
|
||||
options: ['MISSING', 'RECEIVED'].map((value) => ({
|
||||
value,
|
||||
label: t(`checklist.${value}`),
|
||||
})),
|
||||
},
|
||||
{ name: 'note', type: 'textarea' },
|
||||
]}
|
||||
initial={{
|
||||
state: item.state === 'RECEIVED' ? 'RECEIVED' : 'MISSING',
|
||||
note: item.note ?? '',
|
||||
}}
|
||||
schema={checklistEditSchema}
|
||||
build={(values) => ({ ...values, note: values.note || null, version: m.version })}
|
||||
submit={(body) => action.mutate({ path: `/checklist/${item.id}`, body })}
|
||||
close={() => setOpen(false)}
|
||||
pending={action.isPending}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
export function ReviewHistory({ merchant: m }: { merchant: MerchantDetail }) {
|
||||
const { t } = useTranslation();
|
||||
const f = useFormat();
|
||||
const [open, setOpen] = useState(false);
|
||||
const action = useAction(m, () => setOpen(false));
|
||||
const pending = m.reviews.find((review) => review.decision === 'PENDING');
|
||||
return (
|
||||
<section className="surface">
|
||||
<SectionHeader
|
||||
title={t('workflow.reviews')}
|
||||
action={
|
||||
m.capabilities.review &&
|
||||
pending && (
|
||||
<Button
|
||||
onClick={() => {
|
||||
action.reset();
|
||||
setOpen(true);
|
||||
}}
|
||||
>
|
||||
{t('workflow.decide')}
|
||||
</Button>
|
||||
)
|
||||
}
|
||||
/>
|
||||
<div className="space-y-4 p-5 sm:p-6">
|
||||
{action.feedback}
|
||||
{!m.reviews.length && (
|
||||
<p className="text-sm text-muted-foreground">{t('review.emptyText')}</p>
|
||||
)}
|
||||
{m.reviews.map((review) => (
|
||||
<article key={review.id} className="rounded-lg border p-4">
|
||||
<p className="text-sm font-semibold">
|
||||
{t('workflow.cycle', { cycle: review.cycle })} · {t(`workflow.${review.decision}`)}
|
||||
</p>
|
||||
<p className="mt-2 text-xs text-muted-foreground">
|
||||
{t('workflow.submitted', {
|
||||
name: review.submittedBy.name,
|
||||
date: f.date(review.submittedAt),
|
||||
})}
|
||||
</p>
|
||||
{review.reviewer && review.decidedAt && (
|
||||
<p className="mt-1 text-xs text-muted-foreground">
|
||||
{t('workflow.reviewed', {
|
||||
name: review.reviewer.name,
|
||||
date: f.date(review.decidedAt),
|
||||
})}
|
||||
</p>
|
||||
)}
|
||||
{review.reason && (
|
||||
<p className="mt-3 whitespace-pre-wrap text-sm leading-relaxed">{review.reason}</p>
|
||||
)}
|
||||
</article>
|
||||
))}
|
||||
</div>
|
||||
{open && pending && (
|
||||
<Editor
|
||||
title={t('workflow.decide')}
|
||||
description={t('workflow.correctionHint')}
|
||||
fields={[
|
||||
{
|
||||
name: 'decision',
|
||||
options: ['APPROVED', 'CORRECTIONS', 'REJECTED'].map((value) => ({
|
||||
value,
|
||||
label: t(`workflow.${value}`),
|
||||
})),
|
||||
},
|
||||
{ name: 'reason', type: 'textarea' },
|
||||
...m.checklist.map((item) => ({
|
||||
name: `correction_${item.id}`,
|
||||
label: t(`documents.${item.documentCode}`),
|
||||
type: 'textarea',
|
||||
})),
|
||||
]}
|
||||
initial={{ decision: 'APPROVED', reason: '' }}
|
||||
schema={reviewDecisionSchema}
|
||||
build={(values) => ({
|
||||
version: m.version,
|
||||
decision: values.decision,
|
||||
reason: values.reason,
|
||||
corrections:
|
||||
values.decision === 'CORRECTIONS'
|
||||
? m.checklist
|
||||
.filter((item) => values[`correction_${item.id}`]?.trim())
|
||||
.map((item) => ({ itemId: item.id, note: values[`correction_${item.id}`] }))
|
||||
: [],
|
||||
})}
|
||||
submit={(body) =>
|
||||
action.mutate({ path: `/reviews/${pending.id}/decision`, method: 'POST', body })
|
||||
}
|
||||
close={() => setOpen(false)}
|
||||
pending={action.isPending}
|
||||
/>
|
||||
)}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
function useActivityText() {
|
||||
const { t } = useTranslation();
|
||||
return (activity: MerchantDetail['activities'][number]) => {
|
||||
if (activity.kind !== 'AUDIT') return activity.text;
|
||||
const labels: Record<string, string> = {
|
||||
'Merchant details updated': 'detailsUpdated',
|
||||
'Manager assignment updated': 'assignmentUpdated',
|
||||
'Activity edited': 'activityEdited',
|
||||
'Task updated': 'taskUpdated',
|
||||
'Task created': 'taskCreated',
|
||||
};
|
||||
if (labels[activity.text]) return t(`workflow.${labels[activity.text]}`);
|
||||
const stages = activity.text.split(' → ');
|
||||
if (stages.length === 2 && stages.every((stage) => statuses.some((code) => code === stage)))
|
||||
return stages.map((stage) => t(`statuses.${stage}`)).join(' → ');
|
||||
if (activity.text.startsWith('Checklist updated: '))
|
||||
return t('workflow.checklistUpdated', {
|
||||
document: t(`documents.${activity.text.slice(19)}`),
|
||||
});
|
||||
if (activity.text.startsWith('Compliance review: '))
|
||||
return t('workflow.reviewDecided', { decision: t(`workflow.${activity.text.slice(19)}`) });
|
||||
return activity.text;
|
||||
};
|
||||
}
|
||||
export function InteractionHistory({ merchant: m }: { merchant: MerchantDetail }) {
|
||||
const { t } = useTranslation();
|
||||
const f = useFormat();
|
||||
const [edit, setEdit] = useState<string | null>(null);
|
||||
const action = useAction(m, () => setEdit(null));
|
||||
const existing = m.activities.find((activity) => activity.id === edit);
|
||||
const describe = useActivityText();
|
||||
const audit = m.activities.filter((activity) => activity.kind === 'AUDIT');
|
||||
return (
|
||||
<section className="surface">
|
||||
<SectionHeader
|
||||
title={t('workflow.activities')}
|
||||
action={
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => {
|
||||
action.reset();
|
||||
setEdit('new');
|
||||
}}
|
||||
>
|
||||
{t('workflow.addActivity')}
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
<div className="space-y-4 p-5 sm:p-6">
|
||||
{action.feedback}
|
||||
{m.activities
|
||||
.filter((activity) => activity.kind !== 'AUDIT')
|
||||
.map((activity) => (
|
||||
<article key={activity.id} className="rounded-lg bg-background p-4">
|
||||
<p className="mb-2 text-xs text-muted-foreground">
|
||||
{t(`workflow.${activity.kind}`)} · {activity.actor.name} ·{' '}
|
||||
{f.date(activity.occurredAt)}
|
||||
</p>
|
||||
<p className="whitespace-pre-wrap break-words text-sm leading-relaxed">
|
||||
{activity.text}
|
||||
</p>
|
||||
{m.capabilities.activityKinds.some((kind) => kind === activity.kind) && (
|
||||
<Button
|
||||
className="mt-2"
|
||||
variant="ghost"
|
||||
onClick={() => {
|
||||
action.reset();
|
||||
setEdit(activity.id);
|
||||
}}
|
||||
>
|
||||
{t('workflow.editActivity')}
|
||||
</Button>
|
||||
)}
|
||||
</article>
|
||||
))}
|
||||
{!!audit.length && (
|
||||
<details className="border-t pt-2">
|
||||
<summary className="min-h-11 cursor-pointer py-3 text-sm font-medium">
|
||||
{t('workflow.auditHistory', { count: audit.length })}
|
||||
</summary>
|
||||
<ol className="divide-y">
|
||||
{audit.map((activity) => (
|
||||
<li key={activity.id} className="py-3">
|
||||
<p className="text-sm">{describe(activity)}</p>
|
||||
<p className="mt-1 text-xs text-muted-foreground">
|
||||
{activity.actor.name} · {f.date(activity.occurredAt)}
|
||||
</p>
|
||||
</li>
|
||||
))}
|
||||
</ol>
|
||||
</details>
|
||||
)}
|
||||
</div>
|
||||
{edit && (
|
||||
<Editor
|
||||
title={t(existing ? 'workflow.editActivity' : 'workflow.addActivity')}
|
||||
fields={[
|
||||
{
|
||||
name: 'kind',
|
||||
options: m.capabilities.activityKinds.map((value) => ({
|
||||
value,
|
||||
label: t(`workflow.${value}`),
|
||||
})),
|
||||
},
|
||||
{ name: 'text', type: 'textarea' },
|
||||
]}
|
||||
initial={{
|
||||
kind: existing?.kind ?? m.capabilities.activityKinds[0]!,
|
||||
text: existing?.text ?? '',
|
||||
}}
|
||||
schema={activityInputSchema}
|
||||
build={(values) => ({ ...values, version: m.version })}
|
||||
submit={(body) =>
|
||||
action.mutate({
|
||||
path: `/activities${existing ? `/${existing.id}` : ''}`,
|
||||
method: existing ? 'PATCH' : 'POST',
|
||||
body,
|
||||
})
|
||||
}
|
||||
close={() => setEdit(null)}
|
||||
pending={action.isPending}
|
||||
/>
|
||||
)}
|
||||
</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}
|
||||
/>
|
||||
)}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
export function RecentInteractions({ activities }: { activities: MerchantDetail['activities'] }) {
|
||||
const { t } = useTranslation();
|
||||
const f = useFormat();
|
||||
const describe = useActivityText();
|
||||
return (
|
||||
<div className="divide-y px-5 sm:px-6">
|
||||
{activities.map((activity) => (
|
||||
<article key={activity.id} className="py-4">
|
||||
<Link
|
||||
className="text-sm font-semibold hover:underline"
|
||||
to={`/app/merchants/${activity.merchant.id}`}
|
||||
>
|
||||
{activity.merchant.name}
|
||||
</Link>
|
||||
<p className="mt-1 text-xs text-muted-foreground">
|
||||
{t(`workflow.${activity.kind}`)} · {activity.actor.name} ·{' '}
|
||||
{f.relative(activity.occurredAt)}
|
||||
</p>
|
||||
<p className="mt-2 whitespace-pre-wrap break-words text-sm leading-relaxed">
|
||||
{describe(activity)}
|
||||
</p>
|
||||
</article>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -234,7 +234,7 @@ export function MerchantCard({ merchant }: { merchant: Merchant }) {
|
||||
/>
|
||||
</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>{merchant.owner?.name.split(' ')[0] ?? t('workflow.unassigned')}</span>
|
||||
<span className="flex items-center gap-1">
|
||||
<Clock3 className="size-3" aria-hidden="true" />
|
||||
{f.relative(merchant.stageEnteredAt)}
|
||||
|
||||
@@ -40,9 +40,9 @@ export async function api<T>(
|
||||
}
|
||||
if (!response.ok) {
|
||||
const body = await response.json().catch(() => ({}));
|
||||
if (response.status === 401 && !path.startsWith('/auth/')) {
|
||||
await queryClient.cancelQueries();
|
||||
queryClient.clear();
|
||||
if (response.status === 401 && path !== '/auth/login') {
|
||||
await queryClient.cancelQueries({ predicate: (query) => query.queryKey[0] !== 'session' });
|
||||
queryClient.removeQueries({ predicate: (query) => query.queryKey[0] !== 'session' });
|
||||
queryClient.setQueryData(['session'], null);
|
||||
}
|
||||
throw new ApiError(
|
||||
|
||||
@@ -10,6 +10,14 @@ export function useFormat() {
|
||||
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),
|
||||
usd: (value: string | null) =>
|
||||
value === null
|
||||
? '—'
|
||||
: new Intl.NumberFormat(locale, {
|
||||
style: 'currency',
|
||||
currency: 'USD',
|
||||
maximumFractionDigits: 2,
|
||||
}).format(Number(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);
|
||||
|
||||
+12
-2
@@ -1,4 +1,6 @@
|
||||
import { workflowEn, workflowRu } from './workflow-locales';
|
||||
export const en = {
|
||||
workflow: workflowEn,
|
||||
common: {
|
||||
workspace: 'Workspace',
|
||||
team: 'Merchant workspace',
|
||||
@@ -115,6 +117,10 @@ export const en = {
|
||||
invalid: 'Please check this value.',
|
||||
},
|
||||
errors: {
|
||||
CONFLICT: 'This record changed. Review the latest information and try again.',
|
||||
WORKFLOW_INVALID:
|
||||
'This action requires a valid stage, complete documents and approval where applicable.',
|
||||
REVIEW_LOCKED: 'This information is locked during or after review.',
|
||||
UNAUTHORIZED: 'Sign in to continue.',
|
||||
INVALID_CREDENTIALS: 'The email or password is incorrect.',
|
||||
FORBIDDEN: 'You do not have access to this view.',
|
||||
@@ -152,7 +158,7 @@ export const en = {
|
||||
emptyActivity: 'No activity to show yet',
|
||||
scopeHead: 'Your entire merchant portfolio',
|
||||
scopeManager: 'Your assigned merchants',
|
||||
scopeCompliance: 'Merchants in KYB and Compliance Review',
|
||||
scopeCompliance: 'Merchant context across the portfolio · personal compliance tasks',
|
||||
},
|
||||
merchants: {
|
||||
title: 'Merchants',
|
||||
@@ -233,6 +239,7 @@ export const en = {
|
||||
},
|
||||
};
|
||||
export const ru = {
|
||||
workflow: workflowRu,
|
||||
common: {
|
||||
workspace: 'Рабочее пространство',
|
||||
team: 'Работа с мерчантами',
|
||||
@@ -351,6 +358,9 @@ export const ru = {
|
||||
invalid: 'Проверьте это значение.',
|
||||
},
|
||||
errors: {
|
||||
CONFLICT: 'Запись изменилась. Проверьте актуальные данные и повторите действие.',
|
||||
WORKFLOW_INVALID: 'Проверьте этап, готовность документов и наличие одобрения.',
|
||||
REVIEW_LOCKED: 'Эти данные защищены от изменений во время и после проверки.',
|
||||
UNAUTHORIZED: 'Войдите, чтобы продолжить.',
|
||||
INVALID_CREDENTIALS: 'Неверная почта или пароль.',
|
||||
FORBIDDEN: 'У вас нет доступа к этому разделу.',
|
||||
@@ -388,7 +398,7 @@ export const ru = {
|
||||
emptyActivity: 'Событий пока нет',
|
||||
scopeHead: 'Весь портфель мерчантов',
|
||||
scopeManager: 'Закреплённые за вами мерчанты',
|
||||
scopeCompliance: 'Мерчанты на KYB и комплаенс-проверке',
|
||||
scopeCompliance: 'Контекст всех мерчантов · личные комплаенс-задачи',
|
||||
},
|
||||
merchants: {
|
||||
title: 'Мерчанты',
|
||||
|
||||
+42
-18
@@ -1,3 +1,11 @@
|
||||
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';
|
||||
@@ -174,7 +182,7 @@ export function Dashboard() {
|
||||
title={t('dashboard.activity')}
|
||||
description={t('dashboard.activityText')}
|
||||
/>
|
||||
<ActivityFeed events={data.recentEvents} />
|
||||
<RecentInteractions activities={data.recentActivities} />
|
||||
</section>
|
||||
<section className="surface self-start">
|
||||
<SectionHeader
|
||||
@@ -255,7 +263,9 @@ function MerchantTable({ merchants }: { merchants: Merchant[] }) {
|
||||
<TableCell className="text-xs text-muted-foreground">
|
||||
{f.country(m.country)}
|
||||
</TableCell>
|
||||
<TableCell className="text-xs">{m.owner.name}</TableCell>
|
||||
<TableCell className="text-xs">
|
||||
{m.owner?.name ?? t('workflow.unassigned')}
|
||||
</TableCell>
|
||||
<TableCell className="pr-6 text-right text-xs text-muted-foreground">
|
||||
{f.shortDate(m.createdAt)}
|
||||
</TableCell>
|
||||
@@ -279,7 +289,9 @@ function MerchantTable({ merchants }: { merchants: Merchant[] }) {
|
||||
</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>
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{m.owner?.name ?? t('workflow.unassigned')}
|
||||
</span>
|
||||
</div>
|
||||
</Link>
|
||||
))}
|
||||
@@ -459,6 +471,7 @@ export function MerchantDetail() {
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<MerchantControls merchant={m} />
|
||||
<div className="grid gap-6 xl:grid-cols-[1.15fr_1fr]">
|
||||
<div className="min-w-0 space-y-6">
|
||||
<section className="surface">
|
||||
@@ -468,8 +481,28 @@ export function MerchantDetail() {
|
||||
/>
|
||||
<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('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: (
|
||||
@@ -505,6 +538,7 @@ export function MerchantDetail() {
|
||||
))}
|
||||
</dl>
|
||||
</section>
|
||||
<ReviewHistory merchant={m} />
|
||||
<section id="checklist" className="surface">
|
||||
<SectionHeader
|
||||
title={t('merchants.checklist')}
|
||||
@@ -541,6 +575,7 @@ export function MerchantDetail() {
|
||||
{t(`checklist.${doc.state}`)}
|
||||
</Badge>
|
||||
</div>
|
||||
<ChecklistControl merchant={m} item={doc} />
|
||||
{doc.note && (
|
||||
<p className="mt-2 text-xs leading-relaxed text-muted-foreground">
|
||||
{doc.note}
|
||||
@@ -580,19 +615,8 @@ export function MerchantDetail() {
|
||||
/>
|
||||
<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>
|
||||
<MerchantTasks merchant={m} />
|
||||
<InteractionHistory merchant={m} />
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
@@ -787,7 +811,7 @@ export function ReviewQueue() {
|
||||
{m.name}
|
||||
</Link>
|
||||
<p className="mt-1 text-xs text-muted-foreground">
|
||||
{m.owner.name} · {t(`industry.${m.industry}`)}
|
||||
{m.owner?.name ?? t('workflow.unassigned')} · {t(`industry.${m.industry}`)}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -147,8 +147,8 @@ export function Login() {
|
||||
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' },
|
||||
{ email: 'alex', role: 'ACCOUNT_MANAGER', name: 'Alex' },
|
||||
{ email: 'sam', role: 'ACCOUNT_MANAGER', name: 'Sam' },
|
||||
];
|
||||
return (
|
||||
<div className="grid min-h-dvh bg-white lg:grid-cols-2">
|
||||
|
||||
@@ -0,0 +1,157 @@
|
||||
export const workflowEn = {
|
||||
auditHistory: 'Audit history ({{count}})',
|
||||
detailsUpdated: 'Merchant details updated',
|
||||
assignmentUpdated: 'Manager assignment updated',
|
||||
activityEdited: 'Interaction edited',
|
||||
taskUpdated: 'Task updated',
|
||||
taskCreated: 'Task created',
|
||||
checklistUpdated: 'Checklist updated: {{document}}',
|
||||
reviewDecided: 'Compliance review: {{decision}}',
|
||||
unassigned: 'Unassigned',
|
||||
edit: 'Edit',
|
||||
save: 'Save changes',
|
||||
saving: 'Saving…',
|
||||
cancel: 'Cancel',
|
||||
saved: 'Changes saved.',
|
||||
editMerchant: 'Edit merchant',
|
||||
assign: 'Assign manager',
|
||||
ownerId: 'Account manager',
|
||||
advance: 'Move to {{stage}}',
|
||||
identityLocked:
|
||||
'Reviewed company and KYB information is locked. Contact and commercial details can still be updated.',
|
||||
checklistEdit: 'Update document',
|
||||
checklistHistory: 'Document history',
|
||||
state: 'Document status',
|
||||
note: 'Note',
|
||||
reviews: 'Compliance reviews',
|
||||
decide: 'Record decision',
|
||||
decision: 'Decision',
|
||||
reason: 'Decision reason',
|
||||
correctionHint:
|
||||
'For a correction request, describe the change needed for each affected document.',
|
||||
APPROVED: 'Approved',
|
||||
PENDING: 'Pending',
|
||||
REJECTED: 'Rejected',
|
||||
CORRECTIONS: 'Corrections requested',
|
||||
cycle: 'Review {{cycle}}',
|
||||
submitted: 'Submitted by {{name}} on {{date}}',
|
||||
reviewed: 'Reviewed by {{name}} on {{date}}',
|
||||
activities: 'Interactions and audit trail',
|
||||
addActivity: 'Log interaction',
|
||||
editActivity: 'Edit interaction',
|
||||
kind: 'Interaction type',
|
||||
text: 'Details',
|
||||
NOTE: 'Note',
|
||||
CALL: 'Call',
|
||||
EMAIL: 'Email',
|
||||
MEETING: 'Meeting',
|
||||
KYB_NOTE: 'KYB note',
|
||||
AUDIT: 'System history',
|
||||
addTask: 'Add task',
|
||||
editTask: 'Edit task',
|
||||
complete: 'Complete task',
|
||||
title: 'Task title',
|
||||
dueAt: 'Due date and time',
|
||||
remindAt: 'Reminder date and time',
|
||||
status: 'Task status',
|
||||
taskOwnership: 'Commercial tasks follow the assigned manager. Compliance tasks are personal.',
|
||||
COMMERCIAL: 'Commercial',
|
||||
COMPLIANCE: 'Compliance',
|
||||
name: 'Company name',
|
||||
legalName: 'Legal company name',
|
||||
registrationNumber: 'Registration number',
|
||||
address: 'Company address',
|
||||
website: 'Website',
|
||||
country: 'Country code',
|
||||
industry: 'Industry',
|
||||
contactName: 'Primary contact',
|
||||
contactEmail: 'Contact email',
|
||||
contactPhone: 'Contact phone',
|
||||
contactTitle: 'Contact title',
|
||||
estimatedMonthlyVolumeUsd: 'Estimated monthly processing (USD)',
|
||||
source: 'Lead source',
|
||||
INBOUND: 'Inbound enquiry',
|
||||
OUTBOUND: 'Outbound outreach',
|
||||
REFERRAL: 'Referral',
|
||||
PARTNER: 'Partner',
|
||||
EVENT: 'Event',
|
||||
};
|
||||
export const workflowRu: Record<keyof typeof workflowEn, string> = {
|
||||
auditHistory: 'Журнал действий ({{count}})',
|
||||
detailsUpdated: 'Данные мерчанта обновлены',
|
||||
assignmentUpdated: 'Назначение менеджера изменено',
|
||||
activityEdited: 'Взаимодействие изменено',
|
||||
taskUpdated: 'Задача обновлена',
|
||||
taskCreated: 'Задача создана',
|
||||
checklistUpdated: 'Документ обновлён: {{document}}',
|
||||
reviewDecided: 'Комплаенс-проверка: {{decision}}',
|
||||
unassigned: 'Не назначен',
|
||||
edit: 'Изменить',
|
||||
save: 'Сохранить изменения',
|
||||
saving: 'Сохраняем…',
|
||||
cancel: 'Отмена',
|
||||
saved: 'Изменения сохранены.',
|
||||
editMerchant: 'Изменить мерчанта',
|
||||
assign: 'Назначить менеджера',
|
||||
ownerId: 'Аккаунт-менеджер',
|
||||
advance: 'Перевести: {{stage}}',
|
||||
identityLocked:
|
||||
'Проверенные данные компании и KYB защищены от изменений. Контактные и коммерческие данные можно обновлять.',
|
||||
checklistEdit: 'Обновить документ',
|
||||
checklistHistory: 'История документа',
|
||||
state: 'Статус документа',
|
||||
note: 'Заметка',
|
||||
reviews: 'Комплаенс-проверки',
|
||||
decide: 'Записать решение',
|
||||
decision: 'Решение',
|
||||
reason: 'Основание решения',
|
||||
correctionHint:
|
||||
'Для запроса исправлений укажите необходимые изменения для каждого затронутого документа.',
|
||||
APPROVED: 'Одобрено',
|
||||
PENDING: 'Ожидает решения',
|
||||
REJECTED: 'Отклонено',
|
||||
CORRECTIONS: 'Запрошены исправления',
|
||||
cycle: 'Проверка {{cycle}}',
|
||||
submitted: 'Отправлено: {{name}}, {{date}}',
|
||||
reviewed: 'Проверено: {{name}}, {{date}}',
|
||||
activities: 'Взаимодействия и журнал действий',
|
||||
addActivity: 'Добавить взаимодействие',
|
||||
editActivity: 'Изменить взаимодействие',
|
||||
kind: 'Тип взаимодействия',
|
||||
text: 'Подробности',
|
||||
NOTE: 'Заметка',
|
||||
CALL: 'Звонок',
|
||||
EMAIL: 'Письмо',
|
||||
MEETING: 'Встреча',
|
||||
KYB_NOTE: 'Заметка KYB',
|
||||
AUDIT: 'Системная история',
|
||||
addTask: 'Добавить задачу',
|
||||
editTask: 'Изменить задачу',
|
||||
complete: 'Выполнить задачу',
|
||||
title: 'Название задачи',
|
||||
dueAt: 'Дата и время выполнения',
|
||||
remindAt: 'Дата и время напоминания',
|
||||
status: 'Статус задачи',
|
||||
taskOwnership:
|
||||
'Коммерческие задачи закреплены за менеджером мерчанта. Комплаенс-задачи — личные.',
|
||||
COMMERCIAL: 'Коммерческая',
|
||||
COMPLIANCE: 'Комплаенс',
|
||||
name: 'Название компании',
|
||||
legalName: 'Юридическое название',
|
||||
registrationNumber: 'Регистрационный номер',
|
||||
address: 'Адрес компании',
|
||||
website: 'Сайт',
|
||||
country: 'Код страны',
|
||||
industry: 'Отрасль',
|
||||
contactName: 'Основной контакт',
|
||||
contactEmail: 'Email контакта',
|
||||
contactPhone: 'Телефон контакта',
|
||||
contactTitle: 'Должность контакта',
|
||||
estimatedMonthlyVolumeUsd: 'Месячный объём обработки (USD)',
|
||||
source: 'Источник лида',
|
||||
INBOUND: 'Входящий запрос',
|
||||
OUTBOUND: 'Исходящий контакт',
|
||||
REFERRAL: 'Рекомендация',
|
||||
PARTNER: 'Партнёр',
|
||||
EVENT: 'Мероприятие',
|
||||
};
|
||||
Reference in New Issue
Block a user