Frontend completo (Etapas 11-18) e extensões de backend (Etapas 13 e 18)
Adiciona o frontend Next.js em frontend/ (setup, design system, autenticação/tema, layout/navegação, área master, área tenant completa: clientes, produtos, vendas, recebimentos, whatsapp, e-mail, alertas, equipe e perfil). Estende o backend de forma aditiva e autorizada: cookie httpOnly para refresh token (Etapa 13) e CRUD de equipe + edição de perfil do tenant (Etapa 18, módulo src/modules/equipe/ novo e PUT /tenant/perfil). Detalhes completos em Etapas/V2/*. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,125 @@
|
||||
'use client';
|
||||
|
||||
import * as React from 'react';
|
||||
import Link from 'next/link';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { zodResolver } from '@hookform/resolvers/zod';
|
||||
import { apiClient, ApiError } from '@/lib/api/client';
|
||||
import { forgotPasswordSchema, type ForgotPasswordFormValues } from '@/lib/validators/auth';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { FormField } from '@/components/ui/form-field';
|
||||
|
||||
type Area = 'tenant' | 'master';
|
||||
|
||||
export default function EsqueciSenhaPage() {
|
||||
const [area, setArea] = React.useState<Area>('tenant');
|
||||
const [sent, setSent] = React.useState(false);
|
||||
const [error, setError] = React.useState<string | null>(null);
|
||||
|
||||
const {
|
||||
register,
|
||||
handleSubmit,
|
||||
formState: { errors, isSubmitting },
|
||||
} = useForm<ForgotPasswordFormValues>({ resolver: zodResolver(forgotPasswordSchema) });
|
||||
|
||||
const onSubmit = async (values: ForgotPasswordFormValues) => {
|
||||
setError(null);
|
||||
try {
|
||||
// Resposta é sempre genérica (200), mesmo se o e-mail não existir —
|
||||
// o backend nunca revela isso (Etapa 13: nunca revelar se o e-mail existe).
|
||||
await apiClient.post('/auth/password/forgot', {
|
||||
email: values.email,
|
||||
usuario_tipo: area === 'master' ? 'master' : 'tenant_user',
|
||||
});
|
||||
setSent(true);
|
||||
} catch (err) {
|
||||
setError(
|
||||
err instanceof ApiError ? err.message : 'Não foi possível conectar. Tente novamente.',
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<main className="flex min-h-screen items-center justify-center bg-neutral-50 p-4">
|
||||
<div className="flex w-full max-w-[420px] flex-col gap-6 rounded-xl border border-border bg-surface p-6 shadow-sm sm:p-8">
|
||||
<div className="flex flex-col gap-2 text-center">
|
||||
<h1 className="text-xl font-semibold text-foreground">Esqueci minha senha</h1>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Informe seu e-mail — se ele existir no sistema, enviaremos instruções de redefinição.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{sent ? (
|
||||
<div className="flex flex-col gap-4">
|
||||
<p role="status" className="rounded-lg bg-success/10 p-3 text-sm text-success">
|
||||
Se o e-mail informado existir, as instruções de redefinição foram enviadas.
|
||||
</p>
|
||||
<Link
|
||||
href="/login"
|
||||
className="text-center text-sm text-primary-on-light underline-offset-4 hover:underline"
|
||||
>
|
||||
Voltar para o login
|
||||
</Link>
|
||||
</div>
|
||||
) : (
|
||||
<form className="flex flex-col gap-4" onSubmit={handleSubmit(onSubmit)} noValidate>
|
||||
<div
|
||||
role="radiogroup"
|
||||
aria-label="Tipo de acesso"
|
||||
className="grid grid-cols-2 gap-1 rounded-lg bg-muted p-1"
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
role="radio"
|
||||
aria-checked={area === 'tenant'}
|
||||
onClick={() => setArea('tenant')}
|
||||
className={`min-h-9 rounded-md text-sm font-medium transition-colors focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring ${
|
||||
area === 'tenant'
|
||||
? 'bg-background text-foreground shadow-sm'
|
||||
: 'text-muted-foreground'
|
||||
}`}
|
||||
>
|
||||
Sou cliente
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
role="radio"
|
||||
aria-checked={area === 'master'}
|
||||
onClick={() => setArea('master')}
|
||||
className={`min-h-9 rounded-md text-sm font-medium transition-colors focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring ${
|
||||
area === 'master'
|
||||
? 'bg-background text-foreground shadow-sm'
|
||||
: 'text-muted-foreground'
|
||||
}`}
|
||||
>
|
||||
Sou administrador
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<FormField label="E-mail" error={errors.email?.message}>
|
||||
<Input type="email" autoComplete="email" {...register('email')} />
|
||||
</FormField>
|
||||
|
||||
{error && (
|
||||
<p role="alert" className="rounded-lg bg-danger/10 p-3 text-sm text-danger">
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
|
||||
<Button type="submit" loading={isSubmitting} className="w-full">
|
||||
Enviar instruções
|
||||
</Button>
|
||||
|
||||
<Link
|
||||
href="/login"
|
||||
className="text-center text-sm text-primary-on-light underline-offset-4 hover:underline"
|
||||
>
|
||||
Voltar para o login
|
||||
</Link>
|
||||
</form>
|
||||
)}
|
||||
</div>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,153 @@
|
||||
'use client';
|
||||
|
||||
import * as React from 'react';
|
||||
import { useRouter, useSearchParams } from 'next/navigation';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { zodResolver } from '@hookform/resolvers/zod';
|
||||
import Image from 'next/image';
|
||||
import { useAuth } from '@/lib/auth/auth-context';
|
||||
import { useTenantTheme, TenantThemeProvider } from '@/lib/theme/theme-provider';
|
||||
import { ApiError } from '@/lib/api/client';
|
||||
import { loginSchema, type LoginFormValues } from '@/lib/validators/auth';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { FormField } from '@/components/ui/form-field';
|
||||
import Link from 'next/link';
|
||||
|
||||
type LoginArea = 'tenant' | 'master';
|
||||
|
||||
function GenericInvalidCredentialsMessage(): string {
|
||||
return 'E-mail ou senha inválidos.';
|
||||
}
|
||||
|
||||
function LoginFormInner() {
|
||||
const router = useRouter();
|
||||
const searchParams = useSearchParams();
|
||||
const { loginMaster, loginTenant } = useAuth();
|
||||
const { theme } = useTenantTheme();
|
||||
|
||||
// Estratégia de detecção de tipo de login (Etapa 13): o backend expõe
|
||||
// dois endpoints separados (`/auth/master/login` e `/auth/tenant/login`,
|
||||
// sem detecção automática por e-mail — ver observações da Etapa 13 no
|
||||
// controle de progresso). Escolhido um toggle explícito em vez de dois
|
||||
// formulários separados por ser a opção mais simples de implementar e
|
||||
// mais clara para o usuário; "tenant" é o padrão porque é o público
|
||||
// majoritário (clientes), master é uso interno raro.
|
||||
const [area, setArea] = React.useState<LoginArea>('tenant');
|
||||
const [submitError, setSubmitError] = React.useState<string | null>(null);
|
||||
|
||||
const {
|
||||
register,
|
||||
handleSubmit,
|
||||
formState: { errors, isSubmitting },
|
||||
} = useForm<LoginFormValues>({ resolver: zodResolver(loginSchema) });
|
||||
|
||||
const onSubmit = async (values: LoginFormValues) => {
|
||||
setSubmitError(null);
|
||||
try {
|
||||
if (area === 'master') {
|
||||
await loginMaster(values.email, values.senha);
|
||||
} else {
|
||||
await loginTenant(values.email, values.senha);
|
||||
}
|
||||
|
||||
const redirectParam = searchParams.get('redirect');
|
||||
const fallback = area === 'master' ? '/master/dashboard' : '/app/dashboard';
|
||||
router.push(redirectParam && redirectParam.startsWith('/') ? redirectParam : fallback);
|
||||
} catch (err) {
|
||||
if (err instanceof ApiError && err.statusCode === 401) {
|
||||
setSubmitError(GenericInvalidCredentialsMessage());
|
||||
} else if (err instanceof ApiError) {
|
||||
setSubmitError(err.message);
|
||||
} else {
|
||||
setSubmitError('Não foi possível conectar. Tente novamente.');
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="flex w-full max-w-[420px] flex-col gap-6 rounded-xl border border-border bg-surface p-6 shadow-sm sm:p-8">
|
||||
<div className="flex flex-col items-center gap-2 text-center">
|
||||
{theme?.logoUrl ? (
|
||||
<Image
|
||||
src={theme.logoUrl}
|
||||
alt={theme.nome}
|
||||
width={48}
|
||||
height={48}
|
||||
className="size-12 rounded-lg object-contain"
|
||||
/>
|
||||
) : null}
|
||||
<h1 className="text-xl font-semibold text-foreground">
|
||||
{theme?.nome ?? 'SeConectai Vendas'}
|
||||
</h1>
|
||||
<p className="text-sm text-muted-foreground">Entre com seu e-mail e senha</p>
|
||||
</div>
|
||||
|
||||
<div
|
||||
role="radiogroup"
|
||||
aria-label="Tipo de acesso"
|
||||
className="grid grid-cols-2 gap-1 rounded-lg bg-muted p-1"
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
role="radio"
|
||||
aria-checked={area === 'tenant'}
|
||||
onClick={() => setArea('tenant')}
|
||||
className={`min-h-9 rounded-md text-sm font-medium transition-colors focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring ${
|
||||
area === 'tenant' ? 'bg-background text-foreground shadow-sm' : 'text-muted-foreground'
|
||||
}`}
|
||||
>
|
||||
Sou cliente
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
role="radio"
|
||||
aria-checked={area === 'master'}
|
||||
onClick={() => setArea('master')}
|
||||
className={`min-h-9 rounded-md text-sm font-medium transition-colors focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring ${
|
||||
area === 'master' ? 'bg-background text-foreground shadow-sm' : 'text-muted-foreground'
|
||||
}`}
|
||||
>
|
||||
Sou administrador
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<form className="flex flex-col gap-4" onSubmit={handleSubmit(onSubmit)} noValidate>
|
||||
<FormField label="E-mail" error={errors.email?.message}>
|
||||
<Input type="email" autoComplete="email" {...register('email')} />
|
||||
</FormField>
|
||||
<FormField label="Senha" error={errors.senha?.message}>
|
||||
<Input type="password" autoComplete="current-password" {...register('senha')} />
|
||||
</FormField>
|
||||
|
||||
{submitError && (
|
||||
<p role="alert" className="rounded-lg bg-danger/10 p-3 text-sm text-danger">
|
||||
{submitError}
|
||||
</p>
|
||||
)}
|
||||
|
||||
<Button type="submit" loading={isSubmitting} className="w-full">
|
||||
Entrar
|
||||
</Button>
|
||||
|
||||
<Link
|
||||
href="/esqueci-senha"
|
||||
className="text-center text-sm text-primary-on-light underline-offset-4 hover:underline"
|
||||
>
|
||||
Esqueci minha senha
|
||||
</Link>
|
||||
</form>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function LoginForm() {
|
||||
const searchParams = useSearchParams();
|
||||
const tenantId = searchParams.get('tenant');
|
||||
|
||||
return (
|
||||
<TenantThemeProvider tenantId={tenantId}>
|
||||
<LoginFormInner />
|
||||
</TenantThemeProvider>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
import { Suspense } from 'react';
|
||||
import { LoginForm } from './login-form';
|
||||
|
||||
export default function LoginPage() {
|
||||
return (
|
||||
<main className="flex min-h-screen items-center justify-center bg-neutral-50 p-4">
|
||||
<Suspense fallback={null}>
|
||||
<LoginForm />
|
||||
</Suspense>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
'use client';
|
||||
|
||||
import * as React from 'react';
|
||||
import Link from 'next/link';
|
||||
import { useParams } from 'next/navigation';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { zodResolver } from '@hookform/resolvers/zod';
|
||||
import { apiClient, ApiError } from '@/lib/api/client';
|
||||
import { resetPasswordSchema, type ResetPasswordFormValues } from '@/lib/validators/auth';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { FormField } from '@/components/ui/form-field';
|
||||
|
||||
export default function RedefinirSenhaPage() {
|
||||
const { token } = useParams<{ token: string }>();
|
||||
const [done, setDone] = React.useState(false);
|
||||
const [tokenInvalido, setTokenInvalido] = React.useState(false);
|
||||
const [error, setError] = React.useState<string | null>(null);
|
||||
|
||||
const {
|
||||
register,
|
||||
handleSubmit,
|
||||
formState: { errors, isSubmitting },
|
||||
} = useForm<ResetPasswordFormValues>({ resolver: zodResolver(resetPasswordSchema) });
|
||||
|
||||
const onSubmit = async (values: ResetPasswordFormValues) => {
|
||||
setError(null);
|
||||
setTokenInvalido(false);
|
||||
try {
|
||||
await apiClient.post('/auth/password/reset', { token, nova_senha: values.novaSenha });
|
||||
setDone(true);
|
||||
} catch (err) {
|
||||
if (err instanceof ApiError && err.statusCode === 401) {
|
||||
setTokenInvalido(true);
|
||||
} else if (err instanceof ApiError) {
|
||||
setError(err.message);
|
||||
} else {
|
||||
setError('Não foi possível conectar. Tente novamente.');
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<main className="flex min-h-screen items-center justify-center bg-neutral-50 p-4">
|
||||
<div className="flex w-full max-w-[420px] flex-col gap-6 rounded-xl border border-border bg-surface p-6 shadow-sm sm:p-8">
|
||||
<div className="flex flex-col gap-2 text-center">
|
||||
<h1 className="text-xl font-semibold text-foreground">Redefinir senha</h1>
|
||||
</div>
|
||||
|
||||
{done ? (
|
||||
<div className="flex flex-col gap-4">
|
||||
<p role="status" className="rounded-lg bg-success/10 p-3 text-sm text-success">
|
||||
Senha redefinida com sucesso.
|
||||
</p>
|
||||
<Link
|
||||
href="/login"
|
||||
className="text-center text-sm text-primary-on-light underline-offset-4 hover:underline"
|
||||
>
|
||||
Ir para o login
|
||||
</Link>
|
||||
</div>
|
||||
) : tokenInvalido ? (
|
||||
<div className="flex flex-col gap-4">
|
||||
<p role="alert" className="rounded-lg bg-danger/10 p-3 text-sm text-danger">
|
||||
Este link de redefinição é inválido ou já expirou.
|
||||
</p>
|
||||
<Link
|
||||
href="/esqueci-senha"
|
||||
className="text-center text-sm text-primary-on-light underline-offset-4 hover:underline"
|
||||
>
|
||||
Solicitar um novo link
|
||||
</Link>
|
||||
</div>
|
||||
) : (
|
||||
<form className="flex flex-col gap-4" onSubmit={handleSubmit(onSubmit)} noValidate>
|
||||
<FormField
|
||||
label="Nova senha"
|
||||
error={errors.novaSenha?.message}
|
||||
helpText="Mínimo de 10 caracteres."
|
||||
>
|
||||
<Input type="password" autoComplete="new-password" {...register('novaSenha')} />
|
||||
</FormField>
|
||||
<FormField label="Confirmar nova senha" error={errors.confirmarSenha?.message}>
|
||||
<Input type="password" autoComplete="new-password" {...register('confirmarSenha')} />
|
||||
</FormField>
|
||||
|
||||
{error && (
|
||||
<p role="alert" className="rounded-lg bg-danger/10 p-3 text-sm text-danger">
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
|
||||
<Button type="submit" loading={isSubmitting} className="w-full">
|
||||
Redefinir senha
|
||||
</Button>
|
||||
</form>
|
||||
)}
|
||||
</div>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,209 @@
|
||||
'use client';
|
||||
|
||||
import * as React from 'react';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import type { DateRange } from 'react-day-picker';
|
||||
|
||||
import {
|
||||
ALERT_LOG_STATUSES,
|
||||
listTenantAlertLogs,
|
||||
type AlertLog,
|
||||
type AlertLogStatus,
|
||||
} from '@/lib/api/tenant-alert-logs';
|
||||
import { CANAIS_TEMPLATE, CANAL_TEMPLATE_LABEL, TIPO_TEMPLATE_LABEL } from '@/lib/api/alert-templates';
|
||||
import type { CanalTemplate } from '@/lib/api/alert-templates';
|
||||
import { formatDateTime } from '@/lib/format';
|
||||
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { DataTable, type DataTableColumn } from '@/components/ui/data-table';
|
||||
import { DateRangePicker } from '@/components/ui/date-picker';
|
||||
import { ResponsiveDialog } from '@/components/ui/responsive-dialog';
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
|
||||
import { Separator } from '@/components/ui/separator';
|
||||
|
||||
const STATUS_LABEL: Record<AlertLogStatus, string> = {
|
||||
enviado: 'Enviado',
|
||||
entregue: 'Entregue',
|
||||
lido: 'Lido',
|
||||
falhou: 'Falhou',
|
||||
};
|
||||
|
||||
const STATUS_TONE: Record<AlertLogStatus, 'default' | 'destructive' | 'outline'> = {
|
||||
enviado: 'outline',
|
||||
entregue: 'default',
|
||||
lido: 'default',
|
||||
falhou: 'destructive',
|
||||
};
|
||||
|
||||
const STATUS_OPTIONS: { value: AlertLogStatus | 'todos'; label: string }[] = [
|
||||
{ value: 'todos', label: 'Todos os status' },
|
||||
...ALERT_LOG_STATUSES.map((s) => ({ value: s, label: STATUS_LABEL[s] })),
|
||||
];
|
||||
|
||||
const CANAL_OPTIONS: { value: CanalTemplate | 'todos'; label: string }[] = [
|
||||
{ value: 'todos', label: 'Todos os canais' },
|
||||
...CANAIS_TEMPLATE.map((c) => ({ value: c, label: CANAL_TEMPLATE_LABEL[c] })),
|
||||
];
|
||||
|
||||
const LIMIT = 20;
|
||||
|
||||
export default function TenantAlertLogsPage() {
|
||||
const [canal, setCanal] = React.useState<CanalTemplate | 'todos'>('todos');
|
||||
const [status, setStatus] = React.useState<AlertLogStatus | 'todos'>('todos');
|
||||
const [periodo, setPeriodo] = React.useState<DateRange | undefined>();
|
||||
const [page, setPage] = React.useState(1);
|
||||
const [detail, setDetail] = React.useState<AlertLog | null>(null);
|
||||
|
||||
const { data, isLoading } = useQuery({
|
||||
queryKey: [
|
||||
'tenant',
|
||||
'alert-logs',
|
||||
{ canal, status, de: periodo?.from?.toISOString(), ate: periodo?.to?.toISOString(), page },
|
||||
],
|
||||
queryFn: () =>
|
||||
listTenantAlertLogs({
|
||||
canal: canal === 'todos' ? undefined : canal,
|
||||
status: status === 'todos' ? undefined : status,
|
||||
data_inicio: periodo?.from?.toISOString(),
|
||||
data_fim: periodo?.to?.toISOString(),
|
||||
page,
|
||||
limit: LIMIT,
|
||||
}),
|
||||
placeholderData: (prev) => prev,
|
||||
});
|
||||
|
||||
const columns: DataTableColumn<AlertLog>[] = [
|
||||
{
|
||||
id: 'tipo',
|
||||
header: 'Tipo',
|
||||
primary: true,
|
||||
cell: (row) => (row.template ? TIPO_TEMPLATE_LABEL[row.template.tipo] : '—'),
|
||||
},
|
||||
{ id: 'canal', header: 'Canal', primary: true, cell: (row) => CANAL_TEMPLATE_LABEL[row.canal] },
|
||||
{
|
||||
id: 'status',
|
||||
header: 'Status',
|
||||
cell: (row) => <Badge variant={STATUS_TONE[row.status]}>{STATUS_LABEL[row.status]}</Badge>,
|
||||
},
|
||||
{ id: 'enviado_em', header: 'Enviado em', cell: (row) => formatDateTime(row.enviado_em) },
|
||||
];
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-6">
|
||||
<div>
|
||||
<h1 className="text-xl font-semibold text-foreground">Logs de alerta</h1>
|
||||
<p className="text-sm text-muted-foreground">Histórico de envios de WhatsApp/e-mail aos seus clientes</p>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col gap-3 sm:flex-row sm:flex-wrap sm:items-center">
|
||||
<Select
|
||||
value={canal}
|
||||
onValueChange={(value) => {
|
||||
setCanal(value as CanalTemplate | 'todos');
|
||||
setPage(1);
|
||||
}}
|
||||
>
|
||||
<SelectTrigger className="w-full sm:w-44" aria-label="Filtrar por canal">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{CANAL_OPTIONS.map((opt) => (
|
||||
<SelectItem key={opt.value} value={opt.value}>
|
||||
{opt.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<Select
|
||||
value={status}
|
||||
onValueChange={(value) => {
|
||||
setStatus(value as AlertLogStatus | 'todos');
|
||||
setPage(1);
|
||||
}}
|
||||
>
|
||||
<SelectTrigger className="w-full sm:w-44" aria-label="Filtrar por status">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{STATUS_OPTIONS.map((opt) => (
|
||||
<SelectItem key={opt.value} value={opt.value}>
|
||||
{opt.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<DateRangePicker
|
||||
value={periodo}
|
||||
onChange={(range) => {
|
||||
setPeriodo(range);
|
||||
setPage(1);
|
||||
}}
|
||||
placeholder="Período"
|
||||
className="w-full sm:w-64"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<DataTable
|
||||
columns={columns}
|
||||
data={data?.data ?? []}
|
||||
keyField={(row) => row.id}
|
||||
loading={isLoading}
|
||||
emptyTitle="Nenhum log encontrado"
|
||||
emptyDescription="Ajuste os filtros de período/canal/status."
|
||||
onRowClick={(row) => setDetail(row)}
|
||||
rowActions={() => (
|
||||
<Button variant="ghost" size="sm">
|
||||
Ver detalhes
|
||||
</Button>
|
||||
)}
|
||||
pagination={
|
||||
data ? { page: data.meta.page, limit: data.meta.limit, total: data.meta.total, onPageChange: setPage } : undefined
|
||||
}
|
||||
/>
|
||||
|
||||
<ResponsiveDialog
|
||||
open={detail !== null}
|
||||
onOpenChange={(open) => !open && setDetail(null)}
|
||||
title="Detalhe do envio"
|
||||
description={detail ? formatDateTime(detail.enviado_em) : undefined}
|
||||
>
|
||||
{detail && (
|
||||
<div className="flex flex-col gap-4 px-4 pb-4 sm:px-0 sm:pb-0">
|
||||
<div className="flex flex-wrap gap-4 text-sm">
|
||||
<div>
|
||||
<p className="text-muted-foreground">Tipo</p>
|
||||
<p className="font-medium text-foreground">
|
||||
{detail.template ? TIPO_TEMPLATE_LABEL[detail.template.tipo] : '—'}
|
||||
</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-muted-foreground">Canal</p>
|
||||
<p className="font-medium text-foreground">{CANAL_TEMPLATE_LABEL[detail.canal]}</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-muted-foreground">Status</p>
|
||||
<Badge variant={STATUS_TONE[detail.status]}>{STATUS_LABEL[detail.status]}</Badge>
|
||||
</div>
|
||||
</div>
|
||||
<Separator />
|
||||
<div>
|
||||
<p className="mb-1 text-sm font-medium text-foreground">Conteúdo enviado</p>
|
||||
<p className="rounded-lg border border-border bg-muted/50 p-3 text-sm whitespace-pre-wrap">
|
||||
{detail.conteudo_enviado || '—'}
|
||||
</p>
|
||||
</div>
|
||||
{detail.erro && (
|
||||
<div>
|
||||
<p className="mb-1 text-sm font-medium text-danger">Erro</p>
|
||||
<p className="rounded-lg border border-danger/30 bg-danger/10 p-3 text-sm whitespace-pre-wrap text-danger">
|
||||
{detail.erro}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</ResponsiveDialog>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,412 @@
|
||||
'use client';
|
||||
|
||||
import * as React from 'react';
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { zodResolver } from '@hookform/resolvers/zod';
|
||||
import { Plus } from 'lucide-react';
|
||||
|
||||
import {
|
||||
CANAIS_TEMPLATE,
|
||||
CANAL_TEMPLATE_LABEL,
|
||||
PLACEHOLDERS_POR_TIPO,
|
||||
TIPOS_TEMPLATE_TENANT,
|
||||
TIPO_TEMPLATE_TENANT_LABEL,
|
||||
createTenantAlertTemplate,
|
||||
deleteTenantAlertTemplate,
|
||||
listTenantAlertTemplates,
|
||||
updateTenantAlertTemplate,
|
||||
type AlertTemplate,
|
||||
type CanalTemplate,
|
||||
type TipoTemplateTenant,
|
||||
} from '@/lib/api/tenant-alert-templates';
|
||||
import {
|
||||
tenantAlertTemplateSchema,
|
||||
type TenantAlertTemplateFormValues,
|
||||
} from '@/lib/validators/tenant-alert-templates';
|
||||
import { ApiError } from '@/lib/api/client';
|
||||
import { toast } from '@/lib/toast';
|
||||
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Card } from '@/components/ui/card';
|
||||
import { DataTable, type DataTableColumn } from '@/components/ui/data-table';
|
||||
import { FormField } from '@/components/ui/form-field';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { ResponsiveDialog } from '@/components/ui/responsive-dialog';
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
|
||||
import { Textarea } from '@/components/ui/textarea';
|
||||
import { ConfirmDialog } from '@/components/domain/confirm-dialog';
|
||||
|
||||
const TIPO_OPTIONS: { value: TipoTemplateTenant | 'todos'; label: string }[] = [
|
||||
{ value: 'todos', label: 'Todos os tipos' },
|
||||
...TIPOS_TEMPLATE_TENANT.map((tipo) => ({ value: tipo, label: TIPO_TEMPLATE_TENANT_LABEL[tipo] })),
|
||||
];
|
||||
|
||||
const CANAL_OPTIONS: { value: CanalTemplate | 'todos'; label: string }[] = [
|
||||
{ value: 'todos', label: 'Todos os canais' },
|
||||
...CANAIS_TEMPLATE.map((canal) => ({ value: canal, label: CANAL_TEMPLATE_LABEL[canal] })),
|
||||
];
|
||||
|
||||
const LIMIT = 20;
|
||||
// Limite alto o bastante para trazer todas as combinações tipo×canal numa
|
||||
// única chamada — usado só para calcular a matriz de fallback abaixo, não
|
||||
// para a listagem paginada principal.
|
||||
const MATRIX_LIMIT = 100;
|
||||
|
||||
export default function TenantAlertTemplatesPage() {
|
||||
const queryClient = useQueryClient();
|
||||
const [tipo, setTipo] = React.useState<TipoTemplateTenant | 'todos'>('todos');
|
||||
const [canal, setCanal] = React.useState<CanalTemplate | 'todos'>('todos');
|
||||
const [page, setPage] = React.useState(1);
|
||||
|
||||
const [editing, setEditing] = React.useState<AlertTemplate | null>(null);
|
||||
const [formOpen, setFormOpen] = React.useState(false);
|
||||
const [deleting, setDeleting] = React.useState<AlertTemplate | null>(null);
|
||||
|
||||
const { data, isLoading } = useQuery({
|
||||
queryKey: ['tenant', 'alert-templates', { tipo, canal, page }],
|
||||
queryFn: () =>
|
||||
listTenantAlertTemplates({
|
||||
tipo: tipo === 'todos' ? undefined : tipo,
|
||||
canal: canal === 'todos' ? undefined : canal,
|
||||
page,
|
||||
limit: LIMIT,
|
||||
}),
|
||||
placeholderData: (prev) => prev,
|
||||
});
|
||||
|
||||
// Matriz de fallback: não existe endpoint que informe se um tipo/canal
|
||||
// está usando o padrão da plataforma — inferido client-side comparando
|
||||
// contra a lista completa de templates ativos do tenant.
|
||||
const { data: allTemplates } = useQuery({
|
||||
queryKey: ['tenant', 'alert-templates', 'matrix'],
|
||||
queryFn: () => listTenantAlertTemplates({ ativo: true, limit: MATRIX_LIMIT }),
|
||||
});
|
||||
|
||||
const form = useForm<TenantAlertTemplateFormValues>({ resolver: zodResolver(tenantAlertTemplateSchema) });
|
||||
const corpoFieldRef = React.useRef<HTMLTextAreaElement | null>(null);
|
||||
const { ref: corpoRegisterRef, ...corpoRegister } = form.register('corpo');
|
||||
const watchedTipo = form.watch('tipo');
|
||||
const watchedCanal = form.watch('canal');
|
||||
|
||||
function openCreate(preset?: { tipo: TipoTemplateTenant; canal: CanalTemplate }) {
|
||||
setEditing(null);
|
||||
form.reset({
|
||||
tipo: preset?.tipo ?? 'cobranca_cliente',
|
||||
canal: preset?.canal ?? 'whatsapp',
|
||||
assunto: '',
|
||||
corpo: '',
|
||||
ativo: true,
|
||||
});
|
||||
setFormOpen(true);
|
||||
}
|
||||
|
||||
function openEdit(template: AlertTemplate) {
|
||||
setEditing(template);
|
||||
form.reset({
|
||||
tipo: template.tipo as TipoTemplateTenant,
|
||||
canal: template.canal,
|
||||
assunto: template.assunto ?? '',
|
||||
corpo: template.corpo,
|
||||
ativo: template.ativo,
|
||||
});
|
||||
setFormOpen(true);
|
||||
}
|
||||
|
||||
function insertPlaceholder(chave: string) {
|
||||
const token = `{{${chave}}}`;
|
||||
const el = corpoFieldRef.current;
|
||||
const current = form.getValues('corpo') ?? '';
|
||||
|
||||
if (!el) {
|
||||
form.setValue('corpo', current + token, { shouldValidate: true });
|
||||
return;
|
||||
}
|
||||
|
||||
const start = el.selectionStart ?? current.length;
|
||||
const end = el.selectionEnd ?? current.length;
|
||||
const next = current.slice(0, start) + token + current.slice(end);
|
||||
form.setValue('corpo', next, { shouldValidate: true });
|
||||
|
||||
requestAnimationFrame(() => {
|
||||
el.focus();
|
||||
const pos = start + token.length;
|
||||
el.setSelectionRange(pos, pos);
|
||||
});
|
||||
}
|
||||
|
||||
function invalidateAll() {
|
||||
queryClient.invalidateQueries({ queryKey: ['tenant', 'alert-templates'] });
|
||||
}
|
||||
|
||||
const saveMutation = useMutation({
|
||||
mutationFn: (values: TenantAlertTemplateFormValues) => {
|
||||
const payload = { ...values, assunto: values.canal === 'email' ? values.assunto : undefined };
|
||||
return editing ? updateTenantAlertTemplate(editing.id, payload) : createTenantAlertTemplate(payload);
|
||||
},
|
||||
onSuccess: () => {
|
||||
invalidateAll();
|
||||
toast.success(editing ? 'Template atualizado.' : 'Template criado.');
|
||||
setFormOpen(false);
|
||||
},
|
||||
onError: (err) => {
|
||||
toast.error(err instanceof ApiError ? err.message : 'Não foi possível salvar o template.');
|
||||
},
|
||||
});
|
||||
|
||||
const deleteMutation = useMutation({
|
||||
mutationFn: (id: string) => deleteTenantAlertTemplate(id),
|
||||
onSuccess: () => {
|
||||
invalidateAll();
|
||||
toast.success('Template desativado.');
|
||||
setDeleting(null);
|
||||
},
|
||||
onError: (err) => {
|
||||
toast.error(err instanceof ApiError ? err.message : 'Não foi possível desativar o template.');
|
||||
setDeleting(null);
|
||||
},
|
||||
});
|
||||
|
||||
const columns: DataTableColumn<AlertTemplate>[] = [
|
||||
{ id: 'tipo', header: 'Tipo', primary: true, cell: (row) => TIPO_TEMPLATE_TENANT_LABEL[row.tipo as TipoTemplateTenant] },
|
||||
{ id: 'canal', header: 'Canal', primary: true, cell: (row) => CANAL_TEMPLATE_LABEL[row.canal] },
|
||||
{
|
||||
id: 'corpo',
|
||||
header: 'Prévia',
|
||||
cell: (row) => <span className="line-clamp-1 text-muted-foreground">{row.corpo}</span>,
|
||||
},
|
||||
{
|
||||
id: 'status',
|
||||
header: 'Status',
|
||||
cell: (row) => <Badge variant={row.ativo ? 'default' : 'outline'}>{row.ativo ? 'Ativo' : 'Inativo'}</Badge>,
|
||||
},
|
||||
];
|
||||
|
||||
const placeholders = watchedTipo ? PLACEHOLDERS_POR_TIPO[watchedTipo] : [];
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-6">
|
||||
<div className="flex flex-wrap items-center justify-between gap-4">
|
||||
<div>
|
||||
<h1 className="text-xl font-semibold text-foreground">Templates de alerta</h1>
|
||||
<p className="text-sm text-muted-foreground">Mensagens enviadas aos seus clientes</p>
|
||||
</div>
|
||||
<Button onClick={() => openCreate()}>
|
||||
<Plus /> Novo template
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-3">
|
||||
{TIPOS_TEMPLATE_TENANT.map((t) =>
|
||||
CANAIS_TEMPLATE.map((c) => {
|
||||
const usaProprio = allTemplates?.data.some((tpl) => tpl.tipo === t && tpl.canal === c) ?? false;
|
||||
return (
|
||||
<Card key={`${t}-${c}`} className="flex flex-col gap-2 p-4">
|
||||
<p className="text-sm font-medium text-foreground">
|
||||
{TIPO_TEMPLATE_TENANT_LABEL[t]} · {CANAL_TEMPLATE_LABEL[c]}
|
||||
</p>
|
||||
{usaProprio ? (
|
||||
<Badge variant="default" className="w-fit">
|
||||
Template próprio configurado
|
||||
</Badge>
|
||||
) : (
|
||||
<>
|
||||
<Badge variant="outline" className="w-fit">
|
||||
Usando padrão da plataforma
|
||||
</Badge>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="w-fit"
|
||||
onClick={() => openCreate({ tipo: t, canal: c })}
|
||||
>
|
||||
Criar meu próprio
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
</Card>
|
||||
);
|
||||
}),
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col gap-3 sm:flex-row sm:items-center">
|
||||
<Select
|
||||
value={tipo}
|
||||
onValueChange={(value) => {
|
||||
setTipo(value as TipoTemplateTenant | 'todos');
|
||||
setPage(1);
|
||||
}}
|
||||
>
|
||||
<SelectTrigger className="w-full sm:w-56" aria-label="Filtrar por tipo">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{TIPO_OPTIONS.map((opt) => (
|
||||
<SelectItem key={opt.value} value={opt.value}>
|
||||
{opt.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<Select
|
||||
value={canal}
|
||||
onValueChange={(value) => {
|
||||
setCanal(value as CanalTemplate | 'todos');
|
||||
setPage(1);
|
||||
}}
|
||||
>
|
||||
<SelectTrigger className="w-full sm:w-44" aria-label="Filtrar por canal">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{CANAL_OPTIONS.map((opt) => (
|
||||
<SelectItem key={opt.value} value={opt.value}>
|
||||
{opt.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
<DataTable
|
||||
columns={columns}
|
||||
data={data?.data ?? []}
|
||||
keyField={(row) => row.id}
|
||||
loading={isLoading}
|
||||
emptyTitle="Nenhum template próprio cadastrado"
|
||||
emptyDescription="Sem um template próprio, o padrão da plataforma é usado automaticamente."
|
||||
emptyAction={
|
||||
<Button size="sm" onClick={() => openCreate()}>
|
||||
Novo template
|
||||
</Button>
|
||||
}
|
||||
rowActions={(row) => (
|
||||
<>
|
||||
<Button variant="ghost" size="sm" onClick={() => openEdit(row)}>
|
||||
Editar
|
||||
</Button>
|
||||
<Button variant="ghost" size="sm" onClick={() => setDeleting(row)}>
|
||||
Desativar
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
pagination={
|
||||
data ? { page: data.meta.page, limit: data.meta.limit, total: data.meta.total, onPageChange: setPage } : undefined
|
||||
}
|
||||
/>
|
||||
|
||||
<ResponsiveDialog
|
||||
open={formOpen}
|
||||
onOpenChange={setFormOpen}
|
||||
title={editing ? 'Editar template' : 'Novo template'}
|
||||
className="sm:max-w-2xl"
|
||||
footer={
|
||||
<>
|
||||
<Button variant="outline" onClick={() => setFormOpen(false)}>
|
||||
Cancelar
|
||||
</Button>
|
||||
<Button
|
||||
loading={saveMutation.isPending}
|
||||
onClick={form.handleSubmit((values) => saveMutation.mutate(values))}
|
||||
>
|
||||
Salvar
|
||||
</Button>
|
||||
</>
|
||||
}
|
||||
>
|
||||
<form
|
||||
className="flex flex-col gap-4 px-4 pb-4 sm:px-0 sm:pb-0"
|
||||
onSubmit={form.handleSubmit((values) => saveMutation.mutate(values))}
|
||||
>
|
||||
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
|
||||
<FormField label="Tipo" id="tipo" error={form.formState.errors.tipo?.message} required>
|
||||
<Select
|
||||
value={watchedTipo}
|
||||
onValueChange={(value) =>
|
||||
form.setValue('tipo', value as TipoTemplateTenant, { shouldValidate: true })
|
||||
}
|
||||
>
|
||||
<SelectTrigger id="tipo" className="w-full">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{TIPOS_TEMPLATE_TENANT.map((t) => (
|
||||
<SelectItem key={t} value={t}>
|
||||
{TIPO_TEMPLATE_TENANT_LABEL[t]}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</FormField>
|
||||
<FormField label="Canal" id="canal" error={form.formState.errors.canal?.message} required>
|
||||
<Select
|
||||
value={watchedCanal}
|
||||
onValueChange={(value) => form.setValue('canal', value as CanalTemplate, { shouldValidate: true })}
|
||||
>
|
||||
<SelectTrigger id="canal" className="w-full">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{CANAIS_TEMPLATE.map((c) => (
|
||||
<SelectItem key={c} value={c}>
|
||||
{CANAL_TEMPLATE_LABEL[c]}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</FormField>
|
||||
</div>
|
||||
|
||||
{watchedCanal === 'email' && (
|
||||
<FormField label="Assunto" error={form.formState.errors.assunto?.message} required>
|
||||
<Input {...form.register('assunto')} />
|
||||
</FormField>
|
||||
)}
|
||||
|
||||
<div className="grid grid-cols-1 gap-4 sm:grid-cols-[1fr_220px]">
|
||||
<FormField label="Corpo da mensagem" error={form.formState.errors.corpo?.message} required>
|
||||
<Textarea
|
||||
rows={8}
|
||||
{...corpoRegister}
|
||||
ref={(el) => {
|
||||
corpoRegisterRef(el);
|
||||
corpoFieldRef.current = el;
|
||||
}}
|
||||
/>
|
||||
</FormField>
|
||||
<div className="flex flex-col gap-2">
|
||||
<p className="text-xs font-medium text-muted-foreground">Placeholders disponíveis</p>
|
||||
<div className="flex flex-col gap-1.5 overflow-y-auto rounded-lg border border-border p-2 sm:max-h-56">
|
||||
{placeholders.map((p) => (
|
||||
<button
|
||||
key={p.chave}
|
||||
type="button"
|
||||
onClick={() => insertPlaceholder(p.chave)}
|
||||
title={p.descricao}
|
||||
className="rounded-md px-2 py-1.5 text-left text-xs hover:bg-muted"
|
||||
>
|
||||
<code className="font-mono font-medium text-primary-on-light">{`{{${p.chave}}}`}</code>
|
||||
<p className="text-muted-foreground">{p.descricao}</p>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
</ResponsiveDialog>
|
||||
|
||||
<ConfirmDialog
|
||||
open={deleting !== null}
|
||||
onOpenChange={(open) => !open && setDeleting(null)}
|
||||
title="Desativar template?"
|
||||
description="O padrão da plataforma volta a ser usado nos disparos automáticos, mas o template continua no histórico."
|
||||
confirmLabel="Desativar"
|
||||
destructive
|
||||
loading={deleteMutation.isPending}
|
||||
onConfirm={() => deleting && deleteMutation.mutate(deleting.id)}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,473 @@
|
||||
'use client';
|
||||
|
||||
import * as React from 'react';
|
||||
import Link from 'next/link';
|
||||
import { useParams } from 'next/navigation';
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { zodResolver } from '@hookform/resolvers/zod';
|
||||
import { Plus, Star } from 'lucide-react';
|
||||
|
||||
import {
|
||||
createCustomerContact,
|
||||
deactivateCustomer,
|
||||
deleteCustomerContact,
|
||||
getCustomer,
|
||||
updateCustomer,
|
||||
updateCustomerContact,
|
||||
type Customer,
|
||||
type CustomerContact,
|
||||
} from '@/lib/api/customers';
|
||||
import { listSales, type SaleListItem } from '@/lib/api/sales';
|
||||
import {
|
||||
customerContactSchema,
|
||||
customerSchema,
|
||||
type CustomerContactFormValues,
|
||||
type CustomerFormValues,
|
||||
} from '@/lib/validators/customers';
|
||||
import { ApiError } from '@/lib/api/client';
|
||||
import { BR_STATES } from '@/lib/br-states';
|
||||
import { formatCurrency, formatDate } from '@/lib/format';
|
||||
import { toast } from '@/lib/toast';
|
||||
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { DataTable, type DataTableColumn } from '@/components/ui/data-table';
|
||||
import { FormField } from '@/components/ui/form-field';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { ResponsiveDialog } from '@/components/ui/responsive-dialog';
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
|
||||
import { Skeleton } from '@/components/ui/skeleton';
|
||||
import { StatusPill } from '@/components/ui/status-pill';
|
||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
|
||||
import { Textarea } from '@/components/ui/textarea';
|
||||
import { ConfirmDialog } from '@/components/domain/confirm-dialog';
|
||||
|
||||
export default function ClienteDetalhePage() {
|
||||
const params = useParams<{ id: string }>();
|
||||
const customerId = params.id;
|
||||
const queryClient = useQueryClient();
|
||||
const [deactivateOpen, setDeactivateOpen] = React.useState(false);
|
||||
|
||||
const { data: customer, isLoading } = useQuery({
|
||||
queryKey: ['tenant', 'customers', customerId],
|
||||
queryFn: () => getCustomer(customerId),
|
||||
});
|
||||
|
||||
const deactivateMutation = useMutation({
|
||||
mutationFn: () => deactivateCustomer(customerId),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['tenant', 'customers'] });
|
||||
toast.success('Cliente desativado.');
|
||||
setDeactivateOpen(false);
|
||||
},
|
||||
onError: (err) => {
|
||||
toast.error(err instanceof ApiError ? err.message : 'Não foi possível desativar o cliente.');
|
||||
setDeactivateOpen(false);
|
||||
},
|
||||
});
|
||||
|
||||
if (isLoading || !customer) {
|
||||
return (
|
||||
<div className="flex flex-col gap-4">
|
||||
<Skeleton className="h-8 w-64" />
|
||||
<Skeleton className="h-64 w-full" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-6">
|
||||
<div className="flex flex-wrap items-center justify-between gap-4">
|
||||
<div>
|
||||
<div className="flex items-center gap-3">
|
||||
<h1 className="text-xl font-semibold text-foreground">
|
||||
{customer.nome_fantasia || customer.razao_social}
|
||||
</h1>
|
||||
<Badge variant={customer.ativo ? 'default' : 'outline'}>{customer.ativo ? 'Ativo' : 'Inativo'}</Badge>
|
||||
</div>
|
||||
<p className="text-sm text-muted-foreground">{customer.documento || customer.email || '—'}</p>
|
||||
</div>
|
||||
{customer.ativo && (
|
||||
<Button variant="outline" onClick={() => setDeactivateOpen(true)}>
|
||||
Desativar cliente
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<Tabs defaultValue="dados">
|
||||
<TabsList>
|
||||
<TabsTrigger value="dados">Dados cadastrais</TabsTrigger>
|
||||
<TabsTrigger value="contatos">Contatos</TabsTrigger>
|
||||
<TabsTrigger value="historico">Histórico de vendas</TabsTrigger>
|
||||
</TabsList>
|
||||
|
||||
<TabsContent value="dados" className="pt-4">
|
||||
<DadosCadastraisForm customerId={customerId} customer={customer} />
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="contatos" className="pt-4">
|
||||
<ContatosTab customerId={customerId} contatos={customer.contatos} />
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="historico" className="pt-4">
|
||||
<HistoricoVendasTab customerId={customerId} />
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
|
||||
<ConfirmDialog
|
||||
open={deactivateOpen}
|
||||
onOpenChange={setDeactivateOpen}
|
||||
title="Desativar cliente?"
|
||||
description="O cliente sai das listagens de ativos, mas o cadastro e o histórico de vendas continuam disponíveis."
|
||||
confirmLabel="Desativar"
|
||||
destructive
|
||||
loading={deactivateMutation.isPending}
|
||||
onConfirm={() => deactivateMutation.mutate()}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function DadosCadastraisForm({ customerId, customer }: { customerId: string; customer: Customer }) {
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
const form = useForm<CustomerFormValues>({
|
||||
resolver: zodResolver(customerSchema),
|
||||
defaultValues: {
|
||||
razao_social: customer.razao_social,
|
||||
nome_fantasia: customer.nome_fantasia ?? '',
|
||||
documento: customer.documento ?? '',
|
||||
email: customer.email ?? '',
|
||||
telefone_whatsapp: customer.telefone_whatsapp ?? '',
|
||||
endereco: customer.endereco ?? '',
|
||||
cidade: customer.cidade ?? '',
|
||||
uf: customer.uf ?? '',
|
||||
observacoes: customer.observacoes ?? '',
|
||||
},
|
||||
});
|
||||
|
||||
const mutation = useMutation({
|
||||
mutationFn: (values: CustomerFormValues) =>
|
||||
updateCustomer(customerId, {
|
||||
...values,
|
||||
nome_fantasia: values.nome_fantasia || undefined,
|
||||
documento: values.documento || undefined,
|
||||
email: values.email || undefined,
|
||||
telefone_whatsapp: values.telefone_whatsapp || undefined,
|
||||
endereco: values.endereco || undefined,
|
||||
cidade: values.cidade || undefined,
|
||||
uf: values.uf || undefined,
|
||||
observacoes: values.observacoes || undefined,
|
||||
}),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['tenant', 'customers', customerId] });
|
||||
queryClient.invalidateQueries({ queryKey: ['tenant', 'customers'] });
|
||||
toast.success('Dados do cliente atualizados.');
|
||||
},
|
||||
onError: (err) => {
|
||||
toast.error(err instanceof ApiError ? err.message : 'Não foi possível salvar as alterações.');
|
||||
},
|
||||
});
|
||||
|
||||
return (
|
||||
<Card className="max-w-2xl">
|
||||
<CardHeader>
|
||||
<CardTitle>Dados cadastrais</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<form
|
||||
className="flex flex-col gap-4"
|
||||
onSubmit={form.handleSubmit((values) => mutation.mutate(values))}
|
||||
>
|
||||
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
|
||||
<FormField label="Razão social" error={form.formState.errors.razao_social?.message} required>
|
||||
<Input {...form.register('razao_social')} />
|
||||
</FormField>
|
||||
<FormField label="Nome fantasia" error={form.formState.errors.nome_fantasia?.message}>
|
||||
<Input {...form.register('nome_fantasia')} />
|
||||
</FormField>
|
||||
</div>
|
||||
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
|
||||
<FormField label="Documento (CPF/CNPJ)" error={form.formState.errors.documento?.message}>
|
||||
<Input {...form.register('documento')} />
|
||||
</FormField>
|
||||
<FormField label="Telefone/WhatsApp" error={form.formState.errors.telefone_whatsapp?.message}>
|
||||
<Input {...form.register('telefone_whatsapp')} />
|
||||
</FormField>
|
||||
</div>
|
||||
<FormField label="E-mail" error={form.formState.errors.email?.message}>
|
||||
<Input type="email" {...form.register('email')} />
|
||||
</FormField>
|
||||
<FormField label="Endereço" error={form.formState.errors.endereco?.message}>
|
||||
<Input {...form.register('endereco')} />
|
||||
</FormField>
|
||||
<div className="grid grid-cols-1 gap-4 sm:grid-cols-[1fr_120px]">
|
||||
<FormField label="Cidade" error={form.formState.errors.cidade?.message}>
|
||||
<Input {...form.register('cidade')} />
|
||||
</FormField>
|
||||
<FormField label="UF" id="uf" error={form.formState.errors.uf?.message}>
|
||||
<Select
|
||||
value={form.watch('uf')}
|
||||
onValueChange={(value) => form.setValue('uf', value, { shouldValidate: true })}
|
||||
>
|
||||
<SelectTrigger id="uf" className="w-full">
|
||||
<SelectValue placeholder="UF" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{BR_STATES.map((uf) => (
|
||||
<SelectItem key={uf} value={uf}>
|
||||
{uf}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</FormField>
|
||||
</div>
|
||||
<FormField label="Observações" error={form.formState.errors.observacoes?.message}>
|
||||
<Textarea rows={3} {...form.register('observacoes')} />
|
||||
</FormField>
|
||||
<div>
|
||||
<Button type="submit" loading={mutation.isPending}>
|
||||
Salvar alterações
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
function ContatosTab({ customerId, contatos }: { customerId: string; contatos: CustomerContact[] }) {
|
||||
const queryClient = useQueryClient();
|
||||
const [editing, setEditing] = React.useState<CustomerContact | null>(null);
|
||||
const [formOpen, setFormOpen] = React.useState(false);
|
||||
const [deleting, setDeleting] = React.useState<CustomerContact | null>(null);
|
||||
const [settingPrincipalId, setSettingPrincipalId] = React.useState<string | null>(null);
|
||||
|
||||
const form = useForm<CustomerContactFormValues>({ resolver: zodResolver(customerContactSchema) });
|
||||
|
||||
function invalidate() {
|
||||
queryClient.invalidateQueries({ queryKey: ['tenant', 'customers', customerId] });
|
||||
}
|
||||
|
||||
function openCreate() {
|
||||
setEditing(null);
|
||||
form.reset({ nome: '', cargo: '', email: '', telefone_whatsapp: '', principal: contatos.length === 0 });
|
||||
setFormOpen(true);
|
||||
}
|
||||
|
||||
function openEdit(contact: CustomerContact) {
|
||||
setEditing(contact);
|
||||
form.reset({
|
||||
nome: contact.nome,
|
||||
cargo: contact.cargo ?? '',
|
||||
email: contact.email ?? '',
|
||||
telefone_whatsapp: contact.telefone_whatsapp ?? '',
|
||||
principal: contact.principal,
|
||||
});
|
||||
setFormOpen(true);
|
||||
}
|
||||
|
||||
const saveMutation = useMutation({
|
||||
mutationFn: (values: CustomerContactFormValues) => {
|
||||
const payload = {
|
||||
nome: values.nome,
|
||||
cargo: values.cargo || undefined,
|
||||
email: values.email || undefined,
|
||||
telefone_whatsapp: values.telefone_whatsapp || undefined,
|
||||
principal: values.principal,
|
||||
};
|
||||
return editing
|
||||
? updateCustomerContact(customerId, editing.id, payload)
|
||||
: createCustomerContact(customerId, payload);
|
||||
},
|
||||
onSuccess: () => {
|
||||
invalidate();
|
||||
toast.success(editing ? 'Contato atualizado.' : 'Contato adicionado.');
|
||||
setFormOpen(false);
|
||||
},
|
||||
onError: (err) => {
|
||||
toast.error(err instanceof ApiError ? err.message : 'Não foi possível salvar o contato.');
|
||||
},
|
||||
});
|
||||
|
||||
const deleteMutation = useMutation({
|
||||
mutationFn: (contactId: string) => deleteCustomerContact(customerId, contactId),
|
||||
onSuccess: () => {
|
||||
invalidate();
|
||||
toast.success('Contato removido.');
|
||||
setDeleting(null);
|
||||
},
|
||||
onError: (err) => {
|
||||
toast.error(err instanceof ApiError ? err.message : 'Não foi possível remover o contato.');
|
||||
setDeleting(null);
|
||||
},
|
||||
});
|
||||
|
||||
const setPrincipalMutation = useMutation({
|
||||
mutationFn: (contactId: string) => updateCustomerContact(customerId, contactId, { principal: true }),
|
||||
onMutate: (contactId) => setSettingPrincipalId(contactId),
|
||||
onSuccess: () => {
|
||||
invalidate();
|
||||
toast.success('Contato principal atualizado.');
|
||||
},
|
||||
onError: (err) => {
|
||||
toast.error(err instanceof ApiError ? err.message : 'Não foi possível atualizar o contato principal.');
|
||||
},
|
||||
onSettled: () => setSettingPrincipalId(null),
|
||||
});
|
||||
|
||||
const columns: DataTableColumn<CustomerContact>[] = [
|
||||
{
|
||||
id: 'nome',
|
||||
header: 'Nome',
|
||||
primary: true,
|
||||
cell: (row) => (
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="font-medium text-foreground">{row.nome}</span>
|
||||
{row.principal && <Badge>Principal</Badge>}
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{ id: 'cargo', header: 'Cargo', cell: (row) => row.cargo || '—' },
|
||||
{
|
||||
id: 'contato',
|
||||
header: 'Contato',
|
||||
primary: true,
|
||||
cell: (row) => (
|
||||
<div className="flex flex-col">
|
||||
{row.telefone_whatsapp && <span>{row.telefone_whatsapp}</span>}
|
||||
{row.email && <span className="text-xs text-muted-foreground">{row.email}</span>}
|
||||
{!row.telefone_whatsapp && !row.email && '—'}
|
||||
</div>
|
||||
),
|
||||
},
|
||||
];
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-4">
|
||||
<div className="flex justify-end">
|
||||
<Button size="sm" onClick={openCreate}>
|
||||
<Plus /> Novo contato
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<DataTable
|
||||
columns={columns}
|
||||
data={contatos}
|
||||
keyField={(row) => row.id}
|
||||
emptyTitle="Nenhum contato cadastrado"
|
||||
emptyAction={
|
||||
<Button size="sm" onClick={openCreate}>
|
||||
Novo contato
|
||||
</Button>
|
||||
}
|
||||
rowActions={(row) => (
|
||||
<>
|
||||
{!row.principal && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
loading={settingPrincipalId === row.id}
|
||||
onClick={() => setPrincipalMutation.mutate(row.id)}
|
||||
>
|
||||
<Star /> Tornar principal
|
||||
</Button>
|
||||
)}
|
||||
<Button variant="ghost" size="sm" onClick={() => openEdit(row)}>
|
||||
Editar
|
||||
</Button>
|
||||
<Button variant="ghost" size="sm" onClick={() => setDeleting(row)}>
|
||||
Excluir
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
/>
|
||||
|
||||
<ResponsiveDialog
|
||||
open={formOpen}
|
||||
onOpenChange={setFormOpen}
|
||||
title={editing ? 'Editar contato' : 'Novo contato'}
|
||||
footer={
|
||||
<>
|
||||
<Button variant="outline" onClick={() => setFormOpen(false)}>
|
||||
Cancelar
|
||||
</Button>
|
||||
<Button
|
||||
loading={saveMutation.isPending}
|
||||
onClick={form.handleSubmit((values) => saveMutation.mutate(values))}
|
||||
>
|
||||
Salvar
|
||||
</Button>
|
||||
</>
|
||||
}
|
||||
>
|
||||
<form
|
||||
className="flex flex-col gap-4 px-4 pb-4 sm:px-0 sm:pb-0"
|
||||
onSubmit={form.handleSubmit((values) => saveMutation.mutate(values))}
|
||||
>
|
||||
<FormField label="Nome" error={form.formState.errors.nome?.message} required>
|
||||
<Input {...form.register('nome')} />
|
||||
</FormField>
|
||||
<FormField label="Cargo" error={form.formState.errors.cargo?.message}>
|
||||
<Input {...form.register('cargo')} />
|
||||
</FormField>
|
||||
<FormField label="E-mail" error={form.formState.errors.email?.message}>
|
||||
<Input type="email" {...form.register('email')} />
|
||||
</FormField>
|
||||
<FormField label="Telefone/WhatsApp" error={form.formState.errors.telefone_whatsapp?.message}>
|
||||
<Input {...form.register('telefone_whatsapp')} />
|
||||
</FormField>
|
||||
</form>
|
||||
</ResponsiveDialog>
|
||||
|
||||
<ConfirmDialog
|
||||
open={deleting !== null}
|
||||
onOpenChange={(open) => !open && setDeleting(null)}
|
||||
title={`Remover "${deleting?.nome}"?`}
|
||||
description="Esta ação não pode ser desfeita."
|
||||
confirmLabel="Remover"
|
||||
destructive
|
||||
loading={deleteMutation.isPending}
|
||||
onConfirm={() => deleting && deleteMutation.mutate(deleting.id)}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function HistoricoVendasTab({ customerId }: { customerId: string }) {
|
||||
const [page, setPage] = React.useState(1);
|
||||
const { data, isLoading } = useQuery({
|
||||
queryKey: ['tenant', 'vendas', { customerId, page }],
|
||||
queryFn: () => listSales({ customer_id: customerId, page, limit: 10 }),
|
||||
placeholderData: (prev) => prev,
|
||||
});
|
||||
|
||||
const columns: DataTableColumn<SaleListItem>[] = [
|
||||
{ id: 'numero', header: 'Venda', primary: true, cell: (row) => `#${row.numero_venda}` },
|
||||
{ id: 'status', header: 'Status', primary: true, cell: (row) => <StatusPill status={row.status} /> },
|
||||
{ id: 'valor', header: 'Valor total', cell: (row) => formatCurrency(row.valor_total) },
|
||||
{ id: 'data', header: 'Data', cell: (row) => formatDate(row.data_venda) },
|
||||
];
|
||||
|
||||
return (
|
||||
<DataTable
|
||||
columns={columns}
|
||||
data={data?.data ?? []}
|
||||
keyField={(row) => row.id}
|
||||
loading={isLoading}
|
||||
emptyTitle="Nenhuma venda registrada"
|
||||
emptyDescription="As vendas feitas para este cliente aparecem aqui."
|
||||
rowActions={(row) => (
|
||||
<Button variant="ghost" size="sm" asChild>
|
||||
<Link href={`/app/vendas/${row.id}`}>Ver</Link>
|
||||
</Button>
|
||||
)}
|
||||
pagination={
|
||||
data ? { page: data.meta.page, limit: data.meta.limit, total: data.meta.total, onPageChange: setPage } : undefined
|
||||
}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,140 @@
|
||||
'use client';
|
||||
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { useMutation } from '@tanstack/react-query';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { zodResolver } from '@hookform/resolvers/zod';
|
||||
|
||||
import { createCustomer } from '@/lib/api/customers';
|
||||
import { customerSchema, type CustomerFormValues } from '@/lib/validators/customers';
|
||||
import { ApiError } from '@/lib/api/client';
|
||||
import { BR_STATES } from '@/lib/br-states';
|
||||
import { toast } from '@/lib/toast';
|
||||
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { FormField } from '@/components/ui/form-field';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
|
||||
import { Textarea } from '@/components/ui/textarea';
|
||||
|
||||
export default function NovoClientePage() {
|
||||
const router = useRouter();
|
||||
|
||||
const form = useForm<CustomerFormValues>({
|
||||
resolver: zodResolver(customerSchema),
|
||||
defaultValues: {
|
||||
razao_social: '',
|
||||
nome_fantasia: '',
|
||||
documento: '',
|
||||
email: '',
|
||||
telefone_whatsapp: '',
|
||||
endereco: '',
|
||||
cidade: '',
|
||||
uf: '',
|
||||
observacoes: '',
|
||||
},
|
||||
});
|
||||
|
||||
const mutation = useMutation({
|
||||
mutationFn: (values: CustomerFormValues) =>
|
||||
createCustomer({
|
||||
razao_social: values.razao_social,
|
||||
nome_fantasia: values.nome_fantasia || undefined,
|
||||
documento: values.documento || undefined,
|
||||
email: values.email || undefined,
|
||||
telefone_whatsapp: values.telefone_whatsapp || undefined,
|
||||
endereco: values.endereco || undefined,
|
||||
cidade: values.cidade || undefined,
|
||||
uf: values.uf || undefined,
|
||||
observacoes: values.observacoes || undefined,
|
||||
}),
|
||||
onSuccess: (customer) => {
|
||||
toast.success('Cliente cadastrado.');
|
||||
router.push(`/app/clientes/${customer.id}`);
|
||||
},
|
||||
onError: (err) => {
|
||||
// Erro de limite do plano (400) vem com mensagem de negócio clara do
|
||||
// backend — mostrado direto, sem mensagem genérica (Etapa 16, item 6).
|
||||
toast.error(err instanceof ApiError ? err.message : 'Não foi possível cadastrar o cliente.');
|
||||
},
|
||||
});
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-6">
|
||||
<div>
|
||||
<h1 className="text-xl font-semibold text-foreground">Novo cliente</h1>
|
||||
<p className="text-sm text-muted-foreground">Cadastro de cliente</p>
|
||||
</div>
|
||||
|
||||
<form
|
||||
className="flex max-w-2xl flex-col gap-6"
|
||||
onSubmit={form.handleSubmit((values) => mutation.mutate(values))}
|
||||
>
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Dados cadastrais</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="flex flex-col gap-4">
|
||||
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
|
||||
<FormField label="Razão social" error={form.formState.errors.razao_social?.message} required>
|
||||
<Input {...form.register('razao_social')} />
|
||||
</FormField>
|
||||
<FormField label="Nome fantasia" error={form.formState.errors.nome_fantasia?.message}>
|
||||
<Input {...form.register('nome_fantasia')} />
|
||||
</FormField>
|
||||
</div>
|
||||
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
|
||||
<FormField label="Documento (CPF/CNPJ)" error={form.formState.errors.documento?.message}>
|
||||
<Input placeholder="000.000.000-00" {...form.register('documento')} />
|
||||
</FormField>
|
||||
<FormField label="Telefone/WhatsApp" error={form.formState.errors.telefone_whatsapp?.message}>
|
||||
<Input {...form.register('telefone_whatsapp')} />
|
||||
</FormField>
|
||||
</div>
|
||||
<FormField label="E-mail" error={form.formState.errors.email?.message}>
|
||||
<Input type="email" {...form.register('email')} />
|
||||
</FormField>
|
||||
<FormField label="Endereço" error={form.formState.errors.endereco?.message}>
|
||||
<Input {...form.register('endereco')} />
|
||||
</FormField>
|
||||
<div className="grid grid-cols-1 gap-4 sm:grid-cols-[1fr_120px]">
|
||||
<FormField label="Cidade" error={form.formState.errors.cidade?.message}>
|
||||
<Input {...form.register('cidade')} />
|
||||
</FormField>
|
||||
<FormField label="UF" id="uf" error={form.formState.errors.uf?.message}>
|
||||
<Select
|
||||
value={form.watch('uf')}
|
||||
onValueChange={(value) => form.setValue('uf', value, { shouldValidate: true })}
|
||||
>
|
||||
<SelectTrigger id="uf" className="w-full">
|
||||
<SelectValue placeholder="UF" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{BR_STATES.map((uf) => (
|
||||
<SelectItem key={uf} value={uf}>
|
||||
{uf}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</FormField>
|
||||
</div>
|
||||
<FormField label="Observações" error={form.formState.errors.observacoes?.message}>
|
||||
<Textarea rows={3} {...form.register('observacoes')} />
|
||||
</FormField>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<div className="flex items-center gap-3">
|
||||
<Button type="submit" loading={mutation.isPending}>
|
||||
Cadastrar cliente
|
||||
</Button>
|
||||
<Button type="button" variant="outline" onClick={() => router.push('/app/clientes')}>
|
||||
Cancelar
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,145 @@
|
||||
'use client';
|
||||
|
||||
import * as React from 'react';
|
||||
import Link from 'next/link';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { Plus, Search } from 'lucide-react';
|
||||
|
||||
import { listCustomers, type Customer } from '@/lib/api/customers';
|
||||
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { DataTable, type DataTableColumn } from '@/components/ui/data-table';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
|
||||
|
||||
const ATIVO_OPTIONS = [
|
||||
{ value: 'todos', label: 'Ativos e inativos' },
|
||||
{ value: 'true', label: 'Somente ativos' },
|
||||
{ value: 'false', label: 'Somente inativos' },
|
||||
];
|
||||
|
||||
const LIMIT = 20;
|
||||
|
||||
export default function ClientesPage() {
|
||||
const router = useRouter();
|
||||
const [busca, setBusca] = React.useState('');
|
||||
const [ativo, setAtivo] = React.useState('true');
|
||||
const [page, setPage] = React.useState(1);
|
||||
|
||||
const { data, isLoading } = useQuery({
|
||||
queryKey: ['tenant', 'customers', { busca, ativo, page }],
|
||||
queryFn: () =>
|
||||
listCustomers({
|
||||
busca: busca || undefined,
|
||||
ativo: ativo === 'todos' ? undefined : ativo === 'true',
|
||||
page,
|
||||
limit: LIMIT,
|
||||
}),
|
||||
placeholderData: (prev) => prev,
|
||||
});
|
||||
|
||||
const columns: DataTableColumn<Customer>[] = [
|
||||
{
|
||||
id: 'nome',
|
||||
header: 'Cliente',
|
||||
primary: true,
|
||||
cell: (row) => (
|
||||
<div className="flex flex-col">
|
||||
<span className="font-medium text-foreground">{row.nome_fantasia || row.razao_social}</span>
|
||||
{row.documento && <span className="text-xs text-muted-foreground">{row.documento}</span>}
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
id: 'contato',
|
||||
header: 'Contato',
|
||||
cell: (row) => (
|
||||
<div className="flex flex-col">
|
||||
{row.telefone_whatsapp && <span>{row.telefone_whatsapp}</span>}
|
||||
{row.email && <span className="text-xs text-muted-foreground">{row.email}</span>}
|
||||
{!row.telefone_whatsapp && !row.email && '—'}
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
id: 'status',
|
||||
header: 'Status',
|
||||
primary: true,
|
||||
cell: (row) => <Badge variant={row.ativo ? 'default' : 'outline'}>{row.ativo ? 'Ativo' : 'Inativo'}</Badge>,
|
||||
},
|
||||
];
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-6">
|
||||
<div className="flex flex-wrap items-center justify-between gap-4">
|
||||
<div>
|
||||
<h1 className="text-xl font-semibold text-foreground">Clientes</h1>
|
||||
<p className="text-sm text-muted-foreground">Base de clientes do seu negócio</p>
|
||||
</div>
|
||||
<Button asChild>
|
||||
<Link href="/app/clientes/novo">
|
||||
<Plus /> Novo cliente
|
||||
</Link>
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col gap-3 sm:flex-row sm:items-center">
|
||||
<div className="relative flex-1 sm:max-w-xs">
|
||||
<Search className="pointer-events-none absolute top-1/2 left-3 size-4 -translate-y-1/2 text-neutral-500" />
|
||||
<Input
|
||||
placeholder="Buscar por nome ou documento..."
|
||||
className="pl-9"
|
||||
value={busca}
|
||||
onChange={(e) => {
|
||||
setBusca(e.target.value);
|
||||
setPage(1);
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
<Select
|
||||
value={ativo}
|
||||
onValueChange={(value) => {
|
||||
setAtivo(value);
|
||||
setPage(1);
|
||||
}}
|
||||
>
|
||||
<SelectTrigger className="w-full sm:w-52" aria-label="Filtrar por status">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{ATIVO_OPTIONS.map((opt) => (
|
||||
<SelectItem key={opt.value} value={opt.value}>
|
||||
{opt.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
<DataTable
|
||||
columns={columns}
|
||||
data={data?.data ?? []}
|
||||
keyField={(row) => row.id}
|
||||
loading={isLoading}
|
||||
emptyTitle="Nenhum cliente encontrado"
|
||||
emptyDescription="Ajuste os filtros ou cadastre um novo cliente."
|
||||
emptyAction={
|
||||
<Button size="sm" asChild>
|
||||
<Link href="/app/clientes/novo">Novo cliente</Link>
|
||||
</Button>
|
||||
}
|
||||
onRowClick={(row) => router.push(`/app/clientes/${row.id}`)}
|
||||
rowActions={(row) => (
|
||||
<Button variant="ghost" size="sm" asChild>
|
||||
<Link href={`/app/clientes/${row.id}`}>Ver</Link>
|
||||
</Button>
|
||||
)}
|
||||
pagination={
|
||||
data ? { page: data.meta.page, limit: data.meta.limit, total: data.meta.total, onPageChange: setPage } : undefined
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,181 @@
|
||||
'use client';
|
||||
|
||||
import * as React from 'react';
|
||||
import Link from 'next/link';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { Area, AreaChart, CartesianGrid, ResponsiveContainer, Tooltip, XAxis, YAxis } from 'recharts';
|
||||
import { ArrowRight, CircleDollarSign, ShoppingCart, TriangleAlert } from 'lucide-react';
|
||||
|
||||
import {
|
||||
getFinanceiro,
|
||||
getResumoMensal,
|
||||
getResumoSemanal,
|
||||
type ResumoMensalRow,
|
||||
type ResumoSemanalRow,
|
||||
} from '@/lib/api/tenant-dashboard';
|
||||
import { formatCurrency, formatDate } from '@/lib/format';
|
||||
import { StatCard } from '@/components/domain/stat-card';
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { Skeleton } from '@/components/ui/skeleton';
|
||||
import { EmptyState } from '@/components/ui/empty-state';
|
||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
|
||||
|
||||
function useChartColor() {
|
||||
const [color, setColor] = React.useState('#2563eb');
|
||||
React.useEffect(() => {
|
||||
const value = getComputedStyle(document.documentElement).getPropertyValue('--color-primary').trim();
|
||||
if (value) setColor(value);
|
||||
}, []);
|
||||
return color;
|
||||
}
|
||||
|
||||
function ResumoChart({ periodo }: { periodo: 'semanal' | 'mensal' }) {
|
||||
const color = useChartColor();
|
||||
const { data, isLoading } = useQuery({
|
||||
queryKey: ['tenant', 'dashboard', 'resumo', periodo],
|
||||
queryFn: (): Promise<(ResumoSemanalRow | ResumoMensalRow)[]> =>
|
||||
periodo === 'semanal' ? getResumoSemanal() : getResumoMensal(),
|
||||
});
|
||||
|
||||
const chartData = (data ?? []).map((row) => ({
|
||||
label: formatDate('semana' in row ? row.semana : row.mes),
|
||||
total_vendido: row.total_vendido,
|
||||
qtd_vendas: row.qtd_vendas,
|
||||
}));
|
||||
|
||||
if (isLoading) return <Skeleton className="h-64 w-full" />;
|
||||
if (chartData.length === 0) {
|
||||
return <EmptyState title="Sem vendas no período" description="Ainda não há dados suficientes para o gráfico." />;
|
||||
}
|
||||
|
||||
return (
|
||||
<ResponsiveContainer width="100%" height={260}>
|
||||
<AreaChart data={chartData} margin={{ left: 8, right: 8, top: 8, bottom: 0 }}>
|
||||
<defs>
|
||||
<linearGradient id="resumoVendasFill" x1="0" y1="0" x2="0" y2="1">
|
||||
<stop offset="5%" stopColor={color} stopOpacity={0.35} />
|
||||
<stop offset="95%" stopColor={color} stopOpacity={0.02} />
|
||||
</linearGradient>
|
||||
</defs>
|
||||
<CartesianGrid strokeDasharray="3 3" vertical={false} className="stroke-border" />
|
||||
<XAxis dataKey="label" tickLine={false} axisLine={false} className="text-xs fill-muted-foreground" />
|
||||
<YAxis
|
||||
tickLine={false}
|
||||
axisLine={false}
|
||||
width={72}
|
||||
className="text-xs fill-muted-foreground"
|
||||
tickFormatter={(value: number) => formatCurrency(value)}
|
||||
/>
|
||||
<Tooltip
|
||||
formatter={(value, name) =>
|
||||
name === 'total_vendido' ? [formatCurrency(Number(value)), 'Total vendido'] : [String(value), 'Vendas']
|
||||
}
|
||||
contentStyle={{ borderRadius: 8, borderColor: 'var(--border)' }}
|
||||
/>
|
||||
<Area type="monotone" dataKey="total_vendido" stroke={color} strokeWidth={2} fill="url(#resumoVendasFill)" />
|
||||
</AreaChart>
|
||||
</ResponsiveContainer>
|
||||
);
|
||||
}
|
||||
|
||||
export default function TenantDashboardPage() {
|
||||
const { data: financeiro, isLoading: loadingFinanceiro } = useQuery({
|
||||
queryKey: ['tenant', 'dashboard', 'financeiro'],
|
||||
queryFn: () => getFinanceiro(8),
|
||||
});
|
||||
|
||||
const totalAtrasado = Number(financeiro?.total_atrasado ?? 0);
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-6">
|
||||
<div>
|
||||
<h1 className="text-xl font-semibold text-foreground">Dashboard</h1>
|
||||
<p className="text-sm text-muted-foreground">Visão geral das suas vendas</p>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 gap-4 sm:grid-cols-3">
|
||||
<StatCard
|
||||
label="Recebido no mês"
|
||||
value={formatCurrency(financeiro?.total_recebido_mes)}
|
||||
icon={CircleDollarSign}
|
||||
tone="success"
|
||||
loading={loadingFinanceiro}
|
||||
/>
|
||||
<StatCard
|
||||
label="A receber"
|
||||
value={formatCurrency(financeiro?.total_a_receber)}
|
||||
icon={ShoppingCart}
|
||||
tone="warning"
|
||||
loading={loadingFinanceiro}
|
||||
/>
|
||||
<StatCard
|
||||
label="Atrasado"
|
||||
value={formatCurrency(financeiro?.total_atrasado)}
|
||||
icon={TriangleAlert}
|
||||
tone={totalAtrasado > 0 ? 'danger' : 'default'}
|
||||
loading={loadingFinanceiro}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Evolução de vendas</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<Tabs defaultValue="semanal">
|
||||
<TabsList>
|
||||
<TabsTrigger value="semanal">Semanal</TabsTrigger>
|
||||
<TabsTrigger value="mensal">Mensal</TabsTrigger>
|
||||
</TabsList>
|
||||
<TabsContent value="semanal" className="pt-4">
|
||||
<ResumoChart periodo="semanal" />
|
||||
</TabsContent>
|
||||
<TabsContent value="mensal" className="pt-4">
|
||||
<ResumoChart periodo="mensal" />
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardHeader className="flex flex-row items-center justify-between gap-2 space-y-0">
|
||||
<CardTitle>Próximas parcelas a vencer</CardTitle>
|
||||
<Link
|
||||
href="/app/recebimentos"
|
||||
className="flex items-center gap-1 text-sm text-primary-on-light hover:underline"
|
||||
>
|
||||
Ver todos <ArrowRight className="size-3.5" />
|
||||
</Link>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{loadingFinanceiro ? (
|
||||
<div className="flex flex-col gap-2">
|
||||
{Array.from({ length: 4 }).map((_, i) => (
|
||||
<Skeleton key={i} className="h-10 w-full" />
|
||||
))}
|
||||
</div>
|
||||
) : financeiro && financeiro.proximas_parcelas.length > 0 ? (
|
||||
<ul className="flex flex-col divide-y divide-border">
|
||||
{financeiro.proximas_parcelas.map((parcela) => (
|
||||
<li key={parcela.id} className="flex items-center justify-between gap-4 py-2.5 text-sm">
|
||||
<div className="min-w-0">
|
||||
<p className="truncate font-medium text-foreground">{parcela.sale.customer.razao_social}</p>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Venda #{parcela.sale.numero_venda} · Parcela {parcela.numero_parcela}
|
||||
</p>
|
||||
</div>
|
||||
<div className="text-right">
|
||||
<p className="font-medium tabular-nums text-foreground">{formatCurrency(parcela.valor)}</p>
|
||||
<p className="text-xs text-muted-foreground">{formatDate(parcela.vencimento)}</p>
|
||||
</div>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
) : (
|
||||
<EmptyState title="Nenhuma parcela pendente" description="Não há parcelas a vencer no momento." />
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,215 @@
|
||||
'use client';
|
||||
|
||||
import * as React from 'react';
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { zodResolver } from '@hookform/resolvers/zod';
|
||||
import { Send } from 'lucide-react';
|
||||
|
||||
import { getTenantEmailConfig, testarEnvioEmail, updateTenantEmailConfig } from '@/lib/api/email-config';
|
||||
import {
|
||||
tenantEmailConfigSchema,
|
||||
testarEnvioEmailSchema,
|
||||
type TenantEmailConfigFormValues,
|
||||
type TestarEnvioEmailFormValues,
|
||||
} from '@/lib/validators/email-config';
|
||||
import { ApiError } from '@/lib/api/client';
|
||||
import { toast } from '@/lib/toast';
|
||||
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { FormField } from '@/components/ui/form-field';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
|
||||
import { Skeleton } from '@/components/ui/skeleton';
|
||||
|
||||
const USAR_PADRAO_OPTIONS = [
|
||||
{ value: 'padrao', label: 'Usar configuração padrão da plataforma' },
|
||||
{ value: 'proprio', label: 'Usar meu próprio SMTP' },
|
||||
] as const;
|
||||
|
||||
export default function EmailConfigPage() {
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
const { data: config, isLoading } = useQuery({
|
||||
queryKey: ['tenant', 'email-config'],
|
||||
queryFn: getTenantEmailConfig,
|
||||
});
|
||||
|
||||
const form = useForm<TenantEmailConfigFormValues>({
|
||||
resolver: zodResolver(tenantEmailConfigSchema),
|
||||
values: config
|
||||
? {
|
||||
usar_config_padrao: config.usar_config_padrao,
|
||||
smtp_host: config.smtp_host ?? '',
|
||||
smtp_porta: config.smtp_porta,
|
||||
smtp_usuario: config.smtp_usuario ?? '',
|
||||
smtp_senha: '',
|
||||
email_remetente: config.email_remetente ?? '',
|
||||
}
|
||||
: undefined,
|
||||
});
|
||||
|
||||
const usarPadrao = form.watch('usar_config_padrao');
|
||||
|
||||
const saveMutation = useMutation({
|
||||
mutationFn: (values: TenantEmailConfigFormValues) => updateTenantEmailConfig(values),
|
||||
onSuccess: (result) => {
|
||||
queryClient.setQueryData(['tenant', 'email-config'], result);
|
||||
toast.success('Configuração de e-mail atualizada.');
|
||||
},
|
||||
onError: (err) => {
|
||||
toast.error(err instanceof ApiError ? err.message : 'Não foi possível salvar a configuração.');
|
||||
},
|
||||
});
|
||||
|
||||
const testForm = useForm<TestarEnvioEmailFormValues>({
|
||||
resolver: zodResolver(testarEnvioEmailSchema),
|
||||
defaultValues: { destinatario: '' },
|
||||
});
|
||||
|
||||
const testMutation = useMutation({
|
||||
mutationFn: (values: TestarEnvioEmailFormValues) => testarEnvioEmail(values.destinatario),
|
||||
onSuccess: (result) => {
|
||||
// `DispatchResult` sempre responde HTTP 200 — falha de envio vem como
|
||||
// `{ sucesso: false, erro }`, não como erro HTTP (ver `lib/api/email-config.ts`).
|
||||
if (result.sucesso) {
|
||||
toast.success('E-mail de teste enviado com sucesso.');
|
||||
} else {
|
||||
toast.error(result.erro ?? 'Falha ao enviar o e-mail de teste.');
|
||||
}
|
||||
},
|
||||
onError: (err) => {
|
||||
toast.error(err instanceof ApiError ? err.message : 'Falha ao enviar o e-mail de teste.');
|
||||
},
|
||||
});
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-6">
|
||||
<div>
|
||||
<h1 className="text-xl font-semibold text-foreground">Configuração de e-mail</h1>
|
||||
<p className="text-sm text-muted-foreground">SMTP usado para envio de alertas por e-mail</p>
|
||||
</div>
|
||||
|
||||
<Card className="max-w-xl">
|
||||
<CardHeader>
|
||||
<CardTitle>Servidor SMTP</CardTitle>
|
||||
<CardDescription>
|
||||
Ao desativar o padrão da plataforma, os campos de SMTP próprio ficam obrigatórios.
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{isLoading ? (
|
||||
<div className="flex flex-col gap-4">
|
||||
<Skeleton className="h-11 w-full" />
|
||||
<Skeleton className="h-11 w-full" />
|
||||
</div>
|
||||
) : (
|
||||
<form
|
||||
className="flex flex-col gap-4"
|
||||
onSubmit={form.handleSubmit((values) => saveMutation.mutate(values))}
|
||||
>
|
||||
<FormField label="Origem do envio" id="usar_config_padrao">
|
||||
<Select
|
||||
value={usarPadrao ? 'padrao' : 'proprio'}
|
||||
onValueChange={(value) =>
|
||||
form.setValue('usar_config_padrao', value === 'padrao', { shouldValidate: true })
|
||||
}
|
||||
>
|
||||
<SelectTrigger id="usar_config_padrao" className="w-full">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{USAR_PADRAO_OPTIONS.map((opt) => (
|
||||
<SelectItem key={opt.value} value={opt.value}>
|
||||
{opt.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</FormField>
|
||||
|
||||
{!usarPadrao && (
|
||||
<>
|
||||
<div className="grid grid-cols-1 gap-4 sm:grid-cols-[1fr_140px]">
|
||||
<FormField
|
||||
label="Host SMTP"
|
||||
error={form.formState.errors.smtp_host?.message}
|
||||
required
|
||||
>
|
||||
<Input placeholder="smtp.exemplo.com" {...form.register('smtp_host')} />
|
||||
</FormField>
|
||||
<FormField
|
||||
label="Porta"
|
||||
error={form.formState.errors.smtp_porta?.message}
|
||||
required
|
||||
>
|
||||
<Input
|
||||
type="number"
|
||||
{...form.register('smtp_porta', {
|
||||
setValueAs: (v) => (v === '' ? undefined : Number(v)),
|
||||
})}
|
||||
/>
|
||||
</FormField>
|
||||
</div>
|
||||
<FormField
|
||||
label="Usuário SMTP"
|
||||
error={form.formState.errors.smtp_usuario?.message}
|
||||
required
|
||||
>
|
||||
<Input {...form.register('smtp_usuario')} />
|
||||
</FormField>
|
||||
<FormField
|
||||
label="Senha SMTP"
|
||||
error={form.formState.errors.smtp_senha?.message}
|
||||
helpText="Por segurança, o valor atual nunca é pré-preenchido — é preciso reinformar a senha a cada alteração"
|
||||
required
|
||||
>
|
||||
<Input type="password" autoComplete="off" {...form.register('smtp_senha')} />
|
||||
</FormField>
|
||||
<FormField
|
||||
label="E-mail remetente"
|
||||
error={form.formState.errors.email_remetente?.message}
|
||||
required
|
||||
>
|
||||
<Input type="email" {...form.register('email_remetente')} />
|
||||
</FormField>
|
||||
</>
|
||||
)}
|
||||
|
||||
<div>
|
||||
<Button type="submit" loading={saveMutation.isPending}>
|
||||
Salvar
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card className="max-w-xl">
|
||||
<CardHeader>
|
||||
<CardTitle>Testar envio</CardTitle>
|
||||
<CardDescription>Envia um e-mail de teste usando a configuração atual.</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<form
|
||||
className="flex flex-col gap-4 sm:flex-row sm:items-end"
|
||||
onSubmit={testForm.handleSubmit((values) => testMutation.mutate(values))}
|
||||
>
|
||||
<FormField
|
||||
className="flex-1"
|
||||
label="E-mail de destino"
|
||||
error={testForm.formState.errors.destinatario?.message}
|
||||
>
|
||||
<Input type="email" {...testForm.register('destinatario')} />
|
||||
</FormField>
|
||||
<Button type="submit" variant="outline" loading={testMutation.isPending}>
|
||||
<Send /> Enviar teste
|
||||
</Button>
|
||||
</form>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,359 @@
|
||||
'use client';
|
||||
|
||||
import * as React from 'react';
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { zodResolver } from '@hookform/resolvers/zod';
|
||||
import { Copy, Plus } from 'lucide-react';
|
||||
|
||||
import {
|
||||
EQUIPE_ROLES,
|
||||
EQUIPE_ROLE_LABEL,
|
||||
createEquipeUser,
|
||||
listEquipe,
|
||||
updateEquipeUser,
|
||||
type EquipeUser,
|
||||
type EquipeUserCreated,
|
||||
} from '@/lib/api/equipe';
|
||||
import {
|
||||
createEquipeUserSchema,
|
||||
updateEquipeRoleSchema,
|
||||
type CreateEquipeUserFormValues,
|
||||
type UpdateEquipeRoleFormValues,
|
||||
} from '@/lib/validators/equipe';
|
||||
import { ApiError } from '@/lib/api/client';
|
||||
import { useAuth } from '@/lib/auth/auth-context';
|
||||
import { formatDateTime } from '@/lib/format';
|
||||
import { toast } from '@/lib/toast';
|
||||
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { DataTable, type DataTableColumn } from '@/components/ui/data-table';
|
||||
import { FormField } from '@/components/ui/form-field';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { ResponsiveDialog } from '@/components/ui/responsive-dialog';
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
|
||||
import { Separator } from '@/components/ui/separator';
|
||||
import { ConfirmDialog } from '@/components/domain/confirm-dialog';
|
||||
|
||||
export default function EquipePage() {
|
||||
const queryClient = useQueryClient();
|
||||
const { user } = useAuth();
|
||||
const meuId = user?.sub;
|
||||
|
||||
const { data: equipe, isLoading } = useQuery({
|
||||
queryKey: ['tenant', 'equipe'],
|
||||
queryFn: listEquipe,
|
||||
});
|
||||
|
||||
const [formOpen, setFormOpen] = React.useState(false);
|
||||
const [created, setCreated] = React.useState<EquipeUserCreated | null>(null);
|
||||
const [changingRole, setChangingRole] = React.useState<EquipeUser | null>(null);
|
||||
const [togglingAtivo, setTogglingAtivo] = React.useState<EquipeUser | null>(null);
|
||||
|
||||
const createForm = useForm<CreateEquipeUserFormValues>({
|
||||
resolver: zodResolver(createEquipeUserSchema),
|
||||
defaultValues: { nome: '', email: '', role: 'vendedor', senha: '' },
|
||||
});
|
||||
|
||||
function openCreate() {
|
||||
createForm.reset({ nome: '', email: '', role: 'vendedor', senha: '' });
|
||||
setFormOpen(true);
|
||||
}
|
||||
|
||||
const createMutation = useMutation({
|
||||
mutationFn: (values: CreateEquipeUserFormValues) =>
|
||||
createEquipeUser({
|
||||
nome: values.nome,
|
||||
email: values.email,
|
||||
role: values.role,
|
||||
senha: values.senha || undefined,
|
||||
}),
|
||||
onSuccess: (result) => {
|
||||
queryClient.invalidateQueries({ queryKey: ['tenant', 'equipe'] });
|
||||
setFormOpen(false);
|
||||
setCreated(result);
|
||||
},
|
||||
onError: (err) => {
|
||||
toast.error(err instanceof ApiError ? err.message : 'Não foi possível criar o usuário.');
|
||||
},
|
||||
});
|
||||
|
||||
async function copySenha() {
|
||||
if (!created) return;
|
||||
try {
|
||||
await navigator.clipboard.writeText(created.senha_provisoria);
|
||||
toast.success('Senha copiada.');
|
||||
} catch {
|
||||
toast.error('Não foi possível copiar automaticamente — selecione e copie manualmente.');
|
||||
}
|
||||
}
|
||||
|
||||
const roleForm = useForm<UpdateEquipeRoleFormValues>({
|
||||
resolver: zodResolver(updateEquipeRoleSchema),
|
||||
});
|
||||
|
||||
React.useEffect(() => {
|
||||
if (changingRole) roleForm.reset({ role: changingRole.role });
|
||||
}, [changingRole, roleForm]);
|
||||
|
||||
const roleMutation = useMutation({
|
||||
mutationFn: (values: UpdateEquipeRoleFormValues) =>
|
||||
updateEquipeUser(changingRole!.id, { role: values.role as EquipeUser['role'] }),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['tenant', 'equipe'] });
|
||||
toast.success('Papel atualizado.');
|
||||
setChangingRole(null);
|
||||
},
|
||||
onError: (err) => {
|
||||
toast.error(err instanceof ApiError ? err.message : 'Não foi possível alterar o papel.');
|
||||
},
|
||||
});
|
||||
|
||||
const toggleAtivoMutation = useMutation({
|
||||
mutationFn: (target: EquipeUser) => updateEquipeUser(target.id, { ativo: !target.ativo }),
|
||||
onSuccess: (_, target) => {
|
||||
queryClient.invalidateQueries({ queryKey: ['tenant', 'equipe'] });
|
||||
toast.success(target.ativo ? 'Usuário desativado.' : 'Usuário reativado.');
|
||||
setTogglingAtivo(null);
|
||||
},
|
||||
onError: (err) => {
|
||||
toast.error(err instanceof ApiError ? err.message : 'Não foi possível atualizar o usuário.');
|
||||
setTogglingAtivo(null);
|
||||
},
|
||||
});
|
||||
|
||||
const columns: DataTableColumn<EquipeUser>[] = [
|
||||
{ id: 'nome', header: 'Nome', primary: true, cell: (row) => row.nome },
|
||||
{ id: 'email', header: 'E-mail', primary: true, cell: (row) => row.email },
|
||||
{ id: 'role', header: 'Papel', cell: (row) => EQUIPE_ROLE_LABEL[row.role] },
|
||||
{
|
||||
id: 'ativo',
|
||||
header: 'Status',
|
||||
cell: (row) => (
|
||||
<Badge variant={row.ativo ? 'default' : 'outline'}>{row.ativo ? 'Ativo' : 'Inativo'}</Badge>
|
||||
),
|
||||
},
|
||||
{
|
||||
id: 'criado_em',
|
||||
header: 'Criado em',
|
||||
hideOnMobileCard: true,
|
||||
cell: (row) => formatDateTime(row.criado_em),
|
||||
},
|
||||
];
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-6">
|
||||
<div className="flex flex-wrap items-center justify-between gap-4">
|
||||
<div>
|
||||
<h1 className="text-xl font-semibold text-foreground">Equipe</h1>
|
||||
<p className="text-sm text-muted-foreground">Usuários com acesso ao painel deste tenant</p>
|
||||
</div>
|
||||
<Button onClick={openCreate}>
|
||||
<Plus /> Nova pessoa
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<DataTable
|
||||
columns={columns}
|
||||
data={equipe ?? []}
|
||||
keyField={(row) => row.id}
|
||||
loading={isLoading}
|
||||
emptyTitle="Nenhum usuário cadastrado"
|
||||
emptyAction={
|
||||
<Button size="sm" onClick={openCreate}>
|
||||
Nova pessoa
|
||||
</Button>
|
||||
}
|
||||
rowActions={(row) => {
|
||||
const isSelf = row.id === meuId;
|
||||
return (
|
||||
<>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
disabled={isSelf}
|
||||
title={isSelf ? 'Não é possível alterar o próprio papel' : undefined}
|
||||
onClick={() => setChangingRole(row)}
|
||||
>
|
||||
Alterar papel
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
disabled={isSelf}
|
||||
title={isSelf ? 'Não é possível desativar o próprio usuário' : undefined}
|
||||
onClick={() => setTogglingAtivo(row)}
|
||||
>
|
||||
{row.ativo ? 'Desativar' : 'Reativar'}
|
||||
</Button>
|
||||
</>
|
||||
);
|
||||
}}
|
||||
/>
|
||||
|
||||
<ResponsiveDialog
|
||||
open={formOpen}
|
||||
onOpenChange={setFormOpen}
|
||||
title="Nova pessoa"
|
||||
description="Cria um novo acesso ao painel deste tenant."
|
||||
footer={
|
||||
<>
|
||||
<Button variant="outline" onClick={() => setFormOpen(false)}>
|
||||
Cancelar
|
||||
</Button>
|
||||
<Button
|
||||
loading={createMutation.isPending}
|
||||
onClick={createForm.handleSubmit((values) => createMutation.mutate(values))}
|
||||
>
|
||||
Criar
|
||||
</Button>
|
||||
</>
|
||||
}
|
||||
>
|
||||
<form
|
||||
className="flex flex-col gap-4 px-4 pb-4 sm:px-0 sm:pb-0"
|
||||
onSubmit={createForm.handleSubmit((values) => createMutation.mutate(values))}
|
||||
>
|
||||
<FormField label="Nome" error={createForm.formState.errors.nome?.message} required>
|
||||
<Input {...createForm.register('nome')} />
|
||||
</FormField>
|
||||
<FormField label="E-mail" error={createForm.formState.errors.email?.message} required>
|
||||
<Input type="email" {...createForm.register('email')} />
|
||||
</FormField>
|
||||
<FormField label="Papel" id="role" error={createForm.formState.errors.role?.message} required>
|
||||
<Select
|
||||
value={createForm.watch('role')}
|
||||
onValueChange={(value) =>
|
||||
createForm.setValue('role', value as CreateEquipeUserFormValues['role'], {
|
||||
shouldValidate: true,
|
||||
})
|
||||
}
|
||||
>
|
||||
<SelectTrigger id="role" className="w-full">
|
||||
<SelectValue placeholder="Selecione um papel" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{EQUIPE_ROLES.map((role) => (
|
||||
<SelectItem key={role} value={role}>
|
||||
{EQUIPE_ROLE_LABEL[role]}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</FormField>
|
||||
<FormField
|
||||
label="Senha provisória"
|
||||
helpText="Deixe em branco para o sistema gerar uma senha automaticamente"
|
||||
error={createForm.formState.errors.senha?.message}
|
||||
>
|
||||
<Input type="text" autoComplete="off" {...createForm.register('senha')} />
|
||||
</FormField>
|
||||
</form>
|
||||
</ResponsiveDialog>
|
||||
|
||||
<ResponsiveDialog
|
||||
open={created !== null}
|
||||
onOpenChange={(open) => !open && setCreated(null)}
|
||||
title="Usuário criado com sucesso"
|
||||
description="Copie e repasse a senha provisória à pessoa agora — ela não será mostrada novamente."
|
||||
footer={
|
||||
<Button className="w-full" onClick={() => setCreated(null)}>
|
||||
Concluir
|
||||
</Button>
|
||||
}
|
||||
>
|
||||
{created && (
|
||||
<div className="flex flex-col gap-4 px-4 pb-4 sm:px-0 sm:pb-0">
|
||||
<div>
|
||||
<p className="text-sm text-muted-foreground">Usuário</p>
|
||||
<p className="font-medium text-foreground">
|
||||
{created.nome} · {created.email} · {EQUIPE_ROLE_LABEL[created.role]}
|
||||
</p>
|
||||
</div>
|
||||
<Separator />
|
||||
<div className="flex flex-col gap-2">
|
||||
<p className="text-sm font-medium text-foreground">Senha provisória</p>
|
||||
<div className="flex items-center gap-2 rounded-lg border border-warning/30 bg-warning/10 p-3">
|
||||
<code className="flex-1 font-mono text-base font-semibold text-foreground select-all">
|
||||
{created.senha_provisoria}
|
||||
</code>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
onClick={copySenha}
|
||||
aria-label="Copiar senha"
|
||||
>
|
||||
<Copy className="size-4" />
|
||||
</Button>
|
||||
</div>
|
||||
<p className="text-xs text-warning">
|
||||
Atenção: esta senha não fica salva em texto puro em nenhum lugar e não será exibida
|
||||
novamente. Copie e repasse à pessoa agora.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</ResponsiveDialog>
|
||||
|
||||
<ResponsiveDialog
|
||||
open={changingRole !== null}
|
||||
onOpenChange={(open) => !open && setChangingRole(null)}
|
||||
title={`Alterar papel — ${changingRole?.nome ?? ''}`}
|
||||
footer={
|
||||
<>
|
||||
<Button variant="outline" onClick={() => setChangingRole(null)}>
|
||||
Cancelar
|
||||
</Button>
|
||||
<Button
|
||||
loading={roleMutation.isPending}
|
||||
onClick={roleForm.handleSubmit((values) => roleMutation.mutate(values))}
|
||||
>
|
||||
Salvar
|
||||
</Button>
|
||||
</>
|
||||
}
|
||||
>
|
||||
<div className="flex flex-col gap-4 px-4 pb-4 sm:px-0 sm:pb-0">
|
||||
<FormField label="Papel" id="changing-role">
|
||||
<Select
|
||||
value={roleForm.watch('role')}
|
||||
onValueChange={(value) =>
|
||||
roleForm.setValue('role', value as UpdateEquipeRoleFormValues['role'], {
|
||||
shouldValidate: true,
|
||||
})
|
||||
}
|
||||
>
|
||||
<SelectTrigger id="changing-role" className="w-full">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{EQUIPE_ROLES.map((role) => (
|
||||
<SelectItem key={role} value={role}>
|
||||
{EQUIPE_ROLE_LABEL[role]}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</FormField>
|
||||
</div>
|
||||
</ResponsiveDialog>
|
||||
|
||||
<ConfirmDialog
|
||||
open={togglingAtivo !== null}
|
||||
onOpenChange={(open) => !open && setTogglingAtivo(null)}
|
||||
title={togglingAtivo?.ativo ? `Desativar ${togglingAtivo.nome}?` : `Reativar ${togglingAtivo?.nome}?`}
|
||||
description={
|
||||
togglingAtivo?.ativo
|
||||
? 'A pessoa perde acesso imediatamente — as sessões abertas são revogadas.'
|
||||
: 'A pessoa volta a ter acesso ao painel com as mesmas credenciais.'
|
||||
}
|
||||
confirmLabel={togglingAtivo?.ativo ? 'Desativar' : 'Reativar'}
|
||||
destructive={togglingAtivo?.ativo}
|
||||
loading={toggleAtivoMutation.isPending}
|
||||
onConfirm={() => togglingAtivo && toggleAtivoMutation.mutate(togglingAtivo)}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
import { cookies } from 'next/headers';
|
||||
|
||||
import { TenantShell } from '@/components/layout/tenant-shell';
|
||||
import { SIDEBAR_COOKIE, readSidebarCollapsedCookie } from '@/lib/layout/sidebar-cookie';
|
||||
|
||||
export default async function TenantLayout({ children }: { children: React.ReactNode }) {
|
||||
const cookieStore = await cookies();
|
||||
const collapsed = readSidebarCollapsedCookie(cookieStore.get(SIDEBAR_COOKIE)?.value);
|
||||
|
||||
return <TenantShell initialCollapsed={collapsed}>{children}</TenantShell>;
|
||||
}
|
||||
@@ -0,0 +1,332 @@
|
||||
'use client';
|
||||
|
||||
import * as React from 'react';
|
||||
import Image from 'next/image';
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { zodResolver } from '@hookform/resolvers/zod';
|
||||
import { Trash2, Upload } from 'lucide-react';
|
||||
|
||||
import {
|
||||
getTenantProfile,
|
||||
removeTenantLogo,
|
||||
updateTenantCor,
|
||||
updateTenantProfile,
|
||||
uploadTenantLogo,
|
||||
} from '@/lib/api/tenant-profile';
|
||||
import {
|
||||
updateTenantCorSchema,
|
||||
updateTenantProfileSchema,
|
||||
type UpdateTenantCorFormValues,
|
||||
type UpdateTenantProfileFormValues,
|
||||
} from '@/lib/validators/tenant-profile';
|
||||
import { ApiError } from '@/lib/api/client';
|
||||
import { resolveAssetUrl } from '@/lib/api/asset-url';
|
||||
import { ensureAccessibleTextColor } from '@/lib/theme/contrast';
|
||||
import { useTenantTheme } from '@/lib/theme/theme-provider';
|
||||
import { toast } from '@/lib/toast';
|
||||
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { ConfirmDialog } from '@/components/domain/confirm-dialog';
|
||||
import { FormField } from '@/components/ui/form-field';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Skeleton } from '@/components/ui/skeleton';
|
||||
|
||||
const TAMANHO_MAXIMO_LOGO_BYTES = 2 * 1024 * 1024;
|
||||
const TIPOS_LOGO_ACEITOS = ['image/png', 'image/jpeg', 'image/svg+xml'];
|
||||
|
||||
export default function PerfilPage() {
|
||||
const queryClient = useQueryClient();
|
||||
const { applyThemeUpdate } = useTenantTheme();
|
||||
|
||||
const { data: perfil, isLoading } = useQuery({
|
||||
queryKey: ['tenant', 'perfil'],
|
||||
queryFn: getTenantProfile,
|
||||
});
|
||||
|
||||
const dadosForm = useForm<UpdateTenantProfileFormValues>({
|
||||
resolver: zodResolver(updateTenantProfileSchema),
|
||||
values: perfil
|
||||
? { nome_fantasia: perfil.nome_fantasia ?? '', razao_social: perfil.razao_social ?? '' }
|
||||
: undefined,
|
||||
});
|
||||
|
||||
const dadosMutation = useMutation({
|
||||
mutationFn: (values: UpdateTenantProfileFormValues) => updateTenantProfile(values),
|
||||
onSuccess: (result) => {
|
||||
queryClient.setQueryData(['tenant', 'perfil'], result);
|
||||
applyThemeUpdate({ nome: result.nome_fantasia ?? result.razao_social ?? undefined });
|
||||
toast.success('Dados da empresa atualizados.');
|
||||
},
|
||||
onError: (err) => {
|
||||
toast.error(err instanceof ApiError ? err.message : 'Não foi possível salvar os dados.');
|
||||
},
|
||||
});
|
||||
|
||||
// --- Logo ---
|
||||
const fileInputRef = React.useRef<HTMLInputElement | null>(null);
|
||||
const [previewUrl, setPreviewUrl] = React.useState<string | null>(null);
|
||||
const [removingLogo, setRemovingLogo] = React.useState(false);
|
||||
|
||||
const uploadMutation = useMutation({
|
||||
mutationFn: (file: File) => uploadTenantLogo(file),
|
||||
onSuccess: (result) => {
|
||||
queryClient.setQueryData(['tenant', 'perfil'], (prev: typeof perfil) =>
|
||||
prev ? { ...prev, logo_url: result.logo_url } : prev,
|
||||
);
|
||||
applyThemeUpdate({ logoUrl: resolveAssetUrl(result.logo_url) });
|
||||
toast.success('Logo atualizada.');
|
||||
},
|
||||
onError: (err) => {
|
||||
toast.error(err instanceof ApiError ? err.message : 'Não foi possível enviar a logo.');
|
||||
},
|
||||
onSettled: () => {
|
||||
setPreviewUrl((prev) => {
|
||||
if (prev) URL.revokeObjectURL(prev);
|
||||
return null;
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
const removeLogoMutation = useMutation({
|
||||
mutationFn: removeTenantLogo,
|
||||
onSuccess: (result) => {
|
||||
queryClient.setQueryData(['tenant', 'perfil'], (prev: typeof perfil) =>
|
||||
prev ? { ...prev, logo_url: result.logo_url } : prev,
|
||||
);
|
||||
applyThemeUpdate({ logoUrl: null });
|
||||
toast.success('Logo removida — voltou ao padrão da plataforma.');
|
||||
setRemovingLogo(false);
|
||||
},
|
||||
onError: (err) => {
|
||||
toast.error(err instanceof ApiError ? err.message : 'Não foi possível remover a logo.');
|
||||
setRemovingLogo(false);
|
||||
},
|
||||
});
|
||||
|
||||
function onSelectLogoFile(event: React.ChangeEvent<HTMLInputElement>) {
|
||||
const file = event.target.files?.[0];
|
||||
event.target.value = '';
|
||||
if (!file) return;
|
||||
|
||||
if (!TIPOS_LOGO_ACEITOS.includes(file.type)) {
|
||||
toast.error('Formato não suportado — envie um arquivo PNG, JPG ou SVG.');
|
||||
return;
|
||||
}
|
||||
if (file.size > TAMANHO_MAXIMO_LOGO_BYTES) {
|
||||
toast.error('Arquivo maior que 2MB — escolha uma imagem menor.');
|
||||
return;
|
||||
}
|
||||
|
||||
setPreviewUrl(URL.createObjectURL(file));
|
||||
uploadMutation.mutate(file);
|
||||
}
|
||||
|
||||
const logoSrc = previewUrl ?? resolveAssetUrl(perfil?.logo_url);
|
||||
|
||||
// --- Cor primária ---
|
||||
const corForm = useForm<UpdateTenantCorFormValues>({
|
||||
resolver: zodResolver(updateTenantCorSchema),
|
||||
values: perfil ? { cor_primaria: perfil.cor_primaria ?? '#2563EB' } : undefined,
|
||||
});
|
||||
const corAtual = corForm.watch('cor_primaria') || '#2563EB';
|
||||
const corValida = /^#[0-9A-Fa-f]{6}$/.test(corAtual);
|
||||
|
||||
const corMutation = useMutation({
|
||||
mutationFn: (values: UpdateTenantCorFormValues) => updateTenantCor(values.cor_primaria),
|
||||
onSuccess: (result) => {
|
||||
queryClient.setQueryData(['tenant', 'perfil'], (prev: typeof perfil) =>
|
||||
prev ? { ...prev, cor_primaria: result.cor_primaria } : prev,
|
||||
);
|
||||
applyThemeUpdate({ corPrimaria: result.cor_primaria });
|
||||
toast.success('Cor primária atualizada.');
|
||||
},
|
||||
onError: (err) => {
|
||||
toast.error(err instanceof ApiError ? err.message : 'Não foi possível salvar a cor.');
|
||||
},
|
||||
});
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-6">
|
||||
<div>
|
||||
<h1 className="text-xl font-semibold text-foreground">Perfil da empresa</h1>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Dados cadastrais e identidade visual usados em toda a aplicação
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<Card className="max-w-xl">
|
||||
<CardHeader>
|
||||
<CardTitle>Dados da empresa</CardTitle>
|
||||
<CardDescription>Nome fantasia e razão social exibidos no sistema.</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{isLoading ? (
|
||||
<div className="flex flex-col gap-4">
|
||||
<Skeleton className="h-11 w-full" />
|
||||
<Skeleton className="h-11 w-full" />
|
||||
</div>
|
||||
) : (
|
||||
<form
|
||||
className="flex flex-col gap-4"
|
||||
onSubmit={dadosForm.handleSubmit((values) => dadosMutation.mutate(values))}
|
||||
>
|
||||
<FormField
|
||||
label="Nome fantasia"
|
||||
error={dadosForm.formState.errors.nome_fantasia?.message}
|
||||
required
|
||||
>
|
||||
<Input {...dadosForm.register('nome_fantasia')} />
|
||||
</FormField>
|
||||
<FormField
|
||||
label="Razão social"
|
||||
error={dadosForm.formState.errors.razao_social?.message}
|
||||
required
|
||||
>
|
||||
<Input {...dadosForm.register('razao_social')} />
|
||||
</FormField>
|
||||
<div>
|
||||
<Button type="submit" loading={dadosMutation.isPending}>
|
||||
Salvar dados
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card className="max-w-xl">
|
||||
<CardHeader>
|
||||
<CardTitle>Logo</CardTitle>
|
||||
<CardDescription>
|
||||
PNG, JPG ou SVG, até 2MB. Sem logo própria, a plataforma usa um ícone padrão.
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="flex flex-col gap-4">
|
||||
<div className="flex items-center gap-4">
|
||||
<div className="flex size-20 shrink-0 items-center justify-center overflow-hidden rounded-lg border border-border bg-muted">
|
||||
{logoSrc ? (
|
||||
<Image
|
||||
src={logoSrc}
|
||||
alt="Logo do tenant"
|
||||
width={80}
|
||||
height={80}
|
||||
unoptimized={previewUrl !== null}
|
||||
className="size-20 object-contain"
|
||||
/>
|
||||
) : (
|
||||
<span className="text-xs text-muted-foreground">Sem logo</span>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex flex-col gap-2">
|
||||
<input
|
||||
ref={fileInputRef}
|
||||
type="file"
|
||||
accept="image/png,image/jpeg,image/svg+xml"
|
||||
className="hidden"
|
||||
onChange={onSelectLogoFile}
|
||||
/>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
loading={uploadMutation.isPending}
|
||||
onClick={() => fileInputRef.current?.click()}
|
||||
>
|
||||
<Upload /> Enviar logo
|
||||
</Button>
|
||||
{perfil?.logo_url && (
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => setRemovingLogo(true)}
|
||||
>
|
||||
<Trash2 /> Remover logo
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card className="max-w-xl">
|
||||
<CardHeader>
|
||||
<CardTitle>Cor primária</CardTitle>
|
||||
<CardDescription>
|
||||
Aplicada na sidebar, botões e destaques em toda a aplicação, com ajuste automático de
|
||||
contraste quando necessário.
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<form
|
||||
className="flex flex-col gap-4"
|
||||
onSubmit={corForm.handleSubmit((values) => corMutation.mutate(values))}
|
||||
>
|
||||
<FormField
|
||||
label="Cor"
|
||||
error={corForm.formState.errors.cor_primaria?.message}
|
||||
required
|
||||
>
|
||||
<div className="flex items-center gap-2">
|
||||
<input
|
||||
type="color"
|
||||
aria-label="Selecionar cor primária"
|
||||
className="size-11 shrink-0 cursor-pointer rounded-lg border border-input bg-transparent p-1"
|
||||
value={corValida ? corAtual : '#2563EB'}
|
||||
onChange={(e) =>
|
||||
corForm.setValue('cor_primaria', e.target.value.toUpperCase(), {
|
||||
shouldValidate: true,
|
||||
})
|
||||
}
|
||||
/>
|
||||
<Input
|
||||
className="max-w-40 font-mono uppercase"
|
||||
placeholder="#2563EB"
|
||||
{...corForm.register('cor_primaria')}
|
||||
/>
|
||||
</div>
|
||||
</FormField>
|
||||
|
||||
{corValida && (
|
||||
<div className="flex flex-col gap-2 rounded-lg border border-border p-4">
|
||||
<p className="text-xs font-medium text-muted-foreground">Pré-visualização</p>
|
||||
<div className="flex flex-wrap items-center gap-3">
|
||||
<span
|
||||
className="inline-flex h-11 items-center rounded-lg px-4 text-sm font-medium text-white"
|
||||
style={{ backgroundColor: corAtual }}
|
||||
>
|
||||
Botão de exemplo
|
||||
</span>
|
||||
<span
|
||||
className="text-sm font-medium"
|
||||
style={{ color: ensureAccessibleTextColor(corAtual) }}
|
||||
>
|
||||
Texto/ícone sobre fundo claro
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div>
|
||||
<Button type="submit" loading={corMutation.isPending} disabled={!corValida}>
|
||||
Salvar cor
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<ConfirmDialog
|
||||
open={removingLogo}
|
||||
onOpenChange={setRemovingLogo}
|
||||
title="Remover logo?"
|
||||
description="A identidade visual volta a usar o ícone padrão da plataforma."
|
||||
confirmLabel="Remover"
|
||||
destructive
|
||||
loading={removeLogoMutation.isPending}
|
||||
onConfirm={() => removeLogoMutation.mutate()}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
'use client';
|
||||
|
||||
import * as React from 'react';
|
||||
import { useParams, useRouter } from 'next/navigation';
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
|
||||
import { deactivateProduct, getProduct, updateProduct } from '@/lib/api/products';
|
||||
import type { ProductFormValues } from '@/lib/validators/products';
|
||||
import { ApiError } from '@/lib/api/client';
|
||||
import { toast } from '@/lib/toast';
|
||||
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Skeleton } from '@/components/ui/skeleton';
|
||||
import { ProductForm } from '@/components/domain/product-form';
|
||||
import { ConfirmDialog } from '@/components/domain/confirm-dialog';
|
||||
|
||||
export default function ProdutoDetalhePage() {
|
||||
const params = useParams<{ id: string }>();
|
||||
const productId = params.id;
|
||||
const router = useRouter();
|
||||
const queryClient = useQueryClient();
|
||||
const [deactivateOpen, setDeactivateOpen] = React.useState(false);
|
||||
|
||||
const { data: product, isLoading } = useQuery({
|
||||
queryKey: ['tenant', 'produtos', productId],
|
||||
queryFn: () => getProduct(productId),
|
||||
});
|
||||
|
||||
const saveMutation = useMutation({
|
||||
mutationFn: (values: ProductFormValues) =>
|
||||
updateProduct(productId, {
|
||||
...values,
|
||||
sku: values.sku || undefined,
|
||||
descricao: values.descricao || undefined,
|
||||
unidade: values.unidade || undefined,
|
||||
}),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['tenant', 'produtos', productId] });
|
||||
queryClient.invalidateQueries({ queryKey: ['tenant', 'produtos'] });
|
||||
toast.success('Produto atualizado.');
|
||||
},
|
||||
onError: (err) => {
|
||||
toast.error(err instanceof ApiError ? err.message : 'Não foi possível salvar as alterações.');
|
||||
},
|
||||
});
|
||||
|
||||
const deactivateMutation = useMutation({
|
||||
mutationFn: () => deactivateProduct(productId),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['tenant', 'produtos', productId] });
|
||||
queryClient.invalidateQueries({ queryKey: ['tenant', 'produtos'] });
|
||||
toast.success('Produto desativado.');
|
||||
setDeactivateOpen(false);
|
||||
},
|
||||
onError: (err) => {
|
||||
toast.error(err instanceof ApiError ? err.message : 'Não foi possível desativar o produto.');
|
||||
setDeactivateOpen(false);
|
||||
},
|
||||
});
|
||||
|
||||
if (isLoading || !product) {
|
||||
return (
|
||||
<div className="flex flex-col gap-4">
|
||||
<Skeleton className="h-8 w-64" />
|
||||
<Skeleton className="h-64 w-full" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-6">
|
||||
<div className="flex flex-wrap items-center justify-between gap-4">
|
||||
<div className="flex items-center gap-3">
|
||||
<h1 className="text-xl font-semibold text-foreground">{product.nome}</h1>
|
||||
<Badge variant={product.ativo ? 'default' : 'outline'}>{product.ativo ? 'Ativo' : 'Inativo'}</Badge>
|
||||
</div>
|
||||
{product.ativo && (
|
||||
<Button variant="outline" onClick={() => setDeactivateOpen(true)}>
|
||||
Desativar
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<ProductForm
|
||||
defaultValues={{
|
||||
tipo: product.tipo,
|
||||
nome: product.nome,
|
||||
descricao: product.descricao ?? '',
|
||||
sku: product.sku ?? '',
|
||||
valor_venda: Number(product.valor_venda),
|
||||
valor_custo: product.valor_custo ? Number(product.valor_custo) : undefined,
|
||||
unidade: product.unidade,
|
||||
recorrente: product.recorrente,
|
||||
}}
|
||||
onSubmit={(values) => saveMutation.mutate(values)}
|
||||
onCancel={() => router.push('/app/produtos')}
|
||||
submitting={saveMutation.isPending}
|
||||
submitLabel="Salvar alterações"
|
||||
/>
|
||||
|
||||
<ConfirmDialog
|
||||
open={deactivateOpen}
|
||||
onOpenChange={setDeactivateOpen}
|
||||
title="Desativar produto?"
|
||||
description="O item sai das listagens de ativos, mas o histórico de vendas continua íntegro."
|
||||
confirmLabel="Desativar"
|
||||
destructive
|
||||
loading={deactivateMutation.isPending}
|
||||
onConfirm={() => deactivateMutation.mutate()}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
'use client';
|
||||
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { useMutation } from '@tanstack/react-query';
|
||||
|
||||
import { createProduct } from '@/lib/api/products';
|
||||
import type { ProductFormValues } from '@/lib/validators/products';
|
||||
import { ApiError } from '@/lib/api/client';
|
||||
import { toast } from '@/lib/toast';
|
||||
import { ProductForm } from '@/components/domain/product-form';
|
||||
|
||||
export default function NovoProdutoPage() {
|
||||
const router = useRouter();
|
||||
|
||||
const mutation = useMutation({
|
||||
mutationFn: (values: ProductFormValues) =>
|
||||
createProduct({
|
||||
...values,
|
||||
sku: values.sku || undefined,
|
||||
descricao: values.descricao || undefined,
|
||||
unidade: values.unidade || undefined,
|
||||
}),
|
||||
onSuccess: (product) => {
|
||||
toast.success('Produto cadastrado.');
|
||||
router.push(`/app/produtos/${product.id}`);
|
||||
},
|
||||
onError: (err) => {
|
||||
// SKU duplicado (409) e limite de plano vêm com mensagem de negócio
|
||||
// clara do backend — mostrada direto (Etapa 16, item 6).
|
||||
toast.error(err instanceof ApiError ? err.message : 'Não foi possível cadastrar o produto.');
|
||||
},
|
||||
});
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-6">
|
||||
<div>
|
||||
<h1 className="text-xl font-semibold text-foreground">Novo produto</h1>
|
||||
<p className="text-sm text-muted-foreground">Cadastro de produto ou serviço</p>
|
||||
</div>
|
||||
|
||||
<ProductForm
|
||||
defaultValues={{
|
||||
tipo: 'produto',
|
||||
nome: '',
|
||||
descricao: '',
|
||||
sku: '',
|
||||
valor_venda: 0,
|
||||
valor_custo: undefined,
|
||||
unidade: '',
|
||||
recorrente: false,
|
||||
}}
|
||||
onSubmit={(values) => mutation.mutate(values)}
|
||||
onCancel={() => router.push('/app/produtos')}
|
||||
submitting={mutation.isPending}
|
||||
submitLabel="Cadastrar produto"
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,167 @@
|
||||
'use client';
|
||||
|
||||
import * as React from 'react';
|
||||
import Link from 'next/link';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { Plus, Search } from 'lucide-react';
|
||||
|
||||
import { listProducts, type ItemTipo, type ProductService } from '@/lib/api/products';
|
||||
import { formatCurrency } from '@/lib/format';
|
||||
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { DataTable, type DataTableColumn } from '@/components/ui/data-table';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
|
||||
|
||||
const TIPO_OPTIONS: { value: ItemTipo | 'todos'; label: string }[] = [
|
||||
{ value: 'todos', label: 'Produtos e serviços' },
|
||||
{ value: 'produto', label: 'Somente produtos' },
|
||||
{ value: 'servico', label: 'Somente serviços' },
|
||||
];
|
||||
|
||||
const ATIVO_OPTIONS = [
|
||||
{ value: 'todos', label: 'Ativos e inativos' },
|
||||
{ value: 'true', label: 'Somente ativos' },
|
||||
{ value: 'false', label: 'Somente inativos' },
|
||||
];
|
||||
|
||||
const LIMIT = 20;
|
||||
|
||||
export default function ProdutosPage() {
|
||||
const router = useRouter();
|
||||
const [busca, setBusca] = React.useState('');
|
||||
const [tipo, setTipo] = React.useState<ItemTipo | 'todos'>('todos');
|
||||
const [ativo, setAtivo] = React.useState('true');
|
||||
const [page, setPage] = React.useState(1);
|
||||
|
||||
const { data, isLoading } = useQuery({
|
||||
queryKey: ['tenant', 'produtos', { busca, tipo, ativo, page }],
|
||||
queryFn: () =>
|
||||
listProducts({
|
||||
busca: busca || undefined,
|
||||
tipo: tipo === 'todos' ? undefined : tipo,
|
||||
ativo: ativo === 'todos' ? undefined : ativo === 'true',
|
||||
page,
|
||||
limit: LIMIT,
|
||||
}),
|
||||
placeholderData: (prev) => prev,
|
||||
});
|
||||
|
||||
const columns: DataTableColumn<ProductService>[] = [
|
||||
{
|
||||
id: 'nome',
|
||||
header: 'Nome',
|
||||
primary: true,
|
||||
cell: (row) => (
|
||||
<div className="flex flex-col">
|
||||
<span className="font-medium text-foreground">{row.nome}</span>
|
||||
{row.sku && <span className="text-xs text-muted-foreground">SKU {row.sku}</span>}
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
id: 'tipo',
|
||||
header: 'Tipo',
|
||||
primary: true,
|
||||
cell: (row) => <Badge variant="outline">{row.tipo === 'produto' ? 'Produto' : 'Serviço'}</Badge>,
|
||||
},
|
||||
{ id: 'valor', header: 'Valor de venda', cell: (row) => formatCurrency(row.valor_venda) },
|
||||
{
|
||||
id: 'status',
|
||||
header: 'Status',
|
||||
cell: (row) => <Badge variant={row.ativo ? 'default' : 'outline'}>{row.ativo ? 'Ativo' : 'Inativo'}</Badge>,
|
||||
},
|
||||
];
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-6">
|
||||
<div className="flex flex-wrap items-center justify-between gap-4">
|
||||
<div>
|
||||
<h1 className="text-xl font-semibold text-foreground">Produtos e serviços</h1>
|
||||
<p className="text-sm text-muted-foreground">Itens que você vende</p>
|
||||
</div>
|
||||
<Button asChild>
|
||||
<Link href="/app/produtos/novo">
|
||||
<Plus /> Novo produto
|
||||
</Link>
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col gap-3 sm:flex-row sm:items-center">
|
||||
<div className="relative flex-1 sm:max-w-xs">
|
||||
<Search className="pointer-events-none absolute top-1/2 left-3 size-4 -translate-y-1/2 text-neutral-500" />
|
||||
<Input
|
||||
placeholder="Buscar por nome ou SKU..."
|
||||
className="pl-9"
|
||||
value={busca}
|
||||
onChange={(e) => {
|
||||
setBusca(e.target.value);
|
||||
setPage(1);
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
<Select
|
||||
value={tipo}
|
||||
onValueChange={(value) => {
|
||||
setTipo(value as ItemTipo | 'todos');
|
||||
setPage(1);
|
||||
}}
|
||||
>
|
||||
<SelectTrigger className="w-full sm:w-52" aria-label="Filtrar por tipo">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{TIPO_OPTIONS.map((opt) => (
|
||||
<SelectItem key={opt.value} value={opt.value}>
|
||||
{opt.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<Select
|
||||
value={ativo}
|
||||
onValueChange={(value) => {
|
||||
setAtivo(value);
|
||||
setPage(1);
|
||||
}}
|
||||
>
|
||||
<SelectTrigger className="w-full sm:w-52" aria-label="Filtrar por status">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{ATIVO_OPTIONS.map((opt) => (
|
||||
<SelectItem key={opt.value} value={opt.value}>
|
||||
{opt.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
<DataTable
|
||||
columns={columns}
|
||||
data={data?.data ?? []}
|
||||
keyField={(row) => row.id}
|
||||
loading={isLoading}
|
||||
emptyTitle="Nenhum produto encontrado"
|
||||
emptyDescription="Ajuste os filtros ou cadastre um novo produto."
|
||||
emptyAction={
|
||||
<Button size="sm" asChild>
|
||||
<Link href="/app/produtos/novo">Novo produto</Link>
|
||||
</Button>
|
||||
}
|
||||
onRowClick={(row) => router.push(`/app/produtos/${row.id}`)}
|
||||
rowActions={(row) => (
|
||||
<Button variant="ghost" size="sm" asChild>
|
||||
<Link href={`/app/produtos/${row.id}`}>Ver</Link>
|
||||
</Button>
|
||||
)}
|
||||
pagination={
|
||||
data ? { page: data.meta.page, limit: data.meta.limit, total: data.meta.total, onPageChange: setPage } : undefined
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,299 @@
|
||||
'use client';
|
||||
|
||||
import * as React from 'react';
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import { RefreshCw } from 'lucide-react';
|
||||
import type { DateRange } from 'react-day-picker';
|
||||
|
||||
import {
|
||||
atualizarRecebimentosAtrasados,
|
||||
listRecebimentos,
|
||||
marcarRecebimentoPago,
|
||||
type FormaPagamento,
|
||||
type Recebimento,
|
||||
} from '@/lib/api/sale-payments';
|
||||
import { listCustomers } from '@/lib/api/customers';
|
||||
import type { ParcelaStatus } from '@/lib/api/sales';
|
||||
import { ApiError } from '@/lib/api/client';
|
||||
import { formatCurrency, formatDate } from '@/lib/format';
|
||||
import { toast } from '@/lib/toast';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Combobox } from '@/components/ui/combobox';
|
||||
import { DataTable, type DataTableColumn } from '@/components/ui/data-table';
|
||||
import { DateRangePicker } from '@/components/ui/date-picker';
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
|
||||
import { StatusPill } from '@/components/ui/status-pill';
|
||||
import { ConfirmDialog } from '@/components/domain/confirm-dialog';
|
||||
import { MarcarPagoDialog } from '@/components/domain/marcar-pago-dialog';
|
||||
|
||||
const STATUS_OPTIONS: { value: ParcelaStatus | 'todos'; label: string }[] = [
|
||||
{ value: 'todos', label: 'Todos os status' },
|
||||
{ value: 'pendente', label: 'Pendente' },
|
||||
{ value: 'atrasado', label: 'Atrasado' },
|
||||
{ value: 'pago', label: 'Pago' },
|
||||
{ value: 'cancelado', label: 'Cancelado' },
|
||||
];
|
||||
|
||||
const FORMAS: { value: FormaPagamento; label: string }[] = [
|
||||
{ value: 'pix', label: 'Pix' },
|
||||
{ value: 'boleto', label: 'Boleto' },
|
||||
{ value: 'cartao', label: 'Cartão' },
|
||||
{ value: 'dinheiro', label: 'Dinheiro' },
|
||||
];
|
||||
|
||||
const LIMIT = 20;
|
||||
|
||||
function invalidateAll(queryClient: ReturnType<typeof useQueryClient>) {
|
||||
queryClient.invalidateQueries({ queryKey: ['tenant', 'recebimentos'] });
|
||||
queryClient.invalidateQueries({ queryKey: ['tenant', 'vendas'] });
|
||||
queryClient.invalidateQueries({ queryKey: ['tenant', 'dashboard'] });
|
||||
}
|
||||
|
||||
export default function RecebimentosPage() {
|
||||
const queryClient = useQueryClient();
|
||||
const [status, setStatus] = React.useState<ParcelaStatus | 'todos'>('todos');
|
||||
const [customerId, setCustomerId] = React.useState('');
|
||||
const [periodo, setPeriodo] = React.useState<DateRange | undefined>();
|
||||
const [page, setPage] = React.useState(1);
|
||||
const [payingParcela, setPayingParcela] = React.useState<{ id: string; valor: string } | null>(null);
|
||||
const [selected, setSelected] = React.useState<Set<string>>(new Set());
|
||||
const [bulkForma, setBulkForma] = React.useState<FormaPagamento | ''>('');
|
||||
const [bulkOpen, setBulkOpen] = React.useState(false);
|
||||
const [bulkLoading, setBulkLoading] = React.useState(false);
|
||||
const [atualizarOpen, setAtualizarOpen] = React.useState(false);
|
||||
|
||||
const { data: customersData } = useQuery({
|
||||
queryKey: ['tenant', 'customers', 'combobox'],
|
||||
queryFn: () => listCustomers({ limit: 100 }),
|
||||
});
|
||||
|
||||
const { data, isLoading } = useQuery({
|
||||
queryKey: [
|
||||
'tenant',
|
||||
'recebimentos',
|
||||
{ status, customerId, de: periodo?.from?.toISOString(), ate: periodo?.to?.toISOString(), page },
|
||||
],
|
||||
queryFn: () =>
|
||||
listRecebimentos({
|
||||
status: status === 'todos' ? undefined : status,
|
||||
customer_id: customerId || undefined,
|
||||
vencimento_inicio: periodo?.from?.toISOString().slice(0, 10),
|
||||
vencimento_fim: periodo?.to?.toISOString().slice(0, 10),
|
||||
page,
|
||||
limit: LIMIT,
|
||||
}),
|
||||
placeholderData: (prev) => prev,
|
||||
});
|
||||
|
||||
const atualizarMutation = useMutation({
|
||||
mutationFn: () => atualizarRecebimentosAtrasados(),
|
||||
onSuccess: (result) => {
|
||||
invalidateAll(queryClient);
|
||||
toast.success(`${result.atualizadas} parcela(s) marcadas como atrasadas.`);
|
||||
setAtualizarOpen(false);
|
||||
},
|
||||
onError: (err) => {
|
||||
toast.error(err instanceof ApiError ? err.message : 'Não foi possível atualizar as parcelas atrasadas.');
|
||||
setAtualizarOpen(false);
|
||||
},
|
||||
});
|
||||
|
||||
function toggleSelected(id: string) {
|
||||
setSelected((prev) => {
|
||||
const next = new Set(prev);
|
||||
if (next.has(id)) next.delete(id);
|
||||
else next.add(id);
|
||||
return next;
|
||||
});
|
||||
}
|
||||
|
||||
async function marcarSelecionadasPagas() {
|
||||
if (!bulkForma) return;
|
||||
setBulkLoading(true);
|
||||
const ids = Array.from(selected);
|
||||
const results = await Promise.allSettled(ids.map((id) => marcarRecebimentoPago(id, bulkForma)));
|
||||
const falhas = results.filter((r) => r.status === 'rejected').length;
|
||||
setBulkLoading(false);
|
||||
setBulkOpen(false);
|
||||
setSelected(new Set());
|
||||
setBulkForma('');
|
||||
invalidateAll(queryClient);
|
||||
if (falhas === 0) {
|
||||
toast.success(`${ids.length} parcela(s) marcadas como pagas.`);
|
||||
} else {
|
||||
toast.error(`${ids.length - falhas} de ${ids.length} marcadas como pagas — ${falhas} falharam.`);
|
||||
}
|
||||
}
|
||||
|
||||
const customerOptions = [
|
||||
{ value: '', label: 'Todos os clientes' },
|
||||
...(customersData?.data ?? []).map((c) => ({ value: c.id, label: c.nome_fantasia || c.razao_social })),
|
||||
];
|
||||
|
||||
const columns: DataTableColumn<Recebimento>[] = [
|
||||
{
|
||||
id: 'select',
|
||||
header: '',
|
||||
hideOnMobileCard: true,
|
||||
cell: (row) =>
|
||||
row.status === 'pendente' || row.status === 'atrasado' ? (
|
||||
<input
|
||||
type="checkbox"
|
||||
className="size-4 accent-primary"
|
||||
checked={selected.has(row.id)}
|
||||
onChange={() => toggleSelected(row.id)}
|
||||
aria-label={`Selecionar parcela de ${row.sale.customer.razao_social}`}
|
||||
/>
|
||||
) : null,
|
||||
className: 'w-px',
|
||||
},
|
||||
{ id: 'cliente', header: 'Cliente', primary: true, cell: (row) => row.sale.customer.razao_social },
|
||||
{
|
||||
id: 'venda',
|
||||
header: 'Venda',
|
||||
cell: (row) => `#${row.sale.numero_venda} · parcela ${row.numero_parcela}`,
|
||||
},
|
||||
{ id: 'valor', header: 'Valor', primary: true, cell: (row) => formatCurrency(row.valor) },
|
||||
{
|
||||
id: 'vencimento',
|
||||
header: 'Vencimento',
|
||||
cell: (row) => (
|
||||
<span className={cn(row.status === 'atrasado' && 'font-medium text-danger')}>{formatDate(row.vencimento)}</span>
|
||||
),
|
||||
},
|
||||
{ id: 'status', header: 'Status', cell: (row) => <StatusPill status={row.status} /> },
|
||||
];
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-6">
|
||||
<div className="flex flex-wrap items-center justify-between gap-4">
|
||||
<div>
|
||||
<h1 className="text-xl font-semibold text-foreground">Recebimentos</h1>
|
||||
<p className="text-sm text-muted-foreground">Parcelas de vendas a receber</p>
|
||||
</div>
|
||||
<Button variant="outline" onClick={() => setAtualizarOpen(true)}>
|
||||
<RefreshCw /> Atualizar atrasadas
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col gap-3 sm:flex-row sm:flex-wrap sm:items-center">
|
||||
<Select
|
||||
value={status}
|
||||
onValueChange={(value) => {
|
||||
setStatus(value as ParcelaStatus | 'todos');
|
||||
setPage(1);
|
||||
}}
|
||||
>
|
||||
<SelectTrigger className="w-full sm:w-48" aria-label="Filtrar por status">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{STATUS_OPTIONS.map((opt) => (
|
||||
<SelectItem key={opt.value} value={opt.value}>
|
||||
{opt.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<Combobox
|
||||
options={customerOptions}
|
||||
value={customerId}
|
||||
onChange={(value) => {
|
||||
setCustomerId(value);
|
||||
setPage(1);
|
||||
}}
|
||||
placeholder="Todos os clientes"
|
||||
searchPlaceholder="Buscar cliente..."
|
||||
className="w-full sm:w-56"
|
||||
/>
|
||||
<DateRangePicker
|
||||
value={periodo}
|
||||
onChange={(range) => {
|
||||
setPeriodo(range);
|
||||
setPage(1);
|
||||
}}
|
||||
placeholder="Período de vencimento"
|
||||
className="w-full sm:w-64"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{selected.size > 0 && (
|
||||
<div className="flex flex-wrap items-center gap-3 rounded-lg border border-primary/30 bg-primary/5 p-3">
|
||||
<span className="text-sm font-medium text-foreground">{selected.size} selecionada(s)</span>
|
||||
<Button size="sm" onClick={() => setBulkOpen(true)}>
|
||||
Marcar selecionadas como pagas
|
||||
</Button>
|
||||
<Button size="sm" variant="ghost" onClick={() => setSelected(new Set())}>
|
||||
Limpar seleção
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<DataTable
|
||||
columns={columns}
|
||||
data={data?.data ?? []}
|
||||
keyField={(row) => row.id}
|
||||
loading={isLoading}
|
||||
emptyTitle="Nenhum recebimento encontrado"
|
||||
emptyDescription="Ajuste os filtros de status/cliente/período."
|
||||
rowActions={(row) =>
|
||||
row.status === 'pendente' || row.status === 'atrasado' ? (
|
||||
<Button variant="ghost" size="sm" onClick={() => setPayingParcela(row)}>
|
||||
Marcar como paga
|
||||
</Button>
|
||||
) : null
|
||||
}
|
||||
pagination={
|
||||
data ? { page: data.meta.page, limit: data.meta.limit, total: data.meta.total, onPageChange: setPage } : undefined
|
||||
}
|
||||
/>
|
||||
|
||||
<MarcarPagoDialog
|
||||
parcela={payingParcela}
|
||||
onOpenChange={(open) => !open && setPayingParcela(null)}
|
||||
onSuccess={() => invalidateAll(queryClient)}
|
||||
/>
|
||||
|
||||
<ConfirmDialog
|
||||
open={atualizarOpen}
|
||||
onOpenChange={setAtualizarOpen}
|
||||
title="Atualizar parcelas atrasadas?"
|
||||
description="Marca como atrasada toda parcela pendente já vencida."
|
||||
confirmLabel="Atualizar"
|
||||
loading={atualizarMutation.isPending}
|
||||
onConfirm={() => atualizarMutation.mutate()}
|
||||
/>
|
||||
|
||||
<ConfirmDialog
|
||||
open={bulkOpen}
|
||||
onOpenChange={(open) => {
|
||||
setBulkOpen(open);
|
||||
if (!open) setBulkForma('');
|
||||
}}
|
||||
title={`Marcar ${selected.size} parcela(s) como pagas?`}
|
||||
description="Selecione a forma de pagamento usada em todas as parcelas selecionadas."
|
||||
confirmLabel="Confirmar"
|
||||
confirmDisabled={!bulkForma}
|
||||
loading={bulkLoading}
|
||||
onConfirm={marcarSelecionadasPagas}
|
||||
>
|
||||
<div className="px-4 pb-4 sm:px-0 sm:pb-0">
|
||||
<Select value={bulkForma} onValueChange={(value) => setBulkForma(value as FormaPagamento)}>
|
||||
<SelectTrigger className="w-full" aria-label="Forma de pagamento">
|
||||
<SelectValue placeholder="Selecione a forma de pagamento" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{FORMAS.map((f) => (
|
||||
<SelectItem key={f.value} value={f.value}>
|
||||
{f.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
</ConfirmDialog>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,301 @@
|
||||
'use client';
|
||||
|
||||
import * as React from 'react';
|
||||
import { useParams, useRouter } from 'next/navigation';
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
|
||||
import {
|
||||
changeSaleStatus,
|
||||
getSale,
|
||||
updateSale,
|
||||
TRANSICOES_VALIDAS,
|
||||
type SaleInput,
|
||||
type SaleListItem,
|
||||
type VendaStatus,
|
||||
} from '@/lib/api/sales';
|
||||
import type { SaleFormValues } from '@/lib/validators/sales';
|
||||
import { ApiError } from '@/lib/api/client';
|
||||
import { formatCurrency, formatDate, formatDateTime } from '@/lib/format';
|
||||
import { toast } from '@/lib/toast';
|
||||
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { EmptyState } from '@/components/ui/empty-state';
|
||||
import { Skeleton } from '@/components/ui/skeleton';
|
||||
import { StatusPill } from '@/components/ui/status-pill';
|
||||
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
|
||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
|
||||
import { ConfirmDialog } from '@/components/domain/confirm-dialog';
|
||||
import { MarcarPagoDialog } from '@/components/domain/marcar-pago-dialog';
|
||||
import { VendaForm } from '@/components/domain/venda-form';
|
||||
|
||||
function saleToFormValues(sale: SaleListItem): SaleFormValues {
|
||||
return {
|
||||
customer_id: sale.customer_id,
|
||||
data_venda: sale.data_venda.slice(0, 10),
|
||||
desconto: Number(sale.desconto),
|
||||
observacoes: sale.observacoes ?? '',
|
||||
itens: sale.itens.map((item) => ({
|
||||
product_service_id: item.product_service_id,
|
||||
nome: item.produto.nome,
|
||||
quantidade: Number(item.quantidade),
|
||||
valor_unitario: Number(item.valor_unitario),
|
||||
valor_catalogo: Number(item.produto.valor_venda),
|
||||
})),
|
||||
modoParcelas: 'manual',
|
||||
numeroParcelas: sale.parcelas.length || 1,
|
||||
parcelasManuais: sale.parcelas.map((p) => ({ valor: Number(p.valor), vencimento: p.vencimento.slice(0, 10) })),
|
||||
};
|
||||
}
|
||||
|
||||
function invalidateSaleQueries(
|
||||
queryClient: ReturnType<typeof useQueryClient>,
|
||||
saleId: string,
|
||||
) {
|
||||
queryClient.invalidateQueries({ queryKey: ['tenant', 'vendas', saleId] });
|
||||
queryClient.invalidateQueries({ queryKey: ['tenant', 'vendas'] });
|
||||
queryClient.invalidateQueries({ queryKey: ['tenant', 'recebimentos'] });
|
||||
queryClient.invalidateQueries({ queryKey: ['tenant', 'dashboard'] });
|
||||
}
|
||||
|
||||
export default function VendaDetalhePage() {
|
||||
const params = useParams<{ id: string }>();
|
||||
const saleId = params.id;
|
||||
const router = useRouter();
|
||||
const queryClient = useQueryClient();
|
||||
const [cancelOpen, setCancelOpen] = React.useState(false);
|
||||
const [concludeOpen, setConcludeOpen] = React.useState(false);
|
||||
const [payingParcela, setPayingParcela] = React.useState<{ id: string; valor: string } | null>(null);
|
||||
|
||||
const { data: sale, isLoading } = useQuery({
|
||||
queryKey: ['tenant', 'vendas', saleId],
|
||||
queryFn: () => getSale(saleId),
|
||||
});
|
||||
|
||||
const statusMutation = useMutation({
|
||||
mutationFn: (status: Exclude<VendaStatus, 'orcamento'>) => changeSaleStatus(saleId, status),
|
||||
onSuccess: () => {
|
||||
invalidateSaleQueries(queryClient, saleId);
|
||||
toast.success('Status da venda atualizado.');
|
||||
setCancelOpen(false);
|
||||
setConcludeOpen(false);
|
||||
},
|
||||
onError: (err) => {
|
||||
toast.error(err instanceof ApiError ? err.message : 'Não foi possível atualizar o status.');
|
||||
setCancelOpen(false);
|
||||
setConcludeOpen(false);
|
||||
},
|
||||
});
|
||||
|
||||
const updateMutation = useMutation({
|
||||
mutationFn: (input: SaleInput) => updateSale(saleId, input),
|
||||
onSuccess: () => {
|
||||
invalidateSaleQueries(queryClient, saleId);
|
||||
toast.success('Venda atualizada.');
|
||||
},
|
||||
onError: (err) => {
|
||||
toast.error(err instanceof ApiError ? err.message : 'Não foi possível salvar as alterações.');
|
||||
},
|
||||
});
|
||||
|
||||
if (isLoading || !sale) {
|
||||
return (
|
||||
<div className="flex flex-col gap-4">
|
||||
<Skeleton className="h-8 w-64" />
|
||||
<Skeleton className="h-64 w-full" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const transicoesDisponiveis = TRANSICOES_VALIDAS[sale.status];
|
||||
const podeConfirmar = transicoesDisponiveis.includes('confirmada');
|
||||
const podeConcluir = transicoesDisponiveis.includes('concluida');
|
||||
const podeCancelar = transicoesDisponiveis.includes('cancelada');
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-6">
|
||||
<div className="flex flex-wrap items-center justify-between gap-4">
|
||||
<div>
|
||||
<div className="flex items-center gap-3">
|
||||
<h1 className="text-xl font-semibold text-foreground">Venda #{sale.numero_venda}</h1>
|
||||
<StatusPill status={sale.status} />
|
||||
</div>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{sale.customer.razao_social} · {formatDate(sale.data_venda)}
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{podeConfirmar && (
|
||||
<Button onClick={() => statusMutation.mutate('confirmada')} loading={statusMutation.isPending}>
|
||||
Confirmar venda
|
||||
</Button>
|
||||
)}
|
||||
{podeConcluir && (
|
||||
<Button variant="outline" onClick={() => setConcludeOpen(true)}>
|
||||
Concluir venda
|
||||
</Button>
|
||||
)}
|
||||
{podeCancelar && (
|
||||
<Button variant="outline" onClick={() => setCancelOpen(true)}>
|
||||
Cancelar venda
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Tabs defaultValue="itens">
|
||||
<TabsList>
|
||||
<TabsTrigger value="itens">Itens</TabsTrigger>
|
||||
<TabsTrigger value="parcelas">Parcelas</TabsTrigger>
|
||||
<TabsTrigger value="historico">Histórico</TabsTrigger>
|
||||
</TabsList>
|
||||
|
||||
<TabsContent value="itens" className="pt-4">
|
||||
{sale.status === 'orcamento' ? (
|
||||
<VendaForm
|
||||
mode="edit"
|
||||
defaultValues={saleToFormValues(sale)}
|
||||
submittingConfirmOrSave={updateMutation.isPending}
|
||||
onConfirmOrSave={(input) => updateMutation.mutate(input)}
|
||||
onCancel={() => router.push('/app/vendas')}
|
||||
/>
|
||||
) : (
|
||||
<ItensReadOnly sale={sale} />
|
||||
)}
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="parcelas" className="pt-4">
|
||||
<ParcelasTab sale={sale} onMarcarPago={setPayingParcela} />
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="historico" className="pt-4">
|
||||
<EmptyState
|
||||
title="Histórico não disponível nesta versão"
|
||||
description="O backend ainda não expõe um endpoint de auditoria (audit_logs) para consulta pelo tenant — só registra internamente."
|
||||
/>
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
|
||||
<ConfirmDialog
|
||||
open={cancelOpen}
|
||||
onOpenChange={setCancelOpen}
|
||||
title="Cancelar venda?"
|
||||
description="Isso cancela todas as parcelas pendentes/atrasadas desta venda. Parcelas já pagas não são estornadas."
|
||||
confirmLabel="Cancelar venda"
|
||||
destructive
|
||||
loading={statusMutation.isPending}
|
||||
onConfirm={() => statusMutation.mutate('cancelada')}
|
||||
/>
|
||||
|
||||
<ConfirmDialog
|
||||
open={concludeOpen}
|
||||
onOpenChange={setConcludeOpen}
|
||||
title="Concluir venda?"
|
||||
description="Marca a venda como concluída — use quando a entrega/prestação do serviço tiver sido finalizada."
|
||||
confirmLabel="Concluir"
|
||||
loading={statusMutation.isPending}
|
||||
onConfirm={() => statusMutation.mutate('concluida')}
|
||||
/>
|
||||
|
||||
<MarcarPagoDialog
|
||||
parcela={payingParcela}
|
||||
onOpenChange={(open) => !open && setPayingParcela(null)}
|
||||
onSuccess={() => invalidateSaleQueries(queryClient, saleId)}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function ItensReadOnly({ sale }: { sale: SaleListItem }) {
|
||||
return (
|
||||
<div className="flex flex-col gap-4">
|
||||
<div className="overflow-x-auto rounded-lg border border-border">
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead>Item</TableHead>
|
||||
<TableHead>Qtd.</TableHead>
|
||||
<TableHead>Valor unit.</TableHead>
|
||||
<TableHead>Subtotal</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{sale.itens.map((item) => (
|
||||
<TableRow key={item.id}>
|
||||
<TableCell>{item.produto.nome}</TableCell>
|
||||
<TableCell className="tabular-nums">{item.quantidade}</TableCell>
|
||||
<TableCell className="tabular-nums">{formatCurrency(item.valor_unitario)}</TableCell>
|
||||
<TableCell className="tabular-nums">{formatCurrency(item.valor_total)}</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</div>
|
||||
<div className="flex flex-col items-end gap-1 text-sm">
|
||||
<div className="flex w-48 justify-between text-muted-foreground">
|
||||
<span>Desconto</span>
|
||||
<span className="tabular-nums">-{formatCurrency(sale.desconto)}</span>
|
||||
</div>
|
||||
<div className="flex w-48 justify-between text-base font-semibold text-foreground">
|
||||
<span>Total</span>
|
||||
<span className="tabular-nums">{formatCurrency(sale.valor_total)}</span>
|
||||
</div>
|
||||
</div>
|
||||
{sale.observacoes && (
|
||||
<p className="text-sm text-muted-foreground">
|
||||
<span className="font-medium text-foreground">Observações: </span>
|
||||
{sale.observacoes}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function ParcelasTab({
|
||||
sale,
|
||||
onMarcarPago,
|
||||
}: {
|
||||
sale: SaleListItem;
|
||||
onMarcarPago: (parcela: { id: string; valor: string }) => void;
|
||||
}) {
|
||||
return (
|
||||
<div className="overflow-x-auto rounded-lg border border-border">
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead>Parcela</TableHead>
|
||||
<TableHead>Valor</TableHead>
|
||||
<TableHead>Vencimento</TableHead>
|
||||
<TableHead>Status</TableHead>
|
||||
<TableHead>Pago em</TableHead>
|
||||
<TableHead className="w-px">
|
||||
<span className="sr-only">Ações</span>
|
||||
</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{sale.parcelas.map((parcela) => (
|
||||
<TableRow key={parcela.id}>
|
||||
<TableCell>{parcela.numero_parcela}</TableCell>
|
||||
<TableCell className="tabular-nums">{formatCurrency(parcela.valor)}</TableCell>
|
||||
<TableCell className="tabular-nums">{formatDate(parcela.vencimento)}</TableCell>
|
||||
<TableCell>
|
||||
<StatusPill status={parcela.status} />
|
||||
</TableCell>
|
||||
<TableCell className="tabular-nums">{formatDateTime(parcela.pago_em)}</TableCell>
|
||||
<TableCell>
|
||||
{parcela.status === 'pendente' || parcela.status === 'atrasado' ? (
|
||||
<Button variant="ghost" size="sm" onClick={() => onMarcarPago(parcela)}>
|
||||
Marcar como paga
|
||||
</Button>
|
||||
) : parcela.status === 'pago' ? (
|
||||
<Badge variant="outline">{parcela.forma_pagamento}</Badge>
|
||||
) : null}
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
'use client';
|
||||
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { useMutation } from '@tanstack/react-query';
|
||||
|
||||
import { createSale, type SaleInput } from '@/lib/api/sales';
|
||||
import type { SaleFormValues } from '@/lib/validators/sales';
|
||||
import { ApiError } from '@/lib/api/client';
|
||||
import { toast } from '@/lib/toast';
|
||||
import { VendaForm } from '@/components/domain/venda-form';
|
||||
|
||||
function todayIso(): string {
|
||||
return new Date().toISOString().slice(0, 10);
|
||||
}
|
||||
|
||||
const DEFAULT_VALUES: SaleFormValues = {
|
||||
customer_id: '',
|
||||
data_venda: todayIso(),
|
||||
desconto: 0,
|
||||
observacoes: '',
|
||||
itens: [],
|
||||
modoParcelas: 'automatico',
|
||||
numeroParcelas: 1,
|
||||
parcelasManuais: [],
|
||||
};
|
||||
|
||||
export default function NovaVendaPage() {
|
||||
const router = useRouter();
|
||||
|
||||
const draftMutation = useMutation({
|
||||
mutationFn: (input: SaleInput) => createSale({ ...input, status: 'orcamento' }),
|
||||
onSuccess: (sale) => {
|
||||
toast.success('Orçamento salvo.');
|
||||
router.push(`/app/vendas/${sale.id}`);
|
||||
},
|
||||
onError: (err) => {
|
||||
toast.error(err instanceof ApiError ? err.message : 'Não foi possível salvar o orçamento.');
|
||||
},
|
||||
});
|
||||
|
||||
const confirmMutation = useMutation({
|
||||
mutationFn: (input: SaleInput) => createSale({ ...input, status: 'confirmada' }),
|
||||
onSuccess: (sale) => {
|
||||
toast.success('Venda confirmada.');
|
||||
router.push(`/app/vendas/${sale.id}`);
|
||||
},
|
||||
onError: (err) => {
|
||||
toast.error(err instanceof ApiError ? err.message : 'Não foi possível confirmar a venda.');
|
||||
},
|
||||
});
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-6">
|
||||
<div>
|
||||
<h1 className="text-xl font-semibold text-foreground">Nova venda</h1>
|
||||
<p className="text-sm text-muted-foreground">Registre uma venda com itens e parcelas</p>
|
||||
</div>
|
||||
|
||||
<VendaForm
|
||||
mode="create"
|
||||
defaultValues={DEFAULT_VALUES}
|
||||
submittingDraft={draftMutation.isPending}
|
||||
submittingConfirmOrSave={confirmMutation.isPending}
|
||||
onSaveDraft={(input) => draftMutation.mutate(input)}
|
||||
onConfirmOrSave={(input) => confirmMutation.mutate(input)}
|
||||
onCancel={() => router.push('/app/vendas')}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,153 @@
|
||||
'use client';
|
||||
|
||||
import * as React from 'react';
|
||||
import Link from 'next/link';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { Plus } from 'lucide-react';
|
||||
import type { DateRange } from 'react-day-picker';
|
||||
|
||||
import { listSales, type SaleListItem, type VendaStatus } from '@/lib/api/sales';
|
||||
import { listCustomers } from '@/lib/api/customers';
|
||||
import { formatCurrency, formatDate } from '@/lib/format';
|
||||
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Combobox } from '@/components/ui/combobox';
|
||||
import { DataTable, type DataTableColumn } from '@/components/ui/data-table';
|
||||
import { DateRangePicker } from '@/components/ui/date-picker';
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
|
||||
import { StatusPill } from '@/components/ui/status-pill';
|
||||
|
||||
const STATUS_OPTIONS: { value: VendaStatus | 'todos'; label: string }[] = [
|
||||
{ value: 'todos', label: 'Todos os status' },
|
||||
{ value: 'orcamento', label: 'Orçamento' },
|
||||
{ value: 'confirmada', label: 'Confirmada' },
|
||||
{ value: 'concluida', label: 'Concluída' },
|
||||
{ value: 'cancelada', label: 'Cancelada' },
|
||||
];
|
||||
|
||||
const LIMIT = 20;
|
||||
|
||||
export default function VendasPage() {
|
||||
const router = useRouter();
|
||||
const [status, setStatus] = React.useState<VendaStatus | 'todos'>('todos');
|
||||
const [customerId, setCustomerId] = React.useState('');
|
||||
const [periodo, setPeriodo] = React.useState<DateRange | undefined>();
|
||||
const [page, setPage] = React.useState(1);
|
||||
|
||||
const { data: customersData } = useQuery({
|
||||
queryKey: ['tenant', 'customers', 'combobox'],
|
||||
queryFn: () => listCustomers({ limit: 100 }),
|
||||
});
|
||||
|
||||
const { data, isLoading } = useQuery({
|
||||
queryKey: [
|
||||
'tenant',
|
||||
'vendas',
|
||||
{ status, customerId, de: periodo?.from?.toISOString(), ate: periodo?.to?.toISOString(), page },
|
||||
],
|
||||
queryFn: () =>
|
||||
listSales({
|
||||
status: status === 'todos' ? undefined : status,
|
||||
customer_id: customerId || undefined,
|
||||
data_inicio: periodo?.from?.toISOString().slice(0, 10),
|
||||
data_fim: periodo?.to?.toISOString().slice(0, 10),
|
||||
page,
|
||||
limit: LIMIT,
|
||||
}),
|
||||
placeholderData: (prev) => prev,
|
||||
});
|
||||
|
||||
const customerOptions = [
|
||||
{ value: '', label: 'Todos os clientes' },
|
||||
...(customersData?.data ?? []).map((c) => ({ value: c.id, label: c.nome_fantasia || c.razao_social })),
|
||||
];
|
||||
|
||||
const columns: DataTableColumn<SaleListItem>[] = [
|
||||
{ id: 'numero', header: 'Venda', primary: true, cell: (row) => `#${row.numero_venda}` },
|
||||
{ id: 'cliente', header: 'Cliente', primary: true, cell: (row) => row.customer.razao_social },
|
||||
{ id: 'valor', header: 'Valor total', cell: (row) => formatCurrency(row.valor_total) },
|
||||
{ id: 'status', header: 'Status', cell: (row) => <StatusPill status={row.status} /> },
|
||||
{ id: 'data', header: 'Data', cell: (row) => formatDate(row.data_venda) },
|
||||
];
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-6">
|
||||
<div className="flex flex-wrap items-center justify-between gap-4">
|
||||
<div>
|
||||
<h1 className="text-xl font-semibold text-foreground">Vendas</h1>
|
||||
<p className="text-sm text-muted-foreground">Orçamentos e vendas confirmadas</p>
|
||||
</div>
|
||||
<Button asChild>
|
||||
<Link href="/app/vendas/nova">
|
||||
<Plus /> Nova venda
|
||||
</Link>
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col gap-3 sm:flex-row sm:flex-wrap sm:items-center">
|
||||
<Select
|
||||
value={status}
|
||||
onValueChange={(value) => {
|
||||
setStatus(value as VendaStatus | 'todos');
|
||||
setPage(1);
|
||||
}}
|
||||
>
|
||||
<SelectTrigger className="w-full sm:w-48" aria-label="Filtrar por status">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{STATUS_OPTIONS.map((opt) => (
|
||||
<SelectItem key={opt.value} value={opt.value}>
|
||||
{opt.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<Combobox
|
||||
options={customerOptions}
|
||||
value={customerId}
|
||||
onChange={(value) => {
|
||||
setCustomerId(value);
|
||||
setPage(1);
|
||||
}}
|
||||
placeholder="Todos os clientes"
|
||||
searchPlaceholder="Buscar cliente..."
|
||||
className="w-full sm:w-56"
|
||||
/>
|
||||
<DateRangePicker
|
||||
value={periodo}
|
||||
onChange={(range) => {
|
||||
setPeriodo(range);
|
||||
setPage(1);
|
||||
}}
|
||||
placeholder="Período da venda"
|
||||
className="w-full sm:w-64"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<DataTable
|
||||
columns={columns}
|
||||
data={data?.data ?? []}
|
||||
keyField={(row) => row.id}
|
||||
loading={isLoading}
|
||||
emptyTitle="Nenhuma venda encontrada"
|
||||
emptyDescription="Ajuste os filtros ou registre uma nova venda."
|
||||
emptyAction={
|
||||
<Button size="sm" asChild>
|
||||
<Link href="/app/vendas/nova">Nova venda</Link>
|
||||
</Button>
|
||||
}
|
||||
onRowClick={(row) => router.push(`/app/vendas/${row.id}`)}
|
||||
rowActions={(row) => (
|
||||
<Button variant="ghost" size="sm" asChild>
|
||||
<Link href={`/app/vendas/${row.id}`}>Ver</Link>
|
||||
</Button>
|
||||
)}
|
||||
pagination={
|
||||
data ? { page: data.meta.page, limit: data.meta.limit, total: data.meta.total, onPageChange: setPage } : undefined
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,338 @@
|
||||
'use client';
|
||||
|
||||
import * as React from 'react';
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { zodResolver } from '@hookform/resolvers/zod';
|
||||
import { CheckCircle2, Plus, Send } from 'lucide-react';
|
||||
|
||||
import {
|
||||
consultarWhatsappStatus,
|
||||
criarWhatsappInstance,
|
||||
listWhatsappInstances,
|
||||
obterWhatsappQrCode,
|
||||
removerWhatsappInstance,
|
||||
testarEnvioWhatsapp,
|
||||
type WhatsappInstance,
|
||||
type WhatsappInstanceStatus,
|
||||
} from '@/lib/api/whatsapp';
|
||||
import {
|
||||
testarEnvioWhatsappSchema,
|
||||
type TestarEnvioWhatsappFormValues,
|
||||
} from '@/lib/validators/whatsapp';
|
||||
import { ApiError } from '@/lib/api/client';
|
||||
import { formatDateTime } from '@/lib/format';
|
||||
import { toast } from '@/lib/toast';
|
||||
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { DataTable, type DataTableColumn } from '@/components/ui/data-table';
|
||||
import { FormField } from '@/components/ui/form-field';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { ResponsiveDialog } from '@/components/ui/responsive-dialog';
|
||||
import { Skeleton } from '@/components/ui/skeleton';
|
||||
import { Textarea } from '@/components/ui/textarea';
|
||||
import { ConfirmDialog } from '@/components/domain/confirm-dialog';
|
||||
|
||||
const STATUS_LABEL: Record<WhatsappInstanceStatus, string> = {
|
||||
desconectado: 'Desconectado',
|
||||
conectando: 'Conectando',
|
||||
conectado: 'Conectado',
|
||||
erro: 'Erro',
|
||||
};
|
||||
|
||||
const STATUS_TONE: Record<WhatsappInstanceStatus, 'default' | 'destructive' | 'outline' | 'secondary'> = {
|
||||
desconectado: 'outline',
|
||||
conectando: 'secondary',
|
||||
conectado: 'default',
|
||||
erro: 'destructive',
|
||||
};
|
||||
|
||||
const POLL_INTERVAL_MS = 4000;
|
||||
|
||||
/** `EvolutionQrCode.base64` não tem prefixo garantido pelo backend — renderiza defensivamente. */
|
||||
function qrImageSrc(base64?: string): string | null {
|
||||
if (!base64) return null;
|
||||
return base64.startsWith('data:') ? base64 : `data:image/png;base64,${base64}`;
|
||||
}
|
||||
|
||||
function ConnectInstanceDialog({
|
||||
instance,
|
||||
onOpenChange,
|
||||
}: {
|
||||
instance: WhatsappInstance | null;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
}) {
|
||||
const open = instance !== null;
|
||||
const queryClient = useQueryClient();
|
||||
const [status, setStatus] = React.useState<WhatsappInstanceStatus | null>(null);
|
||||
|
||||
React.useEffect(() => {
|
||||
setStatus(instance?.status ?? null);
|
||||
}, [instance?.id, instance?.status]);
|
||||
|
||||
const {
|
||||
data: qrcode,
|
||||
isLoading: qrLoading,
|
||||
error: qrError,
|
||||
} = useQuery({
|
||||
queryKey: ['tenant', 'whatsapp', 'qrcode', instance?.id],
|
||||
queryFn: () => obterWhatsappQrCode(instance!.id),
|
||||
enabled: open && status !== 'conectado',
|
||||
retry: false,
|
||||
});
|
||||
|
||||
// Polling automático do status a cada poucos segundos, parando sozinho ao
|
||||
// detectar "conectado" ou quando o diálogo fecha/desmonta — o efeito
|
||||
// depende de `status`, então uma vez "conectado" a condição de guarda
|
||||
// abaixo impede reagendar um novo `setInterval` (sem vazamento).
|
||||
React.useEffect(() => {
|
||||
if (!open || !instance || status === 'conectado') return;
|
||||
|
||||
const interval = setInterval(() => {
|
||||
consultarWhatsappStatus(instance.id)
|
||||
.then((updated) => {
|
||||
setStatus(updated.status);
|
||||
if (updated.status === 'conectado') {
|
||||
queryClient.invalidateQueries({ queryKey: ['tenant', 'whatsapp'] });
|
||||
}
|
||||
})
|
||||
.catch(() => {
|
||||
// falha pontual de rede/consulta — a próxima iteração tenta de novo
|
||||
});
|
||||
}, POLL_INTERVAL_MS);
|
||||
|
||||
return () => clearInterval(interval);
|
||||
}, [open, instance, status, queryClient]);
|
||||
|
||||
const qrSrc = qrImageSrc(qrcode?.base64);
|
||||
|
||||
return (
|
||||
<ResponsiveDialog
|
||||
open={open}
|
||||
onOpenChange={onOpenChange}
|
||||
title={`Conectar — ${instance?.instance_name ?? ''}`}
|
||||
description="Escaneie o QR code no WhatsApp do número que vai enviar as mensagens."
|
||||
footer={
|
||||
<Button className="w-full" variant="outline" onClick={() => onOpenChange(false)}>
|
||||
Fechar
|
||||
</Button>
|
||||
}
|
||||
>
|
||||
<div className="flex flex-col items-center gap-4 px-4 pb-4 sm:px-0 sm:pb-0">
|
||||
{status === 'conectado' ? (
|
||||
<div className="flex flex-col items-center gap-2 py-8 text-center">
|
||||
<CheckCircle2 className="size-10 text-success" aria-hidden />
|
||||
<p className="font-medium text-foreground">Conectado com sucesso!</p>
|
||||
<p className="text-sm text-muted-foreground">Esta instância já pode enviar mensagens.</p>
|
||||
</div>
|
||||
) : qrLoading ? (
|
||||
<Skeleton className="size-56" />
|
||||
) : qrError ? (
|
||||
<p className="py-8 text-center text-sm text-destructive">
|
||||
{qrError instanceof ApiError ? qrError.message : 'Não foi possível obter o QR code.'}
|
||||
</p>
|
||||
) : qrSrc ? (
|
||||
<>
|
||||
{/* Base64 de origem dinâmica (Evolution API) — `<img>` puro, `next/image` não otimiza data URIs. */}
|
||||
{/* eslint-disable-next-line @next/next/no-img-element */}
|
||||
<img
|
||||
src={qrSrc}
|
||||
alt="QR code para conectar o WhatsApp"
|
||||
className="size-56 rounded-lg border border-border object-contain"
|
||||
/>
|
||||
{qrcode?.pairing_code && (
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Código de pareamento: <span className="font-mono font-medium">{qrcode.pairing_code}</span>
|
||||
</p>
|
||||
)}
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Aguardando leitura — o status atualiza automaticamente assim que o WhatsApp conectar.
|
||||
</p>
|
||||
</>
|
||||
) : (
|
||||
<p className="py-8 text-center text-sm text-muted-foreground">QR code indisponível.</p>
|
||||
)}
|
||||
</div>
|
||||
</ResponsiveDialog>
|
||||
);
|
||||
}
|
||||
|
||||
function TestSendDialog({
|
||||
instance,
|
||||
onOpenChange,
|
||||
}: {
|
||||
instance: WhatsappInstance | null;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
}) {
|
||||
const form = useForm<TestarEnvioWhatsappFormValues>({
|
||||
resolver: zodResolver(testarEnvioWhatsappSchema),
|
||||
defaultValues: { numero: '', mensagem: '' },
|
||||
});
|
||||
|
||||
React.useEffect(() => {
|
||||
if (instance) form.reset({ numero: '', mensagem: '' });
|
||||
}, [instance, form]);
|
||||
|
||||
const mutation = useMutation({
|
||||
mutationFn: (values: TestarEnvioWhatsappFormValues) =>
|
||||
testarEnvioWhatsapp(instance!.id, { numero: values.numero, mensagem: values.mensagem || undefined }),
|
||||
onSuccess: (result) => {
|
||||
// `DispatchResult` sempre responde HTTP 200 — falha de envio vem como
|
||||
// `{ sucesso: false, erro }`, não como erro HTTP (ver `lib/api/whatsapp.ts`).
|
||||
if (result.sucesso) {
|
||||
toast.success('Mensagem de teste enviada.');
|
||||
onOpenChange(false);
|
||||
} else {
|
||||
toast.error(result.erro ?? 'Falha ao enviar a mensagem de teste.');
|
||||
}
|
||||
},
|
||||
onError: (err) => {
|
||||
toast.error(err instanceof ApiError ? err.message : 'Falha ao enviar a mensagem de teste.');
|
||||
},
|
||||
});
|
||||
|
||||
return (
|
||||
<ResponsiveDialog
|
||||
open={instance !== null}
|
||||
onOpenChange={onOpenChange}
|
||||
title={`Testar envio — ${instance?.instance_name ?? ''}`}
|
||||
footer={
|
||||
<>
|
||||
<Button variant="outline" onClick={() => onOpenChange(false)}>
|
||||
Cancelar
|
||||
</Button>
|
||||
<Button loading={mutation.isPending} onClick={form.handleSubmit((v) => mutation.mutate(v))}>
|
||||
<Send /> Enviar
|
||||
</Button>
|
||||
</>
|
||||
}
|
||||
>
|
||||
<form
|
||||
className="flex flex-col gap-4 px-4 pb-4 sm:px-0 sm:pb-0"
|
||||
onSubmit={form.handleSubmit((v) => mutation.mutate(v))}
|
||||
>
|
||||
<FormField
|
||||
label="Número (DDI+DDD+número)"
|
||||
error={form.formState.errors.numero?.message}
|
||||
required
|
||||
>
|
||||
<Input placeholder="5511999998888" {...form.register('numero')} />
|
||||
</FormField>
|
||||
<FormField label="Mensagem" error={form.formState.errors.mensagem?.message}>
|
||||
<Textarea placeholder="Mensagem de teste do SeConectai Vendas." {...form.register('mensagem')} />
|
||||
</FormField>
|
||||
</form>
|
||||
</ResponsiveDialog>
|
||||
);
|
||||
}
|
||||
|
||||
export default function WhatsappPage() {
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
const { data: instances, isLoading } = useQuery({
|
||||
queryKey: ['tenant', 'whatsapp'],
|
||||
queryFn: listWhatsappInstances,
|
||||
});
|
||||
|
||||
const [connecting, setConnecting] = React.useState<WhatsappInstance | null>(null);
|
||||
const [testing, setTesting] = React.useState<WhatsappInstance | null>(null);
|
||||
const [removing, setRemoving] = React.useState<WhatsappInstance | null>(null);
|
||||
|
||||
const createMutation = useMutation({
|
||||
mutationFn: criarWhatsappInstance,
|
||||
onSuccess: (instance) => {
|
||||
queryClient.invalidateQueries({ queryKey: ['tenant', 'whatsapp'] });
|
||||
setConnecting(instance);
|
||||
},
|
||||
onError: (err) => {
|
||||
toast.error(err instanceof ApiError ? err.message : 'Não foi possível criar a instância.');
|
||||
},
|
||||
});
|
||||
|
||||
const removeMutation = useMutation({
|
||||
mutationFn: (id: string) => removerWhatsappInstance(id),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['tenant', 'whatsapp'] });
|
||||
toast.success('Instância removida.');
|
||||
setRemoving(null);
|
||||
},
|
||||
onError: (err) => {
|
||||
toast.error(err instanceof ApiError ? err.message : 'Não foi possível remover a instância.');
|
||||
setRemoving(null);
|
||||
},
|
||||
});
|
||||
|
||||
const columns: DataTableColumn<WhatsappInstance>[] = [
|
||||
{ id: 'instance_name', header: 'Instância', primary: true, cell: (row) => row.instance_name },
|
||||
{
|
||||
id: 'status',
|
||||
header: 'Status',
|
||||
primary: true,
|
||||
cell: (row) => <Badge variant={STATUS_TONE[row.status]}>{STATUS_LABEL[row.status]}</Badge>,
|
||||
},
|
||||
{
|
||||
id: 'numero_conectado',
|
||||
header: 'Número conectado',
|
||||
cell: (row) => row.numero_conectado ?? '—',
|
||||
},
|
||||
{ id: 'criado_em', header: 'Criada em', hideOnMobileCard: true, cell: (row) => formatDateTime(row.criado_em) },
|
||||
];
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-6">
|
||||
<div className="flex flex-wrap items-center justify-between gap-4">
|
||||
<div>
|
||||
<h1 className="text-xl font-semibold text-foreground">WhatsApp</h1>
|
||||
<p className="text-sm text-muted-foreground">Instâncias de envio de mensagens via Evolution API</p>
|
||||
</div>
|
||||
<Button loading={createMutation.isPending} onClick={() => createMutation.mutate()}>
|
||||
<Plus /> Nova instância
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<DataTable
|
||||
columns={columns}
|
||||
data={instances ?? []}
|
||||
keyField={(row) => row.id}
|
||||
loading={isLoading}
|
||||
emptyTitle="Nenhuma instância cadastrada"
|
||||
emptyDescription="Crie uma instância para conectar um número de WhatsApp."
|
||||
emptyAction={
|
||||
<Button size="sm" loading={createMutation.isPending} onClick={() => createMutation.mutate()}>
|
||||
Nova instância
|
||||
</Button>
|
||||
}
|
||||
rowActions={(row) => (
|
||||
<>
|
||||
{row.status !== 'conectado' && (
|
||||
<Button variant="ghost" size="sm" onClick={() => setConnecting(row)}>
|
||||
Conectar
|
||||
</Button>
|
||||
)}
|
||||
<Button variant="ghost" size="sm" onClick={() => setTesting(row)}>
|
||||
Testar envio
|
||||
</Button>
|
||||
<Button variant="ghost" size="sm" onClick={() => setRemoving(row)}>
|
||||
Remover
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
/>
|
||||
|
||||
<ConnectInstanceDialog instance={connecting} onOpenChange={(open) => !open && setConnecting(null)} />
|
||||
<TestSendDialog instance={testing} onOpenChange={(open) => !open && setTesting(null)} />
|
||||
|
||||
<ConfirmDialog
|
||||
open={removing !== null}
|
||||
onOpenChange={(open) => !open && setRemoving(null)}
|
||||
title={`Remover instância "${removing?.instance_name}"?`}
|
||||
description="Desconecta o número e apaga a instância na Evolution API — não é possível desfazer."
|
||||
confirmLabel="Remover"
|
||||
destructive
|
||||
loading={removeMutation.isPending}
|
||||
onConfirm={() => removing && removeMutation.mutate(removing.id)}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
import { notFound } from 'next/navigation';
|
||||
import { ComponentesShowcase } from './showcase-client';
|
||||
|
||||
/** Rota de desenvolvimento (Etapa 12) — nunca acessível fora de dev. */
|
||||
export default function ComponentesPage() {
|
||||
if (process.env.NODE_ENV === 'production') {
|
||||
notFound();
|
||||
}
|
||||
|
||||
return <ComponentesShowcase />;
|
||||
}
|
||||
@@ -0,0 +1,408 @@
|
||||
'use client';
|
||||
|
||||
import * as React from 'react';
|
||||
import type { DateRange } from 'react-day-picker';
|
||||
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Textarea } from '@/components/ui/textarea';
|
||||
import { FormField } from '@/components/ui/form-field';
|
||||
import {
|
||||
InputGroup,
|
||||
InputGroupAddon,
|
||||
InputGroupInput,
|
||||
InputGroupText,
|
||||
} from '@/components/ui/input-group';
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from '@/components/ui/select';
|
||||
import { Combobox } from '@/components/ui/combobox';
|
||||
import { DatePicker, DateRangePicker } from '@/components/ui/date-picker';
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { STATUS_PILL_MAP, StatusPill, type BusinessStatus } from '@/components/ui/status-pill';
|
||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
|
||||
import { Skeleton, SkeletonCard, SkeletonText } from '@/components/ui/skeleton';
|
||||
import { EmptyState } from '@/components/ui/empty-state';
|
||||
import { DataPagination } from '@/components/ui/data-pagination';
|
||||
import { ResponsiveDialog } from '@/components/ui/responsive-dialog';
|
||||
import { DataTable, type DataTableColumn, type DataTableSort } from '@/components/ui/data-table';
|
||||
import { toast } from '@/lib/toast';
|
||||
|
||||
interface DemoCliente {
|
||||
id: string;
|
||||
nome: string;
|
||||
documento: string;
|
||||
telefone: string;
|
||||
cidade: string;
|
||||
status: BusinessStatus;
|
||||
valor: number;
|
||||
}
|
||||
|
||||
const DEMO_CLIENTES: DemoCliente[] = [
|
||||
{
|
||||
id: '1',
|
||||
nome: 'Ateliê Boa Vista Ltda',
|
||||
documento: '12.345.678/0001-90',
|
||||
telefone: '(11) 98765-4321',
|
||||
cidade: 'São Paulo/SP',
|
||||
status: 'ativo',
|
||||
valor: 4230.5,
|
||||
},
|
||||
{
|
||||
id: '2',
|
||||
nome: 'Comércio Silva & Filhos',
|
||||
documento: '98.765.432/0001-10',
|
||||
telefone: '(21) 91234-5678',
|
||||
cidade: 'Rio de Janeiro/RJ',
|
||||
status: 'inadimplente',
|
||||
valor: 1890,
|
||||
},
|
||||
{
|
||||
id: '3',
|
||||
nome: 'Padaria Pão Dourado',
|
||||
documento: '11.222.333/0001-44',
|
||||
telefone: '(31) 99887-6655',
|
||||
cidade: 'Belo Horizonte/MG',
|
||||
status: 'ativo',
|
||||
valor: 750.9,
|
||||
},
|
||||
{
|
||||
id: '4',
|
||||
nome: 'Distribuidora Nordeste',
|
||||
documento: '55.666.777/0001-88',
|
||||
telefone: '(85) 98111-2233',
|
||||
cidade: 'Fortaleza/CE',
|
||||
status: 'trial',
|
||||
valor: 0,
|
||||
},
|
||||
{
|
||||
id: '5',
|
||||
nome: 'Oficina Central Auto Peças',
|
||||
documento: '22.333.444/0001-55',
|
||||
telefone: '(41) 97654-3210',
|
||||
cidade: 'Curitiba/PR',
|
||||
status: 'suspenso',
|
||||
valor: 320,
|
||||
},
|
||||
];
|
||||
|
||||
const CLIENTE_COLUMNS: DataTableColumn<DemoCliente>[] = [
|
||||
{ id: 'nome', header: 'Cliente', primary: true, sortable: true, cell: (row) => row.nome },
|
||||
{ id: 'documento', header: 'Documento', cell: (row) => row.documento },
|
||||
{ id: 'telefone', header: 'Telefone', cell: (row) => row.telefone },
|
||||
{ id: 'cidade', header: 'Cidade', cell: (row) => row.cidade },
|
||||
{
|
||||
id: 'valor',
|
||||
header: 'Valor em aberto',
|
||||
sortable: true,
|
||||
className: 'text-right',
|
||||
cell: (row) => row.valor.toLocaleString('pt-BR', { style: 'currency', currency: 'BRL' }),
|
||||
},
|
||||
{
|
||||
id: 'status',
|
||||
header: 'Status',
|
||||
primary: true,
|
||||
cell: (row) => <StatusPill status={row.status} />,
|
||||
},
|
||||
];
|
||||
|
||||
const PRODUTO_OPTIONS = [
|
||||
{ value: 'p1', label: 'Consultoria mensal' },
|
||||
{ value: 'p2', label: 'Licença de software' },
|
||||
{ value: 'p3', label: 'Suporte técnico avançado' },
|
||||
{ value: 'p4', label: 'Treinamento presencial' },
|
||||
];
|
||||
|
||||
function Section({ title, children }: { title: string; children: React.ReactNode }) {
|
||||
return (
|
||||
<section className="flex flex-col gap-4 border-t border-border pt-8 first:border-0 first:pt-0">
|
||||
<h2 className="text-lg font-semibold text-foreground">{title}</h2>
|
||||
{children}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
export function ComponentesShowcase() {
|
||||
const [tableLoading, setTableLoading] = React.useState(false);
|
||||
const [tableEmpty, setTableEmpty] = React.useState(false);
|
||||
const [sort, setSort] = React.useState<DataTableSort | undefined>();
|
||||
const [page, setPage] = React.useState(1);
|
||||
const [dialogOpen, setDialogOpen] = React.useState(false);
|
||||
const [comboboxValue, setComboboxValue] = React.useState<string>();
|
||||
const [date, setDate] = React.useState<Date>();
|
||||
const [range, setRange] = React.useState<DateRange>();
|
||||
const [paginationDemoPage, setPaginationDemoPage] = React.useState(1);
|
||||
|
||||
const sortedData = React.useMemo(() => {
|
||||
if (!sort) return DEMO_CLIENTES;
|
||||
const factor = sort.direction === 'asc' ? 1 : -1;
|
||||
return [...DEMO_CLIENTES].sort((a, b) => {
|
||||
const av = a[sort.columnId as keyof DemoCliente];
|
||||
const bv = b[sort.columnId as keyof DemoCliente];
|
||||
if (typeof av === 'number' && typeof bv === 'number') return (av - bv) * factor;
|
||||
return String(av).localeCompare(String(bv)) * factor;
|
||||
});
|
||||
}, [sort]);
|
||||
|
||||
return (
|
||||
<main className="mx-auto flex max-w-5xl flex-col gap-10 p-6 pb-24 sm:p-10">
|
||||
<header className="flex flex-col gap-1">
|
||||
<p className="text-sm text-muted-foreground">/dev/componentes — Etapa 12</p>
|
||||
<h1 className="text-2xl font-semibold text-foreground">
|
||||
Design system — SeConectai Vendas
|
||||
</h1>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Rota só de desenvolvimento (404 em produção). Redimensione a janela para ver o
|
||||
comportamento responsivo.
|
||||
</p>
|
||||
</header>
|
||||
|
||||
<Section title="Button">
|
||||
<div className="flex flex-wrap items-center gap-3">
|
||||
<Button variant="primary">Primary</Button>
|
||||
<Button variant="secondary">Secondary</Button>
|
||||
<Button variant="destructive">Destructive</Button>
|
||||
<Button variant="ghost">Ghost</Button>
|
||||
<Button variant="outline">Outline</Button>
|
||||
</div>
|
||||
<div className="flex flex-wrap items-center gap-3">
|
||||
<Button size="sm">Small (denso, ex: linha de tabela)</Button>
|
||||
<Button size="md">Medium (padrão, 44px)</Button>
|
||||
<Button size="lg">Large</Button>
|
||||
</div>
|
||||
<div className="flex flex-wrap items-center gap-3">
|
||||
<Button loading>Salvando…</Button>
|
||||
<Button disabled>Desabilitado</Button>
|
||||
</div>
|
||||
</Section>
|
||||
|
||||
<Section title="Input / Textarea / FormField">
|
||||
<div className="grid max-w-md gap-4">
|
||||
<FormField label="Nome fantasia" helpText="Como o cliente é conhecido no dia a dia.">
|
||||
<Input placeholder="Ex: Padaria Pão Dourado" />
|
||||
</FormField>
|
||||
<FormField label="E-mail" error="E-mail inválido" required>
|
||||
<Input type="email" defaultValue="nao-e-um-email" />
|
||||
</FormField>
|
||||
<FormField label="Valor de venda">
|
||||
<InputGroup>
|
||||
<InputGroupAddon>
|
||||
<InputGroupText>R$</InputGroupText>
|
||||
</InputGroupAddon>
|
||||
<InputGroupInput placeholder="0,00" inputMode="decimal" />
|
||||
</InputGroup>
|
||||
</FormField>
|
||||
<FormField label="Observações">
|
||||
<Textarea placeholder="Notas internas sobre o cliente…" />
|
||||
</FormField>
|
||||
</div>
|
||||
</Section>
|
||||
|
||||
<Section title="Select / Combobox (busca)">
|
||||
<div className="grid max-w-md gap-4">
|
||||
<FormField label="Papel do usuário">
|
||||
<Select defaultValue="tenant_admin">
|
||||
<SelectTrigger>
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="tenant_admin">Administrador</SelectItem>
|
||||
<SelectItem value="vendedor">Vendedor</SelectItem>
|
||||
<SelectItem value="financeiro">Financeiro</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</FormField>
|
||||
<FormField label="Produto/serviço" helpText="Busca por nome ou SKU.">
|
||||
<Combobox
|
||||
options={PRODUTO_OPTIONS}
|
||||
value={comboboxValue}
|
||||
onChange={setComboboxValue}
|
||||
placeholder="Selecionar produto…"
|
||||
searchPlaceholder="Buscar produto…"
|
||||
/>
|
||||
</FormField>
|
||||
</div>
|
||||
</Section>
|
||||
|
||||
<Section title="DatePicker">
|
||||
<div className="grid max-w-md gap-4 sm:grid-cols-2">
|
||||
<FormField label="Data de vencimento">
|
||||
<DatePicker value={date} onChange={setDate} />
|
||||
</FormField>
|
||||
<FormField label="Período">
|
||||
<DateRangePicker value={range} onChange={setRange} />
|
||||
</FormField>
|
||||
</div>
|
||||
</Section>
|
||||
|
||||
<Section title="Table (responsiva — vira Cards abaixo de 768px)">
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<Button variant="outline" size="sm" onClick={() => setTableLoading((v) => !v)}>
|
||||
{tableLoading ? 'Parar loading' : 'Simular loading'}
|
||||
</Button>
|
||||
<Button variant="outline" size="sm" onClick={() => setTableEmpty((v) => !v)}>
|
||||
{tableEmpty ? 'Mostrar dados' : 'Simular vazio'}
|
||||
</Button>
|
||||
</div>
|
||||
<DataTable
|
||||
columns={CLIENTE_COLUMNS}
|
||||
data={tableEmpty ? [] : sortedData}
|
||||
keyField={(row) => row.id}
|
||||
loading={tableLoading}
|
||||
sort={sort}
|
||||
onSortChange={setSort}
|
||||
emptyTitle="Nenhum cliente cadastrado ainda"
|
||||
emptyDescription="Cadastre o primeiro cliente para começar a vender."
|
||||
emptyAction={<Button size="sm">Cadastrar cliente</Button>}
|
||||
rowActions={() => (
|
||||
<Button variant="ghost" size="sm">
|
||||
Ver
|
||||
</Button>
|
||||
)}
|
||||
pagination={{ page, limit: 5, total: 23, onPageChange: setPage }}
|
||||
/>
|
||||
</Section>
|
||||
|
||||
<Section title="Pagination (isolada)">
|
||||
<DataPagination
|
||||
page={paginationDemoPage}
|
||||
limit={10}
|
||||
total={97}
|
||||
onPageChange={setPaginationDemoPage}
|
||||
/>
|
||||
</Section>
|
||||
|
||||
<Section title="Modal / Sheet responsivo">
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Vira modal centralizado no desktop e bottom sheet no mobile (mesmo breakpoint da Table).
|
||||
</p>
|
||||
<Button className="w-fit" onClick={() => setDialogOpen(true)}>
|
||||
Abrir exemplo
|
||||
</Button>
|
||||
<ResponsiveDialog
|
||||
open={dialogOpen}
|
||||
onOpenChange={setDialogOpen}
|
||||
title="Cadastro rápido de cliente"
|
||||
description="Usado no fluxo de nova venda quando o cliente ainda não existe."
|
||||
footer={
|
||||
<>
|
||||
<Button variant="outline" onClick={() => setDialogOpen(false)}>
|
||||
Cancelar
|
||||
</Button>
|
||||
<Button onClick={() => setDialogOpen(false)}>Salvar</Button>
|
||||
</>
|
||||
}
|
||||
>
|
||||
<div className="flex flex-col gap-4 px-4 pb-4 sm:px-0 sm:pb-0">
|
||||
<FormField label="Nome">
|
||||
<Input placeholder="Nome do cliente" />
|
||||
</FormField>
|
||||
<FormField label="Telefone/WhatsApp">
|
||||
<Input placeholder="(00) 00000-0000" />
|
||||
</FormField>
|
||||
</div>
|
||||
</ResponsiveDialog>
|
||||
</Section>
|
||||
|
||||
<Section title="Toast">
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => toast.success('Cliente salvo com sucesso.')}
|
||||
>
|
||||
Sucesso
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => toast.error('Não foi possível salvar. Tente novamente.')}
|
||||
>
|
||||
Erro
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => toast.warning('Limite do plano quase atingido.')}
|
||||
>
|
||||
Aviso
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => toast.info('Sessão renovada automaticamente.')}
|
||||
>
|
||||
Info
|
||||
</Button>
|
||||
</div>
|
||||
</Section>
|
||||
|
||||
<Section title="Badge / StatusPill">
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<Badge>Default</Badge>
|
||||
<Badge variant="secondary">Secondary</Badge>
|
||||
<Badge variant="destructive">Destructive</Badge>
|
||||
<Badge variant="outline">Outline</Badge>
|
||||
</div>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{(Object.keys(STATUS_PILL_MAP) as BusinessStatus[]).map((status) => (
|
||||
<StatusPill key={status} status={status} />
|
||||
))}
|
||||
</div>
|
||||
</Section>
|
||||
|
||||
<Section title="Card">
|
||||
<Card className="max-w-sm">
|
||||
<CardHeader>
|
||||
<CardTitle>Total recebido no mês</CardTitle>
|
||||
<CardDescription>Atualizado há 2 minutos</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<p className="text-2xl font-semibold tabular-nums text-foreground">R$ 18.420,00</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</Section>
|
||||
|
||||
<Section title="EmptyState">
|
||||
<EmptyState
|
||||
title="Nenhuma venda registrada"
|
||||
description="As vendas confirmadas aparecerão aqui."
|
||||
action={<Button size="sm">Nova venda</Button>}
|
||||
/>
|
||||
</Section>
|
||||
|
||||
<Section title="Skeleton">
|
||||
<div className="flex max-w-md flex-col gap-3">
|
||||
<SkeletonText />
|
||||
<SkeletonText className="w-2/3" />
|
||||
<SkeletonCard />
|
||||
<Skeleton className="size-11 rounded-full" />
|
||||
</div>
|
||||
</Section>
|
||||
|
||||
<Section title="Tabs">
|
||||
<Tabs defaultValue="itens" className="max-w-md">
|
||||
<TabsList>
|
||||
<TabsTrigger value="itens">Itens</TabsTrigger>
|
||||
<TabsTrigger value="parcelas">Parcelas</TabsTrigger>
|
||||
<TabsTrigger value="historico">Histórico</TabsTrigger>
|
||||
</TabsList>
|
||||
<TabsContent value="itens" className="text-sm text-muted-foreground">
|
||||
Lista de itens da venda.
|
||||
</TabsContent>
|
||||
<TabsContent value="parcelas" className="text-sm text-muted-foreground">
|
||||
Lista de parcelas geradas.
|
||||
</TabsContent>
|
||||
<TabsContent value="historico" className="text-sm text-muted-foreground">
|
||||
Histórico de mudanças de status.
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
</Section>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
'use client';
|
||||
|
||||
import { useEffect, useState } from 'react';
|
||||
import { apiClient, ApiError } from '@/lib/api/client';
|
||||
|
||||
interface HealthStatus {
|
||||
status: 'ok' | 'error';
|
||||
timestamp: string;
|
||||
database: 'up' | 'down';
|
||||
}
|
||||
|
||||
type DiagnosticoState =
|
||||
| { phase: 'loading' }
|
||||
| { phase: 'success'; data: HealthStatus }
|
||||
| { phase: 'error'; message: string };
|
||||
|
||||
/**
|
||||
* Rota temporária para validar a integração frontend↔backend de ponta a
|
||||
* ponta (Etapa 11). Pode ser removida quando não fizer mais falta.
|
||||
*/
|
||||
export default function DiagnosticoPage() {
|
||||
const [state, setState] = useState<DiagnosticoState>({ phase: 'loading' });
|
||||
|
||||
useEffect(() => {
|
||||
apiClient
|
||||
.get<HealthStatus>('/health')
|
||||
.then((data) => setState({ phase: 'success', data }))
|
||||
.catch((err: unknown) => {
|
||||
const message = err instanceof ApiError ? err.message : 'Falha ao conectar com a API.';
|
||||
setState({ phase: 'error', message });
|
||||
});
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<main className="flex min-h-screen flex-col items-center justify-center gap-4 p-8">
|
||||
<h1 className="text-xl font-semibold text-neutral-950">Diagnóstico de conexão com a API</h1>
|
||||
|
||||
{state.phase === 'loading' && <p className="text-neutral-500">Consultando GET /health…</p>}
|
||||
|
||||
{state.phase === 'success' && (
|
||||
<div className="tabular-nums rounded-lg border border-neutral-200 bg-surface p-4 text-sm">
|
||||
<p>
|
||||
Status:{' '}
|
||||
<span className={state.data.status === 'ok' ? 'text-success' : 'text-danger'}>
|
||||
{state.data.status}
|
||||
</span>
|
||||
</p>
|
||||
<p>
|
||||
Banco de dados:{' '}
|
||||
<span className={state.data.database === 'up' ? 'text-success' : 'text-danger'}>
|
||||
{state.data.database}
|
||||
</span>
|
||||
</p>
|
||||
<p>Timestamp: {state.data.timestamp}</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{state.phase === 'error' && (
|
||||
<p className="rounded-lg border border-danger bg-surface p-4 text-sm text-danger">
|
||||
{state.message}
|
||||
</p>
|
||||
)}
|
||||
</main>
|
||||
);
|
||||
}
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 25 KiB |
@@ -0,0 +1,129 @@
|
||||
@import 'tailwindcss';
|
||||
@import '../styles/tokens.css';
|
||||
@import 'tw-animate-css';
|
||||
@import 'shadcn/tailwind.css';
|
||||
|
||||
@custom-variant dark (&:is(.dark *));
|
||||
|
||||
@theme inline {
|
||||
--color-sidebar-ring: var(--sidebar-ring);
|
||||
--color-sidebar-border: var(--sidebar-border);
|
||||
--color-sidebar-accent-foreground: var(--sidebar-accent-foreground);
|
||||
--color-sidebar-accent: var(--sidebar-accent);
|
||||
--color-sidebar-primary-foreground: var(--sidebar-primary-foreground);
|
||||
--color-sidebar-primary: var(--sidebar-primary);
|
||||
--color-sidebar-foreground: var(--sidebar-foreground);
|
||||
--color-sidebar: var(--sidebar);
|
||||
--color-chart-5: var(--chart-5);
|
||||
--color-chart-4: var(--chart-4);
|
||||
--color-chart-3: var(--chart-3);
|
||||
--color-chart-2: var(--chart-2);
|
||||
--color-chart-1: var(--chart-1);
|
||||
--color-ring: var(--ring);
|
||||
--color-input: var(--input);
|
||||
--color-border: var(--border);
|
||||
--color-destructive-foreground: var(--destructive-foreground);
|
||||
--color-destructive: var(--destructive);
|
||||
--color-accent-foreground: var(--accent-foreground);
|
||||
--color-accent: var(--accent);
|
||||
--color-muted-foreground: var(--muted-foreground);
|
||||
--color-muted: var(--muted);
|
||||
--color-secondary-foreground: var(--secondary-foreground);
|
||||
--color-secondary: var(--secondary);
|
||||
--color-primary-foreground: var(--primary-foreground);
|
||||
--color-primary: var(--primary);
|
||||
--color-popover-foreground: var(--popover-foreground);
|
||||
--color-popover: var(--popover);
|
||||
--color-card-foreground: var(--card-foreground);
|
||||
--color-card: var(--card);
|
||||
--color-foreground: var(--foreground);
|
||||
--color-background: var(--background);
|
||||
--radius-sm: calc(var(--radius) * 0.6);
|
||||
--radius-md: calc(var(--radius) * 0.8);
|
||||
--radius-lg: var(--radius);
|
||||
--radius-xl: calc(var(--radius) * 1.4);
|
||||
--radius-2xl: calc(var(--radius) * 1.8);
|
||||
--radius-3xl: calc(var(--radius) * 2.2);
|
||||
--radius-4xl: calc(var(--radius) * 2.6);
|
||||
}
|
||||
|
||||
/*
|
||||
* Ponte shadcn/ui → tokens do projeto (styles/tokens.css). Em vez da
|
||||
* paleta oklch neutra que o `shadcn init` gera por padrão, cada variável
|
||||
* que os componentes shadcn consomem aponta para os tokens definidos na
|
||||
* Etapa 11 — assim customizar a cor de marca (--color-primary, dinâmica
|
||||
* por tenant a partir da Etapa 13) muda os componentes automaticamente,
|
||||
* sem precisar editar cada um.
|
||||
*/
|
||||
:root {
|
||||
--background: var(--neutral-50);
|
||||
--foreground: var(--neutral-950);
|
||||
--card: var(--surface);
|
||||
--card-foreground: var(--neutral-950);
|
||||
--popover: var(--surface);
|
||||
--popover-foreground: var(--neutral-950);
|
||||
--primary: var(--color-primary);
|
||||
--primary-foreground: #ffffff;
|
||||
--secondary: var(--neutral-50);
|
||||
--secondary-foreground: var(--neutral-950);
|
||||
--muted: var(--neutral-50);
|
||||
--muted-foreground: var(--neutral-500);
|
||||
--accent: var(--neutral-50);
|
||||
--accent-foreground: var(--neutral-950);
|
||||
--destructive: var(--danger);
|
||||
--destructive-foreground: #ffffff;
|
||||
--border: var(--neutral-200);
|
||||
--input: var(--neutral-200);
|
||||
--ring: var(--color-primary);
|
||||
--radius: 0.625rem;
|
||||
--chart-1: var(--color-primary);
|
||||
--chart-2: var(--success);
|
||||
--chart-3: var(--warning);
|
||||
--chart-4: var(--danger);
|
||||
--chart-5: var(--neutral-500);
|
||||
--sidebar: var(--surface);
|
||||
--sidebar-foreground: var(--neutral-950);
|
||||
--sidebar-primary: var(--color-primary);
|
||||
--sidebar-primary-foreground: #ffffff;
|
||||
--sidebar-accent: var(--neutral-50);
|
||||
--sidebar-accent-foreground: var(--neutral-950);
|
||||
--sidebar-border: var(--neutral-200);
|
||||
--sidebar-ring: var(--color-primary);
|
||||
}
|
||||
|
||||
@layer base {
|
||||
* {
|
||||
@apply border-border outline-ring/50;
|
||||
}
|
||||
body {
|
||||
@apply bg-background text-foreground;
|
||||
}
|
||||
html {
|
||||
@apply font-sans;
|
||||
}
|
||||
|
||||
/* Fallback de foco para elementos nativos que não passam por um
|
||||
componente shadcn (esses já têm seu próprio focus-visible:ring). */
|
||||
a:focus-visible,
|
||||
button:focus-visible,
|
||||
input:focus-visible,
|
||||
select:focus-visible,
|
||||
textarea:focus-visible,
|
||||
[tabindex]:focus-visible {
|
||||
outline: 2px solid var(--ring);
|
||||
outline-offset: 2px;
|
||||
}
|
||||
}
|
||||
|
||||
/* `prefers-reduced-motion` (Etapa 12, obrigatório) — aplicado globalmente
|
||||
para cobrir qualquer animação/transição, independente da biblioteca. */
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
*,
|
||||
*::before,
|
||||
*::after {
|
||||
animation-duration: 0.01ms !important;
|
||||
animation-iteration-count: 1 !important;
|
||||
transition-duration: 0.01ms !important;
|
||||
scroll-behavior: auto !important;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
import type { Metadata } from 'next';
|
||||
import { Inter } from 'next/font/google';
|
||||
import './globals.css';
|
||||
import { Toaster } from '@/components/ui/sonner';
|
||||
import { AuthProvider } from '@/lib/auth/auth-context';
|
||||
import { QueryProvider } from '@/lib/query/query-provider';
|
||||
|
||||
const inter = Inter({
|
||||
variable: '--font-inter',
|
||||
subsets: ['latin'],
|
||||
});
|
||||
|
||||
export const metadata: Metadata = {
|
||||
title: 'SeConectai Vendas',
|
||||
description: 'CRM/vendas multi-tenant SeConectai',
|
||||
};
|
||||
|
||||
export default function RootLayout({
|
||||
children,
|
||||
}: Readonly<{
|
||||
children: React.ReactNode;
|
||||
}>) {
|
||||
return (
|
||||
<html lang="pt-BR">
|
||||
<body className={`${inter.variable} font-sans antialiased`}>
|
||||
<QueryProvider>
|
||||
<AuthProvider>{children}</AuthProvider>
|
||||
<Toaster position="top-center" />
|
||||
</QueryProvider>
|
||||
</body>
|
||||
</html>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,209 @@
|
||||
'use client';
|
||||
|
||||
import * as React from 'react';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import type { DateRange } from 'react-day-picker';
|
||||
|
||||
import {
|
||||
ALERT_LOG_STATUSES,
|
||||
listAlertLogs,
|
||||
type AlertLog,
|
||||
type AlertLogStatus,
|
||||
} from '@/lib/api/alert-logs';
|
||||
import { CANAIS_TEMPLATE, CANAL_TEMPLATE_LABEL, TIPO_TEMPLATE_LABEL } from '@/lib/api/alert-templates';
|
||||
import type { CanalTemplate } from '@/lib/api/alert-templates';
|
||||
import { formatDateTime } from '@/lib/format';
|
||||
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { DataTable, type DataTableColumn } from '@/components/ui/data-table';
|
||||
import { DateRangePicker } from '@/components/ui/date-picker';
|
||||
import { ResponsiveDialog } from '@/components/ui/responsive-dialog';
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
|
||||
import { Separator } from '@/components/ui/separator';
|
||||
|
||||
const STATUS_LABEL: Record<AlertLogStatus, string> = {
|
||||
enviado: 'Enviado',
|
||||
entregue: 'Entregue',
|
||||
lido: 'Lido',
|
||||
falhou: 'Falhou',
|
||||
};
|
||||
|
||||
const STATUS_TONE: Record<AlertLogStatus, 'default' | 'destructive' | 'outline'> = {
|
||||
enviado: 'outline',
|
||||
entregue: 'default',
|
||||
lido: 'default',
|
||||
falhou: 'destructive',
|
||||
};
|
||||
|
||||
const STATUS_OPTIONS: { value: AlertLogStatus | 'todos'; label: string }[] = [
|
||||
{ value: 'todos', label: 'Todos os status' },
|
||||
...ALERT_LOG_STATUSES.map((s) => ({ value: s, label: STATUS_LABEL[s] })),
|
||||
];
|
||||
|
||||
const CANAL_OPTIONS: { value: CanalTemplate | 'todos'; label: string }[] = [
|
||||
{ value: 'todos', label: 'Todos os canais' },
|
||||
...CANAIS_TEMPLATE.map((c) => ({ value: c, label: CANAL_TEMPLATE_LABEL[c] })),
|
||||
];
|
||||
|
||||
const LIMIT = 20;
|
||||
|
||||
export default function AlertLogsPage() {
|
||||
const [canal, setCanal] = React.useState<CanalTemplate | 'todos'>('todos');
|
||||
const [status, setStatus] = React.useState<AlertLogStatus | 'todos'>('todos');
|
||||
const [periodo, setPeriodo] = React.useState<DateRange | undefined>();
|
||||
const [page, setPage] = React.useState(1);
|
||||
const [detail, setDetail] = React.useState<AlertLog | null>(null);
|
||||
|
||||
const { data, isLoading } = useQuery({
|
||||
queryKey: [
|
||||
'master',
|
||||
'alert-logs',
|
||||
{ canal, status, de: periodo?.from?.toISOString(), ate: periodo?.to?.toISOString(), page },
|
||||
],
|
||||
queryFn: () =>
|
||||
listAlertLogs({
|
||||
canal: canal === 'todos' ? undefined : canal,
|
||||
status: status === 'todos' ? undefined : status,
|
||||
data_inicio: periodo?.from?.toISOString(),
|
||||
data_fim: periodo?.to?.toISOString(),
|
||||
page,
|
||||
limit: LIMIT,
|
||||
}),
|
||||
placeholderData: (prev) => prev,
|
||||
});
|
||||
|
||||
const columns: DataTableColumn<AlertLog>[] = [
|
||||
{
|
||||
id: 'tipo',
|
||||
header: 'Tipo',
|
||||
primary: true,
|
||||
cell: (row) => (row.template ? TIPO_TEMPLATE_LABEL[row.template.tipo] : '—'),
|
||||
},
|
||||
{ id: 'canal', header: 'Canal', primary: true, cell: (row) => CANAL_TEMPLATE_LABEL[row.canal] },
|
||||
{
|
||||
id: 'status',
|
||||
header: 'Status',
|
||||
cell: (row) => <Badge variant={STATUS_TONE[row.status]}>{STATUS_LABEL[row.status]}</Badge>,
|
||||
},
|
||||
{ id: 'enviado_em', header: 'Enviado em', cell: (row) => formatDateTime(row.enviado_em) },
|
||||
];
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-6">
|
||||
<div>
|
||||
<h1 className="text-xl font-semibold text-foreground">Logs de alerta</h1>
|
||||
<p className="text-sm text-muted-foreground">Histórico de envios de WhatsApp/e-mail</p>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col gap-3 sm:flex-row sm:flex-wrap sm:items-center">
|
||||
<Select
|
||||
value={canal}
|
||||
onValueChange={(value) => {
|
||||
setCanal(value as CanalTemplate | 'todos');
|
||||
setPage(1);
|
||||
}}
|
||||
>
|
||||
<SelectTrigger className="w-full sm:w-44" aria-label="Filtrar por canal">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{CANAL_OPTIONS.map((opt) => (
|
||||
<SelectItem key={opt.value} value={opt.value}>
|
||||
{opt.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<Select
|
||||
value={status}
|
||||
onValueChange={(value) => {
|
||||
setStatus(value as AlertLogStatus | 'todos');
|
||||
setPage(1);
|
||||
}}
|
||||
>
|
||||
<SelectTrigger className="w-full sm:w-44" aria-label="Filtrar por status">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{STATUS_OPTIONS.map((opt) => (
|
||||
<SelectItem key={opt.value} value={opt.value}>
|
||||
{opt.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<DateRangePicker
|
||||
value={periodo}
|
||||
onChange={(range) => {
|
||||
setPeriodo(range);
|
||||
setPage(1);
|
||||
}}
|
||||
placeholder="Período"
|
||||
className="w-full sm:w-64"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<DataTable
|
||||
columns={columns}
|
||||
data={data?.data ?? []}
|
||||
keyField={(row) => row.id}
|
||||
loading={isLoading}
|
||||
emptyTitle="Nenhum log encontrado"
|
||||
emptyDescription="Ajuste os filtros de período/canal/status."
|
||||
onRowClick={(row) => setDetail(row)}
|
||||
rowActions={() => (
|
||||
<Button variant="ghost" size="sm">
|
||||
Ver detalhes
|
||||
</Button>
|
||||
)}
|
||||
pagination={
|
||||
data ? { page: data.meta.page, limit: data.meta.limit, total: data.meta.total, onPageChange: setPage } : undefined
|
||||
}
|
||||
/>
|
||||
|
||||
<ResponsiveDialog
|
||||
open={detail !== null}
|
||||
onOpenChange={(open) => !open && setDetail(null)}
|
||||
title="Detalhe do envio"
|
||||
description={detail ? formatDateTime(detail.enviado_em) : undefined}
|
||||
>
|
||||
{detail && (
|
||||
<div className="flex flex-col gap-4 px-4 pb-4 sm:px-0 sm:pb-0">
|
||||
<div className="flex flex-wrap gap-4 text-sm">
|
||||
<div>
|
||||
<p className="text-muted-foreground">Tipo</p>
|
||||
<p className="font-medium text-foreground">
|
||||
{detail.template ? TIPO_TEMPLATE_LABEL[detail.template.tipo] : '—'}
|
||||
</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-muted-foreground">Canal</p>
|
||||
<p className="font-medium text-foreground">{CANAL_TEMPLATE_LABEL[detail.canal]}</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-muted-foreground">Status</p>
|
||||
<Badge variant={STATUS_TONE[detail.status]}>{STATUS_LABEL[detail.status]}</Badge>
|
||||
</div>
|
||||
</div>
|
||||
<Separator />
|
||||
<div>
|
||||
<p className="mb-1 text-sm font-medium text-foreground">Conteúdo enviado</p>
|
||||
<p className="rounded-lg border border-border bg-muted/50 p-3 text-sm whitespace-pre-wrap">
|
||||
{detail.conteudo_enviado || '—'}
|
||||
</p>
|
||||
</div>
|
||||
{detail.erro && (
|
||||
<div>
|
||||
<p className="mb-1 text-sm font-medium text-danger">Erro</p>
|
||||
<p className="rounded-lg border border-danger/30 bg-danger/10 p-3 text-sm whitespace-pre-wrap text-danger">
|
||||
{detail.erro}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</ResponsiveDialog>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,349 @@
|
||||
'use client';
|
||||
|
||||
import * as React from 'react';
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { zodResolver } from '@hookform/resolvers/zod';
|
||||
import { Plus } from 'lucide-react';
|
||||
|
||||
import {
|
||||
CANAL_TEMPLATE_LABEL,
|
||||
CANAIS_TEMPLATE,
|
||||
PLACEHOLDERS_POR_TIPO,
|
||||
TIPO_TEMPLATE_LABEL,
|
||||
TIPOS_TEMPLATE,
|
||||
createAlertTemplate,
|
||||
deleteAlertTemplate,
|
||||
listAlertTemplates,
|
||||
updateAlertTemplate,
|
||||
type AlertTemplate,
|
||||
type CanalTemplate,
|
||||
type TipoTemplate,
|
||||
} from '@/lib/api/alert-templates';
|
||||
import { alertTemplateSchema, type AlertTemplateFormValues } from '@/lib/validators/alert-templates';
|
||||
import { ApiError } from '@/lib/api/client';
|
||||
import { toast } from '@/lib/toast';
|
||||
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { DataTable, type DataTableColumn } from '@/components/ui/data-table';
|
||||
import { FormField } from '@/components/ui/form-field';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { ResponsiveDialog } from '@/components/ui/responsive-dialog';
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
|
||||
import { Textarea } from '@/components/ui/textarea';
|
||||
import { ConfirmDialog } from '@/components/domain/confirm-dialog';
|
||||
|
||||
const TIPO_OPTIONS: { value: TipoTemplate | 'todos'; label: string }[] = [
|
||||
{ value: 'todos', label: 'Todos os tipos' },
|
||||
...TIPOS_TEMPLATE.map((tipo) => ({ value: tipo, label: TIPO_TEMPLATE_LABEL[tipo] })),
|
||||
];
|
||||
|
||||
const CANAL_OPTIONS: { value: CanalTemplate | 'todos'; label: string }[] = [
|
||||
{ value: 'todos', label: 'Todos os canais' },
|
||||
...CANAIS_TEMPLATE.map((canal) => ({ value: canal, label: CANAL_TEMPLATE_LABEL[canal] })),
|
||||
];
|
||||
|
||||
const LIMIT = 20;
|
||||
|
||||
export default function AlertTemplatesPage() {
|
||||
const queryClient = useQueryClient();
|
||||
const [tipo, setTipo] = React.useState<TipoTemplate | 'todos'>('todos');
|
||||
const [canal, setCanal] = React.useState<CanalTemplate | 'todos'>('todos');
|
||||
const [page, setPage] = React.useState(1);
|
||||
|
||||
const [editing, setEditing] = React.useState<AlertTemplate | null>(null);
|
||||
const [formOpen, setFormOpen] = React.useState(false);
|
||||
const [deleting, setDeleting] = React.useState<AlertTemplate | null>(null);
|
||||
|
||||
const { data, isLoading } = useQuery({
|
||||
queryKey: ['master', 'alert-templates', { tipo, canal, page }],
|
||||
queryFn: () =>
|
||||
listAlertTemplates({
|
||||
tipo: tipo === 'todos' ? undefined : tipo,
|
||||
canal: canal === 'todos' ? undefined : canal,
|
||||
page,
|
||||
limit: LIMIT,
|
||||
}),
|
||||
placeholderData: (prev) => prev,
|
||||
});
|
||||
|
||||
const form = useForm<AlertTemplateFormValues>({ resolver: zodResolver(alertTemplateSchema) });
|
||||
const corpoFieldRef = React.useRef<HTMLTextAreaElement | null>(null);
|
||||
const { ref: corpoRegisterRef, ...corpoRegister } = form.register('corpo');
|
||||
const watchedTipo = form.watch('tipo');
|
||||
const watchedCanal = form.watch('canal');
|
||||
|
||||
function openCreate() {
|
||||
setEditing(null);
|
||||
form.reset({ tipo: 'mensalidade_tenant', canal: 'whatsapp', assunto: '', corpo: '', ativo: true });
|
||||
setFormOpen(true);
|
||||
}
|
||||
|
||||
function openEdit(template: AlertTemplate) {
|
||||
setEditing(template);
|
||||
form.reset({
|
||||
tipo: template.tipo,
|
||||
canal: template.canal,
|
||||
assunto: template.assunto ?? '',
|
||||
corpo: template.corpo,
|
||||
ativo: template.ativo,
|
||||
});
|
||||
setFormOpen(true);
|
||||
}
|
||||
|
||||
function insertPlaceholder(chave: string) {
|
||||
const token = `{{${chave}}}`;
|
||||
const el = corpoFieldRef.current;
|
||||
const current = form.getValues('corpo') ?? '';
|
||||
|
||||
if (!el) {
|
||||
form.setValue('corpo', current + token, { shouldValidate: true });
|
||||
return;
|
||||
}
|
||||
|
||||
const start = el.selectionStart ?? current.length;
|
||||
const end = el.selectionEnd ?? current.length;
|
||||
const next = current.slice(0, start) + token + current.slice(end);
|
||||
form.setValue('corpo', next, { shouldValidate: true });
|
||||
|
||||
requestAnimationFrame(() => {
|
||||
el.focus();
|
||||
const pos = start + token.length;
|
||||
el.setSelectionRange(pos, pos);
|
||||
});
|
||||
}
|
||||
|
||||
const saveMutation = useMutation({
|
||||
mutationFn: (values: AlertTemplateFormValues) => {
|
||||
const payload = { ...values, assunto: values.canal === 'email' ? values.assunto : undefined };
|
||||
return editing ? updateAlertTemplate(editing.id, payload) : createAlertTemplate(payload);
|
||||
},
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['master', 'alert-templates'] });
|
||||
toast.success(editing ? 'Template atualizado.' : 'Template criado.');
|
||||
setFormOpen(false);
|
||||
},
|
||||
onError: (err) => {
|
||||
toast.error(err instanceof ApiError ? err.message : 'Não foi possível salvar o template.');
|
||||
},
|
||||
});
|
||||
|
||||
const deleteMutation = useMutation({
|
||||
mutationFn: (id: string) => deleteAlertTemplate(id),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['master', 'alert-templates'] });
|
||||
toast.success('Template desativado.');
|
||||
setDeleting(null);
|
||||
},
|
||||
onError: (err) => {
|
||||
toast.error(err instanceof ApiError ? err.message : 'Não foi possível desativar o template.');
|
||||
setDeleting(null);
|
||||
},
|
||||
});
|
||||
|
||||
const columns: DataTableColumn<AlertTemplate>[] = [
|
||||
{ id: 'tipo', header: 'Tipo', primary: true, cell: (row) => TIPO_TEMPLATE_LABEL[row.tipo] },
|
||||
{ id: 'canal', header: 'Canal', primary: true, cell: (row) => CANAL_TEMPLATE_LABEL[row.canal] },
|
||||
{
|
||||
id: 'corpo',
|
||||
header: 'Prévia',
|
||||
cell: (row) => <span className="line-clamp-1 text-muted-foreground">{row.corpo}</span>,
|
||||
},
|
||||
{
|
||||
id: 'status',
|
||||
header: 'Status',
|
||||
cell: (row) => <Badge variant={row.ativo ? 'default' : 'outline'}>{row.ativo ? 'Ativo' : 'Inativo'}</Badge>,
|
||||
},
|
||||
];
|
||||
|
||||
const placeholders = watchedTipo ? PLACEHOLDERS_POR_TIPO[watchedTipo] : [];
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-6">
|
||||
<div className="flex flex-wrap items-center justify-between gap-4">
|
||||
<div>
|
||||
<h1 className="text-xl font-semibold text-foreground">Templates de alerta</h1>
|
||||
<p className="text-sm text-muted-foreground">Padrões de mensagem da plataforma</p>
|
||||
</div>
|
||||
<Button onClick={openCreate}>
|
||||
<Plus /> Novo template
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col gap-3 sm:flex-row sm:items-center">
|
||||
<Select
|
||||
value={tipo}
|
||||
onValueChange={(value) => {
|
||||
setTipo(value as TipoTemplate | 'todos');
|
||||
setPage(1);
|
||||
}}
|
||||
>
|
||||
<SelectTrigger className="w-full sm:w-56" aria-label="Filtrar por tipo">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{TIPO_OPTIONS.map((opt) => (
|
||||
<SelectItem key={opt.value} value={opt.value}>
|
||||
{opt.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<Select
|
||||
value={canal}
|
||||
onValueChange={(value) => {
|
||||
setCanal(value as CanalTemplate | 'todos');
|
||||
setPage(1);
|
||||
}}
|
||||
>
|
||||
<SelectTrigger className="w-full sm:w-44" aria-label="Filtrar por canal">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{CANAL_OPTIONS.map((opt) => (
|
||||
<SelectItem key={opt.value} value={opt.value}>
|
||||
{opt.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
<DataTable
|
||||
columns={columns}
|
||||
data={data?.data ?? []}
|
||||
keyField={(row) => row.id}
|
||||
loading={isLoading}
|
||||
emptyTitle="Nenhum template cadastrado"
|
||||
emptyAction={
|
||||
<Button size="sm" onClick={openCreate}>
|
||||
Novo template
|
||||
</Button>
|
||||
}
|
||||
rowActions={(row) => (
|
||||
<>
|
||||
<Button variant="ghost" size="sm" onClick={() => openEdit(row)}>
|
||||
Editar
|
||||
</Button>
|
||||
<Button variant="ghost" size="sm" onClick={() => setDeleting(row)}>
|
||||
Desativar
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
pagination={
|
||||
data ? { page: data.meta.page, limit: data.meta.limit, total: data.meta.total, onPageChange: setPage } : undefined
|
||||
}
|
||||
/>
|
||||
|
||||
<ResponsiveDialog
|
||||
open={formOpen}
|
||||
onOpenChange={setFormOpen}
|
||||
title={editing ? 'Editar template' : 'Novo template'}
|
||||
className="sm:max-w-2xl"
|
||||
footer={
|
||||
<>
|
||||
<Button variant="outline" onClick={() => setFormOpen(false)}>
|
||||
Cancelar
|
||||
</Button>
|
||||
<Button
|
||||
loading={saveMutation.isPending}
|
||||
onClick={form.handleSubmit((values) => saveMutation.mutate(values))}
|
||||
>
|
||||
Salvar
|
||||
</Button>
|
||||
</>
|
||||
}
|
||||
>
|
||||
<form
|
||||
className="flex flex-col gap-4 px-4 pb-4 sm:px-0 sm:pb-0"
|
||||
onSubmit={form.handleSubmit((values) => saveMutation.mutate(values))}
|
||||
>
|
||||
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
|
||||
<FormField label="Tipo" id="tipo" error={form.formState.errors.tipo?.message} required>
|
||||
<Select
|
||||
value={watchedTipo}
|
||||
onValueChange={(value) => form.setValue('tipo', value as TipoTemplate, { shouldValidate: true })}
|
||||
>
|
||||
<SelectTrigger id="tipo" className="w-full">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{TIPOS_TEMPLATE.map((t) => (
|
||||
<SelectItem key={t} value={t}>
|
||||
{TIPO_TEMPLATE_LABEL[t]}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</FormField>
|
||||
<FormField label="Canal" id="canal" error={form.formState.errors.canal?.message} required>
|
||||
<Select
|
||||
value={watchedCanal}
|
||||
onValueChange={(value) => form.setValue('canal', value as CanalTemplate, { shouldValidate: true })}
|
||||
>
|
||||
<SelectTrigger id="canal" className="w-full">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{CANAIS_TEMPLATE.map((c) => (
|
||||
<SelectItem key={c} value={c}>
|
||||
{CANAL_TEMPLATE_LABEL[c]}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</FormField>
|
||||
</div>
|
||||
|
||||
{watchedCanal === 'email' && (
|
||||
<FormField label="Assunto" error={form.formState.errors.assunto?.message} required>
|
||||
<Input {...form.register('assunto')} />
|
||||
</FormField>
|
||||
)}
|
||||
|
||||
<div className="grid grid-cols-1 gap-4 sm:grid-cols-[1fr_220px]">
|
||||
<FormField label="Corpo da mensagem" error={form.formState.errors.corpo?.message} required>
|
||||
<Textarea
|
||||
rows={8}
|
||||
{...corpoRegister}
|
||||
ref={(el) => {
|
||||
corpoRegisterRef(el);
|
||||
corpoFieldRef.current = el;
|
||||
}}
|
||||
/>
|
||||
</FormField>
|
||||
<div className="flex flex-col gap-2">
|
||||
<p className="text-xs font-medium text-muted-foreground">Placeholders disponíveis</p>
|
||||
<div className="flex flex-col gap-1.5 overflow-y-auto rounded-lg border border-border p-2 sm:max-h-56">
|
||||
{placeholders.map((p) => (
|
||||
<button
|
||||
key={p.chave}
|
||||
type="button"
|
||||
onClick={() => insertPlaceholder(p.chave)}
|
||||
title={p.descricao}
|
||||
className="rounded-md px-2 py-1.5 text-left text-xs hover:bg-muted"
|
||||
>
|
||||
<code className="font-mono font-medium text-primary-on-light">{`{{${p.chave}}}`}</code>
|
||||
<p className="text-muted-foreground">{p.descricao}</p>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
</ResponsiveDialog>
|
||||
|
||||
<ConfirmDialog
|
||||
open={deleting !== null}
|
||||
onOpenChange={(open) => !open && setDeleting(null)}
|
||||
title="Desativar template?"
|
||||
description="O template deixa de ser usado nos disparos automáticos, mas continua no histórico."
|
||||
confirmLabel="Desativar"
|
||||
destructive
|
||||
loading={deleteMutation.isPending}
|
||||
onConfirm={() => deleting && deleteMutation.mutate(deleting.id)}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
'use client';
|
||||
|
||||
import * as React from 'react';
|
||||
import { useMutation, useQuery } from '@tanstack/react-query';
|
||||
import { KeyRound } from 'lucide-react';
|
||||
|
||||
import { listMasterAdmins } from '@/lib/api/master-admins';
|
||||
import { apiClient, ApiError } from '@/lib/api/client';
|
||||
import { useAuth } from '@/lib/auth/auth-context';
|
||||
import { formatDateTime } from '@/lib/format';
|
||||
import { toast } from '@/lib/toast';
|
||||
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { Skeleton } from '@/components/ui/skeleton';
|
||||
|
||||
/**
|
||||
* Não existe endpoint de perfil/senha dedicado para o master admin no
|
||||
* backend (só `GET /auth/master/admins`, somente leitura, e o fluxo
|
||||
* genérico `forgot`/`reset` por e-mail — ver observações da Etapa 15 no
|
||||
* controle de progresso). Nome/e-mail aqui são só exibidos (resolvidos
|
||||
* filtrando a lista completa pelo `sub` do JWT), e a troca de senha
|
||||
* reaproveita `POST /auth/password/forgot`, o mesmo fluxo já usado em
|
||||
* `/esqueci-senha` — não uma troca "senha atual → nova senha" direta na
|
||||
* tela, porque essa rota não existe.
|
||||
*/
|
||||
export default function MasterConfiguracoesPage() {
|
||||
const { user } = useAuth();
|
||||
const { data: admins, isLoading } = useQuery({
|
||||
queryKey: ['master', 'admins'],
|
||||
queryFn: listMasterAdmins,
|
||||
});
|
||||
|
||||
const me = admins?.find((admin) => admin.id === user?.sub);
|
||||
|
||||
const resetMutation = useMutation({
|
||||
mutationFn: () =>
|
||||
apiClient.post('/auth/password/forgot', { email: me!.email, usuario_tipo: 'master' }),
|
||||
onSuccess: () => {
|
||||
toast.success('Se o e-mail existir, as instruções de redefinição foram enviadas.');
|
||||
},
|
||||
onError: (err) => {
|
||||
toast.error(err instanceof ApiError ? err.message : 'Não foi possível enviar o e-mail.');
|
||||
},
|
||||
});
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-6">
|
||||
<div>
|
||||
<h1 className="text-xl font-semibold text-foreground">Configurações</h1>
|
||||
<p className="text-sm text-muted-foreground">Dados da sua conta de administrador</p>
|
||||
</div>
|
||||
|
||||
<Card className="max-w-xl">
|
||||
<CardHeader>
|
||||
<CardTitle>Meus dados</CardTitle>
|
||||
<CardDescription>Somente leitura nesta versão.</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="flex flex-col gap-4">
|
||||
{isLoading ? (
|
||||
<div className="flex flex-col gap-2">
|
||||
<Skeleton className="h-5 w-48" />
|
||||
<Skeleton className="h-5 w-64" />
|
||||
</div>
|
||||
) : me ? (
|
||||
<dl className="flex flex-col gap-3 text-sm">
|
||||
<div className="flex justify-between gap-4">
|
||||
<dt className="text-muted-foreground">Nome</dt>
|
||||
<dd className="font-medium text-foreground">{me.nome}</dd>
|
||||
</div>
|
||||
<div className="flex justify-between gap-4">
|
||||
<dt className="text-muted-foreground">E-mail</dt>
|
||||
<dd className="font-medium text-foreground">{me.email}</dd>
|
||||
</div>
|
||||
<div className="flex justify-between gap-4">
|
||||
<dt className="text-muted-foreground">Último login</dt>
|
||||
<dd className="text-foreground">{formatDateTime(me.ultimo_login)}</dd>
|
||||
</div>
|
||||
</dl>
|
||||
) : (
|
||||
<p className="text-sm text-muted-foreground">Não foi possível identificar sua conta.</p>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card className="max-w-xl">
|
||||
<CardHeader>
|
||||
<CardTitle>Senha</CardTitle>
|
||||
<CardDescription>
|
||||
Enviaremos um e-mail com um link para você definir uma nova senha.
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<Button
|
||||
variant="outline"
|
||||
loading={resetMutation.isPending}
|
||||
disabled={!me}
|
||||
onClick={() => resetMutation.mutate()}
|
||||
>
|
||||
<KeyRound /> Enviar e-mail de redefinição de senha
|
||||
</Button>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
'use client';
|
||||
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { Building2, CheckCircle2, CircleDollarSign, Clock, TrendingUp, XCircle } from 'lucide-react';
|
||||
|
||||
import { getMasterDashboard } from '@/lib/api/dashboard';
|
||||
import { formatCurrency } from '@/lib/format';
|
||||
import { StatCard } from '@/components/domain/stat-card';
|
||||
|
||||
/**
|
||||
* Sem gráfico de evolução (tarefa 1 da Etapa 15, "se o backend expuser dado
|
||||
* suficiente"): `GET /master/dashboard` (`dashboard.service.ts#resumo`) só
|
||||
* devolve o snapshot atual — nenhuma série histórica de faturamento/novos
|
||||
* tenants. Ficou só com os cards de resumo, como a própria tarefa já
|
||||
* previa para esse cenário.
|
||||
*/
|
||||
export default function MasterDashboardPage() {
|
||||
const { data, isLoading } = useQuery({
|
||||
queryKey: ['master', 'dashboard'],
|
||||
queryFn: getMasterDashboard,
|
||||
});
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-6">
|
||||
<div>
|
||||
<h1 className="text-xl font-semibold text-foreground">Dashboard</h1>
|
||||
<p className="text-sm text-muted-foreground">Visão geral da plataforma</p>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<h2 className="mb-3 text-sm font-medium text-muted-foreground">Tenants por status</h2>
|
||||
<div className="grid grid-cols-2 gap-4 sm:grid-cols-3 lg:grid-cols-5">
|
||||
<StatCard label="Trial" value={String(data?.tenants_por_status.trial ?? 0)} icon={Clock} loading={isLoading} />
|
||||
<StatCard
|
||||
label="Ativos"
|
||||
value={String(data?.tenants_por_status.ativo ?? 0)}
|
||||
icon={CheckCircle2}
|
||||
tone="success"
|
||||
loading={isLoading}
|
||||
/>
|
||||
<StatCard
|
||||
label="Inadimplentes"
|
||||
value={String(data?.tenants_por_status.inadimplente ?? 0)}
|
||||
icon={XCircle}
|
||||
tone="danger"
|
||||
loading={isLoading}
|
||||
/>
|
||||
<StatCard
|
||||
label="Suspensos"
|
||||
value={String(data?.tenants_por_status.suspenso ?? 0)}
|
||||
icon={XCircle}
|
||||
tone="warning"
|
||||
loading={isLoading}
|
||||
/>
|
||||
<StatCard
|
||||
label="Cancelados"
|
||||
value={String(data?.tenants_por_status.cancelado ?? 0)}
|
||||
icon={Building2}
|
||||
loading={isLoading}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<h2 className="mb-3 text-sm font-medium text-muted-foreground">Financeiro</h2>
|
||||
<div className="grid grid-cols-1 gap-4 sm:grid-cols-3">
|
||||
<StatCard label="MRR" value={formatCurrency(data?.mrr)} icon={TrendingUp} loading={isLoading} />
|
||||
<StatCard
|
||||
label="Recebido no mês"
|
||||
value={formatCurrency(data?.total_recebido_mes)}
|
||||
icon={CircleDollarSign}
|
||||
tone="success"
|
||||
loading={isLoading}
|
||||
/>
|
||||
<StatCard
|
||||
label="Em aberto"
|
||||
value={formatCurrency(data?.total_em_aberto)}
|
||||
icon={CircleDollarSign}
|
||||
tone="warning"
|
||||
loading={isLoading}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,223 @@
|
||||
'use client';
|
||||
|
||||
import * as React from 'react';
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { zodResolver } from '@hookform/resolvers/zod';
|
||||
import { Plug, Plus } from 'lucide-react';
|
||||
|
||||
import {
|
||||
createEvolutionConfig,
|
||||
deleteEvolutionConfig,
|
||||
listEvolutionConfigs,
|
||||
testarConexaoEvolution,
|
||||
updateEvolutionConfig,
|
||||
type EvolutionConfig,
|
||||
} from '@/lib/api/evolution-config';
|
||||
import {
|
||||
evolutionConfigSchema,
|
||||
type EvolutionConfigFormValues,
|
||||
} from '@/lib/validators/evolution-config';
|
||||
import { ApiError } from '@/lib/api/client';
|
||||
import { formatDate } from '@/lib/format';
|
||||
import { toast } from '@/lib/toast';
|
||||
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { DataTable, type DataTableColumn } from '@/components/ui/data-table';
|
||||
import { FormField } from '@/components/ui/form-field';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { ResponsiveDialog } from '@/components/ui/responsive-dialog';
|
||||
import { ConfirmDialog } from '@/components/domain/confirm-dialog';
|
||||
|
||||
export default function EvolutionConfigPage() {
|
||||
const queryClient = useQueryClient();
|
||||
const { data: configs, isLoading } = useQuery({
|
||||
queryKey: ['master', 'evolution-config'],
|
||||
queryFn: listEvolutionConfigs,
|
||||
});
|
||||
|
||||
const [editing, setEditing] = React.useState<EvolutionConfig | null>(null);
|
||||
const [formOpen, setFormOpen] = React.useState(false);
|
||||
const [deleting, setDeleting] = React.useState<EvolutionConfig | null>(null);
|
||||
const [testingId, setTestingId] = React.useState<string | null>(null);
|
||||
|
||||
const form = useForm<EvolutionConfigFormValues>({ resolver: zodResolver(evolutionConfigSchema) });
|
||||
|
||||
function openCreate() {
|
||||
setEditing(null);
|
||||
form.reset({ nome: '', base_url: '', api_key: '', versao: '' });
|
||||
setFormOpen(true);
|
||||
}
|
||||
|
||||
function openEdit(config: EvolutionConfig) {
|
||||
setEditing(config);
|
||||
form.reset({ nome: config.nome, base_url: config.base_url, api_key: '', versao: config.versao });
|
||||
setFormOpen(true);
|
||||
}
|
||||
|
||||
const saveMutation = useMutation({
|
||||
mutationFn: (values: EvolutionConfigFormValues) => {
|
||||
if (editing) {
|
||||
return updateEvolutionConfig(editing.id, {
|
||||
nome: values.nome,
|
||||
base_url: values.base_url,
|
||||
versao: values.versao || undefined,
|
||||
...(values.api_key ? { api_key: values.api_key } : {}),
|
||||
});
|
||||
}
|
||||
return createEvolutionConfig({
|
||||
nome: values.nome,
|
||||
base_url: values.base_url,
|
||||
api_key: values.api_key,
|
||||
versao: values.versao || undefined,
|
||||
});
|
||||
},
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['master', 'evolution-config'] });
|
||||
toast.success(editing ? 'Configuração atualizada.' : 'Configuração criada.');
|
||||
setFormOpen(false);
|
||||
},
|
||||
onError: (err) => {
|
||||
toast.error(err instanceof ApiError ? err.message : 'Não foi possível salvar a configuração.');
|
||||
},
|
||||
});
|
||||
|
||||
const deleteMutation = useMutation({
|
||||
mutationFn: (id: string) => deleteEvolutionConfig(id),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['master', 'evolution-config'] });
|
||||
toast.success('Configuração excluída.');
|
||||
setDeleting(null);
|
||||
},
|
||||
onError: (err) => {
|
||||
toast.error(err instanceof ApiError ? err.message : 'Não foi possível excluir a configuração.');
|
||||
setDeleting(null);
|
||||
},
|
||||
});
|
||||
|
||||
const testMutation = useMutation({
|
||||
mutationFn: (id: string) => testarConexaoEvolution(id),
|
||||
onMutate: (id) => setTestingId(id),
|
||||
onSuccess: (result) => {
|
||||
toast.success(`Conexão OK (status ${result.status_http}${result.versao ? `, versão ${result.versao}` : ''}).`);
|
||||
},
|
||||
onError: (err) => {
|
||||
toast.error(err instanceof ApiError ? err.message : 'Falha ao testar a conexão.');
|
||||
},
|
||||
onSettled: () => setTestingId(null),
|
||||
});
|
||||
|
||||
const columns: DataTableColumn<EvolutionConfig>[] = [
|
||||
{ id: 'nome', header: 'Nome', primary: true, cell: (row) => row.nome },
|
||||
{ id: 'base_url', header: 'URL base', cell: (row) => row.base_url },
|
||||
{ id: 'api_key', header: 'API key', cell: (row) => <code className="text-xs">{row.api_key}</code> },
|
||||
{ id: 'versao', header: 'Versão', cell: (row) => row.versao },
|
||||
{
|
||||
id: 'status',
|
||||
header: 'Status',
|
||||
primary: true,
|
||||
cell: (row) => <Badge variant={row.ativo ? 'default' : 'outline'}>{row.ativo ? 'Ativo' : 'Inativo'}</Badge>,
|
||||
},
|
||||
{ id: 'criado_em', header: 'Criado em', hideOnMobileCard: true, cell: (row) => formatDate(row.criado_em) },
|
||||
];
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-6">
|
||||
<div className="flex flex-wrap items-center justify-between gap-4">
|
||||
<div>
|
||||
<h1 className="text-xl font-semibold text-foreground">Evolution API</h1>
|
||||
<p className="text-sm text-muted-foreground">Conexão usada para disparar mensagens de WhatsApp</p>
|
||||
</div>
|
||||
<Button onClick={openCreate}>
|
||||
<Plus /> Nova configuração
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<DataTable
|
||||
columns={columns}
|
||||
data={configs ?? []}
|
||||
keyField={(row) => row.id}
|
||||
loading={isLoading}
|
||||
emptyTitle="Nenhuma configuração cadastrada"
|
||||
emptyDescription="Cadastre a conexão com a Evolution API para habilitar o envio de WhatsApp."
|
||||
emptyAction={
|
||||
<Button size="sm" onClick={openCreate}>
|
||||
Nova configuração
|
||||
</Button>
|
||||
}
|
||||
rowActions={(row) => (
|
||||
<>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
loading={testingId === row.id}
|
||||
onClick={() => testMutation.mutate(row.id)}
|
||||
>
|
||||
<Plug /> Testar conexão
|
||||
</Button>
|
||||
<Button variant="ghost" size="sm" onClick={() => openEdit(row)}>
|
||||
Editar
|
||||
</Button>
|
||||
<Button variant="ghost" size="sm" onClick={() => setDeleting(row)}>
|
||||
Excluir
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
/>
|
||||
|
||||
<ResponsiveDialog
|
||||
open={formOpen}
|
||||
onOpenChange={setFormOpen}
|
||||
title={editing ? 'Editar configuração' : 'Nova configuração'}
|
||||
footer={
|
||||
<>
|
||||
<Button variant="outline" onClick={() => setFormOpen(false)}>
|
||||
Cancelar
|
||||
</Button>
|
||||
<Button
|
||||
loading={saveMutation.isPending}
|
||||
onClick={form.handleSubmit((values) => saveMutation.mutate(values))}
|
||||
>
|
||||
Salvar
|
||||
</Button>
|
||||
</>
|
||||
}
|
||||
>
|
||||
<form
|
||||
className="flex flex-col gap-4 px-4 pb-4 sm:px-0 sm:pb-0"
|
||||
onSubmit={form.handleSubmit((values) => saveMutation.mutate(values))}
|
||||
>
|
||||
<FormField label="Nome" error={form.formState.errors.nome?.message} required>
|
||||
<Input {...form.register('nome')} />
|
||||
</FormField>
|
||||
<FormField label="URL base" error={form.formState.errors.base_url?.message} required>
|
||||
<Input placeholder="https://evolution.exemplo.com" {...form.register('base_url')} />
|
||||
</FormField>
|
||||
<FormField
|
||||
label="API key"
|
||||
error={form.formState.errors.api_key?.message}
|
||||
helpText={editing ? 'Deixe em branco para manter a chave atual' : undefined}
|
||||
required={!editing}
|
||||
>
|
||||
<Input type="password" autoComplete="off" {...form.register('api_key')} />
|
||||
</FormField>
|
||||
<FormField label="Versão" error={form.formState.errors.versao?.message}>
|
||||
<Input placeholder="2.3" {...form.register('versao')} />
|
||||
</FormField>
|
||||
</form>
|
||||
</ResponsiveDialog>
|
||||
|
||||
<ConfirmDialog
|
||||
open={deleting !== null}
|
||||
onOpenChange={(open) => !open && setDeleting(null)}
|
||||
title={`Excluir "${deleting?.nome}"?`}
|
||||
description="Só é possível excluir se nenhuma instância de WhatsApp estiver usando esta configuração."
|
||||
confirmLabel="Excluir"
|
||||
destructive
|
||||
loading={deleteMutation.isPending}
|
||||
onConfirm={() => deleting && deleteMutation.mutate(deleting.id)}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,218 @@
|
||||
'use client';
|
||||
|
||||
import * as React from 'react';
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import { RefreshCw, Zap } from 'lucide-react';
|
||||
|
||||
import {
|
||||
atualizarFaturasAtrasadas,
|
||||
gerarFaturasMes,
|
||||
listFaturas,
|
||||
marcarFaturaPaga,
|
||||
type FaturaListItem,
|
||||
type FaturaStatus,
|
||||
} from '@/lib/api/faturas';
|
||||
import { listTenants } from '@/lib/api/tenants';
|
||||
import { ApiError } from '@/lib/api/client';
|
||||
import { formatCurrency, formatDate } from '@/lib/format';
|
||||
import { toast } from '@/lib/toast';
|
||||
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Combobox } from '@/components/ui/combobox';
|
||||
import { DataTable, type DataTableColumn } from '@/components/ui/data-table';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
|
||||
import { StatusPill } from '@/components/ui/status-pill';
|
||||
import { ConfirmDialog } from '@/components/domain/confirm-dialog';
|
||||
|
||||
const STATUS_OPTIONS: { value: FaturaStatus | 'todos'; label: string }[] = [
|
||||
{ value: 'todos', label: 'Todos os status' },
|
||||
{ value: 'pendente', label: 'Pendente' },
|
||||
{ value: 'pago', label: 'Pago' },
|
||||
{ value: 'atrasado', label: 'Atrasado' },
|
||||
{ value: 'cancelado', label: 'Cancelado' },
|
||||
];
|
||||
|
||||
const LIMIT = 20;
|
||||
|
||||
export default function FaturasPage() {
|
||||
const queryClient = useQueryClient();
|
||||
const [status, setStatus] = React.useState<FaturaStatus | 'todos'>('todos');
|
||||
const [tenantId, setTenantId] = React.useState<string>('');
|
||||
const [referencia, setReferencia] = React.useState('');
|
||||
const [page, setPage] = React.useState(1);
|
||||
const [gerarOpen, setGerarOpen] = React.useState(false);
|
||||
const [atualizarOpen, setAtualizarOpen] = React.useState(false);
|
||||
|
||||
const { data: tenantsOptions } = useQuery({
|
||||
queryKey: ['master', 'tenants', 'combobox'],
|
||||
queryFn: () => listTenants({ limit: 100 }),
|
||||
});
|
||||
|
||||
const { data, isLoading } = useQuery({
|
||||
queryKey: ['master', 'faturas', { status, tenantId, referencia, page }],
|
||||
queryFn: () =>
|
||||
listFaturas({
|
||||
status: status === 'todos' ? undefined : status,
|
||||
tenant_id: tenantId || undefined,
|
||||
referencia: referencia || undefined,
|
||||
page,
|
||||
limit: LIMIT,
|
||||
}),
|
||||
placeholderData: (prev) => prev,
|
||||
});
|
||||
|
||||
const marcarPagoMutation = useMutation({
|
||||
mutationFn: (id: string) => marcarFaturaPaga(id),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['master', 'faturas'] });
|
||||
queryClient.invalidateQueries({ queryKey: ['master', 'dashboard'] });
|
||||
toast.success('Fatura marcada como paga.');
|
||||
},
|
||||
onError: (err) => {
|
||||
toast.error(err instanceof ApiError ? err.message : 'Não foi possível marcar a fatura como paga.');
|
||||
},
|
||||
});
|
||||
|
||||
const gerarMutation = useMutation({
|
||||
mutationFn: () => gerarFaturasMes(),
|
||||
onSuccess: (result) => {
|
||||
queryClient.invalidateQueries({ queryKey: ['master', 'faturas'] });
|
||||
toast.success(`${result.criadas} fatura(s) geradas para ${result.referencia} (${result.ignoradas} já existiam).`);
|
||||
setGerarOpen(false);
|
||||
},
|
||||
onError: (err) => {
|
||||
toast.error(err instanceof ApiError ? err.message : 'Não foi possível gerar as faturas do mês.');
|
||||
},
|
||||
});
|
||||
|
||||
const atualizarMutation = useMutation({
|
||||
mutationFn: () => atualizarFaturasAtrasadas(),
|
||||
onSuccess: (result) => {
|
||||
queryClient.invalidateQueries({ queryKey: ['master', 'faturas'] });
|
||||
queryClient.invalidateQueries({ queryKey: ['master', 'tenants'] });
|
||||
toast.success(`${result.atualizadas} fatura(s) marcadas como atrasadas (${result.tenants_afetados} tenant(s) afetados).`);
|
||||
setAtualizarOpen(false);
|
||||
},
|
||||
onError: (err) => {
|
||||
toast.error(err instanceof ApiError ? err.message : 'Não foi possível atualizar as faturas atrasadas.');
|
||||
},
|
||||
});
|
||||
|
||||
const columns: DataTableColumn<FaturaListItem>[] = [
|
||||
{ id: 'tenant', header: 'Tenant', primary: true, cell: (row) => row.tenant.razao_social },
|
||||
{ id: 'referencia', header: 'Referência', cell: (row) => row.referencia },
|
||||
{ id: 'valor', header: 'Valor', cell: (row) => formatCurrency(row.valor) },
|
||||
{ id: 'vencimento', header: 'Vencimento', cell: (row) => formatDate(row.vencimento) },
|
||||
{ id: 'status', header: 'Status', primary: true, cell: (row) => <StatusPill status={row.status} /> },
|
||||
];
|
||||
|
||||
const tenantComboboxOptions = (tenantsOptions?.data ?? []).map((t) => ({
|
||||
value: t.id,
|
||||
label: t.nome_fantasia || t.razao_social,
|
||||
}));
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-6">
|
||||
<div className="flex flex-wrap items-center justify-between gap-4">
|
||||
<div>
|
||||
<h1 className="text-xl font-semibold text-foreground">Faturas</h1>
|
||||
<p className="text-sm text-muted-foreground">Mensalidades cobradas dos tenants</p>
|
||||
</div>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<Button variant="outline" onClick={() => setAtualizarOpen(true)}>
|
||||
<RefreshCw /> Atualizar atrasadas
|
||||
</Button>
|
||||
<Button onClick={() => setGerarOpen(true)}>
|
||||
<Zap /> Gerar faturas do mês
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col gap-3 sm:flex-row sm:flex-wrap sm:items-center">
|
||||
<Select
|
||||
value={status}
|
||||
onValueChange={(value) => {
|
||||
setStatus(value as FaturaStatus | 'todos');
|
||||
setPage(1);
|
||||
}}
|
||||
>
|
||||
<SelectTrigger className="w-full sm:w-48" aria-label="Filtrar por status">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{STATUS_OPTIONS.map((opt) => (
|
||||
<SelectItem key={opt.value} value={opt.value}>
|
||||
{opt.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<Combobox
|
||||
options={[{ value: '', label: 'Todos os tenants' }, ...tenantComboboxOptions]}
|
||||
value={tenantId}
|
||||
onChange={(value) => {
|
||||
setTenantId(value);
|
||||
setPage(1);
|
||||
}}
|
||||
placeholder="Todos os tenants"
|
||||
searchPlaceholder="Buscar tenant..."
|
||||
className="w-full sm:w-56"
|
||||
/>
|
||||
<Input
|
||||
placeholder="Referência (aaaa-mm)"
|
||||
value={referencia}
|
||||
onChange={(e) => {
|
||||
setReferencia(e.target.value);
|
||||
setPage(1);
|
||||
}}
|
||||
className="w-full sm:w-40"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<DataTable
|
||||
columns={columns}
|
||||
data={data?.data ?? []}
|
||||
keyField={(row) => row.id}
|
||||
loading={isLoading}
|
||||
emptyTitle="Nenhuma fatura encontrada"
|
||||
emptyDescription="Ajuste os filtros ou gere as faturas do mês."
|
||||
rowActions={(row) =>
|
||||
row.status !== 'pago' && row.status !== 'cancelado' ? (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
loading={marcarPagoMutation.isPending && marcarPagoMutation.variables === row.id}
|
||||
onClick={() => marcarPagoMutation.mutate(row.id)}
|
||||
>
|
||||
Marcar como paga
|
||||
</Button>
|
||||
) : null
|
||||
}
|
||||
pagination={
|
||||
data ? { page: data.meta.page, limit: data.meta.limit, total: data.meta.total, onPageChange: setPage } : undefined
|
||||
}
|
||||
/>
|
||||
|
||||
<ConfirmDialog
|
||||
open={gerarOpen}
|
||||
onOpenChange={setGerarOpen}
|
||||
title="Gerar faturas do mês"
|
||||
description="Cria uma fatura pendente para cada tenant que ainda não tem uma fatura no mês corrente. Tenants que já têm fatura para o mês não são duplicados."
|
||||
confirmLabel="Gerar faturas"
|
||||
loading={gerarMutation.isPending}
|
||||
onConfirm={() => gerarMutation.mutate()}
|
||||
/>
|
||||
|
||||
<ConfirmDialog
|
||||
open={atualizarOpen}
|
||||
onOpenChange={setAtualizarOpen}
|
||||
title="Atualizar faturas atrasadas"
|
||||
description="Marca como atrasada toda fatura pendente vencida, e move para inadimplente os tenants ativos afetados."
|
||||
confirmLabel="Atualizar"
|
||||
loading={atualizarMutation.isPending}
|
||||
onConfirm={() => atualizarMutation.mutate()}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
import { cookies } from 'next/headers';
|
||||
|
||||
import { MasterShell } from '@/components/layout/master-shell';
|
||||
import { SIDEBAR_COOKIE, readSidebarCollapsedCookie } from '@/lib/layout/sidebar-cookie';
|
||||
|
||||
export default async function MasterLayout({ children }: { children: React.ReactNode }) {
|
||||
const cookieStore = await cookies();
|
||||
const collapsed = readSidebarCollapsedCookie(cookieStore.get(SIDEBAR_COOKIE)?.value);
|
||||
|
||||
return <MasterShell initialCollapsed={collapsed}>{children}</MasterShell>;
|
||||
}
|
||||
@@ -0,0 +1,248 @@
|
||||
'use client';
|
||||
|
||||
import * as React from 'react';
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { zodResolver } from '@hookform/resolvers/zod';
|
||||
import { Plus } from 'lucide-react';
|
||||
|
||||
import { createPlano, deletePlano, listPlanos, updatePlano, type Plano } from '@/lib/api/planos';
|
||||
import { planoSchema, type PlanoFormValues } from '@/lib/validators/planos';
|
||||
import { ApiError } from '@/lib/api/client';
|
||||
import { formatCurrency } from '@/lib/format';
|
||||
import { toast } from '@/lib/toast';
|
||||
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { DataTable, type DataTableColumn } from '@/components/ui/data-table';
|
||||
import { FormField } from '@/components/ui/form-field';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { ResponsiveDialog } from '@/components/ui/responsive-dialog';
|
||||
import { Textarea } from '@/components/ui/textarea';
|
||||
import { ConfirmDialog } from '@/components/domain/confirm-dialog';
|
||||
|
||||
/** `<input type="number">` vazio deve virar `undefined` (ilimitado), não `NaN`/`0`. */
|
||||
function toOptionalInt(value: string): number | undefined {
|
||||
return value === '' ? undefined : Number(value);
|
||||
}
|
||||
|
||||
export default function PlanosPage() {
|
||||
const queryClient = useQueryClient();
|
||||
const { data: planos, isLoading } = useQuery({
|
||||
queryKey: ['master', 'planos'],
|
||||
queryFn: () => listPlanos(),
|
||||
});
|
||||
|
||||
const [editing, setEditing] = React.useState<Plano | null>(null);
|
||||
const [formOpen, setFormOpen] = React.useState(false);
|
||||
const [deleting, setDeleting] = React.useState<Plano | null>(null);
|
||||
|
||||
const form = useForm<PlanoFormValues>({ resolver: zodResolver(planoSchema) });
|
||||
|
||||
function openCreate() {
|
||||
setEditing(null);
|
||||
form.reset({
|
||||
nome: '',
|
||||
descricao: '',
|
||||
valor_mensal: 0,
|
||||
limite_customers: undefined,
|
||||
limite_usuarios: undefined,
|
||||
limite_instancias_whatsapp: undefined,
|
||||
});
|
||||
setFormOpen(true);
|
||||
}
|
||||
|
||||
function openEdit(plano: Plano) {
|
||||
setEditing(plano);
|
||||
form.reset({
|
||||
nome: plano.nome,
|
||||
descricao: plano.descricao ?? '',
|
||||
valor_mensal: Number(plano.valor_mensal),
|
||||
limite_customers: plano.limite_customers ?? undefined,
|
||||
limite_usuarios: plano.limite_usuarios ?? undefined,
|
||||
limite_instancias_whatsapp: plano.limite_instancias_whatsapp,
|
||||
});
|
||||
setFormOpen(true);
|
||||
}
|
||||
|
||||
const saveMutation = useMutation({
|
||||
mutationFn: (values: PlanoFormValues) =>
|
||||
editing ? updatePlano(editing.id, values) : createPlano(values),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['master', 'planos'] });
|
||||
toast.success(editing ? 'Plano atualizado.' : 'Plano criado.');
|
||||
setFormOpen(false);
|
||||
},
|
||||
onError: (err) => {
|
||||
toast.error(err instanceof ApiError ? err.message : 'Não foi possível salvar o plano.');
|
||||
},
|
||||
});
|
||||
|
||||
const deleteMutation = useMutation({
|
||||
mutationFn: (id: string) => deletePlano(id),
|
||||
onSuccess: (result) => {
|
||||
queryClient.invalidateQueries({ queryKey: ['master', 'planos'] });
|
||||
toast.success(
|
||||
result.deletado ? 'Plano excluído.' : 'Plano em uso por tenant(s) — desativado em vez de excluído.',
|
||||
);
|
||||
setDeleting(null);
|
||||
},
|
||||
onError: (err) => {
|
||||
toast.error(err instanceof ApiError ? err.message : 'Não foi possível excluir o plano.');
|
||||
setDeleting(null);
|
||||
},
|
||||
});
|
||||
|
||||
const columns: DataTableColumn<Plano>[] = [
|
||||
{ id: 'nome', header: 'Plano', primary: true, cell: (row) => row.nome },
|
||||
{
|
||||
id: 'valor',
|
||||
header: 'Valor mensal',
|
||||
cell: (row) => formatCurrency(row.valor_mensal),
|
||||
},
|
||||
{
|
||||
id: 'limites',
|
||||
header: 'Limites',
|
||||
cell: (row) => (
|
||||
<span className="text-muted-foreground">
|
||||
{row.limite_customers ?? '∞'} clientes · {row.limite_usuarios ?? '∞'} usuários ·{' '}
|
||||
{row.limite_instancias_whatsapp} WhatsApp
|
||||
</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
id: 'status',
|
||||
header: 'Status',
|
||||
primary: true,
|
||||
cell: (row) => (
|
||||
<Badge variant={row.ativo ? 'default' : 'outline'}>{row.ativo ? 'Ativo' : 'Inativo'}</Badge>
|
||||
),
|
||||
},
|
||||
];
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-6">
|
||||
<div className="flex flex-wrap items-center justify-between gap-4">
|
||||
<div>
|
||||
<h1 className="text-xl font-semibold text-foreground">Planos</h1>
|
||||
<p className="text-sm text-muted-foreground">Planos de assinatura oferecidos aos tenants</p>
|
||||
</div>
|
||||
<Button onClick={openCreate}>
|
||||
<Plus /> Novo plano
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<DataTable
|
||||
columns={columns}
|
||||
data={planos ?? []}
|
||||
keyField={(row) => row.id}
|
||||
loading={isLoading}
|
||||
emptyTitle="Nenhum plano cadastrado"
|
||||
emptyDescription="Crie o primeiro plano para poder cadastrar tenants."
|
||||
emptyAction={
|
||||
<Button size="sm" onClick={openCreate}>
|
||||
Novo plano
|
||||
</Button>
|
||||
}
|
||||
rowActions={(row) => (
|
||||
<>
|
||||
<Button variant="ghost" size="sm" onClick={() => openEdit(row)}>
|
||||
Editar
|
||||
</Button>
|
||||
<Button variant="ghost" size="sm" onClick={() => setDeleting(row)}>
|
||||
Excluir
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
/>
|
||||
|
||||
<ResponsiveDialog
|
||||
open={formOpen}
|
||||
onOpenChange={setFormOpen}
|
||||
title={editing ? 'Editar plano' : 'Novo plano'}
|
||||
footer={
|
||||
<>
|
||||
<Button variant="outline" onClick={() => setFormOpen(false)}>
|
||||
Cancelar
|
||||
</Button>
|
||||
<Button
|
||||
loading={saveMutation.isPending}
|
||||
onClick={form.handleSubmit((values) => saveMutation.mutate(values))}
|
||||
>
|
||||
Salvar
|
||||
</Button>
|
||||
</>
|
||||
}
|
||||
>
|
||||
<form
|
||||
className="flex flex-col gap-4 px-4 pb-4 sm:px-0 sm:pb-0"
|
||||
onSubmit={form.handleSubmit((values) => saveMutation.mutate(values))}
|
||||
>
|
||||
<FormField label="Nome" error={form.formState.errors.nome?.message} required>
|
||||
<Input {...form.register('nome')} />
|
||||
</FormField>
|
||||
<FormField label="Descrição" error={form.formState.errors.descricao?.message}>
|
||||
<Textarea rows={2} {...form.register('descricao')} />
|
||||
</FormField>
|
||||
<FormField
|
||||
label="Valor mensal (R$)"
|
||||
error={form.formState.errors.valor_mensal?.message}
|
||||
required
|
||||
>
|
||||
<Input
|
||||
type="number"
|
||||
step="0.01"
|
||||
min="0"
|
||||
{...form.register('valor_mensal', { valueAsNumber: true })}
|
||||
/>
|
||||
</FormField>
|
||||
<div className="grid grid-cols-1 gap-4 sm:grid-cols-3">
|
||||
<FormField
|
||||
label="Limite de clientes"
|
||||
helpText="Vazio = ilimitado"
|
||||
error={form.formState.errors.limite_customers?.message}
|
||||
>
|
||||
<Input
|
||||
type="number"
|
||||
min="1"
|
||||
{...form.register('limite_customers', { setValueAs: toOptionalInt })}
|
||||
/>
|
||||
</FormField>
|
||||
<FormField
|
||||
label="Limite de usuários"
|
||||
helpText="Vazio = ilimitado"
|
||||
error={form.formState.errors.limite_usuarios?.message}
|
||||
>
|
||||
<Input
|
||||
type="number"
|
||||
min="1"
|
||||
{...form.register('limite_usuarios', { setValueAs: toOptionalInt })}
|
||||
/>
|
||||
</FormField>
|
||||
<FormField
|
||||
label="Instâncias WhatsApp"
|
||||
error={form.formState.errors.limite_instancias_whatsapp?.message}
|
||||
>
|
||||
<Input
|
||||
type="number"
|
||||
min="1"
|
||||
{...form.register('limite_instancias_whatsapp', { setValueAs: toOptionalInt })}
|
||||
/>
|
||||
</FormField>
|
||||
</div>
|
||||
</form>
|
||||
</ResponsiveDialog>
|
||||
|
||||
<ConfirmDialog
|
||||
open={deleting !== null}
|
||||
onOpenChange={(open) => !open && setDeleting(null)}
|
||||
title={`Excluir "${deleting?.nome}"?`}
|
||||
description="Se este plano estiver em uso por algum tenant não cancelado, ele será desativado em vez de excluído."
|
||||
confirmLabel="Excluir"
|
||||
destructive
|
||||
loading={deleteMutation.isPending}
|
||||
onConfirm={() => deleting && deleteMutation.mutate(deleting.id)}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,271 @@
|
||||
'use client';
|
||||
|
||||
import * as React from 'react';
|
||||
import { useParams } from 'next/navigation';
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { zodResolver } from '@hookform/resolvers/zod';
|
||||
import { Package, ShoppingCart, Users } from 'lucide-react';
|
||||
|
||||
import { getTenant, updateTenant, type TenantDetail } from '@/lib/api/tenants';
|
||||
import { listPlanos } from '@/lib/api/planos';
|
||||
import { marcarFaturaPaga } from '@/lib/api/faturas';
|
||||
import type { Fatura } from '@/lib/api/faturas';
|
||||
import { updateTenantSchema, type UpdateTenantFormValues } from '@/lib/validators/tenants';
|
||||
import { ApiError } from '@/lib/api/client';
|
||||
import { formatCurrency, formatDate } from '@/lib/format';
|
||||
import { toast } from '@/lib/toast';
|
||||
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { DataTable, type DataTableColumn } from '@/components/ui/data-table';
|
||||
import { FormField } from '@/components/ui/form-field';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
|
||||
import { Skeleton } from '@/components/ui/skeleton';
|
||||
import { StatusPill } from '@/components/ui/status-pill';
|
||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
|
||||
import { StatCard } from '@/components/domain/stat-card';
|
||||
import { TenantStatusDialog } from '@/components/domain/tenant-status-dialog';
|
||||
|
||||
export default function TenantDetailPage() {
|
||||
const params = useParams<{ id: string }>();
|
||||
const tenantId = params.id;
|
||||
const queryClient = useQueryClient();
|
||||
const [statusDialogOpen, setStatusDialogOpen] = React.useState(false);
|
||||
|
||||
const { data: tenant, isLoading } = useQuery({
|
||||
queryKey: ['master', 'tenants', tenantId],
|
||||
queryFn: () => getTenant(tenantId),
|
||||
});
|
||||
|
||||
if (isLoading || !tenant) {
|
||||
return (
|
||||
<div className="flex flex-col gap-4">
|
||||
<Skeleton className="h-8 w-64" />
|
||||
<Skeleton className="h-64 w-full" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-6">
|
||||
<div className="flex flex-wrap items-center justify-between gap-4">
|
||||
<div>
|
||||
<div className="flex items-center gap-3">
|
||||
<h1 className="text-xl font-semibold text-foreground">
|
||||
{tenant.nome_fantasia || tenant.razao_social}
|
||||
</h1>
|
||||
<StatusPill status={tenant.status} />
|
||||
</div>
|
||||
<p className="text-sm text-muted-foreground">{tenant.email_contato}</p>
|
||||
</div>
|
||||
<Button variant="outline" onClick={() => setStatusDialogOpen(true)}>
|
||||
Mudar status
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<Tabs defaultValue="dados">
|
||||
<TabsList>
|
||||
<TabsTrigger value="dados">Dados cadastrais</TabsTrigger>
|
||||
<TabsTrigger value="faturas">Faturas</TabsTrigger>
|
||||
<TabsTrigger value="uso">Uso</TabsTrigger>
|
||||
</TabsList>
|
||||
|
||||
<TabsContent value="dados" className="pt-4">
|
||||
<DadosCadastraisForm tenantId={tenantId} tenant={tenant} />
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="faturas" className="pt-4">
|
||||
<FaturasTab faturas={tenant.faturas} tenantId={tenantId} />
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="uso" className="pt-4">
|
||||
<div className="grid grid-cols-1 gap-4 sm:grid-cols-3">
|
||||
<StatCard label="Usuários" value={String(tenant._count.usuarios)} icon={Users} />
|
||||
<StatCard
|
||||
label="Clientes"
|
||||
value={`${tenant._count.customers}${tenant.plano.limite_customers ? ` / ${tenant.plano.limite_customers}` : ''}`}
|
||||
icon={Package}
|
||||
/>
|
||||
<StatCard label="Vendas" value={String(tenant._count.vendas)} icon={ShoppingCart} />
|
||||
</div>
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
|
||||
<TenantStatusDialog
|
||||
tenant={statusDialogOpen ? { id: tenant.id, razao_social: tenant.razao_social, status: tenant.status } : null}
|
||||
onOpenChange={setStatusDialogOpen}
|
||||
onSuccess={() => queryClient.invalidateQueries({ queryKey: ['master', 'tenants', tenantId] })}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function DadosCadastraisForm({ tenantId, tenant }: { tenantId: string; tenant: TenantDetail }) {
|
||||
const queryClient = useQueryClient();
|
||||
const { data: planos } = useQuery({
|
||||
queryKey: ['master', 'planos', { ativo: true }],
|
||||
queryFn: () => listPlanos({ ativo: true }),
|
||||
});
|
||||
|
||||
const form = useForm<UpdateTenantFormValues>({
|
||||
resolver: zodResolver(updateTenantSchema),
|
||||
defaultValues: {
|
||||
razao_social: tenant.razao_social,
|
||||
nome_fantasia: tenant.nome_fantasia ?? '',
|
||||
documento: tenant.documento ?? '',
|
||||
email_contato: tenant.email_contato,
|
||||
telefone: tenant.telefone ?? '',
|
||||
plano_id: tenant.plano_id,
|
||||
dia_vencimento_mensalidade: tenant.dia_vencimento_mensalidade,
|
||||
},
|
||||
});
|
||||
|
||||
const mutation = useMutation({
|
||||
mutationFn: (values: UpdateTenantFormValues) =>
|
||||
updateTenant(tenantId, {
|
||||
...values,
|
||||
nome_fantasia: values.nome_fantasia || undefined,
|
||||
documento: values.documento || undefined,
|
||||
telefone: values.telefone || undefined,
|
||||
}),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['master', 'tenants', tenantId] });
|
||||
queryClient.invalidateQueries({ queryKey: ['master', 'tenants'] });
|
||||
toast.success('Dados do tenant atualizados.');
|
||||
},
|
||||
onError: (err) => {
|
||||
toast.error(err instanceof ApiError ? err.message : 'Não foi possível salvar as alterações.');
|
||||
},
|
||||
});
|
||||
|
||||
return (
|
||||
<Card className="max-w-2xl">
|
||||
<CardHeader>
|
||||
<CardTitle>Dados cadastrais</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<form
|
||||
className="flex flex-col gap-4"
|
||||
onSubmit={form.handleSubmit((values) => mutation.mutate(values))}
|
||||
>
|
||||
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
|
||||
<FormField label="Razão social" error={form.formState.errors.razao_social?.message} required>
|
||||
<Input {...form.register('razao_social')} />
|
||||
</FormField>
|
||||
<FormField label="Nome fantasia" error={form.formState.errors.nome_fantasia?.message}>
|
||||
<Input {...form.register('nome_fantasia')} />
|
||||
</FormField>
|
||||
</div>
|
||||
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
|
||||
<FormField label="Documento" error={form.formState.errors.documento?.message}>
|
||||
<Input {...form.register('documento')} />
|
||||
</FormField>
|
||||
<FormField label="Telefone" error={form.formState.errors.telefone?.message}>
|
||||
<Input {...form.register('telefone')} />
|
||||
</FormField>
|
||||
</div>
|
||||
<FormField label="E-mail de contato" error={form.formState.errors.email_contato?.message} required>
|
||||
<Input type="email" {...form.register('email_contato')} />
|
||||
</FormField>
|
||||
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
|
||||
<FormField
|
||||
label="Plano"
|
||||
id="plano_id"
|
||||
error={form.formState.errors.plano_id?.message}
|
||||
required
|
||||
>
|
||||
<Select
|
||||
value={form.watch('plano_id')}
|
||||
onValueChange={(value) => form.setValue('plano_id', value, { shouldValidate: true })}
|
||||
>
|
||||
<SelectTrigger id="plano_id" className="w-full">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{(planos ?? []).map((plano) => (
|
||||
<SelectItem key={plano.id} value={plano.id}>
|
||||
{plano.nome}
|
||||
</SelectItem>
|
||||
))}
|
||||
{!planos?.some((p) => p.id === tenant.plano_id) && (
|
||||
<SelectItem value={tenant.plano_id}>{tenant.plano.nome} (inativo)</SelectItem>
|
||||
)}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</FormField>
|
||||
<FormField
|
||||
label="Dia de vencimento da mensalidade"
|
||||
error={form.formState.errors.dia_vencimento_mensalidade?.message}
|
||||
>
|
||||
<Input
|
||||
type="number"
|
||||
min="1"
|
||||
max="28"
|
||||
{...form.register('dia_vencimento_mensalidade', {
|
||||
setValueAs: (v) => (v === '' ? undefined : Number(v)),
|
||||
})}
|
||||
/>
|
||||
</FormField>
|
||||
</div>
|
||||
<div>
|
||||
<Button type="submit" loading={mutation.isPending}>
|
||||
Salvar alterações
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
function FaturasTab({ faturas, tenantId }: { faturas: Fatura[]; tenantId: string }) {
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
const marcarPagoMutation = useMutation({
|
||||
mutationFn: (id: string) => marcarFaturaPaga(id),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['master', 'tenants', tenantId] });
|
||||
toast.success('Fatura marcada como paga.');
|
||||
},
|
||||
onError: (err) => {
|
||||
toast.error(err instanceof ApiError ? err.message : 'Não foi possível marcar a fatura como paga.');
|
||||
},
|
||||
});
|
||||
|
||||
const columns: DataTableColumn<Fatura>[] = [
|
||||
{ id: 'referencia', header: 'Referência', primary: true, cell: (row) => row.referencia },
|
||||
{ id: 'valor', header: 'Valor', cell: (row) => formatCurrency(row.valor) },
|
||||
{ id: 'vencimento', header: 'Vencimento', cell: (row) => formatDate(row.vencimento) },
|
||||
{ id: 'status', header: 'Status', primary: true, cell: (row) => <StatusPill status={row.status} /> },
|
||||
{ id: 'pago_em', header: 'Pago em', cell: (row) => formatDate(row.pago_em) },
|
||||
];
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-3">
|
||||
<p className="text-sm text-muted-foreground">Últimas 5 faturas deste tenant.</p>
|
||||
<DataTable
|
||||
columns={columns}
|
||||
data={faturas}
|
||||
keyField={(row) => row.id}
|
||||
emptyTitle="Nenhuma fatura gerada ainda"
|
||||
rowActions={(row) =>
|
||||
row.status !== 'pago' ? (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
loading={marcarPagoMutation.isPending && marcarPagoMutation.variables === row.id}
|
||||
onClick={() => marcarPagoMutation.mutate(row.id)}
|
||||
>
|
||||
Marcar como paga
|
||||
</Button>
|
||||
) : (
|
||||
<Badge variant="outline">Paga</Badge>
|
||||
)
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,238 @@
|
||||
'use client';
|
||||
|
||||
import * as React from 'react';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { useMutation, useQuery } from '@tanstack/react-query';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { zodResolver } from '@hookform/resolvers/zod';
|
||||
import { Copy } from 'lucide-react';
|
||||
|
||||
import { createTenant, type CreateTenantResult } from '@/lib/api/tenants';
|
||||
import { listPlanos } from '@/lib/api/planos';
|
||||
import { createTenantSchema, type CreateTenantFormValues } from '@/lib/validators/tenants';
|
||||
import { ApiError } from '@/lib/api/client';
|
||||
import { toast } from '@/lib/toast';
|
||||
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { FormField } from '@/components/ui/form-field';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { ResponsiveDialog } from '@/components/ui/responsive-dialog';
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
|
||||
import { Separator } from '@/components/ui/separator';
|
||||
|
||||
export default function NovoTenantPage() {
|
||||
const router = useRouter();
|
||||
const [created, setCreated] = React.useState<CreateTenantResult | null>(null);
|
||||
|
||||
const { data: planos } = useQuery({
|
||||
queryKey: ['master', 'planos', { ativo: true }],
|
||||
queryFn: () => listPlanos({ ativo: true }),
|
||||
});
|
||||
|
||||
const form = useForm<CreateTenantFormValues>({
|
||||
resolver: zodResolver(createTenantSchema),
|
||||
defaultValues: {
|
||||
razao_social: '',
|
||||
nome_fantasia: '',
|
||||
documento: '',
|
||||
email_contato: '',
|
||||
telefone: '',
|
||||
plano_id: '',
|
||||
admin_nome: '',
|
||||
admin_email: '',
|
||||
admin_senha: '',
|
||||
},
|
||||
});
|
||||
|
||||
const mutation = useMutation({
|
||||
mutationFn: (values: CreateTenantFormValues) =>
|
||||
createTenant({
|
||||
razao_social: values.razao_social,
|
||||
nome_fantasia: values.nome_fantasia || undefined,
|
||||
documento: values.documento || undefined,
|
||||
email_contato: values.email_contato,
|
||||
telefone: values.telefone || undefined,
|
||||
plano_id: values.plano_id,
|
||||
dia_vencimento_mensalidade: values.dia_vencimento_mensalidade,
|
||||
admin: {
|
||||
nome: values.admin_nome,
|
||||
email: values.admin_email,
|
||||
senha: values.admin_senha || undefined,
|
||||
},
|
||||
}),
|
||||
onSuccess: (result) => setCreated(result),
|
||||
onError: (err) => {
|
||||
toast.error(err instanceof ApiError ? err.message : 'Não foi possível criar o tenant.');
|
||||
},
|
||||
});
|
||||
|
||||
async function copySenha() {
|
||||
if (!created) return;
|
||||
try {
|
||||
await navigator.clipboard.writeText(created.admin.senha_provisoria);
|
||||
toast.success('Senha copiada.');
|
||||
} catch {
|
||||
toast.error('Não foi possível copiar automaticamente — selecione e copie manualmente.');
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-6">
|
||||
<div>
|
||||
<h1 className="text-xl font-semibold text-foreground">Novo tenant</h1>
|
||||
<p className="text-sm text-muted-foreground">Cadastro de um novo cliente da plataforma</p>
|
||||
</div>
|
||||
|
||||
<form
|
||||
className="flex max-w-2xl flex-col gap-6"
|
||||
onSubmit={form.handleSubmit((values) => mutation.mutate(values))}
|
||||
>
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Dados cadastrais</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="flex flex-col gap-4">
|
||||
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
|
||||
<FormField label="Razão social" error={form.formState.errors.razao_social?.message} required>
|
||||
<Input {...form.register('razao_social')} />
|
||||
</FormField>
|
||||
<FormField label="Nome fantasia" error={form.formState.errors.nome_fantasia?.message}>
|
||||
<Input {...form.register('nome_fantasia')} />
|
||||
</FormField>
|
||||
</div>
|
||||
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
|
||||
<FormField label="Documento (CNPJ/CPF)" error={form.formState.errors.documento?.message}>
|
||||
<Input {...form.register('documento')} />
|
||||
</FormField>
|
||||
<FormField label="Telefone" error={form.formState.errors.telefone?.message}>
|
||||
<Input {...form.register('telefone')} />
|
||||
</FormField>
|
||||
</div>
|
||||
<FormField
|
||||
label="E-mail de contato"
|
||||
error={form.formState.errors.email_contato?.message}
|
||||
required
|
||||
>
|
||||
<Input type="email" {...form.register('email_contato')} />
|
||||
</FormField>
|
||||
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
|
||||
<FormField
|
||||
label="Plano"
|
||||
id="plano_id"
|
||||
error={form.formState.errors.plano_id?.message}
|
||||
required
|
||||
>
|
||||
<Select
|
||||
value={form.watch('plano_id')}
|
||||
onValueChange={(value) => form.setValue('plano_id', value, { shouldValidate: true })}
|
||||
>
|
||||
<SelectTrigger id="plano_id" className="w-full">
|
||||
<SelectValue placeholder="Selecione um plano" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{(planos ?? []).map((plano) => (
|
||||
<SelectItem key={plano.id} value={plano.id}>
|
||||
{plano.nome}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</FormField>
|
||||
<FormField
|
||||
label="Dia de vencimento da mensalidade"
|
||||
helpText="1 a 28 — vazio usa o padrão do sistema"
|
||||
error={form.formState.errors.dia_vencimento_mensalidade?.message}
|
||||
>
|
||||
<Input
|
||||
type="number"
|
||||
min="1"
|
||||
max="28"
|
||||
{...form.register('dia_vencimento_mensalidade', {
|
||||
setValueAs: (v) => (v === '' ? undefined : Number(v)),
|
||||
})}
|
||||
/>
|
||||
</FormField>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Primeiro usuário (administrador do tenant)</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="flex flex-col gap-4">
|
||||
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
|
||||
<FormField label="Nome" error={form.formState.errors.admin_nome?.message} required>
|
||||
<Input {...form.register('admin_nome')} />
|
||||
</FormField>
|
||||
<FormField label="E-mail" error={form.formState.errors.admin_email?.message} required>
|
||||
<Input type="email" {...form.register('admin_email')} />
|
||||
</FormField>
|
||||
</div>
|
||||
<FormField
|
||||
label="Senha provisória"
|
||||
helpText="Deixe em branco para o sistema gerar uma senha automaticamente"
|
||||
error={form.formState.errors.admin_senha?.message}
|
||||
>
|
||||
<Input type="text" autoComplete="off" {...form.register('admin_senha')} />
|
||||
</FormField>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<div className="flex items-center gap-3">
|
||||
<Button type="submit" loading={mutation.isPending}>
|
||||
Criar tenant
|
||||
</Button>
|
||||
<Button type="button" variant="outline" onClick={() => router.push('/master/tenants')}>
|
||||
Cancelar
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
|
||||
<ResponsiveDialog
|
||||
open={created !== null}
|
||||
onOpenChange={(open) => {
|
||||
if (!open && created) router.push(`/master/tenants/${created.tenant.id}`);
|
||||
}}
|
||||
title="Tenant criado com sucesso"
|
||||
description="Copie e repasse a senha provisória ao cliente agora — ela não será mostrada novamente."
|
||||
footer={
|
||||
<Button
|
||||
className="w-full"
|
||||
onClick={() => created && router.push(`/master/tenants/${created.tenant.id}`)}
|
||||
>
|
||||
Concluir
|
||||
</Button>
|
||||
}
|
||||
>
|
||||
{created && (
|
||||
<div className="flex flex-col gap-4 px-4 pb-4 sm:px-0 sm:pb-0">
|
||||
<div>
|
||||
<p className="text-sm text-muted-foreground">Administrador</p>
|
||||
<p className="font-medium text-foreground">
|
||||
{created.admin.nome} · {created.admin.email}
|
||||
</p>
|
||||
</div>
|
||||
<Separator />
|
||||
<div className="flex flex-col gap-2">
|
||||
<p className="text-sm font-medium text-foreground">Senha provisória</p>
|
||||
<div className="flex items-center gap-2 rounded-lg border border-warning/30 bg-warning/10 p-3">
|
||||
<code className="flex-1 font-mono text-base font-semibold text-foreground select-all">
|
||||
{created.admin.senha_provisoria}
|
||||
</code>
|
||||
<Button type="button" variant="ghost" size="icon-sm" onClick={copySenha} aria-label="Copiar senha">
|
||||
<Copy className="size-4" />
|
||||
</Button>
|
||||
</div>
|
||||
<p className="text-xs text-warning">
|
||||
Atenção: esta senha não fica salva em texto puro em nenhum lugar e não será exibida
|
||||
novamente. Copie e repasse ao cliente agora.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</ResponsiveDialog>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
'use client';
|
||||
|
||||
import * as React from 'react';
|
||||
import Link from 'next/link';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { Plus, Search } from 'lucide-react';
|
||||
|
||||
import { listTenants, type TenantListItem, type TenantStatus } from '@/lib/api/tenants';
|
||||
import { formatDate } from '@/lib/format';
|
||||
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { DataTable, type DataTableColumn } from '@/components/ui/data-table';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { StatusPill } from '@/components/ui/status-pill';
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
|
||||
import { TenantStatusDialog } from '@/components/domain/tenant-status-dialog';
|
||||
|
||||
const STATUS_OPTIONS: { value: TenantStatus | 'todos'; label: string }[] = [
|
||||
{ value: 'todos', label: 'Todos os status' },
|
||||
{ value: 'trial', label: 'Trial' },
|
||||
{ value: 'ativo', label: 'Ativo' },
|
||||
{ value: 'inadimplente', label: 'Inadimplente' },
|
||||
{ value: 'suspenso', label: 'Suspenso' },
|
||||
{ value: 'cancelado', label: 'Cancelado' },
|
||||
];
|
||||
|
||||
const LIMIT = 20;
|
||||
|
||||
export default function TenantsPage() {
|
||||
const router = useRouter();
|
||||
const [busca, setBusca] = React.useState('');
|
||||
const [status, setStatus] = React.useState<TenantStatus | 'todos'>('todos');
|
||||
const [page, setPage] = React.useState(1);
|
||||
const [statusTarget, setStatusTarget] = React.useState<TenantListItem | null>(null);
|
||||
|
||||
const { data, isLoading } = useQuery({
|
||||
queryKey: ['master', 'tenants', { busca, status, page }],
|
||||
queryFn: () =>
|
||||
listTenants({
|
||||
busca: busca || undefined,
|
||||
status: status === 'todos' ? undefined : status,
|
||||
page,
|
||||
limit: LIMIT,
|
||||
}),
|
||||
placeholderData: (prev) => prev,
|
||||
});
|
||||
|
||||
const columns: DataTableColumn<TenantListItem>[] = [
|
||||
{
|
||||
id: 'nome',
|
||||
header: 'Tenant',
|
||||
primary: true,
|
||||
cell: (row) => (
|
||||
<div className="flex flex-col">
|
||||
<span className="font-medium text-foreground">{row.nome_fantasia || row.razao_social}</span>
|
||||
{row.documento && <span className="text-xs text-muted-foreground">{row.documento}</span>}
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
id: 'status',
|
||||
header: 'Status',
|
||||
primary: true,
|
||||
cell: (row) => <StatusPill status={row.status} />,
|
||||
},
|
||||
{ id: 'plano', header: 'Plano', cell: (row) => row.plano?.nome ?? '—' },
|
||||
{ id: 'criado_em', header: 'Criado em', cell: (row) => formatDate(row.criado_em) },
|
||||
];
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-6">
|
||||
<div className="flex flex-wrap items-center justify-between gap-4">
|
||||
<div>
|
||||
<h1 className="text-xl font-semibold text-foreground">Tenants</h1>
|
||||
<p className="text-sm text-muted-foreground">Clientes da plataforma SeConectai Vendas</p>
|
||||
</div>
|
||||
<Button asChild>
|
||||
<Link href="/master/tenants/novo">
|
||||
<Plus /> Novo tenant
|
||||
</Link>
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col gap-3 sm:flex-row sm:items-center">
|
||||
<div className="relative flex-1 sm:max-w-xs">
|
||||
<Search className="pointer-events-none absolute top-1/2 left-3 size-4 -translate-y-1/2 text-neutral-500" />
|
||||
<Input
|
||||
placeholder="Buscar por nome ou documento..."
|
||||
className="pl-9"
|
||||
value={busca}
|
||||
onChange={(e) => {
|
||||
setBusca(e.target.value);
|
||||
setPage(1);
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
<Select
|
||||
value={status}
|
||||
onValueChange={(value) => {
|
||||
setStatus(value as TenantStatus | 'todos');
|
||||
setPage(1);
|
||||
}}
|
||||
>
|
||||
<SelectTrigger className="w-full sm:w-48" aria-label="Filtrar por status">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{STATUS_OPTIONS.map((opt) => (
|
||||
<SelectItem key={opt.value} value={opt.value}>
|
||||
{opt.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
<DataTable
|
||||
columns={columns}
|
||||
data={data?.data ?? []}
|
||||
keyField={(row) => row.id}
|
||||
loading={isLoading}
|
||||
emptyTitle="Nenhum tenant encontrado"
|
||||
emptyDescription="Ajuste os filtros ou cadastre um novo tenant."
|
||||
emptyAction={
|
||||
<Button size="sm" asChild>
|
||||
<Link href="/master/tenants/novo">Novo tenant</Link>
|
||||
</Button>
|
||||
}
|
||||
onRowClick={(row) => router.push(`/master/tenants/${row.id}`)}
|
||||
rowActions={(row) => (
|
||||
<>
|
||||
<Button variant="ghost" size="sm" asChild>
|
||||
<Link href={`/master/tenants/${row.id}`}>Ver</Link>
|
||||
</Button>
|
||||
<Button variant="ghost" size="sm" onClick={() => setStatusTarget(row)}>
|
||||
Mudar status
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
pagination={
|
||||
data ? { page: data.meta.page, limit: data.meta.limit, total: data.meta.total, onPageChange: setPage } : undefined
|
||||
}
|
||||
/>
|
||||
|
||||
<TenantStatusDialog
|
||||
tenant={statusTarget}
|
||||
onOpenChange={(open) => !open && setStatusTarget(null)}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
import { redirect } from 'next/navigation';
|
||||
|
||||
export default function RootPage() {
|
||||
redirect('/login');
|
||||
}
|
||||
Reference in New Issue
Block a user