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,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>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user