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