feat: adicionar construtor de dashboards e api de métricas
This commit is contained in:
parent
c2acd65764
commit
741f1d7f9c
14 changed files with 4356 additions and 9 deletions
|
|
@ -3,6 +3,7 @@
|
|||
import * as React from "react"
|
||||
import {
|
||||
LayoutDashboard,
|
||||
LayoutTemplate,
|
||||
LifeBuoy,
|
||||
Ticket,
|
||||
PlayCircle,
|
||||
|
|
@ -83,6 +84,7 @@ const navigation: NavigationGroup[] = [
|
|||
title: "Relatórios",
|
||||
requiredRole: "staff",
|
||||
items: [
|
||||
{ title: "Dashboards", url: "/dashboards", icon: LayoutTemplate, requiredRole: "staff" },
|
||||
{ title: "Produtividade", url: "/reports/sla", icon: TrendingUp, requiredRole: "staff" },
|
||||
{ title: "Qualidade (CSAT)", url: "/reports/csat", icon: LifeBuoy, requiredRole: "staff" },
|
||||
{ title: "Backlog", url: "/reports/backlog", icon: BarChart3, requiredRole: "staff" },
|
||||
|
|
|
|||
1439
src/components/dashboards/dashboard-builder.tsx
Normal file
1439
src/components/dashboards/dashboard-builder.tsx
Normal file
File diff suppressed because it is too large
Load diff
273
src/components/dashboards/dashboard-list.tsx
Normal file
273
src/components/dashboards/dashboard-list.tsx
Normal 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>
|
||||
)
|
||||
}
|
||||
275
src/components/dashboards/report-canvas.tsx
Normal file
275
src/components/dashboards/report-canvas.tsx
Normal file
|
|
@ -0,0 +1,275 @@
|
|||
"use client"
|
||||
|
||||
import type { ReactNode } from "react"
|
||||
import { useEffect, useMemo, useRef, useState } from "react"
|
||||
import {
|
||||
DndContext,
|
||||
DragEndEvent,
|
||||
MouseSensor,
|
||||
PointerSensor,
|
||||
TouchSensor,
|
||||
closestCenter,
|
||||
useSensor,
|
||||
useSensors,
|
||||
} from "@dnd-kit/core"
|
||||
import { CSS } from "@dnd-kit/utilities"
|
||||
import {
|
||||
SortableContext,
|
||||
arrayMove,
|
||||
useSortable,
|
||||
} from "@dnd-kit/sortable"
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
type PackedLayoutItem = {
|
||||
i: string
|
||||
x: number
|
||||
y: number
|
||||
w: number
|
||||
h: number
|
||||
minW?: number
|
||||
minH?: number
|
||||
static?: boolean
|
||||
}
|
||||
|
||||
type CanvasItem = {
|
||||
key: string
|
||||
element: ReactNode
|
||||
layout: PackedLayoutItem
|
||||
minW?: number
|
||||
minH?: number
|
||||
static?: boolean
|
||||
}
|
||||
|
||||
type ReportCanvasProps = {
|
||||
items: CanvasItem[]
|
||||
editable?: boolean
|
||||
columns?: number
|
||||
rowHeight?: number
|
||||
gap?: number
|
||||
ready?: boolean
|
||||
onReorder?: (nextOrder: string[]) => void
|
||||
onResize?: (key: string, size: { w: number; h: number }, options?: { commit?: boolean }) => void
|
||||
}
|
||||
|
||||
type InternalResizeState = {
|
||||
key: string
|
||||
originX: number
|
||||
originY: number
|
||||
initialWidth: number
|
||||
initialHeight: number
|
||||
minW: number
|
||||
minH: number
|
||||
}
|
||||
|
||||
const DEFAULT_COLUMNS = 12
|
||||
const DEFAULT_ROW_HEIGHT = 80
|
||||
const MAX_ROWS = 24
|
||||
|
||||
export function ReportCanvas({
|
||||
items,
|
||||
editable = false,
|
||||
columns = DEFAULT_COLUMNS,
|
||||
rowHeight = DEFAULT_ROW_HEIGHT,
|
||||
gap = 16,
|
||||
ready = false,
|
||||
onReorder,
|
||||
onResize,
|
||||
}: ReportCanvasProps) {
|
||||
const containerRef = useRef<HTMLDivElement | null>(null)
|
||||
const [containerWidth, setContainerWidth] = useState(0)
|
||||
const [resizing, setResizing] = useState<InternalResizeState | null>(null)
|
||||
const lastResizeSizeRef = useRef<{ w: number; h: number } | null>(null)
|
||||
|
||||
useEffect(() => {
|
||||
const element = containerRef.current
|
||||
if (!element) return
|
||||
const observer = new ResizeObserver((entries) => {
|
||||
for (const entry of entries) {
|
||||
if (entry.contentRect) {
|
||||
setContainerWidth(entry.contentRect.width)
|
||||
}
|
||||
}
|
||||
})
|
||||
observer.observe(element)
|
||||
return () => {
|
||||
observer.disconnect()
|
||||
}
|
||||
}, [])
|
||||
|
||||
const columnWidth = containerWidth > 0 ? containerWidth / columns : 0
|
||||
|
||||
useEffect(() => {
|
||||
if (!resizing) return
|
||||
function handlePointerMove(event: PointerEvent) {
|
||||
if (!resizing) return
|
||||
if (!columnWidth) return
|
||||
const deltaX = event.clientX - resizing.originX
|
||||
const deltaY = event.clientY - resizing.originY
|
||||
const deltaCols = Math.round(deltaX / columnWidth)
|
||||
const deltaRows = Math.round(deltaY / rowHeight)
|
||||
let nextW = resizing.initialWidth + deltaCols
|
||||
let nextH = resizing.initialHeight + deltaRows
|
||||
nextW = Math.min(columns, Math.max(resizing.minW, nextW))
|
||||
nextH = Math.min(MAX_ROWS, Math.max(resizing.minH, nextH))
|
||||
const previous = lastResizeSizeRef.current
|
||||
if (!previous || previous.w !== nextW || previous.h !== nextH) {
|
||||
lastResizeSizeRef.current = { w: nextW, h: nextH }
|
||||
onResize?.(resizing.key, { w: nextW, h: nextH })
|
||||
}
|
||||
}
|
||||
function handlePointerUp() {
|
||||
if (resizing) {
|
||||
const finalSize = lastResizeSizeRef.current ?? { w: resizing.initialWidth, h: resizing.initialHeight }
|
||||
onResize?.(resizing.key, finalSize, { commit: true })
|
||||
}
|
||||
setResizing(null)
|
||||
lastResizeSizeRef.current = null
|
||||
window.removeEventListener("pointermove", handlePointerMove)
|
||||
window.removeEventListener("pointerup", handlePointerUp)
|
||||
}
|
||||
window.addEventListener("pointermove", handlePointerMove)
|
||||
window.addEventListener("pointerup", handlePointerUp)
|
||||
return () => {
|
||||
window.removeEventListener("pointermove", handlePointerMove)
|
||||
window.removeEventListener("pointerup", handlePointerUp)
|
||||
}
|
||||
}, [columnWidth, onResize, resizing, rowHeight, columns])
|
||||
|
||||
const sensors = useSensors(
|
||||
useSensor(PointerSensor, { activationConstraint: { distance: 6 } }),
|
||||
useSensor(MouseSensor, { activationConstraint: { distance: 6 } }),
|
||||
useSensor(TouchSensor, { activationConstraint: { delay: 120, tolerance: 8 } }),
|
||||
)
|
||||
|
||||
const sortableItems = useMemo(() => items.map((item) => item.key), [items])
|
||||
|
||||
const handleDragEnd = (event: DragEndEvent) => {
|
||||
if (!editable) return
|
||||
const { active, over } = event
|
||||
if (!active?.id || !over?.id) return
|
||||
if (active.id === over.id) return
|
||||
const currentOrder = sortableItems
|
||||
const oldIndex = currentOrder.indexOf(String(active.id))
|
||||
const newIndex = currentOrder.indexOf(String(over.id))
|
||||
if (oldIndex === -1 || newIndex === -1) return
|
||||
const nextOrder = arrayMove(currentOrder, oldIndex, newIndex)
|
||||
onReorder?.(nextOrder)
|
||||
}
|
||||
|
||||
const handleResizePointerDown = (
|
||||
event: React.PointerEvent<HTMLDivElement>,
|
||||
item: CanvasItem,
|
||||
) => {
|
||||
if (!editable || item.static) return
|
||||
event.preventDefault()
|
||||
event.stopPropagation()
|
||||
const layout = item.layout
|
||||
const minW = item.minW ?? layout.minW ?? 2
|
||||
const minH = item.minH ?? layout.minH ?? 2
|
||||
setResizing({
|
||||
key: item.key,
|
||||
originX: event.clientX,
|
||||
originY: event.clientY,
|
||||
initialWidth: layout.w,
|
||||
initialHeight: layout.h,
|
||||
minW,
|
||||
minH,
|
||||
})
|
||||
}
|
||||
|
||||
const content = (
|
||||
<div
|
||||
ref={containerRef}
|
||||
data-dashboard-ready={ready}
|
||||
className={cn(
|
||||
"grid transition-all duration-200",
|
||||
ready ? "opacity-100" : "opacity-70",
|
||||
)}
|
||||
style={{
|
||||
gridTemplateColumns: `repeat(${columns}, minmax(0, 1fr))`,
|
||||
gridAutoRows: `${rowHeight}px`,
|
||||
gap,
|
||||
}}
|
||||
>
|
||||
{items.map((item) => {
|
||||
const layout = item.layout
|
||||
const gridStyle: React.CSSProperties = {
|
||||
gridColumn: `${layout.x + 1} / span ${layout.w}`,
|
||||
gridRow: `${layout.y + 1} / span ${layout.h}`,
|
||||
}
|
||||
return (
|
||||
<SortableTile
|
||||
key={item.key}
|
||||
id={item.key}
|
||||
style={gridStyle}
|
||||
className="relative h-full"
|
||||
disabled={!editable || Boolean(resizing)}
|
||||
>
|
||||
<div className="relative h-full">
|
||||
{item.element}
|
||||
{editable && !item.static ? (
|
||||
<div
|
||||
role="presentation"
|
||||
className="absolute bottom-1 right-1 size-4 cursor-se-resize rounded-sm border border-border/60 bg-background/70 shadow ring-1 ring-border/40"
|
||||
onPointerDown={(event) => handleResizePointerDown(event, item)}
|
||||
/>
|
||||
) : null}
|
||||
</div>
|
||||
</SortableTile>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)
|
||||
|
||||
if (!editable) {
|
||||
return content
|
||||
}
|
||||
|
||||
return (
|
||||
<DndContext
|
||||
sensors={sensors}
|
||||
collisionDetection={closestCenter}
|
||||
onDragEnd={handleDragEnd}
|
||||
>
|
||||
<SortableContext items={sortableItems}>{content}</SortableContext>
|
||||
</DndContext>
|
||||
)
|
||||
}
|
||||
|
||||
type SortableTileProps = {
|
||||
id: string
|
||||
children: ReactNode
|
||||
style?: React.CSSProperties
|
||||
className?: string
|
||||
disabled?: boolean
|
||||
}
|
||||
|
||||
function SortableTile({ id, children, style, className, disabled }: SortableTileProps) {
|
||||
const { attributes, listeners, setNodeRef, transform, transition, isDragging } = useSortable({
|
||||
id,
|
||||
disabled,
|
||||
})
|
||||
const combinedStyle: React.CSSProperties = {
|
||||
...style,
|
||||
transform: transform ? CSS.Transform.toString(transform) : undefined,
|
||||
transition,
|
||||
zIndex: isDragging ? 5 : undefined,
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={setNodeRef}
|
||||
style={combinedStyle}
|
||||
className={cn(
|
||||
"rounded-xl border border-transparent bg-transparent transition",
|
||||
isDragging ? "shadow-xl" : "",
|
||||
className,
|
||||
)}
|
||||
{...attributes}
|
||||
{...listeners}
|
||||
data-key={id}
|
||||
>
|
||||
{children}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
865
src/components/dashboards/widget-renderer.tsx
Normal file
865
src/components/dashboards/widget-renderer.tsx
Normal file
|
|
@ -0,0 +1,865 @@
|
|||
"use client"
|
||||
|
||||
import { useEffect, useMemo } from "react"
|
||||
import { useQuery } from "convex/react"
|
||||
import { format } from "date-fns"
|
||||
import { ptBR } from "date-fns/locale"
|
||||
import type { Id } from "@/convex/_generated/dataModel"
|
||||
import {
|
||||
Area,
|
||||
AreaChart,
|
||||
Bar,
|
||||
BarChart,
|
||||
CartesianGrid,
|
||||
Cell,
|
||||
Label,
|
||||
Line,
|
||||
LineChart,
|
||||
Pie,
|
||||
PieChart,
|
||||
PolarAngleAxis,
|
||||
PolarGrid,
|
||||
PolarRadiusAxis,
|
||||
Radar,
|
||||
RadarChart,
|
||||
RadialBar,
|
||||
RadialBarChart,
|
||||
Tooltip as RechartsTooltip,
|
||||
XAxis,
|
||||
YAxis,
|
||||
} from "recharts"
|
||||
import sanitizeHtml from "sanitize-html"
|
||||
|
||||
import { api } from "@/convex/_generated/api"
|
||||
import { DEFAULT_TENANT_ID } from "@/lib/constants"
|
||||
import { useAuth } from "@/lib/auth-client"
|
||||
import { cn } from "@/lib/utils"
|
||||
import {
|
||||
Card,
|
||||
CardContent,
|
||||
CardDescription,
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
} from "@/components/ui/card"
|
||||
import { Badge } from "@/components/ui/badge"
|
||||
import { Skeleton } from "@/components/ui/skeleton"
|
||||
import {
|
||||
ChartConfig,
|
||||
ChartContainer,
|
||||
ChartLegend,
|
||||
ChartLegendContent,
|
||||
ChartTooltip,
|
||||
ChartTooltipContent,
|
||||
} from "@/components/ui/chart"
|
||||
import {
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableHead,
|
||||
TableHeader,
|
||||
TableRow,
|
||||
} from "@/components/ui/table"
|
||||
|
||||
const numberFormatter = new Intl.NumberFormat("pt-BR", { maximumFractionDigits: 1 })
|
||||
const percentFormatter = new Intl.NumberFormat("pt-BR", { style: "percent", maximumFractionDigits: 1 })
|
||||
|
||||
const CHART_COLORS = ["var(--chart-1)", "var(--chart-2)", "var(--chart-3)", "var(--chart-4)", "var(--chart-5)"]
|
||||
|
||||
export type DashboardFilters = {
|
||||
range?: "7d" | "30d" | "90d" | "custom"
|
||||
from?: string | null
|
||||
to?: string | null
|
||||
companyId?: string | null
|
||||
queueId?: string | null
|
||||
}
|
||||
|
||||
export type WidgetConfig = {
|
||||
type?: string
|
||||
title?: string
|
||||
description?: string
|
||||
dataSource?: {
|
||||
metricKey?: string
|
||||
params?: Record<string, unknown>
|
||||
}
|
||||
encoding?: {
|
||||
x?: string
|
||||
y?: Array<{ field: string; label?: string }>
|
||||
category?: string
|
||||
value?: string
|
||||
stacked?: boolean
|
||||
angle?: string
|
||||
radius?: string
|
||||
}
|
||||
options?: Record<string, unknown>
|
||||
columns?: Array<{ field: string; label: string }>
|
||||
content?: string
|
||||
}
|
||||
|
||||
export type DashboardWidgetRecord = {
|
||||
id: Id<"dashboardWidgets">
|
||||
widgetKey: string
|
||||
type: string
|
||||
title: string | null
|
||||
config: WidgetConfig | Record<string, unknown>
|
||||
}
|
||||
|
||||
type WidgetRendererProps = {
|
||||
widget: DashboardWidgetRecord
|
||||
filters: DashboardFilters
|
||||
mode?: "edit" | "view" | "tv" | "print"
|
||||
onReadyChange?: (ready: boolean) => void
|
||||
}
|
||||
|
||||
type UseMetricDataArgs = {
|
||||
metricKey?: string | null
|
||||
params?: Record<string, unknown>
|
||||
enabled?: boolean
|
||||
}
|
||||
|
||||
type MetricResult = {
|
||||
data: unknown
|
||||
meta: { kind: string; [key: string]: unknown } | null
|
||||
isLoading: boolean
|
||||
isError: boolean
|
||||
}
|
||||
|
||||
function normalizeParams(raw?: Record<string, unknown>) {
|
||||
if (!raw) return undefined
|
||||
const next: Record<string, unknown> = {}
|
||||
for (const [key, value] of Object.entries(raw)) {
|
||||
if (value === undefined) continue
|
||||
if (value === null) continue
|
||||
if (typeof value === "string" && value.trim().length === 0) continue
|
||||
if (Array.isArray(value)) {
|
||||
const filtered = value.filter((entry) => entry !== undefined && entry !== null)
|
||||
if (filtered.length === 0) continue
|
||||
next[key] = filtered
|
||||
continue
|
||||
}
|
||||
next[key] = value
|
||||
}
|
||||
return Object.keys(next).length > 0 ? next : undefined
|
||||
}
|
||||
|
||||
function mergeFilterParams(base: Record<string, unknown> | undefined, filters: DashboardFilters) {
|
||||
if (!filters) return base
|
||||
const merged: Record<string, unknown> = { ...(base ?? {}) }
|
||||
if (filters.range) {
|
||||
if (filters.range === "custom") {
|
||||
if (filters.from) merged.from = filters.from
|
||||
if (filters.to) merged.to = filters.to
|
||||
delete merged.range
|
||||
} else {
|
||||
merged.range = filters.range
|
||||
delete merged.from
|
||||
delete merged.to
|
||||
}
|
||||
}
|
||||
if (filters.companyId && filters.companyId !== "all") {
|
||||
merged.companyId = filters.companyId
|
||||
} else if (filters.companyId === "all") {
|
||||
delete merged.companyId
|
||||
}
|
||||
if (filters.queueId) {
|
||||
merged.queueId = filters.queueId
|
||||
}
|
||||
return merged
|
||||
}
|
||||
|
||||
function useMetricData({ metricKey, params, enabled = true }: UseMetricDataArgs): MetricResult {
|
||||
const { session, convexUserId, isStaff } = useAuth()
|
||||
const tenantId = session?.user.tenantId ?? DEFAULT_TENANT_ID
|
||||
const shouldFetch = Boolean(enabled && metricKey && isStaff && convexUserId)
|
||||
const normalized = useMemo(() => normalizeParams(params), [params])
|
||||
const result = useQuery(
|
||||
api.metrics.run,
|
||||
shouldFetch
|
||||
? ({
|
||||
tenantId,
|
||||
viewerId: convexUserId as Id<"users">,
|
||||
metricKey: metricKey as string,
|
||||
params: normalized,
|
||||
} as const)
|
||||
: "skip",
|
||||
) as { data: unknown; meta: { kind: string; [key: string]: unknown } } | undefined
|
||||
const isLoading = shouldFetch && result === undefined
|
||||
const meta = result?.meta ?? null
|
||||
const isError = Boolean(meta && meta.kind === "error")
|
||||
return {
|
||||
data: result?.data,
|
||||
meta,
|
||||
isLoading,
|
||||
isError,
|
||||
}
|
||||
}
|
||||
|
||||
function normalizeWidgetConfig(widget: DashboardWidgetRecord): WidgetConfig {
|
||||
const raw = widget.config
|
||||
if (raw && typeof raw === "object") {
|
||||
return { type: widget.type, ...raw } as WidgetConfig
|
||||
}
|
||||
return { type: widget.type, title: widget.title ?? undefined }
|
||||
}
|
||||
|
||||
function needsMetricData(type: string) {
|
||||
return type !== "text"
|
||||
}
|
||||
|
||||
function formatDateLabel(value: unknown) {
|
||||
if (typeof value === "number") {
|
||||
return format(new Date(value), "dd MMM", { locale: ptBR })
|
||||
}
|
||||
if (typeof value === "string") {
|
||||
const trimmed = value.trim()
|
||||
if (/^\d{4}-\d{2}-\d{2}$/.test(trimmed)) {
|
||||
const date = new Date(trimmed + "T00:00:00Z")
|
||||
if (!Number.isNaN(date.getTime())) {
|
||||
return format(date, "dd MMM", { locale: ptBR })
|
||||
}
|
||||
}
|
||||
return trimmed
|
||||
}
|
||||
return String(value ?? "")
|
||||
}
|
||||
|
||||
function parseNumeric(value: unknown): number | null {
|
||||
if (typeof value === "number" && Number.isFinite(value)) return value
|
||||
if (typeof value === "string") {
|
||||
const parsed = Number(value)
|
||||
if (Number.isFinite(parsed)) return parsed
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
export function WidgetRenderer({ widget, filters, mode = "edit", onReadyChange }: WidgetRendererProps) {
|
||||
const config = normalizeWidgetConfig(widget)
|
||||
const widgetType = (config.type ?? widget.type ?? "text").toLowerCase()
|
||||
const title = config.title ?? widget.title ?? "Widget"
|
||||
const description = config.description
|
||||
const mergedParams = useMemo(() => mergeFilterParams(config.dataSource?.params, filters), [config.dataSource?.params, filters])
|
||||
const metric = useMetricData({
|
||||
metricKey: config.dataSource?.metricKey,
|
||||
params: mergedParams,
|
||||
enabled: needsMetricData(widgetType),
|
||||
})
|
||||
const trendMetric = useMetricData({
|
||||
metricKey: typeof config.options?.trend === "string" ? (config.options.trend as string) : undefined,
|
||||
params: mergedParams,
|
||||
enabled: widgetType === "kpi" && Boolean(config.options?.trend),
|
||||
})
|
||||
|
||||
useEffect(() => {
|
||||
if (!needsMetricData(widgetType)) {
|
||||
onReadyChange?.(true)
|
||||
return
|
||||
}
|
||||
if (widgetType === "kpi" && config.options?.trend) {
|
||||
onReadyChange?.(!metric.isLoading && !trendMetric.isLoading && !metric.isError && !trendMetric.isError)
|
||||
} else {
|
||||
onReadyChange?.(!metric.isLoading && !metric.isError)
|
||||
}
|
||||
}, [
|
||||
widgetType,
|
||||
config.options?.trend,
|
||||
metric.isLoading,
|
||||
metric.isError,
|
||||
trendMetric.isLoading,
|
||||
trendMetric.isError,
|
||||
onReadyChange,
|
||||
])
|
||||
|
||||
const isLoading = metric.isLoading || (widgetType === "kpi" && Boolean(config.options?.trend) && trendMetric.isLoading)
|
||||
const isError = metric.isError
|
||||
const resolvedTitle = mode === "tv" ? title.toUpperCase() : title
|
||||
|
||||
if (isError) {
|
||||
return (
|
||||
<Card className="h-full border-destructive/50 bg-destructive/5">
|
||||
<CardHeader>
|
||||
<CardTitle className="text-destructive">{resolvedTitle}</CardTitle>
|
||||
{description ? <CardDescription>{description}</CardDescription> : null}
|
||||
</CardHeader>
|
||||
<CardContent className="text-sm text-destructive">
|
||||
Não foi possível carregar esta métrica. Verifique a configuração.
|
||||
</CardContent>
|
||||
</Card>
|
||||
)
|
||||
}
|
||||
|
||||
switch (widgetType) {
|
||||
case "kpi":
|
||||
return renderKpi({
|
||||
title: resolvedTitle,
|
||||
description,
|
||||
metric,
|
||||
trend: trendMetric,
|
||||
mode,
|
||||
})
|
||||
case "bar":
|
||||
return renderBarChart({
|
||||
title: resolvedTitle,
|
||||
description,
|
||||
metric,
|
||||
config,
|
||||
})
|
||||
case "line":
|
||||
return renderLineChart({
|
||||
title: resolvedTitle,
|
||||
description,
|
||||
metric,
|
||||
config,
|
||||
})
|
||||
case "area":
|
||||
return renderAreaChart({
|
||||
title: resolvedTitle,
|
||||
description,
|
||||
metric,
|
||||
config,
|
||||
})
|
||||
case "pie":
|
||||
return renderPieChart({
|
||||
title: resolvedTitle,
|
||||
description,
|
||||
metric,
|
||||
config,
|
||||
})
|
||||
case "radar":
|
||||
return renderRadarChart({
|
||||
title: resolvedTitle,
|
||||
description,
|
||||
metric,
|
||||
config,
|
||||
})
|
||||
case "gauge":
|
||||
return renderGauge({
|
||||
title: resolvedTitle,
|
||||
description,
|
||||
metric,
|
||||
config,
|
||||
})
|
||||
case "table":
|
||||
return renderTable({
|
||||
title: resolvedTitle,
|
||||
description,
|
||||
metric,
|
||||
config,
|
||||
isLoading,
|
||||
})
|
||||
case "text":
|
||||
default:
|
||||
return renderText({
|
||||
title: resolvedTitle,
|
||||
description,
|
||||
content: config.content ?? "",
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
type WidgetCardProps = {
|
||||
title: string
|
||||
description?: string
|
||||
children: React.ReactNode
|
||||
isLoading?: boolean
|
||||
}
|
||||
|
||||
function WidgetCard({ title, description, children, isLoading }: WidgetCardProps) {
|
||||
return (
|
||||
<Card className="h-full">
|
||||
<CardHeader className="pb-2">
|
||||
<CardTitle className="text-base font-semibold">{title}</CardTitle>
|
||||
{description ? <CardDescription>{description}</CardDescription> : null}
|
||||
</CardHeader>
|
||||
<CardContent className="pt-0">
|
||||
{isLoading ? <Skeleton className="h-[220px] w-full rounded-lg" /> : children}
|
||||
</CardContent>
|
||||
</Card>
|
||||
)
|
||||
}
|
||||
|
||||
function renderKpi({
|
||||
title,
|
||||
description,
|
||||
metric,
|
||||
trend,
|
||||
mode,
|
||||
}: {
|
||||
title: string
|
||||
description?: string
|
||||
metric: MetricResult
|
||||
trend: MetricResult
|
||||
mode: "edit" | "view" | "tv" | "print"
|
||||
}) {
|
||||
const data = metric.data as { value?: number; atRisk?: number } | null
|
||||
const value = parseNumeric(data?.value) ?? 0
|
||||
const atRisk = parseNumeric(data?.atRisk) ?? 0
|
||||
const trendValue = parseNumeric((trend.data as { value?: number } | null)?.value)
|
||||
const delta = trendValue !== null ? value - trendValue : null
|
||||
const isTv = mode === "tv"
|
||||
return (
|
||||
<Card className={cn("h-full bg-gradient-to-br", isTv ? "from-primary/5 to-primary/10" : "from-muted/50 to-muted/30")}>
|
||||
<CardHeader className="pb-1">
|
||||
<CardDescription className="text-xs uppercase tracking-wide text-muted-foreground">
|
||||
{description ?? "Indicador chave"}
|
||||
</CardDescription>
|
||||
<CardTitle className={cn("text-2xl font-semibold", isTv ? "text-4xl" : "")}>{title}</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-3">
|
||||
<div className={cn("font-semibold text-4xl", isTv ? "text-6xl" : "text-4xl")}>{numberFormatter.format(value)}</div>
|
||||
<div className="flex flex-wrap items-center gap-2 text-sm text-muted-foreground">
|
||||
<Badge variant={atRisk > 0 ? "destructive" : "outline"} className="rounded-full px-3 py-1 text-xs">
|
||||
{atRisk > 0 ? `${numberFormatter.format(atRisk)} em risco` : "Todos no prazo"}
|
||||
</Badge>
|
||||
{delta !== null ? (
|
||||
<span className={cn("font-medium", delta >= 0 ? "text-emerald-600" : "text-destructive")}>
|
||||
{delta >= 0 ? "+" : ""}
|
||||
{numberFormatter.format(delta)} vs período anterior
|
||||
</span>
|
||||
) : null}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)
|
||||
}
|
||||
|
||||
function renderBarChart({
|
||||
title,
|
||||
description,
|
||||
metric,
|
||||
config,
|
||||
}: {
|
||||
title: string
|
||||
description?: string
|
||||
metric: MetricResult
|
||||
config: WidgetConfig
|
||||
}) {
|
||||
const xKey = config.encoding?.x ?? "date"
|
||||
const series = Array.isArray(config.encoding?.y) ? config.encoding?.y ?? [] : []
|
||||
const chartData = Array.isArray(metric.data) ? (metric.data as Array<Record<string, unknown>>) : []
|
||||
const chartConfig = series.reduce<Record<string, { label?: string; color?: string }>>((acc, serie, index) => {
|
||||
acc[serie.field] = {
|
||||
label: serie.label ?? serie.field,
|
||||
color: CHART_COLORS[index % CHART_COLORS.length],
|
||||
}
|
||||
return acc
|
||||
}, {})
|
||||
|
||||
return (
|
||||
<WidgetCard title={title} description={description} isLoading={metric.isLoading}>
|
||||
{chartData.length === 0 ? (
|
||||
<EmptyState />
|
||||
) : (
|
||||
<ChartContainer config={chartConfig as ChartConfig} className="h-[260px] w-full">
|
||||
<BarChart data={chartData}>
|
||||
<CartesianGrid vertical={false} strokeDasharray="3 3" />
|
||||
<XAxis
|
||||
dataKey={xKey}
|
||||
tickLine={false}
|
||||
axisLine={false}
|
||||
tickMargin={8}
|
||||
minTickGap={24}
|
||||
tickFormatter={formatDateLabel}
|
||||
/>
|
||||
<YAxis allowDecimals={false} />
|
||||
<ChartTooltip content={<ChartTooltipContent />} />
|
||||
{series.map((serie, index) => (
|
||||
<Bar
|
||||
key={serie.field}
|
||||
dataKey={serie.field}
|
||||
fill={`var(--color-${serie.field})`}
|
||||
radius={6}
|
||||
stackId={config.encoding?.stacked ? "stack" : undefined}
|
||||
animationDuration={400}
|
||||
/>
|
||||
))}
|
||||
</BarChart>
|
||||
</ChartContainer>
|
||||
)}
|
||||
</WidgetCard>
|
||||
)
|
||||
}
|
||||
|
||||
function renderLineChart({
|
||||
title,
|
||||
description,
|
||||
metric,
|
||||
config,
|
||||
}: {
|
||||
title: string
|
||||
description?: string
|
||||
metric: MetricResult
|
||||
config: WidgetConfig
|
||||
}) {
|
||||
const xKey = config.encoding?.x ?? "date"
|
||||
const series = Array.isArray(config.encoding?.y) ? config.encoding?.y ?? [] : []
|
||||
const chartData = Array.isArray(metric.data) ? (metric.data as Array<Record<string, unknown>>) : []
|
||||
const chartConfig = series.reduce<Record<string, { label?: string; color?: string }>>((acc, serie, index) => {
|
||||
acc[serie.field] = {
|
||||
label: serie.label ?? serie.field,
|
||||
color: CHART_COLORS[index % CHART_COLORS.length],
|
||||
}
|
||||
return acc
|
||||
}, {})
|
||||
|
||||
return (
|
||||
<WidgetCard title={title} description={description} isLoading={metric.isLoading}>
|
||||
{chartData.length === 0 ? (
|
||||
<EmptyState />
|
||||
) : (
|
||||
<ChartContainer config={chartConfig as ChartConfig} className="h-[260px] w-full">
|
||||
<LineChart data={chartData}>
|
||||
<CartesianGrid strokeDasharray="3 3" />
|
||||
<XAxis dataKey={xKey} tickFormatter={formatDateLabel} />
|
||||
<YAxis allowDecimals />
|
||||
<ChartTooltip content={<ChartTooltipContent />} />
|
||||
<ChartLegend content={<ChartLegendContent />} />
|
||||
{series.map((serie, index) => (
|
||||
<Line
|
||||
key={serie.field}
|
||||
type="monotone"
|
||||
dataKey={serie.field}
|
||||
stroke={`var(--color-${serie.field})`}
|
||||
strokeWidth={2}
|
||||
dot={{ r: 3 }}
|
||||
animationDuration={400}
|
||||
/>
|
||||
))}
|
||||
</LineChart>
|
||||
</ChartContainer>
|
||||
)}
|
||||
</WidgetCard>
|
||||
)
|
||||
}
|
||||
|
||||
function renderAreaChart({
|
||||
title,
|
||||
description,
|
||||
metric,
|
||||
config,
|
||||
}: {
|
||||
title: string
|
||||
description?: string
|
||||
metric: MetricResult
|
||||
config: WidgetConfig
|
||||
}) {
|
||||
const xKey = config.encoding?.x ?? "date"
|
||||
const series = Array.isArray(config.encoding?.y) ? config.encoding?.y ?? [] : []
|
||||
const chartData = Array.isArray(metric.data) ? (metric.data as Array<Record<string, unknown>>) : []
|
||||
const stacked = Boolean(config.encoding?.stacked)
|
||||
const chartConfig = series.reduce<Record<string, { label?: string; color?: string }>>((acc, serie, index) => {
|
||||
acc[serie.field] = {
|
||||
label: serie.label ?? serie.field,
|
||||
color: CHART_COLORS[index % CHART_COLORS.length],
|
||||
}
|
||||
return acc
|
||||
}, {})
|
||||
|
||||
return (
|
||||
<WidgetCard title={title} description={description} isLoading={metric.isLoading}>
|
||||
{chartData.length === 0 ? (
|
||||
<EmptyState />
|
||||
) : (
|
||||
<ChartContainer config={chartConfig as ChartConfig} className="h-[260px] w-full">
|
||||
<AreaChart data={chartData}>
|
||||
<defs>
|
||||
{series.map((serie, index) => (
|
||||
<linearGradient key={serie.field} id={`fill-${serie.field}`} x1="0" y1="0" x2="0" y2="1">
|
||||
<stop offset="5%" stopColor={`var(--color-${serie.field})`} stopOpacity={0.8} />
|
||||
<stop offset="95%" stopColor={`var(--color-${serie.field})`} stopOpacity={0.1} />
|
||||
</linearGradient>
|
||||
))}
|
||||
</defs>
|
||||
<CartesianGrid vertical={false} strokeDasharray="3 3" />
|
||||
<XAxis dataKey={xKey} tickFormatter={formatDateLabel} />
|
||||
<YAxis />
|
||||
<ChartTooltip content={<ChartTooltipContent />} />
|
||||
<ChartLegend content={<ChartLegendContent />} />
|
||||
{series.map((serie, index) => (
|
||||
<Area
|
||||
key={serie.field}
|
||||
type="natural"
|
||||
dataKey={serie.field}
|
||||
fill={`url(#fill-${serie.field})`}
|
||||
stroke={`var(--color-${serie.field})`}
|
||||
stackId={stacked ? "stack" : undefined}
|
||||
strokeWidth={2}
|
||||
animationDuration={400}
|
||||
/>
|
||||
))}
|
||||
</AreaChart>
|
||||
</ChartContainer>
|
||||
)}
|
||||
</WidgetCard>
|
||||
)
|
||||
}
|
||||
|
||||
function renderPieChart({
|
||||
title,
|
||||
description,
|
||||
metric,
|
||||
config,
|
||||
}: {
|
||||
title: string
|
||||
description?: string
|
||||
metric: MetricResult
|
||||
config: WidgetConfig
|
||||
}) {
|
||||
const categoryKey = config.encoding?.category ?? "name"
|
||||
const valueKey = config.encoding?.value ?? "value"
|
||||
const chartData = Array.isArray(metric.data) ? (metric.data as Array<Record<string, unknown>>) : []
|
||||
return (
|
||||
<WidgetCard title={title} description={description} isLoading={metric.isLoading}>
|
||||
{chartData.length === 0 ? (
|
||||
<EmptyState />
|
||||
) : (
|
||||
<ChartContainer
|
||||
config={chartData.reduce<Record<string, { label?: string; color?: string }>>((acc, item, index) => {
|
||||
const key = String(item[categoryKey] ?? index)
|
||||
acc[key] = { label: key, color: CHART_COLORS[index % CHART_COLORS.length] }
|
||||
return acc
|
||||
}, {}) as ChartConfig}
|
||||
className="mx-auto aspect-square max-h-[240px]"
|
||||
>
|
||||
<PieChart>
|
||||
<ChartTooltip content={<ChartTooltipContent hideLabel />} />
|
||||
<Pie
|
||||
data={chartData}
|
||||
dataKey={valueKey}
|
||||
nameKey={categoryKey}
|
||||
innerRadius={55}
|
||||
outerRadius={110}
|
||||
strokeWidth={5}
|
||||
>
|
||||
{chartData.map((entry, index) => (
|
||||
<Cell key={index} fill={CHART_COLORS[index % CHART_COLORS.length]} />
|
||||
))}
|
||||
</Pie>
|
||||
</PieChart>
|
||||
</ChartContainer>
|
||||
)}
|
||||
</WidgetCard>
|
||||
)
|
||||
}
|
||||
|
||||
function renderRadarChart({
|
||||
title,
|
||||
description,
|
||||
metric,
|
||||
config,
|
||||
}: {
|
||||
title: string
|
||||
description?: string
|
||||
metric: MetricResult
|
||||
config: WidgetConfig
|
||||
}) {
|
||||
const angleKey = config.encoding?.angle ?? "label"
|
||||
const radiusKey = config.encoding?.radius ?? "value"
|
||||
const chartData = Array.isArray(metric.data) ? (metric.data as Array<Record<string, unknown>>) : []
|
||||
return (
|
||||
<WidgetCard title={title} description={description} isLoading={metric.isLoading}>
|
||||
{chartData.length === 0 ? (
|
||||
<EmptyState />
|
||||
) : (
|
||||
<ChartContainer
|
||||
config={{ [radiusKey]: { label: radiusKey, color: "var(--chart-1)" } }}
|
||||
className="mx-auto aspect-square max-h-[260px]"
|
||||
>
|
||||
<RadarChart data={chartData}>
|
||||
<PolarGrid />
|
||||
<PolarAngleAxis dataKey={angleKey} />
|
||||
<PolarRadiusAxis />
|
||||
<ChartTooltip content={<ChartTooltipContent />} />
|
||||
<Radar
|
||||
dataKey={radiusKey}
|
||||
stroke="var(--chart-1)"
|
||||
fill="var(--chart-1)"
|
||||
fillOpacity={0.4}
|
||||
/>
|
||||
</RadarChart>
|
||||
</ChartContainer>
|
||||
)}
|
||||
</WidgetCard>
|
||||
)
|
||||
}
|
||||
|
||||
function renderGauge({
|
||||
title,
|
||||
description,
|
||||
metric,
|
||||
config,
|
||||
}: {
|
||||
title: string
|
||||
description?: string
|
||||
metric: MetricResult
|
||||
config: WidgetConfig
|
||||
}) {
|
||||
const raw = metric.data as { value?: number; total?: number; resolved?: number } | null
|
||||
const value = parseNumeric(raw?.value) ?? 0
|
||||
const display = Math.max(0, Math.min(1, value))
|
||||
return (
|
||||
<WidgetCard title={title} description={description} isLoading={metric.isLoading}>
|
||||
<ChartContainer
|
||||
config={{ value: { label: "SLA", color: "var(--chart-1)" } }}
|
||||
className="mx-auto aspect-square max-h-[240px]"
|
||||
>
|
||||
<RadialBarChart
|
||||
startAngle={180}
|
||||
endAngle={0}
|
||||
innerRadius={60}
|
||||
outerRadius={110}
|
||||
data={[{ name: "SLA", value: display }]}
|
||||
>
|
||||
<RadialBar
|
||||
minAngle={15}
|
||||
background
|
||||
dataKey="value"
|
||||
cornerRadius={5}
|
||||
fill="var(--color-value)"
|
||||
/>
|
||||
<RechartsTooltip
|
||||
cursor={false}
|
||||
content={<ChartTooltipContent hideLabel valueFormatter={(val) => percentFormatter.format(Number(val ?? 0))} />}
|
||||
/>
|
||||
<Label
|
||||
content={({ viewBox }) => {
|
||||
if (!viewBox || !("cx" in viewBox) || !("cy" in viewBox)) return null
|
||||
return (
|
||||
<text x={viewBox.cx} y={viewBox.cy} textAnchor="middle" dominantBaseline="middle">
|
||||
<tspan x={viewBox.cx} y={(viewBox.cy ?? 0) - 8} className="fill-foreground text-3xl font-semibold">
|
||||
{percentFormatter.format(display)}
|
||||
</tspan>
|
||||
<tspan x={viewBox.cx} y={(viewBox.cy ?? 0) + 16} className="fill-muted-foreground text-sm">
|
||||
Cumprimento
|
||||
</tspan>
|
||||
</text>
|
||||
)
|
||||
}}
|
||||
/>
|
||||
</RadialBarChart>
|
||||
</ChartContainer>
|
||||
</WidgetCard>
|
||||
)
|
||||
}
|
||||
|
||||
function renderTable({
|
||||
title,
|
||||
description,
|
||||
metric,
|
||||
config,
|
||||
isLoading,
|
||||
}: {
|
||||
title: string
|
||||
description?: string
|
||||
metric: MetricResult
|
||||
config: WidgetConfig
|
||||
isLoading: boolean
|
||||
}) {
|
||||
const columns = Array.isArray(config.columns) && config.columns.length > 0
|
||||
? config.columns
|
||||
: [
|
||||
{ field: "subject", label: "Assunto" },
|
||||
{ field: "status", label: "Status" },
|
||||
{ field: "updatedAt", label: "Atualizado em" },
|
||||
]
|
||||
const rows = Array.isArray(metric.data) ? (metric.data as Array<Record<string, unknown>>) : []
|
||||
return (
|
||||
<WidgetCard title={title} description={description} isLoading={isLoading}>
|
||||
{rows.length === 0 ? (
|
||||
<EmptyState />
|
||||
) : (
|
||||
<div className="overflow-hidden rounded-lg border border-border/60">
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
{columns.map((column) => (
|
||||
<TableHead key={column.field}>{column.label}</TableHead>
|
||||
))}
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{rows.map((row, index) => (
|
||||
<TableRow key={index}>
|
||||
{columns.map((column) => (
|
||||
<TableCell key={column.field}>
|
||||
{renderTableCellValue(row[column.field as keyof typeof row])}
|
||||
</TableCell>
|
||||
))}
|
||||
</TableRow>
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</div>
|
||||
)}
|
||||
</WidgetCard>
|
||||
)
|
||||
}
|
||||
|
||||
function renderTableCellValue(value: unknown) {
|
||||
if (typeof value === "number") {
|
||||
return numberFormatter.format(value)
|
||||
}
|
||||
if (typeof value === "string") {
|
||||
if (/^\d{4}-\d{2}-\d{2}T/.test(value) || /^\d+$/.test(value)) {
|
||||
const date = new Date(value)
|
||||
if (!Number.isNaN(date.getTime())) {
|
||||
return format(date, "dd/MM/yyyy HH:mm", { locale: ptBR })
|
||||
}
|
||||
}
|
||||
return value
|
||||
}
|
||||
if (value === null || value === undefined) {
|
||||
return "—"
|
||||
}
|
||||
if (typeof value === "boolean") {
|
||||
return value ? "Sim" : "Não"
|
||||
}
|
||||
if (Array.isArray(value)) {
|
||||
return value.join(", ")
|
||||
}
|
||||
if (typeof value === "object") {
|
||||
try {
|
||||
return JSON.stringify(value)
|
||||
} catch {
|
||||
return "—"
|
||||
}
|
||||
}
|
||||
return String(value)
|
||||
}
|
||||
|
||||
function renderText({
|
||||
title,
|
||||
description,
|
||||
content,
|
||||
}: {
|
||||
title: string
|
||||
description?: string
|
||||
content: string
|
||||
}) {
|
||||
const sanitized = sanitizeHtml(content, {
|
||||
allowedTags: ["b", "i", "strong", "em", "u", "p", "br", "ul", "ol", "li", "span"],
|
||||
allowedAttributes: { span: ["style"] },
|
||||
})
|
||||
return (
|
||||
<Card className="h-full">
|
||||
<CardHeader>
|
||||
<CardTitle>{title}</CardTitle>
|
||||
{description ? <CardDescription>{description}</CardDescription> : null}
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div
|
||||
className="prose max-w-none text-sm leading-relaxed text-muted-foreground [&_ul]:list-disc [&_ol]:list-decimal"
|
||||
dangerouslySetInnerHTML={{ __html: sanitized || "<p>Adicione conteúdo informativo para contextualizar os dados.</p>" }}
|
||||
/>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)
|
||||
}
|
||||
|
||||
function EmptyState() {
|
||||
return (
|
||||
<div className="flex h-[220px] w-full flex-col items-center justify-center rounded-lg border border-dashed border-border/60 text-sm text-muted-foreground">
|
||||
Sem dados para os filtros selecionados.
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export { useMetricData }
|
||||
Loading…
Add table
Add a link
Reference in a new issue