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