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
4
convex/_generated/api.d.ts
vendored
4
convex/_generated/api.d.ts
vendored
|
|
@ -14,6 +14,7 @@ import type * as bootstrap from "../bootstrap.js";
|
|||
import type * as categories from "../categories.js";
|
||||
import type * as commentTemplates from "../commentTemplates.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 deviceExportTemplates from "../deviceExportTemplates.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 invites from "../invites.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 queues from "../queues.js";
|
||||
import type * as rbac from "../rbac.js";
|
||||
|
|
@ -56,6 +58,7 @@ declare const fullApi: ApiFromModules<{
|
|||
categories: typeof categories;
|
||||
commentTemplates: typeof commentTemplates;
|
||||
companies: typeof companies;
|
||||
dashboards: typeof dashboards;
|
||||
crons: typeof crons;
|
||||
deviceExportTemplates: typeof deviceExportTemplates;
|
||||
deviceFields: typeof deviceFields;
|
||||
|
|
@ -64,6 +67,7 @@ declare const fullApi: ApiFromModules<{
|
|||
files: typeof files;
|
||||
invites: typeof invites;
|
||||
machines: typeof machines;
|
||||
metrics: typeof metrics;
|
||||
migrations: typeof migrations;
|
||||
queues: typeof queues;
|
||||
rbac: typeof rbac;
|
||||
|
|
|
|||
767
convex/dashboards.ts
Normal file
767
convex/dashboards.ts
Normal 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
469
convex/metrics.ts
Normal 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
|
||||
}
|
||||
|
|
@ -6,9 +6,9 @@ import type { Doc, Id } from "./_generated/dataModel";
|
|||
import { requireStaff } from "./rbac";
|
||||
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 };
|
||||
const STATUS_NORMALIZE_MAP: Record<string, TicketStatusNormalized> = {
|
||||
export const STATUS_NORMALIZE_MAP: Record<string, TicketStatusNormalized> = {
|
||||
NEW: "PENDING",
|
||||
PENDING: "PENDING",
|
||||
OPEN: "AWAITING_ATTENDANCE",
|
||||
|
|
@ -19,7 +19,7 @@ const STATUS_NORMALIZE_MAP: Record<string, TicketStatusNormalized> = {
|
|||
CLOSED: "RESOLVED",
|
||||
};
|
||||
|
||||
function normalizeStatus(status: string | null | undefined): TicketStatusNormalized {
|
||||
export function normalizeStatus(status: string | null | undefined): TicketStatusNormalized {
|
||||
if (!status) return "PENDING";
|
||||
const normalized = STATUS_NORMALIZE_MAP[status.toUpperCase()];
|
||||
return normalized ?? "PENDING";
|
||||
|
|
@ -30,8 +30,8 @@ function average(values: number[]) {
|
|||
return values.reduce((sum, value) => sum + value, 0) / values.length;
|
||||
}
|
||||
|
||||
const OPEN_STATUSES = new Set<TicketStatusNormalized>(["PENDING", "AWAITING_ATTENDANCE", "PAUSED"]);
|
||||
const ONE_DAY_MS = 24 * 60 * 60 * 1000;
|
||||
export const OPEN_STATUSES = new Set<TicketStatusNormalized>(["PENDING", "AWAITING_ATTENDANCE", "PAUSED"]);
|
||||
export const ONE_DAY_MS = 24 * 60 * 60 * 1000;
|
||||
|
||||
function percentageChange(current: number, previous: number) {
|
||||
if (previous === 0) {
|
||||
|
|
@ -88,14 +88,14 @@ function isNotNull<T>(value: T | null): value is T {
|
|||
return value !== null;
|
||||
}
|
||||
|
||||
async function fetchTickets(ctx: QueryCtx, tenantId: string) {
|
||||
export async function fetchTickets(ctx: QueryCtx, tenantId: string) {
|
||||
return ctx.db
|
||||
.query("tickets")
|
||||
.withIndex("by_tenant", (q) => q.eq("tenantId", tenantId))
|
||||
.collect();
|
||||
}
|
||||
|
||||
async function fetchScopedTickets(
|
||||
export async function fetchScopedTickets(
|
||||
ctx: QueryCtx,
|
||||
tenantId: string,
|
||||
viewer: Awaited<ReturnType<typeof requireStaff>>,
|
||||
|
|
@ -114,7 +114,7 @@ async function fetchScopedTickets(
|
|||
return fetchTickets(ctx, tenantId);
|
||||
}
|
||||
|
||||
async function fetchScopedTicketsByCreatedRange(
|
||||
export async function fetchScopedTicketsByCreatedRange(
|
||||
ctx: QueryCtx,
|
||||
tenantId: string,
|
||||
viewer: Awaited<ReturnType<typeof requireStaff>>,
|
||||
|
|
@ -179,7 +179,7 @@ async function fetchScopedTicketsByCreatedRange(
|
|||
);
|
||||
}
|
||||
|
||||
async function fetchScopedTicketsByResolvedRange(
|
||||
export async function fetchScopedTicketsByResolvedRange(
|
||||
ctx: QueryCtx,
|
||||
tenantId: string,
|
||||
viewer: Awaited<ReturnType<typeof requireStaff>>,
|
||||
|
|
|
|||
100
convex/schema.ts
100
convex/schema.ts
|
|
@ -1,6 +1,35 @@
|
|||
import { defineSchema, defineTable } from "convex/server";
|
||||
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({
|
||||
users: defineTable({
|
||||
tenantId: v.string(),
|
||||
|
|
@ -77,6 +106,77 @@ export default defineSchema({
|
|||
.index("by_tenant_created", ["tenantId", "createdAt"])
|
||||
.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({
|
||||
tenantId: v.string(),
|
||||
name: v.string(),
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue