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:
2026-08-16 09:41:13 -03:00
co-authored by Claude Sonnet 5
parent f9738e54da
commit 323912748f
179 changed files with 29312 additions and 22 deletions
@@ -0,0 +1,66 @@
import type { ReactNode } from 'react';
import { Button } from '@/components/ui/button';
import { ResponsiveDialog } from '@/components/ui/responsive-dialog';
interface ConfirmDialogProps {
open: boolean;
onOpenChange: (open: boolean) => void;
title: string;
description?: string;
confirmLabel?: string;
cancelLabel?: string;
destructive?: boolean;
loading?: boolean;
/** Desabilita o botão de confirmar (ex: falta escolher uma opção obrigatória em `children`). */
confirmDisabled?: boolean;
onConfirm: () => void;
/** Conteúdo extra entre a descrição e os botões (ex: um `Select` obrigatório) — opcional. */
children?: ReactNode;
}
/**
* Confirmação explícita antes de ações sensíveis (mudar status de tenant,
* excluir plano, disparar geração de faturas etc) — Etapa 15. `children`
* é opcional (Etapa 17: usado para pedir a forma de pagamento antes de
* marcar parcelas selecionadas como pagas em lote).
*/
export function ConfirmDialog({
open,
onOpenChange,
title,
description,
confirmLabel = 'Confirmar',
cancelLabel = 'Cancelar',
destructive = false,
loading = false,
confirmDisabled = false,
onConfirm,
children,
}: ConfirmDialogProps) {
return (
<ResponsiveDialog
open={open}
onOpenChange={onOpenChange}
title={title}
description={description}
footer={
<>
<Button variant="outline" onClick={() => onOpenChange(false)} disabled={loading}>
{cancelLabel}
</Button>
<Button
variant={destructive ? 'destructive' : 'primary'}
loading={loading}
disabled={confirmDisabled}
onClick={onConfirm}
>
{confirmLabel}
</Button>
</>
}
>
{children ?? <div className="sr-only" />}
</ResponsiveDialog>
);
}
@@ -0,0 +1,92 @@
'use client';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { useMutation, useQueryClient } from '@tanstack/react-query';
import { createCustomer, type Customer } from '@/lib/api/customers';
import { customerSchema, type CustomerFormValues } from '@/lib/validators/customers';
import { ApiError } from '@/lib/api/client';
import { toast } from '@/lib/toast';
import { Button } from '@/components/ui/button';
import { FormField } from '@/components/ui/form-field';
import { Input } from '@/components/ui/input';
import { ResponsiveDialog } from '@/components/ui/responsive-dialog';
interface CustomerQuickCreateDialogProps {
open: boolean;
onOpenChange: (open: boolean) => void;
onCreated: (customer: Customer) => void;
}
/**
* Cadastro rápido de cliente sem sair do fluxo de nova venda (Etapa 17,
* critério de aceite "não perder o que já foi preenchido na venda") — só
* os campos mínimos; o resto pode ser completado depois em
* `/app/clientes/:id`.
*/
export function CustomerQuickCreateDialog({ open, onOpenChange, onCreated }: CustomerQuickCreateDialogProps) {
const queryClient = useQueryClient();
const form = useForm<CustomerFormValues>({
resolver: zodResolver(customerSchema),
defaultValues: { razao_social: '', documento: '', email: '', telefone_whatsapp: '' },
});
const mutation = useMutation({
mutationFn: (values: CustomerFormValues) =>
createCustomer({
razao_social: values.razao_social,
documento: values.documento || undefined,
email: values.email || undefined,
telefone_whatsapp: values.telefone_whatsapp || undefined,
}),
onSuccess: (customer) => {
queryClient.invalidateQueries({ queryKey: ['tenant', 'customers'] });
toast.success('Cliente cadastrado.');
form.reset({ razao_social: '', documento: '', email: '', telefone_whatsapp: '' });
onCreated(customer);
onOpenChange(false);
},
onError: (err) => {
toast.error(err instanceof ApiError ? err.message : 'Não foi possível cadastrar o cliente.');
},
});
return (
<ResponsiveDialog
open={open}
onOpenChange={onOpenChange}
title="Cadastro rápido de cliente"
description="Só o essencial — complete o resto depois no cadastro do cliente."
footer={
<>
<Button variant="outline" onClick={() => onOpenChange(false)}>
Cancelar
</Button>
<Button loading={mutation.isPending} onClick={form.handleSubmit((values) => mutation.mutate(values))}>
Cadastrar e usar
</Button>
</>
}
>
<form
className="flex flex-col gap-4 px-4 pb-4 sm:px-0 sm:pb-0"
onSubmit={form.handleSubmit((values) => mutation.mutate(values))}
>
<FormField label="Razão social" error={form.formState.errors.razao_social?.message} required>
<Input {...form.register('razao_social')} />
</FormField>
<FormField label="Documento (CPF/CNPJ)" error={form.formState.errors.documento?.message}>
<Input {...form.register('documento')} />
</FormField>
<FormField label="Telefone/WhatsApp" error={form.formState.errors.telefone_whatsapp?.message}>
<Input {...form.register('telefone_whatsapp')} />
</FormField>
<FormField label="E-mail" error={form.formState.errors.email?.message}>
<Input type="email" {...form.register('email')} />
</FormField>
</form>
</ResponsiveDialog>
);
}
@@ -0,0 +1,81 @@
'use client';
import * as React from 'react';
import { useMutation } from '@tanstack/react-query';
import { marcarRecebimentoPago, type FormaPagamento } from '@/lib/api/sale-payments';
import { ApiError } from '@/lib/api/client';
import { formatCurrency } from '@/lib/format';
import { toast } from '@/lib/toast';
import { Button } from '@/components/ui/button';
import { ResponsiveDialog } from '@/components/ui/responsive-dialog';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
const FORMAS: { value: FormaPagamento; label: string }[] = [
{ value: 'pix', label: 'Pix' },
{ value: 'boleto', label: 'Boleto' },
{ value: 'cartao', label: 'Cartão' },
{ value: 'dinheiro', label: 'Dinheiro' },
];
interface MarcarPagoDialogProps {
parcela: { id: string; valor: string } | null;
onOpenChange: (open: boolean) => void;
onSuccess: () => void;
}
/** Reaproveitado no detalhe da venda (aba Parcelas) e em `/app/recebimentos`. */
export function MarcarPagoDialog({ parcela, onOpenChange, onSuccess }: MarcarPagoDialogProps) {
const [forma, setForma] = React.useState<FormaPagamento | ''>('');
React.useEffect(() => {
setForma('');
}, [parcela?.id]);
const mutation = useMutation({
mutationFn: () => marcarRecebimentoPago(parcela!.id, forma as FormaPagamento),
onSuccess: () => {
toast.success('Parcela marcada como paga.');
onOpenChange(false);
onSuccess();
},
onError: (err) => {
toast.error(err instanceof ApiError ? err.message : 'Não foi possível marcar a parcela como paga.');
},
});
return (
<ResponsiveDialog
open={parcela !== null}
onOpenChange={onOpenChange}
title="Marcar parcela como paga"
description={parcela ? `Valor: ${formatCurrency(parcela.valor)}` : undefined}
footer={
<>
<Button variant="outline" onClick={() => onOpenChange(false)} disabled={mutation.isPending}>
Cancelar
</Button>
<Button disabled={!forma} loading={mutation.isPending} onClick={() => mutation.mutate()}>
Confirmar pagamento
</Button>
</>
}
>
<div className="flex flex-col gap-4 px-4 pb-4 sm:px-0 sm:pb-0">
<Select value={forma} onValueChange={(value) => setForma(value as FormaPagamento)}>
<SelectTrigger className="w-full" aria-label="Forma de pagamento">
<SelectValue placeholder="Selecione a forma de pagamento" />
</SelectTrigger>
<SelectContent>
{FORMAS.map((f) => (
<SelectItem key={f.value} value={f.value}>
{f.label}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
</ResponsiveDialog>
);
}
+116
View File
@@ -0,0 +1,116 @@
'use client';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { productSchema, type ProductFormValues } from '@/lib/validators/products';
import type { ItemTipo } from '@/lib/api/products';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { FormField } from '@/components/ui/form-field';
import { Input } from '@/components/ui/input';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Textarea } from '@/components/ui/textarea';
interface ProductFormProps {
defaultValues: ProductFormValues;
onSubmit: (values: ProductFormValues) => void;
onCancel: () => void;
submitting: boolean;
submitLabel: string;
}
/** Campos de produto/serviço, compartilhado entre `/app/produtos/novo` e `/app/produtos/:id` (Etapa 16). */
export function ProductForm({ defaultValues, onSubmit, onCancel, submitting, submitLabel }: ProductFormProps) {
const form = useForm<ProductFormValues>({ resolver: zodResolver(productSchema), defaultValues });
return (
<form className="flex max-w-2xl flex-col gap-6" onSubmit={form.handleSubmit(onSubmit)}>
<Card>
<CardHeader>
<CardTitle>Dados do item</CardTitle>
</CardHeader>
<CardContent className="flex flex-col gap-4">
<div className="grid grid-cols-1 gap-4 sm:grid-cols-[160px_1fr]">
<FormField label="Tipo" id="tipo" error={form.formState.errors.tipo?.message} required>
<Select
value={form.watch('tipo')}
onValueChange={(value) => form.setValue('tipo', value as ItemTipo, { shouldValidate: true })}
>
<SelectTrigger id="tipo" className="w-full">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="produto">Produto</SelectItem>
<SelectItem value="servico">Serviço</SelectItem>
</SelectContent>
</Select>
</FormField>
<FormField label="Nome" error={form.formState.errors.nome?.message} required>
<Input {...form.register('nome')} />
</FormField>
</div>
<FormField label="Descrição" error={form.formState.errors.descricao?.message}>
<Textarea rows={2} {...form.register('descricao')} />
</FormField>
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
<FormField label="SKU" helpText="Opcional — precisa ser único no seu catálogo" error={form.formState.errors.sku?.message}>
<Input {...form.register('sku')} />
</FormField>
<FormField label="Unidade" helpText="Ex: un, kg, hora" error={form.formState.errors.unidade?.message}>
<Input {...form.register('unidade')} />
</FormField>
</div>
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
<FormField label="Valor de venda (R$)" error={form.formState.errors.valor_venda?.message} required>
<Input
type="number"
step="0.01"
min="0"
{...form.register('valor_venda', { valueAsNumber: true })}
/>
</FormField>
<FormField label="Valor de custo (R$)" helpText="Opcional" error={form.formState.errors.valor_custo?.message}>
<Input
type="number"
step="0.01"
min="0"
{...form.register('valor_custo', {
setValueAs: (v) => (v === '' ? undefined : Number(v)),
})}
/>
</FormField>
</div>
<FormField label="Recorrente" id="recorrente" error={form.formState.errors.recorrente?.message}>
<Select
value={form.watch('recorrente') ? 'true' : 'false'}
onValueChange={(value) => form.setValue('recorrente', value === 'true', { shouldValidate: true })}
>
<SelectTrigger id="recorrente" className="w-full sm:w-48">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="false">Não</SelectItem>
<SelectItem value="true">Sim — cobrança recorrente</SelectItem>
</SelectContent>
</Select>
</FormField>
</CardContent>
</Card>
<div className="flex items-center gap-3">
<Button type="submit" loading={submitting}>
{submitLabel}
</Button>
<Button type="button" variant="outline" onClick={onCancel}>
Cancelar
</Button>
</div>
</form>
);
}
+40
View File
@@ -0,0 +1,40 @@
import type { LucideIcon } from 'lucide-react';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Skeleton } from '@/components/ui/skeleton';
import { cn } from '@/lib/utils';
interface StatCardProps {
label: string;
value: string;
icon?: LucideIcon;
loading?: boolean;
tone?: 'default' | 'success' | 'warning' | 'danger';
className?: string;
}
const TONE_CLASSNAMES: Record<NonNullable<StatCardProps['tone']>, string> = {
default: 'text-foreground',
success: 'text-success',
warning: 'text-warning',
danger: 'text-danger',
};
/** Card de resumo numérico (dashboards) — Etapa 15. */
export function StatCard({ label, value, icon: Icon, loading, tone = 'default', className }: StatCardProps) {
return (
<Card className={className}>
<CardHeader className="flex flex-row items-center justify-between gap-2 space-y-0">
<CardTitle className="text-sm font-medium text-muted-foreground">{label}</CardTitle>
{Icon && <Icon className="size-4 text-muted-foreground" aria-hidden />}
</CardHeader>
<CardContent>
{loading ? (
<Skeleton className="h-8 w-24" />
) : (
<p className={cn('text-2xl font-semibold tabular-nums', TONE_CLASSNAMES[tone])}>{value}</p>
)}
</CardContent>
</Card>
);
}
@@ -0,0 +1,90 @@
'use client';
import * as React from 'react';
import { useMutation, useQueryClient } from '@tanstack/react-query';
import { updateTenantStatus, type TenantStatusTransition } from '@/lib/api/tenants';
import { ApiError } from '@/lib/api/client';
import { toast } from '@/lib/toast';
import { STATUS_PILL_MAP } from '@/components/ui/status-pill';
import { Button } from '@/components/ui/button';
import { ResponsiveDialog } from '@/components/ui/responsive-dialog';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
const TRANSITIONS: TenantStatusTransition[] = ['ativo', 'inadimplente', 'suspenso', 'cancelado'];
interface TenantStatusDialogProps {
tenant: { id: string; razao_social: string; status: string } | null;
onOpenChange: (open: boolean) => void;
onSuccess?: () => void;
}
/**
* Mudança de status de tenant com confirmação explícita (critério de
* aceite da Etapa 15) — reaproveitado pela listagem e pelo detalhe de
* tenant, já que a mesma ação aparece nos dois lugares.
*/
export function TenantStatusDialog({ tenant, onOpenChange, onSuccess }: TenantStatusDialogProps) {
const queryClient = useQueryClient();
const [target, setTarget] = React.useState<TenantStatusTransition | ''>('');
React.useEffect(() => {
setTarget('');
}, [tenant?.id]);
const mutation = useMutation({
mutationFn: (status: TenantStatusTransition) => updateTenantStatus(tenant!.id, status),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['master', 'tenants'] });
toast.success('Status do tenant atualizado.');
onOpenChange(false);
onSuccess?.();
},
onError: (err) => {
toast.error(err instanceof ApiError ? err.message : 'Não foi possível atualizar o status.');
},
});
return (
<ResponsiveDialog
open={tenant !== null}
onOpenChange={onOpenChange}
title={`Mudar status — ${tenant?.razao_social ?? ''}`}
description="Suspender ou cancelar bloqueia imediatamente o login de todos os usuários deste tenant, mesmo com sessões já abertas."
footer={
<>
<Button variant="outline" onClick={() => onOpenChange(false)} disabled={mutation.isPending}>
Cancelar
</Button>
<Button
variant={target === 'suspenso' || target === 'cancelado' ? 'destructive' : 'primary'}
disabled={!target}
loading={mutation.isPending}
onClick={() => target && mutation.mutate(target)}
>
Confirmar
</Button>
</>
}
>
<div className="flex flex-col gap-4 px-4 pb-4 sm:px-0 sm:pb-0">
<p className="text-sm text-muted-foreground">
Status atual: <span className="font-medium text-foreground">{STATUS_PILL_MAP[tenant?.status as keyof typeof STATUS_PILL_MAP]?.label ?? tenant?.status}</span>
</p>
<Select value={target} onValueChange={(v) => setTarget(v as TenantStatusTransition)}>
<SelectTrigger className="w-full" aria-label="Novo status">
<SelectValue placeholder="Selecione o novo status" />
</SelectTrigger>
<SelectContent>
{TRANSITIONS.filter((status) => status !== tenant?.status).map((status) => (
<SelectItem key={status} value={status}>
{STATUS_PILL_MAP[status].label}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
</ResponsiveDialog>
);
}
+497
View File
@@ -0,0 +1,497 @@
'use client';
import * as React from 'react';
import { useFieldArray, useForm, type UseFormRegisterReturn } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { useQuery } from '@tanstack/react-query';
import { Plus, Trash2 } from 'lucide-react';
import { listCustomers } from '@/lib/api/customers';
import { listProducts } from '@/lib/api/products';
import type { SaleInput } from '@/lib/api/sales';
import { saleFormSchema, type SaleFormValues } from '@/lib/validators/sales';
import { formatCurrency, formatDate } from '@/lib/format';
import { CustomerQuickCreateDialog } from '@/components/domain/customer-quick-create-dialog';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Combobox } from '@/components/ui/combobox';
import { FormField } from '@/components/ui/form-field';
import { Input } from '@/components/ui/input';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Textarea } from '@/components/ui/textarea';
function toCents(value: number): number {
return Math.round(value * 100);
}
function todayIso(): string {
return new Date().toISOString().slice(0, 10);
}
/** Calcula os vencimentos (30 em 30 dias) só para pré-visualização — o backend recalcula de verdade. */
function previewVencimentosAutomaticos(dataVenda: string, numeroParcelas: number): Date[] {
const base = dataVenda ? new Date(`${dataVenda}T00:00:00Z`) : new Date();
return Array.from({ length: numeroParcelas }, (_, i) => {
const d = new Date(base);
d.setUTCDate(d.getUTCDate() + 30 * (i + 1));
return d;
});
}
export interface VendaFormSubmitHandlers {
/** Só no modo `create` — salva como orçamento. */
onSaveDraft?: (input: SaleInput) => void;
/** No `create`, confirma a venda; no `edit`, salva as alterações (venda continua em orçamento). */
onConfirmOrSave: (input: SaleInput) => void;
}
interface VendaFormProps extends VendaFormSubmitHandlers {
mode: 'create' | 'edit';
defaultValues: SaleFormValues;
submittingDraft?: boolean;
submittingConfirmOrSave?: boolean;
onCancel: () => void;
}
export function VendaForm({
mode,
defaultValues,
submittingDraft,
submittingConfirmOrSave,
onSaveDraft,
onConfirmOrSave,
onCancel,
}: VendaFormProps) {
const [quickCreateOpen, setQuickCreateOpen] = React.useState(false);
const form = useForm<SaleFormValues>({ resolver: zodResolver(saleFormSchema), defaultValues });
const itensArray = useFieldArray({ control: form.control, name: 'itens' });
const parcelasArray = useFieldArray({ control: form.control, name: 'parcelasManuais' });
const customerId = form.watch('customer_id');
const itens = form.watch('itens');
const desconto = form.watch('desconto') || 0;
const dataVenda = form.watch('data_venda');
const modoParcelas = form.watch('modoParcelas');
const numeroParcelas = form.watch('numeroParcelas');
const parcelasManuais = form.watch('parcelasManuais') ?? [];
const { data: customersData } = useQuery({
queryKey: ['tenant', 'customers', 'combobox'],
queryFn: () => listCustomers({ ativo: true, limit: 100 }),
});
const { data: productsData } = useQuery({
queryKey: ['tenant', 'produtos', 'combobox'],
queryFn: () => listProducts({ ativo: true, limit: 100 }),
});
const customerOptions = (customersData?.data ?? []).map((c) => ({
value: c.id,
label: c.nome_fantasia || c.razao_social,
}));
const productOptions = (productsData?.data ?? []).map((p) => ({
value: p.id,
label: p.sku ? `${p.nome} (${p.sku})` : p.nome,
}));
const subtotalItens = itens.reduce((acc, item) => acc + item.quantidade * item.valor_unitario, 0);
const total = Math.max(0, subtotalItens - desconto);
const descontoExcedeItens = desconto > subtotalItens;
const somaParcelasManuais = parcelasManuais.reduce((acc, p) => acc + (p.valor || 0), 0);
const diffParcelas = toCents(total) - toCents(somaParcelasManuais);
const parcelasBatem = modoParcelas === 'automatico' || diffParcelas === 0;
function addItem(productId: string) {
const produto = productsData?.data.find((p) => p.id === productId);
if (!produto) return;
if (itensArray.fields.some((f) => f.product_service_id === productId)) return;
itensArray.append({
product_service_id: produto.id,
nome: produto.nome,
quantidade: 1,
valor_unitario: Number(produto.valor_venda),
valor_catalogo: Number(produto.valor_venda),
});
}
function buildInput(values: SaleFormValues): SaleInput | null {
if (values.modoParcelas === 'manual') {
if (!values.parcelasManuais || values.parcelasManuais.length === 0) {
form.setError('parcelasManuais', { message: 'Adicione pelo menos uma parcela' });
return null;
}
if (!parcelasBatem) {
form.setError('parcelasManuais', {
message: `A soma das parcelas não bate com o total da venda (diferença de ${formatCurrency(Math.abs(diffParcelas) / 100)})`,
});
return null;
}
} else if (!values.numeroParcelas || values.numeroParcelas < 1) {
form.setError('numeroParcelas', { message: 'Informe o número de parcelas' });
return null;
}
return {
customer_id: values.customer_id,
data_venda: values.data_venda,
desconto: values.desconto || undefined,
observacoes: values.observacoes || undefined,
itens: values.itens.map((item) => ({
product_service_id: item.product_service_id,
quantidade: item.quantidade,
valor_unitario: item.valor_unitario,
})),
...(values.modoParcelas === 'manual'
? { parcelas: values.parcelasManuais!.map((p) => ({ valor: p.valor, vencimento: p.vencimento })) }
: { numero_parcelas: values.numeroParcelas }),
};
}
const vencimentosPreview =
modoParcelas === 'automatico' && numeroParcelas
? previewVencimentosAutomaticos(dataVenda, numeroParcelas)
: [];
return (
<div className="flex flex-col gap-6 pb-24 lg:pb-0">
<div className="grid grid-cols-1 gap-6 lg:grid-cols-[1fr_380px]">
<div className="flex flex-col gap-6">
<Card>
<CardHeader>
<CardTitle>Cliente e data</CardTitle>
</CardHeader>
<CardContent className="flex flex-col gap-4">
<div className="flex items-end gap-2">
<FormField
label="Cliente"
id="customer_id"
className="flex-1"
error={form.formState.errors.customer_id?.message}
required
>
<Combobox
id="customer_id"
options={customerOptions}
value={customerId}
onChange={(value) => form.setValue('customer_id', value, { shouldValidate: true })}
placeholder="Selecionar cliente..."
searchPlaceholder="Buscar cliente..."
/>
</FormField>
<Button type="button" variant="outline" onClick={() => setQuickCreateOpen(true)}>
<Plus /> Novo
</Button>
</div>
<FormField label="Data da venda" error={form.formState.errors.data_venda?.message} required>
<Input type="date" {...form.register('data_venda')} />
</FormField>
<FormField label="Observações" error={form.formState.errors.observacoes?.message}>
<Textarea rows={2} {...form.register('observacoes')} />
</FormField>
</CardContent>
</Card>
<Card>
<CardHeader className="flex flex-row items-center justify-between gap-2 space-y-0">
<CardTitle>Itens da venda</CardTitle>
<div className="w-64">
<Combobox
options={productOptions}
value=""
onChange={addItem}
placeholder="Adicionar item..."
searchPlaceholder="Buscar produto/serviço..."
/>
</div>
</CardHeader>
<CardContent className="flex flex-col gap-3">
{form.formState.errors.itens?.message && (
<p className="text-sm text-destructive">{form.formState.errors.itens.message}</p>
)}
{itensArray.fields.length === 0 ? (
<p className="py-6 text-center text-sm text-muted-foreground">
Nenhum item adicionado ainda — busque um produto ou serviço acima.
</p>
) : (
<div className="flex flex-col divide-y divide-border">
{itensArray.fields.map((field, index) => {
const item = itens[index];
const alterado = item && item.valor_unitario !== item.valor_catalogo;
return (
<div key={field.id} className="flex flex-wrap items-end gap-3 py-3">
<div className="min-w-40 flex-1">
<p className="text-sm font-medium text-foreground">{field.nome}</p>
{alterado && (
<Badge variant="outline" className="mt-1">
Valor alterado do catálogo ({formatCurrency(field.valor_catalogo)})
</Badge>
)}
</div>
<FormField label="Qtd." className="w-24">
<Input
type="number"
step="0.01"
min="0.01"
{...form.register(`itens.${index}.quantidade`, { valueAsNumber: true })}
/>
</FormField>
<FormField label="Valor unit. (R$)" className="w-32">
<Input
type="number"
step="0.01"
min="0"
{...form.register(`itens.${index}.valor_unitario`, { valueAsNumber: true })}
/>
</FormField>
<div className="w-28 text-right">
<p className="text-xs text-muted-foreground">Subtotal</p>
<p className="font-medium tabular-nums text-foreground">
{formatCurrency((item?.quantidade || 0) * (item?.valor_unitario || 0))}
</p>
</div>
<Button
type="button"
variant="ghost"
size="icon-sm"
aria-label="Remover item"
onClick={() => itensArray.remove(index)}
>
<Trash2 className="size-4" />
</Button>
</div>
);
})}
</div>
)}
</CardContent>
</Card>
<Card>
<CardHeader>
<CardTitle>Parcelas</CardTitle>
</CardHeader>
<CardContent className="flex flex-col gap-4">
<Select
value={modoParcelas}
onValueChange={(value) => form.setValue('modoParcelas', value as 'automatico' | 'manual')}
>
<SelectTrigger className="w-full sm:w-64" aria-label="Modo de parcelamento">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="automatico">Gerar parcelas automaticamente</SelectItem>
<SelectItem value="manual">Definir parcelas manualmente</SelectItem>
</SelectContent>
</Select>
{modoParcelas === 'automatico' ? (
<div className="flex flex-col gap-3">
<FormField
label="Número de parcelas"
helpText="Vencimentos calculados de 30 em 30 dias a partir da data da venda"
error={form.formState.errors.numeroParcelas?.message}
className="w-40"
>
<Input
type="number"
min="1"
{...form.register('numeroParcelas', {
setValueAs: (v) => (v === '' ? undefined : Number(v)),
})}
/>
</FormField>
{vencimentosPreview.length > 0 && (
<ul className="flex flex-col gap-1 text-sm text-muted-foreground">
{vencimentosPreview.map((date, i) => (
<li key={i} className="flex justify-between tabular-nums">
<span>Parcela {i + 1}</span>
<span>{formatDate(date)}</span>
</li>
))}
</ul>
)}
</div>
) : (
<div className="flex flex-col gap-3">
{form.formState.errors.parcelasManuais?.message && (
<p className="text-sm text-destructive">{form.formState.errors.parcelasManuais.message}</p>
)}
{parcelasArray.fields.map((field, index) => (
<div key={field.id} className="flex items-end gap-2">
<FormField label={`Parcela ${index + 1} — valor`} className="flex-1">
<Input
type="number"
step="0.01"
min="0"
{...form.register(`parcelasManuais.${index}.valor`, { valueAsNumber: true })}
/>
</FormField>
<FormField label="Vencimento" className="flex-1">
<Input type="date" {...form.register(`parcelasManuais.${index}.vencimento`)} />
</FormField>
<Button
type="button"
variant="ghost"
size="icon-sm"
aria-label="Remover parcela"
onClick={() => parcelasArray.remove(index)}
>
<Trash2 className="size-4" />
</Button>
</div>
))}
<Button
type="button"
variant="outline"
size="sm"
className="self-start"
onClick={() => parcelasArray.append({ valor: 0, vencimento: dataVenda || todayIso() })}
>
<Plus /> Adicionar parcela
</Button>
<div
className={`rounded-lg p-3 text-sm ${
parcelasBatem ? 'bg-success/10 text-success' : 'bg-danger/10 text-danger'
}`}
>
Soma das parcelas: {formatCurrency(somaParcelasManuais)} —{' '}
{parcelasBatem ? 'bate com o total' : `diferença de ${formatCurrency(Math.abs(diffParcelas) / 100)}`}
</div>
</div>
)}
</CardContent>
</Card>
</div>
<div className="hidden flex-col gap-4 lg:flex">
<ResumoCard
subtotalItens={subtotalItens}
desconto={desconto}
total={total}
descontoExcedeItens={descontoExcedeItens}
formErrorDesconto={form.formState.errors.desconto?.message}
registerDesconto={form.register('desconto', { valueAsNumber: true })}
mode={mode}
submittingDraft={submittingDraft}
submittingConfirmOrSave={submittingConfirmOrSave}
onSaveDraft={onSaveDraft ? () => { const input = buildInput(form.getValues()); if (input) onSaveDraft(input); } : undefined}
onConfirmOrSave={() => { const input = buildInput(form.getValues()); if (input) onConfirmOrSave(input); }}
onCancel={onCancel}
/>
</div>
</div>
{/* Mobile: resumo + ações fixos no rodapé, sempre visíveis */}
<div className="fixed inset-x-0 bottom-16 z-10 border-t border-border bg-surface p-4 shadow-lg lg:hidden">
<div className="mb-3 flex items-center justify-between">
<span className="text-sm text-muted-foreground">Total da venda</span>
<span className="text-lg font-semibold tabular-nums text-foreground">{formatCurrency(total)}</span>
</div>
<div className="flex gap-2">
{onSaveDraft && (
<Button
type="button"
variant="outline"
className="flex-1"
loading={submittingDraft}
onClick={() => {
const input = buildInput(form.getValues());
if (input) onSaveDraft(input);
}}
>
Orçamento
</Button>
)}
<Button
type="button"
className="flex-1"
loading={submittingConfirmOrSave}
onClick={() => {
const input = buildInput(form.getValues());
if (input) onConfirmOrSave(input);
}}
>
{mode === 'create' ? 'Confirmar venda' : 'Salvar alterações'}
</Button>
</div>
</div>
<CustomerQuickCreateDialog
open={quickCreateOpen}
onOpenChange={setQuickCreateOpen}
onCreated={(customer) => form.setValue('customer_id', customer.id, { shouldValidate: true })}
/>
</div>
);
}
function ResumoCard({
subtotalItens,
desconto,
total,
descontoExcedeItens,
formErrorDesconto,
registerDesconto,
mode,
submittingDraft,
submittingConfirmOrSave,
onSaveDraft,
onConfirmOrSave,
onCancel,
}: {
subtotalItens: number;
desconto: number;
total: number;
descontoExcedeItens: boolean;
formErrorDesconto?: string;
registerDesconto: UseFormRegisterReturn<'desconto'>;
mode: 'create' | 'edit';
submittingDraft?: boolean;
submittingConfirmOrSave?: boolean;
onSaveDraft?: () => void;
onConfirmOrSave: () => void;
onCancel: () => void;
}) {
return (
<Card className="sticky top-4">
<CardHeader>
<CardTitle>Resumo</CardTitle>
</CardHeader>
<CardContent className="flex flex-col gap-4">
<FormField label="Desconto geral (R$)" error={formErrorDesconto || (descontoExcedeItens ? 'Desconto maior que a soma dos itens' : undefined)}>
<Input type="number" step="0.01" min="0" {...registerDesconto} />
</FormField>
<div className="flex flex-col gap-1.5 border-t border-border pt-3 text-sm">
<div className="flex justify-between text-muted-foreground">
<span>Subtotal itens</span>
<span className="tabular-nums">{formatCurrency(subtotalItens)}</span>
</div>
<div className="flex justify-between text-muted-foreground">
<span>Desconto</span>
<span className="tabular-nums">-{formatCurrency(desconto)}</span>
</div>
<div className="flex justify-between text-base font-semibold text-foreground">
<span>Total</span>
<span className="tabular-nums">{formatCurrency(total)}</span>
</div>
</div>
<div className="flex flex-col gap-2">
{onSaveDraft && (
<Button type="button" variant="outline" loading={submittingDraft} onClick={onSaveDraft}>
Salvar como orçamento
</Button>
)}
<Button type="button" loading={submittingConfirmOrSave} onClick={onConfirmOrSave}>
{mode === 'create' ? 'Confirmar venda' : 'Salvar alterações'}
</Button>
<Button type="button" variant="ghost" onClick={onCancel}>
Cancelar
</Button>
</div>
</CardContent>
</Card>
);
}
+115
View File
@@ -0,0 +1,115 @@
'use client';
import * as React from 'react';
import { usePathname } from 'next/navigation';
import { cn } from '@/lib/utils';
import { Sidebar } from '@/components/layout/sidebar';
import { Topbar } from '@/components/layout/topbar';
import { Drawer } from '@/components/layout/drawer';
import { BottomTabBar } from '@/components/layout/bottom-tab-bar';
import { Breadcrumb, type BreadcrumbEntry } from '@/components/layout/breadcrumb';
import { persistSidebarCollapsed } from '@/lib/layout/sidebar-cookie';
import type { NavItem } from '@/lib/layout/nav-items';
interface AppShellProps {
/** Logo/marca completa (sidebar desktop expandida e header do drawer). */
brand: React.ReactNode;
/** Só o símbolo — sidebar desktop recolhida e topbar mobile. */
brandCollapsed: React.ReactNode;
items: NavItem[];
bottomHrefs: string[];
footer: React.ReactNode;
/** Rodapé enxuto (só avatar + logout) para a sidebar recolhida. */
footerCollapsed: React.ReactNode;
initialCollapsed: boolean;
children: React.ReactNode;
}
function findBreadcrumb(items: NavItem[], pathname: string): BreadcrumbEntry[] {
for (const item of items) {
if (item.children) {
const child = item.children.find(
(c) => pathname === c.href || pathname.startsWith(`${c.href}/`),
);
if (child) return [{ label: item.label }, { label: child.label }];
}
if (pathname === item.href || pathname.startsWith(`${item.href}/`)) {
return [{ label: item.label }];
}
}
return [];
}
/**
* Casco de navegação das áreas autenticadas (Etapa 14): compõe
* Sidebar/Topbar/Drawer/BottomTabBar num único lugar para não duplicar essa
* orquestração entre o shell do master e o do tenant — cada um só passa
* marca, itens de menu e rodapé de usuário diferentes.
*/
export function AppShell({
brand,
brandCollapsed,
items,
bottomHrefs,
footer,
footerCollapsed,
initialCollapsed,
children,
}: AppShellProps) {
const pathname = usePathname();
const [collapsed, setCollapsed] = React.useState(initialCollapsed);
const [drawerOpen, setDrawerOpen] = React.useState(false);
const toggleCollapsed = React.useCallback(() => {
setCollapsed((prev) => {
const next = !prev;
persistSidebarCollapsed(next);
return next;
});
}, []);
const bottomItems = React.useMemo(
() =>
bottomHrefs
.map((href) => items.find((item) => item.href === href))
.filter((item): item is NavItem => Boolean(item)),
[items, bottomHrefs],
);
const moreItems = React.useMemo(
() => items.filter((item) => !bottomHrefs.includes(item.href)),
[items, bottomHrefs],
);
const breadcrumbItems = React.useMemo(() => findBreadcrumb(items, pathname), [items, pathname]);
return (
<div className="min-h-dvh bg-neutral-50">
<Sidebar
brand={brand}
brandCollapsed={brandCollapsed}
items={items}
footer={footer}
footerCollapsed={footerCollapsed}
collapsed={collapsed}
onToggleCollapsed={toggleCollapsed}
/>
<Drawer open={drawerOpen} onOpenChange={setDrawerOpen} brand={brand} items={items} footer={footer} />
<div
className={cn(
'flex min-h-dvh flex-col transition-[padding] duration-150',
collapsed ? 'md:pl-16' : 'md:pl-60',
)}
>
<Topbar
breadcrumb={<Breadcrumb items={breadcrumbItems} />}
mobileBrand={brandCollapsed}
onMenuClick={() => setDrawerOpen(true)}
/>
<main className="flex-1 p-4 pb-20 md:p-6 md:pb-6">{children}</main>
</div>
<BottomTabBar items={bottomItems} moreItems={moreItems} />
</div>
);
}
@@ -0,0 +1,82 @@
'use client';
import * as React from 'react';
import Link from 'next/link';
import { usePathname } from 'next/navigation';
import { Ellipsis } from 'lucide-react';
import { cn } from '@/lib/utils';
import { Sheet, SheetContent, SheetHeader, SheetTitle } from '@/components/ui/sheet';
import { NavList } from '@/components/layout/nav-list';
import type { NavItem } from '@/lib/layout/nav-items';
function isActive(pathname: string, href: string): boolean {
return pathname === href || pathname.startsWith(`${href}/`);
}
interface BottomTabBarProps {
/** Os 4 itens principais, já resolvidos na ordem de exibição. */
items: NavItem[];
/** Restante do menu, exibido no sheet "Mais". */
moreItems: NavItem[];
}
/** Bottom tab bar mobile (`<md`) — 4 itens fixos + "Mais" com o restante do menu. */
export function BottomTabBar({ items, moreItems }: BottomTabBarProps) {
const pathname = usePathname();
const [moreOpen, setMoreOpen] = React.useState(false);
const moreActive = moreItems.some(
(item) => isActive(pathname, item.href) || item.children?.some((child) => isActive(pathname, child.href)),
);
return (
<>
<nav
aria-label="Navegação principal"
className="fixed inset-x-0 bottom-0 z-20 flex h-16 items-stretch border-t border-border bg-surface md:hidden"
>
{items.map((item) => {
const Icon = item.icon;
const active = isActive(pathname, item.href);
return (
<Link
key={item.href}
href={item.href}
aria-current={active ? 'page' : undefined}
className={cn(
'flex flex-1 flex-col items-center justify-center gap-0.5 text-[11px] font-medium text-neutral-500',
active && 'text-primary-on-light',
)}
>
<Icon className="size-5" aria-hidden />
{item.label}
</Link>
);
})}
<button
type="button"
onClick={() => setMoreOpen(true)}
aria-haspopup="dialog"
className={cn(
'flex flex-1 flex-col items-center justify-center gap-0.5 text-[11px] font-medium text-neutral-500',
moreActive && 'text-primary-on-light',
)}
>
<Ellipsis className="size-5" aria-hidden />
Mais
</button>
</nav>
<Sheet open={moreOpen} onOpenChange={setMoreOpen}>
<SheetContent side="bottom" className="max-h-[70vh] gap-0 p-0">
<SheetHeader>
<SheetTitle>Mais opções</SheetTitle>
</SheetHeader>
<div className="overflow-y-auto px-3 pb-4">
<NavList items={moreItems} onNavigate={() => setMoreOpen(false)} />
</div>
</SheetContent>
</Sheet>
</>
);
}
+46
View File
@@ -0,0 +1,46 @@
import Link from 'next/link';
import { ChevronRight } from 'lucide-react';
import { cn } from '@/lib/utils';
export interface BreadcrumbEntry {
label: string;
href?: string;
}
/**
* Gerado manualmente a partir do item de menu ativo em `AppShell` nesta
* primeira versão (Etapa 14) — automatizar a partir da árvore de rotas do
* Next é uma melhoria natural de uma etapa futura, quando houver páginas
* com mais de 2 níveis (ex: detalhe dentro de uma lista).
*/
export function Breadcrumb({ items, className }: { items: BreadcrumbEntry[]; className?: string }) {
if (items.length === 0) return null;
return (
<nav aria-label="Breadcrumb" className={cn('min-w-0', className)}>
<ol className="flex min-w-0 items-center gap-1.5 text-sm">
{items.map((item, index) => {
const last = index === items.length - 1;
return (
<li key={`${item.label}-${index}`} className="flex min-w-0 items-center gap-1.5">
{index > 0 && <ChevronRight className="size-3.5 shrink-0 text-neutral-500" aria-hidden />}
{item.href && !last ? (
<Link href={item.href} className="truncate text-neutral-500 hover:text-foreground">
{item.label}
</Link>
) : (
<span
className={cn('truncate', last ? 'font-medium text-foreground' : 'text-neutral-500')}
aria-current={last ? 'page' : undefined}
>
{item.label}
</span>
)}
</li>
);
})}
</ol>
</nav>
);
}
+40
View File
@@ -0,0 +1,40 @@
'use client';
import * as React from 'react';
import { Sheet, SheetContent, SheetHeader, SheetTitle } from '@/components/ui/sheet';
import { Separator } from '@/components/ui/separator';
import { NavList } from '@/components/layout/nav-list';
import type { NavItem } from '@/lib/layout/nav-items';
interface DrawerProps {
open: boolean;
onOpenChange: (open: boolean) => void;
brand: React.ReactNode;
items: NavItem[];
footer: React.ReactNode;
}
/**
* Menu deslizante mobile — réplica do menu completo da sidebar desktop.
* Fecha ao navegar (`NavList.onNavigate`) ou ao tocar fora (comportamento
* padrão do `Sheet`/Radix Dialog).
*/
export function Drawer({ open, onOpenChange, brand, items, footer }: DrawerProps) {
return (
<Sheet open={open} onOpenChange={onOpenChange}>
<SheetContent side="left" className="w-4/5 gap-0 p-0">
<SheetHeader className="h-16 flex-row items-center gap-2 px-4 py-0">
{brand}
<SheetTitle className="sr-only">Menu de navegação</SheetTitle>
</SheetHeader>
<Separator />
<div className="min-h-0 flex-1 overflow-y-auto px-3 py-4">
<NavList items={items} onNavigate={() => onOpenChange(false)} />
</div>
<Separator />
<div className="flex flex-col gap-2 p-3">{footer}</div>
</SheetContent>
</Sheet>
);
}
@@ -0,0 +1,63 @@
'use client';
import * as React from 'react';
import { AppShell } from '@/components/layout/app-shell';
import { UserFooter } from '@/components/layout/user-footer';
import { useAuth } from '@/lib/auth/auth-context';
import { MASTER_NAV_ITEMS, MASTER_BOTTOM_HREFS } from '@/lib/layout/nav-items';
function MasterBrandSymbol() {
return (
<span className="flex size-9 shrink-0 items-center justify-center rounded-lg bg-brand-master text-sm font-bold text-white">
SV
</span>
);
}
/** Identidade fixa do painel master — nunca whitelabel (ver `TenantShell`). */
function MasterBrand() {
return (
<>
<MasterBrandSymbol />
<span className="truncate text-sm font-semibold text-neutral-950">SeConectai Vendas</span>
</>
);
}
export function MasterShell({
initialCollapsed,
children,
}: {
initialCollapsed: boolean;
children: React.ReactNode;
}) {
const { logout } = useAuth();
const handleLogout = React.useCallback(() => {
void logout();
}, [logout]);
return (
// `Sidebar`/`BottomTabBar`/`NavList` destacam o item ativo com os tokens
// `--color-primary(-on-light)` — dinâmicos por tenant (Etapa 13). O
// master tem identidade fixa (seção 6 da arquitetura), então essa
// sobrescrita local troca esses tokens por `--brand-master` só dentro
// desta árvore, sem tocar no `:root` (evitaria vazar pro `/app` do
// tenant na mesma aba).
<div
style={{ '--color-primary': 'var(--brand-master)', '--color-primary-on-light': 'var(--brand-master)' } as React.CSSProperties}
>
<AppShell
brand={<MasterBrand />}
brandCollapsed={<MasterBrandSymbol />}
items={MASTER_NAV_ITEMS}
bottomHrefs={MASTER_BOTTOM_HREFS}
footer={<UserFooter label="Administrador master" onLogout={handleLogout} />}
footerCollapsed={<UserFooter label="Administrador master" compact onLogout={handleLogout} />}
initialCollapsed={initialCollapsed}
>
{children}
</AppShell>
</div>
);
}
+105
View File
@@ -0,0 +1,105 @@
'use client';
import * as React from 'react';
import Link from 'next/link';
import { usePathname } from 'next/navigation';
import { ChevronDown } from 'lucide-react';
import { cn } from '@/lib/utils';
import type { NavItem } from '@/lib/layout/nav-items';
function isActive(pathname: string, href: string): boolean {
return pathname === href || pathname.startsWith(`${href}/`);
}
function isGroupActive(pathname: string, item: NavItem): boolean {
if (isActive(pathname, item.href)) return true;
return item.children?.some((child) => isActive(pathname, child.href)) ?? false;
}
interface NavListProps {
items: NavItem[];
/** Modo ícones-apenas (sidebar recolhida) — grupos viram link direto pro primeiro filho. */
collapsed?: boolean;
/** Disparado ao navegar (o Drawer usa isso para fechar). */
onNavigate?: () => void;
}
/**
* Lista de navegação com estado de item/grupo ativo — compartilhada entre
* `Sidebar` (desktop) e `Drawer` (mobile) para não duplicar essa lógica em
* dois lugares.
*/
export function NavList({ items, collapsed = false, onNavigate }: NavListProps) {
const pathname = usePathname();
const [openHref, setOpenHref] = React.useState<string | null>(null);
return (
<nav className="flex flex-col gap-1">
{items.map((item) => {
const Icon = item.icon;
const active = isGroupActive(pathname, item);
if (item.children && !collapsed) {
const open = openHref === item.href || (openHref === null && active);
return (
<div key={item.href}>
<button
type="button"
onClick={() => setOpenHref(open ? '' : item.href)}
aria-expanded={open}
className={cn(
'flex w-full items-center gap-3 rounded-lg px-3 py-2.5 text-sm font-medium text-neutral-500 transition-colors hover:bg-muted hover:text-foreground',
active && 'bg-primary/10 text-primary-on-light',
)}
>
<Icon className="size-4.5 shrink-0" aria-hidden />
<span className="flex-1 text-left">{item.label}</span>
<ChevronDown
className={cn('size-4 shrink-0 transition-transform', open && 'rotate-180')}
aria-hidden
/>
</button>
{open && (
<div className="ml-4 flex flex-col gap-0.5 border-l border-border py-1 pl-4">
{item.children.map((child) => (
<Link
key={child.href}
href={child.href}
onClick={onNavigate}
aria-current={isActive(pathname, child.href) ? 'page' : undefined}
className={cn(
'rounded-lg px-3 py-2 text-sm text-neutral-500 transition-colors hover:bg-muted hover:text-foreground',
isActive(pathname, child.href) && 'font-medium text-primary-on-light',
)}
>
{child.label}
</Link>
))}
</div>
)}
</div>
);
}
return (
<Link
key={item.href}
href={item.href}
onClick={onNavigate}
aria-current={active ? 'page' : undefined}
title={collapsed ? item.label : undefined}
className={cn(
'flex items-center gap-3 rounded-lg px-3 py-2.5 text-sm font-medium text-neutral-500 transition-colors hover:bg-muted hover:text-foreground',
active && 'bg-primary/10 text-primary-on-light',
collapsed && 'mx-auto size-11 justify-center px-0 py-0',
)}
>
<Icon className="size-4.5 shrink-0" aria-hidden />
{!collapsed && <span>{item.label}</span>}
</Link>
);
})}
</nav>
);
}
+66
View File
@@ -0,0 +1,66 @@
'use client';
import * as React from 'react';
import { PanelLeftClose, PanelLeftOpen } from 'lucide-react';
import { cn } from '@/lib/utils';
import { Button } from '@/components/ui/button';
import { Separator } from '@/components/ui/separator';
import { NavList } from '@/components/layout/nav-list';
import type { NavItem } from '@/lib/layout/nav-items';
interface SidebarProps {
brand: React.ReactNode;
brandCollapsed: React.ReactNode;
items: NavItem[];
footer: React.ReactNode;
footerCollapsed: React.ReactNode;
collapsed: boolean;
onToggleCollapsed: () => void;
}
/**
* Sidebar fixa (desktop, `md+`). Itens de menu e rodapé de usuário chegam
* via props — sem nada hardcoded — para ser reaproveitada entre o shell do
* master e o do tenant com conteúdo diferente (Etapa 14).
*/
export function Sidebar({
brand,
brandCollapsed,
items,
footer,
footerCollapsed,
collapsed,
onToggleCollapsed,
}: SidebarProps) {
return (
<aside
className={cn(
'fixed inset-y-0 left-0 z-30 hidden flex-col border-r border-border bg-surface transition-[width] duration-150 md:flex',
collapsed ? 'w-16' : 'w-60',
)}
>
<div className={cn('flex h-16 shrink-0 items-center gap-2 overflow-hidden px-4', collapsed && 'justify-center px-2')}>
{collapsed ? brandCollapsed : brand}
</div>
<Separator />
<div className="min-h-0 flex-1 overflow-y-auto px-3 py-4">
<NavList items={items} collapsed={collapsed} />
</div>
<Separator />
<div className={cn('flex flex-col gap-2 p-3', collapsed && 'items-center')}>
{collapsed ? footerCollapsed : footer}
<Button
type="button"
variant="ghost"
size="icon-sm"
onClick={onToggleCollapsed}
aria-label={collapsed ? 'Expandir menu' : 'Recolher menu'}
className={collapsed ? 'self-center' : 'self-end'}
>
{collapsed ? <PanelLeftOpen className="size-4" /> : <PanelLeftClose className="size-4" />}
</Button>
</div>
</aside>
);
}
@@ -0,0 +1,94 @@
'use client';
import * as React from 'react';
import Image from 'next/image';
import { AppShell } from '@/components/layout/app-shell';
import { UserFooter } from '@/components/layout/user-footer';
import { useAuth } from '@/lib/auth/auth-context';
import { TenantThemeProvider, useTenantTheme } from '@/lib/theme/theme-provider';
import { TENANT_NAV_ITEMS, TENANT_BOTTOM_HREFS, filterByRole } from '@/lib/layout/nav-items';
import type { UserRole } from '@/lib/auth/jwt';
const ROLE_LABELS: Record<UserRole, string> = {
tenant_admin: 'Administrador',
vendedor: 'Vendedor',
financeiro: 'Financeiro',
visualizador: 'Visualizador',
};
/** Logo/nome resolvidos do tema do tenant (Etapa 13); cai para a marca padrão sem tema. */
function TenantBrand({ collapsed = false }: { collapsed?: boolean }) {
const { theme } = useTenantTheme();
const name = theme?.nome ?? 'SeConectai Vendas';
return (
<>
{theme?.logoUrl ? (
<Image
src={theme.logoUrl}
alt={name}
width={36}
height={36}
className="size-9 shrink-0 rounded-lg object-contain"
/>
) : (
<span className="flex size-9 shrink-0 items-center justify-center rounded-lg bg-primary text-sm font-bold text-primary-foreground">
{name.charAt(0).toUpperCase()}
</span>
)}
{!collapsed && <span className="truncate text-sm font-semibold text-neutral-950">{name}</span>}
</>
);
}
function TenantShellInner({
initialCollapsed,
children,
}: {
initialCollapsed: boolean;
children: React.ReactNode;
}) {
const { user, logout } = useAuth();
const handleLogout = React.useCallback(() => {
void logout();
}, [logout]);
const items = React.useMemo(() => filterByRole(TENANT_NAV_ITEMS, user?.role), [user?.role]);
const roleLabel = user?.role ? ROLE_LABELS[user.role] : 'Usuário';
return (
<AppShell
brand={<TenantBrand />}
brandCollapsed={<TenantBrand collapsed />}
items={items}
bottomHrefs={TENANT_BOTTOM_HREFS}
footer={<UserFooter label={roleLabel} onLogout={handleLogout} />}
footerCollapsed={<UserFooter label={roleLabel} compact onLogout={handleLogout} />}
initialCollapsed={initialCollapsed}
>
{children}
</AppShell>
);
}
/**
* Shell da área `/app`. Resolve o tema do tenant a partir do `tenant_id` do
* usuário autenticado (Etapa 13) e filtra os itens de menu por `role` — ex:
* "Equipe" só aparece para `tenant_admin` (Etapa 14, critério de aceite).
*/
export function TenantShell({
initialCollapsed,
children,
}: {
initialCollapsed: boolean;
children: React.ReactNode;
}) {
const { user } = useAuth();
return (
<TenantThemeProvider tenantId={user?.tenant_id ?? null}>
<TenantShellInner initialCollapsed={initialCollapsed}>{children}</TenantShellInner>
</TenantThemeProvider>
);
}
+52
View File
@@ -0,0 +1,52 @@
'use client';
import * as React from 'react';
import { Bell, Menu, Search } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
interface TopbarProps {
breadcrumb: React.ReactNode;
/** Logo compacta (só símbolo) exibida no lugar do breadcrumb no mobile. */
mobileBrand: React.ReactNode;
onMenuClick: () => void;
}
/**
* Topbar fixa no topo. Desktop: breadcrumb + busca rápida + notificações.
* Mobile (`<md`): logo símbolo + hambúrguer (abre o `Drawer`) + notificações
* — a busca funcional real fica para a Etapa 18/19, aqui só o componente.
*/
export function Topbar({ breadcrumb, mobileBrand, onMenuClick }: TopbarProps) {
return (
<header className="sticky top-0 z-20 flex h-16 items-center gap-3 border-b border-border bg-surface px-4 md:px-6">
<Button
type="button"
variant="ghost"
size="icon-sm"
className="md:hidden"
onClick={onMenuClick}
aria-label="Abrir menu"
>
<Menu className="size-5" />
</Button>
<div className="flex min-w-0 flex-1 items-center gap-3">
<div className="md:hidden">{mobileBrand}</div>
<div className="hidden min-w-0 md:block">{breadcrumb}</div>
</div>
<div className="hidden max-w-xs flex-1 items-center md:flex">
<div className="relative w-full">
<Search className="pointer-events-none absolute top-1/2 left-3 size-4 -translate-y-1/2 text-neutral-500" />
<Input placeholder="Buscar clientes, vendas..." className="pl-9" aria-label="Busca rápida" />
</div>
</div>
<Button type="button" variant="ghost" size="icon-sm" aria-label="Notificações">
<Bell className="size-5" />
</Button>
</header>
);
}
@@ -0,0 +1,48 @@
'use client';
import { LogOut } from 'lucide-react';
import { cn } from '@/lib/utils';
import { Button } from '@/components/ui/button';
interface UserFooterProps {
label: string;
sublabel?: string;
onLogout: () => void;
/** Sidebar recolhida/drawer fechado: só avatar + botão de sair, sem texto. */
compact?: boolean;
}
/**
* Rodapé de identidade + logout da sidebar/drawer (Etapa 14). O access
* token (`lib/auth/jwt.ts`) não carrega nome/e-mail do usuário — só
* `sub`/`tipo`/`tenant_id`/`role` — então a identificação aqui é o papel do
* usuário, não o nome; ver observação da Etapa 14 no controle de progresso.
*/
export function UserFooter({ label, sublabel, onLogout, compact = false }: UserFooterProps) {
const initial = label.charAt(0).toUpperCase();
return (
<div className={cn('flex w-full items-center gap-2', compact && 'w-auto flex-col')}>
<span className="flex size-9 shrink-0 items-center justify-center rounded-full bg-muted text-sm font-semibold text-foreground">
{initial}
</span>
{!compact && (
<div className="min-w-0 flex-1">
<p className="truncate text-sm font-medium text-foreground">{label}</p>
{sublabel && <p className="truncate text-xs text-neutral-500">{sublabel}</p>}
</div>
)}
<Button
type="button"
variant="ghost"
size="icon-sm"
onClick={onLogout}
aria-label="Sair"
title="Sair"
>
<LogOut className="size-4" />
</Button>
</div>
);
}
+45
View File
@@ -0,0 +1,45 @@
import * as React from 'react';
import { cva, type VariantProps } from 'class-variance-authority';
import { Slot } from 'radix-ui';
import { cn } from '@/lib/utils';
const badgeVariants = cva(
'group/badge inline-flex h-5 w-fit shrink-0 items-center justify-center gap-1 overflow-hidden rounded-4xl border border-transparent px-2 py-0.5 text-xs font-medium whitespace-nowrap transition-all focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 has-data-[icon=inline-end]:pr-1.5 has-data-[icon=inline-start]:pl-1.5 aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 [&>svg]:pointer-events-none [&>svg]:size-3!',
{
variants: {
variant: {
default: 'bg-primary text-primary-foreground [a]:hover:bg-primary/80',
secondary: 'bg-secondary text-secondary-foreground [a]:hover:bg-secondary/80',
destructive:
'bg-destructive/10 text-destructive focus-visible:ring-destructive/20 dark:bg-destructive/20 dark:focus-visible:ring-destructive/40 [a]:hover:bg-destructive/20',
outline: 'border-border text-foreground [a]:hover:bg-muted [a]:hover:text-muted-foreground',
ghost: 'hover:bg-muted hover:text-muted-foreground dark:hover:bg-muted/50',
link: 'text-primary underline-offset-4 hover:underline',
},
},
defaultVariants: {
variant: 'default',
},
},
);
function Badge({
className,
variant = 'default',
asChild = false,
...props
}: React.ComponentProps<'span'> & VariantProps<typeof badgeVariants> & { asChild?: boolean }) {
const Comp = asChild ? Slot.Root : 'span';
return (
<Comp
data-slot="badge"
data-variant={variant}
className={cn(badgeVariants({ variant }), className)}
{...props}
/>
);
}
export { Badge, badgeVariants };
+95
View File
@@ -0,0 +1,95 @@
import * as React from 'react';
import { cva, type VariantProps } from 'class-variance-authority';
import { Slot } from 'radix-ui';
import { Loader2Icon } from 'lucide-react';
import { cn } from '@/lib/utils';
const buttonVariants = cva(
"group/button inline-flex shrink-0 items-center justify-center rounded-lg border border-transparent bg-clip-padding text-sm font-medium whitespace-nowrap transition-all outline-none select-none focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 active:not-aria-[haspopup]:translate-y-px disabled:pointer-events-none disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
{
variants: {
variant: {
primary: 'bg-primary text-primary-foreground hover:bg-primary/90',
secondary:
'bg-secondary text-secondary-foreground border-border hover:bg-[color-mix(in_oklch,var(--secondary),var(--foreground)_5%)]',
destructive: 'bg-destructive text-destructive-foreground hover:bg-destructive/90',
ghost:
'hover:bg-muted hover:text-foreground aria-expanded:bg-muted aria-expanded:text-foreground',
outline:
'border-border bg-background hover:bg-muted hover:text-foreground aria-expanded:bg-muted aria-expanded:text-foreground',
link: 'text-primary underline-offset-4 hover:underline',
},
// `sm` fica abaixo de 44px de propósito: reservado para ações densas
// (ex: linha de tabela), nunca a única forma de disparar uma ação —
// ver Etapas/V2/20-controle-de-progresso-frontend.md, Etapa 12.
size: {
sm: 'h-8 gap-1.5 px-2.5 has-data-[icon=inline-end]:pr-2 has-data-[icon=inline-start]:pl-2',
md: 'h-11 min-w-11 gap-2 px-4 has-data-[icon=inline-end]:pr-3.5 has-data-[icon=inline-start]:pl-3.5',
lg: 'h-12 min-w-11 gap-2 px-5 text-base has-data-[icon=inline-end]:pr-4 has-data-[icon=inline-start]:pl-4',
icon: 'size-11',
'icon-sm': 'size-8',
'icon-lg': 'size-12',
},
},
defaultVariants: {
variant: 'primary',
size: 'md',
},
},
);
type ButtonProps = React.ComponentProps<'button'> &
VariantProps<typeof buttonVariants> & {
asChild?: boolean;
loading?: boolean;
};
function Button({
className,
variant,
size,
asChild = false,
loading = false,
disabled,
children,
...props
}: ButtonProps) {
// `Slot.Root` (Radix) exige exatamente um filho React — o wrapper de
// loading/span abaixo (usado no `<button>` nativo) sempre passaria 2
// filhos (o `{loading && ...}` condicional + o `<span>`), quebrando o
// `asChild`. Sem estado de loading fazer sentido quando quem renderiza de
// verdade é o filho (ex: um `Link`), `asChild` passa `children` direto.
if (asChild) {
return (
<Slot.Root
data-slot="button"
data-variant={variant}
data-size={size}
className={cn(buttonVariants({ variant, size, className }))}
{...props}
>
{children}
</Slot.Root>
);
}
return (
<button
data-slot="button"
data-variant={variant}
data-size={size}
aria-busy={loading || undefined}
className={cn(buttonVariants({ variant, size, className }), loading && 'relative')}
disabled={disabled || loading}
{...props}
>
{loading && <Loader2Icon className="absolute size-4 animate-spin" aria-hidden />}
<span className={cn('inline-flex items-center gap-2', loading && 'invisible')}>
{children}
</span>
</button>
);
}
export { Button, buttonVariants };
+186
View File
@@ -0,0 +1,186 @@
'use client';
import * as React from 'react';
import { DayPicker, getDefaultClassNames, type DayButton, type Locale } from 'react-day-picker';
import { cn } from '@/lib/utils';
import { Button, buttonVariants } from '@/components/ui/button';
import { ChevronLeftIcon, ChevronRightIcon, ChevronDownIcon } from 'lucide-react';
function Calendar({
className,
classNames,
showOutsideDays = true,
captionLayout = 'label',
buttonVariant = 'ghost',
locale,
formatters,
components,
...props
}: React.ComponentProps<typeof DayPicker> & {
buttonVariant?: React.ComponentProps<typeof Button>['variant'];
}) {
const defaultClassNames = getDefaultClassNames();
return (
<DayPicker
showOutsideDays={showOutsideDays}
className={cn(
'group/calendar bg-background p-2 [--cell-radius:var(--radius-md)] [--cell-size:--spacing(7)] in-data-[slot=card-content]:bg-transparent in-data-[slot=popover-content]:bg-transparent',
String.raw`rtl:**:[.rdp-button\_next>svg]:rotate-180`,
String.raw`rtl:**:[.rdp-button\_previous>svg]:rotate-180`,
className,
)}
captionLayout={captionLayout}
locale={locale}
formatters={{
formatMonthDropdown: (date) => date.toLocaleString(locale?.code, { month: 'short' }),
...formatters,
}}
classNames={{
root: cn('w-fit', defaultClassNames.root),
months: cn('relative flex flex-col gap-4 md:flex-row', defaultClassNames.months),
month: cn('flex w-full flex-col gap-4', defaultClassNames.month),
nav: cn(
'absolute inset-x-0 top-0 flex w-full items-center justify-between gap-1',
defaultClassNames.nav,
),
button_previous: cn(
buttonVariants({ variant: buttonVariant }),
'size-(--cell-size) p-0 select-none aria-disabled:opacity-50',
defaultClassNames.button_previous,
),
button_next: cn(
buttonVariants({ variant: buttonVariant }),
'size-(--cell-size) p-0 select-none aria-disabled:opacity-50',
defaultClassNames.button_next,
),
month_caption: cn(
'flex h-(--cell-size) w-full items-center justify-center px-(--cell-size)',
defaultClassNames.month_caption,
),
dropdowns: cn(
'flex h-(--cell-size) w-full items-center justify-center gap-1.5 text-sm font-medium',
defaultClassNames.dropdowns,
),
dropdown_root: cn('relative rounded-(--cell-radius)', defaultClassNames.dropdown_root),
dropdown: cn('absolute inset-0 bg-popover opacity-0', defaultClassNames.dropdown),
caption_label: cn(
'font-medium select-none',
captionLayout === 'label'
? 'text-sm'
: 'flex items-center gap-1 rounded-(--cell-radius) text-sm [&>svg]:size-3.5 [&>svg]:text-muted-foreground',
defaultClassNames.caption_label,
),
month_grid: cn('w-full border-collapse', defaultClassNames.month_grid),
weekdays: cn('flex', defaultClassNames.weekdays),
weekday: cn(
'flex-1 rounded-(--cell-radius) text-[0.8rem] font-normal text-muted-foreground select-none',
defaultClassNames.weekday,
),
week: cn('mt-2 flex w-full', defaultClassNames.week),
week_number_header: cn('w-(--cell-size) select-none', defaultClassNames.week_number_header),
week_number: cn(
'text-[0.8rem] text-muted-foreground select-none',
defaultClassNames.week_number,
),
day: cn(
'group/day relative aspect-square h-full w-full rounded-(--cell-radius) p-0 text-center select-none [&:last-child[data-selected=true]_button]:rounded-r-(--cell-radius)',
props.showWeekNumber
? '[&:nth-child(2)[data-selected=true]_button]:rounded-l-(--cell-radius)'
: '[&:first-child[data-selected=true]_button]:rounded-l-(--cell-radius)',
defaultClassNames.day,
),
range_start: cn(
'relative isolate z-0 rounded-l-(--cell-radius) bg-muted after:absolute after:inset-y-0 after:right-0 after:w-4 after:bg-muted',
defaultClassNames.range_start,
),
range_middle: cn('rounded-none', defaultClassNames.range_middle),
range_end: cn(
'relative isolate z-0 rounded-r-(--cell-radius) bg-muted after:absolute after:inset-y-0 after:left-0 after:w-4 after:bg-muted',
defaultClassNames.range_end,
),
today: cn(
'rounded-(--cell-radius) bg-muted text-foreground data-[selected=true]:rounded-none',
defaultClassNames.today,
),
outside: cn(
'text-muted-foreground aria-selected:text-muted-foreground',
defaultClassNames.outside,
),
disabled: cn('text-muted-foreground opacity-50', defaultClassNames.disabled),
hidden: cn('invisible', defaultClassNames.hidden),
...classNames,
}}
components={{
Root: ({ className, rootRef, ...props }) => {
return <div data-slot="calendar" ref={rootRef} className={cn(className)} {...props} />;
},
Chevron: ({ className, orientation, ...props }) => {
if (orientation === 'left') {
return <ChevronLeftIcon className={cn('size-4', className)} {...props} />;
}
if (orientation === 'right') {
return <ChevronRightIcon className={cn('size-4', className)} {...props} />;
}
return <ChevronDownIcon className={cn('size-4', className)} {...props} />;
},
DayButton: ({ ...props }) => <CalendarDayButton locale={locale} {...props} />,
WeekNumber: ({ children, ...props }) => {
return (
<td {...props}>
<div className="flex size-(--cell-size) items-center justify-center text-center">
{children}
</div>
</td>
);
},
...components,
}}
{...props}
/>
);
}
function CalendarDayButton({
className,
day,
modifiers,
locale,
...props
}: React.ComponentProps<typeof DayButton> & { locale?: Partial<Locale> }) {
const defaultClassNames = getDefaultClassNames();
const ref = React.useRef<HTMLButtonElement>(null);
React.useEffect(() => {
if (modifiers.focused) ref.current?.focus();
}, [modifiers.focused]);
return (
<Button
ref={ref}
variant="ghost"
size="icon"
data-day={day.date.toLocaleDateString(locale?.code)}
data-selected-single={
modifiers.selected &&
!modifiers.range_start &&
!modifiers.range_end &&
!modifiers.range_middle
}
data-range-start={modifiers.range_start}
data-range-end={modifiers.range_end}
data-range-middle={modifiers.range_middle}
className={cn(
'relative isolate z-10 flex aspect-square size-auto w-full min-w-(--cell-size) flex-col gap-1 border-0 leading-none font-normal group-data-[focused=true]/day:relative group-data-[focused=true]/day:z-10 group-data-[focused=true]/day:border-ring group-data-[focused=true]/day:ring-[3px] group-data-[focused=true]/day:ring-ring/50 data-[range-end=true]:rounded-(--cell-radius) data-[range-end=true]:rounded-r-(--cell-radius) data-[range-end=true]:bg-primary data-[range-end=true]:text-primary-foreground data-[range-middle=true]:rounded-none data-[range-middle=true]:bg-muted data-[range-middle=true]:text-foreground data-[range-start=true]:rounded-(--cell-radius) data-[range-start=true]:rounded-l-(--cell-radius) data-[range-start=true]:bg-primary data-[range-start=true]:text-primary-foreground data-[selected-single=true]:bg-primary data-[selected-single=true]:text-primary-foreground dark:hover:text-foreground [&>span]:text-xs [&>span]:opacity-70',
defaultClassNames.day,
className,
)}
{...props}
/>
);
}
export { Calendar, CalendarDayButton };
+88
View File
@@ -0,0 +1,88 @@
import * as React from 'react';
import { cn } from '@/lib/utils';
function Card({
className,
size = 'default',
...props
}: React.ComponentProps<'div'> & { size?: 'default' | 'sm' }) {
return (
<div
data-slot="card"
data-size={size}
className={cn(
'group/card flex flex-col gap-(--card-spacing) overflow-hidden rounded-xl bg-card py-(--card-spacing) text-sm text-card-foreground ring-1 ring-foreground/10 [--card-spacing:--spacing(4)] has-data-[slot=card-footer]:pb-0 has-[>img:first-child]:pt-0 data-[size=sm]:[--card-spacing:--spacing(3)] data-[size=sm]:has-data-[slot=card-footer]:pb-0 *:[img:first-child]:rounded-t-xl *:[img:last-child]:rounded-b-xl',
className,
)}
{...props}
/>
);
}
function CardHeader({ className, ...props }: React.ComponentProps<'div'>) {
return (
<div
data-slot="card-header"
className={cn(
'group/card-header @container/card-header grid auto-rows-min items-start gap-1 rounded-t-xl px-(--card-spacing) has-data-[slot=card-action]:grid-cols-[1fr_auto] has-data-[slot=card-description]:grid-rows-[auto_auto] [.border-b]:pb-(--card-spacing)',
className,
)}
{...props}
/>
);
}
function CardTitle({ className, ...props }: React.ComponentProps<'div'>) {
return (
<div
data-slot="card-title"
className={cn(
'text-base leading-snug font-medium group-data-[size=sm]/card:text-sm',
className,
)}
{...props}
/>
);
}
function CardDescription({ className, ...props }: React.ComponentProps<'div'>) {
return (
<div
data-slot="card-description"
className={cn('text-sm text-muted-foreground', className)}
{...props}
/>
);
}
function CardAction({ className, ...props }: React.ComponentProps<'div'>) {
return (
<div
data-slot="card-action"
className={cn('col-start-2 row-span-2 row-start-1 self-start justify-self-end', className)}
{...props}
/>
);
}
function CardContent({ className, ...props }: React.ComponentProps<'div'>) {
return (
<div data-slot="card-content" className={cn('px-(--card-spacing)', className)} {...props} />
);
}
function CardFooter({ className, ...props }: React.ComponentProps<'div'>) {
return (
<div
data-slot="card-footer"
className={cn(
'flex items-center rounded-b-xl border-t bg-muted/50 p-(--card-spacing)',
className,
)}
{...props}
/>
);
}
export { Card, CardHeader, CardFooter, CardTitle, CardAction, CardDescription, CardContent };
+109
View File
@@ -0,0 +1,109 @@
'use client';
import * as React from 'react';
import { CheckIcon, ChevronsUpDownIcon } from 'lucide-react';
import { cn } from '@/lib/utils';
import { Button } from '@/components/ui/button';
import {
Command,
CommandEmpty,
CommandGroup,
CommandInput,
CommandItem,
CommandList,
} from '@/components/ui/command';
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
export interface ComboboxOption {
value: string;
label: string;
}
interface ComboboxProps {
options: ComboboxOption[];
value?: string;
onChange: (value: string) => void;
placeholder?: string;
searchPlaceholder?: string;
emptyText?: string;
disabled?: boolean;
loading?: boolean;
className?: string;
id?: string;
'aria-invalid'?: boolean;
'aria-describedby'?: string;
}
/**
* `Select` com busca, usado nas listas longas do sistema (cliente,
* produto/serviço) — seção 7 do schema de frontend. Composição de
* Command + Popover, não do `Select` nativo do Radix.
*/
function Combobox({
options,
value,
onChange,
placeholder = 'Selecionar…',
searchPlaceholder = 'Buscar…',
emptyText = 'Nenhum resultado encontrado.',
disabled,
loading,
className,
id,
...aria
}: ComboboxProps) {
const [open, setOpen] = React.useState(false);
const selected = options.find((option) => option.value === value);
return (
<Popover open={open} onOpenChange={setOpen}>
<PopoverTrigger asChild>
<Button
id={id}
variant="outline"
role="combobox"
aria-expanded={open}
disabled={disabled || loading}
loading={loading}
className={cn(
'w-full justify-between font-normal',
!selected && 'text-muted-foreground',
className,
)}
{...aria}
>
{selected ? selected.label : placeholder}
<ChevronsUpDownIcon className="opacity-50" />
</Button>
</PopoverTrigger>
<PopoverContent className="w-(--radix-popover-trigger-width) p-0" align="start">
<Command>
<CommandInput placeholder={searchPlaceholder} />
<CommandList>
<CommandEmpty>{emptyText}</CommandEmpty>
<CommandGroup>
{options.map((option) => (
<CommandItem
key={option.value}
value={option.label}
onSelect={() => {
onChange(option.value);
setOpen(false);
}}
>
<CheckIcon
className={cn('mr-2', option.value === value ? 'opacity-100' : 'opacity-0')}
/>
{option.label}
</CommandItem>
))}
</CommandGroup>
</CommandList>
</Command>
</PopoverContent>
</Popover>
);
}
export { Combobox };
+180
View File
@@ -0,0 +1,180 @@
'use client';
import * as React from 'react';
import { Command as CommandPrimitive } from 'cmdk';
import { cn } from '@/lib/utils';
import {
Dialog,
DialogContent,
DialogDescription,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog';
import { InputGroup, InputGroupAddon } from '@/components/ui/input-group';
import { SearchIcon, CheckIcon } from 'lucide-react';
function Command({ className, ...props }: React.ComponentProps<typeof CommandPrimitive>) {
return (
<CommandPrimitive
data-slot="command"
className={cn(
'flex size-full flex-col overflow-hidden rounded-xl! bg-popover p-1 text-popover-foreground',
className,
)}
{...props}
/>
);
}
function CommandDialog({
title = 'Command Palette',
description = 'Search for a command to run...',
children,
className,
showCloseButton = false,
...props
}: React.ComponentProps<typeof Dialog> & {
title?: string;
description?: string;
className?: string;
showCloseButton?: boolean;
}) {
return (
<Dialog {...props}>
<DialogHeader className="sr-only">
<DialogTitle>{title}</DialogTitle>
<DialogDescription>{description}</DialogDescription>
</DialogHeader>
<DialogContent
className={cn('top-1/3 translate-y-0 overflow-hidden rounded-xl! p-0', className)}
showCloseButton={showCloseButton}
>
{children}
</DialogContent>
</Dialog>
);
}
function CommandInput({
className,
...props
}: React.ComponentProps<typeof CommandPrimitive.Input>) {
return (
<div data-slot="command-input-wrapper" className="p-1 pb-0">
<InputGroup className="h-8! rounded-lg! border-input/30 bg-input/30 shadow-none! *:data-[slot=input-group-addon]:pl-2!">
<CommandPrimitive.Input
data-slot="command-input"
className={cn(
'w-full text-sm outline-hidden disabled:cursor-not-allowed disabled:opacity-50',
className,
)}
{...props}
/>
<InputGroupAddon>
<SearchIcon className="size-4 shrink-0 opacity-50" />
</InputGroupAddon>
</InputGroup>
</div>
);
}
function CommandList({ className, ...props }: React.ComponentProps<typeof CommandPrimitive.List>) {
return (
<CommandPrimitive.List
data-slot="command-list"
className={cn(
'no-scrollbar max-h-72 scroll-py-1 overflow-x-hidden overflow-y-auto outline-none',
className,
)}
{...props}
/>
);
}
function CommandEmpty({
className,
...props
}: React.ComponentProps<typeof CommandPrimitive.Empty>) {
return (
<CommandPrimitive.Empty
data-slot="command-empty"
className={cn('py-6 text-center text-sm', className)}
{...props}
/>
);
}
function CommandGroup({
className,
...props
}: React.ComponentProps<typeof CommandPrimitive.Group>) {
return (
<CommandPrimitive.Group
data-slot="command-group"
className={cn(
'overflow-hidden p-1 text-foreground **:[[cmdk-group-heading]]:px-2 **:[[cmdk-group-heading]]:py-1.5 **:[[cmdk-group-heading]]:text-xs **:[[cmdk-group-heading]]:font-medium **:[[cmdk-group-heading]]:text-muted-foreground',
className,
)}
{...props}
/>
);
}
function CommandSeparator({
className,
...props
}: React.ComponentProps<typeof CommandPrimitive.Separator>) {
return (
<CommandPrimitive.Separator
data-slot="command-separator"
className={cn('-mx-1 h-px bg-border', className)}
{...props}
/>
);
}
function CommandItem({
className,
children,
...props
}: React.ComponentProps<typeof CommandPrimitive.Item>) {
return (
<CommandPrimitive.Item
data-slot="command-item"
className={cn(
"group/command-item relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none in-data-[slot=dialog-content]:rounded-lg! data-[disabled=true]:pointer-events-none data-[disabled=true]:opacity-50 data-selected:bg-muted data-selected:text-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 data-selected:*:[svg]:text-foreground",
className,
)}
{...props}
>
{children}
<CheckIcon className="ml-auto opacity-0 group-has-data-[slot=command-shortcut]/command-item:hidden group-data-[checked=true]/command-item:opacity-100" />
</CommandPrimitive.Item>
);
}
function CommandShortcut({ className, ...props }: React.ComponentProps<'span'>) {
return (
<span
data-slot="command-shortcut"
className={cn(
'ml-auto text-xs tracking-widest text-muted-foreground group-data-selected/command-item:text-foreground',
className,
)}
{...props}
/>
);
}
export {
Command,
CommandDialog,
CommandInput,
CommandList,
CommandEmpty,
CommandGroup,
CommandItem,
CommandShortcut,
CommandSeparator,
};
@@ -0,0 +1,86 @@
import * as React from 'react';
import { ChevronLeftIcon, ChevronRightIcon, MoreHorizontalIcon } from 'lucide-react';
import { cn } from '@/lib/utils';
import { Button } from '@/components/ui/button';
interface DataPaginationProps {
/** 1-indexado, compatível com `page`/`limit`/`meta.total` da API (Etapas 1–8 do backend). */
page: number;
limit: number;
total: number;
onPageChange: (page: number) => void;
className?: string;
}
function getPageNumbers(page: number, totalPages: number): (number | 'ellipsis')[] {
if (totalPages <= 7) return Array.from({ length: totalPages }, (_, i) => i + 1);
const pages = new Set([1, totalPages, page, page - 1, page + 1]);
const sorted = [...pages].filter((p) => p >= 1 && p <= totalPages).sort((a, b) => a - b);
const result: (number | 'ellipsis')[] = [];
sorted.forEach((p, i) => {
if (i > 0 && p - sorted[i - 1] > 1) result.push('ellipsis');
result.push(p);
});
return result;
}
/** Controles de página compatíveis com os parâmetros de paginação do backend (Etapa 12). */
function DataPagination({ page, limit, total, onPageChange, className }: DataPaginationProps) {
const totalPages = Math.max(1, Math.ceil(total / limit));
const firstItem = total === 0 ? 0 : (page - 1) * limit + 1;
const lastItem = Math.min(page * limit, total);
return (
<nav
aria-label="Paginação"
className={cn('flex flex-col items-center justify-between gap-3 sm:flex-row', className)}
>
<p className="text-sm text-muted-foreground">
{total === 0 ? 'Nenhum resultado' : `Mostrando ${firstItem}–${lastItem} de ${total}`}
</p>
<div className="flex items-center gap-1">
<Button
variant="ghost"
size="icon"
aria-label="Página anterior"
disabled={page <= 1}
onClick={() => onPageChange(page - 1)}
>
<ChevronLeftIcon />
</Button>
{getPageNumbers(page, totalPages).map((p, index) =>
p === 'ellipsis' ? (
<span key={`ellipsis-${index}`} className="flex size-11 items-center justify-center">
<MoreHorizontalIcon className="size-4 text-muted-foreground" aria-hidden />
</span>
) : (
<Button
key={p}
variant={p === page ? 'outline' : 'ghost'}
size="icon"
aria-label={`Página ${p}`}
aria-current={p === page ? 'page' : undefined}
onClick={() => onPageChange(p)}
>
{p}
</Button>
),
)}
<Button
variant="ghost"
size="icon"
aria-label="Próxima página"
disabled={page >= totalPages}
onClick={() => onPageChange(page + 1)}
>
<ChevronRightIcon />
</Button>
</div>
</nav>
);
}
export { DataPagination };
+306
View File
@@ -0,0 +1,306 @@
'use client';
import * as React from 'react';
import { ArrowDownIcon, ArrowUpIcon, ChevronDownIcon } from 'lucide-react';
import { cn } from '@/lib/utils';
import { useIsDesktop } from '@/hooks/use-media-query';
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from '@/components/ui/table';
import { Card } from '@/components/ui/card';
import { SkeletonTableRow, SkeletonCard } from '@/components/ui/skeleton';
import { EmptyState } from '@/components/ui/empty-state';
import { DataPagination } from '@/components/ui/data-pagination';
export interface DataTableSort {
columnId: string;
direction: 'asc' | 'desc';
}
export interface DataTableColumn<T> {
id: string;
header: string;
cell: (row: T) => React.ReactNode;
sortable?: boolean;
/** Campo em destaque no card mobile (limite recomendado: 1–2 por tabela). */
primary?: boolean;
/** Não mostrado no card mobile (ex: coluna técnica só relevante em tela larga). */
hideOnMobileCard?: boolean;
className?: string;
}
interface DataTableProps<T> {
columns: DataTableColumn<T>[];
data: T[];
keyField: (row: T) => string;
loading?: boolean;
sort?: DataTableSort;
onSortChange?: (sort: DataTableSort) => void;
emptyTitle?: string;
emptyDescription?: string;
emptyAction?: React.ReactNode;
rowActions?: (row: T) => React.ReactNode;
onRowClick?: (row: T) => void;
pagination?: {
page: number;
limit: number;
total: number;
onPageChange: (page: number) => void;
};
className?: string;
}
function SortButton<T>({
column,
sort,
onSortChange,
}: {
column: DataTableColumn<T>;
sort?: DataTableSort;
onSortChange: (sort: DataTableSort) => void;
}) {
const active = sort?.columnId === column.id;
const nextDirection = active && sort?.direction === 'asc' ? 'desc' : 'asc';
return (
<button
type="button"
className="-my-2 -ml-1 flex min-h-11 items-center gap-1 rounded-sm py-2 pl-1 font-medium hover:text-foreground focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring"
onClick={() => onSortChange({ columnId: column.id, direction: nextDirection })}
>
{column.header}
{active ? (
sort.direction === 'asc' ? (
<ArrowUpIcon className="size-3.5" aria-hidden />
) : (
<ArrowDownIcon className="size-3.5" aria-hidden />
)
) : (
<ArrowUpIcon className="size-3.5 opacity-0 group-hover:opacity-30" aria-hidden />
)}
<span className="sr-only">
{active ? `ordenado ${sort.direction === 'asc' ? 'crescente' : 'decrescente'}` : 'ordenar'}
</span>
</button>
);
}
function MobileRowCard<T>({
row,
columns,
rowActions,
onRowClick,
}: {
row: T;
columns: DataTableColumn<T>[];
rowActions?: (row: T) => React.ReactNode;
onRowClick?: (row: T) => void;
}) {
const [expanded, setExpanded] = React.useState(false);
const primaryColumns = columns.filter((c) => c.primary);
const secondaryColumns = columns.filter((c) => !c.primary && !c.hideOnMobileCard);
return (
<Card
className={cn('flex flex-col gap-3 p-4', onRowClick && 'cursor-pointer')}
onClick={onRowClick ? () => onRowClick(row) : undefined}
role={onRowClick ? 'button' : undefined}
tabIndex={onRowClick ? 0 : undefined}
onKeyDown={
onRowClick
? (e) => {
if (e.key === 'Enter' || e.key === ' ') {
e.preventDefault();
onRowClick(row);
}
}
: undefined
}
>
{primaryColumns.length > 0 && (
<div className="flex flex-col gap-0.5">
{primaryColumns.map((column) => (
<div key={column.id} className="text-base font-medium text-foreground">
{column.cell(row)}
</div>
))}
</div>
)}
{secondaryColumns.length > 0 && (
<>
<button
type="button"
className="-mx-2 flex min-h-11 items-center gap-1 self-start px-2 text-xs font-medium text-muted-foreground focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring"
onClick={(e) => {
e.stopPropagation();
setExpanded((v) => !v);
}}
aria-expanded={expanded}
>
{expanded ? 'Ver menos' : 'Ver mais'}
<ChevronDownIcon
className={cn('size-3.5 transition-transform', expanded && 'rotate-180')}
aria-hidden
/>
</button>
{expanded && (
<dl className="flex flex-col gap-2 border-t border-border pt-3">
{secondaryColumns.map((column) => (
<div key={column.id} className="flex items-center justify-between gap-4 text-sm">
<dt className="text-muted-foreground">{column.header}</dt>
<dd className="tabular-nums text-foreground">{column.cell(row)}</dd>
</div>
))}
</dl>
)}
</>
)}
{rowActions && (
<div
className="flex items-center gap-2 border-t border-border pt-3"
onClick={(e) => e.stopPropagation()}
>
{rowActions(row)}
</div>
)}
</Card>
);
}
/**
* Componente central do design system (Etapa 12). Abaixo de `md` renderiza
* como lista de Cards empilhados em vez de fazer scroll horizontal na
* tabela — cada `column.primary` vira um campo em destaque no card, o
* resto fica atrás de "Ver mais".
*/
function DataTable<T>({
columns,
data,
keyField,
loading,
sort,
onSortChange,
emptyTitle = 'Nenhum resultado encontrado',
emptyDescription,
emptyAction,
rowActions,
onRowClick,
pagination,
className,
}: DataTableProps<T>) {
const isDesktop = useIsDesktop();
if (loading) {
return (
<div className={className}>
{isDesktop ? (
<div className="rounded-lg border border-border">
{Array.from({ length: 5 }).map((_, i) => (
<SkeletonTableRow key={i} columns={columns.length + (rowActions ? 1 : 0)} />
))}
</div>
) : (
<div className="flex flex-col gap-3">
{Array.from({ length: 3 }).map((_, i) => (
<SkeletonCard key={i} />
))}
</div>
)}
</div>
);
}
if (data.length === 0) {
return (
<div className={className}>
<EmptyState title={emptyTitle} description={emptyDescription} action={emptyAction} />
</div>
);
}
return (
<div className={cn('flex flex-col gap-4', className)}>
{isDesktop ? (
// `overflow-x-auto` (não `overflow-hidden`): com muitas colunas perto
// do breakpoint `md`, a tabela pode ficar mais larga que o
// container — sem scroll horizontal, a(s) última(s) coluna(s)
// simplesmente sumiam cortadas em vez de ficarem acessíveis
// (achado da Etapa 15, testando `/master/tenants` em 768px).
<div className="overflow-x-auto overflow-y-hidden rounded-lg border border-border">
<Table>
<TableHeader>
<TableRow>
{columns.map((column) => (
<TableHead key={column.id} className={cn('group', column.className)}>
{column.sortable && onSortChange ? (
<SortButton column={column} sort={sort} onSortChange={onSortChange} />
) : (
column.header
)}
</TableHead>
))}
{rowActions && (
<TableHead className="w-px">
<span className="sr-only">Ações</span>
</TableHead>
)}
</TableRow>
</TableHeader>
<TableBody>
{data.map((row) => (
<TableRow
key={keyField(row)}
className={onRowClick ? 'cursor-pointer' : undefined}
onClick={onRowClick ? () => onRowClick(row) : undefined}
tabIndex={onRowClick ? 0 : undefined}
onKeyDown={
onRowClick
? (e) => {
if (e.key === 'Enter') onRowClick(row);
}
: undefined
}
>
{columns.map((column) => (
<TableCell key={column.id} className={cn('tabular-nums', column.className)}>
{column.cell(row)}
</TableCell>
))}
{rowActions && (
<TableCell onClick={(e) => e.stopPropagation()}>
<div className="flex items-center gap-2">{rowActions(row)}</div>
</TableCell>
)}
</TableRow>
))}
</TableBody>
</Table>
</div>
) : (
<div className="flex flex-col gap-3">
{data.map((row) => (
<MobileRowCard
key={keyField(row)}
row={row}
columns={columns}
rowActions={rowActions}
onRowClick={onRowClick}
/>
))}
</div>
)}
{pagination && <DataPagination {...pagination} />}
</div>
);
}
export { DataTable };
+128
View File
@@ -0,0 +1,128 @@
'use client';
import * as React from 'react';
import { format } from 'date-fns';
import { ptBR } from 'date-fns/locale';
import { CalendarIcon } from 'lucide-react';
import type { DateRange } from 'react-day-picker';
import { cn } from '@/lib/utils';
import { Button } from '@/components/ui/button';
import { Calendar } from '@/components/ui/calendar';
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
interface DatePickerProps {
value?: Date;
onChange: (date: Date | undefined) => void;
placeholder?: string;
disabled?: boolean;
className?: string;
id?: string;
'aria-invalid'?: boolean;
'aria-describedby'?: string;
}
/** Seleção de data única — usada em formulários (ex: vencimento de parcela). */
function DatePicker({
value,
onChange,
placeholder = 'Selecionar data',
disabled,
className,
id,
...aria
}: DatePickerProps) {
const [open, setOpen] = React.useState(false);
return (
<Popover open={open} onOpenChange={setOpen}>
<PopoverTrigger asChild>
<Button
id={id}
variant="outline"
disabled={disabled}
className={cn(
'w-full justify-start font-normal',
!value && 'text-muted-foreground',
className,
)}
{...aria}
>
<CalendarIcon />
{value ? format(value, "dd 'de' MMMM 'de' yyyy", { locale: ptBR }) : placeholder}
</Button>
</PopoverTrigger>
<PopoverContent className="w-auto p-0" align="start">
<Calendar
mode="single"
selected={value}
onSelect={(date) => {
onChange(date);
setOpen(false);
}}
locale={ptBR}
autoFocus
/>
</PopoverContent>
</Popover>
);
}
interface DateRangePickerProps {
value?: DateRange;
onChange: (range: DateRange | undefined) => void;
placeholder?: string;
disabled?: boolean;
className?: string;
id?: string;
}
/** Seleção de período — usada nos filtros de dashboard/listagens (seção 7 do schema). */
function DateRangePicker({
value,
onChange,
placeholder = 'Selecionar período',
disabled,
className,
id,
}: DateRangePickerProps) {
const [open, setOpen] = React.useState(false);
const label = React.useMemo(() => {
if (!value?.from) return placeholder;
if (!value.to) return format(value.from, 'dd/MM/yyyy', { locale: ptBR });
return `${format(value.from, 'dd/MM/yyyy', { locale: ptBR })} – ${format(value.to, 'dd/MM/yyyy', { locale: ptBR })}`;
}, [value, placeholder]);
return (
<Popover open={open} onOpenChange={setOpen}>
<PopoverTrigger asChild>
<Button
id={id}
variant="outline"
disabled={disabled}
className={cn(
'w-full justify-start font-normal',
!value?.from && 'text-muted-foreground',
className,
)}
>
<CalendarIcon />
{label}
</Button>
</PopoverTrigger>
<PopoverContent className="w-auto p-0" align="start">
<Calendar
mode="range"
selected={value}
onSelect={onChange}
locale={ptBR}
numberOfMonths={2}
autoFocus
/>
</PopoverContent>
</Popover>
);
}
export { DatePicker, DateRangePicker };
+145
View File
@@ -0,0 +1,145 @@
'use client';
import * as React from 'react';
import { Dialog as DialogPrimitive } from 'radix-ui';
import { cn } from '@/lib/utils';
import { Button } from '@/components/ui/button';
import { XIcon } from 'lucide-react';
function Dialog({ ...props }: React.ComponentProps<typeof DialogPrimitive.Root>) {
return <DialogPrimitive.Root data-slot="dialog" {...props} />;
}
function DialogTrigger({ ...props }: React.ComponentProps<typeof DialogPrimitive.Trigger>) {
return <DialogPrimitive.Trigger data-slot="dialog-trigger" {...props} />;
}
function DialogPortal({ ...props }: React.ComponentProps<typeof DialogPrimitive.Portal>) {
return <DialogPrimitive.Portal data-slot="dialog-portal" {...props} />;
}
function DialogClose({ ...props }: React.ComponentProps<typeof DialogPrimitive.Close>) {
return <DialogPrimitive.Close data-slot="dialog-close" {...props} />;
}
function DialogOverlay({
className,
...props
}: React.ComponentProps<typeof DialogPrimitive.Overlay>) {
return (
<DialogPrimitive.Overlay
data-slot="dialog-overlay"
className={cn(
'fixed inset-0 isolate z-50 bg-black/10 duration-100 supports-backdrop-filter:backdrop-blur-xs data-open:animate-in data-open:fade-in-0 data-closed:animate-out data-closed:fade-out-0',
className,
)}
{...props}
/>
);
}
function DialogContent({
className,
children,
showCloseButton = true,
...props
}: React.ComponentProps<typeof DialogPrimitive.Content> & {
showCloseButton?: boolean;
}) {
return (
<DialogPortal>
<DialogOverlay />
<DialogPrimitive.Content
data-slot="dialog-content"
className={cn(
'fixed top-1/2 left-1/2 z-50 grid w-full max-w-[calc(100%-2rem)] -translate-x-1/2 -translate-y-1/2 gap-4 rounded-xl bg-popover p-4 text-sm text-popover-foreground ring-1 ring-foreground/10 duration-100 outline-none sm:max-w-sm data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95',
className,
)}
{...props}
>
{children}
{showCloseButton && (
<DialogPrimitive.Close data-slot="dialog-close" asChild>
<Button variant="ghost" className="absolute top-2 right-2" size="icon-sm">
<XIcon />
<span className="sr-only">Close</span>
</Button>
</DialogPrimitive.Close>
)}
</DialogPrimitive.Content>
</DialogPortal>
);
}
function DialogHeader({ className, ...props }: React.ComponentProps<'div'>) {
return (
<div data-slot="dialog-header" className={cn('flex flex-col gap-2', className)} {...props} />
);
}
function DialogFooter({
className,
showCloseButton = false,
children,
...props
}: React.ComponentProps<'div'> & {
showCloseButton?: boolean;
}) {
return (
<div
data-slot="dialog-footer"
className={cn(
'-mx-4 -mb-4 flex flex-col-reverse gap-2 rounded-b-xl border-t bg-muted/50 p-4 sm:flex-row sm:justify-end',
className,
)}
{...props}
>
{children}
{showCloseButton && (
<DialogPrimitive.Close asChild>
<Button variant="outline">Close</Button>
</DialogPrimitive.Close>
)}
</div>
);
}
function DialogTitle({ className, ...props }: React.ComponentProps<typeof DialogPrimitive.Title>) {
return (
<DialogPrimitive.Title
data-slot="dialog-title"
className={cn('text-base leading-none font-medium', className)}
{...props}
/>
);
}
function DialogDescription({
className,
...props
}: React.ComponentProps<typeof DialogPrimitive.Description>) {
return (
<DialogPrimitive.Description
data-slot="dialog-description"
className={cn(
'text-sm text-muted-foreground *:[a]:underline *:[a]:underline-offset-3 *:[a]:hover:text-foreground',
className,
)}
{...props}
/>
);
}
export {
Dialog,
DialogClose,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogOverlay,
DialogPortal,
DialogTitle,
DialogTrigger,
};
+41
View File
@@ -0,0 +1,41 @@
import * as React from 'react';
import { InboxIcon, type LucideIcon } from 'lucide-react';
import { cn } from '@/lib/utils';
interface EmptyStateProps {
title: string;
description?: string;
icon?: LucideIcon;
action?: React.ReactNode;
className?: string;
}
/** Usado em toda listagem vazia do sistema (Etapa 12), ex: "Nenhum cliente cadastrado ainda". */
function EmptyState({
title,
description,
icon: Icon = InboxIcon,
action,
className,
}: EmptyStateProps) {
return (
<div
className={cn(
'flex flex-col items-center justify-center gap-3 px-4 py-12 text-center',
className,
)}
>
<div className="flex size-12 items-center justify-center rounded-full bg-muted">
<Icon className="size-6 text-muted-foreground" aria-hidden />
</div>
<div className="flex flex-col gap-1">
<p className="text-sm font-medium text-foreground">{title}</p>
{description && <p className="text-sm text-muted-foreground">{description}</p>}
</div>
{action}
</div>
);
}
export { EmptyState };
+66
View File
@@ -0,0 +1,66 @@
import * as React from 'react';
import { cn } from '@/lib/utils';
import { Label } from '@/components/ui/label';
interface FormFieldProps {
label: string;
children: React.ReactElement<{
id?: string;
'aria-invalid'?: boolean;
'aria-describedby'?: string;
}>;
error?: string;
helpText?: string;
required?: boolean;
className?: string;
id?: string;
}
/**
* Wrapper obrigatório para label + input + erro + texto de ajuda —
* nenhuma tela deve montar esse trio manualmente (Etapa 12). Injeta
* `id`/`aria-invalid`/`aria-describedby` no único filho, então `children`
* precisa ser um componente que espalha `...props` no elemento nativo
* (Input, Textarea, SelectTrigger etc).
*/
function FormField({ label, children, error, helpText, required, className, id }: FormFieldProps) {
const autoId = React.useId();
const fieldId = id ?? autoId;
const errorId = `${fieldId}-error`;
const helpId = `${fieldId}-help`;
const describedBy =
[error ? errorId : null, helpText ? helpId : null].filter(Boolean).join(' ') || undefined;
return (
<div className={cn('flex flex-col gap-1.5', className)}>
<Label htmlFor={fieldId}>
{label}
{required && (
<span className="text-destructive" aria-hidden>
{' '}
*
</span>
)}
</Label>
{React.cloneElement(children, {
id: fieldId,
'aria-invalid': !!error,
'aria-describedby': describedBy,
})}
{helpText && !error && (
<p id={helpId} className="text-xs text-muted-foreground">
{helpText}
</p>
)}
{error && (
<p id={errorId} role="alert" className="text-xs text-destructive">
{error}
</p>
)}
</div>
);
}
export { FormField };
+144
View File
@@ -0,0 +1,144 @@
'use client';
import * as React from 'react';
import { cva, type VariantProps } from 'class-variance-authority';
import { cn } from '@/lib/utils';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Textarea } from '@/components/ui/textarea';
function InputGroup({ className, ...props }: React.ComponentProps<'div'>) {
return (
<div
data-slot="input-group"
role="group"
className={cn(
'group/input-group relative flex h-11 w-full min-w-0 items-center rounded-lg border border-input transition-colors outline-none in-data-[slot=combobox-content]:focus-within:border-inherit in-data-[slot=combobox-content]:focus-within:ring-0 has-disabled:bg-input/50 has-disabled:opacity-50 has-[[data-slot=input-group-control]:focus-visible]:border-ring has-[[data-slot=input-group-control]:focus-visible]:ring-3 has-[[data-slot=input-group-control]:focus-visible]:ring-ring/50 has-[[data-slot][aria-invalid=true]]:border-destructive has-[[data-slot][aria-invalid=true]]:ring-3 has-[[data-slot][aria-invalid=true]]:ring-destructive/20 has-[>[data-align=block-end]]:h-auto has-[>[data-align=block-end]]:flex-col has-[>[data-align=block-start]]:h-auto has-[>[data-align=block-start]]:flex-col has-[>textarea]:h-auto has-[>[data-align=block-end]]:[&>input]:pt-3 has-[>[data-align=block-start]]:[&>input]:pb-3 has-[>[data-align=inline-end]]:[&>input]:pr-1.5 has-[>[data-align=inline-start]]:[&>input]:pl-1.5',
className,
)}
{...props}
/>
);
}
const inputGroupAddonVariants = cva(
"flex h-auto cursor-text items-center justify-center gap-2 py-1.5 text-sm font-medium text-muted-foreground select-none group-data-[disabled=true]/input-group:opacity-50 [&>kbd]:rounded-[calc(var(--radius)-5px)] [&>svg:not([class*='size-'])]:size-4",
{
variants: {
align: {
'inline-start': 'order-first pl-2 has-[>button]:ml-[-0.3rem] has-[>kbd]:ml-[-0.15rem]',
'inline-end': 'order-last pr-2 has-[>button]:mr-[-0.3rem] has-[>kbd]:mr-[-0.15rem]',
'block-start':
'order-first w-full justify-start px-2.5 pt-2 group-has-[>input]/input-group:pt-2 [.border-b]:pb-2',
'block-end':
'order-last w-full justify-start px-2.5 pb-2 group-has-[>input]/input-group:pb-2 [.border-t]:pt-2',
},
},
defaultVariants: {
align: 'inline-start',
},
},
);
function InputGroupAddon({
className,
align = 'inline-start',
...props
}: React.ComponentProps<'div'> & VariantProps<typeof inputGroupAddonVariants>) {
return (
<div
role="group"
data-slot="input-group-addon"
data-align={align}
className={cn(inputGroupAddonVariants({ align }), className)}
onClick={(e) => {
if ((e.target as HTMLElement).closest('button')) {
return;
}
e.currentTarget.parentElement?.querySelector('input')?.focus();
}}
{...props}
/>
);
}
const inputGroupButtonVariants = cva('flex items-center gap-2 text-sm shadow-none', {
variants: {
size: {
xs: "h-6 gap-1 rounded-[calc(var(--radius)-3px)] px-1.5 [&>svg:not([class*='size-'])]:size-3.5",
sm: '',
'icon-xs': 'size-6 rounded-[calc(var(--radius)-3px)] p-0 has-[>svg]:p-0',
'icon-sm': 'size-8 p-0 has-[>svg]:p-0',
},
},
defaultVariants: {
size: 'xs',
},
});
function InputGroupButton({
className,
type = 'button',
variant = 'ghost',
size = 'xs',
...props
}: Omit<React.ComponentProps<typeof Button>, 'size'> &
VariantProps<typeof inputGroupButtonVariants>) {
return (
<Button
type={type}
data-size={size}
variant={variant}
className={cn(inputGroupButtonVariants({ size }), className)}
{...props}
/>
);
}
function InputGroupText({ className, ...props }: React.ComponentProps<'span'>) {
return (
<span
className={cn(
"flex items-center gap-2 text-sm text-muted-foreground [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4",
className,
)}
{...props}
/>
);
}
function InputGroupInput({ className, ...props }: React.ComponentProps<'input'>) {
return (
<Input
data-slot="input-group-control"
className={cn(
'flex-1 rounded-none border-0 bg-transparent shadow-none ring-0 focus-visible:ring-0 disabled:bg-transparent aria-invalid:ring-0 dark:bg-transparent dark:disabled:bg-transparent',
className,
)}
{...props}
/>
);
}
function InputGroupTextarea({ className, ...props }: React.ComponentProps<'textarea'>) {
return (
<Textarea
data-slot="input-group-control"
className={cn(
'flex-1 resize-none rounded-none border-0 bg-transparent py-2 shadow-none ring-0 focus-visible:ring-0 disabled:bg-transparent aria-invalid:ring-0 dark:bg-transparent dark:disabled:bg-transparent',
className,
)}
{...props}
/>
);
}
export {
InputGroup,
InputGroupAddon,
InputGroupButton,
InputGroupText,
InputGroupInput,
InputGroupTextarea,
};
+19
View File
@@ -0,0 +1,19 @@
import * as React from 'react';
import { cn } from '@/lib/utils';
function Input({ className, type, ...props }: React.ComponentProps<'input'>) {
return (
<input
type={type}
data-slot="input"
className={cn(
'h-11 w-full min-w-0 rounded-lg border border-input bg-transparent px-3 py-1 text-base transition-colors outline-none file:inline-flex file:h-6 file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 disabled:pointer-events-none disabled:cursor-not-allowed disabled:bg-input/50 disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 md:text-sm',
className,
)}
{...props}
/>
);
}
export { Input };
+21
View File
@@ -0,0 +1,21 @@
'use client';
import * as React from 'react';
import { Label as LabelPrimitive } from 'radix-ui';
import { cn } from '@/lib/utils';
function Label({ className, ...props }: React.ComponentProps<typeof LabelPrimitive.Root>) {
return (
<LabelPrimitive.Root
data-slot="label"
className={cn(
'flex items-center gap-2 text-sm leading-none font-medium select-none group-data-[disabled=true]:pointer-events-none group-data-[disabled=true]:opacity-50 peer-disabled:cursor-not-allowed peer-disabled:opacity-50',
className,
)}
{...props}
/>
);
}
export { Label };
+74
View File
@@ -0,0 +1,74 @@
'use client';
import * as React from 'react';
import { Popover as PopoverPrimitive } from 'radix-ui';
import { cn } from '@/lib/utils';
function Popover({ ...props }: React.ComponentProps<typeof PopoverPrimitive.Root>) {
return <PopoverPrimitive.Root data-slot="popover" {...props} />;
}
function PopoverTrigger({ ...props }: React.ComponentProps<typeof PopoverPrimitive.Trigger>) {
return <PopoverPrimitive.Trigger data-slot="popover-trigger" {...props} />;
}
function PopoverContent({
className,
align = 'center',
sideOffset = 4,
...props
}: React.ComponentProps<typeof PopoverPrimitive.Content>) {
return (
<PopoverPrimitive.Portal>
<PopoverPrimitive.Content
data-slot="popover-content"
align={align}
sideOffset={sideOffset}
className={cn(
'z-50 flex w-72 origin-(--radix-popover-content-transform-origin) flex-col gap-2.5 rounded-lg bg-popover p-2.5 text-sm text-popover-foreground shadow-md ring-1 ring-foreground/10 outline-hidden duration-100 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95',
className,
)}
{...props}
/>
</PopoverPrimitive.Portal>
);
}
function PopoverAnchor({ ...props }: React.ComponentProps<typeof PopoverPrimitive.Anchor>) {
return <PopoverPrimitive.Anchor data-slot="popover-anchor" {...props} />;
}
function PopoverHeader({ className, ...props }: React.ComponentProps<'div'>) {
return (
<div
data-slot="popover-header"
className={cn('flex flex-col gap-0.5 text-sm', className)}
{...props}
/>
);
}
function PopoverTitle({ className, ...props }: React.ComponentProps<'h2'>) {
return <div data-slot="popover-title" className={cn('font-medium', className)} {...props} />;
}
function PopoverDescription({ className, ...props }: React.ComponentProps<'p'>) {
return (
<p
data-slot="popover-description"
className={cn('text-muted-foreground', className)}
{...props}
/>
);
}
export {
Popover,
PopoverAnchor,
PopoverContent,
PopoverDescription,
PopoverHeader,
PopoverTitle,
PopoverTrigger,
};
@@ -0,0 +1,85 @@
'use client';
import * as React from 'react';
import { useIsDesktop } from '@/hooks/use-media-query';
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog';
import {
Sheet,
SheetContent,
SheetDescription,
SheetFooter,
SheetHeader,
SheetTitle,
} from '@/components/ui/sheet';
interface ResponsiveDialogProps {
open: boolean;
onOpenChange: (open: boolean) => void;
title: string;
description?: string;
children: React.ReactNode;
footer?: React.ReactNode;
className?: string;
}
/**
* Um único componente para modal (Etapa 12): centralizado no desktop
* (`Dialog`), bottom sheet no mobile (`Sheet` com `side="bottom"`) —
* escolhido em vez de tela cheia porque a maioria dos formulários deste
* projeto (confirmações, cadastro rápido de cliente, edição de parcela)
* é curta o bastante para caber sem precisar ocupar a tela inteira;
* `max-h-[85vh]` com scroll interno cobre os casos mais longos. Alterna
* no mesmo breakpoint `md` usado pela `Table`.
*/
function ResponsiveDialog({
open,
onOpenChange,
title,
description,
children,
footer,
className,
}: ResponsiveDialogProps) {
const isDesktop = useIsDesktop();
if (isDesktop) {
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className={className}>
<DialogHeader>
<DialogTitle>{title}</DialogTitle>
{description && <DialogDescription>{description}</DialogDescription>}
</DialogHeader>
{children}
{footer && <DialogFooter>{footer}</DialogFooter>}
</DialogContent>
</Dialog>
);
}
return (
<Sheet open={open} onOpenChange={onOpenChange}>
<SheetContent
side="bottom"
className={`max-h-[85vh] overflow-y-auto rounded-t-xl ${className ?? ''}`}
>
<SheetHeader>
<SheetTitle>{title}</SheetTitle>
{description && <SheetDescription>{description}</SheetDescription>}
</SheetHeader>
<div className="px-4">{children}</div>
{footer && <SheetFooter>{footer}</SheetFooter>}
</SheetContent>
</Sheet>
);
}
export { ResponsiveDialog };
+185
View File
@@ -0,0 +1,185 @@
'use client';
import * as React from 'react';
import { Select as SelectPrimitive } from 'radix-ui';
import { cn } from '@/lib/utils';
import { ChevronDownIcon, CheckIcon, ChevronUpIcon } from 'lucide-react';
function Select({ ...props }: React.ComponentProps<typeof SelectPrimitive.Root>) {
return <SelectPrimitive.Root data-slot="select" {...props} />;
}
function SelectGroup({ className, ...props }: React.ComponentProps<typeof SelectPrimitive.Group>) {
return (
<SelectPrimitive.Group
data-slot="select-group"
className={cn('scroll-my-1 p-1', className)}
{...props}
/>
);
}
function SelectValue({ ...props }: React.ComponentProps<typeof SelectPrimitive.Value>) {
return <SelectPrimitive.Value data-slot="select-value" {...props} />;
}
function SelectTrigger({
className,
size = 'default',
children,
...props
}: React.ComponentProps<typeof SelectPrimitive.Trigger> & {
size?: 'sm' | 'default';
}) {
return (
<SelectPrimitive.Trigger
data-slot="select-trigger"
data-size={size}
className={cn(
"flex w-full items-center justify-between gap-1.5 rounded-lg border border-input bg-transparent py-2 pr-2 pl-3 text-sm whitespace-nowrap transition-colors outline-none select-none focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 data-placeholder:text-muted-foreground data-[size=default]:h-11 data-[size=sm]:h-8 data-[size=sm]:rounded-[min(var(--radius-md),10px)] *:data-[slot=select-value]:line-clamp-1 *:data-[slot=select-value]:flex *:data-[slot=select-value]:items-center *:data-[slot=select-value]:gap-1.5 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
className,
)}
{...props}
>
{children}
<SelectPrimitive.Icon asChild>
<ChevronDownIcon className="pointer-events-none size-4 text-muted-foreground" />
</SelectPrimitive.Icon>
</SelectPrimitive.Trigger>
);
}
function SelectContent({
className,
children,
position = 'item-aligned',
align = 'center',
...props
}: React.ComponentProps<typeof SelectPrimitive.Content>) {
return (
<SelectPrimitive.Portal>
<SelectPrimitive.Content
data-slot="select-content"
data-align-trigger={position === 'item-aligned'}
className={cn(
'relative z-50 max-h-(--radix-select-content-available-height) min-w-36 origin-(--radix-select-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-lg bg-popover text-popover-foreground shadow-md ring-1 ring-foreground/10 duration-100 data-[align-trigger=true]:animate-none data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95',
position === 'popper' &&
'data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1',
className,
)}
position={position}
align={align}
{...props}
>
<SelectScrollUpButton />
<SelectPrimitive.Viewport
data-position={position}
className={cn(
'data-[position=popper]:h-(--radix-select-trigger-height) data-[position=popper]:w-full data-[position=popper]:min-w-(--radix-select-trigger-width)',
position === 'popper' && '',
)}
>
{children}
</SelectPrimitive.Viewport>
<SelectScrollDownButton />
</SelectPrimitive.Content>
</SelectPrimitive.Portal>
);
}
function SelectLabel({ className, ...props }: React.ComponentProps<typeof SelectPrimitive.Label>) {
return (
<SelectPrimitive.Label
data-slot="select-label"
className={cn('px-1.5 py-1 text-xs text-muted-foreground', className)}
{...props}
/>
);
}
function SelectItem({
className,
children,
...props
}: React.ComponentProps<typeof SelectPrimitive.Item>) {
return (
<SelectPrimitive.Item
data-slot="select-item"
className={cn(
"relative flex w-full cursor-default items-center gap-1.5 rounded-md py-1 pr-8 pl-1.5 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground not-data-[variant=destructive]:focus:**:text-accent-foreground data-disabled:pointer-events-none data-disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 *:[span]:last:flex *:[span]:last:items-center *:[span]:last:gap-2",
className,
)}
{...props}
>
<span className="pointer-events-none absolute right-2 flex size-4 items-center justify-center">
<SelectPrimitive.ItemIndicator>
<CheckIcon className="pointer-events-none" />
</SelectPrimitive.ItemIndicator>
</span>
<SelectPrimitive.ItemText>{children}</SelectPrimitive.ItemText>
</SelectPrimitive.Item>
);
}
function SelectSeparator({
className,
...props
}: React.ComponentProps<typeof SelectPrimitive.Separator>) {
return (
<SelectPrimitive.Separator
data-slot="select-separator"
className={cn('pointer-events-none -mx-1 my-1 h-px bg-border', className)}
{...props}
/>
);
}
function SelectScrollUpButton({
className,
...props
}: React.ComponentProps<typeof SelectPrimitive.ScrollUpButton>) {
return (
<SelectPrimitive.ScrollUpButton
data-slot="select-scroll-up-button"
className={cn(
"z-10 flex cursor-default items-center justify-center bg-popover py-1 [&_svg:not([class*='size-'])]:size-4",
className,
)}
{...props}
>
<ChevronUpIcon />
</SelectPrimitive.ScrollUpButton>
);
}
function SelectScrollDownButton({
className,
...props
}: React.ComponentProps<typeof SelectPrimitive.ScrollDownButton>) {
return (
<SelectPrimitive.ScrollDownButton
data-slot="select-scroll-down-button"
className={cn(
"z-10 flex cursor-default items-center justify-center bg-popover py-1 [&_svg:not([class*='size-'])]:size-4",
className,
)}
{...props}
>
<ChevronDownIcon />
</SelectPrimitive.ScrollDownButton>
);
}
export {
Select,
SelectContent,
SelectGroup,
SelectItem,
SelectLabel,
SelectScrollDownButton,
SelectScrollUpButton,
SelectSeparator,
SelectTrigger,
SelectValue,
};
+28
View File
@@ -0,0 +1,28 @@
'use client';
import * as React from 'react';
import { Separator as SeparatorPrimitive } from 'radix-ui';
import { cn } from '@/lib/utils';
function Separator({
className,
orientation = 'horizontal',
decorative = true,
...props
}: React.ComponentProps<typeof SeparatorPrimitive.Root>) {
return (
<SeparatorPrimitive.Root
data-slot="separator"
decorative={decorative}
orientation={orientation}
className={cn(
'shrink-0 bg-border data-horizontal:h-px data-horizontal:w-full data-vertical:w-px data-vertical:self-stretch',
className,
)}
{...props}
/>
);
}
export { Separator };
+130
View File
@@ -0,0 +1,130 @@
'use client';
import * as React from 'react';
import { Dialog as SheetPrimitive } from 'radix-ui';
import { cn } from '@/lib/utils';
import { Button } from '@/components/ui/button';
import { XIcon } from 'lucide-react';
function Sheet({ ...props }: React.ComponentProps<typeof SheetPrimitive.Root>) {
return <SheetPrimitive.Root data-slot="sheet" {...props} />;
}
function SheetTrigger({ ...props }: React.ComponentProps<typeof SheetPrimitive.Trigger>) {
return <SheetPrimitive.Trigger data-slot="sheet-trigger" {...props} />;
}
function SheetClose({ ...props }: React.ComponentProps<typeof SheetPrimitive.Close>) {
return <SheetPrimitive.Close data-slot="sheet-close" {...props} />;
}
function SheetPortal({ ...props }: React.ComponentProps<typeof SheetPrimitive.Portal>) {
return <SheetPrimitive.Portal data-slot="sheet-portal" {...props} />;
}
function SheetOverlay({
className,
...props
}: React.ComponentProps<typeof SheetPrimitive.Overlay>) {
return (
<SheetPrimitive.Overlay
data-slot="sheet-overlay"
className={cn(
'fixed inset-0 z-50 bg-black/10 duration-100 supports-backdrop-filter:backdrop-blur-xs data-open:animate-in data-open:fade-in-0 data-closed:animate-out data-closed:fade-out-0',
className,
)}
{...props}
/>
);
}
function SheetContent({
className,
children,
side = 'right',
showCloseButton = true,
...props
}: React.ComponentProps<typeof SheetPrimitive.Content> & {
side?: 'top' | 'right' | 'bottom' | 'left';
showCloseButton?: boolean;
}) {
return (
<SheetPortal>
<SheetOverlay />
<SheetPrimitive.Content
data-slot="sheet-content"
data-side={side}
className={cn(
'fixed z-50 flex flex-col gap-4 bg-popover bg-clip-padding text-sm text-popover-foreground shadow-lg transition duration-200 ease-in-out data-[side=bottom]:inset-x-0 data-[side=bottom]:bottom-0 data-[side=bottom]:h-auto data-[side=bottom]:border-t data-[side=left]:inset-y-0 data-[side=left]:left-0 data-[side=left]:h-full data-[side=left]:w-3/4 data-[side=left]:border-r data-[side=right]:inset-y-0 data-[side=right]:right-0 data-[side=right]:h-full data-[side=right]:w-3/4 data-[side=right]:border-l data-[side=top]:inset-x-0 data-[side=top]:top-0 data-[side=top]:h-auto data-[side=top]:border-b data-[side=left]:sm:max-w-sm data-[side=right]:sm:max-w-sm data-open:animate-in data-open:fade-in-0 data-[side=bottom]:data-open:slide-in-from-bottom-10 data-[side=left]:data-open:slide-in-from-left-10 data-[side=right]:data-open:slide-in-from-right-10 data-[side=top]:data-open:slide-in-from-top-10 data-closed:animate-out data-closed:fade-out-0 data-[side=bottom]:data-closed:slide-out-to-bottom-10 data-[side=left]:data-closed:slide-out-to-left-10 data-[side=right]:data-closed:slide-out-to-right-10 data-[side=top]:data-closed:slide-out-to-top-10',
className,
)}
{...props}
>
{children}
{showCloseButton && (
<SheetPrimitive.Close data-slot="sheet-close" asChild>
<Button variant="ghost" className="absolute top-3 right-3" size="icon-sm">
<XIcon />
<span className="sr-only">Close</span>
</Button>
</SheetPrimitive.Close>
)}
</SheetPrimitive.Content>
</SheetPortal>
);
}
function SheetHeader({ className, ...props }: React.ComponentProps<'div'>) {
return (
<div
data-slot="sheet-header"
className={cn('flex flex-col gap-0.5 p-4', className)}
{...props}
/>
);
}
function SheetFooter({ className, ...props }: React.ComponentProps<'div'>) {
return (
<div
data-slot="sheet-footer"
className={cn('mt-auto flex flex-col gap-2 p-4', className)}
{...props}
/>
);
}
function SheetTitle({ className, ...props }: React.ComponentProps<typeof SheetPrimitive.Title>) {
return (
<SheetPrimitive.Title
data-slot="sheet-title"
className={cn('text-base font-medium text-foreground', className)}
{...props}
/>
);
}
function SheetDescription({
className,
...props
}: React.ComponentProps<typeof SheetPrimitive.Description>) {
return (
<SheetPrimitive.Description
data-slot="sheet-description"
className={cn('text-sm text-muted-foreground', className)}
{...props}
/>
);
}
export {
Sheet,
SheetTrigger,
SheetClose,
SheetContent,
SheetHeader,
SheetFooter,
SheetTitle,
SheetDescription,
};
+34
View File
@@ -0,0 +1,34 @@
import { cn } from '@/lib/utils';
function Skeleton({ className, ...props }: React.ComponentProps<'div'>) {
return (
<div
data-slot="skeleton"
className={cn('animate-pulse rounded-md bg-muted', className)}
{...props}
/>
);
}
/** Linha de texto — usada em qualquer trecho aguardando conteúdo textual. */
function SkeletonText({ className, ...props }: React.ComponentProps<'div'>) {
return <Skeleton className={cn('h-4 w-full', className)} {...props} />;
}
/** Bloco de card — usada em grids de dashboard enquanto os dados carregam. */
function SkeletonCard({ className, ...props }: React.ComponentProps<'div'>) {
return <Skeleton className={cn('h-32 w-full rounded-xl', className)} {...props} />;
}
/** Linha de tabela — usada pela `DataTable` no estado de loading. */
function SkeletonTableRow({ columns = 4 }: { columns?: number }) {
return (
<div className="flex items-center gap-4 border-b border-border px-2 py-3 last:border-0">
{Array.from({ length: columns }).map((_, index) => (
<Skeleton key={index} className="h-4 flex-1" />
))}
</div>
);
}
export { Skeleton, SkeletonText, SkeletonCard, SkeletonTableRow };
+45
View File
@@ -0,0 +1,45 @@
'use client';
import { useTheme } from 'next-themes';
import { Toaster as Sonner, type ToasterProps } from 'sonner';
import {
CircleCheckIcon,
InfoIcon,
TriangleAlertIcon,
OctagonXIcon,
Loader2Icon,
} from 'lucide-react';
const Toaster = ({ ...props }: ToasterProps) => {
const { theme = 'system' } = useTheme();
return (
<Sonner
theme={theme as ToasterProps['theme']}
className="toaster group"
icons={{
success: <CircleCheckIcon className="size-4" />,
info: <InfoIcon className="size-4" />,
warning: <TriangleAlertIcon className="size-4" />,
error: <OctagonXIcon className="size-4" />,
loading: <Loader2Icon className="size-4 animate-spin" />,
}}
style={
{
'--normal-bg': 'var(--popover)',
'--normal-text': 'var(--popover-foreground)',
'--normal-border': 'var(--border)',
'--border-radius': 'var(--radius)',
} as React.CSSProperties
}
toastOptions={{
classNames: {
toast: 'cn-toast',
},
}}
{...props}
/>
);
};
export { Toaster };
+58
View File
@@ -0,0 +1,58 @@
import { cn } from '@/lib/utils';
export const STATUS_PILL_TONES = ['success', 'warning', 'danger', 'primary', 'neutral'] as const;
type StatusPillTone = (typeof STATUS_PILL_TONES)[number];
/**
* Status de negócio já existentes no backend (Etapas 1–8) → cor semântica
* + label em português, resolvidos uma única vez aqui para não repetir
* esse mapeamento em cada tela (Etapa 12).
*/
export const STATUS_PILL_MAP = {
pendente: { tone: 'warning', label: 'Pendente' },
pago: { tone: 'success', label: 'Pago' },
atrasado: { tone: 'danger', label: 'Atrasado' },
cancelado: { tone: 'neutral', label: 'Cancelado' },
ativo: { tone: 'success', label: 'Ativo' },
inadimplente: { tone: 'danger', label: 'Inadimplente' },
suspenso: { tone: 'warning', label: 'Suspenso' },
trial: { tone: 'primary', label: 'Trial' },
confirmada: { tone: 'primary', label: 'Confirmada' },
concluida: { tone: 'success', label: 'Concluída' },
orcamento: { tone: 'neutral', label: 'Orçamento' },
cancelada: { tone: 'neutral', label: 'Cancelada' },
} as const satisfies Record<string, { tone: StatusPillTone; label: string }>;
export type BusinessStatus = keyof typeof STATUS_PILL_MAP;
const toneClasses: Record<StatusPillTone, string> = {
success: 'bg-success/10 text-success',
warning: 'bg-warning/10 text-warning',
danger: 'bg-danger/10 text-danger',
primary: 'bg-primary/10 text-primary',
neutral: 'bg-neutral-500/10 text-neutral-500',
};
interface StatusPillProps {
status: BusinessStatus;
className?: string;
}
function StatusPill({ status, className }: StatusPillProps) {
const config = STATUS_PILL_MAP[status];
return (
<span
data-slot="status-pill"
className={cn(
'inline-flex h-5 w-fit shrink-0 items-center justify-center rounded-full px-2 py-0.5 text-xs font-medium whitespace-nowrap',
toneClasses[config.tone],
className,
)}
>
{config.label}
</span>
);
}
export { StatusPill };
+92
View File
@@ -0,0 +1,92 @@
'use client';
import * as React from 'react';
import { cn } from '@/lib/utils';
function Table({ className, ...props }: React.ComponentProps<'table'>) {
return (
<div data-slot="table-container" className="relative w-full overflow-x-auto">
<table
data-slot="table"
className={cn('w-full caption-bottom text-sm', className)}
{...props}
/>
</div>
);
}
function TableHeader({ className, ...props }: React.ComponentProps<'thead'>) {
return <thead data-slot="table-header" className={cn('[&_tr]:border-b', className)} {...props} />;
}
function TableBody({ className, ...props }: React.ComponentProps<'tbody'>) {
return (
<tbody
data-slot="table-body"
className={cn('[&_tr:last-child]:border-0', className)}
{...props}
/>
);
}
function TableFooter({ className, ...props }: React.ComponentProps<'tfoot'>) {
return (
<tfoot
data-slot="table-footer"
className={cn('border-t bg-muted/50 font-medium [&>tr]:last:border-b-0', className)}
{...props}
/>
);
}
function TableRow({ className, ...props }: React.ComponentProps<'tr'>) {
return (
<tr
data-slot="table-row"
className={cn(
'border-b transition-colors hover:bg-muted/50 has-aria-expanded:bg-muted/50 data-[state=selected]:bg-muted',
className,
)}
{...props}
/>
);
}
function TableHead({ className, ...props }: React.ComponentProps<'th'>) {
return (
<th
data-slot="table-head"
className={cn(
'h-10 px-3 text-left align-middle font-medium whitespace-nowrap text-foreground [&:has([role=checkbox])]:pr-0',
className,
)}
{...props}
/>
);
}
function TableCell({ className, ...props }: React.ComponentProps<'td'>) {
return (
<td
data-slot="table-cell"
className={cn(
'px-3 py-2.5 align-middle whitespace-nowrap [&:has([role=checkbox])]:pr-0',
className,
)}
{...props}
/>
);
}
function TableCaption({ className, ...props }: React.ComponentProps<'caption'>) {
return (
<caption
data-slot="table-caption"
className={cn('mt-4 text-sm text-muted-foreground', className)}
{...props}
/>
);
}
export { Table, TableHeader, TableBody, TableFooter, TableHead, TableRow, TableCell, TableCaption };
+80
View File
@@ -0,0 +1,80 @@
'use client';
import * as React from 'react';
import { cva, type VariantProps } from 'class-variance-authority';
import { Tabs as TabsPrimitive } from 'radix-ui';
import { cn } from '@/lib/utils';
function Tabs({
className,
orientation = 'horizontal',
...props
}: React.ComponentProps<typeof TabsPrimitive.Root>) {
return (
<TabsPrimitive.Root
data-slot="tabs"
data-orientation={orientation}
className={cn('group/tabs flex gap-2 data-horizontal:flex-col', className)}
{...props}
/>
);
}
const tabsListVariants = cva(
'group/tabs-list inline-flex w-fit items-center justify-center rounded-lg p-[3px] text-muted-foreground group-data-horizontal/tabs:h-11 group-data-vertical/tabs:h-fit group-data-vertical/tabs:flex-col data-[variant=line]:rounded-none',
{
variants: {
variant: {
default: 'bg-muted',
line: 'gap-1 bg-transparent',
},
},
defaultVariants: {
variant: 'default',
},
},
);
function TabsList({
className,
variant = 'default',
...props
}: React.ComponentProps<typeof TabsPrimitive.List> & VariantProps<typeof tabsListVariants>) {
return (
<TabsPrimitive.List
data-slot="tabs-list"
data-variant={variant}
className={cn(tabsListVariants({ variant }), className)}
{...props}
/>
);
}
function TabsTrigger({ className, ...props }: React.ComponentProps<typeof TabsPrimitive.Trigger>) {
return (
<TabsPrimitive.Trigger
data-slot="tabs-trigger"
className={cn(
"relative inline-flex h-[calc(100%-1px)] flex-1 items-center justify-center gap-1.5 rounded-md border border-transparent px-1.5 py-0.5 text-sm font-medium whitespace-nowrap text-foreground/60 transition-all group-data-vertical/tabs:w-full group-data-vertical/tabs:justify-start hover:text-foreground focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 focus-visible:outline-1 focus-visible:outline-ring disabled:pointer-events-none disabled:opacity-50 has-data-[icon=inline-end]:pr-1 has-data-[icon=inline-start]:pl-1 dark:text-muted-foreground dark:hover:text-foreground group-data-[variant=default]/tabs-list:data-active:shadow-sm group-data-[variant=line]/tabs-list:data-active:shadow-none [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
'group-data-[variant=line]/tabs-list:bg-transparent group-data-[variant=line]/tabs-list:data-active:bg-transparent dark:group-data-[variant=line]/tabs-list:data-active:border-transparent dark:group-data-[variant=line]/tabs-list:data-active:bg-transparent',
'data-active:bg-background data-active:text-foreground dark:data-active:border-input dark:data-active:bg-input/30 dark:data-active:text-foreground',
'after:absolute after:bg-foreground after:opacity-0 after:transition-opacity group-data-horizontal/tabs:after:inset-x-0 group-data-horizontal/tabs:after:bottom-[-5px] group-data-horizontal/tabs:after:h-0.5 group-data-vertical/tabs:after:inset-y-0 group-data-vertical/tabs:after:-right-1 group-data-vertical/tabs:after:w-0.5 group-data-[variant=line]/tabs-list:data-active:after:opacity-100',
className,
)}
{...props}
/>
);
}
function TabsContent({ className, ...props }: React.ComponentProps<typeof TabsPrimitive.Content>) {
return (
<TabsPrimitive.Content
data-slot="tabs-content"
className={cn('flex-1 text-sm outline-none', className)}
{...props}
/>
);
}
export { Tabs, TabsList, TabsTrigger, TabsContent, tabsListVariants };
+18
View File
@@ -0,0 +1,18 @@
import * as React from 'react';
import { cn } from '@/lib/utils';
function Textarea({ className, ...props }: React.ComponentProps<'textarea'>) {
return (
<textarea
data-slot="textarea"
className={cn(
'flex field-sizing-content min-h-24 w-full rounded-lg border border-input bg-transparent px-3 py-2 text-base transition-colors outline-none placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:bg-input/50 disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 md:text-sm',
className,
)}
{...props}
/>
);
}
export { Textarea };