feat: adicionar construtor de dashboards e api de métricas

This commit is contained in:
Esdras Renan 2025-11-04 20:37:34 -03:00
parent c2acd65764
commit 741f1d7f9c
14 changed files with 4356 additions and 9 deletions

View file

@ -0,0 +1,273 @@
"use client"
import { useState } from "react"
import Link from "next/link"
import { useRouter } from "next/navigation"
import { useMutation, useQuery } from "convex/react"
import { formatDistanceToNow } from "date-fns"
import { ptBR } from "date-fns/locale"
import { Plus, Sparkles } from "lucide-react"
import type { Id } from "@/convex/_generated/dataModel"
import { api } from "@/convex/_generated/api"
import { DEFAULT_TENANT_ID } from "@/lib/constants"
import { useAuth } from "@/lib/auth-client"
import { Button } from "@/components/ui/button"
import {
Card,
CardContent,
CardDescription,
CardFooter,
CardHeader,
CardTitle,
} from "@/components/ui/card"
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog"
import { Input } from "@/components/ui/input"
import { Skeleton } from "@/components/ui/skeleton"
import { Badge } from "@/components/ui/badge"
import { toast } from "sonner"
type DashboardSummary = {
id: Id<"dashboards">
tenantId: string
name: string
description: string | null
aspectRatio: string
theme: string
filters: Record<string, unknown>
layout: Array<{ i: string; x: number; y: number; w: number; h: number }>
sections: Array<{
id: string
title?: string
description?: string
widgetKeys: string[]
durationSeconds?: number
}>
tvIntervalSeconds: number
readySelector: string | null
createdBy: Id<"users">
updatedBy: Id<"users"> | null
createdAt: number
updatedAt: number
isArchived: boolean
widgetsCount: number
}
type CreateDashboardDialogProps = {
onCreate: (name: string, description: string | null) => Promise<void>
isLoading: boolean
}
function CreateDashboardDialog({ onCreate, isLoading }: CreateDashboardDialogProps) {
const [open, setOpen] = useState(false)
const [name, setName] = useState("")
const [description, setDescription] = useState("")
async function handleSubmit(event: React.FormEvent<HTMLFormElement>) {
event.preventDefault()
const trimmedName = name.trim()
if (!trimmedName) {
toast.error("Informe um nome para o dashboard.")
return
}
await onCreate(trimmedName, description.trim() ? description.trim() : null)
setOpen(false)
setName("")
setDescription("")
}
return (
<>
<Button onClick={() => setOpen(true)} className="gap-2">
<Plus className="size-4" />
Novo dashboard
</Button>
<Dialog open={open} onOpenChange={setOpen}>
<DialogContent className="max-w-md">
<DialogHeader>
<DialogTitle>Criar dashboard</DialogTitle>
</DialogHeader>
<form onSubmit={handleSubmit} className="space-y-4">
<div className="space-y-2">
<label htmlFor="dashboard-name" className="text-sm font-medium">
Nome
</label>
<Input
id="dashboard-name"
value={name}
onChange={(event) => setName(event.target.value)}
placeholder="Ex.: Operações - Visão Geral"
required
/>
</div>
<div className="space-y-2">
<label htmlFor="dashboard-description" className="text-sm font-medium">
Descrição <span className="text-muted-foreground text-xs">(opcional)</span>
</label>
<Input
id="dashboard-description"
value={description}
onChange={(event) => setDescription(event.target.value)}
placeholder="Contextualize para a equipe"
/>
</div>
<DialogFooter className="sm:justify-between">
<Button type="button" variant="outline" onClick={() => setOpen(false)}>
Cancelar
</Button>
<Button type="submit" disabled={isLoading}>
{isLoading ? "Criando..." : "Criar dashboard"}
</Button>
</DialogFooter>
</form>
</DialogContent>
</Dialog>
</>
)
}
export function DashboardListView() {
const router = useRouter()
const { session, convexUserId, isStaff } = useAuth()
const tenantId = session?.user.tenantId ?? DEFAULT_TENANT_ID
const createDashboard = useMutation(api.dashboards.create)
const [isCreating, setIsCreating] = useState(false)
const dashboards = useQuery(
api.dashboards.list,
isStaff && convexUserId
? ({
tenantId,
viewerId: convexUserId as Id<"users">,
} as const)
: "skip"
) as DashboardSummary[] | undefined
async function handleCreate(name: string, description: string | null) {
if (!convexUserId) return
setIsCreating(true)
try {
const result = await createDashboard({
tenantId,
actorId: convexUserId as Id<"users">,
name,
description: description ?? undefined,
})
toast.success("Dashboard criado com sucesso!")
router.push(`/dashboards/${result.id}`)
} catch (error) {
console.error(error)
toast.error("Não foi possível criar o dashboard.")
} finally {
setIsCreating(false)
}
}
if (!isStaff) {
return (
<Card className="border-dashed border-primary/40 bg-primary/5 text-primary">
<CardHeader>
<CardTitle>Acesso restrito</CardTitle>
<CardDescription>Somente a equipe interna pode visualizar e montar dashboards.</CardDescription>
</CardHeader>
</Card>
)
}
if (!dashboards) {
return (
<div className="grid gap-4 sm:grid-cols-2 xl:grid-cols-3">
{Array.from({ length: 3 }).map((_, index) => (
<Card key={index} className="border-muted/60 bg-muted/20">
<CardHeader className="space-y-2">
<Skeleton className="h-4 w-32" />
<Skeleton className="h-6 w-48" />
</CardHeader>
<CardContent className="space-y-2">
<Skeleton className="h-3 w-full" />
<Skeleton className="h-3 w-3/4" />
<Skeleton className="h-3 w-1/2" />
</CardContent>
<CardFooter>
<Skeleton className="h-9 w-full" />
</CardFooter>
</Card>
))}
</div>
)
}
const activeDashboards = dashboards.filter((dashboard) => !dashboard.isArchived)
return (
<div className="space-y-6">
<div className="flex flex-wrap items-center justify-between gap-3">
<div className="flex flex-col gap-1">
<h2 className="text-lg font-semibold">Dashboards personalizados</h2>
<p className="text-sm text-muted-foreground">
Combine KPIs, gráficos, tabelas e texto em painéis dinâmicos com filtros globais.
</p>
</div>
<CreateDashboardDialog onCreate={handleCreate} isLoading={isCreating} />
</div>
{activeDashboards.length === 0 ? (
<Card className="border-dashed border-muted-foreground/40 bg-muted/10">
<CardHeader className="flex flex-col items-start gap-2 sm:flex-row sm:items-center sm:justify-between">
<div>
<CardTitle className="flex items-center gap-2">
<Sparkles className="size-4 text-primary" />
Crie o seu primeiro dashboard
</CardTitle>
<CardDescription>
Monte painéis por cliente, fila ou operação e compartilhe com a equipe.
</CardDescription>
</div>
<CreateDashboardDialog onCreate={handleCreate} isLoading={isCreating} />
</CardHeader>
<CardContent className="space-y-2 text-sm text-muted-foreground">
<p> Arraste e redimensione widgets livremente no canvas.</p>
<p> Salve filtros padrão por dashboard e gere exportações em PDF/PNG.</p>
<p> Ative o modo TV ou compartilhe via link público com token rotativo.</p>
</CardContent>
</Card>
) : (
<div className="grid gap-4 md:grid-cols-2 xl:grid-cols-3">
{activeDashboards.map((dashboard) => {
const updatedAt = formatDistanceToNow(dashboard.updatedAt, {
addSuffix: true,
locale: ptBR,
})
return (
<Card key={dashboard.id} className="group border-muted/70 transition hover:border-primary/60 hover:shadow-lg">
<CardHeader>
<CardTitle className="flex items-center justify-between gap-4 text-base">
<span className="truncate">{dashboard.name}</span>
<Badge variant="outline" className="shrink-0">
{dashboard.widgetsCount} widget{dashboard.widgetsCount === 1 ? "" : "s"}
</Badge>
</CardTitle>
{dashboard.description ? (
<CardDescription className="line-clamp-2 text-sm">{dashboard.description}</CardDescription>
) : null}
</CardHeader>
<CardContent className="space-y-1 text-sm text-muted-foreground">
<p>
Última atualização{" "}
<span className="font-medium text-foreground">{updatedAt}</span>
</p>
<p>Formato {dashboard.aspectRatio} · Tema {dashboard.theme}</p>
</CardContent>
<CardFooter>
<Button asChild className="w-full">
<Link href={`/dashboards/${dashboard.id}`}>Abrir dashboard</Link>
</Button>
</CardFooter>
</Card>
)
})}
</div>
)}
</div>
)
}