feat: CSV exports, PDF improvements, play internal/external with hour split, roles cleanup, admin companies with 'Cliente avulso', ticket list spacing/alignment fixes, status translations and mappings
This commit is contained in:
parent
addd4ce6e8
commit
3bafcc5a0a
45 changed files with 1401 additions and 256 deletions
113
src/app/api/reports/backlog.csv/route.ts
Normal file
113
src/app/api/reports/backlog.csv/route.ts
Normal file
|
|
@ -0,0 +1,113 @@
|
|||
import { NextResponse } from "next/server"
|
||||
import { ConvexHttpClient } from "convex/browser"
|
||||
|
||||
import { api } from "@/convex/_generated/api"
|
||||
import type { Id } from "@/convex/_generated/dataModel"
|
||||
import { env } from "@/lib/env"
|
||||
import { assertAuthenticatedSession } from "@/lib/auth-server"
|
||||
import { DEFAULT_TENANT_ID } from "@/lib/constants"
|
||||
|
||||
export const runtime = "nodejs"
|
||||
|
||||
function csvEscape(value: unknown): string {
|
||||
const s = value == null ? "" : String(value)
|
||||
if (/[",\n]/.test(s)) {
|
||||
return '"' + s.replace(/"/g, '""') + '"'
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
function rowsToCsv(rows: Array<Array<unknown>>): string {
|
||||
return rows.map((row) => row.map(csvEscape).join(",")).join("\n") + "\n"
|
||||
}
|
||||
|
||||
export async function GET(request: Request) {
|
||||
const session = await assertAuthenticatedSession()
|
||||
if (!session) {
|
||||
return NextResponse.json({ error: "Não autorizado" }, { status: 401 })
|
||||
}
|
||||
|
||||
const convexUrl = env.NEXT_PUBLIC_CONVEX_URL
|
||||
if (!convexUrl) {
|
||||
return NextResponse.json({ error: "Convex não configurado" }, { status: 500 })
|
||||
}
|
||||
|
||||
const client = new ConvexHttpClient(convexUrl)
|
||||
const tenantId = session.user.tenantId ?? DEFAULT_TENANT_ID
|
||||
|
||||
let viewerId: string | null = null
|
||||
try {
|
||||
const ensuredUser = await client.mutation(api.users.ensureUser, {
|
||||
tenantId,
|
||||
name: session.user.name ?? session.user.email,
|
||||
email: session.user.email,
|
||||
avatarUrl: session.user.avatarUrl ?? undefined,
|
||||
role: session.user.role.toUpperCase(),
|
||||
})
|
||||
viewerId = ensuredUser?._id ?? null
|
||||
} catch (error) {
|
||||
console.error("Failed to synchronize user with Convex for backlog CSV", error)
|
||||
return NextResponse.json({ error: "Falha ao sincronizar usuário com Convex" }, { status: 500 })
|
||||
}
|
||||
|
||||
if (!viewerId) {
|
||||
return NextResponse.json({ error: "Usuário não encontrado no Convex" }, { status: 403 })
|
||||
}
|
||||
|
||||
try {
|
||||
const { searchParams } = new URL(request.url)
|
||||
const range = searchParams.get("range") ?? undefined
|
||||
const report = await client.query(api.reports.backlogOverview, {
|
||||
tenantId,
|
||||
viewerId: viewerId as unknown as Id<"users">,
|
||||
range,
|
||||
})
|
||||
|
||||
const rows: Array<Array<unknown>> = []
|
||||
rows.push(["Relatório", "Backlog"])
|
||||
rows.push(["Período", report.rangeDays ? `Últimos ${report.rangeDays} dias` : "—"])
|
||||
rows.push([])
|
||||
rows.push(["Seção", "Chave", "Valor"]) // header
|
||||
|
||||
// Status
|
||||
const STATUS_PT: Record<string, string> = {
|
||||
PENDING: "Pendentes",
|
||||
AWAITING_ATTENDANCE: "Aguardando atendimento",
|
||||
PAUSED: "Pausados",
|
||||
RESOLVED: "Resolvidos",
|
||||
}
|
||||
for (const [status, total] of Object.entries(report.statusCounts)) {
|
||||
rows.push(["Status", STATUS_PT[status] ?? status, total])
|
||||
}
|
||||
|
||||
// Prioridade
|
||||
const PRIORITY_PT: Record<string, string> = {
|
||||
LOW: "Baixa",
|
||||
MEDIUM: "Média",
|
||||
HIGH: "Alta",
|
||||
URGENT: "Crítica",
|
||||
}
|
||||
for (const [priority, total] of Object.entries(report.priorityCounts)) {
|
||||
rows.push(["Prioridade", PRIORITY_PT[priority] ?? priority, total])
|
||||
}
|
||||
|
||||
// Filas
|
||||
for (const q of report.queueCounts) {
|
||||
rows.push(["Fila", q.name || q.id, q.total])
|
||||
}
|
||||
|
||||
rows.push(["Abertos", "Total", report.totalOpen])
|
||||
|
||||
const csv = rowsToCsv(rows)
|
||||
return new NextResponse(csv, {
|
||||
headers: {
|
||||
"Content-Type": "text/csv; charset=UTF-8",
|
||||
"Content-Disposition": `attachment; filename="backlog-${tenantId}-${report.rangeDays ?? 'all'}d.csv"`,
|
||||
"Cache-Control": "no-store",
|
||||
},
|
||||
})
|
||||
} catch (error) {
|
||||
console.error("Failed to generate backlog CSV", error)
|
||||
return NextResponse.json({ error: "Falha ao gerar CSV do backlog" }, { status: 500 })
|
||||
}
|
||||
}
|
||||
99
src/app/api/reports/csat.csv/route.ts
Normal file
99
src/app/api/reports/csat.csv/route.ts
Normal file
|
|
@ -0,0 +1,99 @@
|
|||
import { NextResponse } from "next/server"
|
||||
import { ConvexHttpClient } from "convex/browser"
|
||||
|
||||
import { api } from "@/convex/_generated/api"
|
||||
import type { Id } from "@/convex/_generated/dataModel"
|
||||
import { env } from "@/lib/env"
|
||||
import { assertAuthenticatedSession } from "@/lib/auth-server"
|
||||
import { DEFAULT_TENANT_ID } from "@/lib/constants"
|
||||
|
||||
export const runtime = "nodejs"
|
||||
|
||||
function csvEscape(value: unknown): string {
|
||||
const s = value == null ? "" : String(value)
|
||||
if (/[",\n]/.test(s)) {
|
||||
return '"' + s.replace(/"/g, '""') + '"'
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
function rowsToCsv(rows: Array<Array<unknown>>): string {
|
||||
return rows.map((row) => row.map(csvEscape).join(",")).join("\n") + "\n"
|
||||
}
|
||||
|
||||
export async function GET(request: Request) {
|
||||
const session = await assertAuthenticatedSession()
|
||||
if (!session) {
|
||||
return NextResponse.json({ error: "Não autorizado" }, { status: 401 })
|
||||
}
|
||||
|
||||
const convexUrl = env.NEXT_PUBLIC_CONVEX_URL
|
||||
if (!convexUrl) {
|
||||
return NextResponse.json({ error: "Convex não configurado" }, { status: 500 })
|
||||
}
|
||||
|
||||
const { searchParams } = new URL(request.url)
|
||||
const range = searchParams.get("range") ?? undefined
|
||||
|
||||
const client = new ConvexHttpClient(convexUrl)
|
||||
const tenantId = session.user.tenantId ?? DEFAULT_TENANT_ID
|
||||
|
||||
let viewerId: string | null = null
|
||||
try {
|
||||
const ensuredUser = await client.mutation(api.users.ensureUser, {
|
||||
tenantId,
|
||||
name: session.user.name ?? session.user.email,
|
||||
email: session.user.email,
|
||||
avatarUrl: session.user.avatarUrl ?? undefined,
|
||||
role: session.user.role.toUpperCase(),
|
||||
})
|
||||
viewerId = ensuredUser?._id ?? null
|
||||
} catch (error) {
|
||||
console.error("Failed to synchronize user with Convex for CSAT CSV", error)
|
||||
return NextResponse.json({ error: "Falha ao sincronizar usuário com Convex" }, { status: 500 })
|
||||
}
|
||||
|
||||
if (!viewerId) {
|
||||
return NextResponse.json({ error: "Usuário não encontrado no Convex" }, { status: 403 })
|
||||
}
|
||||
|
||||
try {
|
||||
const report = await client.query(api.reports.csatOverview, {
|
||||
tenantId,
|
||||
viewerId: viewerId as unknown as Id<"users">,
|
||||
range,
|
||||
})
|
||||
|
||||
const rows: Array<Array<unknown>> = []
|
||||
rows.push(["Relatório", "CSAT"])
|
||||
rows.push(["Período", report.rangeDays ? `Últimos ${report.rangeDays} dias` : (range ?? '90d')])
|
||||
rows.push([])
|
||||
rows.push(["Métrica", "Valor"]) // header
|
||||
rows.push(["CSAT médio", report.averageScore ?? "—"])
|
||||
rows.push(["Total de respostas", report.totalSurveys ?? 0])
|
||||
rows.push([])
|
||||
rows.push(["Distribuição", "Total"])
|
||||
for (const entry of report.distribution ?? []) {
|
||||
rows.push([`Nota ${entry.score}`, entry.total])
|
||||
}
|
||||
rows.push([])
|
||||
rows.push(["Recentes", "Nota", "Recebido em"])
|
||||
for (const item of report.recent ?? []) {
|
||||
const date = new Date(item.receivedAt).toISOString()
|
||||
rows.push([`#${item.reference}`, item.score, date])
|
||||
}
|
||||
|
||||
const csv = rowsToCsv(rows)
|
||||
return new NextResponse(csv, {
|
||||
headers: {
|
||||
"Content-Type": "text/csv; charset=UTF-8",
|
||||
"Content-Disposition": `attachment; filename="csat-${tenantId}-${report.rangeDays ?? '90'}d.csv"`,
|
||||
"Cache-Control": "no-store",
|
||||
},
|
||||
})
|
||||
} catch (error) {
|
||||
console.error("Failed to generate CSAT CSV", error)
|
||||
return NextResponse.json({ error: "Falha ao gerar CSV de CSAT" }, { status: 500 })
|
||||
}
|
||||
}
|
||||
|
||||
101
src/app/api/reports/sla.csv/route.ts
Normal file
101
src/app/api/reports/sla.csv/route.ts
Normal file
|
|
@ -0,0 +1,101 @@
|
|||
import { NextResponse } from "next/server"
|
||||
import { ConvexHttpClient } from "convex/browser"
|
||||
|
||||
import { api } from "@/convex/_generated/api"
|
||||
import type { Id } from "@/convex/_generated/dataModel"
|
||||
import { env } from "@/lib/env"
|
||||
import { assertAuthenticatedSession } from "@/lib/auth-server"
|
||||
import { DEFAULT_TENANT_ID } from "@/lib/constants"
|
||||
|
||||
export const runtime = "nodejs"
|
||||
|
||||
function csvEscape(value: unknown): string {
|
||||
const s = value == null ? "" : String(value)
|
||||
if (/[",\n]/.test(s)) {
|
||||
return '"' + s.replace(/"/g, '""') + '"'
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
function rowsToCsv(rows: Array<Array<unknown>>): string {
|
||||
return rows.map((row) => row.map(csvEscape).join(",")).join("\n") + "\n"
|
||||
}
|
||||
|
||||
export async function GET(request: Request) {
|
||||
const session = await assertAuthenticatedSession()
|
||||
if (!session) {
|
||||
return NextResponse.json({ error: "Não autorizado" }, { status: 401 })
|
||||
}
|
||||
|
||||
const convexUrl = env.NEXT_PUBLIC_CONVEX_URL
|
||||
if (!convexUrl) {
|
||||
return NextResponse.json({ error: "Convex não configurado" }, { status: 500 })
|
||||
}
|
||||
|
||||
const { searchParams } = new URL(request.url)
|
||||
const range = searchParams.get("range") ?? undefined
|
||||
|
||||
const client = new ConvexHttpClient(convexUrl)
|
||||
const tenantId = session.user.tenantId ?? DEFAULT_TENANT_ID
|
||||
|
||||
let viewerId: string | null = null
|
||||
try {
|
||||
const ensuredUser = await client.mutation(api.users.ensureUser, {
|
||||
tenantId,
|
||||
name: session.user.name ?? session.user.email,
|
||||
email: session.user.email,
|
||||
avatarUrl: session.user.avatarUrl ?? undefined,
|
||||
role: session.user.role.toUpperCase(),
|
||||
})
|
||||
viewerId = ensuredUser?._id ?? null
|
||||
} catch (error) {
|
||||
console.error("Failed to synchronize user with Convex for SLA CSV", error)
|
||||
return NextResponse.json({ error: "Falha ao sincronizar usuário com Convex" }, { status: 500 })
|
||||
}
|
||||
|
||||
if (!viewerId) {
|
||||
return NextResponse.json({ error: "Usuário não encontrado no Convex" }, { status: 403 })
|
||||
}
|
||||
|
||||
try {
|
||||
const report = await client.query(api.reports.slaOverview, {
|
||||
tenantId,
|
||||
viewerId: viewerId as unknown as Id<"users">,
|
||||
range,
|
||||
})
|
||||
|
||||
const rows: Array<Array<unknown>> = []
|
||||
rows.push(["Relatório", "SLA e produtividade"])
|
||||
rows.push(["Período", range ?? "—"])
|
||||
rows.push([])
|
||||
|
||||
rows.push(["Métrica", "Valor"]) // header
|
||||
rows.push(["Tickets totais", report.totals.total])
|
||||
rows.push(["Tickets abertos", report.totals.open])
|
||||
rows.push(["Tickets resolvidos", report.totals.resolved])
|
||||
rows.push(["Atrasados (SLA)", report.totals.overdue])
|
||||
rows.push([])
|
||||
rows.push(["Tempo médio de 1ª resposta (min)", report.response.averageFirstResponseMinutes ?? "—"])
|
||||
rows.push(["Respostas registradas", report.response.responsesRegistered ?? 0])
|
||||
rows.push(["Tempo médio de resolução (min)", report.resolution.averageResolutionMinutes ?? "—"])
|
||||
rows.push(["Tickets resolvidos (amostra)", report.resolution.resolvedCount ?? 0])
|
||||
rows.push([])
|
||||
rows.push(["Fila", "Abertos"])
|
||||
for (const q of report.queueBreakdown ?? []) {
|
||||
rows.push([q.name || q.id, q.open])
|
||||
}
|
||||
|
||||
const csv = rowsToCsv(rows)
|
||||
return new NextResponse(csv, {
|
||||
headers: {
|
||||
"Content-Type": "text/csv; charset=UTF-8",
|
||||
"Content-Disposition": `attachment; filename="sla-${tenantId}.csv"`,
|
||||
"Cache-Control": "no-store",
|
||||
},
|
||||
})
|
||||
} catch (error) {
|
||||
console.error("Failed to generate SLA CSV", error)
|
||||
return NextResponse.json({ error: "Falha ao gerar CSV de SLA" }, { status: 500 })
|
||||
}
|
||||
}
|
||||
|
||||
102
src/app/api/reports/tickets-by-channel.csv/route.ts
Normal file
102
src/app/api/reports/tickets-by-channel.csv/route.ts
Normal file
|
|
@ -0,0 +1,102 @@
|
|||
import { NextResponse } from "next/server"
|
||||
import { ConvexHttpClient } from "convex/browser"
|
||||
|
||||
import { api } from "@/convex/_generated/api"
|
||||
import type { Id } from "@/convex/_generated/dataModel"
|
||||
import { env } from "@/lib/env"
|
||||
import { assertAuthenticatedSession } from "@/lib/auth-server"
|
||||
import { DEFAULT_TENANT_ID } from "@/lib/constants"
|
||||
|
||||
export const runtime = "nodejs"
|
||||
|
||||
function csvEscape(value: unknown): string {
|
||||
const s = value == null ? "" : String(value)
|
||||
if (/[",\n]/.test(s)) {
|
||||
return '"' + s.replace(/"/g, '""') + '"'
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
function rowsToCsv(rows: Array<Array<unknown>>): string {
|
||||
return rows.map((row) => row.map(csvEscape).join(",")).join("\n") + "\n"
|
||||
}
|
||||
|
||||
export async function GET(request: Request) {
|
||||
const session = await assertAuthenticatedSession()
|
||||
if (!session) {
|
||||
return NextResponse.json({ error: "Não autorizado" }, { status: 401 })
|
||||
}
|
||||
|
||||
const convexUrl = env.NEXT_PUBLIC_CONVEX_URL
|
||||
if (!convexUrl) {
|
||||
return NextResponse.json({ error: "Convex não configurado" }, { status: 500 })
|
||||
}
|
||||
|
||||
const { searchParams } = new URL(request.url)
|
||||
const range = searchParams.get("range") ?? undefined // "7d" | "30d" | undefined(=90d)
|
||||
|
||||
const client = new ConvexHttpClient(convexUrl)
|
||||
const tenantId = session.user.tenantId ?? DEFAULT_TENANT_ID
|
||||
|
||||
let viewerId: string | null = null
|
||||
try {
|
||||
const ensuredUser = await client.mutation(api.users.ensureUser, {
|
||||
tenantId,
|
||||
name: session.user.name ?? session.user.email,
|
||||
email: session.user.email,
|
||||
avatarUrl: session.user.avatarUrl ?? undefined,
|
||||
role: session.user.role.toUpperCase(),
|
||||
})
|
||||
viewerId = ensuredUser?._id ?? null
|
||||
} catch (error) {
|
||||
console.error("Failed to synchronize user with Convex for channel CSV", error)
|
||||
return NextResponse.json({ error: "Falha ao sincronizar usuário com Convex" }, { status: 500 })
|
||||
}
|
||||
|
||||
if (!viewerId) {
|
||||
return NextResponse.json({ error: "Usuário não encontrado no Convex" }, { status: 403 })
|
||||
}
|
||||
|
||||
try {
|
||||
const report = await client.query(api.reports.ticketsByChannel, {
|
||||
tenantId,
|
||||
viewerId: viewerId as unknown as Id<"users">,
|
||||
range,
|
||||
})
|
||||
|
||||
const channels = report.channels
|
||||
const CHANNEL_PT: Record<string, string> = {
|
||||
EMAIL: "E-mail",
|
||||
PHONE: "Telefone",
|
||||
CHAT: "Chat",
|
||||
WHATSAPP: "WhatsApp",
|
||||
API: "API",
|
||||
MANUAL: "Manual",
|
||||
WEB: "Portal",
|
||||
PORTAL: "Portal",
|
||||
}
|
||||
const header = ["Data", ...channels.map((ch) => CHANNEL_PT[ch] ?? ch)]
|
||||
const rows: Array<Array<unknown>> = []
|
||||
rows.push(["Relatório", "Tickets por canal"])
|
||||
rows.push(["Período", report.rangeDays ? `Últimos ${report.rangeDays} dias` : (range ?? '90d')])
|
||||
rows.push([])
|
||||
rows.push(header)
|
||||
|
||||
for (const point of report.points) {
|
||||
const values = channels.map((ch) => point.values[ch] ?? 0)
|
||||
rows.push([point.date, ...values])
|
||||
}
|
||||
|
||||
const csv = rowsToCsv(rows)
|
||||
return new NextResponse(csv, {
|
||||
headers: {
|
||||
"Content-Type": "text/csv; charset=UTF-8",
|
||||
"Content-Disposition": `attachment; filename="tickets-by-channel-${tenantId}-${range ?? '90d'}.csv"`,
|
||||
"Cache-Control": "no-store",
|
||||
},
|
||||
})
|
||||
} catch (error) {
|
||||
console.error("Failed to generate tickets-by-channel CSV", error)
|
||||
return NextResponse.json({ error: "Falha ao gerar CSV de tickets por canal" }, { status: 500 })
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue