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

@ -14,6 +14,7 @@ import type * as bootstrap from "../bootstrap.js";
import type * as categories from "../categories.js"; import type * as categories from "../categories.js";
import type * as commentTemplates from "../commentTemplates.js"; import type * as commentTemplates from "../commentTemplates.js";
import type * as companies from "../companies.js"; import type * as companies from "../companies.js";
import type * as dashboards from "../dashboards.js";
import type * as crons from "../crons.js"; import type * as crons from "../crons.js";
import type * as deviceExportTemplates from "../deviceExportTemplates.js"; import type * as deviceExportTemplates from "../deviceExportTemplates.js";
import type * as deviceFields from "../deviceFields.js"; import type * as deviceFields from "../deviceFields.js";
@ -22,6 +23,7 @@ import type * as fields from "../fields.js";
import type * as files from "../files.js"; import type * as files from "../files.js";
import type * as invites from "../invites.js"; import type * as invites from "../invites.js";
import type * as machines from "../machines.js"; import type * as machines from "../machines.js";
import type * as metrics from "../metrics.js";
import type * as migrations from "../migrations.js"; import type * as migrations from "../migrations.js";
import type * as queues from "../queues.js"; import type * as queues from "../queues.js";
import type * as rbac from "../rbac.js"; import type * as rbac from "../rbac.js";
@ -56,6 +58,7 @@ declare const fullApi: ApiFromModules<{
categories: typeof categories; categories: typeof categories;
commentTemplates: typeof commentTemplates; commentTemplates: typeof commentTemplates;
companies: typeof companies; companies: typeof companies;
dashboards: typeof dashboards;
crons: typeof crons; crons: typeof crons;
deviceExportTemplates: typeof deviceExportTemplates; deviceExportTemplates: typeof deviceExportTemplates;
deviceFields: typeof deviceFields; deviceFields: typeof deviceFields;
@ -64,6 +67,7 @@ declare const fullApi: ApiFromModules<{
files: typeof files; files: typeof files;
invites: typeof invites; invites: typeof invites;
machines: typeof machines; machines: typeof machines;
metrics: typeof metrics;
migrations: typeof migrations; migrations: typeof migrations;
queues: typeof queues; queues: typeof queues;
rbac: typeof rbac; rbac: typeof rbac;

767
convex/dashboards.ts Normal file
View file

@ -0,0 +1,767 @@
import { ConvexError, v } from "convex/values"
import type { Doc, Id } from "./_generated/dataModel"
import { mutation, query } from "./_generated/server"
import { requireStaff } from "./rbac"
const WIDGET_TYPES = [
"kpi",
"bar",
"line",
"area",
"pie",
"radar",
"gauge",
"table",
"text",
] as const
type WidgetType = (typeof WIDGET_TYPES)[number]
const gridItemValidator = v.object({
i: v.string(),
x: v.number(),
y: v.number(),
w: v.number(),
h: v.number(),
minW: v.optional(v.number()),
minH: v.optional(v.number()),
static: v.optional(v.boolean()),
})
const widgetLayoutValidator = v.object({
x: v.number(),
y: v.number(),
w: v.number(),
h: v.number(),
minW: v.optional(v.number()),
minH: v.optional(v.number()),
static: v.optional(v.boolean()),
})
function assertWidgetType(type: string): asserts type is WidgetType {
if (!WIDGET_TYPES.includes(type as WidgetType)) {
throw new ConvexError(`Tipo de widget inválido: ${type}`)
}
}
function sanitizeTitle(input?: string | null): string | undefined {
if (!input) return undefined
const trimmed = input.trim()
return trimmed.length > 0 ? trimmed : undefined
}
function generateWidgetKey(dashboardId: Id<"dashboards">) {
const rand = Math.random().toString(36).slice(2, 8)
return `${dashboardId.toString().slice(-6)}-${rand}`
}
function normalizeWidgetConfig(type: WidgetType, config: unknown) {
if (config && typeof config === "object") {
return config
}
switch (type) {
case "kpi":
return {
type: "kpi",
title: "Novo KPI",
dataSource: { metricKey: "tickets.waiting_action_now" },
options: { trend: "tickets.waiting_action_last_7d" },
}
case "bar":
return {
type: "bar",
title: "Abertos x Resolvidos",
dataSource: { metricKey: "tickets.opened_resolved_by_day", params: { range: "30d" } },
encoding: {
x: "date",
y: [
{ field: "opened", label: "Abertos" },
{ field: "resolved", label: "Resolvidos" },
],
},
options: { legend: true },
}
case "line":
return {
type: "line",
title: "Resoluções por dia",
dataSource: { metricKey: "tickets.opened_resolved_by_day", params: { range: "30d" } },
encoding: {
x: "date",
y: [{ field: "resolved", label: "Resolvidos" }],
},
options: { legend: false },
}
case "area":
return {
type: "area",
title: "Volume acumulado",
dataSource: { metricKey: "tickets.opened_resolved_by_day", params: { range: "30d" } },
encoding: {
x: "date",
y: [
{ field: "opened", label: "Abertos" },
{ field: "resolved", label: "Resolvidos" },
],
stacked: true,
},
options: { legend: true },
}
case "pie":
return {
type: "pie",
title: "Backlog por prioridade",
dataSource: { metricKey: "tickets.open_by_priority", params: { range: "30d" } },
encoding: { category: "priority", value: "total" },
options: { legend: true },
}
case "radar":
return {
type: "radar",
title: "SLA por fila",
dataSource: { metricKey: "tickets.sla_compliance_by_queue", params: { range: "30d" } },
encoding: { angle: "queue", radius: "compliance" },
options: {},
}
case "gauge":
return {
type: "gauge",
title: "Cumprimento de SLA",
dataSource: { metricKey: "tickets.sla_rate", params: { range: "7d" } },
options: { min: 0, max: 1, thresholds: [0.5, 0.8] },
}
case "table":
return {
type: "table",
title: "Tickets recentes",
dataSource: { metricKey: "tickets.awaiting_table", params: { limit: 20 } },
columns: [
{ field: "reference", label: "Ref." },
{ field: "subject", label: "Assunto" },
{ field: "status", label: "Status" },
{ field: "priority", label: "Prioridade" },
{ field: "updatedAt", label: "Atualizado em" },
],
options: { downloadCSV: true },
}
case "text":
default:
return {
type: "text",
title: "Notas",
content: "Use este espaço para destacar insights ou orientações.",
}
}
}
function sanitizeDashboard(dashboard: Doc<"dashboards">) {
return {
id: dashboard._id,
tenantId: dashboard.tenantId,
name: dashboard.name,
description: dashboard.description ?? null,
aspectRatio: dashboard.aspectRatio ?? "16:9",
theme: dashboard.theme ?? "system",
filters: dashboard.filters ?? {},
layout: dashboard.layout ?? [],
sections: dashboard.sections ?? [],
tvIntervalSeconds: dashboard.tvIntervalSeconds ?? 30,
readySelector: dashboard.readySelector ?? null,
createdBy: dashboard.createdBy,
updatedBy: dashboard.updatedBy ?? null,
createdAt: dashboard.createdAt,
updatedAt: dashboard.updatedAt,
isArchived: dashboard.isArchived ?? false,
}
}
function normalizeOrder(index: number) {
return index >= 0 ? index : 0
}
export const list = query({
args: {
tenantId: v.string(),
viewerId: v.id("users"),
includeArchived: v.optional(v.boolean()),
},
handler: async (ctx, { tenantId, viewerId, includeArchived }) => {
await requireStaff(ctx, viewerId, tenantId)
const dashboards = await ctx.db
.query("dashboards")
.withIndex("by_tenant", (q) => q.eq("tenantId", tenantId))
.collect()
const filtered = (includeArchived ? dashboards : dashboards.filter((d) => !(d.isArchived ?? false))).sort(
(a, b) => b.updatedAt - a.updatedAt,
)
return Promise.all(
filtered.map(async (dashboard) => {
const widgets = await ctx.db
.query("dashboardWidgets")
.withIndex("by_dashboard", (q) => q.eq("dashboardId", dashboard._id))
.collect()
return {
...sanitizeDashboard(dashboard),
widgetsCount: widgets.length,
}
}),
)
},
})
export const get = query({
args: {
tenantId: v.string(),
viewerId: v.id("users"),
dashboardId: v.id("dashboards"),
},
handler: async (ctx, { tenantId, viewerId, dashboardId }) => {
await requireStaff(ctx, viewerId, tenantId)
const dashboard = await ctx.db.get(dashboardId)
if (!dashboard || dashboard.tenantId !== tenantId) {
throw new ConvexError("Dashboard não encontrado")
}
const widgets = await ctx.db
.query("dashboardWidgets")
.withIndex("by_dashboard_order", (q) => q.eq("dashboardId", dashboardId))
.collect()
widgets.sort((a, b) => a.order - b.order || a.createdAt - b.createdAt)
const shares = await ctx.db
.query("dashboardShares")
.withIndex("by_dashboard", (q) => q.eq("dashboardId", dashboardId))
.collect()
return {
dashboard: sanitizeDashboard(dashboard),
widgets: widgets.map((widget) => ({
id: widget._id,
dashboardId: widget.dashboardId,
widgetKey: widget.widgetKey,
title: widget.title ?? null,
type: widget.type,
config: widget.config,
layout: widget.layout ?? null,
order: widget.order,
isHidden: widget.isHidden ?? false,
createdAt: widget.createdAt,
updatedAt: widget.updatedAt,
})),
shares: shares.map((share) => ({
id: share._id,
audience: share.audience,
token: share.token ?? null,
expiresAt: share.expiresAt ?? null,
canEdit: share.canEdit,
createdBy: share.createdBy,
createdAt: share.createdAt,
lastAccessAt: share.lastAccessAt ?? null,
})),
}
},
})
export const create = mutation({
args: {
tenantId: v.string(),
actorId: v.id("users"),
name: v.string(),
description: v.optional(v.string()),
aspectRatio: v.optional(v.string()),
theme: v.optional(v.string()),
},
handler: async (ctx, { tenantId, actorId, name, description, aspectRatio, theme }) => {
await requireStaff(ctx, actorId, tenantId)
const trimmedName = name.trim()
if (trimmedName.length === 0) {
throw new ConvexError("Nome do dashboard inválido")
}
const now = Date.now()
const dashboardId = await ctx.db.insert("dashboards", {
tenantId,
name: trimmedName,
description: sanitizeTitle(description),
aspectRatio: aspectRatio?.trim() || "16:9",
theme: theme?.trim() || "system",
filters: {},
layout: [],
sections: [],
tvIntervalSeconds: 30,
readySelector: "[data-dashboard-ready=true]",
createdBy: actorId,
updatedBy: actorId,
createdAt: now,
updatedAt: now,
isArchived: false,
})
return { id: dashboardId }
},
})
export const updateMetadata = mutation({
args: {
tenantId: v.string(),
actorId: v.id("users"),
dashboardId: v.id("dashboards"),
name: v.optional(v.string()),
description: v.optional(v.string()),
aspectRatio: v.optional(v.string()),
theme: v.optional(v.string()),
readySelector: v.optional(v.string()),
tvIntervalSeconds: v.optional(v.number()),
},
handler: async (ctx, { tenantId, actorId, dashboardId, name, description, aspectRatio, theme, readySelector, tvIntervalSeconds }) => {
await requireStaff(ctx, actorId, tenantId)
const dashboard = await ctx.db.get(dashboardId)
if (!dashboard || dashboard.tenantId !== tenantId) {
throw new ConvexError("Dashboard não encontrado")
}
const patch: Partial<Doc<"dashboards">> = {}
if (typeof name === "string") {
const trimmed = name.trim()
if (!trimmed) throw new ConvexError("Nome do dashboard inválido")
patch.name = trimmed
}
if (typeof description !== "undefined") {
patch.description = sanitizeTitle(description)
}
if (typeof aspectRatio === "string") {
patch.aspectRatio = aspectRatio.trim() || "16:9"
}
if (typeof theme === "string") {
patch.theme = theme.trim() || "system"
}
if (typeof readySelector === "string") {
patch.readySelector = readySelector.trim() || "[data-dashboard-ready=true]"
}
if (typeof tvIntervalSeconds === "number" && Number.isFinite(tvIntervalSeconds) && tvIntervalSeconds > 0) {
patch.tvIntervalSeconds = Math.max(5, Math.round(tvIntervalSeconds))
}
patch.updatedAt = Date.now()
patch.updatedBy = actorId
await ctx.db.patch(dashboardId, patch)
return { ok: true }
},
})
export const updateFilters = mutation({
args: {
tenantId: v.string(),
actorId: v.id("users"),
dashboardId: v.id("dashboards"),
filters: v.any(),
},
handler: async (ctx, { tenantId, actorId, dashboardId, filters }) => {
await requireStaff(ctx, actorId, tenantId)
const dashboard = await ctx.db.get(dashboardId)
if (!dashboard || dashboard.tenantId !== tenantId) {
throw new ConvexError("Dashboard não encontrado")
}
await ctx.db.patch(dashboardId, {
filters,
updatedAt: Date.now(),
updatedBy: actorId,
})
return { ok: true }
},
})
export const updateSections = mutation({
args: {
tenantId: v.string(),
actorId: v.id("users"),
dashboardId: v.id("dashboards"),
sections: v.array(
v.object({
id: v.string(),
title: v.optional(v.string()),
description: v.optional(v.string()),
widgetKeys: v.array(v.string()),
durationSeconds: v.optional(v.number()),
}),
),
},
handler: async (ctx, { tenantId, actorId, dashboardId, sections }) => {
await requireStaff(ctx, actorId, tenantId)
const dashboard = await ctx.db.get(dashboardId)
if (!dashboard || dashboard.tenantId !== tenantId) {
throw new ConvexError("Dashboard não encontrado")
}
const normalized = sections.map((section) => ({
...section,
title: sanitizeTitle(section.title),
description: sanitizeTitle(section.description),
durationSeconds:
typeof section.durationSeconds === "number" && Number.isFinite(section.durationSeconds)
? Math.max(5, Math.round(section.durationSeconds))
: undefined,
}))
await ctx.db.patch(dashboardId, {
sections: normalized,
updatedAt: Date.now(),
updatedBy: actorId,
})
return { ok: true }
},
})
export const updateLayout = mutation({
args: {
tenantId: v.string(),
actorId: v.id("users"),
dashboardId: v.id("dashboards"),
layout: v.array(gridItemValidator),
},
handler: async (ctx, { tenantId, actorId, dashboardId, layout }) => {
await requireStaff(ctx, actorId, tenantId)
const dashboard = await ctx.db.get(dashboardId)
if (!dashboard || dashboard.tenantId !== tenantId) {
throw new ConvexError("Dashboard não encontrado")
}
const widgets = await ctx.db
.query("dashboardWidgets")
.withIndex("by_dashboard", (q) => q.eq("dashboardId", dashboardId))
.collect()
const byKey = new Map<string, Doc<"dashboardWidgets">>()
widgets.forEach((widget) => byKey.set(widget.widgetKey, widget))
const now = Date.now()
await ctx.db.patch(dashboardId, {
layout,
updatedAt: now,
updatedBy: actorId,
})
for (let index = 0; index < layout.length; index++) {
const item = layout[index]
const widget = byKey.get(item.i)
if (!widget) {
throw new ConvexError(`Widget ${item.i} não encontrado neste dashboard`)
}
await ctx.db.patch(widget._id, {
layout: {
x: item.x,
y: item.y,
w: item.w,
h: item.h,
minW: item.minW,
minH: item.minH,
static: item.static,
},
order: normalizeOrder(index),
updatedAt: now,
updatedBy: actorId,
})
}
return { ok: true }
},
})
export const addWidget = mutation({
args: {
tenantId: v.string(),
actorId: v.id("users"),
dashboardId: v.id("dashboards"),
type: v.string(),
title: v.optional(v.string()),
config: v.optional(v.any()),
layout: v.optional(widgetLayoutValidator),
},
handler: async (ctx, { tenantId, actorId, dashboardId, type, title, config, layout }) => {
await requireStaff(ctx, actorId, tenantId)
const dashboard = await ctx.db.get(dashboardId)
if (!dashboard || dashboard.tenantId !== tenantId) {
throw new ConvexError("Dashboard não encontrado")
}
assertWidgetType(type)
const widgetKey = generateWidgetKey(dashboardId)
const now = Date.now()
const existingWidgets = await ctx.db
.query("dashboardWidgets")
.withIndex("by_dashboard", (q) => q.eq("dashboardId", dashboardId))
.collect()
const widgetId = await ctx.db.insert("dashboardWidgets", {
tenantId,
dashboardId,
widgetKey,
title: sanitizeTitle(title),
type,
config: normalizeWidgetConfig(type, config),
layout: layout ?? undefined,
order: existingWidgets.length,
createdBy: actorId,
updatedBy: actorId,
createdAt: now,
updatedAt: now,
isHidden: false,
})
const nextLayout = [...(dashboard.layout ?? [])]
if (layout) {
nextLayout.push({ i: widgetKey, ...layout })
} else {
const baseY = Math.max(0, nextLayout.length * 4)
nextLayout.push({ i: widgetKey, x: 0, y: baseY, w: 6, h: 6 })
}
await ctx.db.patch(dashboardId, {
layout: nextLayout,
updatedAt: now,
updatedBy: actorId,
})
return { id: widgetId, widgetKey }
},
})
export const updateWidget = mutation({
args: {
tenantId: v.string(),
actorId: v.id("users"),
widgetId: v.id("dashboardWidgets"),
title: v.optional(v.string()),
type: v.optional(v.string()),
config: v.optional(v.any()),
layout: v.optional(widgetLayoutValidator),
hidden: v.optional(v.boolean()),
order: v.optional(v.number()),
},
handler: async (ctx, { tenantId, actorId, widgetId, title, type, config, layout, hidden, order }) => {
await requireStaff(ctx, actorId, tenantId)
const widget = await ctx.db.get(widgetId)
if (!widget || widget.tenantId !== tenantId) {
throw new ConvexError("Widget não encontrado")
}
const patch: Partial<Doc<"dashboardWidgets">> = {}
if (typeof title !== "undefined") {
patch.title = sanitizeTitle(title)
}
if (typeof type === "string") {
assertWidgetType(type)
patch.type = type
patch.config = normalizeWidgetConfig(type, config ?? widget.config)
} else if (typeof config !== "undefined") {
patch.config = config
}
if (typeof layout !== "undefined") {
patch.layout = layout
}
if (typeof hidden === "boolean") {
patch.isHidden = hidden
}
if (typeof order === "number" && Number.isFinite(order)) {
patch.order = Math.max(0, Math.round(order))
}
patch.updatedAt = Date.now()
patch.updatedBy = actorId
await ctx.db.patch(widgetId, patch)
return { ok: true }
},
})
export const duplicateWidget = mutation({
args: {
tenantId: v.string(),
actorId: v.id("users"),
widgetId: v.id("dashboardWidgets"),
},
handler: async (ctx, { tenantId, actorId, widgetId }) => {
await requireStaff(ctx, actorId, tenantId)
const widget = await ctx.db.get(widgetId)
if (!widget || widget.tenantId !== tenantId) {
throw new ConvexError("Widget não encontrado")
}
const dashboard = await ctx.db.get(widget.dashboardId)
if (!dashboard || dashboard.tenantId !== tenantId) {
throw new ConvexError("Dashboard não encontrado")
}
assertWidgetType(widget.type)
const now = Date.now()
const widgetKey = generateWidgetKey(widget.dashboardId)
const newWidgetId = await ctx.db.insert("dashboardWidgets", {
tenantId,
dashboardId: widget.dashboardId,
widgetKey,
title: sanitizeTitle(widget.title),
type: widget.type,
config: widget.config,
layout: widget.layout ?? undefined,
order: widget.order + 1,
createdBy: actorId,
updatedBy: actorId,
createdAt: now,
updatedAt: now,
isHidden: widget.isHidden ?? false,
})
const duplicateLayout = widget.layout
? {
x: widget.layout.x,
y: (widget.layout.y ?? 0) + (widget.layout.h ?? 6) + 1,
w: widget.layout.w,
h: widget.layout.h ?? 6,
minW: widget.layout.minW,
minH: widget.layout.minH,
static: widget.layout.static,
}
: { x: 0, y: Math.max(0, (dashboard.layout?.length ?? 0) * 4), w: 6, h: 6 }
const nextLayout = [...(dashboard.layout ?? []), { i: widgetKey, ...duplicateLayout }]
await ctx.db.patch(dashboard._id, {
layout: nextLayout,
updatedAt: now,
updatedBy: actorId,
})
return { id: newWidgetId, widgetKey }
},
})
export const removeWidget = mutation({
args: {
tenantId: v.string(),
actorId: v.id("users"),
widgetId: v.id("dashboardWidgets"),
},
handler: async (ctx, { tenantId, actorId, widgetId }) => {
await requireStaff(ctx, actorId, tenantId)
const widget = await ctx.db.get(widgetId)
if (!widget || widget.tenantId !== tenantId) {
throw new ConvexError("Widget não encontrado")
}
const dashboard = await ctx.db.get(widget.dashboardId)
if (!dashboard || dashboard.tenantId !== tenantId) {
throw new ConvexError("Dashboard não encontrado")
}
await ctx.db.delete(widgetId)
const filteredLayout = (dashboard.layout ?? []).filter((item) => item.i !== widget.widgetKey)
await ctx.db.patch(dashboard._id, {
layout: filteredLayout,
updatedAt: Date.now(),
updatedBy: actorId,
})
return { ok: true }
},
})
export const archive = mutation({
args: {
tenantId: v.string(),
actorId: v.id("users"),
dashboardId: v.id("dashboards"),
archived: v.optional(v.boolean()),
},
handler: async (ctx, { tenantId, actorId, dashboardId, archived }) => {
await requireStaff(ctx, actorId, tenantId)
const dashboard = await ctx.db.get(dashboardId)
if (!dashboard || dashboard.tenantId !== tenantId) {
throw new ConvexError("Dashboard não encontrado")
}
await ctx.db.patch(dashboardId, {
isArchived: archived ?? !(dashboard.isArchived ?? false),
updatedAt: Date.now(),
updatedBy: actorId,
})
return { ok: true }
},
})
export const upsertShare = mutation({
args: {
tenantId: v.string(),
actorId: v.id("users"),
dashboardId: v.id("dashboards"),
audience: v.union(v.literal("private"), v.literal("tenant"), v.literal("public-link")),
canEdit: v.boolean(),
expiresAt: v.optional(v.union(v.number(), v.null())),
token: v.optional(v.union(v.string(), v.null())),
},
handler: async (ctx, { tenantId, actorId, dashboardId, audience, canEdit, expiresAt, token }) => {
await requireStaff(ctx, actorId, tenantId)
const dashboard = await ctx.db.get(dashboardId)
if (!dashboard || dashboard.tenantId !== tenantId) {
throw new ConvexError("Dashboard não encontrado")
}
const existingShares = await ctx.db
.query("dashboardShares")
.withIndex("by_dashboard", (q) => q.eq("dashboardId", dashboardId))
.collect()
const now = Date.now()
let shareDoc = existingShares.find((share) => share.audience === audience)
const normalizedExpiresAt =
typeof expiresAt === "number" && Number.isFinite(expiresAt) ? Math.max(now, Math.round(expiresAt)) : undefined
const normalizedToken = typeof token === "string" && token.trim().length > 0 ? token.trim() : undefined
if (!shareDoc) {
const generatedToken = audience === "public-link" ? normalizedToken ?? cryptoToken() : undefined
await ctx.db.insert("dashboardShares", {
tenantId,
dashboardId,
audience,
token: generatedToken,
canEdit,
expiresAt: normalizedExpiresAt,
createdBy: actorId,
createdAt: now,
lastAccessAt: undefined,
})
} else {
await ctx.db.patch(shareDoc._id, {
canEdit,
token: audience === "public-link" ? normalizedToken ?? shareDoc.token ?? cryptoToken() : undefined,
expiresAt: normalizedExpiresAt,
lastAccessAt: shareDoc.lastAccessAt,
})
}
await ctx.db.patch(dashboardId, { updatedAt: now, updatedBy: actorId })
return { ok: true }
},
})
export const revokeShareToken = mutation({
args: {
tenantId: v.string(),
actorId: v.id("users"),
dashboardId: v.id("dashboards"),
},
handler: async (ctx, { tenantId, actorId, dashboardId }) => {
await requireStaff(ctx, actorId, tenantId)
const shares = await ctx.db
.query("dashboardShares")
.withIndex("by_dashboard", (q) => q.eq("dashboardId", dashboardId))
.collect()
for (const share of shares) {
if (share.audience === "public-link") {
await ctx.db.patch(share._id, {
token: cryptoToken(),
lastAccessAt: undefined,
})
}
}
await ctx.db.patch(dashboardId, { updatedAt: Date.now(), updatedBy: actorId })
return { ok: true }
},
})
function cryptoToken() {
return Math.random().toString(36).slice(2, 10) + Math.random().toString(36).slice(2, 6)
}

469
convex/metrics.ts Normal file
View file

@ -0,0 +1,469 @@
import { v } from "convex/values"
import type { Id } from "./_generated/dataModel"
import { query } from "./_generated/server"
import {
OPEN_STATUSES,
ONE_DAY_MS,
fetchScopedTickets,
fetchScopedTicketsByCreatedRange,
fetchScopedTicketsByResolvedRange,
normalizeStatus,
} from "./reports"
import { requireStaff } from "./rbac"
type Viewer = Awaited<ReturnType<typeof requireStaff>>
type MetricResolverInput = {
tenantId: string
viewer: Viewer
viewerId: Id<"users">
params?: Record<string, unknown> | undefined
}
type MetricRunPayload = {
meta: { kind: string; key: string } & Record<string, unknown>
data: unknown
}
type MetricResolver = (ctx: Parameters<typeof query>[0], input: MetricResolverInput) => Promise<MetricRunPayload>
function parseRange(params?: Record<string, unknown>): number {
const value = params?.range
if (typeof value === "string") {
const normalized = value.toLowerCase()
if (normalized === "7d") return 7
if (normalized === "90d") return 90
}
if (typeof value === "number" && Number.isFinite(value) && value > 0) {
return Math.min(365, Math.max(1, Math.round(value)))
}
return 30
}
function parseLimit(params?: Record<string, unknown>, fallback = 20) {
const value = params?.limit
if (typeof value === "number" && Number.isFinite(value) && value > 0) {
return Math.min(200, Math.round(value))
}
return fallback
}
function parseCompanyId(params?: Record<string, unknown>): Id<"companies"> | undefined {
const value = params?.companyId
if (typeof value === "string" && value.length > 0) {
return value as Id<"companies">
}
return undefined
}
function parseQueueIds(params?: Record<string, unknown>): string[] | undefined {
const value = params?.queueIds ?? params?.queueId
if (Array.isArray(value)) {
const clean = value
.map((entry) => (typeof entry === "string" ? entry.trim() : null))
.filter((entry): entry is string => Boolean(entry && entry.length > 0))
return clean.length > 0 ? clean : undefined
}
if (typeof value === "string") {
const trimmed = value.trim()
return trimmed.length > 0 ? [trimmed] : undefined
}
return undefined
}
function filterTicketsByQueue<T extends { queueId?: Id<"queues"> | null }>(
tickets: T[],
queueIds?: string[],
): T[] {
if (!queueIds || queueIds.length === 0) {
return tickets
}
const normalized = new Set(queueIds.map((id) => id.trim()))
const includesNull = normalized.has("sem-fila") || normalized.has("null")
return tickets.filter((ticket) => {
if (!ticket.queueId) {
return includesNull
}
return normalized.has(String(ticket.queueId))
})
}
const metricResolvers: Record<string, MetricResolver> = {
"tickets.opened_resolved_by_day": async (ctx, { tenantId, viewer, params }) => {
const rangeDays = parseRange(params)
const companyId = parseCompanyId(params)
const queueIds = parseQueueIds(params)
const end = new Date()
end.setUTCHours(0, 0, 0, 0)
const endMs = end.getTime() + ONE_DAY_MS
const startMs = endMs - rangeDays * ONE_DAY_MS
const openedTickets = filterTicketsByQueue(
await fetchScopedTicketsByCreatedRange(ctx, tenantId, viewer, startMs, endMs, companyId),
queueIds,
)
const resolvedTickets = filterTicketsByQueue(
await fetchScopedTicketsByResolvedRange(ctx, tenantId, viewer, startMs, endMs, companyId),
queueIds,
)
const opened: Record<string, number> = {}
const resolved: Record<string, number> = {}
for (let offset = rangeDays - 1; offset >= 0; offset -= 1) {
const d = new Date(endMs - (offset + 1) * ONE_DAY_MS)
const key = formatDateKey(d.getTime())
opened[key] = 0
resolved[key] = 0
}
for (const ticket of openedTickets) {
if (ticket.createdAt >= startMs && ticket.createdAt < endMs) {
const key = formatDateKey(ticket.createdAt)
opened[key] = (opened[key] ?? 0) + 1
}
}
for (const ticket of resolvedTickets) {
if (typeof ticket.resolvedAt !== "number") continue
if (ticket.resolvedAt < startMs || ticket.resolvedAt >= endMs) continue
const key = formatDateKey(ticket.resolvedAt)
resolved[key] = (resolved[key] ?? 0) + 1
}
const series = []
for (let offset = rangeDays - 1; offset >= 0; offset -= 1) {
const d = new Date(endMs - (offset + 1) * ONE_DAY_MS)
const key = formatDateKey(d.getTime())
series.push({ date: key, opened: opened[key] ?? 0, resolved: resolved[key] ?? 0 })
}
return {
meta: { kind: "series", key: "tickets.opened_resolved_by_day", rangeDays },
data: series,
}
},
"tickets.waiting_action_now": async (ctx, { tenantId, viewer, params }) => {
const tickets = filterTicketsByQueue(await fetchScopedTickets(ctx, tenantId, viewer), parseQueueIds(params))
const now = Date.now()
let total = 0
let atRisk = 0
for (const ticket of tickets) {
const status = normalizeStatus(ticket.status)
if (!OPEN_STATUSES.has(status)) continue
total += 1
if (ticket.dueAt && ticket.dueAt < now) {
atRisk += 1
}
}
return {
meta: { kind: "single", key: "tickets.waiting_action_now", unit: "tickets" },
data: { value: total, atRisk },
}
},
"tickets.waiting_action_last_7d": async (ctx, { tenantId, viewer, params }) => {
const rangeDays = 7
const end = new Date()
end.setUTCHours(0, 0, 0, 0)
const endMs = end.getTime() + ONE_DAY_MS
const startMs = endMs - rangeDays * ONE_DAY_MS
const tickets = filterTicketsByQueue(await fetchScopedTickets(ctx, tenantId, viewer), parseQueueIds(params))
const daily: Record<string, { total: number; atRisk: number }> = {}
for (let offset = rangeDays - 1; offset >= 0; offset -= 1) {
const d = new Date(endMs - (offset + 1) * ONE_DAY_MS)
const key = formatDateKey(d.getTime())
daily[key] = { total: 0, atRisk: 0 }
}
for (const ticket of tickets) {
if (ticket.createdAt < startMs) continue
const key = formatDateKey(ticket.createdAt)
const bucket = daily[key]
if (!bucket) continue
if (OPEN_STATUSES.has(normalizeStatus(ticket.status))) {
bucket.total += 1
if (ticket.dueAt && ticket.dueAt < Date.now()) {
bucket.atRisk += 1
}
}
}
const values = Object.values(daily)
const total = values.reduce((sum, item) => sum + item.total, 0)
const atRisk = values.reduce((sum, item) => sum + item.atRisk, 0)
return {
meta: { kind: "single", key: "tickets.waiting_action_last_7d", aggregation: "sum", rangeDays },
data: { value: total, atRisk },
}
},
"tickets.open_by_priority": async (ctx, { tenantId, viewer, params }) => {
const rangeDays = parseRange(params)
const companyId = parseCompanyId(params)
const end = new Date()
end.setUTCHours(0, 0, 0, 0)
const endMs = end.getTime() + ONE_DAY_MS
const startMs = endMs - rangeDays * ONE_DAY_MS
const tickets = filterTicketsByQueue(
await fetchScopedTicketsByCreatedRange(ctx, tenantId, viewer, startMs, endMs, companyId),
parseQueueIds(params),
)
const counts: Record<string, number> = {}
for (const ticket of tickets) {
if (!OPEN_STATUSES.has(normalizeStatus(ticket.status))) continue
const key = (ticket.priority ?? "MEDIUM").toUpperCase()
counts[key] = (counts[key] ?? 0) + 1
}
const data = Object.entries(counts).map(([priority, total]) => ({ priority, total }))
data.sort((a, b) => b.total - a.total)
return {
meta: { kind: "collection", key: "tickets.open_by_priority", rangeDays },
data,
}
},
"tickets.open_by_queue": async (ctx, { tenantId, viewer, params }) => {
const rangeDays = parseRange(params)
const companyId = parseCompanyId(params)
const end = new Date()
end.setUTCHours(0, 0, 0, 0)
const endMs = end.getTime() + ONE_DAY_MS
const startMs = endMs - rangeDays * ONE_DAY_MS
const queueFilter = parseQueueIds(params)
const tickets = filterTicketsByQueue(
await fetchScopedTicketsByCreatedRange(ctx, tenantId, viewer, startMs, endMs, companyId),
parseQueueIds(params),
)
const queueCounts = new Map<string, number>()
for (const ticket of tickets) {
if (!OPEN_STATUSES.has(normalizeStatus(ticket.status))) continue
const queueKey = ticket.queueId ? String(ticket.queueId) : "sem-fila"
if (queueFilter && queueFilter.length > 0 && !queueFilter.includes(queueKey)) {
continue
}
queueCounts.set(queueKey, (queueCounts.get(queueKey) ?? 0) + 1)
}
const queues = await ctx.db.query("queues").withIndex("by_tenant", (q) => q.eq("tenantId", tenantId)).collect()
const data = Array.from(queueCounts.entries()).map(([queueId, total]) => {
const queue = queues.find((q) => String(q._id) === queueId)
return {
queueId,
name: queue ? queue.name : queueId === "sem-fila" ? "Sem fila" : "Fila desconhecida",
total,
}
})
data.sort((a, b) => b.total - a.total)
return {
meta: { kind: "collection", key: "tickets.open_by_queue", rangeDays },
data,
}
},
"tickets.sla_compliance_by_queue": async (ctx, { tenantId, viewer, params }) => {
const rangeDays = parseRange(params)
const companyId = parseCompanyId(params)
const end = new Date()
end.setUTCHours(0, 0, 0, 0)
const endMs = end.getTime() + ONE_DAY_MS
const startMs = endMs - rangeDays * ONE_DAY_MS
const queueFilter = parseQueueIds(params)
const tickets = await fetchScopedTicketsByCreatedRange(ctx, tenantId, viewer, startMs, endMs, companyId)
const now = Date.now()
const stats = new Map<string, { total: number; compliant: number }>()
for (const ticket of tickets) {
const queueKey = ticket.queueId ? String(ticket.queueId) : "sem-fila"
if (queueFilter && queueFilter.length > 0 && !queueFilter.includes(queueKey)) {
continue
}
const current = stats.get(queueKey) ?? { total: 0, compliant: 0 }
current.total += 1
const dueAt = typeof ticket.dueAt === "number" ? ticket.dueAt : null
const resolvedAt = typeof ticket.resolvedAt === "number" ? ticket.resolvedAt : null
let compliant = false
if (dueAt) {
if (resolvedAt) {
compliant = resolvedAt <= dueAt
} else {
compliant = dueAt >= now
}
} else {
compliant = resolvedAt !== null
}
if (compliant) {
current.compliant += 1
}
stats.set(queueKey, current)
}
const queues = await ctx.db.query("queues").withIndex("by_tenant", (q) => q.eq("tenantId", tenantId)).collect()
const data = Array.from(stats.entries()).map(([queueId, value]) => {
const queue = queues.find((q) => String(q._id) === queueId)
const compliance = value.total > 0 ? value.compliant / value.total : 0
return {
queueId,
name: queue ? queue.name : queueId === "sem-fila" ? "Sem fila" : "Fila desconhecida",
total: value.total,
compliance,
}
})
data.sort((a, b) => (b.compliance ?? 0) - (a.compliance ?? 0))
return {
meta: { kind: "collection", key: "tickets.sla_compliance_by_queue", rangeDays },
data,
}
},
"tickets.sla_rate": async (ctx, { tenantId, viewer, params }) => {
const rangeDays = parseRange(params)
const companyId = parseCompanyId(params)
const end = new Date()
end.setUTCHours(0, 0, 0, 0)
const endMs = end.getTime() + ONE_DAY_MS
const startMs = endMs - rangeDays * ONE_DAY_MS
const tickets = await fetchScopedTicketsByCreatedRange(ctx, tenantId, viewer, startMs, endMs, companyId)
const total = tickets.length
const resolved = tickets.filter((t) => normalizeStatus(t.status) === "RESOLVED").length
const rate = total > 0 ? resolved / total : 0
return {
meta: { kind: "single", key: "tickets.sla_rate", rangeDays, unit: "ratio" },
data: { value: rate, total, resolved },
}
},
"tickets.awaiting_table": async (ctx, { tenantId, viewer, params }) => {
const limit = parseLimit(params, 20)
const tickets = filterTicketsByQueue(await fetchScopedTickets(ctx, tenantId, viewer), parseQueueIds(params))
const awaiting = tickets
.filter((ticket) => OPEN_STATUSES.has(normalizeStatus(ticket.status)))
.sort((a, b) => (b.updatedAt ?? 0) - (a.updatedAt ?? 0))
.slice(0, limit)
.map((ticket) => ({
id: ticket._id,
reference: ticket.reference ?? null,
subject: ticket.subject,
status: normalizeStatus(ticket.status),
priority: ticket.priority,
updatedAt: ticket.updatedAt,
createdAt: ticket.createdAt,
assignee: ticket.assigneeSnapshot
? {
name: (ticket.assigneeSnapshot as { name?: string })?.name ?? null,
email: (ticket.assigneeSnapshot as { email?: string })?.email ?? null,
}
: null,
queueId: ticket.queueId ?? null,
}))
return {
meta: { kind: "table", key: "tickets.awaiting_table", limit },
data: awaiting,
}
},
"devices.health_summary": async (ctx, { tenantId, params }) => {
const limit = parseLimit(params, 10)
const machines = await ctx.db.query("machines").withIndex("by_tenant", (q) => q.eq("tenantId", tenantId)).collect()
const now = Date.now()
const summary = machines
.map((machine) => {
const lastHeartbeatAt = machine.lastHeartbeatAt ?? null
const minutesSinceHeartbeat = lastHeartbeatAt ? Math.round((now - lastHeartbeatAt) / 60000) : null
const status = deriveMachineStatus(machine, now)
const cpu = clampPercent(machine.cpuUsagePercent)
const memory = clampPercent(machine.memoryUsedPercent)
const disk = clampPercent(machine.diskUsedPercent ?? machine.diskUsagePercent)
const alerts = Array.isArray(machine.postureAlerts) ? machine.postureAlerts.length : machine.postureAlertsCount ?? 0
const attention =
(cpu ?? 0) > 85 ||
(memory ?? 0) > 90 ||
(disk ?? 0) > 90 ||
(minutesSinceHeartbeat ?? Infinity) > 120 ||
alerts > 0
return {
id: machine._id,
hostname: machine.hostname ?? machine.computerName ?? "Dispositivo sem nome",
status,
cpuUsagePercent: cpu,
memoryUsedPercent: memory,
diskUsedPercent: disk,
lastHeartbeatAt,
minutesSinceHeartbeat,
alerts,
attention,
}
})
.sort((a, b) => {
if (a.attention === b.attention) {
return (b.cpuUsagePercent ?? 0) - (a.cpuUsagePercent ?? 0)
}
return a.attention ? -1 : 1
})
.slice(0, limit)
return {
meta: { kind: "collection", key: "devices.health_summary", limit },
data: summary,
}
},
}
export const run = query({
args: {
tenantId: v.string(),
viewerId: v.id("users"),
metricKey: v.string(),
params: v.optional(v.any()),
},
handler: async (ctx, { tenantId, viewerId, metricKey, params }) => {
const viewer = await requireStaff(ctx, viewerId, tenantId)
const resolver = metricResolvers[metricKey]
if (!resolver) {
return {
meta: { kind: "error", key: metricKey, message: "Métrica não suportada" },
data: null,
}
}
const payload = await resolver(ctx, {
tenantId,
viewer,
viewerId,
params: params && typeof params === "object" ? (params as Record<string, unknown>) : undefined,
})
return payload
},
})
function formatDateKey(timestamp: number) {
const d = new Date(timestamp)
const year = d.getUTCFullYear()
const month = `${d.getUTCMonth() + 1}`.padStart(2, "0")
const day = `${d.getUTCDate()}`.padStart(2, "0")
return `${year}-${month}-${day}`
}
function deriveMachineStatus(machine: Record<string, unknown>, now: number) {
const lastHeartbeatAt = typeof machine.lastHeartbeatAt === "number" ? machine.lastHeartbeatAt : null
if (!lastHeartbeatAt) return "unknown"
const diffMinutes = (now - lastHeartbeatAt) / 60000
if (diffMinutes <= 10) return "online"
if (diffMinutes <= 120) return "stale"
return "offline"
}
function clampPercent(value: unknown) {
if (typeof value !== "number" || !Number.isFinite(value)) return null
if (value < 0) return 0
if (value > 100) return 100
return Math.round(value * 10) / 10
}

View file

@ -6,9 +6,9 @@ import type { Doc, Id } from "./_generated/dataModel";
import { requireStaff } from "./rbac"; import { requireStaff } from "./rbac";
import { getOfflineThresholdMs, getStaleThresholdMs } from "./machines"; import { getOfflineThresholdMs, getStaleThresholdMs } from "./machines";
type TicketStatusNormalized = "PENDING" | "AWAITING_ATTENDANCE" | "PAUSED" | "RESOLVED"; export type TicketStatusNormalized = "PENDING" | "AWAITING_ATTENDANCE" | "PAUSED" | "RESOLVED";
type QueryFilterBuilder = { lt: (field: unknown, value: number) => unknown; field: (name: string) => unknown }; type QueryFilterBuilder = { lt: (field: unknown, value: number) => unknown; field: (name: string) => unknown };
const STATUS_NORMALIZE_MAP: Record<string, TicketStatusNormalized> = { export const STATUS_NORMALIZE_MAP: Record<string, TicketStatusNormalized> = {
NEW: "PENDING", NEW: "PENDING",
PENDING: "PENDING", PENDING: "PENDING",
OPEN: "AWAITING_ATTENDANCE", OPEN: "AWAITING_ATTENDANCE",
@ -19,7 +19,7 @@ const STATUS_NORMALIZE_MAP: Record<string, TicketStatusNormalized> = {
CLOSED: "RESOLVED", CLOSED: "RESOLVED",
}; };
function normalizeStatus(status: string | null | undefined): TicketStatusNormalized { export function normalizeStatus(status: string | null | undefined): TicketStatusNormalized {
if (!status) return "PENDING"; if (!status) return "PENDING";
const normalized = STATUS_NORMALIZE_MAP[status.toUpperCase()]; const normalized = STATUS_NORMALIZE_MAP[status.toUpperCase()];
return normalized ?? "PENDING"; return normalized ?? "PENDING";
@ -30,8 +30,8 @@ function average(values: number[]) {
return values.reduce((sum, value) => sum + value, 0) / values.length; return values.reduce((sum, value) => sum + value, 0) / values.length;
} }
const OPEN_STATUSES = new Set<TicketStatusNormalized>(["PENDING", "AWAITING_ATTENDANCE", "PAUSED"]); export const OPEN_STATUSES = new Set<TicketStatusNormalized>(["PENDING", "AWAITING_ATTENDANCE", "PAUSED"]);
const ONE_DAY_MS = 24 * 60 * 60 * 1000; export const ONE_DAY_MS = 24 * 60 * 60 * 1000;
function percentageChange(current: number, previous: number) { function percentageChange(current: number, previous: number) {
if (previous === 0) { if (previous === 0) {
@ -88,14 +88,14 @@ function isNotNull<T>(value: T | null): value is T {
return value !== null; return value !== null;
} }
async function fetchTickets(ctx: QueryCtx, tenantId: string) { export async function fetchTickets(ctx: QueryCtx, tenantId: string) {
return ctx.db return ctx.db
.query("tickets") .query("tickets")
.withIndex("by_tenant", (q) => q.eq("tenantId", tenantId)) .withIndex("by_tenant", (q) => q.eq("tenantId", tenantId))
.collect(); .collect();
} }
async function fetchScopedTickets( export async function fetchScopedTickets(
ctx: QueryCtx, ctx: QueryCtx,
tenantId: string, tenantId: string,
viewer: Awaited<ReturnType<typeof requireStaff>>, viewer: Awaited<ReturnType<typeof requireStaff>>,
@ -114,7 +114,7 @@ async function fetchScopedTickets(
return fetchTickets(ctx, tenantId); return fetchTickets(ctx, tenantId);
} }
async function fetchScopedTicketsByCreatedRange( export async function fetchScopedTicketsByCreatedRange(
ctx: QueryCtx, ctx: QueryCtx,
tenantId: string, tenantId: string,
viewer: Awaited<ReturnType<typeof requireStaff>>, viewer: Awaited<ReturnType<typeof requireStaff>>,
@ -179,7 +179,7 @@ async function fetchScopedTicketsByCreatedRange(
); );
} }
async function fetchScopedTicketsByResolvedRange( export async function fetchScopedTicketsByResolvedRange(
ctx: QueryCtx, ctx: QueryCtx,
tenantId: string, tenantId: string,
viewer: Awaited<ReturnType<typeof requireStaff>>, viewer: Awaited<ReturnType<typeof requireStaff>>,

View file

@ -1,6 +1,35 @@
import { defineSchema, defineTable } from "convex/server"; import { defineSchema, defineTable } from "convex/server";
import { v } from "convex/values"; import { v } from "convex/values";
const gridLayoutItem = v.object({
i: v.string(),
x: v.number(),
y: v.number(),
w: v.number(),
h: v.number(),
minW: v.optional(v.number()),
minH: v.optional(v.number()),
static: v.optional(v.boolean()),
});
const widgetLayout = v.object({
x: v.number(),
y: v.number(),
w: v.number(),
h: v.number(),
minW: v.optional(v.number()),
minH: v.optional(v.number()),
static: v.optional(v.boolean()),
});
const tvSection = v.object({
id: v.string(),
title: v.optional(v.string()),
description: v.optional(v.string()),
widgetKeys: v.array(v.string()),
durationSeconds: v.optional(v.number()),
});
export default defineSchema({ export default defineSchema({
users: defineTable({ users: defineTable({
tenantId: v.string(), tenantId: v.string(),
@ -77,6 +106,77 @@ export default defineSchema({
.index("by_tenant_created", ["tenantId", "createdAt"]) .index("by_tenant_created", ["tenantId", "createdAt"])
.index("by_tenant", ["tenantId"]), .index("by_tenant", ["tenantId"]),
dashboards: defineTable({
tenantId: v.string(),
name: v.string(),
description: v.optional(v.string()),
aspectRatio: v.optional(v.string()),
theme: v.optional(v.string()),
filters: v.optional(v.any()),
layout: v.optional(v.array(gridLayoutItem)),
sections: v.optional(v.array(tvSection)),
tvIntervalSeconds: v.optional(v.number()),
readySelector: v.optional(v.string()),
createdBy: v.id("users"),
updatedBy: v.optional(v.id("users")),
createdAt: v.number(),
updatedAt: v.number(),
isArchived: v.optional(v.boolean()),
})
.index("by_tenant", ["tenantId"])
.index("by_tenant_created", ["tenantId", "createdAt"]),
dashboardWidgets: defineTable({
tenantId: v.string(),
dashboardId: v.id("dashboards"),
widgetKey: v.string(),
title: v.optional(v.string()),
type: v.string(),
config: v.any(),
layout: v.optional(widgetLayout),
order: v.number(),
createdBy: v.id("users"),
updatedBy: v.optional(v.id("users")),
createdAt: v.number(),
updatedAt: v.number(),
isHidden: v.optional(v.boolean()),
})
.index("by_dashboard", ["dashboardId"])
.index("by_dashboard_order", ["dashboardId", "order"])
.index("by_dashboard_key", ["dashboardId", "widgetKey"])
.index("by_tenant", ["tenantId"]),
metricDefinitions: defineTable({
tenantId: v.string(),
key: v.string(),
name: v.string(),
description: v.optional(v.string()),
version: v.number(),
definition: v.optional(v.any()),
createdBy: v.id("users"),
updatedBy: v.optional(v.id("users")),
createdAt: v.number(),
updatedAt: v.number(),
tags: v.optional(v.array(v.string())),
})
.index("by_tenant_key", ["tenantId", "key"])
.index("by_tenant", ["tenantId"]),
dashboardShares: defineTable({
tenantId: v.string(),
dashboardId: v.id("dashboards"),
audience: v.string(),
token: v.optional(v.string()),
expiresAt: v.optional(v.number()),
canEdit: v.boolean(),
createdBy: v.id("users"),
createdAt: v.number(),
lastAccessAt: v.optional(v.number()),
})
.index("by_dashboard", ["dashboardId"])
.index("by_token", ["token"])
.index("by_tenant", ["tenantId"]),
queues: defineTable({ queues: defineTable({
tenantId: v.string(), tenantId: v.string(),
name: v.string(), name: v.string(),

View file

@ -0,0 +1,77 @@
import { NextResponse } from "next/server"
export const runtime = "nodejs"
type ExportRequest = {
url?: string
width?: number
height?: number
format?: "pdf" | "png"
waitForSelector?: string
}
export async function POST(request: Request) {
let payload: ExportRequest
try {
payload = await request.json()
} catch (error) {
return NextResponse.json({ error: "Payload inválido" }, { status: 400 })
}
if (!payload.url) {
return NextResponse.json({ error: "URL obrigatória" }, { status: 400 })
}
const { chromium } = await import("playwright")
const width = payload.width ?? 1920
const height = payload.height ?? 1080
const format = payload.format ?? "pdf"
const waitForSelector = payload.waitForSelector ?? "[data-dashboard-ready='true']"
let browser: Awaited<ReturnType<typeof chromium.launch>> | null = null
try {
browser = await chromium.launch()
const page = await browser.newPage({ viewport: { width, height } })
await page.goto(payload.url, { waitUntil: "networkidle" })
if (waitForSelector) {
try {
await page.waitForSelector(waitForSelector, { timeout: 15000 })
} catch (error) {
console.warn("waitForSelector timeout", error)
}
}
if (format === "pdf") {
const pdf = await page.pdf({
width: `${width}px`,
height: `${height}px`,
printBackground: true,
pageRanges: "1",
})
return new NextResponse(pdf, {
status: 200,
headers: {
"Content-Type": "application/pdf",
"Content-Disposition": "attachment; filename=dashboard.pdf",
},
})
}
const screenshot = await page.screenshot({ type: "png", fullPage: true })
return new NextResponse(screenshot, {
status: 200,
headers: {
"Content-Type": "image/png",
"Content-Disposition": "attachment; filename=dashboard.png",
},
})
} catch (error) {
console.error("Failed to export dashboard", error)
return NextResponse.json({ error: "Falha ao exportar o dashboard" }, { status: 500 })
} finally {
if (browser) {
await browser.close()
}
}
}

View file

@ -0,0 +1,35 @@
import { AppShell } from "@/components/app-shell"
import { DashboardBuilder } from "@/components/dashboards/dashboard-builder"
import { SiteHeader } from "@/components/site-header"
import { requireStaffSession } from "@/lib/auth-server"
type PageProps = {
params: { id: string }
searchParams: { [key: string]: string | string[] | undefined }
}
export const dynamic = "force-dynamic"
export default async function DashboardDetailPage({ params, searchParams }: PageProps) {
await requireStaffSession()
const tvMode = searchParams?.tv === "1"
return (
<AppShell
header={
<SiteHeader
title="Construtor de dashboards"
lead="Monte relatórios interativos com filtros globais, exportação e modo TV."
/>
}
>
<div className="mx-auto w-full max-w-7xl px-4 pb-12 lg:px-6">
<DashboardBuilder
dashboardId={params.id}
editable={!tvMode}
mode={tvMode ? "tv" : "edit"}
/>
</div>
</AppShell>
)
}

View file

@ -0,0 +1,17 @@
import { DashboardBuilder } from "@/components/dashboards/dashboard-builder"
import { requireStaffSession } from "@/lib/auth-server"
type PageProps = {
params: { id: string }
}
export const dynamic = "force-dynamic"
export default async function DashboardPrintPage({ params }: PageProps) {
await requireStaffSession()
return (
<div className="min-h-screen bg-white p-6" data-dashboard-print>
<DashboardBuilder dashboardId={params.id} editable={false} mode="print" />
</div>
)
}

View file

@ -0,0 +1,24 @@
import { AppShell } from "@/components/app-shell"
import { DashboardListView } from "@/components/dashboards/dashboard-list"
import { SiteHeader } from "@/components/site-header"
import { requireStaffSession } from "@/lib/auth-server"
export const dynamic = "force-dynamic"
export default async function DashboardsPage() {
await requireStaffSession()
return (
<AppShell
header={
<SiteHeader
title="Dashboards"
lead="Monte relatórios personalizados com filtros compartilhados, exportação e modo TV."
/>
}
>
<div className="mx-auto w-full max-w-6xl px-4 pb-12 lg:px-6">
<DashboardListView />
</div>
</AppShell>
)
}

View file

@ -3,6 +3,7 @@
import * as React from "react" import * as React from "react"
import { import {
LayoutDashboard, LayoutDashboard,
LayoutTemplate,
LifeBuoy, LifeBuoy,
Ticket, Ticket,
PlayCircle, PlayCircle,
@ -83,6 +84,7 @@ const navigation: NavigationGroup[] = [
title: "Relatórios", title: "Relatórios",
requiredRole: "staff", requiredRole: "staff",
items: [ items: [
{ title: "Dashboards", url: "/dashboards", icon: LayoutTemplate, requiredRole: "staff" },
{ title: "Produtividade", url: "/reports/sla", icon: TrendingUp, requiredRole: "staff" }, { title: "Produtividade", url: "/reports/sla", icon: TrendingUp, requiredRole: "staff" },
{ title: "Qualidade (CSAT)", url: "/reports/csat", icon: LifeBuoy, requiredRole: "staff" }, { title: "Qualidade (CSAT)", url: "/reports/csat", icon: LifeBuoy, requiredRole: "staff" },
{ title: "Backlog", url: "/reports/backlog", icon: BarChart3, requiredRole: "staff" }, { title: "Backlog", url: "/reports/backlog", icon: BarChart3, requiredRole: "staff" },

File diff suppressed because it is too large Load diff

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

View 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>
)
}

View 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 }