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>
|
||||
);
|
||||
}
|
||||
@@ -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